sockfile.cpp 262 KB

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