sockfile.cpp 220 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640
  1. /*##############################################################################
  2. HPCC SYSTEMS software Copyright (C) 2012 HPCC Systems®.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. ############################################################################## */
  13. // todo look at IRemoteFileServer stop
  14. #include "platform.h"
  15. #include "limits.h"
  16. #include "jlib.hpp"
  17. #include "jio.hpp"
  18. #include "jmutex.hpp"
  19. #include "jfile.hpp"
  20. #include "jmisc.hpp"
  21. #include "jthread.hpp"
  22. #include "jqueue.tpp"
  23. #include "securesocket.hpp"
  24. #include "sockfile.hpp"
  25. #include "portlist.h"
  26. #include "jsocket.hpp"
  27. #include "jencrypt.hpp"
  28. #include "jset.hpp"
  29. #include "jhtree.hpp"
  30. #include "remoteerr.hpp"
  31. #include <atomic>
  32. #include "rtldynfield.hpp"
  33. #include "rtlds_imp.hpp"
  34. #include "rtlread_imp.hpp"
  35. #include "rtlrecord.hpp"
  36. #include "eclhelper_dyn.hpp"
  37. #include "rtlcommon.hpp"
  38. #include "rtlformat.hpp"
  39. #define SOCKET_CACHE_MAX 500
  40. #define MIN_KEYFILTSUPPORT_VERSION 20
  41. #ifdef _DEBUG
  42. //#define SIMULATE_PACKETLOSS 1
  43. #endif
  44. #define TREECOPYTIMEOUT (60*60*1000) // 1Hr (I guess could take longer for big file but at least will stagger)
  45. #define TREECOPYPOLLTIME (60*1000*5) // for tracing that delayed
  46. #define TREECOPYPRUNETIME (24*60*60*1000) // 1 day
  47. static const unsigned __int64 defaultFileStreamChooseN = I64C(0x7fffffffffffffff); // constant should be move to common place (see eclhelper.hpp)
  48. static const unsigned __int64 defaultFileStreamSkipN = 0;
  49. static const unsigned __int64 defaultFileStreamRowLimit = (unsigned __int64) -1;
  50. static const unsigned __int64 defaultDaFSNumRecs = 100;
  51. enum OutputFormat { outFmt_Binary, outFmt_Xml, outFmt_Json };
  52. #if SIMULATE_PACKETLOSS
  53. #define TESTING_FAILURE_RATE_LOST_SEND 10 // per 1000
  54. #define TESTING_FAILURE_RATE_LOST_RECV 10 // per 1000
  55. #define DUMMY_TIMEOUT_MAX (1000*10)
  56. static bool errorSimulationOn = true;
  57. static ISocket *timeoutreadsock = NULL; // used to trigger
  58. struct dummyReadWrite
  59. {
  60. class X
  61. {
  62. dummyReadWrite *parent;
  63. public:
  64. X(dummyReadWrite *_parent)
  65. {
  66. parent = _parent;
  67. }
  68. ~X()
  69. {
  70. delete parent;
  71. }
  72. };
  73. class TimeoutSocketException: public CInterface, public IJSOCK_Exception
  74. {
  75. public:
  76. IMPLEMENT_IINTERFACE;
  77. TimeoutSocketException()
  78. {
  79. }
  80. virtual ~TimeoutSocketException()
  81. {
  82. }
  83. int errorCode() const { return JSOCKERR_timeout_expired; }
  84. StringBuffer & errorMessage(StringBuffer &str) const
  85. {
  86. return str.append("timeout expired");
  87. }
  88. MessageAudience errorAudience() const
  89. {
  90. return MSGAUD_user;
  91. }
  92. };
  93. ISocket *sock;
  94. dummyReadWrite(ISocket *_sock)
  95. {
  96. sock = _sock;
  97. }
  98. void readtms(void* buf, size32_t min_size, size32_t max_size, size32_t &size_read, time_t timeout)
  99. {
  100. X x(this);
  101. unsigned t = msTick();
  102. unsigned r = getRandom();
  103. bool timeoutread = (timeoutreadsock==sock);
  104. timeoutreadsock=NULL;
  105. if (!timeoutread)
  106. sock->readtms(buf, min_size, max_size, size_read, timeout);
  107. if (timeoutread||(errorSimulationOn&&(TESTING_FAILURE_RATE_LOST_RECV>0)&&(r%1000<TESTING_FAILURE_RATE_LOST_RECV))) {
  108. PrintStackReport();
  109. if (timeoutread)
  110. PROGLOG("** Simulate timeout");
  111. else
  112. PROGLOG("** Simulate Packet loss (size %d,%d)",min_size,max_size);
  113. if (timeout>DUMMY_TIMEOUT_MAX)
  114. timeout = DUMMY_TIMEOUT_MAX;
  115. t = msTick()-t;
  116. if (t<timeout)
  117. Sleep(timeout-t);
  118. IJSOCK_Exception *e = new TimeoutSocketException;
  119. throw e;
  120. }
  121. }
  122. size32_t write(void const* buf, size32_t size)
  123. {
  124. X x(this);
  125. timeoutreadsock=NULL;
  126. unsigned r = getRandom();
  127. if (errorSimulationOn&&(TESTING_FAILURE_RATE_LOST_SEND>0)&&(r%1000<TESTING_FAILURE_RATE_LOST_SEND)) {
  128. PrintStackReport();
  129. PROGLOG("** Simulate Packet loss (size %d)",size);
  130. timeoutreadsock=sock;
  131. return size;
  132. }
  133. return sock->write(buf,size);
  134. }
  135. };
  136. #define SOCKWRITE(sock) (new dummyReadWrite(sock))->write
  137. #define SOCKREADTMS(sock) (new dummyReadWrite(sock))->readtms
  138. #else
  139. #define SOCKWRITE(sock) sock->write
  140. #define SOCKREADTMS(sock) sock->readtms
  141. #endif
  142. // backward compatible modes
  143. typedef enum { compatIFSHnone, compatIFSHread, compatIFSHwrite, compatIFSHexec, compatIFSHall} compatIFSHmode;
  144. static const char *VERSTRING= "DS V2.1" // dont forget FILESRV_VERSION in header
  145. #ifdef _WIN32
  146. "Windows ";
  147. #else
  148. "Linux ";
  149. #endif
  150. typedef unsigned char RemoteFileCommandType;
  151. typedef int RemoteFileIOHandle;
  152. static unsigned maxConnectTime = 0;
  153. static unsigned maxReceiveTime = 0;
  154. //Security and default port attributes
  155. static class _securitySettings
  156. {
  157. public:
  158. DAFSConnectCfg connectMethod;
  159. unsigned short daFileSrvPort;
  160. unsigned short daFileSrvSSLPort;
  161. const char * certificate;
  162. const char * privateKey;
  163. const char * passPhrase;
  164. _securitySettings()
  165. {
  166. queryDafsSecSettings(&connectMethod, &daFileSrvPort, &daFileSrvSSLPort, &certificate, &privateKey, &passPhrase);
  167. }
  168. } securitySettings;
  169. static CriticalSection secureContextCrit;
  170. static Owned<ISecureSocketContext> secureContextServer;
  171. static Owned<ISecureSocketContext> secureContextClient;
  172. #ifdef _USE_OPENSSL
  173. static ISecureSocket *createSecureSocket(ISocket *sock, SecureSocketType type)
  174. {
  175. {
  176. CriticalBlock b(secureContextCrit);
  177. if (type == ServerSocket)
  178. {
  179. if (!secureContextServer)
  180. secureContextServer.setown(createSecureSocketContextEx(securitySettings.certificate, securitySettings.privateKey, securitySettings.passPhrase, type));
  181. }
  182. else if (!secureContextClient)
  183. secureContextClient.setown(createSecureSocketContext(type));
  184. }
  185. int loglevel = SSLogNormal;
  186. #ifdef _DEBUG
  187. loglevel = SSLogMax;
  188. #endif
  189. if (type == ServerSocket)
  190. return secureContextServer->createSecureSocket(sock, loglevel);
  191. else
  192. return secureContextClient->createSecureSocket(sock, loglevel);
  193. }
  194. #endif
  195. void clientSetRemoteFileTimeouts(unsigned maxconnecttime,unsigned maxreadtime)
  196. {
  197. maxConnectTime = maxconnecttime;
  198. maxReceiveTime = maxreadtime;
  199. }
  200. struct sRFTM
  201. {
  202. CTimeMon *timemon;
  203. sRFTM(unsigned limit) { timemon = limit ? new CTimeMon(limit) : NULL; }
  204. ~sRFTM() { delete timemon; }
  205. };
  206. const char *remoteServerVersionString() { return VERSTRING; }
  207. static bool AuthenticationEnabled = true;
  208. bool enableDafsAuthentication(bool on)
  209. {
  210. bool ret = AuthenticationEnabled;
  211. AuthenticationEnabled = on;
  212. return ret;
  213. }
  214. #define CLIENT_TIMEOUT (1000*60*60*12) // long timeout in case zombies
  215. #define CLIENT_INACTIVEWARNING_TIMEOUT (1000*60*60*12) // time between logging inactive clients
  216. #define SERVER_TIMEOUT (1000*60*5) // timeout when waiting for dafilesrv to reply after command
  217. // (increased when waiting for large block)
  218. #define DAFS_CONNECT_FAIL_RETRY_TIME (1000*60*15)
  219. #ifdef SIMULATE_PACKETLOSS
  220. #define NORMAL_RETRIES (1)
  221. #define LENGTHY_RETRIES (1)
  222. #else
  223. #define NORMAL_RETRIES (3)
  224. #define LENGTHY_RETRIES (12)
  225. #endif
  226. #ifdef _DEBUG
  227. static byte traceFlags=0x30;
  228. #else
  229. static byte traceFlags=0x20;
  230. #endif
  231. #define TF_TRACE (traceFlags&1)
  232. #define TF_TRACE_PRE_IO (traceFlags&2)
  233. #define TF_TRACE_FULL (traceFlags&4)
  234. #define TF_TRACE_CLIENT_CONN (traceFlags&8)
  235. #define TF_TRACE_TREE_COPY (traceFlags&0x10)
  236. #define TF_TRACE_CLIENT_STATS (traceFlags&0x20)
  237. enum {
  238. RFCopenIO, // 0
  239. RFCcloseIO,
  240. RFCread,
  241. RFCwrite,
  242. RFCsize,
  243. RFCexists,
  244. RFCremove,
  245. RFCrename,
  246. RFCgetver,
  247. RFCisfile,
  248. RFCisdirectory, // 10
  249. RFCisreadonly,
  250. RFCsetreadonly,
  251. RFCgettime,
  252. RFCsettime,
  253. RFCcreatedir,
  254. RFCgetdir,
  255. RFCstop,
  256. RFCexec, // legacy cmd removed
  257. RFCdummy1, // legacy placeholder
  258. RFCredeploy, // 20
  259. RFCgetcrc,
  260. RFCmove,
  261. // 1.5 features below
  262. RFCsetsize,
  263. RFCextractblobelements,
  264. RFCcopy,
  265. RFCappend,
  266. RFCmonitordir,
  267. RFCsettrace,
  268. RFCgetinfo,
  269. RFCfirewall, // not used currently // 30
  270. RFCunlock,
  271. RFCunlockreply,
  272. RFCinvalid,
  273. RFCcopysection,
  274. // 1.7e
  275. RFCtreecopy,
  276. // 1.7e - 1
  277. RFCtreecopytmp,
  278. // 1.8
  279. RFCsetthrottle, // legacy version
  280. // 1.9
  281. RFCsetthrottle2,
  282. RFCsetfileperms,
  283. // 2.0
  284. RFCreadfilteredindex, // No longer used
  285. RFCreadfilteredindexcount,
  286. RFCreadfilteredindexblob,
  287. RFCmaxnormal,
  288. RFCStreamRead = '{',
  289. RFCmax,
  290. RFCunknown = 255 // 0 would have been more sensible, but can't break backward compatibility
  291. };
  292. #define RFCText(cmd) #cmd
  293. const char *RFCStrings[] =
  294. {
  295. RFCText(RFCopenIO),
  296. RFCText(RFCcloseIO),
  297. RFCText(RFCread),
  298. RFCText(RFCwrite),
  299. RFCText(RFCsize),
  300. RFCText(RFCexists),
  301. RFCText(RFCremove),
  302. RFCText(RFCrename),
  303. RFCText(RFCgetver),
  304. RFCText(RFCisfile),
  305. RFCText(RFCisdirectory),
  306. RFCText(RFCisreadonly),
  307. RFCText(RFCsetreadonly),
  308. RFCText(RFCgettime),
  309. RFCText(RFCsettime),
  310. RFCText(RFCcreatedir),
  311. RFCText(RFCgetdir),
  312. RFCText(RFCstop),
  313. RFCText(RFCexec),
  314. RFCText(RFCdummy1),
  315. RFCText(RFCredeploy),
  316. RFCText(RFCgetcrc),
  317. RFCText(RFCmove),
  318. RFCText(RFCsetsize),
  319. RFCText(RFCextractblobelements),
  320. RFCText(RFCcopy),
  321. RFCText(RFCappend),
  322. RFCText(RFCmonitordir),
  323. RFCText(RFCsettrace),
  324. RFCText(RFCgetinfo),
  325. RFCText(RFCfirewall),
  326. RFCText(RFCunlock),
  327. RFCText(RFCunlockreply),
  328. RFCText(RFCinvalid),
  329. RFCText(RFCcopysection),
  330. RFCText(RFCtreecopy),
  331. RFCText(RFCtreecopytmp),
  332. RFCText(RFCsetthrottle), // legacy version
  333. RFCText(RFCsetthrottle2),
  334. RFCText(RFCsetfileperms),
  335. RFCText(RFCreadfilteredindex),
  336. RFCText(RFCreadfilteredcount),
  337. RFCText(RFCreadfilteredblob),
  338. RFCText(RFCunknown),
  339. };
  340. static const char *getRFCText(RemoteFileCommandType cmd)
  341. {
  342. if (cmd==RFCStreamRead)
  343. return "RFCStreamRead";
  344. else
  345. {
  346. if (cmd > RFCmaxnormal)
  347. cmd = RFCmaxnormal;
  348. return RFCStrings[cmd];
  349. }
  350. }
  351. static const char *getRFSERRText(unsigned err)
  352. {
  353. switch (err)
  354. {
  355. case RFSERR_InvalidCommand:
  356. return "RFSERR_InvalidCommand";
  357. case RFSERR_NullFileIOHandle:
  358. return "RFSERR_NullFileIOHandle";
  359. case RFSERR_InvalidFileIOHandle:
  360. return "RFSERR_InvalidFileIOHandle";
  361. case RFSERR_TimeoutFileIOHandle:
  362. return "RFSERR_TimeoutFileIOHandle";
  363. case RFSERR_OpenFailed:
  364. return "RFSERR_OpenFailed";
  365. case RFSERR_ReadFailed:
  366. return "RFSERR_ReadFailed";
  367. case RFSERR_WriteFailed:
  368. return "RFSERR_WriteFailed";
  369. case RFSERR_RenameFailed:
  370. return "RFSERR_RenameFailed";
  371. case RFSERR_ExistsFailed:
  372. return "RFSERR_ExistsFailed";
  373. case RFSERR_RemoveFailed:
  374. return "RFSERR_RemoveFailed";
  375. case RFSERR_CloseFailed:
  376. return "RFSERR_CloseFailed";
  377. case RFSERR_IsFileFailed:
  378. return "RFSERR_IsFileFailed";
  379. case RFSERR_IsDirectoryFailed:
  380. return "RFSERR_IsDirectoryFailed";
  381. case RFSERR_IsReadOnlyFailed:
  382. return "RFSERR_IsReadOnlyFailed";
  383. case RFSERR_SetReadOnlyFailed:
  384. return "RFSERR_SetReadOnlyFailed";
  385. case RFSERR_GetTimeFailed:
  386. return "RFSERR_GetTimeFailed";
  387. case RFSERR_SetTimeFailed:
  388. return "RFSERR_SetTimeFailed";
  389. case RFSERR_CreateDirFailed:
  390. return "RFSERR_CreateDirFailed";
  391. case RFSERR_GetDirFailed:
  392. return "RFSERR_GetDirFailed";
  393. case RFSERR_GetCrcFailed:
  394. return "RFSERR_GetCrcFailed";
  395. case RFSERR_MoveFailed:
  396. return "RFSERR_MoveFailed";
  397. case RFSERR_ExtractBlobElementsFailed:
  398. return "RFSERR_ExtractBlobElementsFailed";
  399. case RFSERR_CopyFailed:
  400. return "RFSERR_CopyFailed";
  401. case RFSERR_AppendFailed:
  402. return "RFSERR_AppendFailed";
  403. case RFSERR_AuthenticateFailed:
  404. return "RFSERR_AuthenticateFailed";
  405. case RFSERR_CopySectionFailed:
  406. return "RFSERR_CopySectionFailed";
  407. case RFSERR_TreeCopyFailed:
  408. return "RFSERR_TreeCopyFailed";
  409. case RAERR_InvalidUsernamePassword:
  410. return "RAERR_InvalidUsernamePassword";
  411. case RFSERR_MasterSeemsToHaveDied:
  412. return "RFSERR_MasterSeemsToHaveDied";
  413. case RFSERR_TimeoutWaitSlave:
  414. return "RFSERR_TimeoutWaitSlave";
  415. case RFSERR_TimeoutWaitConnect:
  416. return "RFSERR_TimeoutWaitConnect";
  417. case RFSERR_TimeoutWaitMaster:
  418. return "RFSERR_TimeoutWaitMaster";
  419. case RFSERR_NoConnectSlave:
  420. return "RFSERR_NoConnectSlave";
  421. case RFSERR_NoConnectSlaveXY:
  422. return "RFSERR_NoConnectSlaveXY";
  423. case RFSERR_VersionMismatch:
  424. return "RFSERR_VersionMismatch";
  425. case RFSERR_SetThrottleFailed:
  426. return "RFSERR_SetThrottleFailed";
  427. case RFSERR_MaxQueueRequests:
  428. return "RFSERR_MaxQueueRequests";
  429. case RFSERR_KeyIndexFailed:
  430. return "RFSERR_MaxQueueRequests";
  431. }
  432. return "RFSERR_Unknown";
  433. }
  434. #define ThrottleText(throttleClass) #throttleClass
  435. const char *ThrottleStrings[] =
  436. {
  437. ThrottleText(ThrottleStd),
  438. ThrottleText(ThrottleSlow),
  439. };
  440. // very high upper limits that configure can't exceed
  441. #define THROTTLE_MAX_LIMIT 1000000
  442. #define THROTTLE_MAX_DELAYMS 3600000
  443. #define THROTTLE_MAX_CPUTHRESHOLD 100
  444. #define THROTTLE_MAX_QUEUELIMIT 10000000
  445. static const char *getThrottleClassText(ThrottleClass throttleClass) { return ThrottleStrings[throttleClass]; }
  446. typedef enum { ACScontinue, ACSdone, ACSerror} AsyncCommandStatus;
  447. typedef byte OnceKey[16];
  448. static void genOnce(OnceKey &key)
  449. {
  450. static __int64 inc=0;
  451. *(unsigned *)&key[0] = getRandom();
  452. *(__int64 *)&key[4] = ++inc;
  453. *(unsigned *)&key[12] = getRandom();
  454. }
  455. static void mergeOnce(OnceKey &key,size32_t sz,const void *data)
  456. {
  457. assertex(sz<=sizeof(OnceKey));
  458. const byte *p = (const byte *)data;
  459. while (sz)
  460. key[--sz] ^= *(p++);
  461. }
  462. //---------------------------------------------------------------------------
  463. class DECL_EXCEPTION CDafsException: public IDAFS_Exception, public CInterface
  464. {
  465. int errcode;
  466. StringAttr msg;
  467. public:
  468. IMPLEMENT_IINTERFACE;
  469. CDafsException(int code,const char *_msg)
  470. : errcode(code), msg(_msg)
  471. {
  472. };
  473. int errorCode() const
  474. {
  475. return errcode;
  476. }
  477. StringBuffer & errorMessage(StringBuffer &str) const
  478. {
  479. return str.append(msg);
  480. }
  481. MessageAudience errorAudience() const
  482. {
  483. return MSGAUD_user;
  484. }
  485. };
  486. static IDAFS_Exception *createDafsException(int code,const char *msg)
  487. {
  488. return new CDafsException(code,msg);
  489. }
  490. void setDafsEndpointPort(SocketEndpoint &ep)
  491. {
  492. // odd kludge (don't do this at home)
  493. byte ipb[4];
  494. if (ep.getNetAddress(sizeof(ipb),&ipb)==sizeof(ipb)) {
  495. if ((ipb[0]==255)&&(ipb[1]==255)) {
  496. ep.port = (((unsigned)ipb[2])<<8)+ipb[3];
  497. ep.ipset(queryLocalIP());
  498. }
  499. }
  500. if (ep.port==0)
  501. {
  502. if ( (securitySettings.connectMethod == SSLNone) || (securitySettings.connectMethod == UnsecureFirst) )
  503. ep.port = securitySettings.daFileSrvPort;
  504. else
  505. ep.port = securitySettings.daFileSrvSSLPort;
  506. }
  507. }
  508. inline MemoryBuffer & initSendBuffer(MemoryBuffer & buff)
  509. {
  510. buff.setEndian(__BIG_ENDIAN); // transfer as big endian...
  511. buff.append((unsigned)0); // reserve space for length prefix
  512. return buff;
  513. }
  514. inline void sendBuffer(ISocket * socket, MemoryBuffer & src, bool testSocketFlag=false)
  515. {
  516. unsigned length = src.length() - sizeof(unsigned);
  517. byte * buffer = (byte *)src.toByteArray();
  518. if (TF_TRACE_FULL)
  519. PROGLOG("sendBuffer size %d, data = %d %d %d %d",length, (int)buffer[4],(int)buffer[5],(int)buffer[6],(int)buffer[7]);
  520. if (testSocketFlag)
  521. length |= 0x80000000;
  522. _WINCPYREV(buffer, &length, sizeof(unsigned));
  523. SOCKWRITE(socket)(buffer, src.length());
  524. }
  525. inline size32_t receiveBufferSize(ISocket * socket, unsigned numtries=NORMAL_RETRIES,CTimeMon *timemon=NULL)
  526. {
  527. unsigned timeout = SERVER_TIMEOUT;
  528. if (numtries==0) {
  529. numtries = 1;
  530. timeout = 10*1000; // 10s
  531. }
  532. while (numtries--) {
  533. try {
  534. if (timemon) {
  535. unsigned remaining;
  536. if (timemon->timedout(&remaining)||(remaining<10))
  537. remaining = 10;
  538. if (remaining<timeout)
  539. timeout = remaining;
  540. }
  541. size32_t szread;
  542. size32_t gotLength;
  543. SOCKREADTMS(socket)(&gotLength, sizeof(gotLength), sizeof(gotLength), szread, timeout);
  544. _WINREV(gotLength);
  545. if (TF_TRACE_FULL)
  546. PROGLOG("receiveBufferSized %d",gotLength);
  547. return gotLength;
  548. }
  549. catch (IJSOCK_Exception *e) {
  550. if ((numtries==0)||(e->errorCode()!=JSOCKERR_timeout_expired)||(timemon&&timemon->timedout())) {
  551. throw;
  552. }
  553. StringBuffer err;
  554. char peername[256];
  555. socket->peer_name(peername,sizeof(peername)-1);
  556. WARNLOG("Remote connection %s: %s",peername,e->errorMessage(err).str()); // why no peername
  557. e->Release();
  558. Sleep(500+getRandom()%1000); // ~1s
  559. }
  560. }
  561. return 0;
  562. }
  563. static void flush(ISocket *socket)
  564. {
  565. MemoryBuffer sendbuf;
  566. initSendBuffer(sendbuf);
  567. sendbuf.append((RemoteFileCommandType)RFCgetver);
  568. sendbuf.append((unsigned)RFCgetver);
  569. MemoryBuffer reply;
  570. size32_t totread=0;
  571. try {
  572. sendBuffer(socket, sendbuf);
  573. char buf[1024];
  574. for (;;) {
  575. Sleep(1000); // breathe
  576. size32_t szread;
  577. SOCKREADTMS(socket)(buf, 1, sizeof(buf), szread, 1000*60);
  578. totread += szread;
  579. }
  580. }
  581. catch (IJSOCK_Exception *e) {
  582. if (totread)
  583. PROGLOG("%d bytes discarded",totread);
  584. if (e->errorCode()!=JSOCKERR_timeout_expired)
  585. EXCLOG(e,"flush");
  586. e->Release();
  587. }
  588. }
  589. inline void receiveBuffer(ISocket * socket, MemoryBuffer & tgt, unsigned numtries=1, size32_t maxsz=0x7fffffff)
  590. // maxsz is a guess at a resonable upper max to catch where protocol error
  591. {
  592. sRFTM tm(maxReceiveTime);
  593. size32_t gotLength = receiveBufferSize(socket, numtries,tm.timemon);
  594. if (gotLength) {
  595. size32_t origlen = tgt.length();
  596. try {
  597. if (gotLength>maxsz) {
  598. StringBuffer msg;
  599. msg.appendf("receiveBuffer maximum block size exceeded %d/%d",gotLength,maxsz);
  600. PrintStackReport();
  601. throw createDafsException(DAFSERR_protocol_failure,msg.str());
  602. }
  603. unsigned timeout = SERVER_TIMEOUT*(numtries?numtries:1);
  604. if (tm.timemon) {
  605. unsigned remaining;
  606. if (tm.timemon->timedout(&remaining)||(remaining<10))
  607. remaining = 10;
  608. if (remaining<timeout)
  609. timeout = remaining;
  610. }
  611. size32_t szread;
  612. SOCKREADTMS(socket)((gotLength<4000)?tgt.reserve(gotLength):tgt.reserveTruncate(gotLength), gotLength, gotLength, szread, timeout);
  613. }
  614. catch (IJSOCK_Exception *e) {
  615. if (e->errorCode()!=JSOCKERR_timeout_expired) {
  616. EXCLOG(e,"receiveBuffer(1)");
  617. PrintStackReport();
  618. if (!tm.timemon||!tm.timemon->timedout())
  619. flush(socket);
  620. }
  621. else {
  622. EXCLOG(e,"receiveBuffer");
  623. PrintStackReport();
  624. }
  625. tgt.setLength(origlen);
  626. throw;
  627. }
  628. catch (IException *e) {
  629. EXCLOG(e,"receiveBuffer(2)");
  630. PrintStackReport();
  631. if (!tm.timemon||!tm.timemon->timedout())
  632. flush(socket);
  633. tgt.setLength(origlen);
  634. throw;
  635. }
  636. }
  637. tgt.setEndian(__BIG_ENDIAN);
  638. }
  639. struct CConnectionRec
  640. {
  641. SocketEndpoint ep;
  642. unsigned tick;
  643. IArrayOf<ISocket> socks; // relies on isShared
  644. };
  645. //---------------------------------------------------------------------------
  646. // Local mount redirect
  647. struct CLocalMountRec: public CInterface
  648. {
  649. IpAddress ip;
  650. StringAttr dir; // dir path on remote ip
  651. StringAttr local; // local dir path
  652. };
  653. static CIArrayOf<CLocalMountRec> localMounts;
  654. static CriticalSection localMountCrit;
  655. void setDafsLocalMountRedirect(const IpAddress &ip,const char *dir,const char *mountdir)
  656. {
  657. CriticalBlock block(localMountCrit);
  658. ForEachItemInRev(i,localMounts) {
  659. CLocalMountRec &mount = localMounts.item(i);
  660. if (dir==NULL) { // remove all matching mount
  661. if (!mountdir)
  662. return;
  663. if (strcmp(mount.local,mountdir)==0)
  664. localMounts.remove(i);
  665. }
  666. else if (mount.ip.ipequals(ip)&&(strcmp(mount.dir,dir)==0)) {
  667. if (mountdir) {
  668. mount.local.set(mountdir);
  669. return;
  670. }
  671. else
  672. localMounts.remove(i);
  673. }
  674. }
  675. if (dir&&mountdir) {
  676. CLocalMountRec &mount = *new CLocalMountRec;
  677. mount.ip.ipset(ip);
  678. mount.dir.set(dir);
  679. mount.local.set(mountdir);
  680. localMounts.append(mount);
  681. }
  682. }
  683. IFile *createFileLocalMount(const IpAddress &ip, const char * filename)
  684. {
  685. CriticalBlock block(localMountCrit);
  686. ForEachItemInRev(i,localMounts) {
  687. CLocalMountRec &mount = localMounts.item(i);
  688. if (mount.ip.ipequals(ip)) {
  689. size32_t bl = mount.dir.length();
  690. if (isPathSepChar(mount.dir[bl-1]))
  691. bl--;
  692. if ((memcmp((void *)filename,(void *)mount.dir.get(),bl)==0)&&(isPathSepChar(filename[bl])||!filename[bl])) { // match
  693. StringBuffer locpath(mount.local);
  694. if (filename[bl])
  695. addPathSepChar(locpath).append(filename+bl+1);
  696. locpath.replace((PATHSEPCHAR=='\\')?'/':'\\',PATHSEPCHAR);
  697. return createIFile(locpath.str());
  698. }
  699. }
  700. }
  701. return NULL;
  702. }
  703. //---------------------------------------------------------------------------
  704. static class CConnectionTable: public SuperHashTableOf<CConnectionRec,SocketEndpoint>
  705. {
  706. void onAdd(void *) {}
  707. void onRemove(void *e)
  708. {
  709. CConnectionRec *r=(CConnectionRec *)e;
  710. delete r;
  711. }
  712. unsigned getHashFromElement(const void *e) const
  713. {
  714. const CConnectionRec &elem=*(const CConnectionRec *)e;
  715. return elem.ep.hash(0);
  716. }
  717. unsigned getHashFromFindParam(const void *fp) const
  718. {
  719. return ((const SocketEndpoint *)fp)->hash(0);
  720. }
  721. const void * getFindParam(const void *p) const
  722. {
  723. const CConnectionRec &elem=*(const CConnectionRec *)p;
  724. return (void *)&elem.ep;
  725. }
  726. bool matchesFindParam(const void * et, const void *fp, unsigned) const
  727. {
  728. return ((CConnectionRec *)et)->ep.equals(*(SocketEndpoint *)fp);
  729. }
  730. IMPLEMENT_SUPERHASHTABLEOF_REF_FIND(CConnectionRec,SocketEndpoint);
  731. unsigned numsockets;
  732. public:
  733. static CriticalSection crit;
  734. CConnectionTable()
  735. {
  736. numsockets = 0;
  737. }
  738. ~CConnectionTable() {
  739. _releaseAll();
  740. }
  741. ISocket *lookup(const SocketEndpoint &ep)
  742. {
  743. // always called from crit block
  744. CConnectionRec *r = SuperHashTableOf<CConnectionRec,SocketEndpoint>::find(&ep);
  745. if (r) {
  746. ForEachItemIn(i,r->socks) {
  747. ISocket *s = &r->socks.item(i);
  748. if (!QUERYINTERFACE(s, CInterface)->IsShared()) {
  749. r->tick = msTick();
  750. s->Link();
  751. return s;
  752. }
  753. }
  754. }
  755. return NULL;
  756. }
  757. void addLink(SocketEndpoint &ep,ISocket *sock)
  758. {
  759. // always called from crit block
  760. while (numsockets>=SOCKET_CACHE_MAX) {
  761. // find oldest
  762. CConnectionRec *c = NULL;
  763. unsigned oldest = 0;
  764. CConnectionRec *old = NULL;
  765. unsigned oldi;
  766. unsigned now = msTick();
  767. for (;;) {
  768. c = (CConnectionRec *)SuperHashTableOf<CConnectionRec,SocketEndpoint>::next(c);
  769. if (!c)
  770. break;
  771. ForEachItemIn(i,c->socks) {
  772. ISocket *s = &c->socks.item(i);
  773. if (!QUERYINTERFACE(s, CInterface)->IsShared()) { // candidate to remove
  774. unsigned t = now-c->tick;
  775. if (t>oldest) {
  776. oldest = t;
  777. old = c;
  778. oldi = i;
  779. }
  780. }
  781. }
  782. }
  783. if (!old)
  784. return;
  785. old->socks.remove(oldi);
  786. numsockets--;
  787. }
  788. CConnectionRec *r = SuperHashTableOf<CConnectionRec,SocketEndpoint>::find(&ep);
  789. if (!r) {
  790. r = new CConnectionRec;
  791. r->ep = ep;
  792. SuperHashTableOf<CConnectionRec,SocketEndpoint>::add(*r);
  793. }
  794. sock->Link();
  795. r->socks.append(*sock);
  796. numsockets++;
  797. r->tick = msTick();
  798. }
  799. void remove(SocketEndpoint &ep,ISocket *sock)
  800. {
  801. // always called from crit block
  802. CConnectionRec *r = SuperHashTableOf<CConnectionRec,SocketEndpoint>::find(&ep);
  803. if (r)
  804. if (r->socks.zap(*sock)&&numsockets)
  805. numsockets--;
  806. }
  807. } *ConnectionTable = NULL;
  808. CriticalSection CConnectionTable::crit;
  809. void clientSetDaliServixSocketCaching(bool on)
  810. {
  811. CriticalBlock block(CConnectionTable::crit);
  812. if (on) {
  813. if (!ConnectionTable)
  814. ConnectionTable = new CConnectionTable;
  815. }
  816. else {
  817. delete ConnectionTable;
  818. ConnectionTable = NULL;
  819. }
  820. }
  821. //---------------------------------------------------------------------------
  822. // TreeCopy
  823. #define TREECOPY_CACHE_SIZE 50
  824. struct CTreeCopyItem: public CInterface
  825. {
  826. StringAttr net;
  827. StringAttr mask;
  828. offset_t sz; // original size
  829. CDateTime dt; // original date
  830. RemoteFilenameArray loc; // locations for file - 0 is original
  831. Owned<IBitSet> busy;
  832. unsigned lastused;
  833. CTreeCopyItem(RemoteFilename &orig, const char *_net, const char *_mask, offset_t _sz, CDateTime &_dt)
  834. : net(_net), mask(_mask)
  835. {
  836. loc.append(orig);
  837. dt.set(_dt);
  838. sz = _sz;
  839. busy.setown(createThreadSafeBitSet());
  840. lastused = msTick();
  841. }
  842. bool equals(const RemoteFilename &orig, const char *_net, const char *_mask, offset_t _sz, CDateTime &_dt)
  843. {
  844. if (!orig.equals(loc.item(0)))
  845. return false;
  846. if (strcmp(_net,net)!=0)
  847. return false;
  848. if (strcmp(_mask,mask)!=0)
  849. return false;
  850. if (sz!=_sz)
  851. return false;
  852. return (dt.equals(_dt,false));
  853. }
  854. };
  855. static CIArrayOf<CTreeCopyItem> treeCopyArray;
  856. static CriticalSection treeCopyCrit;
  857. static unsigned treeCopyWaiting=0;
  858. static Semaphore treeCopySem;
  859. #define DEBUGSAMEIP false
  860. static void cleanupSocket(ISocket *sock)
  861. {
  862. if (!sock)
  863. return;
  864. try
  865. {
  866. sock->shutdown();
  867. }
  868. catch (IException *e)
  869. {
  870. e->Release();
  871. }
  872. try
  873. {
  874. sock->close();
  875. }
  876. catch (IException *e)
  877. {
  878. e->Release();
  879. }
  880. }
  881. //---------------------------------------------------------------------------
  882. class CRemoteBase: public CInterface
  883. {
  884. Owned<ISocket> socket;
  885. static SocketEndpoint lastfailep;
  886. static unsigned lastfailtime;
  887. DAFSConnectCfg connectMethod;
  888. void connectSocket(SocketEndpoint &ep, unsigned localConnectTime=0, unsigned localRetries=0)
  889. {
  890. unsigned retries = 3;
  891. if (localConnectTime)
  892. {
  893. if (localRetries)
  894. retries = localRetries;
  895. if (localConnectTime > maxConnectTime)
  896. localConnectTime = maxConnectTime;
  897. }
  898. else
  899. localConnectTime = maxConnectTime;
  900. sRFTM tm(localConnectTime);
  901. // called in CConnectionTable::crit
  902. if (ep.equals(lastfailep)) {
  903. if (msTick()-lastfailtime<DAFS_CONNECT_FAIL_RETRY_TIME) {
  904. StringBuffer msg("Failed to connect (host marked down) to dafilesrv/daliservix on ");
  905. ep.getUrlStr(msg);
  906. throw createDafsException(DAFSERR_connection_failed,msg.str());
  907. }
  908. lastfailep.set(NULL);
  909. retries = 1; // on probation
  910. }
  911. while(retries--) {
  912. CriticalUnblock unblock(CConnectionTable::crit); // allow others to connect
  913. StringBuffer eps;
  914. if (TF_TRACE_CLIENT_CONN) {
  915. ep.getUrlStr(eps);
  916. if (ep.port == securitySettings.daFileSrvSSLPort)
  917. PROGLOG("Connecting SECURE to %s", eps.str());
  918. else
  919. PROGLOG("Connecting to %s", eps.str());
  920. //PrintStackReport();
  921. }
  922. bool ok = true;
  923. try {
  924. if (tm.timemon) {
  925. unsigned remaining;
  926. if (tm.timemon->timedout(&remaining))
  927. throwJSocketException(JSOCKERR_connection_failed);
  928. socket.setown(ISocket::connect_timeout(ep,remaining));
  929. }
  930. else
  931. socket.setown(ISocket::connect(ep));
  932. if (ep.port == securitySettings.daFileSrvSSLPort)
  933. {
  934. #ifdef _USE_OPENSSL
  935. Owned<ISecureSocket> ssock;
  936. try
  937. {
  938. ssock.setown(createSecureSocket(socket.getClear(), ClientSocket));
  939. int status = ssock->secure_connect();
  940. if (status < 0)
  941. throw createDafsException(DAFSERR_connection_failed, "Failure to establish secure connection");
  942. socket.setown(ssock.getLink());
  943. }
  944. catch (IException *e)
  945. {
  946. cleanupSocket(ssock);
  947. ssock.clear();
  948. cleanupSocket(socket);
  949. socket.clear();
  950. StringBuffer eMsg;
  951. e->errorMessage(eMsg);
  952. e->Release();
  953. throw createDafsException(DAFSERR_connection_failed, eMsg.str());
  954. }
  955. #else
  956. throw createDafsException(DAFSERR_connection_failed,"Failure to establish secure connection: OpenSSL disabled in build");
  957. #endif
  958. }
  959. }
  960. catch (IJSOCK_Exception *e) {
  961. ok = false;
  962. if (!retries||(tm.timemon&&tm.timemon->timedout())) {
  963. if (e->errorCode()==JSOCKERR_connection_failed) {
  964. lastfailep.set(ep);
  965. lastfailtime = msTick();
  966. e->Release();
  967. StringBuffer msg("Failed to connect (setting host down) to dafilesrv/daliservix on ");
  968. ep.getUrlStr(msg);
  969. throw createDafsException(DAFSERR_connection_failed,msg.str());
  970. }
  971. throw;
  972. }
  973. StringBuffer err;
  974. WARNLOG("Remote file connect %s",e->errorMessage(err).str());
  975. e->Release();
  976. }
  977. if (ok) {
  978. if (TF_TRACE_CLIENT_CONN) {
  979. PROGLOG("Connected to %s",eps.str());
  980. }
  981. if (AuthenticationEnabled) {
  982. try {
  983. sendAuthentication(ep); // this will log error
  984. break;
  985. }
  986. catch (IJSOCK_Exception *e) {
  987. StringBuffer err;
  988. WARNLOG("Remote file authenticate %s for %s ",e->errorMessage(err).str(),ep.getUrlStr(eps.clear()).str());
  989. e->Release();
  990. if (!retries)
  991. break; // MCK - is this a warning or an error ? If an error, should we close and throw here ?
  992. }
  993. }
  994. else
  995. break;
  996. }
  997. bool timeExpired = false;
  998. unsigned sleeptime = getRandom()%3000+1000;
  999. if (tm.timemon)
  1000. {
  1001. unsigned remaining;
  1002. if (tm.timemon->timedout(&remaining))
  1003. timeExpired = true;
  1004. else
  1005. {
  1006. if (remaining/2<sleeptime)
  1007. sleeptime = remaining/2;
  1008. }
  1009. }
  1010. if (!timeExpired)
  1011. {
  1012. Sleep(sleeptime); // prevent multiple retries beating
  1013. if (ep.port == securitySettings.daFileSrvSSLPort)
  1014. PROGLOG("Retrying SECURE connect");
  1015. else
  1016. PROGLOG("Retrying connect");
  1017. }
  1018. }
  1019. if (ConnectionTable)
  1020. ConnectionTable->addLink(ep,socket);
  1021. }
  1022. void killSocket(SocketEndpoint &tep)
  1023. {
  1024. CriticalBlock block2(CConnectionTable::crit); // this is nested with crit
  1025. if (socket) {
  1026. try {
  1027. Owned<ISocket> s = socket.getClear();
  1028. if (ConnectionTable)
  1029. ConnectionTable->remove(tep,s);
  1030. }
  1031. catch (IJSOCK_Exception *e) {
  1032. e->Release(); // ignore errors closing
  1033. }
  1034. Sleep(getRandom()%1000*5+500); // prevent multiple beating
  1035. }
  1036. }
  1037. protected: friend class CRemoteFileIO;
  1038. StringAttr filename;
  1039. CriticalSection crit;
  1040. SocketEndpoint ep;
  1041. void sendRemoteCommand(MemoryBuffer & src, MemoryBuffer & reply, bool retry=true, bool lengthy=false, bool handleErrCode=true)
  1042. {
  1043. CriticalBlock block(crit); // serialize commands on same file
  1044. SocketEndpoint tep(ep);
  1045. setDafsEndpointPort(tep);
  1046. unsigned nretries = retry?3:0;
  1047. Owned<IJSOCK_Exception> firstexc; // when retrying return first error if fails
  1048. for (;;) {
  1049. try {
  1050. if (socket) {
  1051. sendBuffer(socket, src);
  1052. receiveBuffer(socket, reply, lengthy?LENGTHY_RETRIES:NORMAL_RETRIES);
  1053. break;
  1054. }
  1055. }
  1056. catch (IJSOCK_Exception *e) {
  1057. if (!nretries--) {
  1058. if (firstexc) {
  1059. e->Release();
  1060. e = firstexc.getClear();
  1061. }
  1062. killSocket(tep);
  1063. throw e;
  1064. }
  1065. StringBuffer str;
  1066. e->errorMessage(str);
  1067. WARNLOG("Remote File: %s, retrying (%d)",str.str(),nretries);
  1068. if (firstexc)
  1069. e->Release();
  1070. else
  1071. firstexc.setown(e);
  1072. killSocket(tep);
  1073. }
  1074. CriticalBlock block2(CConnectionTable::crit); // this is nested with crit
  1075. if (ConnectionTable) {
  1076. socket.setown(ConnectionTable->lookup(tep));
  1077. if (socket) {
  1078. // validate existing socket by sending an 'exists' command with short time out
  1079. // (use exists for backward compatibility)
  1080. bool ok = false;
  1081. try {
  1082. MemoryBuffer sendbuf;
  1083. initSendBuffer(sendbuf);
  1084. MemoryBuffer replybuf;
  1085. sendbuf.append((RemoteFileCommandType)RFCexists).append(filename);
  1086. sendBuffer(socket, sendbuf);
  1087. receiveBuffer(socket, replybuf, 0, 1024);
  1088. ok = true;
  1089. }
  1090. catch (IException *e) {
  1091. e->Release();
  1092. }
  1093. if (!ok)
  1094. killSocket(tep);
  1095. }
  1096. }
  1097. if (!socket)
  1098. {
  1099. bool doConnect = true;
  1100. if (connectMethod == SSLFirst || connectMethod == UnsecureFirst)
  1101. {
  1102. // MCK - could maintain a list of 100 or so previous endpoints and if connection failed
  1103. // then mark port down for a delay (like 15 min above) to avoid having to try every time ...
  1104. try
  1105. {
  1106. connectSocket(tep, 5000, 1);
  1107. doConnect = false;
  1108. }
  1109. catch (IDAFS_Exception *e)
  1110. {
  1111. if (e->errorCode() == DAFSERR_connection_failed)
  1112. {
  1113. unsigned prevPort = tep.port;
  1114. if (prevPort == securitySettings.daFileSrvSSLPort)
  1115. tep.port = securitySettings.daFileSrvPort;
  1116. else
  1117. tep.port = securitySettings.daFileSrvSSLPort;
  1118. WARNLOG("Connect failed on port %d, retrying on port %d", prevPort, tep.port);
  1119. doConnect = true;
  1120. e->Release();
  1121. }
  1122. else
  1123. throw e;
  1124. }
  1125. }
  1126. if (doConnect)
  1127. connectSocket(tep);
  1128. }
  1129. }
  1130. if (!handleErrCode)
  1131. return;
  1132. unsigned errCode;
  1133. reply.read(errCode);
  1134. if (errCode) {
  1135. StringBuffer msg;
  1136. if (filename.get())
  1137. msg.append(filename);
  1138. ep.getUrlStr(msg.append('[')).append("] ");
  1139. size32_t pos = reply.getPos();
  1140. if (pos<reply.length()) {
  1141. size32_t len = reply.length()-pos;
  1142. const byte *rest = reply.readDirect(len);
  1143. if (errCode==RFSERR_InvalidCommand) {
  1144. const char *s = (const char *)rest;
  1145. const char *e = (const char *)rest+len;
  1146. while (*s&&(s!=e))
  1147. s++;
  1148. msg.append(s-(const char *)rest,(const char *)rest);
  1149. }
  1150. else if (len&&(rest[len-1]==0))
  1151. msg.append((const char *)rest);
  1152. else {
  1153. msg.appendf("extra data[%d]",len);
  1154. for (unsigned i=0;(i<16)&&(i<len);i++)
  1155. msg.appendf(" %2x",(int)rest[i]);
  1156. }
  1157. }
  1158. else if(errCode == 8209)
  1159. msg.append("Failed to open directory.");
  1160. else
  1161. msg.append("ERROR #").append(errCode);
  1162. #ifdef _DEBUG
  1163. ERRLOG("%s",msg.str());
  1164. PrintStackReport();
  1165. #endif
  1166. throw createDafsException(errCode,msg.str());
  1167. }
  1168. }
  1169. void sendRemoteCommand(MemoryBuffer & src, bool retry)
  1170. {
  1171. MemoryBuffer reply;
  1172. sendRemoteCommand(src, reply, retry);
  1173. }
  1174. void throwUnauthenticated(const IpAddress &ip,const char *user,unsigned err=0)
  1175. {
  1176. if (err==0)
  1177. err = RFSERR_AuthenticateFailed;
  1178. StringBuffer msg;
  1179. msg.appendf("Authentication for %s on ",user);
  1180. ip.getIpText(msg);
  1181. msg.append(" failed");
  1182. throw createDafsException(err, msg.str());
  1183. }
  1184. void sendAuthentication(const IpAddress &serverip)
  1185. {
  1186. // send my sig
  1187. // first send my sig which if stream unencrypted will get returned as a bad command
  1188. OnceKey oncekey;
  1189. genOnce(oncekey);
  1190. MemoryBuffer sendbuf;
  1191. initSendBuffer(sendbuf);
  1192. MemoryBuffer replybuf;
  1193. MemoryBuffer encbuf; // because aesEncrypt clears input
  1194. sendbuf.append((RemoteFileCommandType)RFCunlock).append(sizeof(oncekey),&oncekey);
  1195. try {
  1196. sendBuffer(socket, sendbuf);
  1197. receiveBuffer(socket, replybuf, NORMAL_RETRIES, 1024);
  1198. }
  1199. catch (IException *e)
  1200. {
  1201. EXCLOG(e,"Remote file - sendAuthentication(1)");
  1202. throw;
  1203. }
  1204. unsigned errCode;
  1205. replybuf.read(errCode);
  1206. if (errCode!=0) // no authentication required
  1207. return;
  1208. SocketEndpoint ep;
  1209. ep.setLocalHost(0);
  1210. byte ipdata[16];
  1211. size32_t ipds = ep.getNetAddress(sizeof(ipdata),&ipdata);
  1212. mergeOnce(oncekey,ipds,&ipdata);
  1213. StringBuffer username;
  1214. StringBuffer password;
  1215. IPasswordProvider * pp = queryPasswordProvider();
  1216. if (pp)
  1217. pp->getPassword(serverip, username, password);
  1218. if (!username.length())
  1219. username.append("sds_system"); // default account (note if exists should have restricted access!)
  1220. if (!password.length())
  1221. password.append("sds_man");
  1222. if (replybuf.remaining()<=sizeof(size32_t))
  1223. throwUnauthenticated(serverip,username.str());
  1224. size32_t bs;
  1225. replybuf.read(bs);
  1226. if (replybuf.remaining()<bs)
  1227. throwUnauthenticated(serverip,username.str());
  1228. MemoryBuffer skeybuf;
  1229. aesDecrypt(&oncekey,sizeof(oncekey),replybuf.readDirect(bs),bs,skeybuf);
  1230. if (skeybuf.remaining()<sizeof(OnceKey))
  1231. throwUnauthenticated(serverip,username.str());
  1232. OnceKey sokey;
  1233. skeybuf.read(sizeof(OnceKey),&sokey);
  1234. // now we have the key to use to send user/password
  1235. MemoryBuffer tosend;
  1236. tosend.append((byte)2).append(username).append(password);
  1237. initSendBuffer(sendbuf.clear());
  1238. sendbuf.append((RemoteFileCommandType)RFCunlockreply);
  1239. aesEncrypt(&sokey, sizeof(oncekey), tosend.toByteArray(), tosend.length(), encbuf);
  1240. sendbuf.append(encbuf.length());
  1241. sendbuf.append(encbuf);
  1242. try {
  1243. sendBuffer(socket, sendbuf);
  1244. receiveBuffer(socket, replybuf.clear(), NORMAL_RETRIES, 1024);
  1245. }
  1246. catch (IException *e)
  1247. {
  1248. EXCLOG(e,"Remote file - sendAuthentication(2)");
  1249. throw;
  1250. }
  1251. replybuf.read(errCode);
  1252. if (errCode==0) // suceeded!
  1253. return;
  1254. throwUnauthenticated(serverip,username.str(),errCode);
  1255. }
  1256. public:
  1257. SocketEndpoint &queryEp() { return ep; };
  1258. CRemoteBase(const SocketEndpoint &_ep, const char * _filename)
  1259. : filename(_filename)
  1260. {
  1261. ep = _ep;
  1262. connectMethod = securitySettings.connectMethod;
  1263. }
  1264. void disconnect()
  1265. {
  1266. CriticalBlock block(crit);
  1267. CriticalBlock block2(CConnectionTable::crit); // this shouldn't ever block
  1268. if (socket)
  1269. {
  1270. ISocket *s = socket.getClear();
  1271. if (ConnectionTable)
  1272. {
  1273. SocketEndpoint tep(ep);
  1274. setDafsEndpointPort(tep);
  1275. ConnectionTable->remove(tep,s);
  1276. }
  1277. ::Release(s);
  1278. }
  1279. }
  1280. const char *queryLocalName()
  1281. {
  1282. return filename;
  1283. }
  1284. };
  1285. SocketEndpoint CRemoteBase::lastfailep;
  1286. unsigned CRemoteBase::lastfailtime;
  1287. //---------------------------------------------------------------------------
  1288. class CRemoteDirectoryIterator : implements IDirectoryDifferenceIterator, public CInterface
  1289. {
  1290. Owned<IFile> cur;
  1291. bool curvalid;
  1292. bool curisdir;
  1293. StringAttr curname;
  1294. CDateTime curdt;
  1295. __int64 cursize;
  1296. StringAttr dir;
  1297. SocketEndpoint ep;
  1298. byte *flags;
  1299. unsigned numflags;
  1300. unsigned curidx;
  1301. unsigned mask;
  1302. MemoryBuffer buf;
  1303. public:
  1304. static CriticalSection crit;
  1305. CRemoteDirectoryIterator(SocketEndpoint &_ep,const char *_dir)
  1306. : dir(_dir)
  1307. {
  1308. // an extended difference iterator starts with 2 (for bwd compatibility)
  1309. ep = _ep;
  1310. curisdir = false;
  1311. curvalid = false;
  1312. cursize = 0;
  1313. curidx = (unsigned)-1;
  1314. mask = 0;
  1315. numflags = 0;
  1316. flags = NULL;
  1317. }
  1318. bool appendBuf(MemoryBuffer &_buf)
  1319. {
  1320. buf.setSwapEndian(_buf.needSwapEndian());
  1321. byte hdr;
  1322. _buf.read(hdr);
  1323. if (hdr==2) {
  1324. _buf.read(numflags);
  1325. flags = (byte *)malloc(numflags);
  1326. _buf.read(numflags,flags);
  1327. }
  1328. else {
  1329. buf.append(hdr);
  1330. flags = NULL;
  1331. numflags = 0;
  1332. }
  1333. size32_t rest = _buf.length()-_buf.getPos();
  1334. const byte *rb = (const byte *)_buf.readDirect(rest);
  1335. bool ret = true;
  1336. // At the last byte of the rb (rb[rest-1]) is the stream live flag
  1337. // True if the stream has more data
  1338. // False at the end of stream
  1339. // The previous byte (rb[rest-2]) is the flag to signal there are more
  1340. // valid entries in this block
  1341. // True if there are valid directory entry follows this flag
  1342. // False if there are no more valid entry in this block aka end of block
  1343. // If there is more data in the stream, the end of block flag should be removed
  1344. if (rest&&(rb[rest-1]!=0))
  1345. {
  1346. rest--; // remove stream live flag
  1347. if(rest && (0 == rb[rest-1]))
  1348. rest--; //Remove end of block flag
  1349. ret = false; // continuation
  1350. }
  1351. buf.append(rest,rb);
  1352. return ret;
  1353. }
  1354. ~CRemoteDirectoryIterator()
  1355. {
  1356. free(flags);
  1357. }
  1358. IMPLEMENT_IINTERFACE
  1359. bool first()
  1360. {
  1361. curidx = (unsigned)-1;
  1362. buf.reset();
  1363. return next();
  1364. }
  1365. bool next()
  1366. {
  1367. for (;;) {
  1368. curidx++;
  1369. cur.clear();
  1370. curdt.clear();
  1371. curname.clear();
  1372. cursize = 0;
  1373. curisdir = false;
  1374. if (buf.getPos()>=buf.length())
  1375. return false;
  1376. byte isValidEntry;
  1377. buf.read(isValidEntry);
  1378. curvalid = isValidEntry!=0;
  1379. if (!curvalid)
  1380. return false;
  1381. buf.read(curisdir);
  1382. buf.read(cursize);
  1383. curdt.deserialize(buf);
  1384. buf.read(curname);
  1385. // kludge for bug in old linux jlibs
  1386. if (strchr(curname,'\\')&&(getPathSepChar(dir)=='/')) {
  1387. StringBuffer temp(curname);
  1388. temp.replace('\\','/');
  1389. curname.set(temp.str());
  1390. }
  1391. if ((mask==0)||(getFlags()&mask))
  1392. break;
  1393. }
  1394. return true;
  1395. }
  1396. bool isValid()
  1397. {
  1398. return curvalid;
  1399. }
  1400. IFile & query()
  1401. {
  1402. if (!cur) {
  1403. StringBuffer full(dir);
  1404. addPathSepChar(full).append(curname);
  1405. if (ep.isNull())
  1406. cur.setown(createIFile(full.str()));
  1407. else {
  1408. RemoteFilename rfn;
  1409. rfn.setPath(ep,full.str());
  1410. cur.setown(createIFile(rfn));
  1411. }
  1412. }
  1413. return *cur;
  1414. }
  1415. StringBuffer &getName(StringBuffer &buf)
  1416. {
  1417. return buf.append(curname);
  1418. }
  1419. bool isDir()
  1420. {
  1421. return curisdir;
  1422. }
  1423. __int64 getFileSize()
  1424. {
  1425. if (curisdir)
  1426. return -1;
  1427. return cursize;
  1428. }
  1429. bool getModifiedTime(CDateTime &ret)
  1430. {
  1431. ret = curdt;
  1432. return true;
  1433. }
  1434. void setMask(unsigned _mask)
  1435. {
  1436. mask = _mask;
  1437. }
  1438. virtual unsigned getFlags()
  1439. {
  1440. if (flags&&(curidx<numflags))
  1441. return flags[curidx];
  1442. return 0;
  1443. }
  1444. static bool serialize(MemoryBuffer &mb,IDirectoryIterator *iter, size32_t bufsize, bool first)
  1445. {
  1446. bool ret = true;
  1447. byte b=1;
  1448. StringBuffer tmp;
  1449. if (first ? iter->first() : iter->next()) {
  1450. for (;;) {
  1451. mb.append(b);
  1452. bool isdir = iter->isDir();
  1453. __int64 sz = isdir?0:iter->getFileSize();
  1454. CDateTime dt;
  1455. iter->getModifiedTime(dt);
  1456. iter->getName(tmp.clear());
  1457. mb.append(isdir).append(sz);
  1458. dt.serialize(mb);
  1459. mb.append(tmp.str());
  1460. if (bufsize&&(mb.length()>=bufsize-1)) {
  1461. ret = false;
  1462. break;
  1463. }
  1464. if (!iter->next())
  1465. break;
  1466. }
  1467. }
  1468. b = 0;
  1469. mb.append(b);
  1470. return ret;
  1471. }
  1472. static void serializeDiff(MemoryBuffer &mb,IDirectoryDifferenceIterator *iter)
  1473. {
  1474. // bit slow
  1475. MemoryBuffer flags;
  1476. ForEach(*iter)
  1477. flags.append((byte)iter->getFlags());
  1478. if (flags.length()) {
  1479. byte b = 2;
  1480. mb.append(b).append((unsigned)flags.length()).append(flags);
  1481. }
  1482. serialize(mb,iter,0,true);
  1483. }
  1484. void serialize(MemoryBuffer &mb,bool isdiff)
  1485. {
  1486. byte b;
  1487. if (isdiff&&numflags&&flags) {
  1488. b = 2;
  1489. mb.append(b).append(numflags).append(numflags,flags);
  1490. }
  1491. serialize(mb,this,0,true);
  1492. }
  1493. };
  1494. class CCritTable;
  1495. class CEndpointCS : public CriticalSection, public CInterface
  1496. {
  1497. CCritTable &table;
  1498. const SocketEndpoint ep;
  1499. public:
  1500. CEndpointCS(CCritTable &_table, const SocketEndpoint &_ep) : table(_table), ep(_ep) { }
  1501. const void *queryFindParam() const { return &ep; }
  1502. virtual void beforeDispose();
  1503. };
  1504. class CCritTable : private SimpleHashTableOf<CEndpointCS, const SocketEndpoint>
  1505. {
  1506. typedef SimpleHashTableOf<CEndpointCS, const SocketEndpoint> PARENT;
  1507. CriticalSection crit;
  1508. public:
  1509. CEndpointCS *getCrit(const SocketEndpoint &ep)
  1510. {
  1511. CriticalBlock b(crit);
  1512. Linked<CEndpointCS> clientCrit = find(ep);
  1513. if (!clientCrit || !clientCrit->isAlive()) // if !isAlive(), then it is in the process of being destroyed/removed.
  1514. {
  1515. clientCrit.setown(new CEndpointCS(*this, ep));
  1516. replace(*clientCrit); // NB table doesn't own
  1517. }
  1518. return clientCrit.getClear();
  1519. }
  1520. unsigned getHashFromElement(const void *e) const
  1521. {
  1522. const CEndpointCS &elem=*(const CEndpointCS *)e;
  1523. return getHashFromFindParam(elem.queryFindParam());
  1524. }
  1525. unsigned getHashFromFindParam(const void *fp) const
  1526. {
  1527. return ((const SocketEndpoint *)fp)->hash(0);
  1528. }
  1529. void removeExact(CEndpointCS *clientCrit)
  1530. {
  1531. CriticalBlock b(crit);
  1532. PARENT::removeExact(clientCrit); // NB may not exist, could have been replaced if detected !isAlive() in getCrit()
  1533. }
  1534. } *dirCSTable;
  1535. MODULE_INIT(INIT_PRIORITY_STANDARD)
  1536. {
  1537. dirCSTable = new CCritTable;
  1538. return true;
  1539. }
  1540. MODULE_EXIT()
  1541. {
  1542. delete dirCSTable;
  1543. }
  1544. void CEndpointCS::beforeDispose()
  1545. {
  1546. table.removeExact(this);
  1547. }
  1548. class CRemoteFile : public CRemoteBase, implements IFile
  1549. {
  1550. StringAttr remotefilename;
  1551. unsigned flags;
  1552. public:
  1553. IMPLEMENT_IINTERFACE
  1554. CRemoteFile(const SocketEndpoint &_ep, const char * _filename)
  1555. : CRemoteBase(_ep, _filename)
  1556. {
  1557. flags = ((unsigned)IFSHread)|((S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH|S_IWOTH)<<16);
  1558. if (filename.length()>2 && isPathSepChar(filename[0]) && isShareChar(filename[2]))
  1559. {
  1560. VStringBuffer winDriveFilename("%c:%s", filename[1], filename+3);
  1561. filename.set(winDriveFilename);
  1562. }
  1563. }
  1564. bool exists()
  1565. {
  1566. MemoryBuffer sendBuffer;
  1567. initSendBuffer(sendBuffer);
  1568. MemoryBuffer replyBuffer;
  1569. sendBuffer.append((RemoteFileCommandType)RFCexists).append(filename);
  1570. sendRemoteCommand(sendBuffer, replyBuffer);
  1571. bool ok;
  1572. replyBuffer.read(ok);
  1573. return ok;
  1574. }
  1575. bool getTime(CDateTime * createTime, CDateTime * modifiedTime, CDateTime * accessedTime)
  1576. {
  1577. CDateTime dummyTime;
  1578. if (!createTime)
  1579. createTime = &dummyTime;
  1580. if (!modifiedTime)
  1581. modifiedTime = &dummyTime;
  1582. if (!accessedTime)
  1583. accessedTime = &dummyTime;
  1584. MemoryBuffer sendBuffer;
  1585. initSendBuffer(sendBuffer);
  1586. MemoryBuffer replyBuffer;
  1587. sendBuffer.append((RemoteFileCommandType)RFCgettime).append(filename);
  1588. sendRemoteCommand(sendBuffer, replyBuffer);
  1589. bool ok;
  1590. replyBuffer.read(ok);
  1591. if (ok) {
  1592. createTime->deserialize(replyBuffer);
  1593. modifiedTime->deserialize(replyBuffer);
  1594. accessedTime->deserialize(replyBuffer);
  1595. }
  1596. return ok;
  1597. }
  1598. bool setTime(const CDateTime * createTime, const CDateTime * modifiedTime, const CDateTime * accessedTime)
  1599. {
  1600. MemoryBuffer sendBuffer;
  1601. initSendBuffer(sendBuffer);
  1602. MemoryBuffer replyBuffer;
  1603. sendBuffer.append((RemoteFileCommandType)RFCsettime).append(filename);
  1604. if (createTime) {
  1605. sendBuffer.append((bool)true);
  1606. createTime->serialize(sendBuffer);
  1607. }
  1608. else
  1609. sendBuffer.append((bool)false);
  1610. if (modifiedTime) {
  1611. sendBuffer.append((bool)true);
  1612. modifiedTime->serialize(sendBuffer);
  1613. }
  1614. else
  1615. sendBuffer.append((bool)false);
  1616. if (accessedTime) {
  1617. sendBuffer.append((bool)true);
  1618. accessedTime->serialize(sendBuffer);
  1619. }
  1620. else
  1621. sendBuffer.append((bool)false);
  1622. sendRemoteCommand(sendBuffer, replyBuffer);
  1623. bool ok;
  1624. replyBuffer.read(ok);
  1625. return ok;
  1626. }
  1627. fileBool isDirectory()
  1628. {
  1629. MemoryBuffer sendBuffer;
  1630. initSendBuffer(sendBuffer);
  1631. MemoryBuffer replyBuffer;
  1632. sendBuffer.append((RemoteFileCommandType)RFCisdirectory).append(filename);
  1633. sendRemoteCommand(sendBuffer, replyBuffer);
  1634. unsigned ret;
  1635. replyBuffer.read(ret);
  1636. return (fileBool)ret;
  1637. }
  1638. fileBool isFile()
  1639. {
  1640. MemoryBuffer sendBuffer;
  1641. initSendBuffer(sendBuffer);
  1642. MemoryBuffer replyBuffer;
  1643. sendBuffer.append((RemoteFileCommandType)RFCisfile).append(filename);
  1644. sendRemoteCommand(sendBuffer, replyBuffer);
  1645. unsigned ret;
  1646. replyBuffer.read(ret);
  1647. return (fileBool)ret;
  1648. }
  1649. fileBool isReadOnly()
  1650. {
  1651. MemoryBuffer sendBuffer;
  1652. initSendBuffer(sendBuffer);
  1653. MemoryBuffer replyBuffer;
  1654. sendBuffer.append((RemoteFileCommandType)RFCisreadonly).append(filename);
  1655. sendRemoteCommand(sendBuffer, replyBuffer);
  1656. unsigned ret;
  1657. replyBuffer.read(ret);
  1658. return (fileBool)ret;
  1659. }
  1660. IFileIO * open(IFOmode mode,IFEflags extraFlags=IFEnone);
  1661. IFileIO * openShared(IFOmode mode,IFSHmode shmode,IFEflags extraFlags=IFEnone);
  1662. IFileAsyncIO * openAsync(IFOmode mode) { return NULL; } // not supported
  1663. const char * queryFilename()
  1664. {
  1665. if (remotefilename.isEmpty()) {
  1666. RemoteFilename rfn;
  1667. rfn.setPath(ep,filename);
  1668. StringBuffer path;
  1669. rfn.getRemotePath(path);
  1670. remotefilename.set(path);
  1671. }
  1672. return remotefilename.get();
  1673. }
  1674. void resetLocalFilename(const char *name)
  1675. {
  1676. remotefilename.clear();
  1677. filename.set(name);
  1678. }
  1679. bool remove()
  1680. {
  1681. MemoryBuffer sendBuffer;
  1682. initSendBuffer(sendBuffer);
  1683. MemoryBuffer replyBuffer;
  1684. sendBuffer.append((RemoteFileCommandType)RFCremove).append(filename);
  1685. sendRemoteCommand(sendBuffer, replyBuffer);
  1686. bool ok;
  1687. replyBuffer.read(ok);
  1688. return ok;
  1689. }
  1690. void rename(const char *newname)
  1691. {
  1692. // currently ignores directory on newname (in future versions newname will be required to be tail only and not full path)
  1693. StringBuffer path;
  1694. splitDirTail(filename,path);
  1695. StringBuffer newdir;
  1696. path.append(splitDirTail(newname,newdir));
  1697. if (newdir.length()&&(strcmp(newdir.str(),path.str())!=0))
  1698. WARNLOG("CRemoteFile::rename passed full path '%s' that may not to match original directory '%s'",newname,path.str());
  1699. MemoryBuffer sendBuffer;
  1700. initSendBuffer(sendBuffer);
  1701. MemoryBuffer replyBuffer;
  1702. sendBuffer.append((RemoteFileCommandType)RFCrename).append(filename).append(path);
  1703. sendRemoteCommand(sendBuffer, replyBuffer);
  1704. filename.set(path);
  1705. remotefilename.clear();
  1706. }
  1707. void move(const char *newname)
  1708. {
  1709. // like rename except between directories
  1710. // first create replote path
  1711. if (!newname||!*newname)
  1712. return;
  1713. RemoteFilename destrfn;
  1714. if (isPathSepChar(newname[0])&&isPathSepChar(newname[1])) {
  1715. destrfn.setRemotePath(newname);
  1716. if (!destrfn.queryEndpoint().ipequals(ep)) {
  1717. StringBuffer msg;
  1718. msg.appendf("IFile::move %s to %s, destination node must match source node", queryFilename(), newname);
  1719. throw createDafsException(RFSERR_MoveFailed,msg.str());
  1720. }
  1721. }
  1722. else
  1723. destrfn.setPath(ep,newname);
  1724. StringBuffer dest;
  1725. newname = destrfn.getLocalPath(dest).str();
  1726. MemoryBuffer sendBuffer;
  1727. initSendBuffer(sendBuffer);
  1728. MemoryBuffer replyBuffer;
  1729. StringBuffer path;
  1730. splitDirTail(filename,path);
  1731. StringBuffer newdir;
  1732. const char *newtail = splitDirTail(newname,newdir);
  1733. if (strcmp(newdir.str(),path.str())==0) {
  1734. path.append(newtail);
  1735. newname = path;
  1736. sendBuffer.append((RemoteFileCommandType)RFCrename); // use rename if we can (supported on older dafilesrv)
  1737. }
  1738. else
  1739. sendBuffer.append((RemoteFileCommandType)RFCmove);
  1740. sendBuffer.append(filename).append(newname);
  1741. sendRemoteCommand(sendBuffer, replyBuffer);
  1742. filename.set(newname);
  1743. remotefilename.clear();
  1744. }
  1745. void setReadOnly(bool set)
  1746. {
  1747. MemoryBuffer sendBuffer;
  1748. initSendBuffer(sendBuffer);
  1749. MemoryBuffer replyBuffer;
  1750. sendBuffer.append((RemoteFileCommandType)RFCsetreadonly).append(filename).append(set);
  1751. sendRemoteCommand(sendBuffer, replyBuffer);
  1752. }
  1753. void setFilePermissions(unsigned fPerms)
  1754. {
  1755. MemoryBuffer sendBuffer;
  1756. initSendBuffer(sendBuffer);
  1757. MemoryBuffer replyBuffer;
  1758. sendBuffer.append((RemoteFileCommandType)RFCsetfileperms).append(filename).append(fPerms);
  1759. try
  1760. {
  1761. sendRemoteCommand(sendBuffer, replyBuffer);
  1762. }
  1763. catch (IDAFS_Exception *e)
  1764. {
  1765. if (e->errorCode() == RFSERR_InvalidCommand)
  1766. {
  1767. WARNLOG("umask setFilePermissions (0%o) not supported on remote server", fPerms);
  1768. e->Release();
  1769. }
  1770. else
  1771. throw;
  1772. }
  1773. }
  1774. offset_t size()
  1775. {
  1776. #if 1 // faster method (consistant with IFile)
  1777. // do this by using dir call (could be improved with new function but this not *too* bad)
  1778. if (isSpecialPath(filename))
  1779. return 0; // queries deemed to always exist (though don't know size).
  1780. // if needed to get size I guess could use IFileIO method and cache (bit of pain though)
  1781. StringBuffer dir;
  1782. const char *tail = splitDirTail(filename,dir);
  1783. if (!dir.length())
  1784. return false;
  1785. MemoryBuffer sendBuffer;
  1786. initSendBuffer(sendBuffer);
  1787. MemoryBuffer replyBuffer;
  1788. bool includedirs = true;
  1789. bool sub=false;
  1790. {
  1791. //Could be removed with new dafilesrv change [ (stream != 0) ], since this is not streaming.
  1792. Owned<CEndpointCS> crit = dirCSTable->getCrit(ep); // NB dirCSTable doesn't own, last reference will remove from table
  1793. CriticalBlock block(*crit);
  1794. sendBuffer.append((RemoteFileCommandType)RFCgetdir).append(dir).append(tail).append(includedirs).append(sub);
  1795. sendRemoteCommand(sendBuffer, replyBuffer);
  1796. }
  1797. // now should be 0 or 1 files returned
  1798. Owned<CRemoteDirectoryIterator> iter = new CRemoteDirectoryIterator(ep, dir.str());
  1799. iter->appendBuf(replyBuffer);
  1800. if (!iter->first())
  1801. return (offset_t)-1;
  1802. return (offset_t) iter->getFileSize();
  1803. #else
  1804. IFileIO * io = open(IFOread);
  1805. offset_t length = (offset_t)-1;
  1806. if (io)
  1807. {
  1808. length = io->size();
  1809. io->Release();
  1810. }
  1811. return length;
  1812. #endif
  1813. }
  1814. bool createDirectory()
  1815. {
  1816. MemoryBuffer sendBuffer;
  1817. initSendBuffer(sendBuffer);
  1818. MemoryBuffer replyBuffer;
  1819. sendBuffer.append((RemoteFileCommandType)RFCcreatedir).append(filename);
  1820. sendRemoteCommand(sendBuffer, replyBuffer);
  1821. bool ok;
  1822. replyBuffer.read(ok);
  1823. return ok;
  1824. }
  1825. virtual IDirectoryIterator *directoryFiles(const char *mask,bool sub,bool includedirs)
  1826. {
  1827. if (mask&&!*mask)
  1828. return createDirectoryIterator("",""); // NULL iterator
  1829. CRemoteDirectoryIterator *ret = new CRemoteDirectoryIterator(ep, filename);
  1830. byte stream = (sub || !mask || containsFileWildcard(mask)) ? 1 : 0; // no point in streaming if mask without wildcards or sub, as will only be <= 1 match.
  1831. Owned<CEndpointCS> crit = dirCSTable->getCrit(ep); // NB dirCSTable doesn't own, last reference will remove from table
  1832. CriticalBlock block(*crit);
  1833. for (;;) {
  1834. MemoryBuffer sendBuffer;
  1835. initSendBuffer(sendBuffer);
  1836. MemoryBuffer replyBuffer;
  1837. sendBuffer.append((RemoteFileCommandType)RFCgetdir).append(filename).append(mask?mask:"").append(includedirs).append(sub).append(stream);
  1838. sendRemoteCommand(sendBuffer, replyBuffer);
  1839. if (ret->appendBuf(replyBuffer))
  1840. break;
  1841. stream = 2; // NB: will never get here if streaming was off (if stream==0 above)
  1842. }
  1843. return ret;
  1844. }
  1845. IDirectoryDifferenceIterator *monitorDirectory(
  1846. IDirectoryIterator *prev=NULL, // in (NULL means use current as baseline)
  1847. const char *mask=NULL,
  1848. bool sub=false,
  1849. bool includedirs=false,
  1850. unsigned checkinterval=60*1000,
  1851. unsigned timeout=(unsigned)-1,
  1852. Semaphore *abortsem=NULL) // returns NULL if timed out
  1853. {
  1854. // abortsem not yet supported
  1855. MemoryBuffer sendBuffer;
  1856. initSendBuffer(sendBuffer);
  1857. MemoryBuffer replyBuffer;
  1858. sendBuffer.append((RemoteFileCommandType)RFCmonitordir).append(filename).append(mask?mask:"").append(includedirs).append(sub);
  1859. sendBuffer.append(checkinterval).append(timeout);
  1860. __int64 cancelid=0; // not yet used
  1861. sendBuffer.append(cancelid);
  1862. byte isprev=(prev!=NULL)?1:0;
  1863. sendBuffer.append(isprev);
  1864. if (prev)
  1865. CRemoteDirectoryIterator::serialize(sendBuffer,prev,0,true);
  1866. sendRemoteCommand(sendBuffer, replyBuffer);
  1867. byte status;
  1868. replyBuffer.read(status);
  1869. if (status==1) {
  1870. CRemoteDirectoryIterator *iter = new CRemoteDirectoryIterator(ep, filename);
  1871. iter->appendBuf(replyBuffer);
  1872. return iter;
  1873. }
  1874. return NULL;
  1875. }
  1876. bool getInfo(bool &isdir,offset_t &size,CDateTime &modtime)
  1877. {
  1878. // do this by using dir call (could be improved with new function but this not *too* bad)
  1879. StringBuffer dir;
  1880. const char *tail = splitDirTail(filename,dir);
  1881. if (!dir.length())
  1882. return false;
  1883. MemoryBuffer sendBuffer;
  1884. initSendBuffer(sendBuffer);
  1885. MemoryBuffer replyBuffer;
  1886. bool includedirs = true;
  1887. bool sub=false;
  1888. {
  1889. //Could be removed with new dafilesrv change [ (stream != 0) ], since this is not streaming.
  1890. Owned<CEndpointCS> crit = dirCSTable->getCrit(ep); // NB dirCSTable doesn't own, last reference will remove from table
  1891. CriticalBlock block(*crit);
  1892. sendBuffer.append((RemoteFileCommandType)RFCgetdir).append(dir).append(tail).append(includedirs).append(sub);
  1893. sendRemoteCommand(sendBuffer, replyBuffer);
  1894. }
  1895. // now should be 0 or 1 files returned
  1896. Owned<CRemoteDirectoryIterator> iter = new CRemoteDirectoryIterator(ep, dir.str());
  1897. iter->appendBuf(replyBuffer);
  1898. if (!iter->first())
  1899. return false;
  1900. isdir = iter->isDir();
  1901. size = (offset_t) iter->getFileSize();
  1902. iter->getModifiedTime(modtime);
  1903. return true;
  1904. }
  1905. bool setCompression(bool set)
  1906. {
  1907. assertex(!"Need to implement compress()");
  1908. return false;
  1909. }
  1910. offset_t compressedSize()
  1911. {
  1912. assertex(!"Need to implement actualSize()");
  1913. return (offset_t)-1;
  1914. }
  1915. void serialize(MemoryBuffer &tgt)
  1916. {
  1917. throwUnexpected();
  1918. }
  1919. void deserialize(MemoryBuffer &src)
  1920. {
  1921. throwUnexpected();
  1922. }
  1923. unsigned getCRC()
  1924. {
  1925. MemoryBuffer sendBuffer;
  1926. initSendBuffer(sendBuffer);
  1927. MemoryBuffer replyBuffer;
  1928. sendBuffer.append((RemoteFileCommandType)RFCgetcrc).append(filename);
  1929. sendRemoteCommand(sendBuffer, replyBuffer, true, true);
  1930. unsigned crc;
  1931. replyBuffer.read(crc);
  1932. return crc;
  1933. }
  1934. void setCreateFlags(unsigned short cflags)
  1935. {
  1936. flags &= 0xffff;
  1937. flags |= ((unsigned)cflags<<16);
  1938. }
  1939. unsigned short getCreateFlags()
  1940. {
  1941. return (unsigned short)(flags>>16);
  1942. }
  1943. void setShareMode(IFSHmode shmode)
  1944. {
  1945. flags &= ~(IFSHfull|IFSHread);
  1946. flags |= (unsigned)(shmode&(IFSHfull|IFSHread));
  1947. }
  1948. unsigned short getShareMode()
  1949. {
  1950. return (unsigned short)(flags&0xffff);
  1951. }
  1952. void remoteExtractBlobElements(const char * prefix, ExtractedBlobArray & extracted)
  1953. {
  1954. MemoryBuffer sendBuffer;
  1955. initSendBuffer(sendBuffer);
  1956. sendBuffer.append((RemoteFileCommandType)RFCextractblobelements).append(prefix).append(filename);
  1957. MemoryBuffer replyBuffer;
  1958. sendRemoteCommand(sendBuffer, replyBuffer, true, true); // handles error code
  1959. unsigned n;
  1960. replyBuffer.read(n);
  1961. for (unsigned i=0;i<n;i++) {
  1962. ExtractedBlobInfo *item = new ExtractedBlobInfo;
  1963. item->deserialize(replyBuffer);
  1964. extracted.append(*item);
  1965. }
  1966. }
  1967. bool copySectionAsync(const char *uuid,const RemoteFilename &dest, offset_t toOfs, offset_t fromOfs, offset_t size, ICopyFileProgress *progress, unsigned timeout)
  1968. {
  1969. // now if we get here is it can be assumed the source file is local to where we send the command
  1970. StringBuffer tos;
  1971. dest.getRemotePath(tos);
  1972. MemoryBuffer sendBuffer;
  1973. initSendBuffer(sendBuffer);
  1974. MemoryBuffer replyBuffer;
  1975. sendBuffer.append((RemoteFileCommandType)RFCcopysection).append(uuid).append(queryLocalName()).append(tos).append(toOfs).append(fromOfs).append(size).append(timeout);
  1976. sendRemoteCommand(sendBuffer, replyBuffer);
  1977. unsigned status;
  1978. replyBuffer.read(status);
  1979. if (progress) {
  1980. offset_t sizeDone;
  1981. offset_t totalSize;
  1982. replyBuffer.read(sizeDone).read(totalSize);
  1983. progress->onProgress(sizeDone,totalSize);
  1984. }
  1985. return (AsyncCommandStatus)status!=ACScontinue; // should only otherwise be done as errors raised by exception
  1986. }
  1987. void copySection(const RemoteFilename &dest, offset_t toOfs, offset_t fromOfs, offset_t size, ICopyFileProgress *progress, CFflags copyFlags=CFnone)
  1988. {
  1989. StringBuffer uuid;
  1990. genUUID(uuid,true);
  1991. unsigned timeout = 60*1000; // check every minute
  1992. while(!copySectionAsync(uuid.str(),dest,toOfs,fromOfs,size,progress,timeout));
  1993. }
  1994. void copyTo(IFile *dest, size32_t buffersize, ICopyFileProgress *progress, bool usetmp, CFflags copyFlags=CFnone);
  1995. virtual IMemoryMappedFile *openMemoryMapped(offset_t ofs, memsize_t len, bool write)
  1996. {
  1997. return NULL;
  1998. }
  1999. };
  2000. void clientAddSocketToCache(SocketEndpoint &ep,ISocket *socket)
  2001. {
  2002. CriticalBlock block(CConnectionTable::crit);
  2003. if (ConnectionTable)
  2004. ConnectionTable->addLink(ep,socket);
  2005. }
  2006. IFile * createRemoteFile(SocketEndpoint &ep, const char * filename)
  2007. {
  2008. IFile *ret = createFileLocalMount(ep,filename);
  2009. if (ret)
  2010. return ret;
  2011. return new CRemoteFile(ep, filename);
  2012. }
  2013. void clientDisconnectRemoteFile(IFile *file)
  2014. {
  2015. CRemoteFile *cfile = QUERYINTERFACE(file,CRemoteFile);
  2016. if (cfile)
  2017. cfile->disconnect();
  2018. }
  2019. bool clientResetFilename(IFile *file, const char *newname) // returns false if not remote
  2020. {
  2021. CRemoteFile *cfile = QUERYINTERFACE(file,CRemoteFile);
  2022. if (!cfile)
  2023. return false;
  2024. cfile->resetLocalFilename(newname);
  2025. return true;
  2026. }
  2027. extern bool clientAsyncCopyFileSection(const char *uuid,
  2028. IFile *from, // expected to be remote
  2029. RemoteFilename &to,
  2030. offset_t toOfs, // -1 created file and copies to start
  2031. offset_t fromOfs,
  2032. offset_t size,
  2033. ICopyFileProgress *progress,
  2034. unsigned timeout) // returns true when done
  2035. {
  2036. CRemoteFile *cfile = QUERYINTERFACE(from,CRemoteFile);
  2037. if (!cfile) {
  2038. // local - do sync
  2039. from->copySection(to,toOfs,fromOfs,size,progress);
  2040. return true;
  2041. }
  2042. return cfile->copySectionAsync(uuid,to,toOfs,fromOfs, size, progress, timeout);
  2043. }
  2044. //---------------------------------------------------------------------------
  2045. class CRemoteFileIO : implements IFileIO, public CInterface
  2046. {
  2047. protected:
  2048. Linked<CRemoteFile> parent;
  2049. RemoteFileIOHandle handle;
  2050. std::atomic<cycle_t> ioReadCycles;
  2051. std::atomic<cycle_t> ioWriteCycles;
  2052. std::atomic<__uint64> ioReadBytes;
  2053. std::atomic<__uint64> ioWriteBytes;
  2054. std::atomic<__uint64> ioReads;
  2055. std::atomic<__uint64> ioWrites;
  2056. std::atomic<unsigned> ioRetries;
  2057. IFOmode mode;
  2058. compatIFSHmode compatmode;
  2059. IFEflags extraFlags;
  2060. bool disconnectonexit;
  2061. public:
  2062. IMPLEMENT_IINTERFACE
  2063. CRemoteFileIO(CRemoteFile *_parent)
  2064. : parent(_parent), ioReadCycles(0), ioWriteCycles(0), ioReadBytes(0), ioWriteBytes(0), ioReads(0), ioWrites(0), ioRetries(0)
  2065. {
  2066. handle = 0;
  2067. disconnectonexit = false;
  2068. }
  2069. ~CRemoteFileIO()
  2070. {
  2071. if (handle) {
  2072. try {
  2073. close();
  2074. }
  2075. catch (IException *e) {
  2076. StringBuffer s;
  2077. e->errorMessage(s);
  2078. WARNLOG("CRemoteFileIO close file: %s",s.str());
  2079. e->Release();
  2080. }
  2081. }
  2082. if (disconnectonexit)
  2083. parent->disconnect();
  2084. }
  2085. void close()
  2086. {
  2087. if (handle) {
  2088. try {
  2089. MemoryBuffer sendBuffer;
  2090. initSendBuffer(sendBuffer);
  2091. sendBuffer.append((RemoteFileCommandType)RFCcloseIO).append(handle);
  2092. parent->sendRemoteCommand(sendBuffer,false);
  2093. }
  2094. catch (IDAFS_Exception *e) {
  2095. if ((e->errorCode()!=RFSERR_InvalidFileIOHandle)&&(e->errorCode()!=RFSERR_NullFileIOHandle))
  2096. throw;
  2097. e->Release();
  2098. }
  2099. handle = 0;
  2100. }
  2101. }
  2102. RemoteFileIOHandle getHandle() const { return handle; }
  2103. bool open(IFOmode _mode,compatIFSHmode _compatmode,IFEflags _extraFlags=IFEnone)
  2104. {
  2105. MemoryBuffer sendBuffer;
  2106. initSendBuffer(sendBuffer);
  2107. MemoryBuffer replyBuffer;
  2108. const char *localname = parent->queryLocalName();
  2109. localname = skipSpecialPath(localname);
  2110. // also send _extraFlags
  2111. // then also send sMode, cFlags
  2112. unsigned short sMode = parent->getShareMode();
  2113. unsigned short cFlags = parent->getCreateFlags();
  2114. switch ((compatIFSHmode)_compatmode)
  2115. {
  2116. case compatIFSHnone:
  2117. sMode = IFSHnone;
  2118. break;
  2119. case compatIFSHread:
  2120. sMode = IFSHread;
  2121. break;
  2122. case compatIFSHwrite:
  2123. sMode = IFSHfull;
  2124. break;
  2125. case compatIFSHall:
  2126. sMode = IFSHfull;
  2127. break;
  2128. }
  2129. sendBuffer.append((RemoteFileCommandType)RFCopenIO).append(localname).append((byte)_mode).append((byte)_compatmode).append((byte)_extraFlags).append(sMode).append(cFlags);
  2130. parent->sendRemoteCommand(sendBuffer, replyBuffer);
  2131. replyBuffer.read(handle);
  2132. if (!handle)
  2133. return false;
  2134. switch (_mode) {
  2135. case IFOcreate:
  2136. mode = IFOwrite;
  2137. break;
  2138. case IFOcreaterw:
  2139. mode = IFOreadwrite;
  2140. break;
  2141. default:
  2142. mode = _mode;
  2143. break;
  2144. }
  2145. compatmode = _compatmode;
  2146. extraFlags = _extraFlags;
  2147. return true;
  2148. }
  2149. bool reopen()
  2150. {
  2151. StringBuffer s;
  2152. PROGLOG("Attempting reopen of %s on %s",parent->queryLocalName(),parent->queryEp().getUrlStr(s).str());
  2153. if (open(mode,compatmode,extraFlags)) {
  2154. return true;
  2155. }
  2156. return false;
  2157. }
  2158. offset_t size()
  2159. {
  2160. MemoryBuffer sendBuffer;
  2161. initSendBuffer(sendBuffer);
  2162. MemoryBuffer replyBuffer;
  2163. sendBuffer.append((RemoteFileCommandType)RFCsize).append(handle);
  2164. parent->sendRemoteCommand(sendBuffer, replyBuffer, false);
  2165. // Retry using reopen TBD
  2166. offset_t ret;
  2167. replyBuffer.read(ret);
  2168. return ret;
  2169. }
  2170. virtual unsigned __int64 getStatistic(StatisticKind kind)
  2171. {
  2172. switch (kind)
  2173. {
  2174. case StCycleDiskReadIOCycles:
  2175. return ioReadCycles.load(std::memory_order_relaxed);
  2176. case StCycleDiskWriteIOCycles:
  2177. return ioWriteCycles.load(std::memory_order_relaxed);
  2178. case StTimeDiskReadIO:
  2179. return cycle_to_nanosec(ioReadCycles.load(std::memory_order_relaxed));
  2180. case StTimeDiskWriteIO:
  2181. return cycle_to_nanosec(ioWriteCycles.load(std::memory_order_relaxed));
  2182. case StSizeDiskRead:
  2183. return ioReadBytes.load(std::memory_order_relaxed);
  2184. case StSizeDiskWrite:
  2185. return ioWriteBytes.load(std::memory_order_relaxed);
  2186. case StNumDiskReads:
  2187. return ioReads.load(std::memory_order_relaxed);
  2188. case StNumDiskWrites:
  2189. return ioWrites.load(std::memory_order_relaxed);
  2190. case StNumDiskRetries:
  2191. return ioRetries.load(std::memory_order_relaxed);
  2192. }
  2193. return 0;
  2194. }
  2195. size32_t read(offset_t pos, size32_t len, void * data)
  2196. {
  2197. size32_t got;
  2198. MemoryBuffer replyBuffer;
  2199. CCycleTimer timer;
  2200. const void *b;
  2201. try
  2202. {
  2203. b = doRead(pos,len,replyBuffer,got,data);
  2204. }
  2205. catch (...)
  2206. {
  2207. ioReadCycles.fetch_add(timer.elapsedCycles());
  2208. throw;
  2209. }
  2210. ioReadCycles.fetch_add(timer.elapsedCycles());
  2211. ioReadBytes.fetch_add(got);
  2212. ++ioReads;
  2213. if (b!=data)
  2214. memcpy(data,b,got);
  2215. return got;
  2216. }
  2217. virtual void flush()
  2218. {
  2219. }
  2220. const void *doRead(offset_t pos, size32_t len, MemoryBuffer &replyBuffer, size32_t &got, void *dstbuf)
  2221. {
  2222. unsigned tries=0;
  2223. for (;;) {
  2224. try {
  2225. MemoryBuffer sendBuffer;
  2226. initSendBuffer(sendBuffer);
  2227. replyBuffer.clear();
  2228. sendBuffer.append((RemoteFileCommandType)RFCread).append(handle).append(pos).append(len);
  2229. parent->sendRemoteCommand(sendBuffer, replyBuffer,false);
  2230. // kludge dafilesrv versions <= 1.5e don't return error correctly
  2231. if (replyBuffer.length()>len+sizeof(size32_t)+sizeof(unsigned)) {
  2232. size32_t save = replyBuffer.getPos();
  2233. replyBuffer.reset(len+sizeof(size32_t)+sizeof(unsigned));
  2234. unsigned errCode;
  2235. replyBuffer.read(errCode);
  2236. if (errCode) {
  2237. StringBuffer msg;
  2238. parent->ep.getUrlStr(msg.append('[')).append("] ");
  2239. if (replyBuffer.getPos()<replyBuffer.length()) {
  2240. StringAttr s;
  2241. replyBuffer.read(s);
  2242. msg.append(s);
  2243. }
  2244. else
  2245. msg.append("ERROR #").append(errCode);
  2246. throw createDafsException(errCode, msg.str());
  2247. }
  2248. else
  2249. replyBuffer.reset(save);
  2250. }
  2251. replyBuffer.read(got);
  2252. if ((got>replyBuffer.remaining())||(got>len)) {
  2253. PROGLOG("Read beyond buffer %d,%d,%d",got,replyBuffer.remaining(),len);
  2254. throw createDafsException(RFSERR_ReadFailed, "Read beyond buffer");
  2255. }
  2256. return replyBuffer.readDirect(got);
  2257. }
  2258. catch (IJSOCK_Exception *e) {
  2259. EXCLOG(e,"CRemoteFileIO::read");
  2260. if (++tries > 3)
  2261. {
  2262. ioRetries.fetch_add(tries);
  2263. throw;
  2264. }
  2265. WARNLOG("Retrying read of %s (%d)",parent->queryLocalName(),tries);
  2266. Owned<IException> exc = e;
  2267. if (!reopen())
  2268. {
  2269. ioRetries.fetch_add(tries);
  2270. throw exc.getClear();
  2271. }
  2272. }
  2273. }
  2274. if (tries)
  2275. ioRetries.fetch_add(tries);
  2276. got = 0;
  2277. return NULL;
  2278. }
  2279. size32_t write(offset_t pos, size32_t len, const void * data)
  2280. {
  2281. unsigned tries=0;
  2282. size32_t ret = 0;
  2283. CCycleTimer timer;
  2284. for (;;) {
  2285. try {
  2286. MemoryBuffer replyBuffer;
  2287. MemoryBuffer sendBuffer;
  2288. initSendBuffer(sendBuffer);
  2289. sendBuffer.append((RemoteFileCommandType)RFCwrite).append(handle).append(pos).append(len).append(len, data);
  2290. parent->sendRemoteCommand(sendBuffer, replyBuffer, false, true);
  2291. replyBuffer.read(ret);
  2292. break;
  2293. }
  2294. catch (IJSOCK_Exception *e) {
  2295. EXCLOG(e,"CRemoteFileIO::write");
  2296. if (++tries > 3)
  2297. {
  2298. ioRetries.fetch_add(tries);
  2299. ioWriteCycles.fetch_add(timer.elapsedCycles());
  2300. throw;
  2301. }
  2302. WARNLOG("Retrying write(%" I64F "d,%d) of %s (%d)",pos,len,parent->queryLocalName(),tries);
  2303. Owned<IException> exc = e;
  2304. if (!reopen())
  2305. {
  2306. ioRetries.fetch_add(tries);
  2307. ioWriteCycles.fetch_add(timer.elapsedCycles());
  2308. throw exc.getClear();
  2309. }
  2310. }
  2311. }
  2312. if (tries)
  2313. ioRetries.fetch_add(tries);
  2314. ioWriteCycles.fetch_add(timer.elapsedCycles());
  2315. ioWriteBytes.fetch_add(ret);
  2316. ++ioWrites;
  2317. if ((ret==(size32_t)-1) || (ret < len))
  2318. throw createDafsException(DISK_FULL_EXCEPTION_CODE,"write failed, disk full?");
  2319. return ret;
  2320. }
  2321. offset_t appendFile(IFile *file,offset_t pos,offset_t len)
  2322. {
  2323. MemoryBuffer sendBuffer;
  2324. initSendBuffer(sendBuffer);
  2325. MemoryBuffer replyBuffer;
  2326. const char * fname = file->queryFilename();
  2327. sendBuffer.append((RemoteFileCommandType)RFCappend).append(handle).append(fname).append(pos).append(len);
  2328. parent->sendRemoteCommand(sendBuffer, replyBuffer, false, true); // retry not safe
  2329. offset_t ret;
  2330. replyBuffer.read(ret);
  2331. if ((ret==(offset_t)-1) || ((len != ((offset_t)-1)) && (ret < len)))
  2332. throw createDafsException(DISK_FULL_EXCEPTION_CODE,"append failed, disk full?"); // though could be file missing TBD
  2333. return ret;
  2334. }
  2335. void setSize(offset_t size)
  2336. {
  2337. MemoryBuffer sendBuffer;
  2338. initSendBuffer(sendBuffer);
  2339. MemoryBuffer replyBuffer;
  2340. sendBuffer.append((RemoteFileCommandType)RFCsetsize).append(handle).append(size);
  2341. parent->sendRemoteCommand(sendBuffer, replyBuffer, false, true);
  2342. // retry using reopen TBD
  2343. }
  2344. void setDisconnectOnExit(bool set) { disconnectonexit = set; }
  2345. void sendRemoteCommand(MemoryBuffer & sendBuffer, MemoryBuffer & replyBuffer, bool retry=true, bool lengthy=false, bool handleErrCode=true)
  2346. {
  2347. parent->sendRemoteCommand(sendBuffer, replyBuffer, retry, lengthy, handleErrCode);
  2348. }
  2349. };
  2350. void clientDisconnectRemoteIoOnExit(IFileIO *fileio,bool set)
  2351. {
  2352. CRemoteFileIO *cfileio = QUERYINTERFACE(fileio,CRemoteFileIO);
  2353. if (cfileio)
  2354. cfileio->setDisconnectOnExit(set);
  2355. }
  2356. IFileIO * CRemoteFile::openShared(IFOmode mode,IFSHmode shmode,IFEflags extraFlags)
  2357. {
  2358. assertex(((unsigned)shmode&0xffffffc7)==0);
  2359. compatIFSHmode compatmode;
  2360. unsigned fileflags = (flags>>16) & (S_IRUSR|S_IWUSR|S_IXUSR|S_IRGRP|S_IWGRP|S_IXGRP|S_IROTH|S_IWOTH|S_IXOTH);
  2361. if (fileflags&S_IXUSR) // this is bit hit and miss but backward compatible
  2362. compatmode = compatIFSHexec;
  2363. else if (fileflags&(S_IWGRP|S_IWOTH))
  2364. compatmode = compatIFSHall;
  2365. else if (shmode&IFSHfull)
  2366. compatmode = compatIFSHwrite;
  2367. else if (((shmode&(IFSHread|IFSHfull))==0) && ((fileflags&(S_IRGRP|S_IROTH))==0))
  2368. compatmode = compatIFSHnone;
  2369. else
  2370. compatmode = compatIFSHread;
  2371. Owned<CRemoteFileIO> res = new CRemoteFileIO(this);
  2372. if (res->open(mode,compatmode,extraFlags))
  2373. return res.getClear();
  2374. return NULL;
  2375. }
  2376. IFileIO * CRemoteFile::open(IFOmode mode,IFEflags extraFlags)
  2377. {
  2378. return openShared(mode,(IFSHmode)(flags&(IFSHread|IFSHfull)),extraFlags);
  2379. }
  2380. //---------------------------------------------------------------------------
  2381. void CRemoteFile::copyTo(IFile *dest, size32_t buffersize, ICopyFileProgress *progress, bool usetmp, CFflags copyFlags)
  2382. {
  2383. CRemoteFile *dstfile = QUERYINTERFACE(dest,CRemoteFile);
  2384. if (dstfile&&!dstfile->queryEp().isLocal()) {
  2385. StringBuffer tmpname;
  2386. Owned<IFile> destf;
  2387. RemoteFilename dest;
  2388. if (usetmp) {
  2389. makeTempCopyName(tmpname,dstfile->queryLocalName());
  2390. dest.setPath(dstfile->queryEp(),tmpname.str());
  2391. }
  2392. else
  2393. dest.setPath(dstfile->queryEp(),dstfile->queryLocalName());
  2394. destf.setown(createIFile(dest));
  2395. try {
  2396. // following may fail if new dafilesrv not deployed on src
  2397. copySection(dest,(offset_t)-1,0,(offset_t)-1,progress,copyFlags);
  2398. if (usetmp) {
  2399. StringAttr tail(pathTail(dstfile->queryLocalName()));
  2400. dstfile->remove();
  2401. destf->rename(tail);
  2402. }
  2403. return;
  2404. }
  2405. catch (IException *e)
  2406. {
  2407. StringBuffer s;
  2408. s.appendf("Remote File Copy (%d): ",e->errorCode());
  2409. e->errorMessage(s);
  2410. s.append(", retrying local");
  2411. WARNLOG("%s",s.str());
  2412. e->Release();
  2413. }
  2414. // delete dest
  2415. try {
  2416. destf->remove();
  2417. }
  2418. catch (IException *e)
  2419. {
  2420. EXCLOG(e,"Remote File Copy, Deleting temporary file");
  2421. e->Release();
  2422. }
  2423. }
  2424. // assumption if we get here that source remote, dest local (or equiv)
  2425. class cIntercept: implements ICopyFileIntercept
  2426. {
  2427. MemoryAttr ma;
  2428. MemoryBuffer mb;
  2429. virtual offset_t copy(IFileIO *from, IFileIO *to, offset_t ofs, size32_t sz)
  2430. {
  2431. if (ma.length()<sz)
  2432. ma.allocate(sz); // may be not used
  2433. void *buf = ma.bufferBase();
  2434. size32_t got;
  2435. CRemoteFileIO *srcio = QUERYINTERFACE(from,CRemoteFileIO);
  2436. const void *dst;
  2437. if (srcio)
  2438. dst = srcio->doRead(ofs,sz,mb.clear(),got,buf);
  2439. else {
  2440. // shouldn't ever get here if source remote
  2441. got = from->read(ofs, sz, buf);
  2442. dst = buf;
  2443. }
  2444. if (got != 0)
  2445. to->write(ofs, got, dst);
  2446. return got;
  2447. }
  2448. } intercept;
  2449. doCopyFile(dest,this,buffersize,progress,&intercept,usetmp,copyFlags);
  2450. }
  2451. /////////////////////////
  2452. ISocket *checkSocketSecure(ISocket *socket)
  2453. {
  2454. if (securitySettings.connectMethod == SSLNone)
  2455. return LINK(socket);
  2456. char pname[256];
  2457. pname[0] = 0;
  2458. int pport = socket->peer_name(pname, sizeof(pname)-1);
  2459. if ( (pport == securitySettings.daFileSrvSSLPort) && (!socket->isSecure()) )
  2460. {
  2461. #ifdef _USE_OPENSSL
  2462. Owned<ISecureSocket> ssock;
  2463. try
  2464. {
  2465. ssock.setown(createSecureSocket(LINK(socket), ClientSocket));
  2466. int status = ssock->secure_connect();
  2467. if (status < 0)
  2468. throw createDafsException(DAFSERR_connection_failed, "Failure to establish secure connection");
  2469. return ssock.getClear();
  2470. }
  2471. catch (IException *e)
  2472. {
  2473. cleanupSocket(ssock);
  2474. ssock.clear();
  2475. cleanupSocket(socket);
  2476. StringBuffer eMsg;
  2477. e->errorMessage(eMsg);
  2478. e->Release();
  2479. throw createDafsException(DAFSERR_connection_failed, eMsg.str());
  2480. }
  2481. #else
  2482. throw createDafsException(DAFSERR_connection_failed,"Failure to establish secure connection: OpenSSL disabled in build");
  2483. #endif
  2484. }
  2485. return LINK(socket);
  2486. }
  2487. ISocket *connectDafs(SocketEndpoint &ep, unsigned timeoutms)
  2488. {
  2489. Owned<ISocket> socket;
  2490. if ( (securitySettings.connectMethod == SSLNone) || (securitySettings.connectMethod == SSLOnly) )
  2491. {
  2492. socket.setown(ISocket::connect_timeout(ep, timeoutms));
  2493. return checkSocketSecure(socket);
  2494. }
  2495. // SSLFirst or UnsecureFirst ...
  2496. unsigned newtimeout = timeoutms;
  2497. if (newtimeout > 5000)
  2498. newtimeout = 5000;
  2499. int conAttempts = 2;
  2500. while (conAttempts > 0)
  2501. {
  2502. conAttempts--;
  2503. bool connected = false;
  2504. try
  2505. {
  2506. socket.setown(ISocket::connect_timeout(ep, newtimeout));
  2507. connected = true;
  2508. newtimeout = timeoutms;
  2509. }
  2510. catch (IJSOCK_Exception *e)
  2511. {
  2512. if (e->errorCode() == JSOCKERR_connection_failed)
  2513. {
  2514. e->Release();
  2515. if (ep.port == securitySettings.daFileSrvSSLPort)
  2516. ep.port = securitySettings.daFileSrvPort;
  2517. else
  2518. ep.port = securitySettings.daFileSrvSSLPort;
  2519. if (!conAttempts)
  2520. throw;
  2521. }
  2522. else
  2523. throw;
  2524. }
  2525. if (connected)
  2526. {
  2527. if (ep.port == securitySettings.daFileSrvSSLPort)
  2528. {
  2529. try
  2530. {
  2531. return checkSocketSecure(socket);
  2532. }
  2533. catch (IDAFS_Exception *e)
  2534. {
  2535. connected = false;
  2536. if (e->errorCode() == DAFSERR_connection_failed)
  2537. {
  2538. // worth logging to help identify any ssl config issues ...
  2539. StringBuffer errmsg;
  2540. e->errorMessage(errmsg);
  2541. WARNLOG("%s", errmsg.str());
  2542. e->Release();
  2543. ep.port = securitySettings.daFileSrvPort;
  2544. if (!conAttempts)
  2545. throw;
  2546. }
  2547. else
  2548. throw;
  2549. }
  2550. }
  2551. else
  2552. return socket.getClear();
  2553. }
  2554. }
  2555. throw createDafsException(DAFSERR_connection_failed, "Failed to establish connection with DaFileSrv");
  2556. }
  2557. unsigned getRemoteVersion(CRemoteFileIO &remoteFileIO, StringBuffer &ver)
  2558. {
  2559. unsigned ret;
  2560. MemoryBuffer sendBuffer;
  2561. initSendBuffer(sendBuffer);
  2562. sendBuffer.append((RemoteFileCommandType)RFCgetver);
  2563. sendBuffer.append((unsigned)RFCgetver);
  2564. MemoryBuffer replyBuffer;
  2565. try
  2566. {
  2567. remoteFileIO.sendRemoteCommand(sendBuffer, replyBuffer, true, false, false);
  2568. }
  2569. catch (IException *e)
  2570. {
  2571. EXCLOG(e);
  2572. ::Release(e);
  2573. return 0;
  2574. }
  2575. unsigned errCode;
  2576. replyBuffer.read(errCode);
  2577. if (errCode==RFSERR_InvalidCommand)
  2578. {
  2579. ver.append("DS V1.0");
  2580. return 10;
  2581. }
  2582. else if (errCode==0)
  2583. ret = 11;
  2584. else if (errCode<0x10000)
  2585. return 0;
  2586. else
  2587. ret = errCode-0x10000;
  2588. StringAttr vers;
  2589. replyBuffer.read(vers);
  2590. ver.append(vers);
  2591. return ret;
  2592. }
  2593. unsigned getRemoteVersion(ISocket *origSock, StringBuffer &ver)
  2594. {
  2595. // used to have a global critical section here
  2596. if (!origSock)
  2597. return 0;
  2598. Owned<ISocket> socket = checkSocketSecure(origSock);
  2599. unsigned ret;
  2600. MemoryBuffer sendbuf;
  2601. initSendBuffer(sendbuf);
  2602. sendbuf.append((RemoteFileCommandType)RFCgetver);
  2603. sendbuf.append((unsigned)RFCgetver);
  2604. MemoryBuffer reply;
  2605. try {
  2606. sendBuffer(socket, sendbuf);
  2607. receiveBuffer(socket, reply, 1 ,4096);
  2608. unsigned errCode;
  2609. reply.read(errCode);
  2610. if (errCode==RFSERR_InvalidCommand) {
  2611. ver.append("DS V1.0");
  2612. return 10;
  2613. }
  2614. else if (errCode==0)
  2615. ret = 11;
  2616. else if (errCode<0x10000)
  2617. return 0;
  2618. else
  2619. ret = errCode-0x10000;
  2620. }
  2621. catch (IException *e) {
  2622. EXCLOG(e);
  2623. ::Release(e);
  2624. return 0;
  2625. }
  2626. StringAttr vers;
  2627. reply.read(vers);
  2628. ver.append(vers);
  2629. return ret;
  2630. }
  2631. /////////////////////////
  2632. //////////////
  2633. extern unsigned stopRemoteServer(ISocket * socket)
  2634. {
  2635. // used to have a global critical section here
  2636. if (!socket)
  2637. return 0;
  2638. MemoryBuffer sendbuf;
  2639. initSendBuffer(sendbuf);
  2640. sendbuf.append((RemoteFileCommandType)RFCstop);
  2641. sendbuf.append((unsigned)RFCstop);
  2642. MemoryBuffer replybuf;
  2643. unsigned errCode = RFSERR_InvalidCommand;
  2644. try {
  2645. sendBuffer(socket, sendbuf);
  2646. receiveBuffer(socket, replybuf, NORMAL_RETRIES, 1024);
  2647. replybuf.read(errCode);
  2648. }
  2649. catch (IJSOCK_Exception *e) {
  2650. if ((e->errorCode()!=JSOCKERR_broken_pipe)&&(e->errorCode()!=JSOCKERR_graceful_close))
  2651. EXCLOG(e);
  2652. else
  2653. errCode = 0;
  2654. }
  2655. catch (IException *e) {
  2656. EXCLOG(e);
  2657. ::Release(e);
  2658. }
  2659. return errCode;
  2660. }
  2661. int setDafsTrace(ISocket * socket,byte flags)
  2662. {
  2663. if (!socket) {
  2664. byte ret = traceFlags;
  2665. traceFlags = flags;
  2666. return ret;
  2667. }
  2668. MemoryBuffer sendbuf;
  2669. initSendBuffer(sendbuf);
  2670. sendbuf.append((RemoteFileCommandType)RFCsettrace).append(flags);
  2671. MemoryBuffer replybuf;
  2672. try {
  2673. sendBuffer(socket, sendbuf);
  2674. receiveBuffer(socket, replybuf, NORMAL_RETRIES, 1024);
  2675. int retcode;
  2676. replybuf.read(retcode);
  2677. return retcode;
  2678. }
  2679. catch (IException *e) {
  2680. EXCLOG(e);
  2681. ::Release(e);
  2682. }
  2683. return -1;
  2684. }
  2685. int setDafsThrottleLimit(ISocket * socket, ThrottleClass throttleClass, unsigned throttleLimit, unsigned throttleDelayMs, unsigned throttleCPULimit, unsigned queueLimit, StringBuffer *errMsg)
  2686. {
  2687. assertex(socket);
  2688. MemoryBuffer sendbuf;
  2689. initSendBuffer(sendbuf);
  2690. sendbuf.append((RemoteFileCommandType)RFCsetthrottle2).append((unsigned)throttleClass).append(throttleLimit);
  2691. sendbuf.append(throttleDelayMs).append(throttleCPULimit).append(queueLimit);
  2692. MemoryBuffer replybuf;
  2693. try {
  2694. sendBuffer(socket, sendbuf);
  2695. receiveBuffer(socket, replybuf, NORMAL_RETRIES, 1024);
  2696. int retcode;
  2697. replybuf.read(retcode);
  2698. if (retcode && errMsg && replybuf.remaining())
  2699. replybuf.read(*errMsg);
  2700. return retcode;
  2701. }
  2702. catch (IException *e) {
  2703. EXCLOG(e);
  2704. ::Release(e);
  2705. }
  2706. return -1;
  2707. }
  2708. int getDafsInfo(ISocket * socket, unsigned level, StringBuffer &retstr)
  2709. {
  2710. if (!socket) {
  2711. retstr.append(VERSTRING);
  2712. return 0;
  2713. }
  2714. MemoryBuffer sendbuf;
  2715. initSendBuffer(sendbuf);
  2716. sendbuf.append((RemoteFileCommandType)RFCgetinfo).append(level);
  2717. MemoryBuffer replybuf;
  2718. try {
  2719. sendBuffer(socket, sendbuf);
  2720. receiveBuffer(socket, replybuf, 1);
  2721. int retcode;
  2722. replybuf.read(retcode);
  2723. if (retcode==0) {
  2724. StringAttr s;
  2725. replybuf.read(s);
  2726. retstr.append(s);
  2727. }
  2728. return retcode;
  2729. }
  2730. catch (IException *e) {
  2731. EXCLOG(e);
  2732. ::Release(e);
  2733. }
  2734. return -1;
  2735. }
  2736. void remoteExtractBlobElements(const SocketEndpoint &ep,const char * prefix, const char * filename, ExtractedBlobArray & extracted)
  2737. {
  2738. Owned<CRemoteFile> file = new CRemoteFile (ep,filename);
  2739. file->remoteExtractBlobElements(prefix, extracted);
  2740. }
  2741. //====================================================================================================
  2742. class CAsyncCommandManager
  2743. {
  2744. class CAsyncJob: public CInterface
  2745. {
  2746. class cThread: public Thread
  2747. {
  2748. CAsyncJob *parent;
  2749. public:
  2750. cThread(CAsyncJob *_parent)
  2751. : Thread("CAsyncJob")
  2752. {
  2753. parent = _parent;
  2754. }
  2755. int run()
  2756. {
  2757. int ret = -1;
  2758. try {
  2759. ret = parent->run();
  2760. parent->setDone();
  2761. }
  2762. catch (IException *e)
  2763. {
  2764. parent->setException(e);
  2765. }
  2766. parent->signal();
  2767. return ret;
  2768. }
  2769. } *thread;
  2770. StringAttr uuid;
  2771. CAsyncCommandManager &parent;
  2772. public:
  2773. CAsyncJob(CAsyncCommandManager &_parent, const char *_uuid)
  2774. : uuid(_uuid), parent(_parent)
  2775. {
  2776. thread = new cThread(this);
  2777. hash = hashc((const byte *)uuid.get(),uuid.length(),~0U);
  2778. }
  2779. ~CAsyncJob()
  2780. {
  2781. thread->join();
  2782. thread->Release();
  2783. }
  2784. static void destroy(CAsyncJob *j)
  2785. {
  2786. j->Release();
  2787. }
  2788. void signal()
  2789. {
  2790. parent.signal();
  2791. }
  2792. void start()
  2793. {
  2794. parent.wait();
  2795. thread->start();
  2796. }
  2797. void join()
  2798. {
  2799. thread->join();
  2800. }
  2801. static unsigned getHash(const char *key)
  2802. {
  2803. return hashc((const byte *)key,strlen(key),~0U);
  2804. }
  2805. static CAsyncJob* create(const char *key) { assertex(!"CAsyncJob::create not implemented"); return NULL; }
  2806. unsigned hash;
  2807. bool eq(const char *key)
  2808. {
  2809. return stricmp(key,uuid.get())==0;
  2810. }
  2811. virtual int run()=0;
  2812. virtual void setException(IException *e)=0;
  2813. virtual void setDone()=0;
  2814. };
  2815. class CAsyncCopySection: public CAsyncJob
  2816. {
  2817. Owned<IFile> src;
  2818. RemoteFilename dst;
  2819. offset_t toOfs;
  2820. offset_t fromOfs;
  2821. offset_t size;
  2822. CFPmode mode; // not yet supported
  2823. CriticalSection sect;
  2824. offset_t done;
  2825. offset_t total;
  2826. Semaphore finished;
  2827. AsyncCommandStatus status;
  2828. Owned<IException> exc;
  2829. public:
  2830. CAsyncCopySection(CAsyncCommandManager &parent, const char *_uuid, const char *fromFile, const char *toFile, offset_t _toOfs, offset_t _fromOfs, offset_t _size)
  2831. : CAsyncJob(parent, _uuid)
  2832. {
  2833. status = ACScontinue;
  2834. src.setown(createIFile(fromFile));
  2835. dst.setRemotePath(toFile);
  2836. toOfs = _toOfs;
  2837. fromOfs = _fromOfs;
  2838. size = _size;
  2839. mode = CFPcontinue;
  2840. done = 0;
  2841. total = (offset_t)-1;
  2842. }
  2843. AsyncCommandStatus poll(offset_t &_done, offset_t &_total,unsigned timeout)
  2844. {
  2845. if (timeout&&finished.wait(timeout))
  2846. finished.signal(); // may need to call again
  2847. CriticalBlock block(sect);
  2848. if (exc)
  2849. throw exc.getClear();
  2850. _done = done;
  2851. _total = total;
  2852. return status;
  2853. }
  2854. int run()
  2855. {
  2856. class cProgress: implements ICopyFileProgress
  2857. {
  2858. CriticalSection &sect;
  2859. CFPmode &mode;
  2860. offset_t &done;
  2861. offset_t &total;
  2862. public:
  2863. cProgress(CriticalSection &_sect,offset_t &_done,offset_t &_total,CFPmode &_mode)
  2864. : sect(_sect), mode(_mode), done(_done), total(_total)
  2865. {
  2866. }
  2867. CFPmode onProgress(offset_t sizeDone, offset_t totalSize)
  2868. {
  2869. CriticalBlock block(sect);
  2870. done = sizeDone;
  2871. total = totalSize;
  2872. return mode;
  2873. }
  2874. } progress(sect,total,done,mode);
  2875. src->copySection(dst,toOfs, fromOfs, size, &progress); // exceptions will be handled by base class
  2876. return 0;
  2877. }
  2878. void setException(IException *e)
  2879. {
  2880. EXCLOG(e,"CAsyncCommandManager::CAsyncJob");
  2881. CriticalBlock block(sect);
  2882. if (exc.get())
  2883. e->Release();
  2884. else
  2885. exc.setown(e);
  2886. status = ACSerror;
  2887. }
  2888. void setDone()
  2889. {
  2890. CriticalBlock block(sect);
  2891. finished.signal();
  2892. status = ACSdone;
  2893. }
  2894. };
  2895. CMinHashTable<CAsyncJob> jobtable;
  2896. CriticalSection sect;
  2897. Semaphore threadsem;
  2898. unsigned limit;
  2899. public:
  2900. CAsyncCommandManager(unsigned _limit) : limit(_limit)
  2901. {
  2902. if (limit) // 0 == unbound
  2903. threadsem.signal(limit); // max number of async jobs
  2904. }
  2905. void join()
  2906. {
  2907. CriticalBlock block(sect);
  2908. unsigned i;
  2909. CAsyncJob *j=jobtable.first(i);
  2910. while (j) {
  2911. j->join();
  2912. j=jobtable.next(i);
  2913. }
  2914. }
  2915. void signal()
  2916. {
  2917. if (limit)
  2918. threadsem.signal();
  2919. }
  2920. void wait()
  2921. {
  2922. if (limit)
  2923. threadsem.wait();
  2924. }
  2925. AsyncCommandStatus copySection(const char *uuid, const char *fromFile, const char *toFile, offset_t toOfs, offset_t fromOfs, offset_t size, offset_t &done, offset_t &total, unsigned timeout)
  2926. {
  2927. // return 0 if continuing, 1 if done
  2928. CAsyncCopySection * job;
  2929. Linked<CAsyncJob> cjob;
  2930. {
  2931. CriticalBlock block(sect);
  2932. cjob.set(jobtable.find(uuid,false));
  2933. if (cjob) {
  2934. job = QUERYINTERFACE(cjob.get(),CAsyncCopySection);
  2935. if (!job) {
  2936. throw MakeStringException(-1,"Async job ID mismatch");
  2937. }
  2938. }
  2939. else {
  2940. job = new CAsyncCopySection(*this, uuid, fromFile, toFile, toOfs, fromOfs, size);
  2941. cjob.setown(job);
  2942. jobtable.add(cjob.getLink());
  2943. cjob->start();
  2944. }
  2945. }
  2946. AsyncCommandStatus ret = ACSerror;
  2947. Owned<IException> rete;
  2948. try {
  2949. ret = job->poll(done,total,timeout);
  2950. }
  2951. catch (IException * e) {
  2952. rete.setown(e);
  2953. }
  2954. if ((ret!=ACScontinue)||rete.get()) {
  2955. job->join();
  2956. CriticalBlock block(sect);
  2957. jobtable.remove(job);
  2958. if (rete.get())
  2959. throw rete.getClear();
  2960. }
  2961. return ret;
  2962. }
  2963. };
  2964. //====================================================================================================
  2965. inline void appendErr(MemoryBuffer &reply, unsigned e)
  2966. {
  2967. reply.append(e).append(getRFSERRText(e));
  2968. }
  2969. inline void appendErr2(MemoryBuffer &reply, unsigned e, unsigned v)
  2970. {
  2971. StringBuffer msg;
  2972. msg.append(getRFSERRText(e)).append(':').append(v);
  2973. reply.append(e).append(msg.str());
  2974. }
  2975. inline void appendErr3(MemoryBuffer &reply, unsigned e, int code, const char *errMsg)
  2976. {
  2977. StringBuffer msg;
  2978. msg.appendf("ERROR: %s(%d) '%s'", getRFSERRText(e), code, errMsg?errMsg:"");
  2979. reply.append(e);
  2980. reply.append(msg.str());
  2981. }
  2982. inline void appendCmdErr(MemoryBuffer &reply, RemoteFileCommandType e, int code, const char *errMsg)
  2983. {
  2984. StringBuffer msg;
  2985. msg.appendf("ERROR: %s(%d) '%s'", getRFCText(e), code, errMsg?errMsg:"");
  2986. // RFCOpenIO needs remapping to non-zero for client to know its an error
  2987. // perhaps we should use code here instead of e ?
  2988. unsigned err = e;
  2989. if (e == RFCopenIO)
  2990. err = RFSERR_OpenFailed;
  2991. reply.append(err);
  2992. reply.append(msg.str());
  2993. }
  2994. #define MAPCOMMAND(c,p) case c: { ret = this->p(msg, reply) ; break; }
  2995. #define MAPCOMMANDCLIENT(c,p,client) case c: { ret = this->p(msg, reply, client); break; }
  2996. #define MAPCOMMANDCLIENTTESTSOCKET(c,p,client) case c: { ret = this->p(msg, reply, client); testSocketFlag = true; break; }
  2997. #define MAPCOMMANDCLIENTTHROTTLE(c,p,client,throttler) case c: { ret = this->p(msg, reply, client, throttler); break; }
  2998. #define MAPCOMMANDSTATS(c,p,stats) case c: { ret = this->p(msg, reply, stats); break; }
  2999. #define MAPCOMMANDCLIENTSTATS(c,p,client,stats) case c: { ret = this->p(msg, reply, client, stats); break; }
  3000. static unsigned ClientCount = 0;
  3001. static unsigned MaxClientCount = 0;
  3002. static CriticalSection ClientCountSect;
  3003. #define DEFAULT_THROTTLOG_LOG_INTERVAL_SECS 60 // log total throttled delay period
  3004. class CClientStats : public CInterface
  3005. {
  3006. public:
  3007. CClientStats(const char *_client) : client(_client), count(0), bRead(0), bWritten(0) { }
  3008. const char *queryFindString() const { return client; }
  3009. inline void addRead(unsigned __int64 len)
  3010. {
  3011. bRead += len;
  3012. }
  3013. inline void addWrite(unsigned __int64 len)
  3014. {
  3015. bWritten += len;
  3016. }
  3017. void getStatus(StringBuffer & info) const
  3018. {
  3019. info.appendf("Client %s - %" I64F "d requests handled, bytes read = %" I64F "d, bytes written = % " I64F "d",
  3020. client.get(), count, bRead.load(), bWritten.load()).newline();
  3021. }
  3022. StringAttr client;
  3023. unsigned __int64 count;
  3024. std::atomic<unsigned __int64> bRead;
  3025. std::atomic<unsigned __int64> bWritten;
  3026. };
  3027. class CClientStatsTable : public OwningStringSuperHashTableOf<CClientStats>
  3028. {
  3029. typedef OwningStringSuperHashTableOf<CClientStats> PARENT;
  3030. CriticalSection crit;
  3031. unsigned cmdStats[RFCmax];
  3032. static int compareElement(void* const *ll, void* const *rr)
  3033. {
  3034. const CClientStats *l = (const CClientStats *) *ll;
  3035. const CClientStats *r = (const CClientStats *) *rr;
  3036. if (l->count == r->count)
  3037. return 0;
  3038. else if (l->count<r->count)
  3039. return 1;
  3040. else
  3041. return -1;
  3042. }
  3043. public:
  3044. CClientStatsTable()
  3045. {
  3046. memset(&cmdStats[0], 0, sizeof(cmdStats));
  3047. }
  3048. ~CClientStatsTable()
  3049. {
  3050. _releaseAll();
  3051. }
  3052. CClientStats *getClientReference(RemoteFileCommandType cmd, const char *client)
  3053. {
  3054. CriticalBlock b(crit);
  3055. CClientStats *stats = PARENT::find(client);
  3056. if (!stats)
  3057. {
  3058. stats = new CClientStats(client);
  3059. PARENT::replace(*stats);
  3060. }
  3061. if (cmd<RFCmax) // i.e. ignore duff command (which will be traced), but still record client connected
  3062. cmdStats[cmd]++;
  3063. ++stats->count;
  3064. return LINK(stats);
  3065. }
  3066. StringBuffer &getInfo(StringBuffer &info, unsigned level=1)
  3067. {
  3068. CriticalBlock b(crit);
  3069. unsigned __int64 totalCmds = 0;
  3070. for (unsigned c=0; c<RFCmax; c++)
  3071. totalCmds += cmdStats[c];
  3072. unsigned totalClients = PARENT::ordinality();
  3073. info.appendf("Commands processed = %" I64F "u, unique clients = %u", totalCmds, totalClients);
  3074. if (totalCmds)
  3075. {
  3076. info.append("Command stats:").newline();
  3077. for (unsigned c=0; c<RFCmax; c++)
  3078. {
  3079. unsigned __int64 count = cmdStats[c];
  3080. if (count)
  3081. info.append(getRFCText(c)).append(": ").append(count).newline();
  3082. }
  3083. }
  3084. if (totalClients)
  3085. {
  3086. SuperHashIteratorOf<CClientStats> iter(*this);
  3087. PointerArrayOf<CClientStats> elements;
  3088. ForEach(iter)
  3089. {
  3090. CClientStats &elem = iter.query();
  3091. elements.append(&elem);
  3092. }
  3093. elements.sort(&compareElement);
  3094. if (level < 10)
  3095. {
  3096. // list up to 10 clients ordered by # of commands processed
  3097. unsigned max=elements.ordinality();
  3098. if (max>10)
  3099. max = 10; // cap
  3100. info.append("Top 10 clients:").newline();
  3101. for (unsigned e=0; e<max; e++)
  3102. {
  3103. const CClientStats &element = *elements.item(e);
  3104. element.getStatus(info);
  3105. }
  3106. }
  3107. else // list all
  3108. {
  3109. info.append("All clients:").newline();
  3110. ForEachItemIn(e, elements)
  3111. {
  3112. const CClientStats &element = *elements.item(e);
  3113. element.getStatus(info);
  3114. }
  3115. }
  3116. }
  3117. return info;
  3118. }
  3119. void reset()
  3120. {
  3121. CriticalBlock b(crit);
  3122. memset(&cmdStats[0], 0, sizeof(cmdStats));
  3123. kill();
  3124. }
  3125. };
  3126. interface IRemoteActivity : extends IInterface
  3127. {
  3128. virtual const void *nextRow(size32_t &sz) = 0;
  3129. virtual unsigned __int64 queryProcessed() const = 0;
  3130. virtual IOutputMetaData *queryOutputMeta() const = 0;
  3131. virtual StringBuffer &getInfoStr(StringBuffer &out) const = 0;
  3132. virtual void serializeCursor(MemoryBuffer &tgt) const = 0;
  3133. virtual void restoreCursor(MemoryBuffer &src) = 0;
  3134. };
  3135. enum OpenFileFlag { of_null=0x0, of_key=0x01 };
  3136. struct OpenFileInfo
  3137. {
  3138. OpenFileInfo() { }
  3139. OpenFileInfo(int _handle, IFileIO *_fileIO, StringAttrItem *_filename) : handle(_handle), fileIO(_fileIO), filename(_filename) { }
  3140. OpenFileInfo(int _handle, IRemoteActivity *_activity, StringAttrItem *_filename) : handle(_handle), activity(_activity), filename(_filename) { }
  3141. Linked<IFileIO> fileIO;
  3142. Linked<IRemoteActivity> activity;
  3143. Linked<StringAttrItem> filename; // for debug
  3144. int handle = 0;
  3145. unsigned flags = 0;
  3146. };
  3147. static IOutputMetaData *getTypeInfoOutputMetaData(IPropertyTree &actNode, const char *typePropName)
  3148. {
  3149. IPropertyTree *inputJson = actNode.queryPropTree(typePropName);
  3150. if (inputJson)
  3151. return createTypeInfoOutputMetaData(*inputJson, nullptr);
  3152. else
  3153. {
  3154. StringBuffer binTypePropName(typePropName);
  3155. MemoryBuffer mb;
  3156. actNode.getPropBin(binTypePropName.append("Bin").str(), mb);
  3157. bool grouped = actNode.getPropBool(binTypePropName.append("_grouped").str(), false);
  3158. return createTypeInfoOutputMetaData(mb, grouped, nullptr);
  3159. }
  3160. }
  3161. class CRemoteDiskReadActivity : public CSimpleInterfaceOf<IRemoteActivity>
  3162. {
  3163. StringAttr fileName;
  3164. Linked<IHThorDiskReadArg> helper;
  3165. MemoryBuffer resultBuffer;
  3166. MemoryBufferBuilder *outBuilder = nullptr;
  3167. CThorContiguousRowBuffer prefetchBuffer;
  3168. IArrayOf<IKeySegmentMonitor> segMonitors;
  3169. Owned<ISourceRowPrefetcher> prefetcher;
  3170. Owned<ISerialStream> inputStream;
  3171. Owned<IFileIO> iFileIO;
  3172. Linked<IOutputMetaData> outMeta;
  3173. unsigned __int64 chooseN = 0;
  3174. unsigned __int64 limit = 0;
  3175. unsigned __int64 processed = 0;
  3176. unsigned __int64 startPos = 0;
  3177. bool opened = false;
  3178. bool eofSeen = false;
  3179. bool cursorDirty = false;
  3180. bool canMatchAny = false;
  3181. bool needTransform = true;
  3182. void checkOpen()
  3183. {
  3184. if (opened)
  3185. {
  3186. if (!cursorDirty)
  3187. return;
  3188. if (prefetchBuffer.tell() != startPos)
  3189. {
  3190. inputStream->reset(startPos);
  3191. prefetchBuffer.clearStream();
  3192. prefetchBuffer.setStream(inputStream);
  3193. eofSeen = !canMatchAny;
  3194. }
  3195. cursorDirty = false;
  3196. return;
  3197. }
  3198. if (!canMatchAny)
  3199. eofSeen = true;
  3200. else
  3201. {
  3202. const char *fileName = helper->getFileName();
  3203. OwnedIFile iFile = createIFile(fileName);
  3204. #if 0
  3205. bool compressed = false; // isCompressedFile(iFileIO); // Should be passed with JSON
  3206. StringBuffer encryptionkey;
  3207. if (compressed)
  3208. {
  3209. Owned<IExpander> eexp;
  3210. if (encryptionkey.length()!=0)
  3211. eexp.setown(createAESExpander256((size32_t)encryptionkey.length(),encryptionkey.bufferBase()));
  3212. iFileIO.setown(createCompressedFileReader(iFile,eexp));
  3213. if(!iFileIO && !blockcompressed) //fall back to old decompression, unless dfs marked as new
  3214. {
  3215. iFileIO.setown(iFile->open(IFOread));
  3216. if(iFileIO)
  3217. rowcompressed = true;
  3218. }
  3219. }
  3220. else
  3221. #endif
  3222. iFileIO.setown(iFile->open(IFOread));
  3223. if (!iFileIO)
  3224. throw MakeStringException(0, "Failed to open: '%s'", fileName);
  3225. inputStream.setown(createFileSerialStream(iFileIO, startPos));
  3226. prefetchBuffer.setStream(inputStream);
  3227. prefetcher.setown(helper->queryDiskRecordSize()->createDiskPrefetcher());
  3228. outBuilder = new MemoryBufferBuilder(resultBuffer, helper->queryOutputMeta()->getMinRecordSize());
  3229. chooseN = helper->getChooseNLimit();
  3230. limit = helper->getRowLimit();
  3231. }
  3232. opened = true;
  3233. }
  3234. void close()
  3235. {
  3236. iFileIO.clear();
  3237. opened = false;
  3238. }
  3239. bool segMonitorsMatch(const void *row) { return true; }
  3240. public:
  3241. CRemoteDiskReadActivity(IHThorDiskReadArg &_helper)
  3242. : helper(&_helper), prefetchBuffer(nullptr)
  3243. {
  3244. outMeta.set(helper->queryOutputMeta());
  3245. canMatchAny = helper->canMatchAny();
  3246. }
  3247. ~CRemoteDiskReadActivity()
  3248. {
  3249. if (outBuilder)
  3250. delete outBuilder;
  3251. }
  3252. virtual const void *nextRow(size32_t &retSz) override
  3253. {
  3254. checkOpen();
  3255. if (needTransform)
  3256. {
  3257. while (!eofSeen && ((chooseN == 0) || (processed < chooseN)))
  3258. {
  3259. while (!prefetchBuffer.eos())
  3260. {
  3261. prefetcher->readAhead(prefetchBuffer);
  3262. const byte * next = prefetchBuffer.queryRow();
  3263. size32_t rowSz; // use local var instead of reference param for efficiency
  3264. if (segMonitorsMatch(next))
  3265. rowSz = helper->transform(*outBuilder, next);
  3266. else
  3267. rowSz = 0;
  3268. prefetchBuffer.finishedRow();
  3269. if (rowSz)
  3270. {
  3271. if (processed >=limit)
  3272. {
  3273. resultBuffer.clear();
  3274. helper->onLimitExceeded();
  3275. return nullptr;
  3276. }
  3277. retSz = rowSz;
  3278. processed++;
  3279. return resultBuffer.toByteArray();
  3280. }
  3281. }
  3282. eofSeen = true;
  3283. }
  3284. }
  3285. close();
  3286. retSz = 0;
  3287. return nullptr;
  3288. }
  3289. // IRemoteActivity impl.
  3290. virtual void serializeCursor(MemoryBuffer &tgt) const override
  3291. {
  3292. tgt.append(prefetchBuffer.tell());
  3293. tgt.append(processed);
  3294. }
  3295. virtual void restoreCursor(MemoryBuffer &src) override
  3296. {
  3297. cursorDirty = true;
  3298. src.read(startPos);
  3299. src.read(processed);
  3300. }
  3301. virtual unsigned __int64 queryProcessed() const override
  3302. {
  3303. return processed;
  3304. }
  3305. virtual IOutputMetaData *queryOutputMeta() const override
  3306. {
  3307. return outMeta;
  3308. }
  3309. virtual StringBuffer &getInfoStr(StringBuffer &out) const override
  3310. {
  3311. return out.appendf("diskread[%s]", helper->getFileName());
  3312. }
  3313. };
  3314. IRemoteActivity *createRemoteDiskRead(IPropertyTree &actNode)
  3315. {
  3316. const char *fileName = actNode.queryProp("fileName");
  3317. unsigned __int64 chooseN = actNode.getPropInt64("choosen", defaultFileStreamChooseN);
  3318. unsigned __int64 skipN = actNode.getPropInt64("skipN", defaultFileStreamSkipN);
  3319. unsigned __int64 rowLimit = actNode.getPropInt64("rowLimit", defaultFileStreamRowLimit);
  3320. Owned<IOutputMetaData> inMeta = getTypeInfoOutputMetaData(actNode, "input");
  3321. Owned<IOutputMetaData> outMeta = getTypeInfoOutputMetaData(actNode, "output");
  3322. Owned<IHThorDiskReadArg> helper = createDiskReadArg(fileName, inMeta.getClear(), outMeta.getClear(), chooseN, skipN, rowLimit);
  3323. return new CRemoteDiskReadActivity(*helper);
  3324. }
  3325. IRemoteActivity *createRemoteActivity(IPropertyTree &actNode)
  3326. {
  3327. const char *kindStr = actNode.queryProp("kind");
  3328. ThorActivityKind kind = TAKnone;
  3329. if (strieq("diskread", kindStr))
  3330. kind = TAKdiskread;
  3331. Owned<IRemoteActivity> activity;
  3332. switch (kind)
  3333. {
  3334. case TAKdiskread:
  3335. {
  3336. activity.setown(createRemoteDiskRead(actNode));
  3337. break;
  3338. }
  3339. default:
  3340. throwUnexpected(); // for now
  3341. }
  3342. return activity.getClear();
  3343. }
  3344. IRemoteActivity *createOutputActivity(IPropertyTree &requestTree)
  3345. {
  3346. IPropertyTree *actNode = requestTree.queryPropTree("node");
  3347. assertex(actNode);
  3348. return createRemoteActivity(*actNode);
  3349. }
  3350. #define MAX_KEYDATA_SZ 0x10000
  3351. class CRemoteFileServer : implements IRemoteFileServer, public CInterface
  3352. {
  3353. class CThrottler;
  3354. class CRemoteClientHandler : implements ISocketSelectNotify, public CInterface
  3355. {
  3356. public:
  3357. CRemoteFileServer *parent;
  3358. Owned<ISocket> socket;
  3359. StringAttr peerName;
  3360. Owned<IAuthenticatedUser> user;
  3361. MemoryBuffer msg;
  3362. bool selecthandled;
  3363. size32_t left;
  3364. StructArrayOf<OpenFileInfo> openFiles;
  3365. Owned<IDirectoryIterator> opendir;
  3366. unsigned lasttick, lastInactiveTick;
  3367. atomic_t &globallasttick;
  3368. unsigned previdx; // for debug
  3369. IMPLEMENT_IINTERFACE;
  3370. CRemoteClientHandler(CRemoteFileServer *_parent,ISocket *_socket,IAuthenticatedUser *_user,atomic_t &_globallasttick)
  3371. : socket(_socket), user(_user), globallasttick(_globallasttick)
  3372. {
  3373. previdx = (unsigned)-1;
  3374. StringBuffer peerBuf;
  3375. char name[256];
  3376. name[0] = 0;
  3377. int port = socket->peer_name(name,sizeof(name)-1);
  3378. if (port>=0)
  3379. {
  3380. peerBuf.append(name);
  3381. if (port)
  3382. peerBuf.append(':').append(port);
  3383. peerName.set(peerBuf);
  3384. }
  3385. else
  3386. {
  3387. /* There's a possibility the socket closed before got here, in which case, peer name is unavailable
  3388. * May potentially be unavailable for other reasons also.
  3389. * Must be set, as used in client stats HT.
  3390. * If socket closed, the handler will start up but notice closed and quit
  3391. */
  3392. peerName.set("UNKNOWN PEER NAME");
  3393. }
  3394. {
  3395. CriticalBlock block(ClientCountSect);
  3396. if (++ClientCount>MaxClientCount)
  3397. MaxClientCount = ClientCount;
  3398. if (TF_TRACE_CLIENT_CONN)
  3399. {
  3400. StringBuffer s;
  3401. s.appendf("Connecting(%p) [%d,%d] to ",this,ClientCount,MaxClientCount);
  3402. s.append(peerName);
  3403. PROGLOG("%s", s.str());
  3404. }
  3405. }
  3406. parent = _parent;
  3407. left = 0;
  3408. msg.setEndian(__BIG_ENDIAN);
  3409. selecthandled = false;
  3410. touch();
  3411. }
  3412. ~CRemoteClientHandler()
  3413. {
  3414. {
  3415. CriticalBlock block(ClientCountSect);
  3416. ClientCount--;
  3417. if (TF_TRACE_CLIENT_CONN) {
  3418. PROGLOG("Disconnecting(%p) [%d,%d] ",this,ClientCount,MaxClientCount);
  3419. }
  3420. }
  3421. ISocket *sock = socket.getClear();
  3422. try {
  3423. sock->Release();
  3424. }
  3425. catch (IException *e) {
  3426. EXCLOG(e,"~CRemoteClientHandler");
  3427. e->Release();
  3428. }
  3429. }
  3430. bool notifySelected(ISocket *sock,unsigned selected)
  3431. {
  3432. if (TF_TRACE_FULL)
  3433. PROGLOG("notifySelected(%p)",this);
  3434. if (sock!=socket)
  3435. WARNLOG("notifySelected - invalid socket passed");
  3436. size32_t avail = (size32_t)socket->avail_read();
  3437. if (avail)
  3438. touch();
  3439. if (left==0)
  3440. {
  3441. try
  3442. {
  3443. left = avail?receiveBufferSize(socket):0;
  3444. }
  3445. catch (IException *e)
  3446. {
  3447. EXCLOG(e,"notifySelected(1)");
  3448. e->Release();
  3449. left = 0;
  3450. }
  3451. if (left)
  3452. {
  3453. avail = (size32_t)socket->avail_read();
  3454. try
  3455. {
  3456. msg.ensureCapacity(left);
  3457. }
  3458. catch (IException *e)
  3459. {
  3460. EXCLOG(e,"notifySelected(2)");
  3461. e->Release();
  3462. left = 0;
  3463. // if too big then corrupted packet so read avail to try and consume
  3464. char fbuf[1024];
  3465. while (avail)
  3466. {
  3467. size32_t rd = avail>sizeof(fbuf)?sizeof(fbuf):avail;
  3468. try
  3469. {
  3470. socket->read(fbuf, rd); // don't need timeout here
  3471. avail -= rd;
  3472. }
  3473. catch (IException *e)
  3474. {
  3475. EXCLOG(e,"notifySelected(2) flush");
  3476. e->Release();
  3477. break;
  3478. }
  3479. }
  3480. avail = 0;
  3481. left = 0;
  3482. }
  3483. }
  3484. }
  3485. size32_t toread = left>avail?avail:left;
  3486. if (toread)
  3487. {
  3488. try
  3489. {
  3490. socket->read(msg.reserve(toread), toread); // don't need timeout here
  3491. }
  3492. catch (IException *e)
  3493. {
  3494. EXCLOG(e,"notifySelected(3)");
  3495. e->Release();
  3496. toread = left;
  3497. msg.clear();
  3498. }
  3499. }
  3500. if (TF_TRACE_FULL)
  3501. PROGLOG("notifySelected %d,%d",toread,left);
  3502. if ((left!=0)&&(avail==0))
  3503. {
  3504. WARNLOG("notifySelected: Closing mid packet, %d remaining", left);
  3505. toread = left;
  3506. msg.clear();
  3507. }
  3508. left -= toread;
  3509. if (left==0)
  3510. {
  3511. // DEBUG
  3512. parent->notify(this, msg); // consumes msg
  3513. }
  3514. return false;
  3515. }
  3516. void logPrevHandle()
  3517. {
  3518. if (previdx<openFiles.ordinality())
  3519. {
  3520. const OpenFileInfo &fileInfo = openFiles.item(previdx);
  3521. PROGLOG("Previous handle(%d): %s", fileInfo.handle, fileInfo.filename->text.get());
  3522. }
  3523. }
  3524. bool throttleCommand(MemoryBuffer &msg)
  3525. {
  3526. RemoteFileCommandType cmd = RFCunknown;
  3527. Owned<IException> e;
  3528. try
  3529. {
  3530. msg.read(cmd);
  3531. parent->throttleCommand(cmd, msg, this);
  3532. return true;
  3533. }
  3534. catch (IException *_e)
  3535. {
  3536. e.setown(_e);
  3537. }
  3538. /* processCommand() will handle most exception and replies,
  3539. * but if throttleCommand fails before it gets that far, this will handle
  3540. */
  3541. MemoryBuffer reply;
  3542. initSendBuffer(reply);
  3543. StringBuffer s;
  3544. e->errorMessage(s);
  3545. appendCmdErr(reply, cmd, e->errorCode(), s.str());
  3546. parent->appendError(cmd, this, cmd, reply);
  3547. sendBuffer(socket, reply);
  3548. return false;
  3549. }
  3550. void processCommand(RemoteFileCommandType cmd, MemoryBuffer &msg, CThrottler *throttler)
  3551. {
  3552. MemoryBuffer reply;
  3553. bool testSocketFlag = parent->processCommand(cmd, msg, initSendBuffer(reply), this, throttler);
  3554. sendBuffer(socket, reply, testSocketFlag);
  3555. }
  3556. bool immediateCommand() // returns false if socket closed or failure
  3557. {
  3558. MemoryBuffer msg;
  3559. msg.setEndian(__BIG_ENDIAN);
  3560. touch();
  3561. size32_t avail = (size32_t)socket->avail_read();
  3562. if (avail==0)
  3563. return false;
  3564. receiveBuffer(socket, msg, 5); // shouldn't timeout as data is available
  3565. touch();
  3566. if (msg.length()==0)
  3567. return false;
  3568. return throttleCommand(msg);
  3569. }
  3570. void process(MemoryBuffer &msg)
  3571. {
  3572. if (selecthandled)
  3573. throttleCommand(msg);
  3574. else
  3575. {
  3576. // msg only used/filled if process() has been triggered by notify()
  3577. while (parent->threadRunningCount()<=parent->targetActiveThreads) // if too many threads add to select handler
  3578. {
  3579. int w;
  3580. try
  3581. {
  3582. w = socket->wait_read(1000);
  3583. }
  3584. catch (IException *e)
  3585. {
  3586. EXCLOG(e, "CRemoteClientHandler::main wait_read error");
  3587. e->Release();
  3588. parent->onCloseSocket(this,1);
  3589. return;
  3590. }
  3591. if (w==0)
  3592. break;
  3593. if ((w<0)||!immediateCommand())
  3594. {
  3595. if (w<0)
  3596. WARNLOG("CRemoteClientHandler::main wait_read error");
  3597. parent->onCloseSocket(this,1);
  3598. return;
  3599. }
  3600. }
  3601. /* This is a bit confusing..
  3602. * The addClient below, adds this request to a selecthandler handled by another thread
  3603. * and passes ownership of 'this' (CRemoteClientHandler)
  3604. *
  3605. * When notified, the selecthandler will launch a new pool thread to handle the request
  3606. * If the pool thread limit is hit, the selecthandler will be blocked [ see comment in CRemoteFileServer::notify() ]
  3607. *
  3608. * Either way, a thread pool slot is occupied when processing a request.
  3609. * Blocked threads, will be blocked for up to 1 minute (as defined by createThreadPool call)
  3610. * IOW, if there are lots of incoming clients that can't be serviced by the CThrottler limit,
  3611. * a large number of pool threads will build up after a while.
  3612. *
  3613. * The CThrottler mechanism, imposes a further hard limit on how many concurrent request threads can be active.
  3614. * If the thread pool had an absolute limit (instead of just introducing a delay), then I don't see the point
  3615. * in this additional layer of throttling..
  3616. */
  3617. selecthandled = true;
  3618. parent->addClient(this); // add to select handler
  3619. // NB: this (CRemoteClientHandler) is now linked by the selecthandler and owned by the 'clients' list
  3620. }
  3621. }
  3622. bool timedOut()
  3623. {
  3624. return (msTick()-lasttick)>CLIENT_TIMEOUT;
  3625. }
  3626. bool inactiveTimedOut()
  3627. {
  3628. unsigned ms = msTick();
  3629. if ((ms-lastInactiveTick)>CLIENT_INACTIVEWARNING_TIMEOUT)
  3630. {
  3631. lastInactiveTick = ms;
  3632. return true;
  3633. }
  3634. return false;
  3635. }
  3636. void touch()
  3637. {
  3638. lastInactiveTick = lasttick = msTick();
  3639. atomic_set(&globallasttick,lasttick);
  3640. }
  3641. const char *queryPeerName()
  3642. {
  3643. return peerName;
  3644. }
  3645. bool getInfo(StringBuffer &str)
  3646. {
  3647. str.append("client(");
  3648. const char *name = queryPeerName();
  3649. bool ok;
  3650. if (name)
  3651. {
  3652. ok = true;
  3653. str.append(name);
  3654. }
  3655. else
  3656. ok = false;
  3657. unsigned ms = msTick();
  3658. str.appendf("): last touch %d ms ago (%d, %d)",ms-lasttick,lasttick,ms);
  3659. ForEachItemIn(i, openFiles)
  3660. {
  3661. const OpenFileInfo &fileInfo = openFiles.item(i);
  3662. str.appendf("\n %d: ", fileInfo.handle);
  3663. str.append(fileInfo.filename->text.get());
  3664. }
  3665. return ok;
  3666. }
  3667. };
  3668. class CThrottleQueueItem : public CSimpleInterface
  3669. {
  3670. public:
  3671. RemoteFileCommandType cmd;
  3672. Linked<CRemoteClientHandler> client;
  3673. MemoryBuffer msg;
  3674. CCycleTimer timer;
  3675. CThrottleQueueItem(RemoteFileCommandType _cmd, MemoryBuffer &_msg, CRemoteClientHandler *_client) : cmd(_cmd), client(_client)
  3676. {
  3677. msg.swapWith(_msg);
  3678. }
  3679. };
  3680. class CThrottler
  3681. {
  3682. Semaphore sem;
  3683. CriticalSection crit, configureCrit;
  3684. StringAttr title;
  3685. unsigned limit, delayMs, cpuThreshold, queueLimit;
  3686. unsigned disabledLimit;
  3687. unsigned __int64 totalThrottleDelay;
  3688. CCycleTimer totalThrottleDelayTimer;
  3689. QueueOf<CThrottleQueueItem, false> queue;
  3690. unsigned statsIntervalSecs;
  3691. public:
  3692. CThrottler(const char *_title) : title(_title)
  3693. {
  3694. totalThrottleDelay = 0;
  3695. limit = 0;
  3696. delayMs = DEFAULT_STDCMD_THROTTLEDELAYMS;
  3697. cpuThreshold = DEFAULT_STDCMD_THROTTLECPULIMIT;
  3698. disabledLimit = 0;
  3699. queueLimit = DEFAULT_STDCMD_THROTTLEQUEUELIMIT;
  3700. statsIntervalSecs = DEFAULT_STDCMD_THROTTLECPULIMIT;
  3701. }
  3702. ~CThrottler()
  3703. {
  3704. for (;;)
  3705. {
  3706. Owned<CThrottleQueueItem> item = queue.dequeue();
  3707. if (!item)
  3708. break;
  3709. }
  3710. }
  3711. unsigned queryLimit() const { return limit; }
  3712. unsigned queryDelayMs() const { return delayMs; };;
  3713. unsigned queryCpuThreshold() const { return cpuThreshold; }
  3714. unsigned queryQueueLimit() const { return queueLimit; }
  3715. StringBuffer &getInfoSummary(StringBuffer &info)
  3716. {
  3717. info.appendf("Throttler(%s) - limit=%u, delayMs=%u, cpuThreshold=%u, queueLimit=%u", title.get(), limit, delayMs, cpuThreshold, queueLimit).newline();
  3718. unsigned elapsedSecs = totalThrottleDelayTimer.elapsedMs()/1000;
  3719. time_t simple;
  3720. time(&simple);
  3721. simple -= elapsedSecs;
  3722. CDateTime dt;
  3723. dt.set(simple);
  3724. StringBuffer dateStr;
  3725. dt.getTimeString(dateStr, true);
  3726. info.appendf("Throttler(%s): statistics since %s", title.get(), dateStr.str()).newline();
  3727. info.appendf("Total delay of %0.2f seconds", ((double)totalThrottleDelay)/1000).newline();
  3728. info.appendf("Requests currently queued: %u", queue.ordinality());
  3729. return info;
  3730. }
  3731. void getInfo(StringBuffer &info)
  3732. {
  3733. CriticalBlock b(crit);
  3734. getInfoSummary(info).newline();
  3735. }
  3736. void configure(unsigned _limit, unsigned _delayMs, unsigned _cpuThreshold, unsigned _queueLimit)
  3737. {
  3738. if (_limit > THROTTLE_MAX_LIMIT || _delayMs > THROTTLE_MAX_DELAYMS || _cpuThreshold > THROTTLE_MAX_CPUTHRESHOLD || _queueLimit > THROTTLE_MAX_QUEUELIMIT)
  3739. throw MakeStringException(0, "Throttler(%s), rejecting configure command: limit=%u (max permitted=%u), delayMs=%u (max permitted=%u), cpuThreshold=%u (max permitted=%u), queueLimit=%u (max permitted=%u)",
  3740. title.str(), _limit, THROTTLE_MAX_LIMIT, _delayMs, THROTTLE_MAX_DELAYMS, _cpuThreshold,
  3741. THROTTLE_MAX_CPUTHRESHOLD, _queueLimit, THROTTLE_MAX_QUEUELIMIT);
  3742. CriticalBlock b(configureCrit);
  3743. int delta = 0;
  3744. if (_limit)
  3745. {
  3746. if (disabledLimit) // if transitioning from disabled to some throttling
  3747. {
  3748. assertex(0 == limit);
  3749. delta = _limit - disabledLimit; // + or -
  3750. disabledLimit = 0;
  3751. }
  3752. else
  3753. delta = _limit - limit; // + or -
  3754. }
  3755. else if (0 == disabledLimit)
  3756. {
  3757. PROGLOG("Throttler(%s): disabled, previous limit: %u", title.get(), limit);
  3758. /* disabling - set limit immediately to let all new transaction through.
  3759. * NB: the semaphore signals are not consumed in this case, because transactions could be waiting on it.
  3760. * Instead the existing 'limit' is kept in 'disabledLimit', so that if/when throttling is
  3761. * re-enabled, it is used as a basis for increasing or consuming the semaphore signal count.
  3762. */
  3763. disabledLimit = limit;
  3764. limit = 0;
  3765. }
  3766. if (delta > 0)
  3767. {
  3768. PROGLOG("Throttler(%s): Increasing limit from %u to %u", title.get(), limit, _limit);
  3769. sem.signal(delta);
  3770. limit = _limit;
  3771. // NB: If throttling was off, this doesn't effect transactions in progress, i.e. will only throttle new transactions coming in.
  3772. }
  3773. else if (delta < 0)
  3774. {
  3775. PROGLOG("Throttler(%s): Reducing limit from %u to %u", title.get(), limit, _limit);
  3776. // NB: This is not expected to take long
  3777. CCycleTimer timer;
  3778. while (delta < 0)
  3779. {
  3780. if (sem.wait(1000))
  3781. ++delta;
  3782. else
  3783. PROGLOG("Throttler(%s): Waited %0.2f seconds so far for up to a maximum of %u (previous limit) transactions to complete, %u completed", title.get(), ((double)timer.elapsedMs())/1000, limit, -delta);
  3784. }
  3785. limit = _limit;
  3786. // NB: doesn't include transactions in progress, i.e. will only throttle new transactions coming in.
  3787. }
  3788. if (_delayMs != delayMs)
  3789. {
  3790. PROGLOG("Throttler(%s): New delayMs=%u, previous: %u", title.get(), _delayMs, delayMs);
  3791. delayMs = _delayMs;
  3792. }
  3793. if (_cpuThreshold != cpuThreshold)
  3794. {
  3795. PROGLOG("Throttler(%s): New cpuThreshold=%u, previous: %u", title.get(), _cpuThreshold, cpuThreshold);
  3796. cpuThreshold = _cpuThreshold;
  3797. }
  3798. if (((unsigned)-1) != _queueLimit && _queueLimit != queueLimit)
  3799. {
  3800. PROGLOG("Throttler(%s): New queueLimit=%u%s, previous: %u", title.get(), _queueLimit, 0==_queueLimit?"(disabled)":"", queueLimit);
  3801. queueLimit = _queueLimit;
  3802. }
  3803. }
  3804. void setStatsInterval(unsigned _statsIntervalSecs)
  3805. {
  3806. if (_statsIntervalSecs != statsIntervalSecs)
  3807. {
  3808. PROGLOG("Throttler(%s): New statsIntervalSecs=%u, previous: %u", title.get(), _statsIntervalSecs, statsIntervalSecs);
  3809. statsIntervalSecs = _statsIntervalSecs;
  3810. }
  3811. }
  3812. void take(RemoteFileCommandType cmd) // cmd for info. only
  3813. {
  3814. for (;;)
  3815. {
  3816. if (sem.wait(delayMs))
  3817. return;
  3818. PROGLOG("Throttler(%s): transaction delayed [cmd=%s]", title.get(), getRFCText(cmd));
  3819. }
  3820. }
  3821. void release()
  3822. {
  3823. sem.signal();
  3824. }
  3825. StringBuffer &getStats(StringBuffer &stats, bool reset)
  3826. {
  3827. CriticalBlock b(crit);
  3828. getInfoSummary(stats);
  3829. if (reset)
  3830. {
  3831. totalThrottleDelayTimer.reset();
  3832. totalThrottleDelay = 0;
  3833. }
  3834. return stats;
  3835. }
  3836. void addCommand(RemoteFileCommandType cmd, MemoryBuffer &msg, CRemoteClientHandler *client)
  3837. {
  3838. CCycleTimer timer;
  3839. Owned<IException> exception;
  3840. bool hadSem = true;
  3841. if (!sem.wait(delayMs))
  3842. {
  3843. CriticalBlock b(crit);
  3844. if (!sem.wait(0)) // check hasn't become available
  3845. {
  3846. unsigned cpu = getLatestCPUUsage();
  3847. if (getLatestCPUUsage()<cpuThreshold)
  3848. {
  3849. /* Allow to proceed, despite hitting throttle limit because CPU < threshold
  3850. * NB: The overall number of threads is still capped by the thread pool.
  3851. */
  3852. unsigned ms = timer.elapsedMs();
  3853. totalThrottleDelay += ms;
  3854. PROGLOG("Throttler(%s): transaction delayed [cmd=%s] for : %u milliseconds, proceeding as cpu(%u)<throttleCPULimit(%u)", title.get(), getRFCText(cmd), cpu, ms, cpuThreshold);
  3855. hadSem = false;
  3856. }
  3857. else
  3858. {
  3859. if (queueLimit && queue.ordinality()>=queueLimit)
  3860. throw MakeStringException(0, "Throttler(%s), the maxiumum number of items are queued (%u), rejecting new command[%s]", title.str(), queue.ordinality(), getRFCText(cmd));
  3861. queue.enqueue(new CThrottleQueueItem(cmd, msg, client)); // NB: takes over ownership of 'client' from running thread
  3862. PROGLOG("Throttler(%s): transaction delayed [cmd=%s], queuing (%u queueud), [client=%p, sock=%u]", title.get(), getRFCText(cmd), queue.ordinality(), client, client->socket->OShandle());
  3863. return;
  3864. }
  3865. }
  3866. }
  3867. /* Guarantee that sem is released.
  3868. * Should normally release on clean exit when queue is empty.
  3869. */
  3870. struct ReleaseSem
  3871. {
  3872. Semaphore *sem;
  3873. ReleaseSem(Semaphore *_sem) { sem = _sem; }
  3874. ~ReleaseSem() { if (sem) sem->signal(); }
  3875. } releaseSem(hadSem?&sem:NULL);
  3876. /* Whilst holding on this throttle slot (i.e. before signalling semaphore back), process
  3877. * queued items. NB: other threads that are finishing will do also.
  3878. * Queued items are processed 1st, then the current request, then anything that was queued when handling current request
  3879. * Throttle slot (semaphore) is only given back when no more to do.
  3880. */
  3881. Linked<CRemoteClientHandler> currentClient;
  3882. MemoryBuffer currentMsg;
  3883. unsigned ms;
  3884. for (;;)
  3885. {
  3886. RemoteFileCommandType currentCmd;
  3887. {
  3888. CriticalBlock b(crit);
  3889. Owned<CThrottleQueueItem> item = queue.dequeue();
  3890. if (item)
  3891. {
  3892. currentCmd = item->cmd;
  3893. currentClient.setown(item->client.getClear());
  3894. currentMsg.swapWith(item->msg);
  3895. ms = item->timer.elapsedMs();
  3896. }
  3897. else
  3898. {
  3899. if (NULL == client) // previously handled and queue empty
  3900. {
  3901. /* Commands are only queued if semaphore is exhaused (checked inside crit)
  3902. * so only signal the semaphore inside the crit, after checking if there are no queued items
  3903. */
  3904. if (hadSem)
  3905. {
  3906. releaseSem.sem = NULL;
  3907. sem.signal();
  3908. }
  3909. break;
  3910. }
  3911. currentCmd = cmd;
  3912. currentClient.set(client); // process current request after dealing with queue
  3913. currentMsg.swapWith(msg);
  3914. ms = timer.elapsedMs();
  3915. client = NULL;
  3916. }
  3917. }
  3918. if (ms >= 1000)
  3919. {
  3920. if (ms>delayMs)
  3921. PROGLOG("Throttler(%s): transaction delayed [cmd=%s] for : %u seconds", title.get(), getRFCText(currentCmd), ms/1000);
  3922. }
  3923. {
  3924. CriticalBlock b(crit);
  3925. totalThrottleDelay += ms;
  3926. }
  3927. try
  3928. {
  3929. currentClient->processCommand(currentCmd, currentMsg, this);
  3930. }
  3931. catch (IException *e)
  3932. {
  3933. EXCLOG(e, "addCommand: processCommand failed");
  3934. e->Release();
  3935. }
  3936. }
  3937. }
  3938. };
  3939. // temporarily release a throttler slot
  3940. class CThrottleReleaseBlock
  3941. {
  3942. CThrottler &throttler;
  3943. RemoteFileCommandType cmd;
  3944. public:
  3945. CThrottleReleaseBlock(CThrottler &_throttler, RemoteFileCommandType _cmd) : throttler(_throttler), cmd(_cmd)
  3946. {
  3947. throttler.release();
  3948. }
  3949. ~CThrottleReleaseBlock()
  3950. {
  3951. throttler.take(cmd);
  3952. }
  3953. };
  3954. int lasthandle;
  3955. CriticalSection sect;
  3956. Owned<ISocket> acceptsock;
  3957. Owned<ISocket> securesock;
  3958. Owned<ISocketSelectHandler> selecthandler;
  3959. Owned<IThreadPool> threads; // for commands
  3960. bool stopping;
  3961. unsigned clientcounttick;
  3962. unsigned closedclients;
  3963. CAsyncCommandManager asyncCommandManager;
  3964. CThrottler stdCmdThrottler, slowCmdThrottler;
  3965. CClientStatsTable clientStatsTable;
  3966. atomic_t globallasttick;
  3967. unsigned targetActiveThreads;
  3968. int getNextHandle()
  3969. {
  3970. // called in sect critical block
  3971. for (;;) {
  3972. if (lasthandle==INT_MAX)
  3973. lasthandle = 1;
  3974. else
  3975. lasthandle++;
  3976. unsigned idx1;
  3977. unsigned idx2;
  3978. if (!findHandle(lasthandle,idx1,idx2))
  3979. return lasthandle;
  3980. }
  3981. }
  3982. bool findHandle(int handle,unsigned &clientidx,unsigned &handleidx)
  3983. {
  3984. // called in sect critical block
  3985. clientidx = (unsigned)-1;
  3986. handleidx = (unsigned)-1;
  3987. ForEachItemIn(i,clients) {
  3988. CRemoteClientHandler &client = clients.item(i);
  3989. ForEachItemIn(j, client.openFiles)
  3990. {
  3991. if (client.openFiles.item(j).handle==handle)
  3992. {
  3993. handleidx = j;
  3994. clientidx = i;
  3995. return true;
  3996. }
  3997. }
  3998. }
  3999. return false;
  4000. }
  4001. unsigned readKeyData(IKeyManager *keyManager, unsigned maxRecs, MemoryBuffer &reply, bool &maxHit)
  4002. {
  4003. DelayedSizeMarker keyDataSzReturned(reply);
  4004. unsigned numRecs = 0;
  4005. maxHit = false;
  4006. unsigned pos = reply.length();
  4007. while (keyManager->lookup(true))
  4008. {
  4009. unsigned size = keyManager->queryRecordSize();
  4010. const byte *result = keyManager->queryKeyBuffer();
  4011. reply.append(size);
  4012. reply.append(size, result);
  4013. ++numRecs;
  4014. if (maxRecs && (0 == --maxRecs))
  4015. {
  4016. maxHit = true;
  4017. break;
  4018. }
  4019. if (reply.length()-pos >= MAX_KEYDATA_SZ)
  4020. {
  4021. maxHit = true;
  4022. break;
  4023. }
  4024. }
  4025. keyDataSzReturned.write();
  4026. return numRecs;
  4027. }
  4028. class cCommandProcessor: public CInterface, implements IPooledThread
  4029. {
  4030. Owned<CRemoteClientHandler> client;
  4031. MemoryBuffer msg;
  4032. public:
  4033. IMPLEMENT_IINTERFACE;
  4034. struct cCommandProcessorParams
  4035. {
  4036. cCommandProcessorParams() { msg.setEndian(__BIG_ENDIAN); }
  4037. CRemoteClientHandler *client;
  4038. MemoryBuffer msg;
  4039. };
  4040. virtual void init(void *_params) override
  4041. {
  4042. cCommandProcessorParams &params = *(cCommandProcessorParams *)_params;
  4043. client.setown(params.client);
  4044. msg.swapWith(params.msg);
  4045. }
  4046. virtual void threadmain() override
  4047. {
  4048. // idea is that initially we process commands inline then pass over to select handler
  4049. try
  4050. {
  4051. client->process(msg);
  4052. }
  4053. catch (IException *e)
  4054. {
  4055. // suppress some errors
  4056. EXCLOG(e,"cCommandProcessor::threadmain");
  4057. e->Release();
  4058. }
  4059. try
  4060. {
  4061. client.clear();
  4062. }
  4063. catch (IException *e)
  4064. {
  4065. // suppress some more errors clearing client
  4066. EXCLOG(e,"cCommandProcessor::threadmain(2)");
  4067. e->Release();
  4068. }
  4069. }
  4070. virtual bool stop() override
  4071. {
  4072. return true;
  4073. }
  4074. virtual bool canReuse() const override
  4075. {
  4076. return false; // want to free owned socket
  4077. }
  4078. };
  4079. IArrayOf<CRemoteClientHandler> clients;
  4080. class cImpersonateBlock
  4081. {
  4082. CRemoteClientHandler &client;
  4083. public:
  4084. cImpersonateBlock(CRemoteClientHandler &_client)
  4085. : client(_client)
  4086. {
  4087. if (client.user.get()) {
  4088. if (TF_TRACE)
  4089. PROGLOG("Impersonate user: %s",client.user->username());
  4090. client.user->impersonate();
  4091. }
  4092. }
  4093. ~cImpersonateBlock()
  4094. {
  4095. if (client.user.get()) {
  4096. if (TF_TRACE)
  4097. PROGLOG("Stop impersonating user: %s",client.user->username());
  4098. client.user->revert();
  4099. }
  4100. }
  4101. };
  4102. #define IMPERSONATE_USER(client) cImpersonateBlock ublock(client)
  4103. public:
  4104. IMPLEMENT_IINTERFACE
  4105. CRemoteFileServer(unsigned maxThreads, unsigned maxThreadsDelayMs, unsigned maxAsyncCopy)
  4106. : asyncCommandManager(maxAsyncCopy), stdCmdThrottler("stdCmdThrotlter"), slowCmdThrottler("slowCmdThrotlter")
  4107. {
  4108. lasthandle = 0;
  4109. selecthandler.setown(createSocketSelectHandler(NULL));
  4110. stdCmdThrottler.configure(DEFAULT_STDCMD_PARALLELREQUESTLIMIT, DEFAULT_STDCMD_THROTTLEDELAYMS, DEFAULT_STDCMD_THROTTLECPULIMIT, DEFAULT_STDCMD_THROTTLEQUEUELIMIT);
  4111. slowCmdThrottler.configure(DEFAULT_SLOWCMD_PARALLELREQUESTLIMIT, DEFAULT_SLOWCMD_THROTTLEDELAYMS, DEFAULT_SLOWCMD_THROTTLECPULIMIT, DEFAULT_SLOWCMD_THROTTLEQUEUELIMIT);
  4112. unsigned targetMinThreads=maxThreads*20/100; // 20%
  4113. if (0 == targetMinThreads) targetMinThreads = 1;
  4114. targetActiveThreads=maxThreads*80/100; // 80%
  4115. if (0 == targetActiveThreads) targetActiveThreads = 1;
  4116. class CCommandFactory : public CSimpleInterfaceOf<IThreadFactory>
  4117. {
  4118. CRemoteFileServer &parent;
  4119. public:
  4120. CCommandFactory(CRemoteFileServer &_parent) : parent(_parent) { }
  4121. virtual IPooledThread *createNew()
  4122. {
  4123. return parent.createCommandProcessor();
  4124. }
  4125. };
  4126. Owned<IThreadFactory> factory = new CCommandFactory(*this); // NB: pool links factory, so takes ownership
  4127. threads.setown(createThreadPool("CRemoteFileServerPool", factory, NULL, maxThreads, maxThreadsDelayMs,
  4128. #ifdef __64BIT__
  4129. 0, // Unlimited stack size
  4130. #else
  4131. 0x10000,
  4132. #endif
  4133. INFINITE,targetMinThreads));
  4134. threads->setStartDelayTracing(60); // trace amount delayed every minute.
  4135. PROGLOG("CRemoteFileServer: maxThreads = %u, maxThreadsDelayMs = %u, maxAsyncCopy = %u", maxThreads, maxThreadsDelayMs, maxAsyncCopy);
  4136. stopping = false;
  4137. clientcounttick = msTick();
  4138. closedclients = 0;
  4139. atomic_set(&globallasttick,msTick());
  4140. }
  4141. ~CRemoteFileServer()
  4142. {
  4143. #ifdef _DEBUG
  4144. PROGLOG("Exiting CRemoteFileServer");
  4145. #endif
  4146. asyncCommandManager.join();
  4147. clients.kill();
  4148. #ifdef _DEBUG
  4149. PROGLOG("Exited CRemoteFileServer");
  4150. #endif
  4151. }
  4152. bool lookupFileIOHandle(int handle, OpenFileInfo &fileInfo, unsigned newFlags=0)
  4153. {
  4154. if (handle<=0)
  4155. return false;
  4156. CriticalBlock block(sect);
  4157. unsigned clientidx;
  4158. unsigned handleidx;
  4159. if (!findHandle(handle,clientidx,handleidx))
  4160. return false;
  4161. CRemoteClientHandler &client = clients.item(clientidx);
  4162. OpenFileInfo &openFileInfo = client.openFiles.element(handleidx); // NB: links members
  4163. openFileInfo.flags |= newFlags;
  4164. fileInfo = openFileInfo;
  4165. client.previdx = handleidx;
  4166. return true;
  4167. }
  4168. //MORE: The file handles should timeout after a while, and accessing an old (invalid handle)
  4169. // should throw a different exception
  4170. bool checkFileIOHandle(int handle, IFileIO *&fileio, bool del=false)
  4171. {
  4172. fileio = NULL;
  4173. if (handle<=0)
  4174. return false;
  4175. CriticalBlock block(sect);
  4176. unsigned clientidx;
  4177. unsigned handleidx;
  4178. if (findHandle(handle,clientidx,handleidx))
  4179. {
  4180. CRemoteClientHandler &client = clients.item(clientidx);
  4181. const OpenFileInfo &fileInfo = client.openFiles.item(handleidx);
  4182. if (del)
  4183. {
  4184. if (fileInfo.flags & of_key)
  4185. clearKeyStoreCacheEntry(fileInfo.fileIO);
  4186. client.openFiles.remove(handleidx);
  4187. client.previdx = (unsigned)-1;
  4188. }
  4189. else
  4190. {
  4191. fileio = client.openFiles.item(handleidx).fileIO;
  4192. client.previdx = handleidx;
  4193. }
  4194. return true;
  4195. }
  4196. return false;
  4197. }
  4198. bool checkFileIOHandle(MemoryBuffer &reply, int handle, IFileIO *&fileio, bool del=false)
  4199. {
  4200. if (!checkFileIOHandle(handle, fileio, del))
  4201. {
  4202. appendErr(reply, RFSERR_InvalidFileIOHandle);
  4203. return false;
  4204. }
  4205. return true;
  4206. }
  4207. void onCloseSocket(CRemoteClientHandler *client, int which)
  4208. {
  4209. if (!client)
  4210. return;
  4211. CriticalBlock block(sect);
  4212. #ifdef _DEBUG
  4213. StringBuffer s(client->queryPeerName());
  4214. PROGLOG("onCloseSocket(%d) %s",which,s.str());
  4215. #endif
  4216. if (client->socket)
  4217. {
  4218. try
  4219. {
  4220. /* JCSMORE - shouldn't this really be dependent on whether selecthandled=true
  4221. * It has not been added to the selecthandler
  4222. * Harmless, but wasteful if so.
  4223. */
  4224. selecthandler->remove(client->socket);
  4225. }
  4226. catch (IException *e) {
  4227. EXCLOG(e,"CRemoteFileServer::onCloseSocket.1");
  4228. e->Release();
  4229. }
  4230. }
  4231. try {
  4232. clients.zap(*client);
  4233. }
  4234. catch (IException *e) {
  4235. EXCLOG(e,"CRemoteFileServer::onCloseSocket.2");
  4236. e->Release();
  4237. }
  4238. }
  4239. bool cmdOpenFileIO(MemoryBuffer & msg, MemoryBuffer & reply, CRemoteClientHandler &client)
  4240. {
  4241. IMPERSONATE_USER(client);
  4242. Owned<StringAttrItem> name = new StringAttrItem;
  4243. byte mode;
  4244. byte share;
  4245. msg.read(name->text).read(mode).read(share);
  4246. // also try to recv extra byte
  4247. byte extra = 0;
  4248. unsigned short sMode = IFUnone;
  4249. unsigned short cFlags = IFUnone;
  4250. if (msg.remaining() >= sizeof(byte))
  4251. {
  4252. msg.read(extra);
  4253. // and then try to recv extra sMode, cFlags (always sent together)
  4254. if (msg.remaining() >= (sizeof(sMode) + sizeof(cFlags)))
  4255. msg.read(sMode).read(cFlags);
  4256. }
  4257. IFEflags extraFlags = (IFEflags)extra;
  4258. // none => nocache for remote (hint)
  4259. // can revert to previous behavior with conf file setting "allow_pgcache_flush=false"
  4260. if (extraFlags == IFEnone)
  4261. extraFlags = IFEnocache;
  4262. Owned<IFile> file = createIFile(name->text);
  4263. switch ((compatIFSHmode)share) {
  4264. case compatIFSHnone:
  4265. file->setCreateFlags(S_IRUSR|S_IWUSR);
  4266. file->setShareMode(IFSHnone);
  4267. break;
  4268. case compatIFSHread:
  4269. file->setShareMode(IFSHread);
  4270. break;
  4271. case compatIFSHwrite:
  4272. file->setShareMode(IFSHfull);
  4273. break;
  4274. case compatIFSHexec:
  4275. file->setCreateFlags(S_IRUSR|S_IWUSR|S_IXUSR|S_IRGRP|S_IXGRP|S_IROTH|S_IXOTH);
  4276. break;
  4277. case compatIFSHall:
  4278. file->setCreateFlags(S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH|S_IWOTH); // bit excessive
  4279. file->setShareMode(IFSHfull);
  4280. break;
  4281. }
  4282. // use sMode, cFlags if sent
  4283. if (sMode != IFUnone && cFlags != IFUnone)
  4284. {
  4285. file->setCreateFlags(cFlags);
  4286. file->setShareMode((IFSHmode)sMode);
  4287. }
  4288. if (TF_TRACE_PRE_IO)
  4289. PROGLOG("before open file '%s', (%d,%d,%d,%d,0%o)",name->text.get(),(int)mode,(int)share,extraFlags,sMode,cFlags);
  4290. Owned<IFileIO> fileio = file->open((IFOmode)mode,extraFlags);
  4291. int handle;
  4292. if (fileio) {
  4293. CriticalBlock block(sect);
  4294. handle = getNextHandle();
  4295. client.previdx = client.openFiles.ordinality();
  4296. client.openFiles.append(OpenFileInfo(handle, fileio, name));
  4297. }
  4298. else
  4299. handle = 0;
  4300. reply.append(RFEnoerror);
  4301. reply.append(handle);
  4302. if (TF_TRACE)
  4303. PROGLOG("open file '%s', (%d,%d) handle = %d",name->text.get(),(int)mode,(int)share,handle);
  4304. return true;
  4305. }
  4306. bool cmdCloseFileIO(MemoryBuffer & msg, MemoryBuffer & reply)
  4307. {
  4308. int handle;
  4309. msg.read(handle);
  4310. IFileIO *fileio;
  4311. if (!checkFileIOHandle(reply, handle, fileio, true))
  4312. return false;
  4313. if (TF_TRACE)
  4314. PROGLOG("close file, handle = %d",handle);
  4315. reply.append(RFEnoerror);
  4316. return true;
  4317. }
  4318. bool cmdRead(MemoryBuffer & msg, MemoryBuffer & reply, CClientStats &stats)
  4319. {
  4320. int handle;
  4321. __int64 pos;
  4322. size32_t len;
  4323. msg.read(handle).read(pos).read(len);
  4324. IFileIO *fileio;
  4325. if (!checkFileIOHandle(reply, handle, fileio))
  4326. return false;
  4327. //arrange it so we read directly into the reply buffer...
  4328. unsigned posOfErr = reply.length();
  4329. reply.append((unsigned)RFEnoerror);
  4330. size32_t numRead;
  4331. unsigned posOfLength = reply.length();
  4332. if (TF_TRACE_PRE_IO)
  4333. PROGLOG("before read file, handle = %d, toread = %d",handle,len);
  4334. void * data;
  4335. {
  4336. reply.reserve(sizeof(numRead));
  4337. data = reply.reserve(len);
  4338. }
  4339. try {
  4340. numRead = fileio->read(pos,len,data);
  4341. }
  4342. catch (IException *e)
  4343. {
  4344. reply.setWritePos(posOfErr);
  4345. StringBuffer s;
  4346. e->errorMessage(s);
  4347. appendErr3(reply, RFSERR_ReadFailed, e->errorCode(), s.str());
  4348. e->Release();
  4349. return false;
  4350. }
  4351. stats.addRead(len);
  4352. if (TF_TRACE)
  4353. PROGLOG("read file, handle = %d, pos = %" I64F "d, toread = %d, read = %d",handle,pos,len,numRead);
  4354. {
  4355. reply.setLength(posOfLength + sizeof(numRead) + numRead);
  4356. reply.writeEndianDirect(posOfLength,sizeof(numRead),&numRead);
  4357. }
  4358. return true;
  4359. }
  4360. bool cmdSize(MemoryBuffer & msg, MemoryBuffer & reply)
  4361. {
  4362. int handle;
  4363. msg.read(handle);
  4364. IFileIO *fileio;
  4365. if (!checkFileIOHandle(reply, handle, fileio))
  4366. return false;
  4367. __int64 size = fileio->size();
  4368. reply.append((unsigned)RFEnoerror).append(size);
  4369. if (TF_TRACE)
  4370. PROGLOG("size file, handle = %d, size = %" I64F "d",handle,size);
  4371. return true;
  4372. }
  4373. bool cmdSetSize(MemoryBuffer & msg, MemoryBuffer & reply)
  4374. {
  4375. int handle;
  4376. offset_t size;
  4377. msg.read(handle).read(size);
  4378. IFileIO *fileio;
  4379. if (TF_TRACE)
  4380. PROGLOG("set size file, handle = %d, size = %" I64F "d",handle,size);
  4381. if (!checkFileIOHandle(reply, handle, fileio))
  4382. return false;
  4383. fileio->setSize(size);
  4384. reply.append((unsigned)RFEnoerror);
  4385. return true;
  4386. }
  4387. bool cmdWrite(MemoryBuffer & msg, MemoryBuffer & reply, CClientStats &stats)
  4388. {
  4389. int handle;
  4390. __int64 pos;
  4391. size32_t len;
  4392. msg.read(handle).read(pos).read(len);
  4393. IFileIO *fileio;
  4394. if (!checkFileIOHandle(reply, handle, fileio))
  4395. return false;
  4396. const byte *data = (const byte *)msg.readDirect(len);
  4397. if (TF_TRACE_PRE_IO)
  4398. PROGLOG("before write file, handle = %d, towrite = %d",handle,len);
  4399. size32_t numWritten = fileio->write(pos,len,data);
  4400. stats.addWrite(numWritten);
  4401. if (TF_TRACE)
  4402. PROGLOG("write file, handle = %d, towrite = %d, written = %d",handle,len,numWritten);
  4403. reply.append((unsigned)RFEnoerror).append(numWritten);
  4404. return true;
  4405. }
  4406. bool cmdExists(MemoryBuffer & msg, MemoryBuffer & reply, CRemoteClientHandler &client)
  4407. {
  4408. IMPERSONATE_USER(client);
  4409. StringAttr name;
  4410. msg.read(name);
  4411. if (TF_TRACE)
  4412. PROGLOG("exists, '%s'",name.get());
  4413. Owned<IFile> file=createIFile(name);
  4414. bool e = file->exists();
  4415. reply.append((unsigned)RFEnoerror).append(e);
  4416. return true;
  4417. }
  4418. bool cmdRemove(MemoryBuffer & msg, MemoryBuffer & reply,CRemoteClientHandler &client)
  4419. {
  4420. IMPERSONATE_USER(client);
  4421. StringAttr name;
  4422. msg.read(name);
  4423. if (TF_TRACE)
  4424. PROGLOG("remove, '%s'",name.get());
  4425. Owned<IFile> file=createIFile(name);
  4426. bool e = file->remove();
  4427. reply.append((unsigned)RFEnoerror).append(e);
  4428. return true;
  4429. }
  4430. bool cmdGetVer(MemoryBuffer & msg, MemoryBuffer & reply)
  4431. {
  4432. if (TF_TRACE)
  4433. PROGLOG("getVer");
  4434. if (msg.getPos()+sizeof(unsigned)>msg.length())
  4435. reply.append((unsigned)RFEnoerror);
  4436. else
  4437. reply.append((unsigned)FILESRV_VERSION+0x10000);
  4438. reply.append(VERSTRING);
  4439. return true;
  4440. }
  4441. bool cmdRename(MemoryBuffer & msg, MemoryBuffer & reply,CRemoteClientHandler &client)
  4442. {
  4443. IMPERSONATE_USER(client);
  4444. StringAttr fromname;
  4445. msg.read(fromname);
  4446. StringAttr toname;
  4447. msg.read(toname);
  4448. if (TF_TRACE)
  4449. PROGLOG("rename, '%s' to '%s'",fromname.get(),toname.get());
  4450. Owned<IFile> file=createIFile(fromname);
  4451. file->rename(toname);
  4452. reply.append((unsigned)RFEnoerror);
  4453. return true;
  4454. }
  4455. bool cmdMove(MemoryBuffer & msg, MemoryBuffer & reply,CRemoteClientHandler &client)
  4456. {
  4457. IMPERSONATE_USER(client);
  4458. StringAttr fromname;
  4459. msg.read(fromname);
  4460. StringAttr toname;
  4461. msg.read(toname);
  4462. if (TF_TRACE)
  4463. PROGLOG("move, '%s' to '%s'",fromname.get(),toname.get());
  4464. Owned<IFile> file=createIFile(fromname);
  4465. file->move(toname);
  4466. reply.append((unsigned)RFEnoerror);
  4467. return true;
  4468. }
  4469. bool cmdCopy(MemoryBuffer & msg, MemoryBuffer & reply, CRemoteClientHandler &client)
  4470. {
  4471. IMPERSONATE_USER(client);
  4472. StringAttr fromname;
  4473. msg.read(fromname);
  4474. StringAttr toname;
  4475. msg.read(toname);
  4476. if (TF_TRACE)
  4477. PROGLOG("copy, '%s' to '%s'",fromname.get(),toname.get());
  4478. copyFile(toname, fromname);
  4479. reply.append((unsigned)RFEnoerror);
  4480. return true;
  4481. }
  4482. bool cmdAppend(MemoryBuffer & msg, MemoryBuffer & reply, CRemoteClientHandler &client, CClientStats &stats)
  4483. {
  4484. IMPERSONATE_USER(client);
  4485. int handle;
  4486. __int64 pos;
  4487. __int64 len;
  4488. StringAttr srcname;
  4489. msg.read(handle).read(srcname).read(pos).read(len);
  4490. IFileIO *fileio;
  4491. if (!checkFileIOHandle(reply, handle, fileio))
  4492. return false;
  4493. Owned<IFile> file = createIFile(srcname.get());
  4494. __int64 written = fileio->appendFile(file,pos,len);
  4495. stats.addWrite(written);
  4496. if (TF_TRACE)
  4497. PROGLOG("append file, handle = %d, file=%s, pos = %" I64F "d len = %" I64F "d written = %" I64F "d",handle,srcname.get(),pos,len,written);
  4498. reply.append((unsigned)RFEnoerror).append(written);
  4499. return true;
  4500. }
  4501. bool cmdIsFile(MemoryBuffer &msg, MemoryBuffer &reply, CRemoteClientHandler &client)
  4502. {
  4503. IMPERSONATE_USER(client);
  4504. StringAttr name;
  4505. msg.read(name);
  4506. if (TF_TRACE)
  4507. PROGLOG("isFile, '%s'",name.get());
  4508. Owned<IFile> file=createIFile(name);
  4509. unsigned ret = (unsigned)file->isFile();
  4510. reply.append((unsigned)RFEnoerror).append(ret);
  4511. return true;
  4512. }
  4513. bool cmdIsDir(MemoryBuffer &msg, MemoryBuffer &reply, CRemoteClientHandler &client)
  4514. {
  4515. IMPERSONATE_USER(client);
  4516. StringAttr name;
  4517. msg.read(name);
  4518. if (TF_TRACE)
  4519. PROGLOG("isDir, '%s'",name.get());
  4520. Owned<IFile> file=createIFile(name);
  4521. unsigned ret = (unsigned)file->isDirectory();
  4522. reply.append((unsigned)RFEnoerror).append(ret);
  4523. return true;
  4524. }
  4525. bool cmdIsReadOnly(MemoryBuffer &msg, MemoryBuffer &reply, CRemoteClientHandler &client)
  4526. {
  4527. IMPERSONATE_USER(client);
  4528. StringAttr name;
  4529. msg.read(name);
  4530. if (TF_TRACE)
  4531. PROGLOG("isReadOnly, '%s'",name.get());
  4532. Owned<IFile> file=createIFile(name);
  4533. unsigned ret = (unsigned)file->isReadOnly();
  4534. reply.append((unsigned)RFEnoerror).append(ret);
  4535. return true;
  4536. }
  4537. bool cmdSetReadOnly(MemoryBuffer &msg, MemoryBuffer &reply, CRemoteClientHandler &client)
  4538. {
  4539. IMPERSONATE_USER(client);
  4540. StringAttr name;
  4541. bool set;
  4542. msg.read(name).read(set);
  4543. if (TF_TRACE)
  4544. PROGLOG("setReadOnly, '%s' %d",name.get(),(int)set);
  4545. Owned<IFile> file=createIFile(name);
  4546. file->setReadOnly(set);
  4547. reply.append((unsigned)RFEnoerror);
  4548. return true;
  4549. }
  4550. bool cmdSetFilePerms(MemoryBuffer &msg, MemoryBuffer &reply, CRemoteClientHandler &client)
  4551. {
  4552. IMPERSONATE_USER(client);
  4553. StringAttr name;
  4554. unsigned fPerms;
  4555. msg.read(name).read(fPerms);
  4556. if (TF_TRACE)
  4557. PROGLOG("setFilePerms, '%s' 0%o",name.get(),fPerms);
  4558. Owned<IFile> file=createIFile(name);
  4559. file->setFilePermissions(fPerms);
  4560. reply.append((unsigned)RFEnoerror);
  4561. return true;
  4562. }
  4563. bool cmdGetTime(MemoryBuffer &msg, MemoryBuffer &reply, CRemoteClientHandler &client)
  4564. {
  4565. IMPERSONATE_USER(client);
  4566. StringAttr name;
  4567. msg.read(name);
  4568. if (TF_TRACE)
  4569. PROGLOG("getTime, '%s'",name.get());
  4570. Owned<IFile> file=createIFile(name);
  4571. CDateTime createTime;
  4572. CDateTime modifiedTime;
  4573. CDateTime accessedTime;
  4574. bool ret = file->getTime(&createTime,&modifiedTime,&accessedTime);
  4575. reply.append((unsigned)RFEnoerror).append(ret);
  4576. if (ret) {
  4577. createTime.serialize(reply);
  4578. modifiedTime.serialize(reply);
  4579. accessedTime.serialize(reply);
  4580. }
  4581. return true;
  4582. }
  4583. bool cmdSetTime(MemoryBuffer &msg, MemoryBuffer &reply, CRemoteClientHandler &client)
  4584. {
  4585. IMPERSONATE_USER(client);
  4586. StringAttr name;
  4587. bool creategot;
  4588. CDateTime createTime;
  4589. bool modifiedgot;
  4590. CDateTime modifiedTime;
  4591. bool accessedgot;
  4592. CDateTime accessedTime;
  4593. msg.read(name);
  4594. msg.read(creategot);
  4595. if (creategot)
  4596. createTime.deserialize(msg);
  4597. msg.read(modifiedgot);
  4598. if (modifiedgot)
  4599. modifiedTime.deserialize(msg);
  4600. msg.read(accessedgot);
  4601. if (accessedgot)
  4602. accessedTime.deserialize(msg);
  4603. if (TF_TRACE)
  4604. PROGLOG("setTime, '%s'",name.get());
  4605. Owned<IFile> file=createIFile(name);
  4606. bool ret = file->setTime(creategot?&createTime:NULL,modifiedgot?&modifiedTime:NULL,accessedgot?&accessedTime:NULL);
  4607. reply.append((unsigned)RFEnoerror).append(ret);
  4608. return true;
  4609. }
  4610. bool cmdCreateDir(MemoryBuffer &msg, MemoryBuffer &reply, CRemoteClientHandler &client)
  4611. {
  4612. IMPERSONATE_USER(client);
  4613. StringAttr name;
  4614. msg.read(name);
  4615. if (TF_TRACE)
  4616. PROGLOG("CreateDir, '%s'",name.get());
  4617. Owned<IFile> dir=createIFile(name);
  4618. bool ret = dir->createDirectory();
  4619. reply.append((unsigned)RFEnoerror).append(ret);
  4620. return true;
  4621. }
  4622. bool cmdGetDir(MemoryBuffer &msg, MemoryBuffer &reply, CRemoteClientHandler &client)
  4623. {
  4624. IMPERSONATE_USER(client);
  4625. StringAttr name;
  4626. StringAttr mask;
  4627. bool includedir;
  4628. bool sub;
  4629. byte stream = 0;
  4630. msg.read(name).read(mask).read(includedir).read(sub);
  4631. if (msg.remaining()>=sizeof(byte))
  4632. {
  4633. msg.read(stream);
  4634. if (stream==1)
  4635. client.opendir.clear();
  4636. }
  4637. if (TF_TRACE)
  4638. PROGLOG("GetDir, '%s', '%s', stream='%u'",name.get(),mask.get(),stream);
  4639. if (!stream && !containsFileWildcard(mask))
  4640. {
  4641. // if no streaming, and mask contains no wildcard, it is much more efficient to get the info without a directory iterator!
  4642. StringBuffer fullFilename(name);
  4643. addPathSepChar(fullFilename).append(mask);
  4644. Owned<IFile> iFile = createIFile(fullFilename);
  4645. if (!iFile->exists())
  4646. {
  4647. reply.append((unsigned)RFSERR_GetDirFailed);
  4648. return false;
  4649. }
  4650. else
  4651. {
  4652. reply.append((unsigned)RFEnoerror);
  4653. // NB: This must preserve same serialization format as CRemoteDirectoryIterator::serialize produces for 1 file.
  4654. byte b=1;
  4655. reply.append(b);
  4656. bool isDir = foundYes == iFile->isDirectory();
  4657. reply.append(isDir);
  4658. reply.append(isDir ? 0 : iFile->size());
  4659. CDateTime dt;
  4660. iFile->getTime(nullptr, &dt, nullptr);
  4661. dt.serialize(reply);
  4662. reply.append(iFile->queryFilename());
  4663. b = 0;
  4664. reply.append(b);
  4665. return true;
  4666. }
  4667. }
  4668. else
  4669. {
  4670. Owned<IFile> dir=createIFile(name);
  4671. Owned<IDirectoryIterator> iter;
  4672. if (stream>1)
  4673. iter.set(client.opendir);
  4674. else
  4675. {
  4676. iter.setown(dir->directoryFiles(mask.length()?mask.get():NULL,sub,includedir));
  4677. if (stream != 0)
  4678. client.opendir.set(iter);
  4679. }
  4680. if (!iter)
  4681. {
  4682. reply.append((unsigned)RFSERR_GetDirFailed);
  4683. return false;
  4684. }
  4685. reply.append((unsigned)RFEnoerror);
  4686. if (CRemoteDirectoryIterator::serialize(reply,iter,stream?0x100000:0,stream<2))
  4687. {
  4688. if (stream != 0)
  4689. client.opendir.clear();
  4690. }
  4691. else
  4692. {
  4693. bool cont=true;
  4694. reply.append(cont);
  4695. }
  4696. }
  4697. return true;
  4698. }
  4699. bool cmdMonitorDir(MemoryBuffer &msg, MemoryBuffer &reply, CRemoteClientHandler &client)
  4700. {
  4701. IMPERSONATE_USER(client);
  4702. StringAttr name;
  4703. StringAttr mask;
  4704. bool includedir;
  4705. bool sub;
  4706. unsigned checkinterval;
  4707. unsigned timeout;
  4708. __int64 cancelid; // not yet used
  4709. msg.read(name).read(mask).read(includedir).read(sub).read(checkinterval).read(timeout).read(cancelid);
  4710. byte isprev;
  4711. msg.read(isprev);
  4712. Owned<IDirectoryIterator> prev;
  4713. if (isprev==1) {
  4714. SocketEndpoint ep;
  4715. CRemoteDirectoryIterator *di = new CRemoteDirectoryIterator(ep,name);
  4716. di->appendBuf(msg);
  4717. prev.setown(di);
  4718. }
  4719. if (TF_TRACE)
  4720. PROGLOG("MonitorDir, '%s' '%s'",name.get(),mask.get());
  4721. Owned<IFile> dir=createIFile(name);
  4722. Owned<IDirectoryDifferenceIterator> iter=dir->monitorDirectory(prev,mask.length()?mask.get():NULL,sub,includedir,checkinterval,timeout);
  4723. reply.append((unsigned)RFEnoerror);
  4724. byte state = (iter.get()==NULL)?0:1;
  4725. reply.append(state);
  4726. if (state==1)
  4727. CRemoteDirectoryIterator::serializeDiff(reply,iter);
  4728. return true;
  4729. }
  4730. bool cmdCopySection(MemoryBuffer &msg, MemoryBuffer &reply, CRemoteClientHandler &client)
  4731. {
  4732. IMPERSONATE_USER(client);
  4733. StringAttr uuid;
  4734. StringAttr fromFile;
  4735. StringAttr toFile;
  4736. offset_t toOfs;
  4737. offset_t fromOfs;
  4738. offset_t size;
  4739. offset_t sizeDone=0;
  4740. offset_t totalSize=(offset_t)-1;
  4741. unsigned timeout;
  4742. msg.read(uuid).read(fromFile).read(toFile).read(toOfs).read(fromOfs).read(size).read(timeout);
  4743. AsyncCommandStatus status = asyncCommandManager.copySection(uuid,fromFile,toFile,toOfs,fromOfs,size,sizeDone,totalSize,timeout);
  4744. reply.append((unsigned)RFEnoerror).append((unsigned)status).append(sizeDone).append(totalSize);
  4745. return true;
  4746. }
  4747. static void treeCopyFile(RemoteFilename &srcfn, RemoteFilename &dstfn, const char *net, const char *mask, IpAddress &ip, bool usetmp, CThrottler *throttler, CFflags copyFlags=CFnone)
  4748. {
  4749. unsigned start = msTick();
  4750. Owned<IFile> dstfile = createIFile(dstfn);
  4751. // the following is really to check the dest node is up and working (otherwise not much point in continuing!)
  4752. if (dstfile->exists())
  4753. PROGLOG("TREECOPY overwriting '%s'",dstfile->queryFilename());
  4754. Owned<IFile> srcfile = createIFile(srcfn);
  4755. unsigned lastmin = 0;
  4756. if (!srcfn.queryIP().ipequals(dstfn.queryIP())) {
  4757. CriticalBlock block(treeCopyCrit);
  4758. for (;;) {
  4759. CDateTime dt;
  4760. offset_t sz;
  4761. try {
  4762. sz = srcfile->size();
  4763. if (sz==(offset_t)-1) {
  4764. if (TF_TRACE_TREE_COPY)
  4765. PROGLOG("TREECOPY source not found '%s'",srcfile->queryFilename());
  4766. break;
  4767. }
  4768. srcfile->getTime(NULL,&dt,NULL);
  4769. }
  4770. catch (IException *e) {
  4771. EXCLOG(e,"treeCopyFile(1)");
  4772. e->Release();
  4773. break;
  4774. }
  4775. Linked<CTreeCopyItem> tc;
  4776. unsigned now = msTick();
  4777. ForEachItemInRev(i1,treeCopyArray) {
  4778. CTreeCopyItem &item = treeCopyArray.item(i1);
  4779. // prune old entries (not strictly needed buf I think better)
  4780. if (now-item.lastused>TREECOPYPRUNETIME)
  4781. treeCopyArray.remove(i1);
  4782. else if (!tc.get()&&item.equals(srcfn,net,mask,sz,dt)) {
  4783. tc.set(&item);
  4784. item.lastused = now;
  4785. }
  4786. }
  4787. if (!tc.get()) {
  4788. if (treeCopyArray.ordinality()>=TREECOPY_CACHE_SIZE)
  4789. treeCopyArray.remove(0);
  4790. tc.setown(new CTreeCopyItem(srcfn,net,mask,sz,dt));
  4791. treeCopyArray.append(*tc.getLink());
  4792. }
  4793. ForEachItemInRev(cand,tc->loc) { // rev to choose copied locations first (maybe optional?)
  4794. if (!tc->busy->testSet(cand)) {
  4795. // check file accessible and matches
  4796. if (!cand&&dstfn.equals(tc->loc.item(cand))) // hmm trying to overwrite existing, better humor
  4797. continue;
  4798. bool ok = true;
  4799. Owned<IFile> rmtfile = createIFile(tc->loc.item(cand));
  4800. if (cand) { // only need to check if remote
  4801. try {
  4802. if (rmtfile->size()!=sz)
  4803. ok = false;
  4804. else {
  4805. CDateTime fdt;
  4806. rmtfile->getTime(NULL,&fdt,NULL);
  4807. ok = fdt.equals(dt);
  4808. }
  4809. }
  4810. catch (IException *e) {
  4811. EXCLOG(e,"treeCopyFile(2)");
  4812. e->Release();
  4813. ok = false;
  4814. }
  4815. }
  4816. if (ok) { // if not ok leave 'busy'
  4817. // finally lets try and copy!
  4818. try {
  4819. if (TF_TRACE_TREE_COPY)
  4820. PROGLOG("TREECOPY(started) %s to %s",rmtfile->queryFilename(),dstfile->queryFilename());
  4821. {
  4822. CriticalUnblock unblock(treeCopyCrit); // note we have tc linked
  4823. rmtfile->copyTo(dstfile,DEFAULT_COPY_BLKSIZE,NULL,usetmp,copyFlags);
  4824. }
  4825. if (TF_TRACE_TREE_COPY)
  4826. PROGLOG("TREECOPY(done) %s to %s",rmtfile->queryFilename(),dstfile->queryFilename());
  4827. tc->busy->set(cand,false);
  4828. if (treeCopyWaiting)
  4829. treeCopySem.signal((treeCopyWaiting>1)?2:1);
  4830. // add to known locations
  4831. tc->busy->set(tc->loc.ordinality(),false); // prob already is clear
  4832. tc->loc.append(dstfn);
  4833. ip.ipset(tc->loc.item(cand).queryIP());
  4834. return;
  4835. }
  4836. catch (IException *e) {
  4837. if (cand==0) {
  4838. tc->busy->set(0,false); // don't leave busy
  4839. if (treeCopyWaiting)
  4840. treeCopySem.signal();
  4841. throw; // what more can we do!
  4842. }
  4843. EXCLOG(e,"treeCopyFile(3)");
  4844. e->Release();
  4845. }
  4846. }
  4847. }
  4848. }
  4849. // all locations busy
  4850. if (msTick()-start>TREECOPYTIMEOUT) {
  4851. WARNLOG("Treecopy %s wait timed out", srcfile->queryFilename());
  4852. break;
  4853. }
  4854. treeCopyWaiting++; // note this isn't precise - just indication
  4855. {
  4856. CriticalUnblock unblock(treeCopyCrit);
  4857. if (throttler)
  4858. {
  4859. CThrottleReleaseBlock block(*throttler, RFCtreecopy);
  4860. treeCopySem.wait(TREECOPYPOLLTIME);
  4861. }
  4862. else
  4863. treeCopySem.wait(TREECOPYPOLLTIME);
  4864. }
  4865. treeCopyWaiting--;
  4866. if ((msTick()-start)/10*1000!=lastmin) {
  4867. lastmin = (msTick()-start)/10*1000;
  4868. PROGLOG("treeCopyFile delayed: %s to %s",srcfile->queryFilename(),dstfile->queryFilename());
  4869. }
  4870. }
  4871. }
  4872. else if (TF_TRACE_TREE_COPY)
  4873. PROGLOG("TREECOPY source on same node as destination");
  4874. if (TF_TRACE_TREE_COPY)
  4875. PROGLOG("TREECOPY(started,fallback) %s to %s",srcfile->queryFilename(),dstfile->queryFilename());
  4876. try {
  4877. GetHostIp(ip);
  4878. srcfile->copyTo(dstfile,DEFAULT_COPY_BLKSIZE,NULL,usetmp,copyFlags);
  4879. }
  4880. catch (IException *e) {
  4881. EXCLOG(e,"TREECOPY(done,fallback)");
  4882. throw;
  4883. }
  4884. if (TF_TRACE_TREE_COPY)
  4885. PROGLOG("TREECOPY(done,fallback) %s to %s",srcfile->queryFilename(),dstfile->queryFilename());
  4886. }
  4887. bool cmdTreeCopy(MemoryBuffer &msg, MemoryBuffer &reply, CRemoteClientHandler &client, CThrottler *throttler, bool usetmp=false)
  4888. {
  4889. IMPERSONATE_USER(client);
  4890. RemoteFilename src;
  4891. src.deserialize(msg);
  4892. RemoteFilename dst;
  4893. dst.deserialize(msg);
  4894. StringAttr net;
  4895. StringAttr mask;
  4896. msg.read(net).read(mask);
  4897. IpAddress ip;
  4898. treeCopyFile(src,dst,net,mask,ip,usetmp,throttler);
  4899. unsigned status = 0;
  4900. reply.append((unsigned)RFEnoerror).append((unsigned)status);
  4901. ip.ipserialize(reply);
  4902. return true;
  4903. }
  4904. bool cmdTreeCopyTmp(MemoryBuffer &msg, MemoryBuffer &reply, CRemoteClientHandler &client, CThrottler *throttler)
  4905. {
  4906. return cmdTreeCopy(msg, reply, client, throttler, true);
  4907. }
  4908. bool cmdGetCRC(MemoryBuffer &msg, MemoryBuffer &reply, CRemoteClientHandler &client)
  4909. {
  4910. IMPERSONATE_USER(client);
  4911. StringAttr name;
  4912. msg.read(name);
  4913. if (TF_TRACE)
  4914. PROGLOG("getCRC, '%s'",name.get());
  4915. Owned<IFile> file=createIFile(name);
  4916. unsigned ret = file->getCRC();
  4917. reply.append((unsigned)RFEnoerror).append(ret);
  4918. return true;
  4919. }
  4920. bool cmdStop(MemoryBuffer &msg, MemoryBuffer &reply)
  4921. {
  4922. PROGLOG("Abort request received");
  4923. stopping = true;
  4924. if (acceptsock)
  4925. acceptsock->cancel_accept();
  4926. if (securesock)
  4927. securesock->cancel_accept();
  4928. reply.append((unsigned)RFEnoerror);
  4929. return false;
  4930. }
  4931. bool cmdExec(MemoryBuffer &msg, MemoryBuffer &reply, CRemoteClientHandler &client)
  4932. {
  4933. StringAttr cmdLine;
  4934. msg.read(cmdLine);
  4935. // NB: legacy remoteExec used to simply pass error code and buffer back to caller.
  4936. VStringBuffer errMsg("Remote command execution no longer supported. Trying to execute cmdline=%s", cmdLine.get());
  4937. WARNLOG("%s", errMsg.str());
  4938. size32_t outSz = errMsg.length()+1; // reply with null terminated string
  4939. // reply with error code -1
  4940. reply.append((unsigned)-1).append((unsigned)0).append(outSz).append(outSz, errMsg.str());
  4941. return true;
  4942. }
  4943. bool cmdSetTrace(MemoryBuffer &msg, MemoryBuffer &reply)
  4944. {
  4945. byte flags;
  4946. msg.read(flags);
  4947. int retcode=-1;
  4948. if (flags!=255) { // escape
  4949. retcode = traceFlags;
  4950. traceFlags = flags;
  4951. }
  4952. reply.append(retcode);
  4953. return true;
  4954. }
  4955. bool cmdGetInfo(MemoryBuffer &msg, MemoryBuffer &reply)
  4956. {
  4957. unsigned level=1;
  4958. if (msg.remaining() >= sizeof(unsigned))
  4959. msg.read(level);
  4960. StringBuffer retstr;
  4961. getInfo(retstr, level);
  4962. reply.append(0).append(retstr.str());
  4963. return true;
  4964. }
  4965. bool cmdFirewall(MemoryBuffer &msg, MemoryBuffer &reply)
  4966. {
  4967. // TBD
  4968. StringBuffer retstr;
  4969. getInfo(retstr);
  4970. reply.append(0).append(retstr.str());
  4971. return true;
  4972. }
  4973. bool cmdExtractBlobElements(MemoryBuffer &msg, MemoryBuffer &reply, CRemoteClientHandler &client)
  4974. {
  4975. IMPERSONATE_USER(client);
  4976. StringAttr prefix;
  4977. StringAttr filename;
  4978. msg.read(prefix).read(filename);
  4979. RemoteFilename rfn;
  4980. rfn.setLocalPath(filename);
  4981. ExtractedBlobArray extracted;
  4982. extractBlobElements(prefix, rfn, extracted);
  4983. unsigned n = extracted.ordinality();
  4984. reply.append((unsigned)RFEnoerror).append(n);
  4985. for (unsigned i=0;i<n;i++)
  4986. extracted.item(i).serialize(reply);
  4987. return true;
  4988. }
  4989. bool cmdRedeploy(MemoryBuffer &msg, MemoryBuffer &reply)
  4990. {
  4991. return false; // TBD
  4992. }
  4993. bool cmdUnknown(MemoryBuffer & msg, MemoryBuffer & reply,RemoteFileCommandType cmd)
  4994. {
  4995. appendErr2(reply, RFSERR_InvalidCommand, cmd);
  4996. return false;
  4997. }
  4998. bool cmdUnlock(MemoryBuffer & msg, MemoryBuffer & reply,CRemoteClientHandler &client)
  4999. {
  5000. // this is an attempt to authenticate when we haven't got authentication turned on
  5001. if (TF_TRACE_CLIENT_STATS)
  5002. {
  5003. StringBuffer s(client.queryPeerName());
  5004. PROGLOG("Connect from %s",s.str());
  5005. }
  5006. appendErr2(reply, RFSERR_InvalidCommand, RFCunlock);
  5007. return false;
  5008. }
  5009. bool cmdStreamReadTestSocket(MemoryBuffer & msg, MemoryBuffer & reply, CRemoteClientHandler &client)
  5010. {
  5011. unsigned replyPos = reply.length();
  5012. try
  5013. {
  5014. reply.append('J');
  5015. return cmdStreamRead(msg, reply, client);
  5016. }
  5017. catch (IException *)
  5018. {
  5019. reply.rewrite(replyPos);
  5020. reply.append('-');
  5021. throw;
  5022. }
  5023. }
  5024. bool cmdStreamRead(MemoryBuffer & msg, MemoryBuffer & reply, CRemoteClientHandler &client)
  5025. {
  5026. // this is an attempt to authenticate when we haven't got authentication turned on
  5027. if (TF_TRACE_CLIENT_STATS)
  5028. {
  5029. StringBuffer s(client.queryPeerName());
  5030. PROGLOG("Connect from %s",s.str());
  5031. }
  5032. Owned<IPropertyTree> requestTree = createPTreeFromJSONString(msg.length(), msg.toByteArray());
  5033. /* Example JSON request:
  5034. * {
  5035. * "format" : "xml",
  5036. * "cursor" : "1234",
  5037. * "node" : {
  5038. * "kind" : "diskread",
  5039. * "fileName": "examplefilename",
  5040. * "keyfilter" : "f1='1 '",
  5041. * "choosen" : "5",
  5042. * "cursor" : "12345", // cursor handle
  5043. * "input" : {
  5044. * "f1" : "string5",
  5045. * "f2" : "string5"
  5046. * },
  5047. * "output" : {
  5048. * "f2" : "string",
  5049. * "f1" : "real"
  5050. * }
  5051. * }
  5052. * }
  5053. *
  5054. */
  5055. const char *outputFmtStr = requestTree->queryProp("format");
  5056. int cursorHandle = requestTree->getPropInt("cursor");
  5057. OutputFormat outputFormat;
  5058. if (nullptr == outputFmtStr)
  5059. outputFormat = outFmt_Xml; // default
  5060. else if (strieq("xml", outputFmtStr))
  5061. outputFormat = outFmt_Xml;
  5062. else if (strieq("json", outputFmtStr))
  5063. outputFormat = outFmt_Json;
  5064. else if (strieq("binary", outputFmtStr))
  5065. outputFormat = outFmt_Binary;
  5066. else
  5067. throw MakeStringException(0, "Unrecognised output format: %s", outputFmtStr);
  5068. Owned<IRemoteActivity> outputActivity;
  5069. OpenFileInfo fileInfo;
  5070. if (!cursorHandle)
  5071. {
  5072. // In future this may be passed the request and build a chain of activities and return sink.
  5073. outputActivity.setown(createOutputActivity(*requestTree));
  5074. StringBuffer requestStr("jsonrequest:");
  5075. outputActivity->getInfoStr(requestStr);
  5076. Owned<StringAttrItem> name = new StringAttrItem(requestStr);
  5077. CriticalBlock block(sect);
  5078. cursorHandle = getNextHandle();
  5079. client.previdx = client.openFiles.ordinality();
  5080. client.openFiles.append(OpenFileInfo(cursorHandle, outputActivity, name));
  5081. }
  5082. else if (!lookupFileIOHandle(cursorHandle, fileInfo))
  5083. cursorHandle = 0; // challenge response ..
  5084. else // known handle, continuation
  5085. outputActivity.set(fileInfo.activity);
  5086. if (outputActivity && requestTree->hasProp("cursorBin")) // use handle if one provided
  5087. {
  5088. MemoryBuffer cursorMb;
  5089. cursorMb.setEndian(__BIG_ENDIAN);
  5090. JBASE64_Decode(requestTree->queryProp("cursorBin"), cursorMb);
  5091. outputActivity->restoreCursor(cursorMb);
  5092. }
  5093. Owned<IXmlWriterExt> responseWriter; // for xml or json response
  5094. if (outFmt_Binary == outputFormat)
  5095. reply.append(cursorHandle);
  5096. else // outFmt_Xml || outFmt_Json
  5097. {
  5098. responseWriter.setown(createIXmlWriterExt(0, 0, nullptr, outFmt_Xml == outputFormat ? WTStandard : WTJSON));
  5099. responseWriter->outputBeginNested("Response", true);
  5100. responseWriter->outputUInt(cursorHandle, sizeof(cursorHandle), "cursor");
  5101. }
  5102. if (cursorHandle)
  5103. {
  5104. IOutputMetaData *out = outputActivity->queryOutputMeta();
  5105. unsigned __int64 initProcessed = outputActivity->queryProcessed();
  5106. bool eoi=false;
  5107. if (outFmt_Binary == outputFormat)
  5108. {
  5109. DelayedSizeMarker dataLenMarker(reply); // data length
  5110. for (unsigned __int64 i=0; i<defaultDaFSNumRecs; i++)
  5111. {
  5112. size32_t rowSz;
  5113. const void *row = outputActivity->nextRow(rowSz);
  5114. if (!row)
  5115. {
  5116. eoi = true;
  5117. break;
  5118. }
  5119. reply.append(rowSz, row);
  5120. }
  5121. dataLenMarker.write();
  5122. DelayedSizeMarker cursorLenMarker(reply); // cursor length
  5123. if (!eoi)
  5124. outputActivity->serializeCursor(reply);
  5125. cursorLenMarker.write();
  5126. }
  5127. else
  5128. {
  5129. for (unsigned __int64 i=0; i<defaultDaFSNumRecs; i++)
  5130. {
  5131. size32_t rowSz;
  5132. const void *row = outputActivity->nextRow(rowSz);
  5133. if (!row)
  5134. {
  5135. eoi = true;
  5136. break;
  5137. }
  5138. responseWriter->outputBeginNested("Row", true);
  5139. out->toXML((const byte *)row, *responseWriter);
  5140. responseWriter->outputEndNested("Row");
  5141. }
  5142. if (!eoi)
  5143. {
  5144. MemoryBuffer cursorMb;
  5145. cursorMb.setEndian(__BIG_ENDIAN);
  5146. outputActivity->serializeCursor(cursorMb);
  5147. StringBuffer cursorBinStr;
  5148. JBASE64_Encode(cursorMb.toByteArray(), cursorMb.length(), cursorBinStr);
  5149. responseWriter->outputString(cursorBinStr.length(), cursorBinStr.str(), "cursorBin");
  5150. }
  5151. }
  5152. }
  5153. if (outFmt_Binary != outputFormat)
  5154. {
  5155. responseWriter->outputEndNested("Response");
  5156. PROGLOG("Response: %s", responseWriter->str());
  5157. reply.append(responseWriter->length(), responseWriter->str());
  5158. }
  5159. return true;
  5160. }
  5161. // legacy version
  5162. bool cmdSetThrottle(MemoryBuffer & msg, MemoryBuffer & reply)
  5163. {
  5164. unsigned limit, delayMs, cpuThreshold;
  5165. msg.read(limit);
  5166. msg.read(delayMs);
  5167. msg.read(cpuThreshold);
  5168. stdCmdThrottler.configure(limit, delayMs, cpuThreshold, (unsigned)-1);
  5169. reply.append((unsigned)RFEnoerror);
  5170. return true;
  5171. }
  5172. bool cmdSetThrottle2(MemoryBuffer & msg, MemoryBuffer & reply)
  5173. {
  5174. unsigned throttleClass, limit, delayMs, cpuThreshold, queueLimit;
  5175. msg.read(throttleClass);
  5176. msg.read(limit);
  5177. msg.read(delayMs);
  5178. msg.read(cpuThreshold);
  5179. msg.read(queueLimit);
  5180. setThrottle((ThrottleClass)throttleClass, limit, delayMs, cpuThreshold, queueLimit);
  5181. reply.append((unsigned)RFEnoerror);
  5182. return true;
  5183. }
  5184. void appendError(RemoteFileCommandType cmd, CRemoteClientHandler *client, unsigned ret, MemoryBuffer &reply)
  5185. {
  5186. if (reply.length()>=sizeof(unsigned)*2)
  5187. {
  5188. reply.reset();
  5189. unsigned z;
  5190. unsigned e;
  5191. reply.read(z).read(e);
  5192. StringBuffer err("ERR(");
  5193. err.append(e).append(") ");
  5194. if (client)
  5195. {
  5196. const char *peer = client->queryPeerName();
  5197. if (peer)
  5198. err.append(peer);
  5199. }
  5200. if (e&&(reply.getPos()<reply.length()))
  5201. {
  5202. StringAttr es;
  5203. reply.read(es);
  5204. err.append(" : ").append(es);
  5205. }
  5206. reply.reset();
  5207. if (cmd!=RFCunlock)
  5208. PROGLOG("%s",err.str()); // supress authentication logging
  5209. if (client)
  5210. client->logPrevHandle();
  5211. }
  5212. }
  5213. void throttleCommand(RemoteFileCommandType cmd, MemoryBuffer &msg, CRemoteClientHandler *client)
  5214. {
  5215. switch(cmd)
  5216. {
  5217. case RFCexec:
  5218. case RFCgetcrc:
  5219. case RFCcopy:
  5220. case RFCappend:
  5221. case RFCtreecopy:
  5222. case RFCtreecopytmp:
  5223. slowCmdThrottler.addCommand(cmd, msg, client);
  5224. return;
  5225. case RFCcloseIO:
  5226. case RFCopenIO:
  5227. case RFCread:
  5228. case RFCsize:
  5229. case RFCwrite:
  5230. case RFCexists:
  5231. case RFCremove:
  5232. case RFCrename:
  5233. case RFCgetver:
  5234. case RFCisfile:
  5235. case RFCisdirectory:
  5236. case RFCisreadonly:
  5237. case RFCsetreadonly:
  5238. case RFCsetfileperms:
  5239. case RFCreadfilteredindex:
  5240. case RFCreadfilteredindexcount:
  5241. case RFCreadfilteredindexblob:
  5242. case RFCgettime:
  5243. case RFCsettime:
  5244. case RFCcreatedir:
  5245. case RFCgetdir:
  5246. case RFCmonitordir:
  5247. case RFCstop:
  5248. case RFCextractblobelements:
  5249. case RFCredeploy:
  5250. case RFCmove:
  5251. case RFCsetsize:
  5252. case RFCsettrace:
  5253. case RFCgetinfo:
  5254. case RFCfirewall:
  5255. case RFCunlock:
  5256. case RFCStreamRead:
  5257. stdCmdThrottler.addCommand(cmd, msg, client);
  5258. return;
  5259. // NB: The following commands are still bound by the the thread pool
  5260. case RFCsetthrottle: // legacy version
  5261. case RFCsetthrottle2:
  5262. case RFCcopysection: // slightly odd, but has it's own limit
  5263. default:
  5264. {
  5265. client->processCommand(cmd, msg, NULL);
  5266. break;
  5267. }
  5268. }
  5269. }
  5270. bool processCommand(RemoteFileCommandType cmd, MemoryBuffer & msg, MemoryBuffer & reply, CRemoteClientHandler *client, CThrottler *throttler)
  5271. {
  5272. Owned<CClientStats> stats = clientStatsTable.getClientReference(cmd, client->queryPeerName());
  5273. bool ret = true;
  5274. bool testSocketFlag = false;
  5275. try
  5276. {
  5277. switch(cmd)
  5278. {
  5279. MAPCOMMANDSTATS(RFCread, cmdRead, *stats);
  5280. MAPCOMMANDSTATS(RFCwrite, cmdWrite, *stats);
  5281. MAPCOMMANDCLIENTSTATS(RFCappend, cmdAppend, *client, *stats);
  5282. MAPCOMMAND(RFCcloseIO, cmdCloseFileIO);
  5283. MAPCOMMANDCLIENT(RFCopenIO, cmdOpenFileIO, *client);
  5284. MAPCOMMAND(RFCsize, cmdSize);
  5285. MAPCOMMANDCLIENT(RFCexists, cmdExists, *client);
  5286. MAPCOMMANDCLIENT(RFCremove, cmdRemove, *client);
  5287. MAPCOMMANDCLIENT(RFCrename, cmdRename, *client);
  5288. MAPCOMMAND(RFCgetver, cmdGetVer);
  5289. MAPCOMMANDCLIENT(RFCisfile, cmdIsFile, *client);
  5290. MAPCOMMANDCLIENT(RFCisdirectory, cmdIsDir, *client);
  5291. MAPCOMMANDCLIENT(RFCisreadonly, cmdIsReadOnly, *client);
  5292. MAPCOMMANDCLIENT(RFCsetreadonly, cmdSetReadOnly, *client);
  5293. MAPCOMMANDCLIENT(RFCsetfileperms, cmdSetFilePerms, *client);
  5294. MAPCOMMANDCLIENT(RFCgettime, cmdGetTime, *client);
  5295. MAPCOMMANDCLIENT(RFCsettime, cmdSetTime, *client);
  5296. MAPCOMMANDCLIENT(RFCcreatedir, cmdCreateDir, *client);
  5297. MAPCOMMANDCLIENT(RFCgetdir, cmdGetDir, *client);
  5298. MAPCOMMANDCLIENT(RFCmonitordir, cmdMonitorDir, *client);
  5299. MAPCOMMAND(RFCstop, cmdStop);
  5300. MAPCOMMANDCLIENT(RFCexec, cmdExec, *client);
  5301. MAPCOMMANDCLIENT(RFCextractblobelements, cmdExtractBlobElements, *client);
  5302. MAPCOMMAND(RFCredeploy, cmdRedeploy); // only Windows
  5303. MAPCOMMANDCLIENT(RFCgetcrc, cmdGetCRC, *client);
  5304. MAPCOMMANDCLIENT(RFCmove, cmdMove, *client);
  5305. MAPCOMMANDCLIENT(RFCcopy, cmdCopy, *client);
  5306. MAPCOMMAND(RFCsetsize, cmdSetSize);
  5307. MAPCOMMAND(RFCsettrace, cmdSetTrace);
  5308. MAPCOMMAND(RFCgetinfo, cmdGetInfo);
  5309. MAPCOMMAND(RFCfirewall, cmdFirewall);
  5310. MAPCOMMANDCLIENT(RFCunlock, cmdUnlock, *client);
  5311. MAPCOMMANDCLIENTTESTSOCKET(RFCStreamRead, cmdStreamReadTestSocket, *client);
  5312. MAPCOMMANDCLIENT(RFCcopysection, cmdCopySection, *client);
  5313. MAPCOMMANDCLIENTTHROTTLE(RFCtreecopy, cmdTreeCopy, *client, &slowCmdThrottler);
  5314. MAPCOMMANDCLIENTTHROTTLE(RFCtreecopytmp, cmdTreeCopyTmp, *client, &slowCmdThrottler);
  5315. MAPCOMMAND(RFCsetthrottle, cmdSetThrottle); // legacy version
  5316. MAPCOMMAND(RFCsetthrottle2, cmdSetThrottle2);
  5317. default:
  5318. ret = cmdUnknown(msg,reply,cmd);
  5319. break;
  5320. }
  5321. }
  5322. catch (IException *e)
  5323. {
  5324. ret = false;
  5325. StringBuffer s;
  5326. e->errorMessage(s);
  5327. appendCmdErr(reply, cmd, e->errorCode(), s.str());
  5328. e->Release();
  5329. }
  5330. if (!ret) // append error string
  5331. {
  5332. appendError(cmd, client, cmd, reply);
  5333. }
  5334. return testSocketFlag;
  5335. }
  5336. IPooledThread *createCommandProcessor()
  5337. {
  5338. return new cCommandProcessor();
  5339. }
  5340. void run(DAFSConnectCfg _connectMethod, SocketEndpoint &listenep, unsigned sslPort)
  5341. {
  5342. SocketEndpoint sslep(listenep);
  5343. if (sslPort)
  5344. sslep.port = sslPort;
  5345. else
  5346. sslep.port = securitySettings.daFileSrvSSLPort;
  5347. Owned<ISocket> acceptSocket, acceptSSLSocket;
  5348. if (_connectMethod != SSLOnly)
  5349. {
  5350. if (listenep.port == 0)
  5351. throw createDafsException(DAFSERR_serverinit_failed, "dafilesrv port not specified");
  5352. if (listenep.isNull())
  5353. acceptSocket.setown(ISocket::create(listenep.port));
  5354. else
  5355. {
  5356. StringBuffer ips;
  5357. listenep.getIpText(ips);
  5358. acceptSocket.setown(ISocket::create_ip(listenep.port,ips.str()));
  5359. }
  5360. }
  5361. if (_connectMethod == SSLOnly || _connectMethod == SSLFirst || _connectMethod == UnsecureFirst)
  5362. {
  5363. if (sslep.port == 0)
  5364. throw createDafsException(DAFSERR_serverinit_failed, "Secure dafilesrv port not specified");
  5365. if (_connectMethod == UnsecureFirst)
  5366. {
  5367. // don't fail, but warn - this allows for fast SSL client rejections
  5368. if (!securitySettings.certificate)
  5369. WARNLOG("SSL Certificate information not found in environment.conf, cannot accept SSL connections");
  5370. else if ( !checkFileExists(securitySettings.certificate) )
  5371. {
  5372. WARNLOG("SSL Certificate File not found in environment.conf, cannot accept SSL connections");
  5373. securitySettings.certificate = nullptr;
  5374. }
  5375. if (!securitySettings.privateKey)
  5376. WARNLOG("SSL Key information not found in environment.conf, cannot accept SSL connections");
  5377. else if ( !checkFileExists(securitySettings.privateKey) )
  5378. {
  5379. WARNLOG("SSL Key File not found in environment.conf, cannot accept SSL connections");
  5380. securitySettings.privateKey = nullptr;
  5381. }
  5382. }
  5383. else
  5384. {
  5385. if (!securitySettings.certificate)
  5386. throw createDafsException(DAFSERR_serverinit_failed, "SSL Certificate information not found in environment.conf");
  5387. if (!checkFileExists(securitySettings.certificate))
  5388. throw createDafsException(DAFSERR_serverinit_failed, "SSL Certificate File not found in environment.conf");
  5389. if (!securitySettings.privateKey)
  5390. throw createDafsException(DAFSERR_serverinit_failed, "SSL Key information not found in environment.conf");
  5391. if (!checkFileExists(securitySettings.privateKey))
  5392. throw createDafsException(DAFSERR_serverinit_failed, "SSL Key File not found in environment.conf");
  5393. }
  5394. if (sslep.isNull())
  5395. acceptSSLSocket.setown(ISocket::create(sslep.port));
  5396. else
  5397. {
  5398. StringBuffer ips;
  5399. sslep.getIpText(ips);
  5400. acceptSSLSocket.setown(ISocket::create_ip(sslep.port,ips.str()));
  5401. }
  5402. }
  5403. run(_connectMethod, acceptSocket.getClear(), acceptSSLSocket.getClear());
  5404. }
  5405. void run(DAFSConnectCfg _connectMethod, ISocket *regSocket, ISocket *secureSocket)
  5406. {
  5407. if (_connectMethod != SSLOnly)
  5408. {
  5409. if (regSocket)
  5410. acceptsock.setown(regSocket);
  5411. else
  5412. throw createDafsException(DAFSERR_serverinit_failed, "Invalid non-secure socket");
  5413. }
  5414. if (_connectMethod == SSLOnly || _connectMethod == SSLFirst || _connectMethod == UnsecureFirst)
  5415. {
  5416. if (secureSocket)
  5417. securesock.setown(secureSocket);
  5418. else
  5419. throw createDafsException(DAFSERR_serverinit_failed, "Invalid secure socket");
  5420. }
  5421. selecthandler->start();
  5422. for (;;)
  5423. {
  5424. Owned<ISocket> sock;
  5425. Owned<ISocket> sockSSL;
  5426. bool sockavail = false;
  5427. bool securesockavail = false;
  5428. if (_connectMethod == SSLNone)
  5429. sockavail = acceptsock->wait_read(1000*60*1)!=0;
  5430. else if (_connectMethod == SSLOnly)
  5431. securesockavail = securesock->wait_read(1000*60*1)!=0;
  5432. else
  5433. {
  5434. UnsignedArray readSocks;
  5435. UnsignedArray waitingSocks;
  5436. readSocks.append(acceptsock->OShandle());
  5437. readSocks.append(securesock->OShandle());
  5438. int numReady = wait_read_multiple(readSocks, 1000*60*1, waitingSocks);
  5439. if (numReady > 0)
  5440. {
  5441. for (int idx = 0; idx < numReady; idx++)
  5442. {
  5443. if (waitingSocks.item(idx) == acceptsock->OShandle())
  5444. sockavail = true;
  5445. else if (waitingSocks.item(idx) == securesock->OShandle())
  5446. securesockavail = true;
  5447. }
  5448. }
  5449. }
  5450. #if 0
  5451. if (!sockavail && !securesockavail)
  5452. {
  5453. JSocketStatistics stats;
  5454. getSocketStatistics(stats);
  5455. StringBuffer s;
  5456. getSocketStatisticsString(stats,s);
  5457. PROGLOG( "Socket statistics : \n%s\n",s.str());
  5458. }
  5459. #endif
  5460. if (stopping)
  5461. break;
  5462. if (sockavail || securesockavail)
  5463. {
  5464. if (sockavail)
  5465. {
  5466. try
  5467. {
  5468. sock.setown(acceptsock->accept(true));
  5469. if (!sock||stopping)
  5470. break;
  5471. #ifdef _DEBUG
  5472. SocketEndpoint eps;
  5473. sock->getPeerEndpoint(eps);
  5474. StringBuffer sb;
  5475. eps.getUrlStr(sb);
  5476. PROGLOG("Server accepting from %s", sb.str());
  5477. #endif
  5478. }
  5479. catch (IException *e)
  5480. {
  5481. EXCLOG(e,"CRemoteFileServer");
  5482. e->Release();
  5483. break;
  5484. }
  5485. }
  5486. if (securesockavail)
  5487. {
  5488. Owned<ISecureSocket> ssock;
  5489. try
  5490. {
  5491. sockSSL.setown(securesock->accept(true));
  5492. if (!sockSSL||stopping)
  5493. break;
  5494. if ( (_connectMethod == UnsecureFirst) && (!securitySettings.certificate || !securitySettings.privateKey) )
  5495. {
  5496. // for client secure_connect() to fail quickly ...
  5497. cleanupSocket(sockSSL);
  5498. sockSSL.clear();
  5499. securesockavail = false;
  5500. }
  5501. else
  5502. {
  5503. #ifdef _USE_OPENSSL
  5504. ssock.setown(createSecureSocket(sockSSL.getClear(), ServerSocket));
  5505. int status = ssock->secure_accept();
  5506. if (status < 0)
  5507. throw createDafsException(DAFSERR_serveraccept_failed,"Failure to establish secure connection");
  5508. sockSSL.setown(ssock.getLink());
  5509. #else
  5510. throw createDafsException(DAFSERR_serveraccept_failed,"Failure to establish secure connection: OpenSSL disabled in build");
  5511. #endif
  5512. #ifdef _DEBUG
  5513. SocketEndpoint eps;
  5514. sockSSL->getPeerEndpoint(eps);
  5515. StringBuffer sb;
  5516. eps.getUrlStr(sb);
  5517. PROGLOG("Server accepting SECURE from %s", sb.str());
  5518. #endif
  5519. }
  5520. }
  5521. catch (IJSOCK_Exception *e)
  5522. {
  5523. // accept failed ...
  5524. EXCLOG(e,"CRemoteFileServer (secure)");
  5525. e->Release();
  5526. break;
  5527. }
  5528. catch (IException *e) // IDAFS_Exception also ...
  5529. {
  5530. EXCLOG(e,"CRemoteFileServer1 (secure)");
  5531. e->Release();
  5532. cleanupSocket(sockSSL);
  5533. sockSSL.clear();
  5534. cleanupSocket(ssock);
  5535. ssock.clear();
  5536. securesockavail = false;
  5537. }
  5538. }
  5539. if (sockavail)
  5540. runClient(sock.getClear());
  5541. if (securesockavail)
  5542. runClient(sockSSL.getClear());
  5543. }
  5544. else
  5545. checkTimeout();
  5546. }
  5547. if (TF_TRACE_CLIENT_STATS)
  5548. PROGLOG("CRemoteFileServer:run exiting");
  5549. selecthandler->stop(true);
  5550. }
  5551. void processUnauthenticatedCommand(RemoteFileCommandType cmd, ISocket *socket, MemoryBuffer &msg)
  5552. {
  5553. // these are unauthenticated commands
  5554. if (cmd != RFCgetver)
  5555. cmd = RFCinvalid;
  5556. MemoryBuffer reply;
  5557. bool testSocketFlag = processCommand(cmd, msg, initSendBuffer(reply), NULL, NULL);
  5558. sendBuffer(socket, reply, testSocketFlag);
  5559. }
  5560. bool checkAuthentication(ISocket *socket, IAuthenticatedUser *&ret)
  5561. {
  5562. ret = NULL;
  5563. if (!AuthenticationEnabled)
  5564. return true;
  5565. MemoryBuffer reqbuf;
  5566. MemoryBuffer reply;
  5567. MemoryBuffer encbuf; // because aesEncrypt clears input
  5568. initSendBuffer(reply);
  5569. receiveBuffer(socket, reqbuf, 1);
  5570. RemoteFileCommandType typ=0;
  5571. if (reqbuf.remaining()<sizeof(RemoteFileCommandType))
  5572. return false;
  5573. reqbuf.read(typ);
  5574. if (typ!=RFCunlock) {
  5575. processUnauthenticatedCommand(typ,socket,reqbuf);
  5576. return false;
  5577. }
  5578. if (reqbuf.remaining()<sizeof(OnceKey))
  5579. return false;
  5580. OnceKey oncekey;
  5581. reqbuf.read(sizeof(oncekey),&oncekey);
  5582. IpAddress ip;
  5583. socket->getPeerAddress(ip);
  5584. byte ipdata[16];
  5585. ip.getNetAddress(sizeof(ipdata),&ipdata);
  5586. mergeOnce(oncekey,sizeof(ipdata),&ipdata); // this is clients key
  5587. OnceKey mykey;
  5588. genOnce(mykey);
  5589. reply.append((unsigned)0); // errcode
  5590. aesEncrypt(&oncekey,sizeof(oncekey),&mykey,sizeof(oncekey),encbuf);
  5591. reply.append(encbuf.length()).append(encbuf);
  5592. sendBuffer(socket, reply); // send my oncekey
  5593. reqbuf.clear();
  5594. receiveBuffer(socket, reqbuf, 1);
  5595. if (reqbuf.remaining()>sizeof(RemoteFileCommandType)+sizeof(size32_t)) {
  5596. reqbuf.read(typ);
  5597. if (typ==RFCunlockreply) {
  5598. size32_t bs;
  5599. reqbuf.read(bs);
  5600. if (bs<=reqbuf.remaining()) {
  5601. MemoryBuffer userbuf;
  5602. aesDecrypt(&mykey,sizeof(mykey),reqbuf.readDirect(bs),bs,userbuf);
  5603. byte n;
  5604. userbuf.read(n);
  5605. if (n>=2) {
  5606. StringAttr user;
  5607. StringAttr password;
  5608. userbuf.read(user).read(password);
  5609. Owned<IAuthenticatedUser> iau = createAuthenticatedUser();
  5610. if (iau->login(user,password)) {
  5611. initSendBuffer(reply.clear());
  5612. reply.append((unsigned)0);
  5613. sendBuffer(socket, reply); // send OK
  5614. ret = iau;
  5615. return true;
  5616. }
  5617. }
  5618. }
  5619. }
  5620. }
  5621. reply.clear();
  5622. appendErr(reply, RFSERR_AuthenticateFailed);
  5623. sendBuffer(socket, reply); // send OK
  5624. return false;
  5625. }
  5626. void runClient(ISocket *sock)
  5627. {
  5628. cCommandProcessor::cCommandProcessorParams params;
  5629. IAuthenticatedUser *user=NULL;
  5630. bool authenticated = false;
  5631. try {
  5632. if (checkAuthentication(sock,user))
  5633. authenticated = true;
  5634. }
  5635. catch (IException *e) {
  5636. e->Release();
  5637. }
  5638. if (!authenticated) {
  5639. try {
  5640. sock->Release();
  5641. }
  5642. catch (IException *e) {
  5643. e->Release();
  5644. }
  5645. return;
  5646. }
  5647. params.client = new CRemoteClientHandler(this,sock,user,globallasttick);
  5648. {
  5649. CriticalBlock block(sect);
  5650. clients.append(*LINK(params.client));
  5651. }
  5652. // NB: This could be blocked, by thread pool limit
  5653. threads->start(&params);
  5654. }
  5655. void stop()
  5656. {
  5657. // stop accept loop
  5658. if (TF_TRACE_CLIENT_STATS)
  5659. PROGLOG("CRemoteFileServer::stop");
  5660. if (acceptsock)
  5661. acceptsock->cancel_accept();
  5662. if (securesock)
  5663. securesock->cancel_accept();
  5664. threads->stopAll();
  5665. threads->joinAll(true,60*1000);
  5666. }
  5667. bool notify(CRemoteClientHandler *_client, MemoryBuffer &msg)
  5668. {
  5669. Linked<CRemoteClientHandler> client;
  5670. client.set(_client);
  5671. if (TF_TRACE_FULL)
  5672. PROGLOG("notify %d", msg.length());
  5673. if (msg.length())
  5674. {
  5675. if (TF_TRACE_FULL)
  5676. PROGLOG("notify CRemoteClientHandler(%p), msg length=%u", _client, msg.length());
  5677. cCommandProcessor::cCommandProcessorParams params;
  5678. params.client = client.getClear();
  5679. params.msg.swapWith(msg);
  5680. /* This can block because the thread pool is full and therefore block the selecthandler
  5681. * This is akin to the main server blocking post accept() for the same reason.
  5682. */
  5683. threads->start(&params);
  5684. }
  5685. else
  5686. onCloseSocket(client,3); // removes owned handles
  5687. return false;
  5688. }
  5689. void addClient(CRemoteClientHandler *client)
  5690. {
  5691. if (client&&client->socket)
  5692. selecthandler->add(client->socket,SELECTMODE_READ,client);
  5693. }
  5694. void checkTimeout()
  5695. {
  5696. if (msTick()-clientcounttick>1000*60*60)
  5697. {
  5698. CriticalBlock block(ClientCountSect);
  5699. if (TF_TRACE_CLIENT_STATS && (ClientCount || MaxClientCount))
  5700. PROGLOG("Client count = %d, max = %d", ClientCount, MaxClientCount);
  5701. clientcounttick = msTick();
  5702. MaxClientCount = ClientCount;
  5703. if (closedclients)
  5704. {
  5705. if (TF_TRACE_CLIENT_STATS)
  5706. PROGLOG("Closed client count = %d",closedclients);
  5707. closedclients = 0;
  5708. }
  5709. }
  5710. CriticalBlock block(sect);
  5711. ForEachItemInRev(i,clients)
  5712. {
  5713. CRemoteClientHandler &client = clients.item(i);
  5714. if (client.timedOut())
  5715. {
  5716. StringBuffer s;
  5717. bool ok = client.getInfo(s); // will spot duff sockets
  5718. if (ok&&(client.openFiles.ordinality()!=0))
  5719. {
  5720. if (TF_TRACE_CLIENT_CONN && client.inactiveTimedOut())
  5721. WARNLOG("Inactive %s",s.str());
  5722. }
  5723. else
  5724. {
  5725. #ifndef _DEBUG
  5726. if (TF_TRACE_CLIENT_CONN)
  5727. #endif
  5728. PROGLOG("Timing out %s",s.str());
  5729. closedclients++;
  5730. onCloseSocket(&client,4); // removes owned handles
  5731. }
  5732. }
  5733. }
  5734. }
  5735. void getInfo(StringBuffer &info, unsigned level=1)
  5736. {
  5737. {
  5738. CriticalBlock block(ClientCountSect);
  5739. info.append(VERSTRING).append('\n');
  5740. info.appendf("Client count = %d\n",ClientCount);
  5741. info.appendf("Max client count = %d",MaxClientCount);
  5742. }
  5743. CriticalBlock block(sect);
  5744. ForEachItemIn(i,clients)
  5745. {
  5746. info.newline().append(i).append(": ");
  5747. clients.item(i).getInfo(info);
  5748. }
  5749. info.newline().appendf("Running threads: %u", threadRunningCount());
  5750. info.newline();
  5751. stdCmdThrottler.getInfo(info);
  5752. info.newline();
  5753. slowCmdThrottler.getInfo(info);
  5754. clientStatsTable.getInfo(info, level);
  5755. }
  5756. unsigned threadRunningCount()
  5757. {
  5758. if (!threads)
  5759. return 0;
  5760. return threads->runningCount();
  5761. }
  5762. unsigned idleTime()
  5763. {
  5764. unsigned t = (unsigned)atomic_read(&globallasttick);
  5765. return msTick()-t;
  5766. }
  5767. void setThrottle(ThrottleClass throttleClass, unsigned limit, unsigned delayMs, unsigned cpuThreshold, unsigned queueLimit)
  5768. {
  5769. switch (throttleClass)
  5770. {
  5771. case ThrottleStd:
  5772. stdCmdThrottler.configure(limit, delayMs, cpuThreshold, queueLimit);
  5773. break;
  5774. case ThrottleSlow:
  5775. slowCmdThrottler.configure(limit, delayMs, cpuThreshold, queueLimit);
  5776. break;
  5777. default:
  5778. {
  5779. StringBuffer availableClasses("{ ");
  5780. for (unsigned c=0; c<ThrottleClassMax; c++)
  5781. {
  5782. availableClasses.append(c).append(" = ").append(getThrottleClassText((ThrottleClass)c));
  5783. if (c+1<ThrottleClassMax)
  5784. availableClasses.append(", ");
  5785. }
  5786. availableClasses.append(" }");
  5787. throw MakeStringException(0, "Unknown throttle class: %u, available classes are: %s", (unsigned)throttleClass, availableClasses.str());
  5788. }
  5789. }
  5790. }
  5791. StringBuffer &getStats(StringBuffer &stats, bool reset)
  5792. {
  5793. CriticalBlock block(sect);
  5794. stdCmdThrottler.getStats(stats, reset).newline();
  5795. slowCmdThrottler.getStats(stats, reset);
  5796. if (reset)
  5797. clientStatsTable.reset();
  5798. return stats;
  5799. }
  5800. };
  5801. IRemoteFileServer * createRemoteFileServer(unsigned maxThreads, unsigned maxThreadsDelayMs, unsigned maxAsyncCopy)
  5802. {
  5803. #if SIMULATE_PACKETLOSS
  5804. errorSimulationOn = false;
  5805. #endif
  5806. return new CRemoteFileServer(maxThreads, maxThreadsDelayMs, maxAsyncCopy);
  5807. }
  5808. #ifdef _USE_CPPUNIT
  5809. #include "unittests.hpp"
  5810. #include "rmtfile.hpp"
  5811. static unsigned serverPort = DAFILESRV_PORT+1; // do not use standard port, which if in a URL will be converted to local parth if IP is local
  5812. static StringBuffer basePath;
  5813. static Owned<CSimpleInterface> serverThread;
  5814. class RemoteFileTest : public CppUnit::TestFixture
  5815. {
  5816. CPPUNIT_TEST_SUITE(RemoteFileTest);
  5817. CPPUNIT_TEST(testRemoteFilename);
  5818. CPPUNIT_TEST(testStartServer);
  5819. CPPUNIT_TEST(testBasicFunctionality);
  5820. CPPUNIT_TEST(testCopy);
  5821. CPPUNIT_TEST(testOther);
  5822. CPPUNIT_TEST(testConfiguration);
  5823. CPPUNIT_TEST(testDirectoryMonitoring);
  5824. CPPUNIT_TEST(testFinish);
  5825. CPPUNIT_TEST_SUITE_END();
  5826. size32_t testLen = 1024;
  5827. protected:
  5828. void testRemoteFilename()
  5829. {
  5830. const char *rfns = "//1.2.3.4/dir1/file1|//1.2.3.4:7100/dir1/file1,"
  5831. "//1.2.3.4:7100/dir1/file1|//1.2.3.4:7100/dir1/file1,"
  5832. "//1.2.3.4/c$/dir1/file1|//1.2.3.4:7100/c$/dir1/file1,"
  5833. "//1.2.3.4:7100/c$/dir1/file1|//1.2.3.4:7100/c$/dir1/file1,"
  5834. "//1.2.3.4:7100/d$/dir1/file1|//1.2.3.4:7100/d$/dir1/file1";
  5835. StringArray tests;
  5836. tests.appendList(rfns, ",");
  5837. ForEachItemIn(i, tests)
  5838. {
  5839. StringArray inOut;
  5840. const char *pair = tests.item(i);
  5841. inOut.appendList(pair, "|");
  5842. const char *rfn = inOut.item(0);
  5843. const char *expected = inOut.item(1);
  5844. Owned<IFile> iFile = createIFile(rfn);
  5845. const char *res = iFile->queryFilename();
  5846. if (!streq(expected, res))
  5847. {
  5848. StringBuffer errMsg("testRemoteFilename MISMATCH");
  5849. errMsg.newline().append("Expected: ").append(expected);
  5850. errMsg.newline().append("Got: ").append(res);
  5851. PROGLOG("%s", errMsg.str());
  5852. CPPUNIT_ASSERT_MESSAGE(errMsg.str(), 0);
  5853. }
  5854. else
  5855. PROGLOG("MATCH: %s", res);
  5856. }
  5857. }
  5858. void testStartServer()
  5859. {
  5860. Owned<ISocket> socket;
  5861. unsigned endPort = MP_END_PORT;
  5862. while (1)
  5863. {
  5864. try
  5865. {
  5866. socket.setown(ISocket::create(serverPort));
  5867. break;
  5868. }
  5869. catch (IJSOCK_Exception *e)
  5870. {
  5871. if (e->errorCode() != JSOCKERR_port_in_use)
  5872. {
  5873. StringBuffer eStr;
  5874. e->errorMessage(eStr);
  5875. e->Release();
  5876. CPPUNIT_ASSERT_MESSAGE(eStr.str(), 0);
  5877. }
  5878. else if (serverPort == endPort)
  5879. {
  5880. e->Release();
  5881. CPPUNIT_ASSERT_MESSAGE("Could not find a free port to use for remote file server", 0);
  5882. }
  5883. }
  5884. ++serverPort;
  5885. }
  5886. basePath.append("//");
  5887. SocketEndpoint ep(serverPort);
  5888. ep.getUrlStr(basePath);
  5889. char cpath[_MAX_DIR];
  5890. if (!GetCurrentDirectory(_MAX_DIR, cpath))
  5891. CPPUNIT_ASSERT_MESSAGE("Current directory path too big", 0);
  5892. else
  5893. basePath.append(cpath);
  5894. addPathSepChar(basePath);
  5895. PROGLOG("basePath = %s", basePath.str());
  5896. class CServerThread : public CSimpleInterface, implements IThreaded
  5897. {
  5898. CThreaded threaded;
  5899. Owned<CRemoteFileServer> server;
  5900. Linked<ISocket> socket;
  5901. public:
  5902. CServerThread(CRemoteFileServer *_server, ISocket *_socket) : server(_server), socket(_socket), threaded("CServerThread")
  5903. {
  5904. threaded.init(this);
  5905. }
  5906. ~CServerThread()
  5907. {
  5908. threaded.join();
  5909. }
  5910. // IThreaded
  5911. virtual void threadmain() override
  5912. {
  5913. DAFSConnectCfg sslCfg = SSLNone;
  5914. server->run(sslCfg, socket, nullptr);
  5915. }
  5916. };
  5917. enableDafsAuthentication(false);
  5918. Owned<IRemoteFileServer> server = createRemoteFileServer();
  5919. serverThread.setown(new CServerThread(QUERYINTERFACE(server.getClear(), CRemoteFileServer), socket.getClear()));
  5920. }
  5921. void testBasicFunctionality()
  5922. {
  5923. VStringBuffer filePath("%s%s", basePath.str(), "file1");
  5924. // create file
  5925. Owned<IFile> iFile = createIFile(filePath);
  5926. CPPUNIT_ASSERT(iFile);
  5927. Owned<IFileIO> iFileIO = iFile->open(IFOcreate);
  5928. CPPUNIT_ASSERT(iFileIO);
  5929. // write out 1k of random data and crc
  5930. MemoryBuffer mb;
  5931. char *buf = (char *)mb.reserveTruncate(testLen);
  5932. for (unsigned b=0; b<1024; b++)
  5933. buf[b] = getRandom()%256;
  5934. CRC32 crc;
  5935. crc.tally(testLen, buf);
  5936. unsigned writeCrc = crc.get();
  5937. size32_t sz = iFileIO->write(0, testLen, buf);
  5938. CPPUNIT_ASSERT(sz == testLen);
  5939. // close file
  5940. iFileIO.clear();
  5941. // validate remote crc
  5942. CPPUNIT_ASSERT(writeCrc == iFile->getCRC());
  5943. // exists
  5944. CPPUNIT_ASSERT(iFile->exists());
  5945. // validate size
  5946. CPPUNIT_ASSERT(iFile->size() == testLen);
  5947. // read back and validate read data's crc against written
  5948. iFileIO.setown(iFile->open(IFOread));
  5949. CPPUNIT_ASSERT(iFileIO);
  5950. sz = iFileIO->read(0, testLen, buf);
  5951. iFileIO.clear();
  5952. CPPUNIT_ASSERT(sz == testLen);
  5953. crc.reset();
  5954. crc.tally(testLen, buf);
  5955. CPPUNIT_ASSERT(writeCrc == crc.get());
  5956. }
  5957. void testCopy()
  5958. {
  5959. VStringBuffer filePath("%s%s", basePath.str(), "file1");
  5960. Owned<IFile> iFile = createIFile(filePath);
  5961. // test file copy
  5962. VStringBuffer filePathCopy("%s%s", basePath.str(), "file1copy");
  5963. Owned<IFile> iFile1Copy = createIFile(filePathCopy);
  5964. iFile->copyTo(iFile1Copy);
  5965. // read back copy and validate read data's crc against written
  5966. Owned<IFileIO> iFileIO = iFile1Copy->open(IFOreadwrite); // open read/write for appendFile in next step.
  5967. CPPUNIT_ASSERT(iFileIO);
  5968. MemoryBuffer mb;
  5969. char *buf = (char *)mb.reserveTruncate(testLen);
  5970. size32_t sz = iFileIO->read(0, testLen, buf);
  5971. CPPUNIT_ASSERT(sz == testLen);
  5972. CRC32 crc;
  5973. crc.tally(testLen, buf);
  5974. CPPUNIT_ASSERT(iFile->getCRC() == crc.get());
  5975. // check appendFile functionality. NB after this "file1copy" should be 2*testLen
  5976. CPPUNIT_ASSERT(testLen == iFileIO->appendFile(iFile));
  5977. iFileIO.clear();
  5978. // validate new size
  5979. CPPUNIT_ASSERT(iFile1Copy->size() == 2 * testLen);
  5980. // setSize test, truncate copy to original size
  5981. iFileIO.setown(iFile1Copy->open(IFOreadwrite));
  5982. iFileIO->setSize(testLen);
  5983. // validate new size
  5984. CPPUNIT_ASSERT(iFile1Copy->size() == testLen);
  5985. }
  5986. void testOther()
  5987. {
  5988. VStringBuffer filePath("%s%s", basePath.str(), "file1");
  5989. Owned<IFile> iFile = createIFile(filePath);
  5990. // rename
  5991. iFile->rename("file2");
  5992. // create a directory
  5993. VStringBuffer subDirPath("%s%s", basePath.str(), "subdir1");
  5994. Owned<IFile> subDirIFile = createIFile(subDirPath);
  5995. subDirIFile->createDirectory();
  5996. // check isDirectory result
  5997. CPPUNIT_ASSERT(subDirIFile->isDirectory());
  5998. // move previous created and renamed file into new sub-directory
  5999. // ensure not present before move
  6000. VStringBuffer subDirFilePath("%s/%s", subDirPath.str(), "file2");
  6001. Owned<IFile> iFile2 = createIFile(subDirFilePath);
  6002. iFile2->remove();
  6003. iFile->move(subDirFilePath);
  6004. // count sub-directory files with a wildcard
  6005. unsigned count=0;
  6006. Owned<IDirectoryIterator> iter = subDirIFile->directoryFiles("*2");
  6007. ForEach(*iter)
  6008. ++count;
  6009. CPPUNIT_ASSERT(1 == count);
  6010. // check isFile result
  6011. CPPUNIT_ASSERT(iFile2->isFile());
  6012. // validate isReadOnly before after setting
  6013. CPPUNIT_ASSERT(!iFile2->isReadOnly());
  6014. iFile2->setReadOnly(true);
  6015. CPPUNIT_ASSERT(iFile2->isReadOnly());
  6016. // get/set Time and validate result
  6017. CDateTime createTime, modifiedTime, accessedTime;
  6018. CPPUNIT_ASSERT(subDirIFile->getTime(&createTime, &modifiedTime, &accessedTime));
  6019. CDateTime newModifiedTime = modifiedTime;
  6020. newModifiedTime.adjustTime(-86400); // -1 day
  6021. CPPUNIT_ASSERT(subDirIFile->setTime(&createTime, &newModifiedTime, &accessedTime));
  6022. CPPUNIT_ASSERT(subDirIFile->getTime(&createTime, &modifiedTime, &accessedTime));
  6023. CPPUNIT_ASSERT(modifiedTime == newModifiedTime);
  6024. // test set file permissions
  6025. iFile2->setFilePermissions(0777);
  6026. }
  6027. void testConfiguration()
  6028. {
  6029. SocketEndpoint ep(serverPort); // test trace open connections
  6030. CPPUNIT_ASSERT(setDafileSvrTraceFlags(ep, 0x08));
  6031. StringBuffer infoStr;
  6032. CPPUNIT_ASSERT(RFEnoerror == getDafileSvrInfo(ep, 10, infoStr));
  6033. CPPUNIT_ASSERT(RFEnoerror == setDafileSvrThrottleLimit(ep, ThrottleStd, DEFAULT_STDCMD_PARALLELREQUESTLIMIT+1, DEFAULT_STDCMD_THROTTLEDELAYMS+1, DEFAULT_STDCMD_THROTTLECPULIMIT+1, DEFAULT_STDCMD_THROTTLEQUEUELIMIT+1));
  6034. }
  6035. void testDirectoryMonitoring()
  6036. {
  6037. VStringBuffer subDirPath("%s%s", basePath.str(), "subdir1");
  6038. Owned<IFile> subDirIFile = createIFile(subDirPath);
  6039. subDirIFile->createDirectory();
  6040. VStringBuffer filePath("%s/%s", subDirPath.str(), "file1");
  6041. class CDelayedFileCreate : implements IThreaded
  6042. {
  6043. CThreaded threaded;
  6044. StringAttr filePath;
  6045. Semaphore doneSem;
  6046. public:
  6047. CDelayedFileCreate(const char *_filePath) : filePath(_filePath), threaded("CDelayedFileCreate")
  6048. {
  6049. threaded.init(this);
  6050. }
  6051. ~CDelayedFileCreate()
  6052. {
  6053. stop();
  6054. }
  6055. void stop()
  6056. {
  6057. doneSem.signal();
  6058. threaded.join();
  6059. }
  6060. // IThreaded impl.
  6061. virtual void threadmain() override
  6062. {
  6063. MilliSleep(1000); // give monitorDirectory a chance to be monitoring
  6064. // create file
  6065. Owned<IFile> iFile = createIFile(filePath);
  6066. CPPUNIT_ASSERT(iFile);
  6067. Owned<IFileIO> iFileIO = iFile->open(IFOcreate);
  6068. CPPUNIT_ASSERT(iFileIO);
  6069. iFileIO.clear();
  6070. doneSem.wait(60 * 1000);
  6071. CPPUNIT_ASSERT(iFile->remove());
  6072. }
  6073. } delayedFileCreate(filePath);
  6074. Owned<IDirectoryDifferenceIterator> iter = subDirIFile->monitorDirectory(nullptr, nullptr, false, false, 2000, 60 * 1000);
  6075. ForEach(*iter)
  6076. {
  6077. StringBuffer fname;
  6078. iter->getName(fname);
  6079. PROGLOG("fname = %s", fname.str());
  6080. }
  6081. delayedFileCreate.stop();
  6082. }
  6083. void testFinish()
  6084. {
  6085. // clearup
  6086. VStringBuffer filePathCopy("%s%s", basePath.str(), "file1copy");
  6087. Owned<IFile> iFile1Copy = createIFile(filePathCopy);
  6088. CPPUNIT_ASSERT(iFile1Copy->remove());
  6089. VStringBuffer subDirPath("%s%s", basePath.str(), "subdir1");
  6090. VStringBuffer subDirFilePath("%s/%s", subDirPath.str(), "file2");
  6091. Owned<IFile> iFile2 = createIFile(subDirFilePath);
  6092. CPPUNIT_ASSERT(iFile2->remove());
  6093. Owned<IFile> subDirIFile = createIFile(subDirPath);
  6094. CPPUNIT_ASSERT(subDirIFile->remove());
  6095. SocketEndpoint ep(serverPort);
  6096. Owned<ISocket> sock = ISocket::connect_timeout(ep, 60 * 1000);
  6097. CPPUNIT_ASSERT(RFEnoerror == stopRemoteServer(sock));
  6098. serverThread.clear();
  6099. }
  6100. };
  6101. CPPUNIT_TEST_SUITE_REGISTRATION( RemoteFileTest );
  6102. CPPUNIT_TEST_SUITE_NAMED_REGISTRATION( RemoteFileTest, "RemoteFileTests" );
  6103. #endif // _USE_CPPUNIT