sockfile.cpp 247 KB

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