sockfile.cpp 246 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441
  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. handleFirstRequest();
  1754. size32_t cursorLength;
  1755. reply.read(cursorLength);
  1756. if (!cursorLength)
  1757. {
  1758. eof = true;
  1759. return;
  1760. }
  1761. MemoryBuffer mrequest;
  1762. MemoryBuffer newReply;
  1763. initSendBuffer(mrequest);
  1764. mrequest.append((RemoteFileCommandType)RFCStreamRead);
  1765. VStringBuffer json("{ \"handle\" : %u }", handle);
  1766. mrequest.append(json.length(), json.str());
  1767. sendRemoteCommand(mrequest, newReply);
  1768. unsigned newHandle;
  1769. newReply.read(newHandle);
  1770. if (newHandle == handle)
  1771. {
  1772. reply.swapWith(newReply);
  1773. reply.read(bufRemaining);
  1774. eof = (bufRemaining == 0);
  1775. }
  1776. else
  1777. {
  1778. assertex(newHandle == 0);
  1779. sendRequest(cursorLength, reply.readDirect(cursorLength));
  1780. }
  1781. }
  1782. void sendRequest(unsigned cursorLen, const void *cursorData)
  1783. {
  1784. MemoryBuffer mrequest;
  1785. initSendBuffer(mrequest);
  1786. mrequest.append((RemoteFileCommandType)RFCStreamRead);
  1787. mrequest.append(request.length(), request.str());
  1788. if (cursorLen)
  1789. {
  1790. StringBuffer cursorInfo;
  1791. cursorInfo.append(",\"cursorBin\": \"");
  1792. JBASE64_Encode(cursorData, cursorLen, cursorInfo, false);
  1793. cursorInfo.append("\"\n");
  1794. mrequest.append(cursorInfo.length(), cursorInfo.str());
  1795. }
  1796. if (TF_TRACE_FULL)
  1797. PROGLOG("req = <%s}>", request.str());
  1798. mrequest.append(3, " \n}");
  1799. sendRemoteCommand(mrequest, reply);
  1800. reply.read(handle);
  1801. reply.read(bufRemaining);
  1802. eof = (bufRemaining == 0);
  1803. }
  1804. StringBuffer request;
  1805. MemoryBuffer reply;
  1806. unsigned handle = 0;
  1807. size32_t bufRemaining = 0;
  1808. unsigned bufPos = 0;
  1809. bool eof = false;
  1810. bool firstRequest = true;
  1811. std::unordered_map<std::string, std::string> virtualFields;
  1812. };
  1813. class CRemoteFilteredFileIO : public CRemoteFilteredFileIOBase
  1814. {
  1815. public:
  1816. // Really a stream, but life (maybe) easier elsewhere if looks like a file
  1817. // Sometime should refactor to be based on ISerialStream instead - or maybe IRowStream.
  1818. CRemoteFilteredFileIO(SocketEndpoint &ep, const char *filename, IOutputMetaData *actual, IOutputMetaData *projected, const RowFilter &fieldFilters, bool compressed, bool grouped, unsigned __int64 chooseN)
  1819. : CRemoteFilteredFileIOBase(ep, filename, actual, projected, fieldFilters, chooseN)
  1820. {
  1821. // NB: inputGrouped == outputGrouped for now, but may want output to be ungrouped
  1822. request.appendf(",\n \"kind\" : \"diskread\",\n"
  1823. " \"compressed\" : \"%s\",\n"
  1824. " \"inputGrouped\" : \"%s\",\n"
  1825. " \"outputGrouped\" : \"%s\"", boolToStr(compressed), boolToStr(grouped), boolToStr(grouped));
  1826. }
  1827. };
  1828. class CRemoteFilteredRowStream : public CRemoteFilteredFileIO, implements IRowStream
  1829. {
  1830. public:
  1831. CRemoteFilteredRowStream(const RtlRecord &_recInfo, SocketEndpoint &ep, const char * filename, IOutputMetaData *actual, IOutputMetaData *projected, const RowFilter &fieldFilters, bool compressed, bool grouped)
  1832. : CRemoteFilteredFileIO(ep, filename, actual, projected, fieldFilters, compressed, grouped, 0), recInfo(_recInfo)
  1833. {
  1834. }
  1835. virtual const byte *queryNextRow() // NOTE - rows returned must NOT be freed
  1836. {
  1837. if (!bufRemaining && !eof)
  1838. refill();
  1839. if (eof)
  1840. return nullptr;
  1841. unsigned len = recInfo.getRecordSize(reply.readDirect(0));
  1842. bufPos += len;
  1843. bufRemaining -= len;
  1844. return reply.readDirect(len);
  1845. }
  1846. virtual void stop() override
  1847. {
  1848. close();
  1849. eof = true;
  1850. }
  1851. protected:
  1852. const RtlRecord &recInfo;
  1853. };
  1854. extern IRemoteFileIO *createRemoteFilteredFile(SocketEndpoint &ep, const char * filename, IOutputMetaData *actual, IOutputMetaData *projected, const RowFilter &fieldFilters, bool compressed, bool grouped, unsigned __int64 chooseN)
  1855. {
  1856. try
  1857. {
  1858. return new CRemoteFilteredFileIO(ep, filename, actual, projected, fieldFilters, compressed, grouped, chooseN);
  1859. }
  1860. catch (IException *e)
  1861. {
  1862. EXCLOG(e, nullptr);
  1863. e->Release();
  1864. }
  1865. return nullptr;
  1866. }
  1867. class CRemoteFilteredKeyIO : public CRemoteFilteredFileIOBase
  1868. {
  1869. public:
  1870. // Really a stream, but life (maybe) easier elsewhere if looks like a file
  1871. // Sometime should refactor to be based on ISerialStream instead - or maybe IRowStream.
  1872. CRemoteFilteredKeyIO(SocketEndpoint &ep, const char *filename, IOutputMetaData *actual, IOutputMetaData *projected, const RowFilter &fieldFilters, unsigned __int64 chooseN)
  1873. : CRemoteFilteredFileIOBase(ep, filename, actual, projected, fieldFilters, chooseN)
  1874. {
  1875. request.appendf(",\n \"kind\" : \"indexread\"");
  1876. }
  1877. };
  1878. class CRemoteFilteredKeyCountIO : public CRemoteFilteredFileIOBase
  1879. {
  1880. public:
  1881. // Really a stream, but life (maybe) easier elsewhere if looks like a file
  1882. // Sometime should refactor to be based on ISerialStream instead - or maybe IRowStream.
  1883. CRemoteFilteredKeyCountIO(SocketEndpoint &ep, const char *filename, IOutputMetaData *actual, const RowFilter &fieldFilters, unsigned __int64 rowLimit)
  1884. : CRemoteFilteredFileIOBase(ep, filename, actual, actual, fieldFilters, rowLimit)
  1885. {
  1886. request.appendf(",\n \"kind\" : \"indexcount\"");
  1887. }
  1888. };
  1889. class CRemoteKey : public CSimpleInterfaceOf<IIndexLookup>
  1890. {
  1891. Owned<IRemoteFileIO> iRemoteFileIO;
  1892. offset_t pos = 0;
  1893. Owned<ISourceRowPrefetcher> prefetcher;
  1894. CThorContiguousRowBuffer prefetchBuffer;
  1895. Owned<ISerialStream> strm;
  1896. bool pending = false;
  1897. SocketEndpoint ep;
  1898. StringAttr filename;
  1899. Linked<IOutputMetaData> actual, projected;
  1900. RowFilter fieldFilters;
  1901. public:
  1902. CRemoteKey(SocketEndpoint &_ep, const char *_filename, IOutputMetaData *_actual, IOutputMetaData *_projected, const RowFilter &_fieldFilters, unsigned __int64 rowLimit)
  1903. : ep(_ep), filename(_filename), actual(_actual), projected(_projected)
  1904. {
  1905. for (unsigned f=0; f<_fieldFilters.numFilterFields(); f++)
  1906. fieldFilters.addFilter(OLINK(_fieldFilters.queryFilter(f)));
  1907. iRemoteFileIO.setown(new CRemoteFilteredKeyIO(ep, filename, actual, projected, fieldFilters, rowLimit));
  1908. if (!iRemoteFileIO)
  1909. throw MakeStringException(0, "Unable to open remote key part: '%s'", filename.get());
  1910. strm.setown(createFileSerialStream(iRemoteFileIO));
  1911. prefetcher.setown(projected->createDiskPrefetcher());
  1912. assertex(prefetcher);
  1913. prefetchBuffer.setStream(strm);
  1914. }
  1915. // IIndexLookup
  1916. virtual void ensureAvailable() override
  1917. {
  1918. iRemoteFileIO->ensureAvailable(); // will throw an exception if fails
  1919. }
  1920. virtual unsigned __int64 getCount() override
  1921. {
  1922. return checkCount(0);
  1923. }
  1924. virtual unsigned __int64 checkCount(unsigned __int64 limit) override
  1925. {
  1926. Owned<IFileIO> iFileIO = new CRemoteFilteredKeyCountIO(ep, filename, actual, fieldFilters, limit);
  1927. unsigned __int64 result;
  1928. iFileIO->read(0, sizeof(result), &result);
  1929. return result;
  1930. }
  1931. virtual const void *nextKey() override
  1932. {
  1933. if (pending)
  1934. prefetchBuffer.finishedRow();
  1935. if (prefetchBuffer.eos())
  1936. return nullptr;
  1937. prefetcher->readAhead(prefetchBuffer);
  1938. pending = true;
  1939. return prefetchBuffer.queryRow();
  1940. }
  1941. virtual unsigned querySeeks() const override { return 0; } // not sure how best to handle these, perhaps should log/record somewhere on server-side
  1942. virtual unsigned queryScans() const override { return 0; }
  1943. virtual unsigned querySkips() const override { return 0; }
  1944. };
  1945. extern IIndexLookup *createRemoteFilteredKey(SocketEndpoint &ep, const char * filename, IOutputMetaData *actual, IOutputMetaData *projected, const RowFilter &fieldFilters, unsigned __int64 chooseN)
  1946. {
  1947. try
  1948. {
  1949. return new CRemoteKey(ep, filename, actual, projected, fieldFilters, chooseN);
  1950. }
  1951. catch (IException *e)
  1952. {
  1953. EXCLOG(e, nullptr);
  1954. e->Release();
  1955. }
  1956. return nullptr;
  1957. }
  1958. class CRemoteFile : public CRemoteBase, implements IFile
  1959. {
  1960. StringAttr remotefilename;
  1961. unsigned flags;
  1962. bool isShareSet;
  1963. public:
  1964. IMPLEMENT_IINTERFACE
  1965. CRemoteFile(const SocketEndpoint &_ep, const char * _filename)
  1966. : CRemoteBase(_ep, _filename)
  1967. {
  1968. flags = ((unsigned)IFSHread)|((S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH|S_IWOTH)<<16);
  1969. isShareSet = false;
  1970. if (filename.length()>2 && isPathSepChar(filename[0]) && isShareChar(filename[2]))
  1971. {
  1972. VStringBuffer winDriveFilename("%c:%s", filename[1], filename+3);
  1973. filename.set(winDriveFilename);
  1974. }
  1975. }
  1976. bool exists()
  1977. {
  1978. MemoryBuffer sendBuffer;
  1979. initSendBuffer(sendBuffer);
  1980. MemoryBuffer replyBuffer;
  1981. sendBuffer.append((RemoteFileCommandType)RFCexists).append(filename);
  1982. sendRemoteCommand(sendBuffer, replyBuffer);
  1983. bool ok;
  1984. replyBuffer.read(ok);
  1985. return ok;
  1986. }
  1987. bool getTime(CDateTime * createTime, CDateTime * modifiedTime, CDateTime * accessedTime)
  1988. {
  1989. CDateTime dummyTime;
  1990. if (!createTime)
  1991. createTime = &dummyTime;
  1992. if (!modifiedTime)
  1993. modifiedTime = &dummyTime;
  1994. if (!accessedTime)
  1995. accessedTime = &dummyTime;
  1996. MemoryBuffer sendBuffer;
  1997. initSendBuffer(sendBuffer);
  1998. MemoryBuffer replyBuffer;
  1999. sendBuffer.append((RemoteFileCommandType)RFCgettime).append(filename);
  2000. sendRemoteCommand(sendBuffer, replyBuffer);
  2001. bool ok;
  2002. replyBuffer.read(ok);
  2003. if (ok) {
  2004. createTime->deserialize(replyBuffer);
  2005. modifiedTime->deserialize(replyBuffer);
  2006. accessedTime->deserialize(replyBuffer);
  2007. }
  2008. return ok;
  2009. }
  2010. bool setTime(const CDateTime * createTime, const CDateTime * modifiedTime, const CDateTime * accessedTime)
  2011. {
  2012. MemoryBuffer sendBuffer;
  2013. initSendBuffer(sendBuffer);
  2014. MemoryBuffer replyBuffer;
  2015. sendBuffer.append((RemoteFileCommandType)RFCsettime).append(filename);
  2016. if (createTime)
  2017. {
  2018. sendBuffer.append((bool)true);
  2019. createTime->serialize(sendBuffer);
  2020. }
  2021. else
  2022. sendBuffer.append((bool)false);
  2023. if (modifiedTime)
  2024. {
  2025. sendBuffer.append((bool)true);
  2026. modifiedTime->serialize(sendBuffer);
  2027. }
  2028. else
  2029. sendBuffer.append((bool)false);
  2030. if (accessedTime)
  2031. {
  2032. sendBuffer.append((bool)true);
  2033. accessedTime->serialize(sendBuffer);
  2034. }
  2035. else
  2036. sendBuffer.append((bool)false);
  2037. sendRemoteCommand(sendBuffer, replyBuffer);
  2038. bool ok;
  2039. replyBuffer.read(ok);
  2040. return ok;
  2041. }
  2042. fileBool isDirectory()
  2043. {
  2044. MemoryBuffer sendBuffer;
  2045. initSendBuffer(sendBuffer);
  2046. MemoryBuffer replyBuffer;
  2047. sendBuffer.append((RemoteFileCommandType)RFCisdirectory).append(filename);
  2048. sendRemoteCommand(sendBuffer, replyBuffer);
  2049. unsigned ret;
  2050. replyBuffer.read(ret);
  2051. return (fileBool)ret;
  2052. }
  2053. fileBool isFile()
  2054. {
  2055. MemoryBuffer sendBuffer;
  2056. initSendBuffer(sendBuffer);
  2057. MemoryBuffer replyBuffer;
  2058. sendBuffer.append((RemoteFileCommandType)RFCisfile).append(filename);
  2059. sendRemoteCommand(sendBuffer, replyBuffer);
  2060. unsigned ret;
  2061. replyBuffer.read(ret);
  2062. return (fileBool)ret;
  2063. }
  2064. fileBool isReadOnly()
  2065. {
  2066. MemoryBuffer sendBuffer;
  2067. initSendBuffer(sendBuffer);
  2068. MemoryBuffer replyBuffer;
  2069. sendBuffer.append((RemoteFileCommandType)RFCisreadonly).append(filename);
  2070. sendRemoteCommand(sendBuffer, replyBuffer);
  2071. unsigned ret;
  2072. replyBuffer.read(ret);
  2073. return (fileBool)ret;
  2074. }
  2075. IFileIO * open(IFOmode mode,IFEflags extraFlags=IFEnone);
  2076. IFileIO * openShared(IFOmode mode,IFSHmode shmode,IFEflags extraFlags=IFEnone);
  2077. IFileAsyncIO * openAsync(IFOmode mode) { return NULL; } // not supported
  2078. const char * queryFilename()
  2079. {
  2080. if (remotefilename.isEmpty()) {
  2081. RemoteFilename rfn;
  2082. rfn.setPath(ep,filename);
  2083. StringBuffer path;
  2084. rfn.getRemotePath(path);
  2085. remotefilename.set(path);
  2086. }
  2087. return remotefilename.get();
  2088. }
  2089. void resetLocalFilename(const char *name)
  2090. {
  2091. remotefilename.clear();
  2092. filename.set(name);
  2093. }
  2094. bool remove()
  2095. {
  2096. MemoryBuffer sendBuffer;
  2097. initSendBuffer(sendBuffer);
  2098. MemoryBuffer replyBuffer;
  2099. sendBuffer.append((RemoteFileCommandType)RFCremove).append(filename);
  2100. sendRemoteCommand(sendBuffer, replyBuffer);
  2101. bool ok;
  2102. replyBuffer.read(ok);
  2103. return ok;
  2104. }
  2105. void rename(const char *newname)
  2106. {
  2107. // currently ignores directory on newname (in future versions newname will be required to be tail only and not full path)
  2108. StringBuffer path;
  2109. splitDirTail(filename,path);
  2110. StringBuffer newdir;
  2111. path.append(splitDirTail(newname,newdir));
  2112. if (newdir.length()&&(strcmp(newdir.str(),path.str())!=0))
  2113. WARNLOG("CRemoteFile::rename passed full path '%s' that may not to match original directory '%s'",newname,path.str());
  2114. MemoryBuffer sendBuffer;
  2115. initSendBuffer(sendBuffer);
  2116. MemoryBuffer replyBuffer;
  2117. sendBuffer.append((RemoteFileCommandType)RFCrename).append(filename).append(path);
  2118. sendRemoteCommand(sendBuffer, replyBuffer);
  2119. filename.set(path);
  2120. remotefilename.clear();
  2121. }
  2122. void move(const char *newname)
  2123. {
  2124. // like rename except between directories
  2125. // first create replote path
  2126. if (!newname||!*newname)
  2127. return;
  2128. RemoteFilename destrfn;
  2129. if (isPathSepChar(newname[0])&&isPathSepChar(newname[1])) {
  2130. destrfn.setRemotePath(newname);
  2131. if (!destrfn.queryEndpoint().ipequals(ep)) {
  2132. StringBuffer msg;
  2133. msg.appendf("IFile::move %s to %s, destination node must match source node", queryFilename(), newname);
  2134. throw createDafsException(RFSERR_MoveFailed,msg.str());
  2135. }
  2136. }
  2137. else
  2138. destrfn.setPath(ep,newname);
  2139. StringBuffer dest;
  2140. newname = destrfn.getLocalPath(dest).str();
  2141. MemoryBuffer sendBuffer;
  2142. initSendBuffer(sendBuffer);
  2143. MemoryBuffer replyBuffer;
  2144. StringBuffer path;
  2145. splitDirTail(filename,path);
  2146. StringBuffer newdir;
  2147. const char *newtail = splitDirTail(newname,newdir);
  2148. if (strcmp(newdir.str(),path.str())==0)
  2149. {
  2150. path.append(newtail);
  2151. newname = path;
  2152. sendBuffer.append((RemoteFileCommandType)RFCrename); // use rename if we can (supported on older dafilesrv)
  2153. }
  2154. else
  2155. sendBuffer.append((RemoteFileCommandType)RFCmove);
  2156. sendBuffer.append(filename).append(newname);
  2157. sendRemoteCommand(sendBuffer, replyBuffer);
  2158. filename.set(newname);
  2159. remotefilename.clear();
  2160. }
  2161. void setReadOnly(bool set)
  2162. {
  2163. MemoryBuffer sendBuffer;
  2164. initSendBuffer(sendBuffer);
  2165. MemoryBuffer replyBuffer;
  2166. sendBuffer.append((RemoteFileCommandType)RFCsetreadonly).append(filename).append(set);
  2167. sendRemoteCommand(sendBuffer, replyBuffer);
  2168. }
  2169. void setFilePermissions(unsigned fPerms)
  2170. {
  2171. MemoryBuffer sendBuffer;
  2172. initSendBuffer(sendBuffer);
  2173. MemoryBuffer replyBuffer;
  2174. sendBuffer.append((RemoteFileCommandType)RFCsetfileperms).append(filename).append(fPerms);
  2175. try
  2176. {
  2177. sendRemoteCommand(sendBuffer, replyBuffer);
  2178. }
  2179. catch (IDAFS_Exception *e)
  2180. {
  2181. if (e->errorCode() == RFSERR_InvalidCommand)
  2182. {
  2183. WARNLOG("umask setFilePermissions (0%o) not supported on remote server", fPerms);
  2184. e->Release();
  2185. }
  2186. else
  2187. throw;
  2188. }
  2189. }
  2190. offset_t size()
  2191. {
  2192. #if 1 // faster method (consistant with IFile)
  2193. // do this by using dir call (could be improved with new function but this not *too* bad)
  2194. if (isSpecialPath(filename))
  2195. return 0; // queries deemed to always exist (though don't know size).
  2196. // if needed to get size I guess could use IFileIO method and cache (bit of pain though)
  2197. StringBuffer dir;
  2198. const char *tail = splitDirTail(filename,dir);
  2199. if (!dir.length())
  2200. return false;
  2201. MemoryBuffer sendBuffer;
  2202. initSendBuffer(sendBuffer);
  2203. MemoryBuffer replyBuffer;
  2204. bool includedirs = true;
  2205. bool sub=false;
  2206. {
  2207. //Could be removed with new dafilesrv change [ (stream != 0) ], since this is not streaming.
  2208. Owned<CEndpointCS> crit = dirCSTable->getCrit(ep); // NB dirCSTable doesn't own, last reference will remove from table
  2209. CriticalBlock block(*crit);
  2210. sendBuffer.append((RemoteFileCommandType)RFCgetdir).append(dir).append(tail).append(includedirs).append(sub);
  2211. try
  2212. {
  2213. sendRemoteCommand(sendBuffer, replyBuffer);
  2214. }
  2215. catch (IDAFS_Exception * e)
  2216. {
  2217. if (e->errorCode() == RFSERR_GetDirFailed)
  2218. {
  2219. e->Release();
  2220. return (offset_t)-1;
  2221. }
  2222. else
  2223. throw e;
  2224. }
  2225. }
  2226. // now should be 0 or 1 files returned
  2227. Owned<CRemoteDirectoryIterator> iter = new CRemoteDirectoryIterator(ep, dir.str());
  2228. iter->appendBuf(replyBuffer);
  2229. if (!iter->first())
  2230. return (offset_t)-1;
  2231. return (offset_t) iter->getFileSize();
  2232. #else
  2233. IFileIO * io = open(IFOread);
  2234. offset_t length = (offset_t)-1;
  2235. if (io)
  2236. {
  2237. length = io->size();
  2238. io->Release();
  2239. }
  2240. return length;
  2241. #endif
  2242. }
  2243. bool createDirectory()
  2244. {
  2245. MemoryBuffer sendBuffer;
  2246. initSendBuffer(sendBuffer);
  2247. MemoryBuffer replyBuffer;
  2248. sendBuffer.append((RemoteFileCommandType)RFCcreatedir).append(filename);
  2249. sendRemoteCommand(sendBuffer, replyBuffer);
  2250. bool ok;
  2251. replyBuffer.read(ok);
  2252. return ok;
  2253. }
  2254. virtual IDirectoryIterator *directoryFiles(const char *mask,bool sub,bool includedirs)
  2255. {
  2256. if (mask&&!*mask)
  2257. return createDirectoryIterator("",""); // NULL iterator
  2258. CRemoteDirectoryIterator *ret = new CRemoteDirectoryIterator(ep, filename);
  2259. byte stream = (sub || !mask || containsFileWildcard(mask)) ? 1 : 0; // no point in streaming if mask without wildcards or sub, as will only be <= 1 match.
  2260. Owned<CEndpointCS> crit = dirCSTable->getCrit(ep); // NB dirCSTable doesn't own, last reference will remove from table
  2261. CriticalBlock block(*crit);
  2262. for (;;)
  2263. {
  2264. MemoryBuffer sendBuffer;
  2265. initSendBuffer(sendBuffer);
  2266. MemoryBuffer replyBuffer;
  2267. sendBuffer.append((RemoteFileCommandType)RFCgetdir).append(filename).append(mask?mask:"").append(includedirs).append(sub).append(stream);
  2268. sendRemoteCommand(sendBuffer, replyBuffer);
  2269. if (ret->appendBuf(replyBuffer))
  2270. break;
  2271. stream = 2; // NB: will never get here if streaming was off (if stream==0 above)
  2272. }
  2273. return ret;
  2274. }
  2275. IDirectoryDifferenceIterator *monitorDirectory(
  2276. IDirectoryIterator *prev=NULL, // in (NULL means use current as baseline)
  2277. const char *mask=NULL,
  2278. bool sub=false,
  2279. bool includedirs=false,
  2280. unsigned checkinterval=60*1000,
  2281. unsigned timeout=(unsigned)-1,
  2282. Semaphore *abortsem=NULL) // returns NULL if timed out
  2283. {
  2284. // abortsem not yet supported
  2285. MemoryBuffer sendBuffer;
  2286. initSendBuffer(sendBuffer);
  2287. MemoryBuffer replyBuffer;
  2288. sendBuffer.append((RemoteFileCommandType)RFCmonitordir).append(filename).append(mask?mask:"").append(includedirs).append(sub);
  2289. sendBuffer.append(checkinterval).append(timeout);
  2290. __int64 cancelid=0; // not yet used
  2291. sendBuffer.append(cancelid);
  2292. byte isprev=(prev!=NULL)?1:0;
  2293. sendBuffer.append(isprev);
  2294. if (prev)
  2295. CRemoteDirectoryIterator::serialize(sendBuffer,prev,0,true);
  2296. sendRemoteCommand(sendBuffer, replyBuffer);
  2297. byte status;
  2298. replyBuffer.read(status);
  2299. if (status==1)
  2300. {
  2301. CRemoteDirectoryIterator *iter = new CRemoteDirectoryIterator(ep, filename);
  2302. iter->appendBuf(replyBuffer);
  2303. return iter;
  2304. }
  2305. return NULL;
  2306. }
  2307. bool getInfo(bool &isdir,offset_t &size,CDateTime &modtime)
  2308. {
  2309. // do this by using dir call (could be improved with new function but this not *too* bad)
  2310. StringBuffer dir;
  2311. const char *tail = splitDirTail(filename,dir);
  2312. if (!dir.length())
  2313. return false;
  2314. MemoryBuffer sendBuffer;
  2315. initSendBuffer(sendBuffer);
  2316. MemoryBuffer replyBuffer;
  2317. bool includedirs = true;
  2318. bool sub=false;
  2319. {
  2320. //Could be removed with new dafilesrv change [ (stream != 0) ], since this is not streaming.
  2321. Owned<CEndpointCS> crit = dirCSTable->getCrit(ep); // NB dirCSTable doesn't own, last reference will remove from table
  2322. CriticalBlock block(*crit);
  2323. sendBuffer.append((RemoteFileCommandType)RFCgetdir).append(dir).append(tail).append(includedirs).append(sub);
  2324. sendRemoteCommand(sendBuffer, replyBuffer);
  2325. }
  2326. // now should be 0 or 1 files returned
  2327. Owned<CRemoteDirectoryIterator> iter = new CRemoteDirectoryIterator(ep, dir.str());
  2328. iter->appendBuf(replyBuffer);
  2329. if (!iter->first())
  2330. return false;
  2331. isdir = iter->isDir();
  2332. size = (offset_t) iter->getFileSize();
  2333. iter->getModifiedTime(modtime);
  2334. return true;
  2335. }
  2336. bool setCompression(bool set)
  2337. {
  2338. assertex(!"Need to implement compress()");
  2339. return false;
  2340. }
  2341. offset_t compressedSize()
  2342. {
  2343. assertex(!"Need to implement actualSize()");
  2344. return (offset_t)-1;
  2345. }
  2346. void serialize(MemoryBuffer &tgt)
  2347. {
  2348. throwUnexpected();
  2349. }
  2350. void deserialize(MemoryBuffer &src)
  2351. {
  2352. throwUnexpected();
  2353. }
  2354. unsigned getCRC()
  2355. {
  2356. MemoryBuffer sendBuffer;
  2357. initSendBuffer(sendBuffer);
  2358. MemoryBuffer replyBuffer;
  2359. sendBuffer.append((RemoteFileCommandType)RFCgetcrc).append(filename);
  2360. sendRemoteCommand(sendBuffer, replyBuffer, true, true);
  2361. unsigned crc;
  2362. replyBuffer.read(crc);
  2363. return crc;
  2364. }
  2365. void setCreateFlags(unsigned short cflags)
  2366. {
  2367. flags &= 0xffff;
  2368. flags |= ((unsigned)cflags<<16);
  2369. }
  2370. unsigned short getCreateFlags()
  2371. {
  2372. return (unsigned short)(flags>>16);
  2373. }
  2374. void setShareMode(IFSHmode shmode)
  2375. {
  2376. flags &= ~(IFSHfull|IFSHread);
  2377. flags |= (unsigned)(shmode&(IFSHfull|IFSHread));
  2378. isShareSet = true;
  2379. }
  2380. unsigned short getShareMode()
  2381. {
  2382. return (unsigned short)(flags&0xffff);
  2383. }
  2384. bool getIsShareSet()
  2385. {
  2386. return isShareSet;
  2387. }
  2388. void remoteExtractBlobElements(const char * prefix, ExtractedBlobArray & extracted)
  2389. {
  2390. MemoryBuffer sendBuffer;
  2391. initSendBuffer(sendBuffer);
  2392. sendBuffer.append((RemoteFileCommandType)RFCextractblobelements).append(prefix).append(filename);
  2393. MemoryBuffer replyBuffer;
  2394. sendRemoteCommand(sendBuffer, replyBuffer, true, true); // handles error code
  2395. unsigned n;
  2396. replyBuffer.read(n);
  2397. for (unsigned i=0;i<n;i++) {
  2398. ExtractedBlobInfo *item = new ExtractedBlobInfo;
  2399. item->deserialize(replyBuffer);
  2400. extracted.append(*item);
  2401. }
  2402. }
  2403. bool copySectionAsync(const char *uuid,const RemoteFilename &dest, offset_t toOfs, offset_t fromOfs, offset_t size, ICopyFileProgress *progress, unsigned timeout)
  2404. {
  2405. // now if we get here is it can be assumed the source file is local to where we send the command
  2406. StringBuffer tos;
  2407. dest.getRemotePath(tos);
  2408. MemoryBuffer sendBuffer;
  2409. initSendBuffer(sendBuffer);
  2410. MemoryBuffer replyBuffer;
  2411. sendBuffer.append((RemoteFileCommandType)RFCcopysection).append(uuid).append(queryLocalName()).append(tos).append(toOfs).append(fromOfs).append(size).append(timeout);
  2412. sendRemoteCommand(sendBuffer, replyBuffer);
  2413. unsigned status;
  2414. replyBuffer.read(status);
  2415. if (progress)
  2416. {
  2417. offset_t sizeDone;
  2418. offset_t totalSize;
  2419. replyBuffer.read(sizeDone).read(totalSize);
  2420. progress->onProgress(sizeDone,totalSize);
  2421. }
  2422. return (AsyncCommandStatus)status!=ACScontinue; // should only otherwise be done as errors raised by exception
  2423. }
  2424. void copySection(const RemoteFilename &dest, offset_t toOfs, offset_t fromOfs, offset_t size, ICopyFileProgress *progress, CFflags copyFlags=CFnone)
  2425. {
  2426. StringBuffer uuid;
  2427. genUUID(uuid,true);
  2428. unsigned timeout = 60*1000; // check every minute
  2429. while(!copySectionAsync(uuid.str(),dest,toOfs,fromOfs,size,progress,timeout));
  2430. }
  2431. void copyTo(IFile *dest, size32_t buffersize, ICopyFileProgress *progress, bool usetmp, CFflags copyFlags=CFnone);
  2432. virtual IMemoryMappedFile *openMemoryMapped(offset_t ofs, memsize_t len, bool write)
  2433. {
  2434. return NULL;
  2435. }
  2436. };
  2437. void clientAddSocketToCache(SocketEndpoint &ep,ISocket *socket)
  2438. {
  2439. CriticalBlock block(CConnectionTable::crit);
  2440. if (ConnectionTable)
  2441. ConnectionTable->addLink(ep,socket);
  2442. }
  2443. IFile * createRemoteFile(SocketEndpoint &ep, const char * filename)
  2444. {
  2445. IFile *ret = createFileLocalMount(ep,filename);
  2446. if (ret)
  2447. return ret;
  2448. return new CRemoteFile(ep, filename);
  2449. }
  2450. void clientDisconnectRemoteFile(IFile *file)
  2451. {
  2452. CRemoteFile *cfile = QUERYINTERFACE(file,CRemoteFile);
  2453. if (cfile)
  2454. cfile->disconnect();
  2455. }
  2456. bool clientResetFilename(IFile *file, const char *newname) // returns false if not remote
  2457. {
  2458. CRemoteFile *cfile = QUERYINTERFACE(file,CRemoteFile);
  2459. if (!cfile)
  2460. return false;
  2461. cfile->resetLocalFilename(newname);
  2462. return true;
  2463. }
  2464. extern bool clientAsyncCopyFileSection(const char *uuid,
  2465. IFile *from, // expected to be remote
  2466. RemoteFilename &to,
  2467. offset_t toOfs, // -1 created file and copies to start
  2468. offset_t fromOfs,
  2469. offset_t size,
  2470. ICopyFileProgress *progress,
  2471. unsigned timeout) // returns true when done
  2472. {
  2473. CRemoteFile *cfile = QUERYINTERFACE(from,CRemoteFile);
  2474. if (!cfile) {
  2475. // local - do sync
  2476. from->copySection(to,toOfs,fromOfs,size,progress);
  2477. return true;
  2478. }
  2479. return cfile->copySectionAsync(uuid,to,toOfs,fromOfs, size, progress, timeout);
  2480. }
  2481. //---------------------------------------------------------------------------
  2482. class CRemoteFileIO : implements IFileIO, public CInterface
  2483. {
  2484. protected:
  2485. Linked<CRemoteFile> parent;
  2486. RemoteFileIOHandle handle;
  2487. std::atomic<cycle_t> ioReadCycles;
  2488. std::atomic<cycle_t> ioWriteCycles;
  2489. std::atomic<__uint64> ioReadBytes;
  2490. std::atomic<__uint64> ioWriteBytes;
  2491. std::atomic<__uint64> ioReads;
  2492. std::atomic<__uint64> ioWrites;
  2493. std::atomic<unsigned> ioRetries;
  2494. IFOmode mode;
  2495. compatIFSHmode compatmode;
  2496. IFEflags extraFlags;
  2497. bool disconnectonexit;
  2498. public:
  2499. IMPLEMENT_IINTERFACE
  2500. CRemoteFileIO(CRemoteFile *_parent)
  2501. : parent(_parent), ioReadCycles(0), ioWriteCycles(0), ioReadBytes(0), ioWriteBytes(0), ioReads(0), ioWrites(0), ioRetries(0)
  2502. {
  2503. handle = 0;
  2504. disconnectonexit = false;
  2505. }
  2506. ~CRemoteFileIO()
  2507. {
  2508. if (handle) {
  2509. try {
  2510. close();
  2511. }
  2512. catch (IException *e) {
  2513. StringBuffer s;
  2514. e->errorMessage(s);
  2515. WARNLOG("CRemoteFileIO close file: %s",s.str());
  2516. e->Release();
  2517. }
  2518. }
  2519. if (disconnectonexit)
  2520. parent->disconnect();
  2521. }
  2522. void close()
  2523. {
  2524. if (handle)
  2525. {
  2526. try
  2527. {
  2528. MemoryBuffer sendBuffer;
  2529. initSendBuffer(sendBuffer);
  2530. sendBuffer.append((RemoteFileCommandType)RFCcloseIO).append(handle);
  2531. parent->sendRemoteCommand(sendBuffer,false);
  2532. }
  2533. catch (IDAFS_Exception *e)
  2534. {
  2535. if ((e->errorCode()!=RFSERR_InvalidFileIOHandle)&&(e->errorCode()!=RFSERR_NullFileIOHandle))
  2536. throw;
  2537. e->Release();
  2538. }
  2539. handle = 0;
  2540. }
  2541. }
  2542. RemoteFileIOHandle getHandle() const { return handle; }
  2543. bool open(IFOmode _mode,compatIFSHmode _compatmode,IFEflags _extraFlags=IFEnone)
  2544. {
  2545. MemoryBuffer sendBuffer;
  2546. initSendBuffer(sendBuffer);
  2547. MemoryBuffer replyBuffer;
  2548. const char *localname = parent->queryLocalName();
  2549. localname = skipSpecialPath(localname);
  2550. // also send _extraFlags
  2551. // then also send sMode, cFlags
  2552. unsigned short sMode = parent->getShareMode();
  2553. unsigned short cFlags = parent->getCreateFlags();
  2554. if (!(parent->getIsShareSet()))
  2555. {
  2556. switch ((compatIFSHmode)_compatmode)
  2557. {
  2558. case compatIFSHnone:
  2559. sMode = IFSHnone;
  2560. break;
  2561. case compatIFSHread:
  2562. sMode = IFSHread;
  2563. break;
  2564. case compatIFSHwrite:
  2565. sMode = IFSHfull;
  2566. break;
  2567. case compatIFSHall:
  2568. sMode = IFSHfull;
  2569. break;
  2570. }
  2571. }
  2572. sendBuffer.append((RemoteFileCommandType)RFCopenIO).append(localname).append((byte)_mode).append((byte)_compatmode).append((byte)_extraFlags).append(sMode).append(cFlags);
  2573. parent->sendRemoteCommand(sendBuffer, replyBuffer);
  2574. replyBuffer.read(handle);
  2575. if (!handle)
  2576. return false;
  2577. switch (_mode) {
  2578. case IFOcreate:
  2579. mode = IFOwrite;
  2580. break;
  2581. case IFOcreaterw:
  2582. mode = IFOreadwrite;
  2583. break;
  2584. default:
  2585. mode = _mode;
  2586. break;
  2587. }
  2588. compatmode = _compatmode;
  2589. extraFlags = _extraFlags;
  2590. return true;
  2591. }
  2592. bool reopen()
  2593. {
  2594. StringBuffer s;
  2595. PROGLOG("Attempting reopen of %s on %s",parent->queryLocalName(),parent->queryEp().getUrlStr(s).str());
  2596. if (open(mode,compatmode,extraFlags))
  2597. return true;
  2598. return false;
  2599. }
  2600. offset_t size()
  2601. {
  2602. MemoryBuffer sendBuffer;
  2603. initSendBuffer(sendBuffer);
  2604. MemoryBuffer replyBuffer;
  2605. sendBuffer.append((RemoteFileCommandType)RFCsize).append(handle);
  2606. parent->sendRemoteCommand(sendBuffer, replyBuffer, false);
  2607. // Retry using reopen TBD
  2608. offset_t ret;
  2609. replyBuffer.read(ret);
  2610. return ret;
  2611. }
  2612. virtual unsigned __int64 getStatistic(StatisticKind kind)
  2613. {
  2614. switch (kind)
  2615. {
  2616. case StCycleDiskReadIOCycles:
  2617. return ioReadCycles.load(std::memory_order_relaxed);
  2618. case StCycleDiskWriteIOCycles:
  2619. return ioWriteCycles.load(std::memory_order_relaxed);
  2620. case StTimeDiskReadIO:
  2621. return cycle_to_nanosec(ioReadCycles.load(std::memory_order_relaxed));
  2622. case StTimeDiskWriteIO:
  2623. return cycle_to_nanosec(ioWriteCycles.load(std::memory_order_relaxed));
  2624. case StSizeDiskRead:
  2625. return ioReadBytes.load(std::memory_order_relaxed);
  2626. case StSizeDiskWrite:
  2627. return ioWriteBytes.load(std::memory_order_relaxed);
  2628. case StNumDiskReads:
  2629. return ioReads.load(std::memory_order_relaxed);
  2630. case StNumDiskWrites:
  2631. return ioWrites.load(std::memory_order_relaxed);
  2632. case StNumDiskRetries:
  2633. return ioRetries.load(std::memory_order_relaxed);
  2634. }
  2635. return 0;
  2636. }
  2637. size32_t read(offset_t pos, size32_t len, void * data)
  2638. {
  2639. size32_t got;
  2640. MemoryBuffer replyBuffer;
  2641. CCycleTimer timer;
  2642. const void *b;
  2643. try
  2644. {
  2645. b = doRead(pos,len,replyBuffer,got,data);
  2646. }
  2647. catch (...)
  2648. {
  2649. ioReadCycles.fetch_add(timer.elapsedCycles());
  2650. throw;
  2651. }
  2652. ioReadCycles.fetch_add(timer.elapsedCycles());
  2653. ioReadBytes.fetch_add(got);
  2654. ++ioReads;
  2655. if (b!=data)
  2656. memcpy(data,b,got);
  2657. return got;
  2658. }
  2659. virtual void flush()
  2660. {
  2661. }
  2662. const void *doRead(offset_t pos, size32_t len, MemoryBuffer &replyBuffer, size32_t &got, void *dstbuf)
  2663. {
  2664. unsigned tries=0;
  2665. for (;;)
  2666. {
  2667. try
  2668. {
  2669. MemoryBuffer sendBuffer;
  2670. initSendBuffer(sendBuffer);
  2671. replyBuffer.clear();
  2672. sendBuffer.append((RemoteFileCommandType)RFCread).append(handle).append(pos).append(len);
  2673. parent->sendRemoteCommand(sendBuffer, replyBuffer,false);
  2674. // kludge dafilesrv versions <= 1.5e don't return error correctly
  2675. if (replyBuffer.length()>len+sizeof(size32_t)+sizeof(unsigned))
  2676. {
  2677. size32_t save = replyBuffer.getPos();
  2678. replyBuffer.reset(len+sizeof(size32_t)+sizeof(unsigned));
  2679. unsigned errCode;
  2680. replyBuffer.read(errCode);
  2681. if (errCode)
  2682. {
  2683. StringBuffer msg;
  2684. parent->ep.getUrlStr(msg.append('[')).append("] ");
  2685. if (replyBuffer.getPos()<replyBuffer.length())
  2686. {
  2687. StringAttr s;
  2688. replyBuffer.read(s);
  2689. msg.append(s);
  2690. }
  2691. else
  2692. msg.append("ERROR #").append(errCode);
  2693. throw createDafsException(errCode, msg.str());
  2694. }
  2695. else
  2696. replyBuffer.reset(save);
  2697. }
  2698. replyBuffer.read(got);
  2699. if ((got>replyBuffer.remaining())||(got>len))
  2700. {
  2701. PROGLOG("Read beyond buffer %d,%d,%d",got,replyBuffer.remaining(),len);
  2702. throw createDafsException(RFSERR_ReadFailed, "Read beyond buffer");
  2703. }
  2704. return replyBuffer.readDirect(got);
  2705. }
  2706. catch (IJSOCK_Exception *e)
  2707. {
  2708. EXCLOG(e,"CRemoteFileIO::read");
  2709. if (++tries > 3)
  2710. {
  2711. ioRetries.fetch_add(tries);
  2712. throw;
  2713. }
  2714. WARNLOG("Retrying read of %s (%d)",parent->queryLocalName(),tries);
  2715. Owned<IException> exc = e;
  2716. if (!reopen())
  2717. {
  2718. ioRetries.fetch_add(tries);
  2719. throw exc.getClear();
  2720. }
  2721. }
  2722. }
  2723. if (tries)
  2724. ioRetries.fetch_add(tries);
  2725. got = 0;
  2726. return NULL;
  2727. }
  2728. size32_t write(offset_t pos, size32_t len, const void * data)
  2729. {
  2730. unsigned tries=0;
  2731. size32_t ret = 0;
  2732. CCycleTimer timer;
  2733. for (;;)
  2734. {
  2735. try
  2736. {
  2737. MemoryBuffer replyBuffer;
  2738. MemoryBuffer sendBuffer;
  2739. initSendBuffer(sendBuffer);
  2740. sendBuffer.append((RemoteFileCommandType)RFCwrite).append(handle).append(pos).append(len).append(len, data);
  2741. parent->sendRemoteCommand(sendBuffer, replyBuffer, false, true);
  2742. replyBuffer.read(ret);
  2743. break;
  2744. }
  2745. catch (IJSOCK_Exception *e)
  2746. {
  2747. EXCLOG(e,"CRemoteFileIO::write");
  2748. if (++tries > 3)
  2749. {
  2750. ioRetries.fetch_add(tries);
  2751. ioWriteCycles.fetch_add(timer.elapsedCycles());
  2752. throw;
  2753. }
  2754. WARNLOG("Retrying write(%" I64F "d,%d) of %s (%d)",pos,len,parent->queryLocalName(),tries);
  2755. Owned<IException> exc = e;
  2756. if (!reopen())
  2757. {
  2758. ioRetries.fetch_add(tries);
  2759. ioWriteCycles.fetch_add(timer.elapsedCycles());
  2760. throw exc.getClear();
  2761. }
  2762. }
  2763. }
  2764. if (tries)
  2765. ioRetries.fetch_add(tries);
  2766. ioWriteCycles.fetch_add(timer.elapsedCycles());
  2767. ioWriteBytes.fetch_add(ret);
  2768. ++ioWrites;
  2769. if ((ret==(size32_t)-1) || (ret < len))
  2770. throw createDafsException(DISK_FULL_EXCEPTION_CODE,"write failed, disk full?");
  2771. return ret;
  2772. }
  2773. offset_t appendFile(IFile *file,offset_t pos,offset_t len)
  2774. {
  2775. MemoryBuffer sendBuffer;
  2776. initSendBuffer(sendBuffer);
  2777. MemoryBuffer replyBuffer;
  2778. const char * fname = file->queryFilename();
  2779. sendBuffer.append((RemoteFileCommandType)RFCappend).append(handle).append(fname).append(pos).append(len);
  2780. parent->sendRemoteCommand(sendBuffer, replyBuffer, false, true); // retry not safe
  2781. offset_t ret;
  2782. replyBuffer.read(ret);
  2783. if ((ret==(offset_t)-1) || ((len != ((offset_t)-1)) && (ret < len)))
  2784. throw createDafsException(DISK_FULL_EXCEPTION_CODE,"append failed, disk full?"); // though could be file missing TBD
  2785. return ret;
  2786. }
  2787. void setSize(offset_t size)
  2788. {
  2789. MemoryBuffer sendBuffer;
  2790. initSendBuffer(sendBuffer);
  2791. MemoryBuffer replyBuffer;
  2792. sendBuffer.append((RemoteFileCommandType)RFCsetsize).append(handle).append(size);
  2793. parent->sendRemoteCommand(sendBuffer, replyBuffer, false, true);
  2794. // retry using reopen TBD
  2795. }
  2796. void setDisconnectOnExit(bool set) { disconnectonexit = set; }
  2797. void sendRemoteCommand(MemoryBuffer & sendBuffer, MemoryBuffer & replyBuffer, bool retry=true, bool lengthy=false, bool handleErrCode=true)
  2798. {
  2799. parent->sendRemoteCommand(sendBuffer, replyBuffer, retry, lengthy, handleErrCode);
  2800. }
  2801. };
  2802. void clientDisconnectRemoteIoOnExit(IFileIO *fileio,bool set)
  2803. {
  2804. CRemoteFileIO *cfileio = QUERYINTERFACE(fileio,CRemoteFileIO);
  2805. if (cfileio)
  2806. cfileio->setDisconnectOnExit(set);
  2807. }
  2808. IFileIO * CRemoteFile::openShared(IFOmode mode,IFSHmode shmode,IFEflags extraFlags)
  2809. {
  2810. // 0x0, 0x8, 0x10 and 0x20 are only share modes supported in this assert
  2811. // currently only 0x0 (IFSHnone), 0x8 (IFSHread) and 0x10 (IFSHfull) are used so this could be 0xffffffe7
  2812. // note: IFSHfull also includes read sharing (ie write|read)
  2813. assertex(((unsigned)shmode&0xffffffc7)==0);
  2814. compatIFSHmode compatmode;
  2815. unsigned fileflags = (flags>>16) & (S_IRUSR|S_IWUSR|S_IXUSR|S_IRGRP|S_IWGRP|S_IXGRP|S_IROTH|S_IWOTH|S_IXOTH);
  2816. if (fileflags&S_IXUSR) // this is bit hit and miss but backward compatible
  2817. compatmode = compatIFSHexec;
  2818. else if (fileflags&(S_IWGRP|S_IWOTH))
  2819. compatmode = compatIFSHall;
  2820. else if (shmode&IFSHfull)
  2821. compatmode = compatIFSHwrite;
  2822. else if (((shmode&(IFSHread|IFSHfull))==0) && ((fileflags&(S_IRGRP|S_IROTH))==0))
  2823. compatmode = compatIFSHnone;
  2824. else
  2825. compatmode = compatIFSHread;
  2826. Owned<CRemoteFileIO> res = new CRemoteFileIO(this);
  2827. if (res->open(mode,compatmode,extraFlags))
  2828. return res.getClear();
  2829. return NULL;
  2830. }
  2831. IFileIO * CRemoteFile::open(IFOmode mode,IFEflags extraFlags)
  2832. {
  2833. return openShared(mode,(IFSHmode)(flags&(IFSHread|IFSHfull)),extraFlags);
  2834. }
  2835. //---------------------------------------------------------------------------
  2836. void CRemoteFile::copyTo(IFile *dest, size32_t buffersize, ICopyFileProgress *progress, bool usetmp, CFflags copyFlags)
  2837. {
  2838. CRemoteFile *dstfile = QUERYINTERFACE(dest,CRemoteFile);
  2839. if (dstfile&&!dstfile->queryEp().isLocal()) {
  2840. StringBuffer tmpname;
  2841. Owned<IFile> destf;
  2842. RemoteFilename dest;
  2843. if (usetmp) {
  2844. makeTempCopyName(tmpname,dstfile->queryLocalName());
  2845. dest.setPath(dstfile->queryEp(),tmpname.str());
  2846. }
  2847. else
  2848. dest.setPath(dstfile->queryEp(),dstfile->queryLocalName());
  2849. destf.setown(createIFile(dest));
  2850. try {
  2851. // following may fail if new dafilesrv not deployed on src
  2852. copySection(dest,(offset_t)-1,0,(offset_t)-1,progress,copyFlags);
  2853. if (usetmp) {
  2854. StringAttr tail(pathTail(dstfile->queryLocalName()));
  2855. dstfile->remove();
  2856. destf->rename(tail);
  2857. }
  2858. return;
  2859. }
  2860. catch (IException *e)
  2861. {
  2862. StringBuffer s;
  2863. s.appendf("Remote File Copy (%d): ",e->errorCode());
  2864. e->errorMessage(s);
  2865. s.append(", retrying local");
  2866. WARNLOG("%s",s.str());
  2867. e->Release();
  2868. }
  2869. // delete dest
  2870. try {
  2871. destf->remove();
  2872. }
  2873. catch (IException *e)
  2874. {
  2875. EXCLOG(e,"Remote File Copy, Deleting temporary file");
  2876. e->Release();
  2877. }
  2878. }
  2879. // assumption if we get here that source remote, dest local (or equiv)
  2880. class cIntercept: implements ICopyFileIntercept
  2881. {
  2882. MemoryAttr ma;
  2883. MemoryBuffer mb;
  2884. virtual offset_t copy(IFileIO *from, IFileIO *to, offset_t ofs, size32_t sz)
  2885. {
  2886. if (ma.length()<sz)
  2887. ma.allocate(sz); // may be not used
  2888. void *buf = ma.bufferBase();
  2889. size32_t got;
  2890. CRemoteFileIO *srcio = QUERYINTERFACE(from,CRemoteFileIO);
  2891. const void *dst;
  2892. if (srcio)
  2893. dst = srcio->doRead(ofs,sz,mb.clear(),got,buf);
  2894. else {
  2895. // shouldn't ever get here if source remote
  2896. got = from->read(ofs, sz, buf);
  2897. dst = buf;
  2898. }
  2899. if (got != 0)
  2900. to->write(ofs, got, dst);
  2901. return got;
  2902. }
  2903. } intercept;
  2904. doCopyFile(dest,this,buffersize,progress,&intercept,usetmp,copyFlags);
  2905. }
  2906. /////////////////////////
  2907. ISocket *checkSocketSecure(ISocket *socket)
  2908. {
  2909. if (securitySettings.connectMethod == SSLNone)
  2910. return LINK(socket);
  2911. char pname[256];
  2912. pname[0] = 0;
  2913. int pport = socket->peer_name(pname, sizeof(pname)-1);
  2914. if ( (pport == securitySettings.daFileSrvSSLPort) && (!socket->isSecure()) )
  2915. {
  2916. #ifdef _USE_OPENSSL
  2917. Owned<ISecureSocket> ssock;
  2918. try
  2919. {
  2920. ssock.setown(createSecureSocket(LINK(socket), ClientSocket));
  2921. int status = ssock->secure_connect();
  2922. if (status < 0)
  2923. throw createDafsException(DAFSERR_connection_failed, "Failure to establish secure connection");
  2924. return ssock.getClear();
  2925. }
  2926. catch (IException *e)
  2927. {
  2928. cleanupSocket(ssock);
  2929. ssock.clear();
  2930. cleanupSocket(socket);
  2931. StringBuffer eMsg;
  2932. e->errorMessage(eMsg);
  2933. e->Release();
  2934. throw createDafsException(DAFSERR_connection_failed, eMsg.str());
  2935. }
  2936. #else
  2937. throw createDafsException(DAFSERR_connection_failed,"Failure to establish secure connection: OpenSSL disabled in build");
  2938. #endif
  2939. }
  2940. return LINK(socket);
  2941. }
  2942. ISocket *connectDafs(SocketEndpoint &ep, unsigned timeoutms)
  2943. {
  2944. Owned<ISocket> socket;
  2945. if ( (securitySettings.connectMethod == SSLNone) || (securitySettings.connectMethod == SSLOnly) )
  2946. {
  2947. socket.setown(ISocket::connect_timeout(ep, timeoutms));
  2948. return checkSocketSecure(socket);
  2949. }
  2950. // SSLFirst or UnsecureFirst ...
  2951. unsigned newtimeout = timeoutms;
  2952. if (newtimeout > 5000)
  2953. newtimeout = 5000;
  2954. int conAttempts = 2;
  2955. while (conAttempts > 0)
  2956. {
  2957. conAttempts--;
  2958. bool connected = false;
  2959. try
  2960. {
  2961. socket.setown(ISocket::connect_timeout(ep, newtimeout));
  2962. connected = true;
  2963. newtimeout = timeoutms;
  2964. }
  2965. catch (IJSOCK_Exception *e)
  2966. {
  2967. if (e->errorCode() == JSOCKERR_connection_failed)
  2968. {
  2969. e->Release();
  2970. if (ep.port == securitySettings.daFileSrvSSLPort)
  2971. ep.port = securitySettings.daFileSrvPort;
  2972. else
  2973. ep.port = securitySettings.daFileSrvSSLPort;
  2974. if (!conAttempts)
  2975. throw;
  2976. }
  2977. else
  2978. throw;
  2979. }
  2980. if (connected)
  2981. {
  2982. if (ep.port == securitySettings.daFileSrvSSLPort)
  2983. {
  2984. try
  2985. {
  2986. return checkSocketSecure(socket);
  2987. }
  2988. catch (IDAFS_Exception *e)
  2989. {
  2990. connected = false;
  2991. if (e->errorCode() == DAFSERR_connection_failed)
  2992. {
  2993. // worth logging to help identify any ssl config issues ...
  2994. StringBuffer errmsg;
  2995. e->errorMessage(errmsg);
  2996. WARNLOG("%s", errmsg.str());
  2997. e->Release();
  2998. ep.port = securitySettings.daFileSrvPort;
  2999. if (!conAttempts)
  3000. throw;
  3001. }
  3002. else
  3003. throw;
  3004. }
  3005. }
  3006. else
  3007. return socket.getClear();
  3008. }
  3009. }
  3010. throw createDafsException(DAFSERR_connection_failed, "Failed to establish connection with DaFileSrv");
  3011. }
  3012. unsigned getRemoteVersion(CRemoteFileIO &remoteFileIO, StringBuffer &ver)
  3013. {
  3014. unsigned ret;
  3015. MemoryBuffer sendBuffer;
  3016. initSendBuffer(sendBuffer);
  3017. sendBuffer.append((RemoteFileCommandType)RFCgetver);
  3018. sendBuffer.append((unsigned)RFCgetver);
  3019. MemoryBuffer replyBuffer;
  3020. try
  3021. {
  3022. remoteFileIO.sendRemoteCommand(sendBuffer, replyBuffer, true, false, false);
  3023. }
  3024. catch (IException *e)
  3025. {
  3026. EXCLOG(e);
  3027. ::Release(e);
  3028. return 0;
  3029. }
  3030. unsigned errCode;
  3031. replyBuffer.read(errCode);
  3032. if (errCode==RFSERR_InvalidCommand)
  3033. {
  3034. ver.append("DS V1.0");
  3035. return 10;
  3036. }
  3037. else if (errCode==0)
  3038. ret = 11;
  3039. else if (errCode<0x10000)
  3040. return 0;
  3041. else
  3042. ret = errCode-0x10000;
  3043. StringAttr vers;
  3044. replyBuffer.read(vers);
  3045. ver.append(vers);
  3046. return ret;
  3047. }
  3048. unsigned getRemoteVersion(ISocket *origSock, StringBuffer &ver)
  3049. {
  3050. // used to have a global critical section here
  3051. if (!origSock)
  3052. return 0;
  3053. Owned<ISocket> socket = checkSocketSecure(origSock);
  3054. unsigned ret;
  3055. MemoryBuffer sendbuf;
  3056. initSendBuffer(sendbuf);
  3057. sendbuf.append((RemoteFileCommandType)RFCgetver);
  3058. sendbuf.append((unsigned)RFCgetver);
  3059. MemoryBuffer reply;
  3060. try
  3061. {
  3062. sendBuffer(socket, sendbuf);
  3063. receiveBuffer(socket, reply, 1 ,4096);
  3064. unsigned errCode;
  3065. reply.read(errCode);
  3066. if (errCode==RFSERR_InvalidCommand)
  3067. {
  3068. ver.append("DS V1.0");
  3069. return 10;
  3070. }
  3071. else if (errCode==0)
  3072. ret = 11;
  3073. else if (errCode<0x10000)
  3074. return 0;
  3075. else
  3076. ret = errCode-0x10000;
  3077. }
  3078. catch (IException *e)
  3079. {
  3080. EXCLOG(e);
  3081. ::Release(e);
  3082. return 0;
  3083. }
  3084. StringAttr vers;
  3085. reply.read(vers);
  3086. ver.append(vers);
  3087. return ret;
  3088. }
  3089. /////////////////////////
  3090. //////////////
  3091. extern unsigned stopRemoteServer(ISocket * socket)
  3092. {
  3093. // used to have a global critical section here
  3094. if (!socket)
  3095. return 0;
  3096. MemoryBuffer sendbuf;
  3097. initSendBuffer(sendbuf);
  3098. sendbuf.append((RemoteFileCommandType)RFCstop);
  3099. sendbuf.append((unsigned)RFCstop);
  3100. MemoryBuffer replybuf;
  3101. unsigned errCode = RFSERR_InvalidCommand;
  3102. try
  3103. {
  3104. sendBuffer(socket, sendbuf);
  3105. receiveBuffer(socket, replybuf, NORMAL_RETRIES, 1024);
  3106. replybuf.read(errCode);
  3107. }
  3108. catch (IJSOCK_Exception *e)
  3109. {
  3110. if ((e->errorCode()!=JSOCKERR_broken_pipe)&&(e->errorCode()!=JSOCKERR_graceful_close))
  3111. EXCLOG(e);
  3112. else
  3113. errCode = 0;
  3114. }
  3115. catch (IException *e)
  3116. {
  3117. EXCLOG(e);
  3118. ::Release(e);
  3119. }
  3120. return errCode;
  3121. }
  3122. int setDafsTrace(ISocket * socket,byte flags)
  3123. {
  3124. if (!socket)
  3125. {
  3126. byte ret = traceFlags;
  3127. traceFlags = flags;
  3128. return ret;
  3129. }
  3130. MemoryBuffer sendbuf;
  3131. initSendBuffer(sendbuf);
  3132. sendbuf.append((RemoteFileCommandType)RFCsettrace).append(flags);
  3133. MemoryBuffer replybuf;
  3134. try
  3135. {
  3136. sendBuffer(socket, sendbuf);
  3137. receiveBuffer(socket, replybuf, NORMAL_RETRIES, 1024);
  3138. int retcode;
  3139. replybuf.read(retcode);
  3140. return retcode;
  3141. }
  3142. catch (IException *e)
  3143. {
  3144. EXCLOG(e);
  3145. ::Release(e);
  3146. }
  3147. return -1;
  3148. }
  3149. int setDafsThrottleLimit(ISocket * socket, ThrottleClass throttleClass, unsigned throttleLimit, unsigned throttleDelayMs, unsigned throttleCPULimit, unsigned queueLimit, StringBuffer *errMsg)
  3150. {
  3151. assertex(socket);
  3152. MemoryBuffer sendbuf;
  3153. initSendBuffer(sendbuf);
  3154. sendbuf.append((RemoteFileCommandType)RFCsetthrottle2).append((unsigned)throttleClass).append(throttleLimit);
  3155. sendbuf.append(throttleDelayMs).append(throttleCPULimit).append(queueLimit);
  3156. MemoryBuffer replybuf;
  3157. try
  3158. {
  3159. sendBuffer(socket, sendbuf);
  3160. receiveBuffer(socket, replybuf, NORMAL_RETRIES, 1024);
  3161. int retcode;
  3162. replybuf.read(retcode);
  3163. if (retcode && errMsg && replybuf.remaining())
  3164. replybuf.read(*errMsg);
  3165. return retcode;
  3166. }
  3167. catch (IException *e)
  3168. {
  3169. EXCLOG(e);
  3170. ::Release(e);
  3171. }
  3172. return -1;
  3173. }
  3174. int getDafsInfo(ISocket * socket, unsigned level, StringBuffer &retstr)
  3175. {
  3176. if (!socket)
  3177. {
  3178. retstr.append(VERSTRING);
  3179. return 0;
  3180. }
  3181. MemoryBuffer sendbuf;
  3182. initSendBuffer(sendbuf);
  3183. sendbuf.append((RemoteFileCommandType)RFCgetinfo).append(level);
  3184. MemoryBuffer replybuf;
  3185. try
  3186. {
  3187. sendBuffer(socket, sendbuf);
  3188. receiveBuffer(socket, replybuf, 1);
  3189. int retcode;
  3190. replybuf.read(retcode);
  3191. if (retcode==0)
  3192. {
  3193. StringAttr s;
  3194. replybuf.read(s);
  3195. retstr.append(s);
  3196. }
  3197. return retcode;
  3198. }
  3199. catch (IException *e)
  3200. {
  3201. EXCLOG(e);
  3202. ::Release(e);
  3203. }
  3204. return -1;
  3205. }
  3206. void remoteExtractBlobElements(const SocketEndpoint &ep,const char * prefix, const char * filename, ExtractedBlobArray & extracted)
  3207. {
  3208. Owned<CRemoteFile> file = new CRemoteFile (ep,filename);
  3209. file->remoteExtractBlobElements(prefix, extracted);
  3210. }
  3211. //====================================================================================================
  3212. class CAsyncCommandManager
  3213. {
  3214. class CAsyncJob: public CInterface
  3215. {
  3216. class cThread: public Thread
  3217. {
  3218. CAsyncJob *parent;
  3219. public:
  3220. cThread(CAsyncJob *_parent)
  3221. : Thread("CAsyncJob")
  3222. {
  3223. parent = _parent;
  3224. }
  3225. int run()
  3226. {
  3227. int ret = -1;
  3228. try {
  3229. ret = parent->run();
  3230. parent->setDone();
  3231. }
  3232. catch (IException *e)
  3233. {
  3234. parent->setException(e);
  3235. }
  3236. parent->signal();
  3237. return ret;
  3238. }
  3239. } *thread;
  3240. StringAttr uuid;
  3241. CAsyncCommandManager &parent;
  3242. public:
  3243. CAsyncJob(CAsyncCommandManager &_parent, const char *_uuid)
  3244. : uuid(_uuid), parent(_parent)
  3245. {
  3246. thread = new cThread(this);
  3247. hash = hashc((const byte *)uuid.get(),uuid.length(),~0U);
  3248. }
  3249. ~CAsyncJob()
  3250. {
  3251. thread->join();
  3252. thread->Release();
  3253. }
  3254. static void destroy(CAsyncJob *j)
  3255. {
  3256. j->Release();
  3257. }
  3258. void signal()
  3259. {
  3260. parent.signal();
  3261. }
  3262. void start()
  3263. {
  3264. parent.wait();
  3265. thread->start();
  3266. }
  3267. void join()
  3268. {
  3269. thread->join();
  3270. }
  3271. static unsigned getHash(const char *key)
  3272. {
  3273. return hashc((const byte *)key,strlen(key),~0U);
  3274. }
  3275. static CAsyncJob* create(const char *key) { assertex(!"CAsyncJob::create not implemented"); return NULL; }
  3276. unsigned hash;
  3277. bool eq(const char *key)
  3278. {
  3279. return stricmp(key,uuid.get())==0;
  3280. }
  3281. virtual int run()=0;
  3282. virtual void setException(IException *e)=0;
  3283. virtual void setDone()=0;
  3284. };
  3285. class CAsyncCopySection: public CAsyncJob
  3286. {
  3287. Owned<IFile> src;
  3288. RemoteFilename dst;
  3289. offset_t toOfs;
  3290. offset_t fromOfs;
  3291. offset_t size;
  3292. CFPmode mode; // not yet supported
  3293. CriticalSection sect;
  3294. offset_t done;
  3295. offset_t total;
  3296. Semaphore finished;
  3297. AsyncCommandStatus status;
  3298. Owned<IException> exc;
  3299. public:
  3300. CAsyncCopySection(CAsyncCommandManager &parent, const char *_uuid, const char *fromFile, const char *toFile, offset_t _toOfs, offset_t _fromOfs, offset_t _size)
  3301. : CAsyncJob(parent, _uuid)
  3302. {
  3303. status = ACScontinue;
  3304. src.setown(createIFile(fromFile));
  3305. dst.setRemotePath(toFile);
  3306. toOfs = _toOfs;
  3307. fromOfs = _fromOfs;
  3308. size = _size;
  3309. mode = CFPcontinue;
  3310. done = 0;
  3311. total = (offset_t)-1;
  3312. }
  3313. AsyncCommandStatus poll(offset_t &_done, offset_t &_total,unsigned timeout)
  3314. {
  3315. if (timeout&&finished.wait(timeout))
  3316. finished.signal(); // may need to call again
  3317. CriticalBlock block(sect);
  3318. if (exc)
  3319. throw exc.getClear();
  3320. _done = done;
  3321. _total = total;
  3322. return status;
  3323. }
  3324. int run()
  3325. {
  3326. class cProgress: implements ICopyFileProgress
  3327. {
  3328. CriticalSection &sect;
  3329. CFPmode &mode;
  3330. offset_t &done;
  3331. offset_t &total;
  3332. public:
  3333. cProgress(CriticalSection &_sect,offset_t &_done,offset_t &_total,CFPmode &_mode)
  3334. : sect(_sect), mode(_mode), done(_done), total(_total)
  3335. {
  3336. }
  3337. CFPmode onProgress(offset_t sizeDone, offset_t totalSize)
  3338. {
  3339. CriticalBlock block(sect);
  3340. done = sizeDone;
  3341. total = totalSize;
  3342. return mode;
  3343. }
  3344. } progress(sect,total,done,mode);
  3345. src->copySection(dst,toOfs, fromOfs, size, &progress); // exceptions will be handled by base class
  3346. return 0;
  3347. }
  3348. void setException(IException *e)
  3349. {
  3350. EXCLOG(e,"CAsyncCommandManager::CAsyncJob");
  3351. CriticalBlock block(sect);
  3352. if (exc.get())
  3353. e->Release();
  3354. else
  3355. exc.setown(e);
  3356. status = ACSerror;
  3357. }
  3358. void setDone()
  3359. {
  3360. CriticalBlock block(sect);
  3361. finished.signal();
  3362. status = ACSdone;
  3363. }
  3364. };
  3365. CMinHashTable<CAsyncJob> jobtable;
  3366. CriticalSection sect;
  3367. Semaphore threadsem;
  3368. unsigned limit;
  3369. public:
  3370. CAsyncCommandManager(unsigned _limit) : limit(_limit)
  3371. {
  3372. if (limit) // 0 == unbound
  3373. threadsem.signal(limit); // max number of async jobs
  3374. }
  3375. void join()
  3376. {
  3377. CriticalBlock block(sect);
  3378. unsigned i;
  3379. CAsyncJob *j=jobtable.first(i);
  3380. while (j) {
  3381. j->join();
  3382. j=jobtable.next(i);
  3383. }
  3384. }
  3385. void signal()
  3386. {
  3387. if (limit)
  3388. threadsem.signal();
  3389. }
  3390. void wait()
  3391. {
  3392. if (limit)
  3393. threadsem.wait();
  3394. }
  3395. 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)
  3396. {
  3397. // return 0 if continuing, 1 if done
  3398. CAsyncCopySection * job;
  3399. Linked<CAsyncJob> cjob;
  3400. {
  3401. CriticalBlock block(sect);
  3402. cjob.set(jobtable.find(uuid,false));
  3403. if (cjob) {
  3404. job = QUERYINTERFACE(cjob.get(),CAsyncCopySection);
  3405. if (!job) {
  3406. throw MakeStringException(-1,"Async job ID mismatch");
  3407. }
  3408. }
  3409. else {
  3410. job = new CAsyncCopySection(*this, uuid, fromFile, toFile, toOfs, fromOfs, size);
  3411. cjob.setown(job);
  3412. jobtable.add(cjob.getLink());
  3413. cjob->start();
  3414. }
  3415. }
  3416. AsyncCommandStatus ret = ACSerror;
  3417. Owned<IException> rete;
  3418. try {
  3419. ret = job->poll(done,total,timeout);
  3420. }
  3421. catch (IException * e) {
  3422. rete.setown(e);
  3423. }
  3424. if ((ret!=ACScontinue)||rete.get()) {
  3425. job->join();
  3426. CriticalBlock block(sect);
  3427. jobtable.remove(job);
  3428. if (rete.get())
  3429. throw rete.getClear();
  3430. }
  3431. return ret;
  3432. }
  3433. };
  3434. //====================================================================================================
  3435. inline void appendErr(MemoryBuffer &reply, unsigned e)
  3436. {
  3437. reply.append(e).append(getRFSERRText(e));
  3438. }
  3439. #define MAPCOMMAND(c,p) case c: { this->p(msg, reply) ; break; }
  3440. #define MAPCOMMANDCLIENT(c,p,client) case c: { this->p(msg, reply, client); break; }
  3441. #define MAPCOMMANDCLIENTTESTSOCKET(c,p,client) case c: { testSocketFlag = true; this->p(msg, reply, client); break; }
  3442. #define MAPCOMMANDCLIENTTHROTTLE(c,p,client,throttler) case c: { this->p(msg, reply, client, throttler); break; }
  3443. #define MAPCOMMANDSTATS(c,p,stats) case c: { this->p(msg, reply, stats); break; }
  3444. #define MAPCOMMANDCLIENTSTATS(c,p,client,stats) case c: { this->p(msg, reply, client, stats); break; }
  3445. static unsigned ClientCount = 0;
  3446. static unsigned MaxClientCount = 0;
  3447. static CriticalSection ClientCountSect;
  3448. #define DEFAULT_THROTTLOG_LOG_INTERVAL_SECS 60 // log total throttled delay period
  3449. class CClientStats : public CInterface
  3450. {
  3451. public:
  3452. CClientStats(const char *_client) : client(_client), count(0), bRead(0), bWritten(0) { }
  3453. const char *queryFindString() const { return client; }
  3454. inline void addRead(unsigned __int64 len)
  3455. {
  3456. bRead += len;
  3457. }
  3458. inline void addWrite(unsigned __int64 len)
  3459. {
  3460. bWritten += len;
  3461. }
  3462. void getStatus(StringBuffer & info) const
  3463. {
  3464. info.appendf("Client %s - %" I64F "d requests handled, bytes read = %" I64F "d, bytes written = % " I64F "d",
  3465. client.get(), count, bRead.load(), bWritten.load()).newline();
  3466. }
  3467. StringAttr client;
  3468. unsigned __int64 count;
  3469. std::atomic<unsigned __int64> bRead;
  3470. std::atomic<unsigned __int64> bWritten;
  3471. };
  3472. class CClientStatsTable : public OwningStringSuperHashTableOf<CClientStats>
  3473. {
  3474. typedef OwningStringSuperHashTableOf<CClientStats> PARENT;
  3475. CriticalSection crit;
  3476. unsigned cmdStats[RFCmax];
  3477. static int compareElement(void* const *ll, void* const *rr)
  3478. {
  3479. const CClientStats *l = (const CClientStats *) *ll;
  3480. const CClientStats *r = (const CClientStats *) *rr;
  3481. if (l->count == r->count)
  3482. return 0;
  3483. else if (l->count<r->count)
  3484. return 1;
  3485. else
  3486. return -1;
  3487. }
  3488. public:
  3489. CClientStatsTable()
  3490. {
  3491. memset(&cmdStats[0], 0, sizeof(cmdStats));
  3492. }
  3493. ~CClientStatsTable()
  3494. {
  3495. _releaseAll();
  3496. }
  3497. CClientStats *getClientReference(RemoteFileCommandType cmd, const char *client)
  3498. {
  3499. CriticalBlock b(crit);
  3500. CClientStats *stats = PARENT::find(client);
  3501. if (!stats)
  3502. {
  3503. stats = new CClientStats(client);
  3504. PARENT::replace(*stats);
  3505. }
  3506. if (cmd<RFCmax) // i.e. ignore duff command (which will be traced), but still record client connected
  3507. cmdStats[cmd]++;
  3508. ++stats->count;
  3509. return LINK(stats);
  3510. }
  3511. StringBuffer &getInfo(StringBuffer &info, unsigned level=1)
  3512. {
  3513. CriticalBlock b(crit);
  3514. unsigned __int64 totalCmds = 0;
  3515. for (unsigned c=0; c<RFCmax; c++)
  3516. totalCmds += cmdStats[c];
  3517. unsigned totalClients = PARENT::ordinality();
  3518. info.appendf("Commands processed = %" I64F "u, unique clients = %u", totalCmds, totalClients);
  3519. if (totalCmds)
  3520. {
  3521. info.append("Command stats:").newline();
  3522. for (unsigned c=0; c<RFCmax; c++)
  3523. {
  3524. unsigned __int64 count = cmdStats[c];
  3525. if (count)
  3526. info.append(getRFCText(c)).append(": ").append(count).newline();
  3527. }
  3528. }
  3529. if (totalClients)
  3530. {
  3531. SuperHashIteratorOf<CClientStats> iter(*this);
  3532. PointerArrayOf<CClientStats> elements;
  3533. ForEach(iter)
  3534. {
  3535. CClientStats &elem = iter.query();
  3536. elements.append(&elem);
  3537. }
  3538. elements.sort(&compareElement);
  3539. if (level < 10)
  3540. {
  3541. // list up to 10 clients ordered by # of commands processed
  3542. unsigned max=elements.ordinality();
  3543. if (max>10)
  3544. max = 10; // cap
  3545. info.append("Top 10 clients:").newline();
  3546. for (unsigned e=0; e<max; e++)
  3547. {
  3548. const CClientStats &element = *elements.item(e);
  3549. element.getStatus(info);
  3550. }
  3551. }
  3552. else // list all
  3553. {
  3554. info.append("All clients:").newline();
  3555. ForEachItemIn(e, elements)
  3556. {
  3557. const CClientStats &element = *elements.item(e);
  3558. element.getStatus(info);
  3559. }
  3560. }
  3561. }
  3562. return info;
  3563. }
  3564. void reset()
  3565. {
  3566. CriticalBlock b(crit);
  3567. memset(&cmdStats[0], 0, sizeof(cmdStats));
  3568. kill();
  3569. }
  3570. };
  3571. interface IRemoteActivity : extends IInterface
  3572. {
  3573. virtual const void *nextRow(MemoryBufferBuilder &outBuilder, size32_t &sz) = 0;
  3574. virtual unsigned __int64 queryProcessed() const = 0;
  3575. virtual IOutputMetaData *queryOutputMeta() const = 0;
  3576. virtual StringBuffer &getInfoStr(StringBuffer &out) const = 0;
  3577. virtual void serializeCursor(MemoryBuffer &tgt) const = 0;
  3578. virtual void restoreCursor(MemoryBuffer &src) = 0;
  3579. virtual bool isGrouped() const = 0;
  3580. };
  3581. enum OpenFileFlag { of_null=0x0, of_key=0x01 };
  3582. struct OpenFileInfo
  3583. {
  3584. OpenFileInfo() { }
  3585. OpenFileInfo(int _handle, IFileIO *_fileIO, StringAttrItem *_filename) : handle(_handle), fileIO(_fileIO), filename(_filename) { }
  3586. OpenFileInfo(int _handle, IRemoteActivity *_activity, StringAttrItem *_filename, OutputFormat _format)
  3587. : handle(_handle), activity(_activity), filename(_filename), format(_format) { }
  3588. Linked<IFileIO> fileIO;
  3589. Linked<IRemoteActivity> activity;
  3590. Linked<StringAttrItem> filename; // for debug
  3591. int handle = 0;
  3592. unsigned flags = 0;
  3593. OutputFormat format = outFmt_Xml;
  3594. };
  3595. static IOutputMetaData *getTypeInfoOutputMetaData(IPropertyTree &actNode, const char *typePropName, bool grouped)
  3596. {
  3597. IPropertyTree *json = actNode.queryPropTree(typePropName);
  3598. if (json)
  3599. return createTypeInfoOutputMetaData(*json, grouped, nullptr);
  3600. else
  3601. {
  3602. StringBuffer binTypePropName(typePropName);
  3603. const char *jsonBin = actNode.queryProp(binTypePropName.append("Bin"));
  3604. if (!jsonBin)
  3605. return nullptr;
  3606. MemoryBuffer mb;
  3607. JBASE64_Decode(jsonBin, mb);
  3608. return createTypeInfoOutputMetaData(mb, grouped, nullptr);
  3609. }
  3610. }
  3611. class CRemoteDiskBaseActivity : public CSimpleInterfaceOf<IRemoteActivity>, implements IVirtualFieldCallback
  3612. {
  3613. protected:
  3614. StringAttr fileName; // physical filename
  3615. Linked<IOutputMetaData> inMeta, outMeta;
  3616. unsigned __int64 processed = 0;
  3617. Owned<const IDynamicTransform> translator;
  3618. bool outputGrouped = false;
  3619. bool opened = false;
  3620. bool eofSeen = false;
  3621. const RtlRecord *record = nullptr;
  3622. RowFilter filters;
  3623. // virtual field values
  3624. StringAttr logicalFilename;
  3625. void initCommon(IPropertyTree &config)
  3626. {
  3627. fileName.set(config.queryProp("fileName"));
  3628. record = &inMeta->queryRecordAccessor(true);
  3629. translator.setown(createRecordTranslator(outMeta->queryRecordAccessor(true), *record));
  3630. Owned<IPropertyTreeIterator> filterIter = config.getElements("keyFilter");
  3631. ForEach(*filterIter)
  3632. filters.addFilter(*record, filterIter->query().queryProp(nullptr));
  3633. logicalFilename.set(config.queryProp("virtualFields/logicalFilename"));
  3634. }
  3635. public:
  3636. IMPLEMENT_IINTERFACE_USING(CSimpleInterfaceOf<IRemoteActivity>)
  3637. CRemoteDiskBaseActivity()
  3638. {
  3639. }
  3640. // IRemoteActivity impl.
  3641. virtual unsigned __int64 queryProcessed() const override
  3642. {
  3643. return processed;
  3644. }
  3645. virtual IOutputMetaData *queryOutputMeta() const override
  3646. {
  3647. return outMeta;
  3648. }
  3649. virtual bool isGrouped() const override
  3650. {
  3651. return outputGrouped;
  3652. }
  3653. virtual void serializeCursor(MemoryBuffer &tgt) const override
  3654. {
  3655. throwUnexpected();
  3656. }
  3657. virtual void restoreCursor(MemoryBuffer &src) override
  3658. {
  3659. throwUnexpected();
  3660. }
  3661. //interface IVirtualFieldCallback
  3662. virtual const char * queryLogicalFilename(const void * row) override
  3663. {
  3664. return logicalFilename.str();
  3665. }
  3666. virtual unsigned __int64 getFilePosition(const void * row) override
  3667. {
  3668. throwUnexpected();
  3669. }
  3670. virtual unsigned __int64 getLocalFilePosition(const void * row) override
  3671. {
  3672. throwUnexpected();
  3673. }
  3674. };
  3675. class CRemoteDiskReadActivity : public CRemoteDiskBaseActivity
  3676. {
  3677. typedef CRemoteDiskBaseActivity PARENT;
  3678. CThorContiguousRowBuffer prefetchBuffer;
  3679. Owned<ISourceRowPrefetcher> prefetcher;
  3680. Owned<ISerialStream> inputStream;
  3681. Owned<IFileIO> iFileIO;
  3682. unsigned __int64 chooseN = 0;
  3683. unsigned __int64 startPos = 0;
  3684. bool compressed = false;
  3685. bool inputGrouped = false;
  3686. bool cursorDirty = false;
  3687. mutable bool eogPending = false;
  3688. mutable bool someInGroup = false;
  3689. RtlDynRow *filterRow = nullptr;
  3690. // virtual field values
  3691. unsigned partNum = 0;
  3692. offset_t baseFpos = 0;
  3693. void checkOpen()
  3694. {
  3695. if (opened)
  3696. {
  3697. if (!cursorDirty)
  3698. return;
  3699. if (prefetchBuffer.tell() != startPos)
  3700. {
  3701. inputStream->reset(startPos);
  3702. prefetchBuffer.clearStream();
  3703. prefetchBuffer.setStream(inputStream);
  3704. }
  3705. eofSeen = false;
  3706. cursorDirty = false;
  3707. return;
  3708. }
  3709. OwnedIFile iFile = createIFile(fileName);
  3710. iFileIO.setown(createCompressedFileReader(iFile));
  3711. if (iFileIO)
  3712. {
  3713. if (!compressed)
  3714. {
  3715. WARNLOG("meta info did not mark file '%s' as compressed, but detected file as compressed", fileName.get());
  3716. compressed = true;
  3717. }
  3718. }
  3719. else
  3720. {
  3721. iFileIO.setown(iFile->open(IFOread));
  3722. if (!iFileIO)
  3723. throw MakeStringException(1, "Failed to open: '%s'", fileName.get());
  3724. if (compressed)
  3725. {
  3726. WARNLOG("meta info marked file '%s' as compressed, but detected file as uncompressed", fileName.get());
  3727. compressed = false;
  3728. }
  3729. }
  3730. inputStream.setown(createFileSerialStream(iFileIO, startPos));
  3731. prefetchBuffer.setStream(inputStream);
  3732. prefetcher.setown(inMeta->createDiskPrefetcher());
  3733. opened = true;
  3734. eofSeen = false;
  3735. }
  3736. void close()
  3737. {
  3738. iFileIO.clear();
  3739. opened = false;
  3740. eofSeen = true;
  3741. }
  3742. inline bool fieldFilterMatch(const void * buffer)
  3743. {
  3744. if (filters.numFilterFields())
  3745. {
  3746. filterRow->setRow(buffer, 0);
  3747. return filters.matches(*filterRow);
  3748. }
  3749. else
  3750. return true;
  3751. }
  3752. public:
  3753. CRemoteDiskReadActivity(IPropertyTree &config) : prefetchBuffer(nullptr)
  3754. {
  3755. compressed = config.getPropBool("compressed");
  3756. inputGrouped = config.getPropBool("inputGrouped", false);
  3757. outputGrouped = config.getPropBool("outputGrouped", false);
  3758. chooseN = config.getPropInt64("chooseN", defaultFileStreamChooseNLimit);
  3759. if (!inputGrouped && outputGrouped)
  3760. outputGrouped = false; // perhaps should fire error
  3761. inMeta.setown(getTypeInfoOutputMetaData(config, "input", inputGrouped));
  3762. outMeta.setown(getTypeInfoOutputMetaData(config, "output", outputGrouped));
  3763. if (!outMeta)
  3764. outMeta.set(inMeta);
  3765. partNum = config.getPropInt("virtualFields/partNum");
  3766. baseFpos = (offset_t)config.getPropInt64("virtualFields/baseFpos");
  3767. initCommon(config);
  3768. if (config.hasProp("keyFilter"))
  3769. filterRow = new RtlDynRow(*record);
  3770. }
  3771. ~CRemoteDiskReadActivity()
  3772. {
  3773. delete filterRow;
  3774. }
  3775. // IRemoteActivity impl.
  3776. virtual const void *nextRow(MemoryBufferBuilder &outBuilder, size32_t &retSz) override
  3777. {
  3778. if (eogPending || eofSeen)
  3779. {
  3780. eogPending = false;
  3781. someInGroup = false;
  3782. return nullptr;
  3783. }
  3784. checkOpen();
  3785. while (!eofSeen && (processed < chooseN))
  3786. {
  3787. while (!prefetchBuffer.eos())
  3788. {
  3789. prefetcher->readAhead(prefetchBuffer);
  3790. bool eog = false;
  3791. if (inputGrouped)
  3792. prefetchBuffer.read(sizeof(eog), &eog);
  3793. const byte *next = prefetchBuffer.queryRow();
  3794. size32_t rowSz; // use local var instead of reference param for efficiency
  3795. if (fieldFilterMatch(next))
  3796. rowSz = translator->translate(outBuilder, *this, next);
  3797. else
  3798. rowSz = 0;
  3799. prefetchBuffer.finishedRow();
  3800. const void *ret = outBuilder.getSelf();
  3801. outBuilder.finishRow(rowSz);
  3802. if (rowSz)
  3803. {
  3804. processed++;
  3805. eogPending = eog;
  3806. someInGroup = true;
  3807. retSz = rowSz;
  3808. return ret;
  3809. }
  3810. else if (eog)
  3811. {
  3812. eogPending = false;
  3813. if (someInGroup)
  3814. {
  3815. someInGroup = false;
  3816. return nullptr;
  3817. }
  3818. }
  3819. }
  3820. eofSeen = true;
  3821. }
  3822. close();
  3823. retSz = 0;
  3824. return nullptr;
  3825. }
  3826. virtual void serializeCursor(MemoryBuffer &tgt) const override
  3827. {
  3828. tgt.append(prefetchBuffer.tell());
  3829. tgt.append(processed);
  3830. tgt.append(someInGroup);
  3831. tgt.append(eogPending);
  3832. }
  3833. virtual void restoreCursor(MemoryBuffer &src) override
  3834. {
  3835. cursorDirty = true;
  3836. src.read(startPos);
  3837. src.read(processed);
  3838. src.read(someInGroup);
  3839. src.read(eogPending);
  3840. }
  3841. virtual StringBuffer &getInfoStr(StringBuffer &out) const override
  3842. {
  3843. return out.appendf("diskread[%s]", fileName.get());
  3844. }
  3845. virtual bool isGrouped() const override
  3846. {
  3847. return outputGrouped;
  3848. }
  3849. //interface IVirtualFieldCallback
  3850. virtual unsigned __int64 getFilePosition(const void * row) override
  3851. {
  3852. return prefetchBuffer.tell() + baseFpos;
  3853. }
  3854. virtual unsigned __int64 getLocalFilePosition(const void * row) override
  3855. {
  3856. return makeLocalFposOffset(partNum, prefetchBuffer.tell());
  3857. }
  3858. };
  3859. IRemoteActivity *createRemoteDiskRead(IPropertyTree &actNode)
  3860. {
  3861. return new CRemoteDiskReadActivity(actNode);
  3862. }
  3863. class CRemoteIndexBaseActivity : public CRemoteDiskBaseActivity
  3864. {
  3865. typedef CRemoteDiskBaseActivity PARENT;
  3866. protected:
  3867. bool isTlk = false;
  3868. bool allowPreload = false;
  3869. Owned<IKeyIndex> keyIndex;
  3870. Owned<IKeyManager> keyManager;
  3871. void checkOpen()
  3872. {
  3873. if (opened)
  3874. return;
  3875. keyIndex.setown(createKeyIndex(fileName, 0, isTlk, allowPreload)); // JCSMORE crc
  3876. keyManager.setown(createLocalKeyManager(*record, keyIndex, nullptr, true));
  3877. filters.createSegmentMonitors(keyManager);
  3878. keyManager->finishSegmentMonitors();
  3879. keyManager->reset();
  3880. opened = true;
  3881. }
  3882. void close()
  3883. {
  3884. keyManager.clear();
  3885. keyIndex.clear();
  3886. opened = false;
  3887. eofSeen = true;
  3888. }
  3889. public:
  3890. CRemoteIndexBaseActivity(IPropertyTree &config)
  3891. {
  3892. isTlk = config.getPropBool("isTlk");
  3893. allowPreload = config.getPropBool("allowPreload");
  3894. }
  3895. };
  3896. class CRemoteIndexReadActivity : public CRemoteIndexBaseActivity
  3897. {
  3898. typedef CRemoteIndexBaseActivity PARENT;
  3899. unsigned __int64 chooseN = 0;
  3900. public:
  3901. CRemoteIndexReadActivity(IPropertyTree &config) : PARENT(config)
  3902. {
  3903. chooseN = config.getPropInt64("chooseN", defaultFileStreamChooseNLimit);
  3904. inMeta.setown(getTypeInfoOutputMetaData(config, "input", false));
  3905. outMeta.setown(getTypeInfoOutputMetaData(config, "output", false));
  3906. if (!outMeta)
  3907. outMeta.set(inMeta);
  3908. initCommon(config);
  3909. }
  3910. // IRemoteActivity impl.
  3911. virtual const void *nextRow(MemoryBufferBuilder &outBuilder, size32_t &retSz) override
  3912. {
  3913. if (eofSeen)
  3914. return nullptr;
  3915. checkOpen();
  3916. if (!eofSeen)
  3917. {
  3918. if (processed < chooseN)
  3919. {
  3920. while (keyManager->lookup(true))
  3921. {
  3922. const byte *keyRow = keyManager->queryKeyBuffer();
  3923. retSz = translator->translate(outBuilder, *this, keyRow);
  3924. if (retSz)
  3925. {
  3926. const void *ret = outBuilder.getSelf();
  3927. outBuilder.finishRow(retSz);
  3928. ++processed;
  3929. return ret;
  3930. }
  3931. }
  3932. retSz = 0;
  3933. }
  3934. eofSeen = true;
  3935. }
  3936. close();
  3937. return nullptr;
  3938. }
  3939. virtual void serializeCursor(MemoryBuffer &tgt) const override
  3940. {
  3941. keyManager->serializeCursorPos(tgt);
  3942. tgt.append(processed);
  3943. /* JCSMORE (see HPCC-19640), serialize seek/scan data to client
  3944. tgt.append(keyManager->querySeeks());
  3945. tgt.append(keyManager->queryScans());
  3946. */
  3947. }
  3948. virtual void restoreCursor(MemoryBuffer &src) override
  3949. {
  3950. checkOpen();
  3951. eofSeen = false;
  3952. keyManager->deserializeCursorPos(src);
  3953. src.read(processed);
  3954. }
  3955. virtual StringBuffer &getInfoStr(StringBuffer &out) const override
  3956. {
  3957. return out.appendf("indexread[%s]", fileName.get());
  3958. }
  3959. };
  3960. IRemoteActivity *createRemoteIndexRead(IPropertyTree &actNode)
  3961. {
  3962. return new CRemoteIndexReadActivity(actNode);
  3963. }
  3964. class CRemoteIndexCountActivity : public CRemoteIndexBaseActivity
  3965. {
  3966. typedef CRemoteIndexBaseActivity PARENT;
  3967. unsigned __int64 rowLimit = 0;
  3968. public:
  3969. CRemoteIndexCountActivity(IPropertyTree &config) : PARENT(config)
  3970. {
  3971. rowLimit = config.getPropInt64("chooseN");
  3972. // create helper
  3973. inMeta.setown(getTypeInfoOutputMetaData(config, "input", false));
  3974. outMeta.set(inMeta);
  3975. initCommon(config);
  3976. }
  3977. // IRemoteActivity impl.
  3978. virtual const void *nextRow(MemoryBufferBuilder &outBuilder, size32_t &retSz) override
  3979. {
  3980. if (eofSeen)
  3981. return nullptr;
  3982. checkOpen();
  3983. unsigned __int64 count = 0;
  3984. if (!eofSeen)
  3985. {
  3986. if (rowLimit)
  3987. count = keyManager->checkCount(rowLimit);
  3988. else
  3989. count = keyManager->getCount();
  3990. }
  3991. void *tgt = outBuilder.ensureCapacity(sizeof(count), "count");
  3992. const void *ret = outBuilder.getSelf();
  3993. memcpy(tgt, &count, sizeof(count));
  3994. outBuilder.finishRow(sizeof(count));
  3995. close();
  3996. return ret;
  3997. }
  3998. virtual StringBuffer &getInfoStr(StringBuffer &out) const override
  3999. {
  4000. return out.appendf("indexcount[%s]", fileName.get());
  4001. }
  4002. };
  4003. IRemoteActivity *createRemoteIndexCount(IPropertyTree &actNode)
  4004. {
  4005. return new CRemoteIndexCountActivity(actNode);
  4006. }
  4007. IRemoteActivity *createRemoteActivity(IPropertyTree &actNode)
  4008. {
  4009. const char *kindStr = actNode.queryProp("kind");
  4010. ThorActivityKind kind = TAKnone;
  4011. if (strieq("diskread", kindStr))
  4012. kind = TAKdiskread;
  4013. else if (strieq("indexread", kindStr))
  4014. kind = TAKindexread;
  4015. else if (strieq("indexcount", kindStr))
  4016. kind = TAKindexcount;
  4017. Owned<IRemoteActivity> activity;
  4018. switch (kind)
  4019. {
  4020. case TAKdiskread:
  4021. {
  4022. activity.setown(createRemoteDiskRead(actNode));
  4023. break;
  4024. }
  4025. case TAKindexread:
  4026. {
  4027. activity.setown(createRemoteIndexRead(actNode));
  4028. break;
  4029. }
  4030. case TAKindexcount:
  4031. {
  4032. activity.setown(createRemoteIndexCount(actNode));
  4033. break;
  4034. }
  4035. default:
  4036. throwUnexpected(); // for now
  4037. }
  4038. return activity.getClear();
  4039. }
  4040. IRemoteActivity *createOutputActivity(IPropertyTree &requestTree)
  4041. {
  4042. IPropertyTree *actNode = requestTree.queryPropTree("node");
  4043. assertex(actNode);
  4044. return createRemoteActivity(*actNode);
  4045. }
  4046. #define MAX_KEYDATA_SZ 0x10000
  4047. class CRemoteFileServer : implements IRemoteFileServer, public CInterface
  4048. {
  4049. class CThrottler;
  4050. class CRemoteClientHandler : implements ISocketSelectNotify, public CInterface
  4051. {
  4052. public:
  4053. CRemoteFileServer *parent;
  4054. Owned<ISocket> socket;
  4055. StringAttr peerName;
  4056. Owned<IAuthenticatedUser> user;
  4057. MemoryBuffer msg;
  4058. bool selecthandled;
  4059. size32_t left;
  4060. StructArrayOf<OpenFileInfo> openFiles;
  4061. Owned<IDirectoryIterator> opendir;
  4062. unsigned lasttick, lastInactiveTick;
  4063. atomic_t &globallasttick;
  4064. unsigned previdx; // for debug
  4065. IMPLEMENT_IINTERFACE;
  4066. CRemoteClientHandler(CRemoteFileServer *_parent,ISocket *_socket,IAuthenticatedUser *_user,atomic_t &_globallasttick)
  4067. : socket(_socket), user(_user), globallasttick(_globallasttick)
  4068. {
  4069. previdx = (unsigned)-1;
  4070. StringBuffer peerBuf;
  4071. char name[256];
  4072. name[0] = 0;
  4073. int port = socket->peer_name(name,sizeof(name)-1);
  4074. if (port>=0)
  4075. {
  4076. peerBuf.append(name);
  4077. if (port)
  4078. peerBuf.append(':').append(port);
  4079. peerName.set(peerBuf);
  4080. }
  4081. else
  4082. {
  4083. /* There's a possibility the socket closed before got here, in which case, peer name is unavailable
  4084. * May potentially be unavailable for other reasons also.
  4085. * Must be set, as used in client stats HT.
  4086. * If socket closed, the handler will start up but notice closed and quit
  4087. */
  4088. peerName.set("UNKNOWN PEER NAME");
  4089. }
  4090. {
  4091. CriticalBlock block(ClientCountSect);
  4092. if (++ClientCount>MaxClientCount)
  4093. MaxClientCount = ClientCount;
  4094. if (TF_TRACE_CLIENT_CONN)
  4095. {
  4096. StringBuffer s;
  4097. s.appendf("Connecting(%p) [%d,%d] to ",this,ClientCount,MaxClientCount);
  4098. s.append(peerName);
  4099. PROGLOG("%s", s.str());
  4100. }
  4101. }
  4102. parent = _parent;
  4103. left = 0;
  4104. msg.setEndian(__BIG_ENDIAN);
  4105. selecthandled = false;
  4106. touch();
  4107. }
  4108. ~CRemoteClientHandler()
  4109. {
  4110. {
  4111. CriticalBlock block(ClientCountSect);
  4112. ClientCount--;
  4113. if (TF_TRACE_CLIENT_CONN) {
  4114. PROGLOG("Disconnecting(%p) [%d,%d] ",this,ClientCount,MaxClientCount);
  4115. }
  4116. }
  4117. ISocket *sock = socket.getClear();
  4118. try {
  4119. sock->Release();
  4120. }
  4121. catch (IException *e) {
  4122. EXCLOG(e,"~CRemoteClientHandler");
  4123. e->Release();
  4124. }
  4125. }
  4126. bool notifySelected(ISocket *sock,unsigned selected)
  4127. {
  4128. if (TF_TRACE_FULL)
  4129. PROGLOG("notifySelected(%p)",this);
  4130. if (sock!=socket)
  4131. WARNLOG("notifySelected - invalid socket passed");
  4132. size32_t avail = (size32_t)socket->avail_read();
  4133. if (avail)
  4134. touch();
  4135. if (left==0)
  4136. {
  4137. try
  4138. {
  4139. left = avail?receiveBufferSize(socket):0;
  4140. }
  4141. catch (IException *e)
  4142. {
  4143. EXCLOG(e,"notifySelected(1)");
  4144. e->Release();
  4145. left = 0;
  4146. }
  4147. if (left)
  4148. {
  4149. avail = (size32_t)socket->avail_read();
  4150. try
  4151. {
  4152. msg.ensureCapacity(left);
  4153. }
  4154. catch (IException *e)
  4155. {
  4156. EXCLOG(e,"notifySelected(2)");
  4157. e->Release();
  4158. left = 0;
  4159. // if too big then corrupted packet so read avail to try and consume
  4160. char fbuf[1024];
  4161. while (avail)
  4162. {
  4163. size32_t rd = avail>sizeof(fbuf)?sizeof(fbuf):avail;
  4164. try
  4165. {
  4166. socket->read(fbuf, rd); // don't need timeout here
  4167. avail -= rd;
  4168. }
  4169. catch (IException *e)
  4170. {
  4171. EXCLOG(e,"notifySelected(2) flush");
  4172. e->Release();
  4173. break;
  4174. }
  4175. }
  4176. avail = 0;
  4177. left = 0;
  4178. }
  4179. }
  4180. }
  4181. size32_t toread = left>avail?avail:left;
  4182. if (toread)
  4183. {
  4184. try
  4185. {
  4186. socket->read(msg.reserve(toread), toread); // don't need timeout here
  4187. }
  4188. catch (IException *e)
  4189. {
  4190. EXCLOG(e,"notifySelected(3)");
  4191. e->Release();
  4192. toread = left;
  4193. msg.clear();
  4194. }
  4195. }
  4196. if (TF_TRACE_FULL)
  4197. PROGLOG("notifySelected %d,%d",toread,left);
  4198. if ((left!=0)&&(avail==0))
  4199. {
  4200. WARNLOG("notifySelected: Closing mid packet, %d remaining", left);
  4201. toread = left;
  4202. msg.clear();
  4203. }
  4204. left -= toread;
  4205. if (left==0)
  4206. {
  4207. // DEBUG
  4208. parent->notify(this, msg); // consumes msg
  4209. }
  4210. return false;
  4211. }
  4212. void logPrevHandle()
  4213. {
  4214. if (previdx<openFiles.ordinality())
  4215. {
  4216. const OpenFileInfo &fileInfo = openFiles.item(previdx);
  4217. PROGLOG("Previous handle(%d): %s", fileInfo.handle, fileInfo.filename->text.get());
  4218. }
  4219. }
  4220. bool throttleCommand(MemoryBuffer &msg)
  4221. {
  4222. RemoteFileCommandType cmd = RFCunknown;
  4223. Owned<IException> e;
  4224. try
  4225. {
  4226. msg.read(cmd);
  4227. parent->throttleCommand(cmd, msg, this);
  4228. return true;
  4229. }
  4230. catch (IException *_e)
  4231. {
  4232. e.setown(_e);
  4233. }
  4234. /* processCommand() will handle most exception and replies,
  4235. * but if throttleCommand fails before it gets that far, this will handle
  4236. */
  4237. MemoryBuffer reply;
  4238. initSendBuffer(reply);
  4239. unsigned err = (cmd == RFCopenIO) ? RFSERR_OpenFailed : 0;
  4240. parent->formatException(reply, e, cmd, false, err, this);
  4241. sendBuffer(socket, reply);
  4242. return false;
  4243. }
  4244. void processCommand(RemoteFileCommandType cmd, MemoryBuffer &msg, CThrottler *throttler)
  4245. {
  4246. MemoryBuffer reply;
  4247. bool testSocketFlag = parent->processCommand(cmd, msg, initSendBuffer(reply), this, throttler);
  4248. sendBuffer(socket, reply, testSocketFlag);
  4249. }
  4250. bool immediateCommand() // returns false if socket closed or failure
  4251. {
  4252. MemoryBuffer msg;
  4253. msg.setEndian(__BIG_ENDIAN);
  4254. touch();
  4255. size32_t avail = (size32_t)socket->avail_read();
  4256. if (avail==0)
  4257. return false;
  4258. receiveBuffer(socket, msg, 5); // shouldn't timeout as data is available
  4259. touch();
  4260. if (msg.length()==0)
  4261. return false;
  4262. return throttleCommand(msg);
  4263. }
  4264. void process(MemoryBuffer &msg)
  4265. {
  4266. if (selecthandled)
  4267. throttleCommand(msg);
  4268. else
  4269. {
  4270. // msg only used/filled if process() has been triggered by notify()
  4271. while (parent->threadRunningCount()<=parent->targetActiveThreads) // if too many threads add to select handler
  4272. {
  4273. int w;
  4274. try
  4275. {
  4276. w = socket->wait_read(1000);
  4277. }
  4278. catch (IException *e)
  4279. {
  4280. EXCLOG(e, "CRemoteClientHandler::main wait_read error");
  4281. e->Release();
  4282. parent->onCloseSocket(this,1);
  4283. return;
  4284. }
  4285. if (w==0)
  4286. break;
  4287. if ((w<0)||!immediateCommand())
  4288. {
  4289. if (w<0)
  4290. WARNLOG("CRemoteClientHandler::main wait_read error");
  4291. parent->onCloseSocket(this,1);
  4292. return;
  4293. }
  4294. }
  4295. /* This is a bit confusing..
  4296. * The addClient below, adds this request to a selecthandler handled by another thread
  4297. * and passes ownership of 'this' (CRemoteClientHandler)
  4298. *
  4299. * When notified, the selecthandler will launch a new pool thread to handle the request
  4300. * If the pool thread limit is hit, the selecthandler will be blocked [ see comment in CRemoteFileServer::notify() ]
  4301. *
  4302. * Either way, a thread pool slot is occupied when processing a request.
  4303. * Blocked threads, will be blocked for up to 1 minute (as defined by createThreadPool call)
  4304. * IOW, if there are lots of incoming clients that can't be serviced by the CThrottler limit,
  4305. * a large number of pool threads will build up after a while.
  4306. *
  4307. * The CThrottler mechanism, imposes a further hard limit on how many concurrent request threads can be active.
  4308. * If the thread pool had an absolute limit (instead of just introducing a delay), then I don't see the point
  4309. * in this additional layer of throttling..
  4310. */
  4311. selecthandled = true;
  4312. parent->addClient(this); // add to select handler
  4313. // NB: this (CRemoteClientHandler) is now linked by the selecthandler and owned by the 'clients' list
  4314. }
  4315. }
  4316. bool timedOut()
  4317. {
  4318. return (msTick()-lasttick)>CLIENT_TIMEOUT;
  4319. }
  4320. bool inactiveTimedOut()
  4321. {
  4322. unsigned ms = msTick();
  4323. if ((ms-lastInactiveTick)>CLIENT_INACTIVEWARNING_TIMEOUT)
  4324. {
  4325. lastInactiveTick = ms;
  4326. return true;
  4327. }
  4328. return false;
  4329. }
  4330. void touch()
  4331. {
  4332. lastInactiveTick = lasttick = msTick();
  4333. atomic_set(&globallasttick,lasttick);
  4334. }
  4335. const char *queryPeerName()
  4336. {
  4337. return peerName;
  4338. }
  4339. bool getInfo(StringBuffer &str)
  4340. {
  4341. str.append("client(");
  4342. const char *name = queryPeerName();
  4343. bool ok;
  4344. if (name)
  4345. {
  4346. ok = true;
  4347. str.append(name);
  4348. }
  4349. else
  4350. ok = false;
  4351. unsigned ms = msTick();
  4352. str.appendf("): last touch %d ms ago (%d, %d)",ms-lasttick,lasttick,ms);
  4353. ForEachItemIn(i, openFiles)
  4354. {
  4355. const OpenFileInfo &fileInfo = openFiles.item(i);
  4356. str.appendf("\n %d: ", fileInfo.handle);
  4357. str.append(fileInfo.filename->text.get());
  4358. }
  4359. return ok;
  4360. }
  4361. };
  4362. class CThrottleQueueItem : public CSimpleInterface
  4363. {
  4364. public:
  4365. RemoteFileCommandType cmd;
  4366. Linked<CRemoteClientHandler> client;
  4367. MemoryBuffer msg;
  4368. CCycleTimer timer;
  4369. CThrottleQueueItem(RemoteFileCommandType _cmd, MemoryBuffer &_msg, CRemoteClientHandler *_client) : cmd(_cmd), client(_client)
  4370. {
  4371. msg.swapWith(_msg);
  4372. }
  4373. };
  4374. class CThrottler
  4375. {
  4376. Semaphore sem;
  4377. CriticalSection crit, configureCrit;
  4378. StringAttr title;
  4379. unsigned limit, delayMs, cpuThreshold, queueLimit;
  4380. unsigned disabledLimit;
  4381. unsigned __int64 totalThrottleDelay;
  4382. CCycleTimer totalThrottleDelayTimer;
  4383. QueueOf<CThrottleQueueItem, false> queue;
  4384. unsigned statsIntervalSecs;
  4385. public:
  4386. CThrottler(const char *_title) : title(_title)
  4387. {
  4388. totalThrottleDelay = 0;
  4389. limit = 0;
  4390. delayMs = DEFAULT_STDCMD_THROTTLEDELAYMS;
  4391. cpuThreshold = DEFAULT_STDCMD_THROTTLECPULIMIT;
  4392. disabledLimit = 0;
  4393. queueLimit = DEFAULT_STDCMD_THROTTLEQUEUELIMIT;
  4394. statsIntervalSecs = DEFAULT_STDCMD_THROTTLECPULIMIT;
  4395. }
  4396. ~CThrottler()
  4397. {
  4398. for (;;)
  4399. {
  4400. Owned<CThrottleQueueItem> item = queue.dequeue();
  4401. if (!item)
  4402. break;
  4403. }
  4404. }
  4405. unsigned queryLimit() const { return limit; }
  4406. unsigned queryDelayMs() const { return delayMs; };;
  4407. unsigned queryCpuThreshold() const { return cpuThreshold; }
  4408. unsigned queryQueueLimit() const { return queueLimit; }
  4409. StringBuffer &getInfoSummary(StringBuffer &info)
  4410. {
  4411. info.appendf("Throttler(%s) - limit=%u, delayMs=%u, cpuThreshold=%u, queueLimit=%u", title.get(), limit, delayMs, cpuThreshold, queueLimit).newline();
  4412. unsigned elapsedSecs = totalThrottleDelayTimer.elapsedMs()/1000;
  4413. time_t simple;
  4414. time(&simple);
  4415. simple -= elapsedSecs;
  4416. CDateTime dt;
  4417. dt.set(simple);
  4418. StringBuffer dateStr;
  4419. dt.getTimeString(dateStr, true);
  4420. info.appendf("Throttler(%s): statistics since %s", title.get(), dateStr.str()).newline();
  4421. info.appendf("Total delay of %0.2f seconds", ((double)totalThrottleDelay)/1000).newline();
  4422. info.appendf("Requests currently queued: %u", queue.ordinality());
  4423. return info;
  4424. }
  4425. void getInfo(StringBuffer &info)
  4426. {
  4427. CriticalBlock b(crit);
  4428. getInfoSummary(info).newline();
  4429. }
  4430. void configure(unsigned _limit, unsigned _delayMs, unsigned _cpuThreshold, unsigned _queueLimit)
  4431. {
  4432. if (_limit > THROTTLE_MAX_LIMIT || _delayMs > THROTTLE_MAX_DELAYMS || _cpuThreshold > THROTTLE_MAX_CPUTHRESHOLD || _queueLimit > THROTTLE_MAX_QUEUELIMIT)
  4433. 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)",
  4434. title.str(), _limit, THROTTLE_MAX_LIMIT, _delayMs, THROTTLE_MAX_DELAYMS, _cpuThreshold,
  4435. THROTTLE_MAX_CPUTHRESHOLD, _queueLimit, THROTTLE_MAX_QUEUELIMIT);
  4436. CriticalBlock b(configureCrit);
  4437. int delta = 0;
  4438. if (_limit)
  4439. {
  4440. if (disabledLimit) // if transitioning from disabled to some throttling
  4441. {
  4442. assertex(0 == limit);
  4443. delta = _limit - disabledLimit; // + or -
  4444. disabledLimit = 0;
  4445. }
  4446. else
  4447. delta = _limit - limit; // + or -
  4448. }
  4449. else if (0 == disabledLimit)
  4450. {
  4451. PROGLOG("Throttler(%s): disabled, previous limit: %u", title.get(), limit);
  4452. /* disabling - set limit immediately to let all new transaction through.
  4453. * NB: the semaphore signals are not consumed in this case, because transactions could be waiting on it.
  4454. * Instead the existing 'limit' is kept in 'disabledLimit', so that if/when throttling is
  4455. * re-enabled, it is used as a basis for increasing or consuming the semaphore signal count.
  4456. */
  4457. disabledLimit = limit;
  4458. limit = 0;
  4459. }
  4460. if (delta > 0)
  4461. {
  4462. PROGLOG("Throttler(%s): Increasing limit from %u to %u", title.get(), limit, _limit);
  4463. sem.signal(delta);
  4464. limit = _limit;
  4465. // NB: If throttling was off, this doesn't effect transactions in progress, i.e. will only throttle new transactions coming in.
  4466. }
  4467. else if (delta < 0)
  4468. {
  4469. PROGLOG("Throttler(%s): Reducing limit from %u to %u", title.get(), limit, _limit);
  4470. // NB: This is not expected to take long
  4471. CCycleTimer timer;
  4472. while (delta < 0)
  4473. {
  4474. if (sem.wait(1000))
  4475. ++delta;
  4476. else
  4477. 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);
  4478. }
  4479. limit = _limit;
  4480. // NB: doesn't include transactions in progress, i.e. will only throttle new transactions coming in.
  4481. }
  4482. if (_delayMs != delayMs)
  4483. {
  4484. PROGLOG("Throttler(%s): New delayMs=%u, previous: %u", title.get(), _delayMs, delayMs);
  4485. delayMs = _delayMs;
  4486. }
  4487. if (_cpuThreshold != cpuThreshold)
  4488. {
  4489. PROGLOG("Throttler(%s): New cpuThreshold=%u, previous: %u", title.get(), _cpuThreshold, cpuThreshold);
  4490. cpuThreshold = _cpuThreshold;
  4491. }
  4492. if (((unsigned)-1) != _queueLimit && _queueLimit != queueLimit)
  4493. {
  4494. PROGLOG("Throttler(%s): New queueLimit=%u%s, previous: %u", title.get(), _queueLimit, 0==_queueLimit?"(disabled)":"", queueLimit);
  4495. queueLimit = _queueLimit;
  4496. }
  4497. }
  4498. void setStatsInterval(unsigned _statsIntervalSecs)
  4499. {
  4500. if (_statsIntervalSecs != statsIntervalSecs)
  4501. {
  4502. PROGLOG("Throttler(%s): New statsIntervalSecs=%u, previous: %u", title.get(), _statsIntervalSecs, statsIntervalSecs);
  4503. statsIntervalSecs = _statsIntervalSecs;
  4504. }
  4505. }
  4506. void take(RemoteFileCommandType cmd) // cmd for info. only
  4507. {
  4508. for (;;)
  4509. {
  4510. if (sem.wait(delayMs))
  4511. return;
  4512. PROGLOG("Throttler(%s): transaction delayed [cmd=%s]", title.get(), getRFCText(cmd));
  4513. }
  4514. }
  4515. void release()
  4516. {
  4517. sem.signal();
  4518. }
  4519. StringBuffer &getStats(StringBuffer &stats, bool reset)
  4520. {
  4521. CriticalBlock b(crit);
  4522. getInfoSummary(stats);
  4523. if (reset)
  4524. {
  4525. totalThrottleDelayTimer.reset();
  4526. totalThrottleDelay = 0;
  4527. }
  4528. return stats;
  4529. }
  4530. void addCommand(RemoteFileCommandType cmd, MemoryBuffer &msg, CRemoteClientHandler *client)
  4531. {
  4532. CCycleTimer timer;
  4533. Owned<IException> exception;
  4534. bool hadSem = true;
  4535. if (!sem.wait(delayMs))
  4536. {
  4537. CriticalBlock b(crit);
  4538. if (!sem.wait(0)) // check hasn't become available
  4539. {
  4540. unsigned cpu = getLatestCPUUsage();
  4541. if (getLatestCPUUsage()<cpuThreshold)
  4542. {
  4543. /* Allow to proceed, despite hitting throttle limit because CPU < threshold
  4544. * NB: The overall number of threads is still capped by the thread pool.
  4545. */
  4546. unsigned ms = timer.elapsedMs();
  4547. totalThrottleDelay += ms;
  4548. PROGLOG("Throttler(%s): transaction delayed [cmd=%s] for : %u milliseconds, proceeding as cpu(%u)<throttleCPULimit(%u)", title.get(), getRFCText(cmd), cpu, ms, cpuThreshold);
  4549. hadSem = false;
  4550. }
  4551. else
  4552. {
  4553. if (queueLimit && queue.ordinality()>=queueLimit)
  4554. throw MakeStringException(0, "Throttler(%s), the maxiumum number of items are queued (%u), rejecting new command[%s]", title.str(), queue.ordinality(), getRFCText(cmd));
  4555. queue.enqueue(new CThrottleQueueItem(cmd, msg, client)); // NB: takes over ownership of 'client' from running thread
  4556. PROGLOG("Throttler(%s): transaction delayed [cmd=%s], queuing (%u queueud), [client=%p, sock=%u]", title.get(), getRFCText(cmd), queue.ordinality(), client, client->socket->OShandle());
  4557. return;
  4558. }
  4559. }
  4560. }
  4561. /* Guarantee that sem is released.
  4562. * Should normally release on clean exit when queue is empty.
  4563. */
  4564. struct ReleaseSem
  4565. {
  4566. Semaphore *sem;
  4567. ReleaseSem(Semaphore *_sem) { sem = _sem; }
  4568. ~ReleaseSem() { if (sem) sem->signal(); }
  4569. } releaseSem(hadSem?&sem:NULL);
  4570. /* Whilst holding on this throttle slot (i.e. before signalling semaphore back), process
  4571. * queued items. NB: other threads that are finishing will do also.
  4572. * Queued items are processed 1st, then the current request, then anything that was queued when handling current request
  4573. * Throttle slot (semaphore) is only given back when no more to do.
  4574. */
  4575. Linked<CRemoteClientHandler> currentClient;
  4576. MemoryBuffer currentMsg;
  4577. unsigned ms;
  4578. for (;;)
  4579. {
  4580. RemoteFileCommandType currentCmd;
  4581. {
  4582. CriticalBlock b(crit);
  4583. Owned<CThrottleQueueItem> item = queue.dequeue();
  4584. if (item)
  4585. {
  4586. currentCmd = item->cmd;
  4587. currentClient.setown(item->client.getClear());
  4588. currentMsg.swapWith(item->msg);
  4589. ms = item->timer.elapsedMs();
  4590. }
  4591. else
  4592. {
  4593. if (NULL == client) // previously handled and queue empty
  4594. {
  4595. /* Commands are only queued if semaphore is exhaused (checked inside crit)
  4596. * so only signal the semaphore inside the crit, after checking if there are no queued items
  4597. */
  4598. if (hadSem)
  4599. {
  4600. releaseSem.sem = NULL;
  4601. sem.signal();
  4602. }
  4603. break;
  4604. }
  4605. currentCmd = cmd;
  4606. currentClient.set(client); // process current request after dealing with queue
  4607. currentMsg.swapWith(msg);
  4608. ms = timer.elapsedMs();
  4609. client = NULL;
  4610. }
  4611. }
  4612. if (ms >= 1000)
  4613. {
  4614. if (ms>delayMs)
  4615. PROGLOG("Throttler(%s): transaction delayed [cmd=%s] for : %u seconds", title.get(), getRFCText(currentCmd), ms/1000);
  4616. }
  4617. {
  4618. CriticalBlock b(crit);
  4619. totalThrottleDelay += ms;
  4620. }
  4621. try
  4622. {
  4623. currentClient->processCommand(currentCmd, currentMsg, this);
  4624. }
  4625. catch (IException *e)
  4626. {
  4627. EXCLOG(e, "addCommand: processCommand failed");
  4628. e->Release();
  4629. }
  4630. }
  4631. }
  4632. };
  4633. // temporarily release a throttler slot
  4634. class CThrottleReleaseBlock
  4635. {
  4636. CThrottler &throttler;
  4637. RemoteFileCommandType cmd;
  4638. public:
  4639. CThrottleReleaseBlock(CThrottler &_throttler, RemoteFileCommandType _cmd) : throttler(_throttler), cmd(_cmd)
  4640. {
  4641. throttler.release();
  4642. }
  4643. ~CThrottleReleaseBlock()
  4644. {
  4645. throttler.take(cmd);
  4646. }
  4647. };
  4648. int lasthandle;
  4649. CriticalSection sect;
  4650. Owned<ISocket> acceptsock;
  4651. Owned<ISocket> securesock;
  4652. Owned<ISocketSelectHandler> selecthandler;
  4653. Owned<IThreadPool> threads; // for commands
  4654. bool stopping;
  4655. unsigned clientcounttick;
  4656. unsigned closedclients;
  4657. CAsyncCommandManager asyncCommandManager;
  4658. CThrottler stdCmdThrottler, slowCmdThrottler;
  4659. CClientStatsTable clientStatsTable;
  4660. atomic_t globallasttick;
  4661. unsigned targetActiveThreads;
  4662. int getNextHandle()
  4663. {
  4664. // called in sect critical block
  4665. for (;;) {
  4666. if (lasthandle==INT_MAX)
  4667. lasthandle = 1;
  4668. else
  4669. lasthandle++;
  4670. unsigned idx1;
  4671. unsigned idx2;
  4672. if (!findHandle(lasthandle,idx1,idx2))
  4673. return lasthandle;
  4674. }
  4675. }
  4676. bool findHandle(int handle,unsigned &clientidx,unsigned &handleidx)
  4677. {
  4678. // called in sect critical block
  4679. clientidx = (unsigned)-1;
  4680. handleidx = (unsigned)-1;
  4681. ForEachItemIn(i,clients) {
  4682. CRemoteClientHandler &client = clients.item(i);
  4683. ForEachItemIn(j, client.openFiles)
  4684. {
  4685. if (client.openFiles.item(j).handle==handle)
  4686. {
  4687. handleidx = j;
  4688. clientidx = i;
  4689. return true;
  4690. }
  4691. }
  4692. }
  4693. return false;
  4694. }
  4695. unsigned readKeyData(IKeyManager *keyManager, unsigned maxRecs, MemoryBuffer &reply, bool &maxHit)
  4696. {
  4697. DelayedSizeMarker keyDataSzReturned(reply);
  4698. unsigned numRecs = 0;
  4699. maxHit = false;
  4700. unsigned pos = reply.length();
  4701. while (keyManager->lookup(true))
  4702. {
  4703. unsigned size = keyManager->queryRowSize();
  4704. const byte *result = keyManager->queryKeyBuffer();
  4705. reply.append(size);
  4706. reply.append(size, result);
  4707. ++numRecs;
  4708. if (maxRecs && (0 == --maxRecs))
  4709. {
  4710. maxHit = true;
  4711. break;
  4712. }
  4713. if (reply.length()-pos >= MAX_KEYDATA_SZ)
  4714. {
  4715. maxHit = true;
  4716. break;
  4717. }
  4718. }
  4719. keyDataSzReturned.write();
  4720. return numRecs;
  4721. }
  4722. class cCommandProcessor: public CInterface, implements IPooledThread
  4723. {
  4724. Owned<CRemoteClientHandler> client;
  4725. MemoryBuffer msg;
  4726. public:
  4727. IMPLEMENT_IINTERFACE;
  4728. struct cCommandProcessorParams
  4729. {
  4730. cCommandProcessorParams() { msg.setEndian(__BIG_ENDIAN); }
  4731. CRemoteClientHandler *client;
  4732. MemoryBuffer msg;
  4733. };
  4734. virtual void init(void *_params) override
  4735. {
  4736. cCommandProcessorParams &params = *(cCommandProcessorParams *)_params;
  4737. client.setown(params.client);
  4738. msg.swapWith(params.msg);
  4739. }
  4740. virtual void threadmain() override
  4741. {
  4742. // idea is that initially we process commands inline then pass over to select handler
  4743. try
  4744. {
  4745. client->process(msg);
  4746. }
  4747. catch (IException *e)
  4748. {
  4749. // suppress some errors
  4750. EXCLOG(e,"cCommandProcessor::threadmain");
  4751. e->Release();
  4752. }
  4753. try
  4754. {
  4755. client.clear();
  4756. }
  4757. catch (IException *e)
  4758. {
  4759. // suppress some more errors clearing client
  4760. EXCLOG(e,"cCommandProcessor::threadmain(2)");
  4761. e->Release();
  4762. }
  4763. }
  4764. virtual bool stop() override
  4765. {
  4766. return true;
  4767. }
  4768. virtual bool canReuse() const override
  4769. {
  4770. return false; // want to free owned socket
  4771. }
  4772. };
  4773. IArrayOf<CRemoteClientHandler> clients;
  4774. class cImpersonateBlock
  4775. {
  4776. CRemoteClientHandler &client;
  4777. public:
  4778. cImpersonateBlock(CRemoteClientHandler &_client)
  4779. : client(_client)
  4780. {
  4781. if (client.user.get()) {
  4782. if (TF_TRACE)
  4783. PROGLOG("Impersonate user: %s",client.user->username());
  4784. client.user->impersonate();
  4785. }
  4786. }
  4787. ~cImpersonateBlock()
  4788. {
  4789. if (client.user.get()) {
  4790. if (TF_TRACE)
  4791. PROGLOG("Stop impersonating user: %s",client.user->username());
  4792. client.user->revert();
  4793. }
  4794. }
  4795. };
  4796. #define IMPERSONATE_USER(client) cImpersonateBlock ublock(client)
  4797. public:
  4798. IMPLEMENT_IINTERFACE
  4799. CRemoteFileServer(unsigned maxThreads, unsigned maxThreadsDelayMs, unsigned maxAsyncCopy)
  4800. : asyncCommandManager(maxAsyncCopy), stdCmdThrottler("stdCmdThrotlter"), slowCmdThrottler("slowCmdThrotlter")
  4801. {
  4802. lasthandle = 0;
  4803. selecthandler.setown(createSocketSelectHandler(NULL));
  4804. stdCmdThrottler.configure(DEFAULT_STDCMD_PARALLELREQUESTLIMIT, DEFAULT_STDCMD_THROTTLEDELAYMS, DEFAULT_STDCMD_THROTTLECPULIMIT, DEFAULT_STDCMD_THROTTLEQUEUELIMIT);
  4805. slowCmdThrottler.configure(DEFAULT_SLOWCMD_PARALLELREQUESTLIMIT, DEFAULT_SLOWCMD_THROTTLEDELAYMS, DEFAULT_SLOWCMD_THROTTLECPULIMIT, DEFAULT_SLOWCMD_THROTTLEQUEUELIMIT);
  4806. unsigned targetMinThreads=maxThreads*20/100; // 20%
  4807. if (0 == targetMinThreads) targetMinThreads = 1;
  4808. targetActiveThreads=maxThreads*80/100; // 80%
  4809. if (0 == targetActiveThreads) targetActiveThreads = 1;
  4810. class CCommandFactory : public CSimpleInterfaceOf<IThreadFactory>
  4811. {
  4812. CRemoteFileServer &parent;
  4813. public:
  4814. CCommandFactory(CRemoteFileServer &_parent) : parent(_parent) { }
  4815. virtual IPooledThread *createNew()
  4816. {
  4817. return parent.createCommandProcessor();
  4818. }
  4819. };
  4820. Owned<IThreadFactory> factory = new CCommandFactory(*this); // NB: pool links factory, so takes ownership
  4821. threads.setown(createThreadPool("CRemoteFileServerPool", factory, NULL, maxThreads, maxThreadsDelayMs,
  4822. #ifdef __64BIT__
  4823. 0, // Unlimited stack size
  4824. #else
  4825. 0x10000,
  4826. #endif
  4827. INFINITE,targetMinThreads));
  4828. threads->setStartDelayTracing(60); // trace amount delayed every minute.
  4829. PROGLOG("CRemoteFileServer: maxThreads = %u, maxThreadsDelayMs = %u, maxAsyncCopy = %u", maxThreads, maxThreadsDelayMs, maxAsyncCopy);
  4830. stopping = false;
  4831. clientcounttick = msTick();
  4832. closedclients = 0;
  4833. atomic_set(&globallasttick,msTick());
  4834. }
  4835. ~CRemoteFileServer()
  4836. {
  4837. #ifdef _DEBUG
  4838. PROGLOG("Exiting CRemoteFileServer");
  4839. #endif
  4840. asyncCommandManager.join();
  4841. clients.kill();
  4842. #ifdef _DEBUG
  4843. PROGLOG("Exited CRemoteFileServer");
  4844. #endif
  4845. }
  4846. bool lookupFileIOHandle(int handle, OpenFileInfo &fileInfo, unsigned newFlags=0)
  4847. {
  4848. if (handle<=0)
  4849. return false;
  4850. CriticalBlock block(sect);
  4851. unsigned clientidx;
  4852. unsigned handleidx;
  4853. if (!findHandle(handle,clientidx,handleidx))
  4854. return false;
  4855. CRemoteClientHandler &client = clients.item(clientidx);
  4856. OpenFileInfo &openFileInfo = client.openFiles.element(handleidx); // NB: links members
  4857. openFileInfo.flags |= newFlags;
  4858. fileInfo = openFileInfo;
  4859. client.previdx = handleidx;
  4860. return true;
  4861. }
  4862. //MORE: The file handles should timeout after a while, and accessing an old (invalid handle)
  4863. // should throw a different exception
  4864. bool checkFileIOHandle(int handle, IFileIO *&fileio, bool del=false)
  4865. {
  4866. fileio = NULL;
  4867. if (handle<=0)
  4868. return false;
  4869. CriticalBlock block(sect);
  4870. unsigned clientidx;
  4871. unsigned handleidx;
  4872. if (findHandle(handle,clientidx,handleidx))
  4873. {
  4874. CRemoteClientHandler &client = clients.item(clientidx);
  4875. const OpenFileInfo &fileInfo = client.openFiles.item(handleidx);
  4876. if (del)
  4877. {
  4878. if (fileInfo.flags & of_key)
  4879. clearKeyStoreCacheEntry(fileInfo.fileIO);
  4880. client.openFiles.remove(handleidx);
  4881. client.previdx = (unsigned)-1;
  4882. }
  4883. else
  4884. {
  4885. fileio = client.openFiles.item(handleidx).fileIO;
  4886. client.previdx = handleidx;
  4887. }
  4888. return true;
  4889. }
  4890. return false;
  4891. }
  4892. void checkFileIOHandle(MemoryBuffer &reply, int handle, IFileIO *&fileio, bool del=false)
  4893. {
  4894. if (!checkFileIOHandle(handle, fileio, del))
  4895. throw createDafsException(RFSERR_InvalidFileIOHandle, nullptr);
  4896. }
  4897. void onCloseSocket(CRemoteClientHandler *client, int which)
  4898. {
  4899. if (!client)
  4900. return;
  4901. CriticalBlock block(sect);
  4902. #ifdef _DEBUG
  4903. StringBuffer s(client->queryPeerName());
  4904. PROGLOG("onCloseSocket(%d) %s",which,s.str());
  4905. #endif
  4906. if (client->socket)
  4907. {
  4908. try
  4909. {
  4910. /* JCSMORE - shouldn't this really be dependent on whether selecthandled=true
  4911. * It has not been added to the selecthandler
  4912. * Harmless, but wasteful if so.
  4913. */
  4914. selecthandler->remove(client->socket);
  4915. }
  4916. catch (IException *e) {
  4917. EXCLOG(e,"CRemoteFileServer::onCloseSocket.1");
  4918. e->Release();
  4919. }
  4920. }
  4921. try {
  4922. clients.zap(*client);
  4923. }
  4924. catch (IException *e) {
  4925. EXCLOG(e,"CRemoteFileServer::onCloseSocket.2");
  4926. e->Release();
  4927. }
  4928. }
  4929. bool cmdOpenFileIO(MemoryBuffer & msg, MemoryBuffer & reply, CRemoteClientHandler &client)
  4930. {
  4931. IMPERSONATE_USER(client);
  4932. Owned<StringAttrItem> name = new StringAttrItem;
  4933. byte mode;
  4934. byte share;
  4935. msg.read(name->text).read(mode).read(share);
  4936. // also try to recv extra byte
  4937. byte extra = 0;
  4938. unsigned short sMode = IFUnone;
  4939. unsigned short cFlags = IFUnone;
  4940. if (msg.remaining() >= sizeof(byte))
  4941. {
  4942. msg.read(extra);
  4943. // and then try to recv extra sMode, cFlags (always sent together)
  4944. if (msg.remaining() >= (sizeof(sMode) + sizeof(cFlags)))
  4945. msg.read(sMode).read(cFlags);
  4946. }
  4947. IFEflags extraFlags = (IFEflags)extra;
  4948. // none => nocache for remote (hint)
  4949. // can revert to previous behavior with conf file setting "allow_pgcache_flush=false"
  4950. if (extraFlags == IFEnone)
  4951. extraFlags = IFEnocache;
  4952. Owned<IFile> file = createIFile(name->text);
  4953. switch ((compatIFSHmode)share) {
  4954. case compatIFSHnone:
  4955. file->setCreateFlags(S_IRUSR|S_IWUSR);
  4956. file->setShareMode(IFSHnone);
  4957. break;
  4958. case compatIFSHread:
  4959. file->setShareMode(IFSHread);
  4960. break;
  4961. case compatIFSHwrite:
  4962. file->setShareMode(IFSHfull);
  4963. break;
  4964. case compatIFSHexec:
  4965. file->setCreateFlags(S_IRUSR|S_IWUSR|S_IXUSR|S_IRGRP|S_IXGRP|S_IROTH|S_IXOTH);
  4966. break;
  4967. case compatIFSHall:
  4968. file->setCreateFlags(S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH|S_IWOTH); // bit excessive
  4969. file->setShareMode(IFSHfull);
  4970. break;
  4971. }
  4972. // use sMode, cFlags if sent
  4973. if (sMode != IFUnone && cFlags != IFUnone)
  4974. {
  4975. file->setCreateFlags(cFlags);
  4976. file->setShareMode((IFSHmode)sMode);
  4977. }
  4978. if (TF_TRACE_PRE_IO)
  4979. PROGLOG("before open file '%s', (%d,%d,%d,%d,0%o)",name->text.get(),(int)mode,(int)share,extraFlags,sMode,cFlags);
  4980. Owned<IFileIO> fileio = file->open((IFOmode)mode,extraFlags);
  4981. int handle;
  4982. if (fileio)
  4983. {
  4984. CriticalBlock block(sect);
  4985. handle = getNextHandle();
  4986. client.previdx = client.openFiles.ordinality();
  4987. client.openFiles.append(OpenFileInfo(handle, fileio, name));
  4988. }
  4989. else
  4990. handle = 0;
  4991. reply.append(RFEnoerror);
  4992. reply.append(handle);
  4993. if (TF_TRACE)
  4994. PROGLOG("open file '%s', (%d,%d) handle = %d",name->text.get(),(int)mode,(int)share,handle);
  4995. return true;
  4996. }
  4997. bool cmdCloseFileIO(MemoryBuffer & msg, MemoryBuffer & reply)
  4998. {
  4999. int handle;
  5000. msg.read(handle);
  5001. IFileIO *fileio;
  5002. checkFileIOHandle(reply, handle, fileio, true);
  5003. if (TF_TRACE)
  5004. PROGLOG("close file, handle = %d",handle);
  5005. reply.append(RFEnoerror);
  5006. return true;
  5007. }
  5008. void cmdRead(MemoryBuffer & msg, MemoryBuffer & reply, CClientStats &stats)
  5009. {
  5010. int handle;
  5011. __int64 pos;
  5012. size32_t len;
  5013. msg.read(handle).read(pos).read(len);
  5014. IFileIO *fileio;
  5015. checkFileIOHandle(reply, handle, fileio);
  5016. //arrange it so we read directly into the reply buffer...
  5017. unsigned posOfErr = reply.length();
  5018. reply.append((unsigned)RFEnoerror);
  5019. size32_t numRead;
  5020. unsigned posOfLength = reply.length();
  5021. if (TF_TRACE_PRE_IO)
  5022. PROGLOG("before read file, handle = %d, toread = %d",handle,len);
  5023. reply.reserve(sizeof(numRead));
  5024. void *data = reply.reserve(len);
  5025. numRead = fileio->read(pos,len,data);
  5026. stats.addRead(len);
  5027. if (TF_TRACE)
  5028. PROGLOG("read file, handle = %d, pos = %" I64F "d, toread = %d, read = %d",handle,pos,len,numRead);
  5029. reply.setLength(posOfLength + sizeof(numRead) + numRead);
  5030. reply.writeEndianDirect(posOfLength,sizeof(numRead),&numRead);
  5031. }
  5032. void cmdSize(MemoryBuffer & msg, MemoryBuffer & reply)
  5033. {
  5034. int handle;
  5035. msg.read(handle);
  5036. IFileIO *fileio;
  5037. checkFileIOHandle(reply, handle, fileio);
  5038. __int64 size = fileio->size();
  5039. reply.append((unsigned)RFEnoerror).append(size);
  5040. if (TF_TRACE)
  5041. PROGLOG("size file, handle = %d, size = %" I64F "d",handle,size);
  5042. }
  5043. void cmdSetSize(MemoryBuffer & msg, MemoryBuffer & reply)
  5044. {
  5045. int handle;
  5046. offset_t size;
  5047. msg.read(handle).read(size);
  5048. IFileIO *fileio;
  5049. if (TF_TRACE)
  5050. PROGLOG("set size file, handle = %d, size = %" I64F "d",handle,size);
  5051. checkFileIOHandle(reply, handle, fileio);
  5052. fileio->setSize(size);
  5053. reply.append((unsigned)RFEnoerror);
  5054. }
  5055. void cmdWrite(MemoryBuffer & msg, MemoryBuffer & reply, CClientStats &stats)
  5056. {
  5057. int handle;
  5058. __int64 pos;
  5059. size32_t len;
  5060. msg.read(handle).read(pos).read(len);
  5061. IFileIO *fileio;
  5062. checkFileIOHandle(reply, handle, fileio);
  5063. const byte *data = (const byte *)msg.readDirect(len);
  5064. if (TF_TRACE_PRE_IO)
  5065. PROGLOG("before write file, handle = %d, towrite = %d",handle,len);
  5066. size32_t numWritten = fileio->write(pos,len,data);
  5067. stats.addWrite(numWritten);
  5068. if (TF_TRACE)
  5069. PROGLOG("write file, handle = %d, towrite = %d, written = %d",handle,len,numWritten);
  5070. reply.append((unsigned)RFEnoerror).append(numWritten);
  5071. }
  5072. void cmdExists(MemoryBuffer & msg, MemoryBuffer & reply, CRemoteClientHandler &client)
  5073. {
  5074. IMPERSONATE_USER(client);
  5075. StringAttr name;
  5076. msg.read(name);
  5077. if (TF_TRACE)
  5078. PROGLOG("exists, '%s'",name.get());
  5079. Owned<IFile> file=createIFile(name);
  5080. bool e = file->exists();
  5081. reply.append((unsigned)RFEnoerror).append(e);
  5082. }
  5083. void cmdRemove(MemoryBuffer & msg, MemoryBuffer & reply,CRemoteClientHandler &client)
  5084. {
  5085. IMPERSONATE_USER(client);
  5086. StringAttr name;
  5087. msg.read(name);
  5088. if (TF_TRACE)
  5089. PROGLOG("remove, '%s'",name.get());
  5090. Owned<IFile> file=createIFile(name);
  5091. bool e = file->remove();
  5092. reply.append((unsigned)RFEnoerror).append(e);
  5093. }
  5094. void cmdGetVer(MemoryBuffer & msg, MemoryBuffer & reply)
  5095. {
  5096. if (TF_TRACE)
  5097. PROGLOG("getVer");
  5098. if (msg.getPos()+sizeof(unsigned)>msg.length())
  5099. reply.append((unsigned)RFEnoerror);
  5100. else
  5101. reply.append((unsigned)FILESRV_VERSION+0x10000);
  5102. reply.append(VERSTRING);
  5103. }
  5104. void cmdRename(MemoryBuffer & msg, MemoryBuffer & reply,CRemoteClientHandler &client)
  5105. {
  5106. IMPERSONATE_USER(client);
  5107. StringAttr fromname;
  5108. msg.read(fromname);
  5109. StringAttr toname;
  5110. msg.read(toname);
  5111. if (TF_TRACE)
  5112. PROGLOG("rename, '%s' to '%s'",fromname.get(),toname.get());
  5113. Owned<IFile> file=createIFile(fromname);
  5114. file->rename(toname);
  5115. reply.append((unsigned)RFEnoerror);
  5116. }
  5117. void cmdMove(MemoryBuffer & msg, MemoryBuffer & reply,CRemoteClientHandler &client)
  5118. {
  5119. IMPERSONATE_USER(client);
  5120. StringAttr fromname;
  5121. msg.read(fromname);
  5122. StringAttr toname;
  5123. msg.read(toname);
  5124. if (TF_TRACE)
  5125. PROGLOG("move, '%s' to '%s'",fromname.get(),toname.get());
  5126. Owned<IFile> file=createIFile(fromname);
  5127. file->move(toname);
  5128. reply.append((unsigned)RFEnoerror);
  5129. }
  5130. void cmdCopy(MemoryBuffer & msg, MemoryBuffer & reply, CRemoteClientHandler &client)
  5131. {
  5132. IMPERSONATE_USER(client);
  5133. StringAttr fromname;
  5134. msg.read(fromname);
  5135. StringAttr toname;
  5136. msg.read(toname);
  5137. if (TF_TRACE)
  5138. PROGLOG("copy, '%s' to '%s'",fromname.get(),toname.get());
  5139. copyFile(toname, fromname);
  5140. reply.append((unsigned)RFEnoerror);
  5141. }
  5142. void cmdAppend(MemoryBuffer & msg, MemoryBuffer & reply, CRemoteClientHandler &client, CClientStats &stats)
  5143. {
  5144. IMPERSONATE_USER(client);
  5145. int handle;
  5146. __int64 pos;
  5147. __int64 len;
  5148. StringAttr srcname;
  5149. msg.read(handle).read(srcname).read(pos).read(len);
  5150. IFileIO *fileio;
  5151. checkFileIOHandle(reply, handle, fileio);
  5152. Owned<IFile> file = createIFile(srcname.get());
  5153. __int64 written = fileio->appendFile(file,pos,len);
  5154. stats.addWrite(written);
  5155. if (TF_TRACE)
  5156. PROGLOG("append file, handle = %d, file=%s, pos = %" I64F "d len = %" I64F "d written = %" I64F "d",handle,srcname.get(),pos,len,written);
  5157. reply.append((unsigned)RFEnoerror).append(written);
  5158. }
  5159. void cmdIsFile(MemoryBuffer &msg, MemoryBuffer &reply, CRemoteClientHandler &client)
  5160. {
  5161. IMPERSONATE_USER(client);
  5162. StringAttr name;
  5163. msg.read(name);
  5164. if (TF_TRACE)
  5165. PROGLOG("isFile, '%s'",name.get());
  5166. Owned<IFile> file=createIFile(name);
  5167. unsigned ret = (unsigned)file->isFile();
  5168. reply.append((unsigned)RFEnoerror).append(ret);
  5169. }
  5170. void cmdIsDir(MemoryBuffer &msg, MemoryBuffer &reply, CRemoteClientHandler &client)
  5171. {
  5172. IMPERSONATE_USER(client);
  5173. StringAttr name;
  5174. msg.read(name);
  5175. if (TF_TRACE)
  5176. PROGLOG("isDir, '%s'",name.get());
  5177. Owned<IFile> file=createIFile(name);
  5178. unsigned ret = (unsigned)file->isDirectory();
  5179. reply.append((unsigned)RFEnoerror).append(ret);
  5180. }
  5181. void cmdIsReadOnly(MemoryBuffer &msg, MemoryBuffer &reply, CRemoteClientHandler &client)
  5182. {
  5183. IMPERSONATE_USER(client);
  5184. StringAttr name;
  5185. msg.read(name);
  5186. if (TF_TRACE)
  5187. PROGLOG("isReadOnly, '%s'",name.get());
  5188. Owned<IFile> file=createIFile(name);
  5189. unsigned ret = (unsigned)file->isReadOnly();
  5190. reply.append((unsigned)RFEnoerror).append(ret);
  5191. }
  5192. void cmdSetReadOnly(MemoryBuffer &msg, MemoryBuffer &reply, CRemoteClientHandler &client)
  5193. {
  5194. IMPERSONATE_USER(client);
  5195. StringAttr name;
  5196. bool set;
  5197. msg.read(name).read(set);
  5198. if (TF_TRACE)
  5199. PROGLOG("setReadOnly, '%s' %d",name.get(),(int)set);
  5200. Owned<IFile> file=createIFile(name);
  5201. file->setReadOnly(set);
  5202. reply.append((unsigned)RFEnoerror);
  5203. }
  5204. void cmdSetFilePerms(MemoryBuffer &msg, MemoryBuffer &reply, CRemoteClientHandler &client)
  5205. {
  5206. IMPERSONATE_USER(client);
  5207. StringAttr name;
  5208. unsigned fPerms;
  5209. msg.read(name).read(fPerms);
  5210. if (TF_TRACE)
  5211. PROGLOG("setFilePerms, '%s' 0%o",name.get(),fPerms);
  5212. Owned<IFile> file=createIFile(name);
  5213. file->setFilePermissions(fPerms);
  5214. reply.append((unsigned)RFEnoerror);
  5215. }
  5216. void cmdGetTime(MemoryBuffer &msg, MemoryBuffer &reply, CRemoteClientHandler &client)
  5217. {
  5218. IMPERSONATE_USER(client);
  5219. StringAttr name;
  5220. msg.read(name);
  5221. if (TF_TRACE)
  5222. PROGLOG("getTime, '%s'",name.get());
  5223. Owned<IFile> file=createIFile(name);
  5224. CDateTime createTime;
  5225. CDateTime modifiedTime;
  5226. CDateTime accessedTime;
  5227. bool ret = file->getTime(&createTime,&modifiedTime,&accessedTime);
  5228. reply.append((unsigned)RFEnoerror).append(ret);
  5229. if (ret)
  5230. {
  5231. createTime.serialize(reply);
  5232. modifiedTime.serialize(reply);
  5233. accessedTime.serialize(reply);
  5234. }
  5235. }
  5236. void cmdSetTime(MemoryBuffer &msg, MemoryBuffer &reply, CRemoteClientHandler &client)
  5237. {
  5238. IMPERSONATE_USER(client);
  5239. StringAttr name;
  5240. bool creategot;
  5241. CDateTime createTime;
  5242. bool modifiedgot;
  5243. CDateTime modifiedTime;
  5244. bool accessedgot;
  5245. CDateTime accessedTime;
  5246. msg.read(name);
  5247. msg.read(creategot);
  5248. if (creategot)
  5249. createTime.deserialize(msg);
  5250. msg.read(modifiedgot);
  5251. if (modifiedgot)
  5252. modifiedTime.deserialize(msg);
  5253. msg.read(accessedgot);
  5254. if (accessedgot)
  5255. accessedTime.deserialize(msg);
  5256. if (TF_TRACE)
  5257. PROGLOG("setTime, '%s'",name.get());
  5258. Owned<IFile> file=createIFile(name);
  5259. bool ret = file->setTime(creategot?&createTime:NULL,modifiedgot?&modifiedTime:NULL,accessedgot?&accessedTime:NULL);
  5260. reply.append((unsigned)RFEnoerror).append(ret);
  5261. }
  5262. void cmdCreateDir(MemoryBuffer &msg, MemoryBuffer &reply, CRemoteClientHandler &client)
  5263. {
  5264. IMPERSONATE_USER(client);
  5265. StringAttr name;
  5266. msg.read(name);
  5267. if (TF_TRACE)
  5268. PROGLOG("CreateDir, '%s'",name.get());
  5269. Owned<IFile> dir=createIFile(name);
  5270. bool ret = dir->createDirectory();
  5271. reply.append((unsigned)RFEnoerror).append(ret);
  5272. }
  5273. void cmdGetDir(MemoryBuffer &msg, MemoryBuffer &reply, CRemoteClientHandler &client)
  5274. {
  5275. IMPERSONATE_USER(client);
  5276. StringAttr name;
  5277. StringAttr mask;
  5278. bool includedir;
  5279. bool sub;
  5280. byte stream = 0;
  5281. msg.read(name).read(mask).read(includedir).read(sub);
  5282. if (msg.remaining()>=sizeof(byte))
  5283. {
  5284. msg.read(stream);
  5285. if (stream==1)
  5286. client.opendir.clear();
  5287. }
  5288. if (TF_TRACE)
  5289. PROGLOG("GetDir, '%s', '%s', stream='%u'",name.get(),mask.get(),stream);
  5290. if (!stream && !containsFileWildcard(mask))
  5291. {
  5292. // if no streaming, and mask contains no wildcard, it is much more efficient to get the info without a directory iterator!
  5293. StringBuffer fullFilename(name);
  5294. addPathSepChar(fullFilename).append(mask);
  5295. Owned<IFile> iFile = createIFile(fullFilename);
  5296. // NB: This must preserve same serialization format as CRemoteDirectoryIterator::serialize produces for <=1 file.
  5297. reply.append((unsigned)RFEnoerror);
  5298. if (!iFile->exists())
  5299. reply.append((byte)0);
  5300. else
  5301. {
  5302. byte b=1;
  5303. reply.append(b);
  5304. bool isDir = foundYes == iFile->isDirectory();
  5305. reply.append(isDir);
  5306. reply.append(isDir ? 0 : iFile->size());
  5307. CDateTime dt;
  5308. iFile->getTime(nullptr, &dt, nullptr);
  5309. dt.serialize(reply);
  5310. reply.append(mask);
  5311. b = 0;
  5312. reply.append(b);
  5313. }
  5314. }
  5315. else
  5316. {
  5317. Owned<IFile> dir=createIFile(name);
  5318. Owned<IDirectoryIterator> iter;
  5319. if (stream>1)
  5320. iter.set(client.opendir);
  5321. else
  5322. {
  5323. iter.setown(dir->directoryFiles(mask.length()?mask.get():NULL,sub,includedir));
  5324. if (stream != 0)
  5325. client.opendir.set(iter);
  5326. }
  5327. if (!iter)
  5328. throw createDafsException(RFSERR_GetDirFailed, nullptr);
  5329. reply.append((unsigned)RFEnoerror);
  5330. if (CRemoteDirectoryIterator::serialize(reply,iter,stream?0x100000:0,stream<2))
  5331. {
  5332. if (stream != 0)
  5333. client.opendir.clear();
  5334. }
  5335. else
  5336. {
  5337. bool cont=true;
  5338. reply.append(cont);
  5339. }
  5340. }
  5341. }
  5342. void cmdMonitorDir(MemoryBuffer &msg, MemoryBuffer &reply, CRemoteClientHandler &client)
  5343. {
  5344. IMPERSONATE_USER(client);
  5345. StringAttr name;
  5346. StringAttr mask;
  5347. bool includedir;
  5348. bool sub;
  5349. unsigned checkinterval;
  5350. unsigned timeout;
  5351. __int64 cancelid; // not yet used
  5352. msg.read(name).read(mask).read(includedir).read(sub).read(checkinterval).read(timeout).read(cancelid);
  5353. byte isprev;
  5354. msg.read(isprev);
  5355. Owned<IDirectoryIterator> prev;
  5356. if (isprev==1)
  5357. {
  5358. SocketEndpoint ep;
  5359. CRemoteDirectoryIterator *di = new CRemoteDirectoryIterator(ep,name);
  5360. di->appendBuf(msg);
  5361. prev.setown(di);
  5362. }
  5363. if (TF_TRACE)
  5364. PROGLOG("MonitorDir, '%s' '%s'",name.get(),mask.get());
  5365. Owned<IFile> dir=createIFile(name);
  5366. Owned<IDirectoryDifferenceIterator> iter=dir->monitorDirectory(prev,mask.length()?mask.get():NULL,sub,includedir,checkinterval,timeout);
  5367. reply.append((unsigned)RFEnoerror);
  5368. byte state = (iter.get()==NULL)?0:1;
  5369. reply.append(state);
  5370. if (state==1)
  5371. CRemoteDirectoryIterator::serializeDiff(reply,iter);
  5372. }
  5373. void cmdCopySection(MemoryBuffer &msg, MemoryBuffer &reply, CRemoteClientHandler &client)
  5374. {
  5375. IMPERSONATE_USER(client);
  5376. StringAttr uuid;
  5377. StringAttr fromFile;
  5378. StringAttr toFile;
  5379. offset_t toOfs;
  5380. offset_t fromOfs;
  5381. offset_t size;
  5382. offset_t sizeDone=0;
  5383. offset_t totalSize=(offset_t)-1;
  5384. unsigned timeout;
  5385. msg.read(uuid).read(fromFile).read(toFile).read(toOfs).read(fromOfs).read(size).read(timeout);
  5386. AsyncCommandStatus status = asyncCommandManager.copySection(uuid,fromFile,toFile,toOfs,fromOfs,size,sizeDone,totalSize,timeout);
  5387. reply.append((unsigned)RFEnoerror).append((unsigned)status).append(sizeDone).append(totalSize);
  5388. }
  5389. static void treeCopyFile(RemoteFilename &srcfn, RemoteFilename &dstfn, const char *net, const char *mask, IpAddress &ip, bool usetmp, CThrottler *throttler, CFflags copyFlags=CFnone)
  5390. {
  5391. unsigned start = msTick();
  5392. Owned<IFile> dstfile = createIFile(dstfn);
  5393. // the following is really to check the dest node is up and working (otherwise not much point in continuing!)
  5394. if (dstfile->exists())
  5395. PROGLOG("TREECOPY overwriting '%s'",dstfile->queryFilename());
  5396. Owned<IFile> srcfile = createIFile(srcfn);
  5397. unsigned lastmin = 0;
  5398. if (!srcfn.queryIP().ipequals(dstfn.queryIP())) {
  5399. CriticalBlock block(treeCopyCrit);
  5400. for (;;) {
  5401. CDateTime dt;
  5402. offset_t sz;
  5403. try {
  5404. sz = srcfile->size();
  5405. if (sz==(offset_t)-1) {
  5406. if (TF_TRACE_TREE_COPY)
  5407. PROGLOG("TREECOPY source not found '%s'",srcfile->queryFilename());
  5408. break;
  5409. }
  5410. srcfile->getTime(NULL,&dt,NULL);
  5411. }
  5412. catch (IException *e) {
  5413. EXCLOG(e,"treeCopyFile(1)");
  5414. e->Release();
  5415. break;
  5416. }
  5417. Linked<CTreeCopyItem> tc;
  5418. unsigned now = msTick();
  5419. ForEachItemInRev(i1,treeCopyArray) {
  5420. CTreeCopyItem &item = treeCopyArray.item(i1);
  5421. // prune old entries (not strictly needed buf I think better)
  5422. if (now-item.lastused>TREECOPYPRUNETIME)
  5423. treeCopyArray.remove(i1);
  5424. else if (!tc.get()&&item.equals(srcfn,net,mask,sz,dt)) {
  5425. tc.set(&item);
  5426. item.lastused = now;
  5427. }
  5428. }
  5429. if (!tc.get()) {
  5430. if (treeCopyArray.ordinality()>=TREECOPY_CACHE_SIZE)
  5431. treeCopyArray.remove(0);
  5432. tc.setown(new CTreeCopyItem(srcfn,net,mask,sz,dt));
  5433. treeCopyArray.append(*tc.getLink());
  5434. }
  5435. ForEachItemInRev(cand,tc->loc) { // rev to choose copied locations first (maybe optional?)
  5436. if (!tc->busy->testSet(cand)) {
  5437. // check file accessible and matches
  5438. if (!cand&&dstfn.equals(tc->loc.item(cand))) // hmm trying to overwrite existing, better humor
  5439. continue;
  5440. bool ok = true;
  5441. Owned<IFile> rmtfile = createIFile(tc->loc.item(cand));
  5442. if (cand) { // only need to check if remote
  5443. try {
  5444. if (rmtfile->size()!=sz)
  5445. ok = false;
  5446. else {
  5447. CDateTime fdt;
  5448. rmtfile->getTime(NULL,&fdt,NULL);
  5449. ok = fdt.equals(dt);
  5450. }
  5451. }
  5452. catch (IException *e) {
  5453. EXCLOG(e,"treeCopyFile(2)");
  5454. e->Release();
  5455. ok = false;
  5456. }
  5457. }
  5458. if (ok) { // if not ok leave 'busy'
  5459. // finally lets try and copy!
  5460. try {
  5461. if (TF_TRACE_TREE_COPY)
  5462. PROGLOG("TREECOPY(started) %s to %s",rmtfile->queryFilename(),dstfile->queryFilename());
  5463. {
  5464. CriticalUnblock unblock(treeCopyCrit); // note we have tc linked
  5465. rmtfile->copyTo(dstfile,DEFAULT_COPY_BLKSIZE,NULL,usetmp,copyFlags);
  5466. }
  5467. if (TF_TRACE_TREE_COPY)
  5468. PROGLOG("TREECOPY(done) %s to %s",rmtfile->queryFilename(),dstfile->queryFilename());
  5469. tc->busy->set(cand,false);
  5470. if (treeCopyWaiting)
  5471. treeCopySem.signal((treeCopyWaiting>1)?2:1);
  5472. // add to known locations
  5473. tc->busy->set(tc->loc.ordinality(),false); // prob already is clear
  5474. tc->loc.append(dstfn);
  5475. ip.ipset(tc->loc.item(cand).queryIP());
  5476. return;
  5477. }
  5478. catch (IException *e) {
  5479. if (cand==0) {
  5480. tc->busy->set(0,false); // don't leave busy
  5481. if (treeCopyWaiting)
  5482. treeCopySem.signal();
  5483. throw; // what more can we do!
  5484. }
  5485. EXCLOG(e,"treeCopyFile(3)");
  5486. e->Release();
  5487. }
  5488. }
  5489. }
  5490. }
  5491. // all locations busy
  5492. if (msTick()-start>TREECOPYTIMEOUT) {
  5493. WARNLOG("Treecopy %s wait timed out", srcfile->queryFilename());
  5494. break;
  5495. }
  5496. treeCopyWaiting++; // note this isn't precise - just indication
  5497. {
  5498. CriticalUnblock unblock(treeCopyCrit);
  5499. if (throttler)
  5500. {
  5501. CThrottleReleaseBlock block(*throttler, RFCtreecopy);
  5502. treeCopySem.wait(TREECOPYPOLLTIME);
  5503. }
  5504. else
  5505. treeCopySem.wait(TREECOPYPOLLTIME);
  5506. }
  5507. treeCopyWaiting--;
  5508. if ((msTick()-start)/10*1000!=lastmin) {
  5509. lastmin = (msTick()-start)/10*1000;
  5510. PROGLOG("treeCopyFile delayed: %s to %s",srcfile->queryFilename(),dstfile->queryFilename());
  5511. }
  5512. }
  5513. }
  5514. else if (TF_TRACE_TREE_COPY)
  5515. PROGLOG("TREECOPY source on same node as destination");
  5516. if (TF_TRACE_TREE_COPY)
  5517. PROGLOG("TREECOPY(started,fallback) %s to %s",srcfile->queryFilename(),dstfile->queryFilename());
  5518. try {
  5519. GetHostIp(ip);
  5520. srcfile->copyTo(dstfile,DEFAULT_COPY_BLKSIZE,NULL,usetmp,copyFlags);
  5521. }
  5522. catch (IException *e) {
  5523. EXCLOG(e,"TREECOPY(done,fallback)");
  5524. throw;
  5525. }
  5526. if (TF_TRACE_TREE_COPY)
  5527. PROGLOG("TREECOPY(done,fallback) %s to %s",srcfile->queryFilename(),dstfile->queryFilename());
  5528. }
  5529. void cmdTreeCopy(MemoryBuffer &msg, MemoryBuffer &reply, CRemoteClientHandler &client, CThrottler *throttler, bool usetmp=false)
  5530. {
  5531. IMPERSONATE_USER(client);
  5532. RemoteFilename src;
  5533. src.deserialize(msg);
  5534. RemoteFilename dst;
  5535. dst.deserialize(msg);
  5536. StringAttr net;
  5537. StringAttr mask;
  5538. msg.read(net).read(mask);
  5539. IpAddress ip;
  5540. treeCopyFile(src,dst,net,mask,ip,usetmp,throttler);
  5541. unsigned status = 0;
  5542. reply.append((unsigned)RFEnoerror).append((unsigned)status);
  5543. ip.ipserialize(reply);
  5544. }
  5545. void cmdTreeCopyTmp(MemoryBuffer &msg, MemoryBuffer &reply, CRemoteClientHandler &client, CThrottler *throttler)
  5546. {
  5547. cmdTreeCopy(msg, reply, client, throttler, true);
  5548. }
  5549. void cmdGetCRC(MemoryBuffer &msg, MemoryBuffer &reply, CRemoteClientHandler &client)
  5550. {
  5551. IMPERSONATE_USER(client);
  5552. StringAttr name;
  5553. msg.read(name);
  5554. if (TF_TRACE)
  5555. PROGLOG("getCRC, '%s'",name.get());
  5556. Owned<IFile> file=createIFile(name);
  5557. unsigned ret = file->getCRC();
  5558. reply.append((unsigned)RFEnoerror).append(ret);
  5559. }
  5560. void cmdStop(MemoryBuffer &msg, MemoryBuffer &reply)
  5561. {
  5562. PROGLOG("Abort request received");
  5563. stopping = true;
  5564. if (acceptsock)
  5565. acceptsock->cancel_accept();
  5566. if (securesock)
  5567. securesock->cancel_accept();
  5568. reply.append((unsigned)RFEnoerror);
  5569. }
  5570. void cmdExec(MemoryBuffer &msg, MemoryBuffer &reply, CRemoteClientHandler &client)
  5571. {
  5572. StringAttr cmdLine;
  5573. msg.read(cmdLine);
  5574. // NB: legacy remoteExec used to simply pass error code and buffer back to caller.
  5575. VStringBuffer errMsg("Remote command execution no longer supported. Trying to execute cmdline=%s", cmdLine.get());
  5576. WARNLOG("%s", errMsg.str());
  5577. size32_t outSz = errMsg.length()+1; // reply with null terminated string
  5578. // reply with error code -1
  5579. reply.append((unsigned)-1).append((unsigned)0).append(outSz).append(outSz, errMsg.str());
  5580. }
  5581. void cmdSetTrace(MemoryBuffer &msg, MemoryBuffer &reply)
  5582. {
  5583. byte flags;
  5584. msg.read(flags);
  5585. int retcode=-1;
  5586. if (flags!=255) // escape
  5587. {
  5588. retcode = traceFlags;
  5589. traceFlags = flags;
  5590. }
  5591. reply.append(retcode);
  5592. }
  5593. void cmdGetInfo(MemoryBuffer &msg, MemoryBuffer &reply)
  5594. {
  5595. unsigned level=1;
  5596. if (msg.remaining() >= sizeof(unsigned))
  5597. msg.read(level);
  5598. StringBuffer retstr;
  5599. getInfo(retstr, level);
  5600. reply.append(RFEnoerror).append(retstr.str());
  5601. }
  5602. void cmdFirewall(MemoryBuffer &msg, MemoryBuffer &reply)
  5603. {
  5604. // TBD
  5605. StringBuffer retstr;
  5606. getInfo(retstr);
  5607. reply.append(RFEnoerror).append(retstr.str());
  5608. }
  5609. void cmdExtractBlobElements(MemoryBuffer &msg, MemoryBuffer &reply, CRemoteClientHandler &client)
  5610. {
  5611. IMPERSONATE_USER(client);
  5612. StringAttr prefix;
  5613. StringAttr filename;
  5614. msg.read(prefix).read(filename);
  5615. RemoteFilename rfn;
  5616. rfn.setLocalPath(filename);
  5617. ExtractedBlobArray extracted;
  5618. extractBlobElements(prefix, rfn, extracted);
  5619. unsigned n = extracted.ordinality();
  5620. reply.append((unsigned)RFEnoerror).append(n);
  5621. for (unsigned i=0;i<n;i++)
  5622. extracted.item(i).serialize(reply);
  5623. }
  5624. void cmdUnlock(MemoryBuffer & msg, MemoryBuffer & reply,CRemoteClientHandler &client)
  5625. {
  5626. // this is an attempt to authenticate when we haven't got authentication turned on
  5627. if (TF_TRACE_CLIENT_STATS)
  5628. {
  5629. StringBuffer s(client.queryPeerName());
  5630. PROGLOG("Connect from %s",s.str());
  5631. }
  5632. throw createDafsException(RFSERR_InvalidCommand, nullptr);
  5633. }
  5634. void cmdStreamReadCommon(MemoryBuffer & msg, MemoryBuffer & reply, CRemoteClientHandler &client)
  5635. {
  5636. size32_t jsonSz = msg.remaining();
  5637. Owned<IPropertyTree> requestTree = createPTreeFromJSONString(jsonSz, (const char *)msg.readDirect(jsonSz));
  5638. /* Example JSON request:
  5639. * {
  5640. * "format" : "xml",
  5641. * "handle" : "1234",
  5642. * "node" : {
  5643. * "kind" : "diskread",
  5644. * "fileName": "examplefilename",
  5645. * "keyFilter" : "f1='1 '",
  5646. * "chooseN" : 5,
  5647. * "compressed" : "false"
  5648. * "input" : {
  5649. * "f1" : "string5",
  5650. * "f2" : "string5"
  5651. * },
  5652. * "output" : {
  5653. * "f2" : "string",
  5654. * "f1" : "real"
  5655. * }
  5656. * }
  5657. * }
  5658. * OR
  5659. * {
  5660. * "format" : "xml",
  5661. * "handle" : "1234",
  5662. * "node" : {
  5663. * "kind" : "indexread",
  5664. * "fileName": "examplefilename",
  5665. * "keyLilter" : "f1='1 '",
  5666. * "rowLimit" : 5,
  5667. * "input" : {
  5668. * "f1" : "string5",
  5669. * "f2" : "string5"
  5670. * },
  5671. * "output" : {
  5672. * "f2" : "string",
  5673. * "f1" : "real"
  5674. * }
  5675. * }
  5676. * }
  5677. * OR
  5678. * {
  5679. * "format" : "xml",
  5680. * "node" : {
  5681. * "kind" : "indexcount",
  5682. * "fileName": "examplefilename",
  5683. * "keyFilter" : "f1='1 '",
  5684. * "rowLimit" : 5
  5685. * "input" : {
  5686. * "f1" : "string5",
  5687. * "f2" : "string5"
  5688. * },
  5689. * }
  5690. * }
  5691. *
  5692. */
  5693. int cursorHandle = requestTree->getPropInt("handle");
  5694. OutputFormat outputFormat = outFmt_Xml;
  5695. Owned<IRemoteActivity> outputActivity;
  5696. OpenFileInfo fileInfo;
  5697. if (!cursorHandle)
  5698. {
  5699. const char *outputFmtStr = requestTree->queryProp("format");
  5700. if (nullptr == outputFmtStr)
  5701. outputFormat = outFmt_Xml; // default
  5702. else if (strieq("xml", outputFmtStr))
  5703. outputFormat = outFmt_Xml;
  5704. else if (strieq("json", outputFmtStr))
  5705. outputFormat = outFmt_Json;
  5706. else if (strieq("binary", outputFmtStr))
  5707. outputFormat = outFmt_Binary;
  5708. else
  5709. throw MakeStringException(0, "Unrecognised output format: %s", outputFmtStr);
  5710. // In future this may be passed the request and build a chain of activities and return sink.
  5711. outputActivity.setown(createOutputActivity(*requestTree));
  5712. StringBuffer requestStr("jsonrequest:");
  5713. outputActivity->getInfoStr(requestStr);
  5714. Owned<StringAttrItem> name = new StringAttrItem(requestStr);
  5715. CriticalBlock block(sect);
  5716. cursorHandle = getNextHandle();
  5717. client.previdx = client.openFiles.ordinality();
  5718. client.openFiles.append(OpenFileInfo(cursorHandle, outputActivity, name, outputFormat));
  5719. }
  5720. else if (!lookupFileIOHandle(cursorHandle, fileInfo))
  5721. cursorHandle = 0; // challenge response ..
  5722. else // known handle, continuation
  5723. {
  5724. outputActivity.set(fileInfo.activity);
  5725. outputFormat = fileInfo.format;
  5726. }
  5727. if (outputActivity && requestTree->hasProp("cursorBin")) // use handle if one provided
  5728. {
  5729. MemoryBuffer cursorMb;
  5730. cursorMb.setEndian(__BIG_ENDIAN);
  5731. JBASE64_Decode(requestTree->queryProp("cursorBin"), cursorMb);
  5732. outputActivity->restoreCursor(cursorMb);
  5733. }
  5734. Owned<IXmlWriterExt> responseWriter; // for xml or json response
  5735. if (outFmt_Binary == outputFormat)
  5736. reply.append(cursorHandle);
  5737. else // outFmt_Xml || outFmt_Json
  5738. {
  5739. responseWriter.setown(createIXmlWriterExt(0, 0, nullptr, outFmt_Xml == outputFormat ? WTStandard : WTJSON));
  5740. responseWriter->outputBeginNested("Response", true);
  5741. responseWriter->outputUInt(cursorHandle, sizeof(cursorHandle), "handle");
  5742. }
  5743. if (cursorHandle)
  5744. {
  5745. IOutputMetaData *out = outputActivity->queryOutputMeta();
  5746. bool grouped = outputActivity->isGrouped();
  5747. bool eoi=false;
  5748. MemoryBuffer resultBuffer;
  5749. MemoryBufferBuilder outBuilder(resultBuffer, out->getMinRecordSize());
  5750. if (outFmt_Binary == outputFormat)
  5751. {
  5752. DelayedSizeMarker dataLenMarker(reply); // data length
  5753. outBuilder.setBuffer(reply); // write direct to reply buffer for efficiency
  5754. if (grouped)
  5755. {
  5756. bool pastFirstRow = outputActivity->queryProcessed()>0;
  5757. for (unsigned i=0; i<defaultDaFSNumRecs; i++)
  5758. {
  5759. size32_t eogPos = 0;
  5760. if (pastFirstRow)
  5761. {
  5762. /* this is for last row output, which might have been returned in the previous request
  5763. * The eog marker may change as a result of the next row (see writeDirect() call below);
  5764. */
  5765. eogPos = reply.length();
  5766. reply.append(false);
  5767. }
  5768. size32_t rowSz;
  5769. const void *row = outputActivity->nextRow(outBuilder, rowSz);
  5770. if (!row)
  5771. {
  5772. if (!pastFirstRow)
  5773. {
  5774. eoi = true;
  5775. break;
  5776. }
  5777. else
  5778. {
  5779. bool eog = true;
  5780. reply.writeDirect(eogPos, sizeof(eog), &eog);
  5781. row = outputActivity->nextRow(outBuilder, rowSz);
  5782. if (!row)
  5783. {
  5784. eoi = true;
  5785. break;
  5786. }
  5787. }
  5788. }
  5789. pastFirstRow = true;
  5790. }
  5791. }
  5792. else
  5793. {
  5794. for (unsigned i=0; i<defaultDaFSNumRecs; i++)
  5795. {
  5796. size32_t rowSz;
  5797. const void *row = outputActivity->nextRow(outBuilder, rowSz);
  5798. if (!row)
  5799. {
  5800. eoi = true;
  5801. break;
  5802. }
  5803. }
  5804. }
  5805. dataLenMarker.write();
  5806. DelayedSizeMarker cursorLenMarker(reply); // cursor length
  5807. if (!eoi)
  5808. outputActivity->serializeCursor(reply);
  5809. cursorLenMarker.write();
  5810. }
  5811. else
  5812. {
  5813. if (grouped)
  5814. {
  5815. bool pastFirstRow = outputActivity->queryProcessed()>0;
  5816. for (unsigned __int64 i=0; i<defaultDaFSNumRecs; i++)
  5817. {
  5818. size32_t rowSz;
  5819. const void *row = outputActivity->nextRow(outBuilder, rowSz);
  5820. if (!row)
  5821. {
  5822. if (!pastFirstRow)
  5823. {
  5824. eoi = true;
  5825. break;
  5826. }
  5827. else
  5828. {
  5829. responseWriter->outputBeginNested("Eog", false);
  5830. responseWriter->outputEndNested("Eog");
  5831. row = outputActivity->nextRow(outBuilder, rowSz);
  5832. if (!row)
  5833. {
  5834. eoi = true;
  5835. break;
  5836. }
  5837. }
  5838. }
  5839. responseWriter->outputBeginNested("Row", true);
  5840. out->toXML((const byte *)row, *responseWriter);
  5841. responseWriter->outputEndNested("Row");
  5842. resultBuffer.clear();
  5843. pastFirstRow = true;
  5844. }
  5845. }
  5846. else
  5847. {
  5848. for (unsigned __int64 i=0; i<defaultDaFSNumRecs; i++)
  5849. {
  5850. size32_t rowSz;
  5851. const void *row = outputActivity->nextRow(outBuilder, rowSz);
  5852. if (!row)
  5853. {
  5854. eoi = true;
  5855. break;
  5856. }
  5857. responseWriter->outputBeginNested("Row", true);
  5858. out->toXML((const byte *)row, *responseWriter);
  5859. responseWriter->outputEndNested("Row");
  5860. resultBuffer.clear();
  5861. }
  5862. }
  5863. if (!eoi)
  5864. {
  5865. MemoryBuffer cursorMb;
  5866. cursorMb.setEndian(__BIG_ENDIAN);
  5867. outputActivity->serializeCursor(cursorMb);
  5868. StringBuffer cursorBinStr;
  5869. JBASE64_Encode(cursorMb.toByteArray(), cursorMb.length(), cursorBinStr);
  5870. responseWriter->outputString(cursorBinStr.length(), cursorBinStr.str(), "cursorBin");
  5871. }
  5872. }
  5873. }
  5874. if (outFmt_Binary != outputFormat)
  5875. {
  5876. responseWriter->outputEndNested("Response");
  5877. PROGLOG("Response: %s", responseWriter->str());
  5878. reply.append(responseWriter->length(), responseWriter->str());
  5879. }
  5880. }
  5881. void cmdStreamReadTestSocket(MemoryBuffer & msg, MemoryBuffer & reply, CRemoteClientHandler &client)
  5882. {
  5883. reply.append('J');
  5884. /* testsocket is not actually passing in a command, and is interpreting '{' as the cmd to get here.
  5885. * so rewind so it can be read/parsed as JSON by cmdStreamRead
  5886. */
  5887. msg.reset(msg.getPos()-sizeof(RemoteFileCommandType));
  5888. cmdStreamReadCommon(msg, reply, client);
  5889. }
  5890. void cmdStreamReadStd(MemoryBuffer & msg, MemoryBuffer & reply, CRemoteClientHandler &client)
  5891. {
  5892. reply.append(RFEnoerror);
  5893. cmdStreamReadCommon(msg, reply, client);
  5894. }
  5895. // legacy version
  5896. void cmdSetThrottle(MemoryBuffer & msg, MemoryBuffer & reply)
  5897. {
  5898. unsigned limit, delayMs, cpuThreshold;
  5899. msg.read(limit);
  5900. msg.read(delayMs);
  5901. msg.read(cpuThreshold);
  5902. stdCmdThrottler.configure(limit, delayMs, cpuThreshold, (unsigned)-1);
  5903. reply.append((unsigned)RFEnoerror);
  5904. }
  5905. void cmdSetThrottle2(MemoryBuffer & msg, MemoryBuffer & reply)
  5906. {
  5907. unsigned throttleClass, limit, delayMs, cpuThreshold, queueLimit;
  5908. msg.read(throttleClass);
  5909. msg.read(limit);
  5910. msg.read(delayMs);
  5911. msg.read(cpuThreshold);
  5912. msg.read(queueLimit);
  5913. setThrottle((ThrottleClass)throttleClass, limit, delayMs, cpuThreshold, queueLimit);
  5914. reply.append((unsigned)RFEnoerror);
  5915. }
  5916. void formatException(MemoryBuffer &reply, IException *e, RemoteFileCommandType cmd, bool testSocketFlag, unsigned _dfsErrorCode, CRemoteClientHandler *client)
  5917. {
  5918. unsigned dfsErrorCode = _dfsErrorCode;
  5919. if (!dfsErrorCode)
  5920. {
  5921. if (e)
  5922. dfsErrorCode = (QUERYINTERFACE(e, IDAFS_Exception)) ? e->errorCode() : RFSERR_InternalError;
  5923. else
  5924. dfsErrorCode = RFSERR_InternalError;
  5925. }
  5926. VStringBuffer errMsg("ERROR: cmd=%s, error=%s", getRFCText(cmd), getRFSERRText(dfsErrorCode));
  5927. if (e)
  5928. {
  5929. errMsg.appendf(" (%u, ", e->errorCode());
  5930. unsigned len = errMsg.length();
  5931. e->errorMessage(errMsg);
  5932. if (len == errMsg.length())
  5933. errMsg.setLength(len-2); // strip off ", " if no message in exception
  5934. errMsg.append(")");
  5935. }
  5936. if (testSocketFlag)
  5937. reply.append('-');
  5938. else
  5939. reply.append(dfsErrorCode);
  5940. reply.append(errMsg.str());
  5941. if (client && cmd!=RFCunlock)
  5942. {
  5943. const char *peer = client->queryPeerName();
  5944. if (peer)
  5945. {
  5946. VStringBuffer err("%s. Client: %s", errMsg.str(), peer);
  5947. PROGLOG("%s", err.str());
  5948. }
  5949. client->logPrevHandle();
  5950. }
  5951. }
  5952. void throttleCommand(RemoteFileCommandType cmd, MemoryBuffer &msg, CRemoteClientHandler *client)
  5953. {
  5954. switch (cmd)
  5955. {
  5956. case RFCexec:
  5957. case RFCgetcrc:
  5958. case RFCcopy:
  5959. case RFCappend:
  5960. case RFCtreecopy:
  5961. case RFCtreecopytmp:
  5962. slowCmdThrottler.addCommand(cmd, msg, client);
  5963. return;
  5964. case RFCcloseIO:
  5965. case RFCopenIO:
  5966. case RFCread:
  5967. case RFCsize:
  5968. case RFCwrite:
  5969. case RFCexists:
  5970. case RFCremove:
  5971. case RFCrename:
  5972. case RFCgetver:
  5973. case RFCisfile:
  5974. case RFCisdirectory:
  5975. case RFCisreadonly:
  5976. case RFCsetreadonly:
  5977. case RFCsetfileperms:
  5978. case RFCreadfilteredindex:
  5979. case RFCreadfilteredindexcount:
  5980. case RFCreadfilteredindexblob:
  5981. case RFCgettime:
  5982. case RFCsettime:
  5983. case RFCcreatedir:
  5984. case RFCgetdir:
  5985. case RFCmonitordir:
  5986. case RFCstop:
  5987. case RFCextractblobelements:
  5988. case RFCredeploy:
  5989. case RFCmove:
  5990. case RFCsetsize:
  5991. case RFCsettrace:
  5992. case RFCgetinfo:
  5993. case RFCfirewall:
  5994. case RFCunlock:
  5995. case RFCStreamRead:
  5996. case RFCStreamReadTestSocket:
  5997. stdCmdThrottler.addCommand(cmd, msg, client);
  5998. return;
  5999. // NB: The following commands are still bound by the the thread pool
  6000. case RFCsetthrottle: // legacy version
  6001. case RFCsetthrottle2:
  6002. case RFCcopysection: // slightly odd, but has it's own limit
  6003. default:
  6004. {
  6005. client->processCommand(cmd, msg, NULL);
  6006. break;
  6007. }
  6008. }
  6009. }
  6010. bool processCommand(RemoteFileCommandType cmd, MemoryBuffer & msg, MemoryBuffer & reply, CRemoteClientHandler *client, CThrottler *throttler)
  6011. {
  6012. Owned<CClientStats> stats = clientStatsTable.getClientReference(cmd, client->queryPeerName());
  6013. bool testSocketFlag = false;
  6014. unsigned posOfErr = reply.length();
  6015. try
  6016. {
  6017. switch(cmd)
  6018. {
  6019. MAPCOMMANDSTATS(RFCread, cmdRead, *stats);
  6020. MAPCOMMANDSTATS(RFCwrite, cmdWrite, *stats);
  6021. MAPCOMMANDCLIENTSTATS(RFCappend, cmdAppend, *client, *stats);
  6022. MAPCOMMAND(RFCcloseIO, cmdCloseFileIO);
  6023. MAPCOMMANDCLIENT(RFCopenIO, cmdOpenFileIO, *client);
  6024. MAPCOMMAND(RFCsize, cmdSize);
  6025. MAPCOMMANDCLIENT(RFCexists, cmdExists, *client);
  6026. MAPCOMMANDCLIENT(RFCremove, cmdRemove, *client);
  6027. MAPCOMMANDCLIENT(RFCrename, cmdRename, *client);
  6028. MAPCOMMAND(RFCgetver, cmdGetVer);
  6029. MAPCOMMANDCLIENT(RFCisfile, cmdIsFile, *client);
  6030. MAPCOMMANDCLIENT(RFCisdirectory, cmdIsDir, *client);
  6031. MAPCOMMANDCLIENT(RFCisreadonly, cmdIsReadOnly, *client);
  6032. MAPCOMMANDCLIENT(RFCsetreadonly, cmdSetReadOnly, *client);
  6033. MAPCOMMANDCLIENT(RFCsetfileperms, cmdSetFilePerms, *client);
  6034. MAPCOMMANDCLIENT(RFCgettime, cmdGetTime, *client);
  6035. MAPCOMMANDCLIENT(RFCsettime, cmdSetTime, *client);
  6036. MAPCOMMANDCLIENT(RFCcreatedir, cmdCreateDir, *client);
  6037. MAPCOMMANDCLIENT(RFCgetdir, cmdGetDir, *client);
  6038. MAPCOMMANDCLIENT(RFCmonitordir, cmdMonitorDir, *client);
  6039. MAPCOMMAND(RFCstop, cmdStop);
  6040. MAPCOMMANDCLIENT(RFCexec, cmdExec, *client);
  6041. MAPCOMMANDCLIENT(RFCextractblobelements, cmdExtractBlobElements, *client);
  6042. MAPCOMMANDCLIENT(RFCgetcrc, cmdGetCRC, *client);
  6043. MAPCOMMANDCLIENT(RFCmove, cmdMove, *client);
  6044. MAPCOMMANDCLIENT(RFCcopy, cmdCopy, *client);
  6045. MAPCOMMAND(RFCsetsize, cmdSetSize);
  6046. MAPCOMMAND(RFCsettrace, cmdSetTrace);
  6047. MAPCOMMAND(RFCgetinfo, cmdGetInfo);
  6048. MAPCOMMAND(RFCfirewall, cmdFirewall);
  6049. MAPCOMMANDCLIENT(RFCunlock, cmdUnlock, *client);
  6050. MAPCOMMANDCLIENTTESTSOCKET(RFCStreamReadTestSocket, cmdStreamReadTestSocket, *client);
  6051. MAPCOMMANDCLIENT(RFCStreamRead, cmdStreamReadStd, *client);
  6052. MAPCOMMANDCLIENT(RFCcopysection, cmdCopySection, *client);
  6053. MAPCOMMANDCLIENTTHROTTLE(RFCtreecopy, cmdTreeCopy, *client, &slowCmdThrottler);
  6054. MAPCOMMANDCLIENTTHROTTLE(RFCtreecopytmp, cmdTreeCopyTmp, *client, &slowCmdThrottler);
  6055. MAPCOMMAND(RFCsetthrottle, cmdSetThrottle); // legacy version
  6056. MAPCOMMAND(RFCsetthrottle2, cmdSetThrottle2);
  6057. default:
  6058. formatException(reply, nullptr, cmd, false, RFSERR_InvalidCommand, client);
  6059. break;
  6060. }
  6061. }
  6062. catch (IException *e)
  6063. {
  6064. reply.setWritePos(posOfErr);
  6065. formatException(reply, e, cmd, testSocketFlag, 0, client);
  6066. }
  6067. return testSocketFlag;
  6068. }
  6069. IPooledThread *createCommandProcessor()
  6070. {
  6071. return new cCommandProcessor();
  6072. }
  6073. void run(DAFSConnectCfg _connectMethod, SocketEndpoint &listenep, unsigned sslPort)
  6074. {
  6075. SocketEndpoint sslep(listenep);
  6076. if (sslPort)
  6077. sslep.port = sslPort;
  6078. else
  6079. sslep.port = securitySettings.daFileSrvSSLPort;
  6080. Owned<ISocket> acceptSocket, acceptSSLSocket;
  6081. if (_connectMethod != SSLOnly)
  6082. {
  6083. if (listenep.port == 0)
  6084. throw createDafsException(DAFSERR_serverinit_failed, "dafilesrv port not specified");
  6085. if (listenep.isNull())
  6086. acceptSocket.setown(ISocket::create(listenep.port));
  6087. else
  6088. {
  6089. StringBuffer ips;
  6090. listenep.getIpText(ips);
  6091. acceptSocket.setown(ISocket::create_ip(listenep.port,ips.str()));
  6092. }
  6093. }
  6094. if (_connectMethod == SSLOnly || _connectMethod == SSLFirst || _connectMethod == UnsecureFirst)
  6095. {
  6096. if (sslep.port == 0)
  6097. throw createDafsException(DAFSERR_serverinit_failed, "Secure dafilesrv port not specified");
  6098. if (_connectMethod == UnsecureFirst)
  6099. {
  6100. // don't fail, but warn - this allows for fast SSL client rejections
  6101. if (!securitySettings.certificate)
  6102. WARNLOG("SSL Certificate information not found in environment.conf, cannot accept SSL connections");
  6103. else if ( !checkFileExists(securitySettings.certificate) )
  6104. {
  6105. WARNLOG("SSL Certificate File not found in environment.conf, cannot accept SSL connections");
  6106. securitySettings.certificate = nullptr;
  6107. }
  6108. if (!securitySettings.privateKey)
  6109. WARNLOG("SSL Key information not found in environment.conf, cannot accept SSL connections");
  6110. else if ( !checkFileExists(securitySettings.privateKey) )
  6111. {
  6112. WARNLOG("SSL Key File not found in environment.conf, cannot accept SSL connections");
  6113. securitySettings.privateKey = nullptr;
  6114. }
  6115. }
  6116. else
  6117. {
  6118. if (!securitySettings.certificate)
  6119. throw createDafsException(DAFSERR_serverinit_failed, "SSL Certificate information not found in environment.conf");
  6120. if (!checkFileExists(securitySettings.certificate))
  6121. throw createDafsException(DAFSERR_serverinit_failed, "SSL Certificate File not found in environment.conf");
  6122. if (!securitySettings.privateKey)
  6123. throw createDafsException(DAFSERR_serverinit_failed, "SSL Key information not found in environment.conf");
  6124. if (!checkFileExists(securitySettings.privateKey))
  6125. throw createDafsException(DAFSERR_serverinit_failed, "SSL Key File not found in environment.conf");
  6126. }
  6127. if (sslep.isNull())
  6128. acceptSSLSocket.setown(ISocket::create(sslep.port));
  6129. else
  6130. {
  6131. StringBuffer ips;
  6132. sslep.getIpText(ips);
  6133. acceptSSLSocket.setown(ISocket::create_ip(sslep.port,ips.str()));
  6134. }
  6135. }
  6136. run(_connectMethod, acceptSocket.getClear(), acceptSSLSocket.getClear());
  6137. }
  6138. void run(DAFSConnectCfg _connectMethod, ISocket *regSocket, ISocket *secureSocket)
  6139. {
  6140. if (_connectMethod != SSLOnly)
  6141. {
  6142. if (regSocket)
  6143. acceptsock.setown(regSocket);
  6144. else
  6145. throw createDafsException(DAFSERR_serverinit_failed, "Invalid non-secure socket");
  6146. }
  6147. if (_connectMethod == SSLOnly || _connectMethod == SSLFirst || _connectMethod == UnsecureFirst)
  6148. {
  6149. if (secureSocket)
  6150. securesock.setown(secureSocket);
  6151. else
  6152. throw createDafsException(DAFSERR_serverinit_failed, "Invalid secure socket");
  6153. }
  6154. selecthandler->start();
  6155. for (;;)
  6156. {
  6157. Owned<ISocket> sock;
  6158. Owned<ISocket> sockSSL;
  6159. bool sockavail = false;
  6160. bool securesockavail = false;
  6161. if (_connectMethod == SSLNone)
  6162. sockavail = acceptsock->wait_read(1000*60*1)!=0;
  6163. else if (_connectMethod == SSLOnly)
  6164. securesockavail = securesock->wait_read(1000*60*1)!=0;
  6165. else
  6166. {
  6167. UnsignedArray readSocks;
  6168. UnsignedArray waitingSocks;
  6169. readSocks.append(acceptsock->OShandle());
  6170. readSocks.append(securesock->OShandle());
  6171. int numReady = wait_read_multiple(readSocks, 1000*60*1, waitingSocks);
  6172. if (numReady > 0)
  6173. {
  6174. for (int idx = 0; idx < numReady; idx++)
  6175. {
  6176. if (waitingSocks.item(idx) == acceptsock->OShandle())
  6177. sockavail = true;
  6178. else if (waitingSocks.item(idx) == securesock->OShandle())
  6179. securesockavail = true;
  6180. }
  6181. }
  6182. }
  6183. #if 0
  6184. if (!sockavail && !securesockavail)
  6185. {
  6186. JSocketStatistics stats;
  6187. getSocketStatistics(stats);
  6188. StringBuffer s;
  6189. getSocketStatisticsString(stats,s);
  6190. PROGLOG( "Socket statistics : \n%s\n",s.str());
  6191. }
  6192. #endif
  6193. if (stopping)
  6194. break;
  6195. if (sockavail || securesockavail)
  6196. {
  6197. if (sockavail)
  6198. {
  6199. try
  6200. {
  6201. sock.setown(acceptsock->accept(true));
  6202. if (!sock||stopping)
  6203. break;
  6204. #ifdef _DEBUG
  6205. SocketEndpoint eps;
  6206. sock->getPeerEndpoint(eps);
  6207. StringBuffer sb;
  6208. eps.getUrlStr(sb);
  6209. PROGLOG("Server accepting from %s", sb.str());
  6210. #endif
  6211. }
  6212. catch (IException *e)
  6213. {
  6214. EXCLOG(e,"CRemoteFileServer");
  6215. e->Release();
  6216. break;
  6217. }
  6218. }
  6219. if (securesockavail)
  6220. {
  6221. Owned<ISecureSocket> ssock;
  6222. try
  6223. {
  6224. sockSSL.setown(securesock->accept(true));
  6225. if (!sockSSL||stopping)
  6226. break;
  6227. if ( (_connectMethod == UnsecureFirst) && (!securitySettings.certificate || !securitySettings.privateKey) )
  6228. {
  6229. // for client secure_connect() to fail quickly ...
  6230. cleanupSocket(sockSSL);
  6231. sockSSL.clear();
  6232. securesockavail = false;
  6233. }
  6234. else
  6235. {
  6236. #ifdef _USE_OPENSSL
  6237. ssock.setown(createSecureSocket(sockSSL.getClear(), ServerSocket));
  6238. int status = ssock->secure_accept();
  6239. if (status < 0)
  6240. throw createDafsException(DAFSERR_serveraccept_failed,"Failure to establish secure connection");
  6241. sockSSL.setown(ssock.getLink());
  6242. #else
  6243. throw createDafsException(DAFSERR_serveraccept_failed,"Failure to establish secure connection: OpenSSL disabled in build");
  6244. #endif
  6245. #ifdef _DEBUG
  6246. SocketEndpoint eps;
  6247. sockSSL->getPeerEndpoint(eps);
  6248. StringBuffer sb;
  6249. eps.getUrlStr(sb);
  6250. PROGLOG("Server accepting SECURE from %s", sb.str());
  6251. #endif
  6252. }
  6253. }
  6254. catch (IJSOCK_Exception *e)
  6255. {
  6256. // accept failed ...
  6257. EXCLOG(e,"CRemoteFileServer (secure)");
  6258. e->Release();
  6259. break;
  6260. }
  6261. catch (IException *e) // IDAFS_Exception also ...
  6262. {
  6263. EXCLOG(e,"CRemoteFileServer1 (secure)");
  6264. e->Release();
  6265. cleanupSocket(sockSSL);
  6266. sockSSL.clear();
  6267. cleanupSocket(ssock);
  6268. ssock.clear();
  6269. securesockavail = false;
  6270. }
  6271. }
  6272. if (sockavail)
  6273. runClient(sock.getClear());
  6274. if (securesockavail)
  6275. runClient(sockSSL.getClear());
  6276. }
  6277. else
  6278. checkTimeout();
  6279. }
  6280. if (TF_TRACE_CLIENT_STATS)
  6281. PROGLOG("CRemoteFileServer:run exiting");
  6282. selecthandler->stop(true);
  6283. }
  6284. void processUnauthenticatedCommand(RemoteFileCommandType cmd, ISocket *socket, MemoryBuffer &msg)
  6285. {
  6286. // these are unauthenticated commands
  6287. if (cmd != RFCgetver)
  6288. cmd = RFCinvalid;
  6289. MemoryBuffer reply;
  6290. bool testSocketFlag = processCommand(cmd, msg, initSendBuffer(reply), NULL, NULL);
  6291. sendBuffer(socket, reply, testSocketFlag);
  6292. }
  6293. bool checkAuthentication(ISocket *socket, IAuthenticatedUser *&ret)
  6294. {
  6295. ret = NULL;
  6296. if (!AuthenticationEnabled)
  6297. return true;
  6298. MemoryBuffer reqbuf;
  6299. MemoryBuffer reply;
  6300. MemoryBuffer encbuf; // because aesEncrypt clears input
  6301. initSendBuffer(reply);
  6302. receiveBuffer(socket, reqbuf, 1);
  6303. RemoteFileCommandType typ=0;
  6304. if (reqbuf.remaining()<sizeof(RemoteFileCommandType))
  6305. return false;
  6306. reqbuf.read(typ);
  6307. if (typ!=RFCunlock)
  6308. {
  6309. processUnauthenticatedCommand(typ,socket,reqbuf);
  6310. return false;
  6311. }
  6312. if (reqbuf.remaining()<sizeof(OnceKey))
  6313. return false;
  6314. OnceKey oncekey;
  6315. reqbuf.read(sizeof(oncekey),&oncekey);
  6316. IpAddress ip;
  6317. socket->getPeerAddress(ip);
  6318. byte ipdata[16];
  6319. ip.getNetAddress(sizeof(ipdata),&ipdata);
  6320. mergeOnce(oncekey,sizeof(ipdata),&ipdata); // this is clients key
  6321. OnceKey mykey;
  6322. genOnce(mykey);
  6323. reply.append(RFEnoerror); // errcode
  6324. aesEncrypt(&oncekey,sizeof(oncekey),&mykey,sizeof(oncekey),encbuf);
  6325. reply.append(encbuf.length()).append(encbuf);
  6326. sendBuffer(socket, reply); // send my oncekey
  6327. reqbuf.clear();
  6328. receiveBuffer(socket, reqbuf, 1);
  6329. if (reqbuf.remaining()>sizeof(RemoteFileCommandType)+sizeof(size32_t))
  6330. {
  6331. reqbuf.read(typ);
  6332. if (typ==RFCunlockreply)
  6333. {
  6334. size32_t bs;
  6335. reqbuf.read(bs);
  6336. if (bs<=reqbuf.remaining())
  6337. {
  6338. MemoryBuffer userbuf;
  6339. aesDecrypt(&mykey,sizeof(mykey),reqbuf.readDirect(bs),bs,userbuf);
  6340. byte n;
  6341. userbuf.read(n);
  6342. if (n>=2)
  6343. {
  6344. StringAttr user;
  6345. StringAttr password;
  6346. userbuf.read(user).read(password);
  6347. Owned<IAuthenticatedUser> iau = createAuthenticatedUser();
  6348. if (iau->login(user,password))
  6349. {
  6350. initSendBuffer(reply.clear());
  6351. reply.append(RFEnoerror);
  6352. sendBuffer(socket, reply); // send OK
  6353. ret = iau;
  6354. return true;
  6355. }
  6356. }
  6357. }
  6358. }
  6359. }
  6360. reply.clear();
  6361. appendErr(reply, RFSERR_AuthenticateFailed);
  6362. sendBuffer(socket, reply); // send OK
  6363. return false;
  6364. }
  6365. void runClient(ISocket *sock)
  6366. {
  6367. cCommandProcessor::cCommandProcessorParams params;
  6368. IAuthenticatedUser *user=NULL;
  6369. bool authenticated = false;
  6370. try
  6371. {
  6372. if (checkAuthentication(sock,user))
  6373. authenticated = true;
  6374. }
  6375. catch (IException *e)
  6376. {
  6377. e->Release();
  6378. }
  6379. if (!authenticated)
  6380. {
  6381. try
  6382. {
  6383. sock->Release();
  6384. }
  6385. catch (IException *e)
  6386. {
  6387. e->Release();
  6388. }
  6389. return;
  6390. }
  6391. params.client = new CRemoteClientHandler(this,sock,user,globallasttick);
  6392. {
  6393. CriticalBlock block(sect);
  6394. clients.append(*LINK(params.client));
  6395. }
  6396. // NB: This could be blocked, by thread pool limit
  6397. threads->start(&params);
  6398. }
  6399. void stop()
  6400. {
  6401. // stop accept loop
  6402. if (TF_TRACE_CLIENT_STATS)
  6403. PROGLOG("CRemoteFileServer::stop");
  6404. if (acceptsock)
  6405. acceptsock->cancel_accept();
  6406. if (securesock)
  6407. securesock->cancel_accept();
  6408. threads->stopAll();
  6409. threads->joinAll(true,60*1000);
  6410. }
  6411. bool notify(CRemoteClientHandler *_client, MemoryBuffer &msg)
  6412. {
  6413. Linked<CRemoteClientHandler> client;
  6414. client.set(_client);
  6415. if (TF_TRACE_FULL)
  6416. PROGLOG("notify %d", msg.length());
  6417. if (msg.length())
  6418. {
  6419. if (TF_TRACE_FULL)
  6420. PROGLOG("notify CRemoteClientHandler(%p), msg length=%u", _client, msg.length());
  6421. cCommandProcessor::cCommandProcessorParams params;
  6422. params.client = client.getClear();
  6423. params.msg.swapWith(msg);
  6424. /* This can block because the thread pool is full and therefore block the selecthandler
  6425. * This is akin to the main server blocking post accept() for the same reason.
  6426. */
  6427. threads->start(&params);
  6428. }
  6429. else
  6430. onCloseSocket(client,3); // removes owned handles
  6431. return false;
  6432. }
  6433. void addClient(CRemoteClientHandler *client)
  6434. {
  6435. if (client&&client->socket)
  6436. selecthandler->add(client->socket,SELECTMODE_READ,client);
  6437. }
  6438. void checkTimeout()
  6439. {
  6440. if (msTick()-clientcounttick>1000*60*60)
  6441. {
  6442. CriticalBlock block(ClientCountSect);
  6443. if (TF_TRACE_CLIENT_STATS && (ClientCount || MaxClientCount))
  6444. PROGLOG("Client count = %d, max = %d", ClientCount, MaxClientCount);
  6445. clientcounttick = msTick();
  6446. MaxClientCount = ClientCount;
  6447. if (closedclients)
  6448. {
  6449. if (TF_TRACE_CLIENT_STATS)
  6450. PROGLOG("Closed client count = %d",closedclients);
  6451. closedclients = 0;
  6452. }
  6453. }
  6454. CriticalBlock block(sect);
  6455. ForEachItemInRev(i,clients)
  6456. {
  6457. CRemoteClientHandler &client = clients.item(i);
  6458. if (client.timedOut())
  6459. {
  6460. StringBuffer s;
  6461. bool ok = client.getInfo(s); // will spot duff sockets
  6462. if (ok&&(client.openFiles.ordinality()!=0))
  6463. {
  6464. if (TF_TRACE_CLIENT_CONN && client.inactiveTimedOut())
  6465. WARNLOG("Inactive %s",s.str());
  6466. }
  6467. else
  6468. {
  6469. #ifndef _DEBUG
  6470. if (TF_TRACE_CLIENT_CONN)
  6471. #endif
  6472. PROGLOG("Timing out %s",s.str());
  6473. closedclients++;
  6474. onCloseSocket(&client,4); // removes owned handles
  6475. }
  6476. }
  6477. }
  6478. }
  6479. void getInfo(StringBuffer &info, unsigned level=1)
  6480. {
  6481. {
  6482. CriticalBlock block(ClientCountSect);
  6483. info.append(VERSTRING).append('\n');
  6484. info.appendf("Client count = %d\n",ClientCount);
  6485. info.appendf("Max client count = %d",MaxClientCount);
  6486. }
  6487. CriticalBlock block(sect);
  6488. ForEachItemIn(i,clients)
  6489. {
  6490. info.newline().append(i).append(": ");
  6491. clients.item(i).getInfo(info);
  6492. }
  6493. info.newline().appendf("Running threads: %u", threadRunningCount());
  6494. info.newline();
  6495. stdCmdThrottler.getInfo(info);
  6496. info.newline();
  6497. slowCmdThrottler.getInfo(info);
  6498. clientStatsTable.getInfo(info, level);
  6499. }
  6500. unsigned threadRunningCount()
  6501. {
  6502. if (!threads)
  6503. return 0;
  6504. return threads->runningCount();
  6505. }
  6506. unsigned idleTime()
  6507. {
  6508. unsigned t = (unsigned)atomic_read(&globallasttick);
  6509. return msTick()-t;
  6510. }
  6511. void setThrottle(ThrottleClass throttleClass, unsigned limit, unsigned delayMs, unsigned cpuThreshold, unsigned queueLimit)
  6512. {
  6513. switch (throttleClass)
  6514. {
  6515. case ThrottleStd:
  6516. stdCmdThrottler.configure(limit, delayMs, cpuThreshold, queueLimit);
  6517. break;
  6518. case ThrottleSlow:
  6519. slowCmdThrottler.configure(limit, delayMs, cpuThreshold, queueLimit);
  6520. break;
  6521. default:
  6522. {
  6523. StringBuffer availableClasses("{ ");
  6524. for (unsigned c=0; c<ThrottleClassMax; c++)
  6525. {
  6526. availableClasses.append(c).append(" = ").append(getThrottleClassText((ThrottleClass)c));
  6527. if (c+1<ThrottleClassMax)
  6528. availableClasses.append(", ");
  6529. }
  6530. availableClasses.append(" }");
  6531. throw MakeStringException(0, "Unknown throttle class: %u, available classes are: %s", (unsigned)throttleClass, availableClasses.str());
  6532. }
  6533. }
  6534. }
  6535. StringBuffer &getStats(StringBuffer &stats, bool reset)
  6536. {
  6537. CriticalBlock block(sect);
  6538. stdCmdThrottler.getStats(stats, reset).newline();
  6539. slowCmdThrottler.getStats(stats, reset);
  6540. if (reset)
  6541. clientStatsTable.reset();
  6542. return stats;
  6543. }
  6544. };
  6545. IRemoteFileServer * createRemoteFileServer(unsigned maxThreads, unsigned maxThreadsDelayMs, unsigned maxAsyncCopy)
  6546. {
  6547. #if SIMULATE_PACKETLOSS
  6548. errorSimulationOn = false;
  6549. #endif
  6550. return new CRemoteFileServer(maxThreads, maxThreadsDelayMs, maxAsyncCopy);
  6551. }
  6552. #ifdef _USE_CPPUNIT
  6553. #include "unittests.hpp"
  6554. #include "rmtfile.hpp"
  6555. 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
  6556. static StringBuffer basePath;
  6557. static Owned<CSimpleInterface> serverThread;
  6558. class RemoteFileSlowTest : public CppUnit::TestFixture
  6559. {
  6560. CPPUNIT_TEST_SUITE(RemoteFileSlowTest);
  6561. CPPUNIT_TEST(testRemoteFilename);
  6562. CPPUNIT_TEST(testStartServer);
  6563. CPPUNIT_TEST(testBasicFunctionality);
  6564. CPPUNIT_TEST(testCopy);
  6565. CPPUNIT_TEST(testOther);
  6566. CPPUNIT_TEST(testConfiguration);
  6567. CPPUNIT_TEST(testDirectoryMonitoring);
  6568. CPPUNIT_TEST(testFinish);
  6569. CPPUNIT_TEST_SUITE_END();
  6570. size32_t testLen = 1024;
  6571. protected:
  6572. void testRemoteFilename()
  6573. {
  6574. const char *rfns = "//1.2.3.4/dir1/file1|//1.2.3.4:7100/dir1/file1,"
  6575. "//1.2.3.4:7100/dir1/file1|//1.2.3.4:7100/dir1/file1,"
  6576. "//1.2.3.4/c$/dir1/file1|//1.2.3.4:7100/c$/dir1/file1,"
  6577. "//1.2.3.4:7100/c$/dir1/file1|//1.2.3.4:7100/c$/dir1/file1,"
  6578. "//1.2.3.4:7100/d$/dir1/file1|//1.2.3.4:7100/d$/dir1/file1";
  6579. StringArray tests;
  6580. tests.appendList(rfns, ",");
  6581. ForEachItemIn(i, tests)
  6582. {
  6583. StringArray inOut;
  6584. const char *pair = tests.item(i);
  6585. inOut.appendList(pair, "|");
  6586. const char *rfn = inOut.item(0);
  6587. const char *expected = inOut.item(1);
  6588. Owned<IFile> iFile = createIFile(rfn);
  6589. const char *res = iFile->queryFilename();
  6590. if (!streq(expected, res))
  6591. {
  6592. StringBuffer errMsg("testRemoteFilename MISMATCH");
  6593. errMsg.newline().append("Expected: ").append(expected);
  6594. errMsg.newline().append("Got: ").append(res);
  6595. PROGLOG("%s", errMsg.str());
  6596. CPPUNIT_ASSERT_MESSAGE(errMsg.str(), 0);
  6597. }
  6598. else
  6599. PROGLOG("MATCH: %s", res);
  6600. }
  6601. }
  6602. void testStartServer()
  6603. {
  6604. Owned<ISocket> socket;
  6605. unsigned endPort = MP_END_PORT;
  6606. while (1)
  6607. {
  6608. try
  6609. {
  6610. socket.setown(ISocket::create(serverPort));
  6611. break;
  6612. }
  6613. catch (IJSOCK_Exception *e)
  6614. {
  6615. if (e->errorCode() != JSOCKERR_port_in_use)
  6616. {
  6617. StringBuffer eStr;
  6618. e->errorMessage(eStr);
  6619. e->Release();
  6620. CPPUNIT_ASSERT_MESSAGE(eStr.str(), 0);
  6621. }
  6622. else if (serverPort == endPort)
  6623. {
  6624. e->Release();
  6625. CPPUNIT_ASSERT_MESSAGE("Could not find a free port to use for remote file server", 0);
  6626. }
  6627. }
  6628. ++serverPort;
  6629. }
  6630. basePath.append("//");
  6631. SocketEndpoint ep(serverPort);
  6632. ep.getUrlStr(basePath);
  6633. char cpath[_MAX_DIR];
  6634. if (!GetCurrentDirectory(_MAX_DIR, cpath))
  6635. CPPUNIT_ASSERT_MESSAGE("Current directory path too big", 0);
  6636. else
  6637. basePath.append(cpath);
  6638. addPathSepChar(basePath);
  6639. PROGLOG("basePath = %s", basePath.str());
  6640. class CServerThread : public CSimpleInterface, implements IThreaded
  6641. {
  6642. CThreaded threaded;
  6643. Owned<CRemoteFileServer> server;
  6644. Linked<ISocket> socket;
  6645. public:
  6646. CServerThread(CRemoteFileServer *_server, ISocket *_socket) : server(_server), socket(_socket), threaded("CServerThread")
  6647. {
  6648. threaded.init(this);
  6649. }
  6650. ~CServerThread()
  6651. {
  6652. threaded.join();
  6653. }
  6654. // IThreaded
  6655. virtual void threadmain() override
  6656. {
  6657. DAFSConnectCfg sslCfg = SSLNone;
  6658. server->run(sslCfg, socket, nullptr);
  6659. }
  6660. };
  6661. enableDafsAuthentication(false);
  6662. Owned<IRemoteFileServer> server = createRemoteFileServer();
  6663. serverThread.setown(new CServerThread(QUERYINTERFACE(server.getClear(), CRemoteFileServer), socket.getClear()));
  6664. }
  6665. void testBasicFunctionality()
  6666. {
  6667. VStringBuffer filePath("%s%s", basePath.str(), "file1");
  6668. // create file
  6669. Owned<IFile> iFile = createIFile(filePath);
  6670. CPPUNIT_ASSERT(iFile);
  6671. Owned<IFileIO> iFileIO = iFile->open(IFOcreate);
  6672. CPPUNIT_ASSERT(iFileIO);
  6673. // write out 1k of random data and crc
  6674. MemoryBuffer mb;
  6675. char *buf = (char *)mb.reserveTruncate(testLen);
  6676. for (unsigned b=0; b<1024; b++)
  6677. buf[b] = getRandom()%256;
  6678. CRC32 crc;
  6679. crc.tally(testLen, buf);
  6680. unsigned writeCrc = crc.get();
  6681. size32_t sz = iFileIO->write(0, testLen, buf);
  6682. CPPUNIT_ASSERT(sz == testLen);
  6683. // close file
  6684. iFileIO.clear();
  6685. // validate remote crc
  6686. CPPUNIT_ASSERT(writeCrc == iFile->getCRC());
  6687. // exists
  6688. CPPUNIT_ASSERT(iFile->exists());
  6689. // validate size
  6690. CPPUNIT_ASSERT(iFile->size() == testLen);
  6691. // read back and validate read data's crc against written
  6692. iFileIO.setown(iFile->open(IFOread));
  6693. CPPUNIT_ASSERT(iFileIO);
  6694. sz = iFileIO->read(0, testLen, buf);
  6695. iFileIO.clear();
  6696. CPPUNIT_ASSERT(sz == testLen);
  6697. crc.reset();
  6698. crc.tally(testLen, buf);
  6699. CPPUNIT_ASSERT(writeCrc == crc.get());
  6700. }
  6701. void testCopy()
  6702. {
  6703. VStringBuffer filePath("%s%s", basePath.str(), "file1");
  6704. Owned<IFile> iFile = createIFile(filePath);
  6705. // test file copy
  6706. VStringBuffer filePathCopy("%s%s", basePath.str(), "file1copy");
  6707. Owned<IFile> iFile1Copy = createIFile(filePathCopy);
  6708. iFile->copyTo(iFile1Copy);
  6709. // read back copy and validate read data's crc against written
  6710. Owned<IFileIO> iFileIO = iFile1Copy->open(IFOreadwrite); // open read/write for appendFile in next step.
  6711. CPPUNIT_ASSERT(iFileIO);
  6712. MemoryBuffer mb;
  6713. char *buf = (char *)mb.reserveTruncate(testLen);
  6714. size32_t sz = iFileIO->read(0, testLen, buf);
  6715. CPPUNIT_ASSERT(sz == testLen);
  6716. CRC32 crc;
  6717. crc.tally(testLen, buf);
  6718. CPPUNIT_ASSERT(iFile->getCRC() == crc.get());
  6719. // check appendFile functionality. NB after this "file1copy" should be 2*testLen
  6720. CPPUNIT_ASSERT(testLen == iFileIO->appendFile(iFile));
  6721. iFileIO.clear();
  6722. // validate new size
  6723. CPPUNIT_ASSERT(iFile1Copy->size() == 2 * testLen);
  6724. // setSize test, truncate copy to original size
  6725. iFileIO.setown(iFile1Copy->open(IFOreadwrite));
  6726. iFileIO->setSize(testLen);
  6727. // validate new size
  6728. CPPUNIT_ASSERT(iFile1Copy->size() == testLen);
  6729. }
  6730. void testOther()
  6731. {
  6732. VStringBuffer filePath("%s%s", basePath.str(), "file1");
  6733. Owned<IFile> iFile = createIFile(filePath);
  6734. // rename
  6735. iFile->rename("file2");
  6736. // create a directory
  6737. VStringBuffer subDirPath("%s%s", basePath.str(), "subdir1");
  6738. Owned<IFile> subDirIFile = createIFile(subDirPath);
  6739. subDirIFile->createDirectory();
  6740. // check isDirectory result
  6741. CPPUNIT_ASSERT(subDirIFile->isDirectory());
  6742. // move previous created and renamed file into new sub-directory
  6743. // ensure not present before move
  6744. VStringBuffer subDirFilePath("%s/%s", subDirPath.str(), "file2");
  6745. Owned<IFile> iFile2 = createIFile(subDirFilePath);
  6746. iFile2->remove();
  6747. iFile->move(subDirFilePath);
  6748. // open sub-directory file2 explicitly
  6749. RemoteFilename rfn;
  6750. rfn.setRemotePath(subDirPath.str());
  6751. Owned<IFile> dir = createIFile(rfn);
  6752. Owned<IDirectoryIterator> diriter = dir->directoryFiles("file2");
  6753. if (!diriter->first())
  6754. {
  6755. CPPUNIT_ASSERT_MESSAGE("Error, file2 diriter->first() is null", 0);
  6756. }
  6757. Linked<IFile> iFile3 = &diriter->query();
  6758. diriter.clear();
  6759. dir.clear();
  6760. OwnedIFileIO iFile3IO = iFile3->openShared(IFOread, IFSHfull);
  6761. if (!iFile3IO)
  6762. {
  6763. CPPUNIT_ASSERT_MESSAGE("Error, file2 openShared() failed", 0);
  6764. }
  6765. iFile3IO->close();
  6766. // count sub-directory files with a wildcard
  6767. unsigned count=0;
  6768. Owned<IDirectoryIterator> iter = subDirIFile->directoryFiles("*2");
  6769. ForEach(*iter)
  6770. ++count;
  6771. CPPUNIT_ASSERT(1 == count);
  6772. // check isFile result
  6773. CPPUNIT_ASSERT(iFile2->isFile());
  6774. // validate isReadOnly before after setting
  6775. CPPUNIT_ASSERT(!iFile2->isReadOnly());
  6776. iFile2->setReadOnly(true);
  6777. CPPUNIT_ASSERT(iFile2->isReadOnly());
  6778. // get/set Time and validate result
  6779. CDateTime createTime, modifiedTime, accessedTime;
  6780. CPPUNIT_ASSERT(subDirIFile->getTime(&createTime, &modifiedTime, &accessedTime));
  6781. CDateTime newModifiedTime = modifiedTime;
  6782. newModifiedTime.adjustTime(-86400); // -1 day
  6783. CPPUNIT_ASSERT(subDirIFile->setTime(&createTime, &newModifiedTime, &accessedTime));
  6784. CPPUNIT_ASSERT(subDirIFile->getTime(&createTime, &modifiedTime, &accessedTime));
  6785. CPPUNIT_ASSERT(modifiedTime == newModifiedTime);
  6786. // test set file permissions
  6787. try
  6788. {
  6789. iFile2->setFilePermissions(0777);
  6790. }
  6791. catch (...)
  6792. {
  6793. CPPUNIT_ASSERT_MESSAGE("iFile2->setFilePermissions() exception", 0);
  6794. }
  6795. }
  6796. void testConfiguration()
  6797. {
  6798. SocketEndpoint ep(serverPort); // test trace open connections
  6799. CPPUNIT_ASSERT(setDafileSvrTraceFlags(ep, 0x08));
  6800. StringBuffer infoStr;
  6801. CPPUNIT_ASSERT(RFEnoerror == getDafileSvrInfo(ep, 10, infoStr));
  6802. CPPUNIT_ASSERT(RFEnoerror == setDafileSvrThrottleLimit(ep, ThrottleStd, DEFAULT_STDCMD_PARALLELREQUESTLIMIT+1, DEFAULT_STDCMD_THROTTLEDELAYMS+1, DEFAULT_STDCMD_THROTTLECPULIMIT+1, DEFAULT_STDCMD_THROTTLEQUEUELIMIT+1));
  6803. }
  6804. void testDirectoryMonitoring()
  6805. {
  6806. VStringBuffer subDirPath("%s%s", basePath.str(), "subdir1");
  6807. Owned<IFile> subDirIFile = createIFile(subDirPath);
  6808. subDirIFile->createDirectory();
  6809. VStringBuffer filePath("%s/%s", subDirPath.str(), "file1");
  6810. class CDelayedFileCreate : implements IThreaded
  6811. {
  6812. CThreaded threaded;
  6813. StringAttr filePath;
  6814. Semaphore doneSem;
  6815. public:
  6816. CDelayedFileCreate(const char *_filePath) : filePath(_filePath), threaded("CDelayedFileCreate")
  6817. {
  6818. threaded.init(this);
  6819. }
  6820. ~CDelayedFileCreate()
  6821. {
  6822. stop();
  6823. }
  6824. void stop()
  6825. {
  6826. doneSem.signal();
  6827. threaded.join();
  6828. }
  6829. // IThreaded impl.
  6830. virtual void threadmain() override
  6831. {
  6832. MilliSleep(1000); // give monitorDirectory a chance to be monitoring
  6833. // create file
  6834. Owned<IFile> iFile = createIFile(filePath);
  6835. CPPUNIT_ASSERT(iFile);
  6836. Owned<IFileIO> iFileIO = iFile->open(IFOcreate);
  6837. CPPUNIT_ASSERT(iFileIO);
  6838. iFileIO.clear();
  6839. doneSem.wait(60 * 1000);
  6840. CPPUNIT_ASSERT(iFile->remove());
  6841. }
  6842. } delayedFileCreate(filePath);
  6843. Owned<IDirectoryDifferenceIterator> iter = subDirIFile->monitorDirectory(nullptr, nullptr, false, false, 2000, 60 * 1000);
  6844. ForEach(*iter)
  6845. {
  6846. StringBuffer fname;
  6847. iter->getName(fname);
  6848. PROGLOG("fname = %s", fname.str());
  6849. }
  6850. delayedFileCreate.stop();
  6851. }
  6852. void testFinish()
  6853. {
  6854. // clearup
  6855. VStringBuffer filePathCopy("%s%s", basePath.str(), "file1copy");
  6856. Owned<IFile> iFile1Copy = createIFile(filePathCopy);
  6857. CPPUNIT_ASSERT(iFile1Copy->remove());
  6858. VStringBuffer subDirPath("%s%s", basePath.str(), "subdir1");
  6859. VStringBuffer subDirFilePath("%s/%s", subDirPath.str(), "file2");
  6860. Owned<IFile> iFile2 = createIFile(subDirFilePath);
  6861. CPPUNIT_ASSERT(iFile2->remove());
  6862. Owned<IFile> subDirIFile = createIFile(subDirPath);
  6863. CPPUNIT_ASSERT(subDirIFile->remove());
  6864. SocketEndpoint ep(serverPort);
  6865. Owned<ISocket> sock = ISocket::connect_timeout(ep, 60 * 1000);
  6866. CPPUNIT_ASSERT(RFEnoerror == stopRemoteServer(sock));
  6867. serverThread.clear();
  6868. }
  6869. };
  6870. CPPUNIT_TEST_SUITE_REGISTRATION( RemoteFileSlowTest );
  6871. CPPUNIT_TEST_SUITE_NAMED_REGISTRATION( RemoteFileSlowTest, "RemoteFileSlowTests" );
  6872. #endif // _USE_CPPUNIT