sockfile.cpp 255 KB

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