sockfile.cpp 188 KB

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