sockfile.cpp 141 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587
  1. /*##############################################################################
  2. Copyright (C) 2011 HPCC Systems.
  3. All rights reserved. This program is free software: you can redistribute it and/or modify
  4. it under the terms of the GNU Affero General Public License as
  5. published by the Free Software Foundation, either version 3 of the
  6. License, or (at your option) any later version.
  7. This program is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU Affero General Public License for more details.
  11. You should have received a copy of the GNU Affero General Public License
  12. along with this program. If not, see <http://www.gnu.org/licenses/>.
  13. ############################################################################## */
  14. // todo look at IRemoteFileServer stop
  15. #include "platform.h"
  16. #include "limits.h"
  17. #include "jlib.hpp"
  18. #include "jio.hpp"
  19. #include "jmutex.hpp"
  20. #include "jfile.hpp"
  21. #include "jmisc.hpp"
  22. #include "jthread.hpp"
  23. #include "sockfile.hpp"
  24. #include "portlist.h"
  25. #include "jsocket.hpp"
  26. #include "jencrypt.hpp"
  27. #include "jset.hpp"
  28. #include "remoteerr.hpp"
  29. #define SOCKET_CACHE_MAX 500
  30. #define MAX_THREADS 100
  31. #define TARGET_MIN_THREADS 20
  32. #define TARGET_ACTIVE_THREADS 80
  33. #ifdef _DEBUG
  34. //#define SIMULATE_PACKETLOSS 1
  35. #endif
  36. #define TREECOPYTIMEOUT (60*60*1000) // 1Hr (I guess could take longer for big file but at least will stagger)
  37. #define TREECOPYPOLLTIME (60*1000*5) // for tracing that delayed
  38. #define TREECOPYPRUNETIME (24*60*60*1000) // 1 day
  39. #if SIMULATE_PACKETLOSS
  40. #define TESTING_FAILURE_RATE_LOST_SEND 10 // per 1000
  41. #define TESTING_FAILURE_RATE_LOST_RECV 10 // per 1000
  42. #define DUMMY_TIMEOUT_MAX (1000*10)
  43. static bool errorSimulationOn = true;
  44. static ISocket *timeoutreadsock = NULL; // used to trigger
  45. struct dummyReadWrite
  46. {
  47. class X
  48. {
  49. dummyReadWrite *parent;
  50. public:
  51. X(dummyReadWrite *_parent)
  52. {
  53. parent = _parent;
  54. }
  55. ~X()
  56. {
  57. delete parent;
  58. }
  59. };
  60. class TimeoutSocketException: public CInterface, public IJSOCK_Exception
  61. {
  62. public:
  63. IMPLEMENT_IINTERFACE;
  64. TimeoutSocketException()
  65. {
  66. }
  67. virtual ~TimeoutSocketException()
  68. {
  69. }
  70. int errorCode() const { return JSOCKERR_timeout_expired; }
  71. StringBuffer & errorMessage(StringBuffer &str) const
  72. {
  73. return str.append("timeout expired");
  74. }
  75. MessageAudience errorAudience() const
  76. {
  77. return MSGAUD_user;
  78. }
  79. };
  80. ISocket *sock;
  81. dummyReadWrite(ISocket *_sock)
  82. {
  83. sock = _sock;
  84. }
  85. void readtms(void* buf, size32_t min_size, size32_t max_size, size32_t &size_read, time_t timeout)
  86. {
  87. X x(this);
  88. unsigned t = msTick();
  89. unsigned r = getRandom();
  90. bool timeoutread = (timeoutreadsock==sock);
  91. timeoutreadsock=NULL;
  92. if (!timeoutread)
  93. sock->readtms(buf, min_size, max_size, size_read, timeout);
  94. if (timeoutread||(errorSimulationOn&&(TESTING_FAILURE_RATE_LOST_RECV>0)&&(r%1000<TESTING_FAILURE_RATE_LOST_RECV))) {
  95. PrintStackReport();
  96. if (timeoutread)
  97. PROGLOG("** Simulate timeout");
  98. else
  99. PROGLOG("** Simulate Packet loss (size %d,%d)",min_size,max_size);
  100. if (timeout>DUMMY_TIMEOUT_MAX)
  101. timeout = DUMMY_TIMEOUT_MAX;
  102. t = msTick()-t;
  103. if (t<timeout)
  104. Sleep(timeout-t);
  105. IJSOCK_Exception *e = new TimeoutSocketException;
  106. throw e;
  107. }
  108. }
  109. size32_t write(void const* buf, size32_t size)
  110. {
  111. X x(this);
  112. timeoutreadsock=NULL;
  113. unsigned r = getRandom();
  114. if (errorSimulationOn&&(TESTING_FAILURE_RATE_LOST_SEND>0)&&(r%1000<TESTING_FAILURE_RATE_LOST_SEND)) {
  115. PrintStackReport();
  116. PROGLOG("** Simulate Packet loss (size %d)",size);
  117. timeoutreadsock=sock;
  118. return size;
  119. }
  120. return sock->write(buf,size);
  121. }
  122. };
  123. #define SOCKWRITE(sock) (new dummyReadWrite(sock))->write
  124. #define SOCKREADTMS(sock) (new dummyReadWrite(sock))->readtms
  125. #else
  126. #define SOCKWRITE(sock) sock->write
  127. #define SOCKREADTMS(sock) sock->readtms
  128. #endif
  129. // backward compatible modes
  130. typedef enum { compatIFSHnone, compatIFSHread, compatIFSHwrite, compatIFSHexec, compatIFSHall} compatIFSHmode;
  131. static const char *VERSTRING= "DS V1.7e - 7 " // dont forget FILESRV_VERSION in header
  132. #ifdef _WIN32
  133. "Windows ";
  134. #else
  135. "Linux ";
  136. #endif
  137. typedef unsigned char RemoteFileCommandType;
  138. typedef int RemoteFileIOHandle;
  139. static unsigned maxConnectTime = 0;
  140. static unsigned maxReceiveTime = 0;
  141. void clientSetRemoteFileTimeouts(unsigned maxconnecttime,unsigned maxreadtime)
  142. {
  143. maxConnectTime = maxconnecttime;
  144. maxReceiveTime = maxreadtime;
  145. }
  146. struct sRFTM
  147. {
  148. CTimeMon *timemon;
  149. sRFTM() { timemon = maxReceiveTime?new CTimeMon(maxReceiveTime):NULL; }
  150. ~sRFTM() { delete timemon; }
  151. };
  152. const char *remoteServerVersionString() { return VERSTRING; }
  153. static bool AuthenticationEnabled = true;
  154. bool enableDafsAuthentication(bool on)
  155. {
  156. bool ret = AuthenticationEnabled;
  157. AuthenticationEnabled = on;
  158. return ret;
  159. }
  160. #define CLIENT_TIMEOUT (1000*60*60*12) // long timeout in case zombies
  161. #define SERVER_TIMEOUT (1000*60*5) // timeout when waiting for dafilesrv to reply after command
  162. // (increased when waiting for large block)
  163. #define DAFS_CONNECT_FAIL_RETRY_TIME (1000*60*15)
  164. #ifdef SIMULATE_PACKETLOSS
  165. #define NORMAL_RETRIES (1)
  166. #define LENGTHY_RETRIES (1)
  167. #else
  168. #define NORMAL_RETRIES (3)
  169. #define LENGTHY_RETRIES (12)
  170. #endif
  171. #ifdef _DEBUG
  172. static byte traceFlags=0x30;
  173. #else
  174. static byte traceFlags=0x20;
  175. #endif
  176. #define TF_TRACE (traceFlags&1)
  177. #define TF_TRACE_PRE_IO (traceFlags&2)
  178. #define TF_TRACE_FULL (traceFlags&4)
  179. #define TF_TRACE_CLIENT_CONN (traceFlags&8)
  180. #define TF_TRACE_TREE_COPY (traceFlags&0x10)
  181. #define TF_TRACE_CLIENT_STATS (traceFlags&0x20)
  182. enum {
  183. RFCopenIO, // 0
  184. RFCcloseIO,
  185. RFCread,
  186. RFCwrite,
  187. RFCsize,
  188. RFCexists,
  189. RFCremove,
  190. RFCrename,
  191. RFCgetver,
  192. RFCisfile,
  193. RFCisdirectory, // 10
  194. RFCisreadonly,
  195. RFCsetreadonly,
  196. RFCgettime,
  197. RFCsettime,
  198. RFCcreatedir,
  199. RFCgetdir,
  200. RFCstop,
  201. RFCexec,
  202. RFCkill,
  203. RFCredeploy, // 20
  204. RFCgetcrc,
  205. RFCmove,
  206. // 1.5 features below
  207. RFCsetsize,
  208. RFCextractblobelements,
  209. RFCcopy,
  210. RFCappend,
  211. RFCmonitordir,
  212. RFCsettrace,
  213. RFCgetinfo,
  214. RFCfirewall, // not used currently // 30
  215. RFCunlock,
  216. RFCunlockreply,
  217. RFCinvalid,
  218. RFCcopysection,
  219. // 1.7e
  220. RFCtreecopy,
  221. // 1.7e - 1
  222. RFCtreecopytmp,
  223. RFCmax,
  224. };
  225. typedef enum { ACScontinue, ACSdone, ACSerror} AsyncCommandStatus;
  226. typedef byte OnceKey[16];
  227. static void genOnce(OnceKey &key)
  228. {
  229. static __int64 inc=0;
  230. *(unsigned *)&key[0] = getRandom();
  231. *(__int64 *)&key[4] = ++inc;
  232. *(unsigned *)&key[12] = getRandom();
  233. }
  234. static void mergeOnce(OnceKey &key,size32_t sz,const void *data)
  235. {
  236. assertex(sz<=sizeof(OnceKey));
  237. const byte *p = (const byte *)data;
  238. while (sz)
  239. key[--sz] ^= *(p++);
  240. }
  241. //---------------------------------------------------------------------------
  242. class CThrottler
  243. {
  244. Semaphore &sem;
  245. bool got;
  246. public:
  247. CThrottler(Semaphore &_sem) : sem(_sem), got(false)
  248. {
  249. take();
  250. }
  251. ~CThrottler()
  252. {
  253. release();
  254. }
  255. bool take()
  256. {
  257. assertex(!got);
  258. got = false;
  259. loop {
  260. if (sem.wait(5000)) {
  261. got = true;
  262. break;
  263. }
  264. unsigned cpu = getLatestCPUUsage();
  265. PROGLOG("Throttler stalled (%d%% cpu)",cpu);
  266. if (getLatestCPUUsage()<75)
  267. break;
  268. }
  269. return got;
  270. }
  271. bool release()
  272. {
  273. if (got)
  274. {
  275. got = false;
  276. sem.signal();
  277. return true;
  278. }
  279. return false;
  280. }
  281. };
  282. // temporarily release a throttler slot
  283. class CThrottleReleaseBlock
  284. {
  285. CThrottler &throttler;
  286. bool had;
  287. public:
  288. CThrottleReleaseBlock(CThrottler &_throttler) : throttler(_throttler)
  289. {
  290. had = throttler.release();
  291. }
  292. ~CThrottleReleaseBlock()
  293. {
  294. if (had)
  295. throttler.take();
  296. }
  297. };
  298. //---------------------------------------------------------------------------
  299. class CDafsException: public CInterface, public IDAFS_Exception
  300. {
  301. StringAttr msg;
  302. int errcode;
  303. public:
  304. IMPLEMENT_IINTERFACE;
  305. CDafsException(int code,const char *_msg)
  306. : errcode(code), msg(_msg)
  307. {
  308. };
  309. int errorCode() const
  310. {
  311. return errcode;
  312. }
  313. StringBuffer & errorMessage(StringBuffer &str) const
  314. {
  315. return str.append(msg);
  316. }
  317. MessageAudience errorAudience() const
  318. {
  319. return MSGAUD_user;
  320. }
  321. };
  322. static IDAFS_Exception *createDafsException(int code,const char *msg)
  323. {
  324. return new CDafsException(code,msg);
  325. }
  326. void setDafsEndpointPort(SocketEndpoint &ep)
  327. {
  328. // odd kludge (don't do this at home)
  329. byte ipb[4];
  330. if (ep.getNetAddress(sizeof(ipb),&ipb)==sizeof(ipb)) {
  331. if ((ipb[0]==255)&&(ipb[1]==255)) {
  332. ep.port = (((unsigned)ipb[2])<<8)+ipb[3];
  333. ep.ipset(queryLocalIP());
  334. }
  335. }
  336. if (ep.port==0)
  337. ep.port = DAFILESRV_PORT;
  338. }
  339. inline MemoryBuffer & initSendBuffer(MemoryBuffer & buff)
  340. {
  341. buff.setEndian(__BIG_ENDIAN); // transfer as big endian...
  342. buff.append((unsigned)0); // reserve space for length prefix
  343. return buff;
  344. }
  345. inline void sendBuffer(ISocket * socket, MemoryBuffer & src)
  346. {
  347. unsigned length = src.length() - sizeof(unsigned);
  348. byte * buffer = (byte *)src.toByteArray();
  349. if (TF_TRACE_FULL)
  350. PROGLOG("sendBuffer size %d, data = %d %d %d %d",length, (int)buffer[4],(int)buffer[5],(int)buffer[6],(int)buffer[7]);
  351. _WINCPYREV(buffer, &length, sizeof(unsigned));
  352. SOCKWRITE(socket)(buffer, src.length());
  353. }
  354. inline size32_t receiveBufferSize(ISocket * socket, unsigned numtries=NORMAL_RETRIES,CTimeMon *timemon=NULL)
  355. {
  356. unsigned timeout = SERVER_TIMEOUT;
  357. if (numtries==0) {
  358. numtries = 1;
  359. timeout = 10*1000; // 10s
  360. }
  361. while (numtries--) {
  362. try {
  363. if (timemon) {
  364. unsigned remaining;
  365. if (timemon->timedout(&remaining)||(remaining<10))
  366. remaining = 10;
  367. if (remaining<timeout)
  368. timeout = remaining;
  369. }
  370. size32_t szread;
  371. size32_t gotLength;
  372. SOCKREADTMS(socket)(&gotLength, sizeof(gotLength), sizeof(gotLength), szread, timeout);
  373. _WINREV(gotLength);
  374. if (TF_TRACE_FULL)
  375. PROGLOG("receiveBufferSized %d",gotLength);
  376. return gotLength;
  377. }
  378. catch (IJSOCK_Exception *e) {
  379. if ((numtries==0)||(e->errorCode()!=JSOCKERR_timeout_expired)||(timemon&&timemon->timedout())) {
  380. throw;
  381. }
  382. StringBuffer err;
  383. char peername[256];
  384. socket->peer_name(peername,sizeof(peername)-1);
  385. WARNLOG("Remote connection %s: %s",peername,e->errorMessage(err).str()); // why no peername
  386. e->Release();
  387. Sleep(500+getRandom()%1000); // ~1s
  388. }
  389. }
  390. return 0;
  391. }
  392. static void flush(ISocket *socket)
  393. {
  394. MemoryBuffer sendbuf;
  395. initSendBuffer(sendbuf);
  396. sendbuf.append((RemoteFileCommandType)RFCgetver);
  397. sendbuf.append((unsigned)RFCgetver);
  398. MemoryBuffer reply;
  399. size32_t totread=0;
  400. try {
  401. sendBuffer(socket, sendbuf);
  402. char buf[1024];
  403. loop {
  404. Sleep(1000); // breathe
  405. size32_t szread;
  406. SOCKREADTMS(socket)(buf, 1, sizeof(buf), szread, 1000*60);
  407. totread += szread;
  408. }
  409. }
  410. catch (IJSOCK_Exception *e) {
  411. if (totread)
  412. PROGLOG("%d bytes discarded",totread);
  413. if (e->errorCode()!=JSOCKERR_timeout_expired)
  414. EXCLOG(e,"flush");
  415. e->Release();
  416. }
  417. }
  418. inline void receiveBuffer(ISocket * socket, MemoryBuffer & tgt, unsigned numtries=1, size32_t maxsz=0x7fffffff)
  419. // maxsz is a guess at a resonable upper max to catch where protocol error
  420. {
  421. sRFTM tm;
  422. size32_t gotLength = receiveBufferSize(socket, numtries,tm.timemon);
  423. if (gotLength) {
  424. size32_t origlen = tgt.length();
  425. try {
  426. if (gotLength>maxsz) {
  427. StringBuffer msg;
  428. msg.appendf("receiveBuffer maximum block size exceeded %d/%d",gotLength,maxsz);
  429. PrintStackReport();
  430. throw createDafsException(DAFSERR_protocol_failure,msg.str());
  431. }
  432. unsigned timeout = SERVER_TIMEOUT*(numtries?numtries:1);
  433. if (tm.timemon) {
  434. unsigned remaining;
  435. if (tm.timemon->timedout(&remaining)||(remaining<10))
  436. remaining = 10;
  437. if (remaining<timeout)
  438. timeout = remaining;
  439. }
  440. size32_t szread;
  441. SOCKREADTMS(socket)((gotLength<4000)?tgt.reserve(gotLength):tgt.reserveTruncate(gotLength), gotLength, gotLength, szread, timeout);
  442. }
  443. catch (IJSOCK_Exception *e) {
  444. if (e->errorCode()!=JSOCKERR_timeout_expired) {
  445. EXCLOG(e,"receiveBuffer(1)");
  446. PrintStackReport();
  447. if (!tm.timemon||!tm.timemon->timedout())
  448. flush(socket);
  449. }
  450. else {
  451. EXCLOG(e,"receiveBuffer");
  452. PrintStackReport();
  453. }
  454. tgt.setLength(origlen);
  455. throw;
  456. }
  457. catch (IException *e) {
  458. EXCLOG(e,"receiveBuffer(2)");
  459. PrintStackReport();
  460. if (!tm.timemon||!tm.timemon->timedout())
  461. flush(socket);
  462. tgt.setLength(origlen);
  463. throw;
  464. }
  465. }
  466. tgt.setEndian(__BIG_ENDIAN);
  467. }
  468. struct CConnectionRec
  469. {
  470. SocketEndpoint ep;
  471. unsigned tick;
  472. IArrayOf<ISocket> socks; // relies on isShared
  473. };
  474. //---------------------------------------------------------------------------
  475. // Local mount redirect
  476. struct CLocalMountRec: public CInterface
  477. {
  478. IpAddress ip;
  479. StringAttr dir; // dir path on remote ip
  480. StringAttr local; // local dir path
  481. };
  482. static CIArrayOf<CLocalMountRec> localMounts;
  483. static CriticalSection localMountCrit;
  484. void setDafsLocalMountRedirect(const IpAddress &ip,const char *dir,const char *mountdir)
  485. {
  486. CriticalBlock block(localMountCrit);
  487. ForEachItemInRev(i,localMounts) {
  488. CLocalMountRec &mount = localMounts.item(i);
  489. if (dir==NULL) { // remove all matching mount
  490. if (!mountdir)
  491. return;
  492. if (strcmp(mount.local,mountdir)==0)
  493. localMounts.remove(i);
  494. }
  495. else if (mount.ip.ipequals(ip)&&(strcmp(mount.dir,dir)==0)) {
  496. if (mountdir) {
  497. mount.local.set(mountdir);
  498. return;
  499. }
  500. else
  501. localMounts.remove(i);
  502. }
  503. }
  504. if (dir&&mountdir) {
  505. CLocalMountRec &mount = *new CLocalMountRec;
  506. mount.ip.ipset(ip);
  507. mount.dir.set(dir);
  508. mount.local.set(mountdir);
  509. localMounts.append(mount);
  510. }
  511. }
  512. IFile *createFileLocalMount(const IpAddress &ip, const char * filename)
  513. {
  514. CriticalBlock block(localMountCrit);
  515. ForEachItemInRev(i,localMounts) {
  516. CLocalMountRec &mount = localMounts.item(i);
  517. if (mount.ip.ipequals(ip)) {
  518. size32_t bl = mount.dir.length();
  519. if (isPathSepChar(mount.dir[bl-1]))
  520. bl--;
  521. if ((memcmp((void *)filename,(void *)mount.dir.get(),bl)==0)&&(isPathSepChar(filename[bl])||!filename[bl])) { // match
  522. StringBuffer locpath(mount.local);
  523. if (filename[bl])
  524. addPathSepChar(locpath).append(filename+bl+1);
  525. locpath.replace((PATHSEPCHAR=='\\')?'/':'\\',PATHSEPCHAR);
  526. return createIFile(locpath.str());
  527. }
  528. }
  529. }
  530. return NULL;
  531. }
  532. //---------------------------------------------------------------------------
  533. static class CConnectionTable: public SuperHashTableOf<CConnectionRec,SocketEndpoint>
  534. {
  535. void onAdd(void *) {}
  536. void onRemove(void *e)
  537. {
  538. CConnectionRec *r=(CConnectionRec *)e;
  539. delete r;
  540. }
  541. unsigned getHashFromElement(const void *e) const
  542. {
  543. const CConnectionRec &elem=*(const CConnectionRec *)e;
  544. return elem.ep.hash(0);
  545. }
  546. unsigned getHashFromFindParam(const void *fp) const
  547. {
  548. return ((const SocketEndpoint *)fp)->hash(0);
  549. }
  550. const void * getFindParam(const void *p) const
  551. {
  552. const CConnectionRec &elem=*(const CConnectionRec *)p;
  553. return (void *)&elem.ep;
  554. }
  555. bool matchesFindParam(const void * et, const void *fp, unsigned) const
  556. {
  557. return ((CConnectionRec *)et)->ep.equals(*(SocketEndpoint *)fp);
  558. }
  559. IMPLEMENT_SUPERHASHTABLEOF_REF_FIND(CConnectionRec,SocketEndpoint);
  560. unsigned numsockets;
  561. public:
  562. static CriticalSection crit;
  563. CConnectionTable()
  564. {
  565. numsockets = 0;
  566. }
  567. ~CConnectionTable() {
  568. releaseAll();
  569. }
  570. ISocket *lookup(const SocketEndpoint &ep)
  571. {
  572. // always called from crit block
  573. CConnectionRec *r = SuperHashTableOf<CConnectionRec,SocketEndpoint>::find(&ep);
  574. if (r) {
  575. ForEachItemIn(i,r->socks) {
  576. ISocket *s = &r->socks.item(i);
  577. if (!QUERYINTERFACE(s, CInterface)->IsShared()) {
  578. r->tick = msTick();
  579. s->Link();
  580. return s;
  581. }
  582. }
  583. }
  584. return NULL;
  585. }
  586. void addLink(SocketEndpoint &ep,ISocket *sock)
  587. {
  588. // always called from crit block
  589. while (numsockets>=SOCKET_CACHE_MAX) {
  590. // find oldest
  591. CConnectionRec *c = NULL;
  592. unsigned oldest = 0;
  593. CConnectionRec *old = NULL;
  594. unsigned oldi;
  595. unsigned now = msTick();
  596. loop {
  597. c = (CConnectionRec *)SuperHashTableOf<CConnectionRec,SocketEndpoint>::next(c);
  598. if (!c)
  599. break;
  600. ForEachItemIn(i,c->socks) {
  601. ISocket *s = &c->socks.item(i);
  602. if (!QUERYINTERFACE(s, CInterface)->IsShared()) { // candidate to remove
  603. unsigned t = now-c->tick;
  604. if (t>oldest) {
  605. oldest = t;
  606. old = c;
  607. oldi = i;
  608. }
  609. }
  610. }
  611. }
  612. if (!old)
  613. return;
  614. old->socks.remove(oldi);
  615. numsockets--;
  616. }
  617. CConnectionRec *r = SuperHashTableOf<CConnectionRec,SocketEndpoint>::find(&ep);
  618. if (!r) {
  619. r = new CConnectionRec;
  620. r->ep = ep;
  621. SuperHashTableOf<CConnectionRec,SocketEndpoint>::add(*r);
  622. }
  623. sock->Link();
  624. r->socks.append(*sock);
  625. numsockets++;
  626. r->tick = msTick();
  627. }
  628. void remove(SocketEndpoint &ep,ISocket *sock)
  629. {
  630. // always called from crit block
  631. CConnectionRec *r = SuperHashTableOf<CConnectionRec,SocketEndpoint>::find(&ep);
  632. if (r)
  633. if (r->socks.zap(*sock)&&numsockets)
  634. numsockets--;
  635. }
  636. } *ConnectionTable = NULL;
  637. CriticalSection CConnectionTable::crit;
  638. void clientSetDaliServixSocketCaching(bool on)
  639. {
  640. CriticalBlock block(CConnectionTable::crit);
  641. if (on) {
  642. if (!ConnectionTable)
  643. ConnectionTable = new CConnectionTable;
  644. }
  645. else {
  646. delete ConnectionTable;
  647. ConnectionTable = NULL;
  648. }
  649. }
  650. //---------------------------------------------------------------------------
  651. // TreeCopy
  652. #define TREECOPY_CACHE_SIZE 50
  653. struct CTreeCopyItem: public CInterface
  654. {
  655. StringAttr net;
  656. StringAttr mask;
  657. offset_t sz; // original size
  658. CDateTime dt; // original date
  659. RemoteFilenameArray loc; // locations for file - 0 is original
  660. Owned<IBitSet> busy;
  661. unsigned lastused;
  662. CTreeCopyItem(RemoteFilename &orig, const char *_net, const char *_mask, offset_t _sz, CDateTime &_dt)
  663. : net(_net), mask(_mask)
  664. {
  665. loc.append(orig);
  666. dt.set(_dt);
  667. sz = _sz;
  668. busy.setown(createBitSet());
  669. lastused = msTick();
  670. }
  671. bool equals(const RemoteFilename &orig, const char *_net, const char *_mask, offset_t _sz, CDateTime &_dt)
  672. {
  673. if (!orig.equals(loc.item(0)))
  674. return false;
  675. if (strcmp(_net,net)!=0)
  676. return false;
  677. if (strcmp(_mask,mask)!=0)
  678. return false;
  679. if (sz!=_sz)
  680. return false;
  681. return (dt.equals(_dt,false));
  682. }
  683. };
  684. static CIArrayOf<CTreeCopyItem> treeCopyArray;
  685. static CriticalSection treeCopyCrit;
  686. static unsigned treeCopyWaiting=0;
  687. static Semaphore treeCopySem;
  688. #define DEBUGSAMEIP false
  689. static void treeCopyFile(RemoteFilename &srcfn, RemoteFilename &dstfn, const char *net, const char *mask, IpAddress &ip, bool usetmp, CThrottler *throttler)
  690. {
  691. unsigned start = msTick();
  692. Owned<IFile> dstfile = createIFile(dstfn);
  693. // the following is really to check the dest node is up and working (otherwise not much point in continuing!)
  694. if (dstfile->exists())
  695. PROGLOG("TREECOPY overwriting '%s'",dstfile->queryFilename());
  696. Owned<IFile> srcfile = createIFile(srcfn);
  697. unsigned lastmin = 0;
  698. if (!srcfn.queryIP().ipequals(dstfn.queryIP())) {
  699. CriticalBlock block(treeCopyCrit);
  700. loop {
  701. CDateTime dt;
  702. offset_t sz;
  703. try {
  704. sz = srcfile->size();
  705. if (sz==(offset_t)-1) {
  706. if (TF_TRACE_TREE_COPY)
  707. PROGLOG("TREECOPY source not found '%s'",srcfile->queryFilename());
  708. break;
  709. }
  710. srcfile->getTime(NULL,&dt,NULL);
  711. }
  712. catch (IException *e) {
  713. EXCLOG(e,"treeCopyFile(1)");
  714. e->Release();
  715. break;
  716. }
  717. Linked<CTreeCopyItem> tc;
  718. unsigned now = msTick();
  719. ForEachItemInRev(i1,treeCopyArray) {
  720. CTreeCopyItem &item = treeCopyArray.item(i1);
  721. // prune old entries (not strictly needed buf I think better)
  722. if (now-item.lastused>TREECOPYPRUNETIME)
  723. treeCopyArray.remove(i1);
  724. else if (!tc.get()&&item.equals(srcfn,net,mask,sz,dt)) {
  725. tc.set(&item);
  726. item.lastused = now;
  727. }
  728. }
  729. if (!tc.get()) {
  730. if (treeCopyArray.ordinality()>=TREECOPY_CACHE_SIZE)
  731. treeCopyArray.remove(0);
  732. tc.setown(new CTreeCopyItem(srcfn,net,mask,sz,dt));
  733. treeCopyArray.append(*tc.getLink());
  734. }
  735. ForEachItemInRev(cand,tc->loc) { // rev to choose copied locations first (maybe optional?)
  736. if (!tc->busy->testSet(cand)) {
  737. // check file accessible and matches
  738. if (!cand&&dstfn.equals(tc->loc.item(cand))) // hmm trying to overwrite existing, better humor
  739. continue;
  740. bool ok = true;
  741. Owned<IFile> rmtfile = createIFile(tc->loc.item(cand));
  742. if (cand) { // only need to check if remote
  743. try {
  744. if (rmtfile->size()!=sz)
  745. ok = false;
  746. else {
  747. CDateTime fdt;
  748. rmtfile->getTime(NULL,&fdt,NULL);
  749. ok = fdt.equals(dt);
  750. }
  751. }
  752. catch (IException *e) {
  753. EXCLOG(e,"treeCopyFile(2)");
  754. e->Release();
  755. ok = false;
  756. }
  757. }
  758. if (ok) { // if not ok leave 'busy'
  759. // finally lets try and copy!
  760. try {
  761. if (TF_TRACE_TREE_COPY)
  762. PROGLOG("TREECOPY(started) %s to %s",rmtfile->queryFilename(),dstfile->queryFilename());
  763. {
  764. CriticalUnblock unblock(treeCopyCrit); // note we have tc linked
  765. rmtfile->copyTo(dstfile,0x100000,NULL,usetmp);
  766. }
  767. if (TF_TRACE_TREE_COPY)
  768. PROGLOG("TREECOPY(done) %s to %s",rmtfile->queryFilename(),dstfile->queryFilename());
  769. tc->busy->set(cand,false);
  770. if (treeCopyWaiting)
  771. treeCopySem.signal((treeCopyWaiting>1)?2:1);
  772. // add to known locations
  773. tc->busy->set(tc->loc.ordinality(),false); // prob already is clear
  774. tc->loc.append(dstfn);
  775. ip.ipset(tc->loc.item(cand).queryIP());
  776. return;
  777. }
  778. catch (IException *e) {
  779. if (cand==0) {
  780. tc->busy->set(0,false); // don't leave busy
  781. if (treeCopyWaiting)
  782. treeCopySem.signal();
  783. throw; // what more can we do!
  784. }
  785. EXCLOG(e,"treeCopyFile(3)");
  786. e->Release();
  787. }
  788. }
  789. }
  790. }
  791. // all locations busy
  792. if (msTick()-start>TREECOPYTIMEOUT) {
  793. WARNLOG("Treecopy %s wait timed out", srcfile->queryFilename());
  794. break;
  795. }
  796. treeCopyWaiting++; // note this isn't precise - just indication
  797. {
  798. CriticalUnblock unblock(treeCopyCrit);
  799. if (throttler)
  800. {
  801. CThrottleReleaseBlock block(*throttler);
  802. treeCopySem.wait(TREECOPYPOLLTIME);
  803. }
  804. else
  805. treeCopySem.wait(TREECOPYPOLLTIME);
  806. }
  807. treeCopyWaiting--;
  808. if ((msTick()-start)/10*1000!=lastmin) {
  809. lastmin = (msTick()-start)/10*1000;
  810. PROGLOG("treeCopyFile delayed: %s to %s",srcfile->queryFilename(),dstfile->queryFilename());
  811. }
  812. }
  813. }
  814. else if (TF_TRACE_TREE_COPY)
  815. PROGLOG("TREECOPY source on same node as destination");
  816. if (TF_TRACE_TREE_COPY)
  817. PROGLOG("TREECOPY(started,fallback) %s to %s",srcfile->queryFilename(),dstfile->queryFilename());
  818. try {
  819. GetHostIp(ip);
  820. srcfile->copyTo(dstfile,0x100000,NULL,usetmp);
  821. }
  822. catch (IException *e) {
  823. EXCLOG(e,"TREECOPY(done,fallback)");
  824. throw;
  825. }
  826. if (TF_TRACE_TREE_COPY)
  827. PROGLOG("TREECOPY(done,fallback) %s to %s",srcfile->queryFilename(),dstfile->queryFilename());
  828. }
  829. //---------------------------------------------------------------------------
  830. class CRemoteBase: public CInterface
  831. {
  832. Owned<ISocket> socket;
  833. static SocketEndpoint lastfailep;
  834. static unsigned lastfailtime;
  835. void connectSocket(SocketEndpoint &ep)
  836. {
  837. sRFTM tm;
  838. // called in CConnectionTable::crit
  839. unsigned retries = 3;
  840. if (ep.equals(lastfailep)) {
  841. if (msTick()-lastfailtime<DAFS_CONNECT_FAIL_RETRY_TIME) {
  842. StringBuffer msg("Failed to connect to dafilesrv/daliservix on ");
  843. ep.getUrlStr(msg);
  844. throw createDafsException(DAFSERR_connection_failed,msg.str());
  845. }
  846. lastfailep.set(NULL);
  847. retries = 1; // on probation
  848. }
  849. while(retries--) {
  850. CriticalUnblock unblock(CConnectionTable::crit); // allow others to connect
  851. StringBuffer eps;
  852. if (TF_TRACE_CLIENT_CONN) {
  853. ep.getUrlStr(eps);
  854. PROGLOG("Connecting to %s",eps.str());
  855. //PrintStackReport();
  856. }
  857. bool ok = true;
  858. try {
  859. if (tm.timemon) {
  860. unsigned remaining;
  861. tm.timemon->timedout(&remaining);
  862. socket.setown(ISocket::connect_timeout(ep,remaining));
  863. }
  864. else
  865. socket.setown(ISocket::connect(ep));
  866. }
  867. catch (IJSOCK_Exception *e) {
  868. ok = false;
  869. if (!retries||(tm.timemon&&tm.timemon->timedout())) {
  870. if (e->errorCode()==JSOCKERR_connection_failed) {
  871. lastfailep.set(ep);
  872. lastfailtime = msTick();
  873. e->Release();
  874. StringBuffer msg("Failed to connect to dafilesrv/daliservix on ");
  875. ep.getUrlStr(msg);
  876. throw createDafsException(DAFSERR_connection_failed,msg.str());
  877. }
  878. throw;
  879. }
  880. StringBuffer err;
  881. WARNLOG("Remote file connect %s",e->errorMessage(err).str());
  882. e->Release();
  883. }
  884. if (ok) {
  885. if (TF_TRACE_CLIENT_CONN) {
  886. PROGLOG("Connected to %s",eps.str());
  887. }
  888. if (AuthenticationEnabled) {
  889. try {
  890. sendAuthentication(ep); // this will log error
  891. break;
  892. }
  893. catch (IJSOCK_Exception *e) {
  894. StringBuffer err;
  895. WARNLOG("Remote file authenticate %s for %s ",e->errorMessage(err).str(),ep.getUrlStr(eps.clear()).str());
  896. e->Release();
  897. if (!retries)
  898. break;
  899. }
  900. }
  901. else
  902. break;
  903. }
  904. unsigned sleeptime = getRandom()%3000+1000;
  905. if (tm.timemon) {
  906. unsigned remaining;
  907. tm.timemon->timedout(&remaining);
  908. if (remaining/2<sleeptime)
  909. sleeptime = remaining/2;
  910. }
  911. Sleep(sleeptime); // prevent multiple retries beating
  912. PROGLOG("Retrying connect");
  913. }
  914. if (ConnectionTable)
  915. ConnectionTable->addLink(ep,socket);
  916. }
  917. void killSocket(SocketEndpoint &tep)
  918. {
  919. CriticalBlock block2(CConnectionTable::crit); // this is nested with crit
  920. if (socket) {
  921. try {
  922. Owned<ISocket> s = socket.getClear();
  923. if (ConnectionTable)
  924. ConnectionTable->remove(tep,s);
  925. }
  926. catch (IJSOCK_Exception *e) {
  927. e->Release(); // ignore errors closing
  928. }
  929. Sleep(getRandom()%1000*5+500); // prevent multiple beating
  930. }
  931. }
  932. protected: friend class CRemoteFileIO;
  933. StringAttr filename;
  934. CriticalSection crit;
  935. SocketEndpoint ep;
  936. void sendRemoteCommand(MemoryBuffer & src, MemoryBuffer & reply, bool retry=true, bool lengthy=false)
  937. {
  938. CriticalBlock block(crit); // serialize commands on same file
  939. SocketEndpoint tep(ep);
  940. setDafsEndpointPort(tep);
  941. unsigned nretries = retry?3:0;
  942. Owned<IJSOCK_Exception> firstexc; // when retrying return first error if fails
  943. loop {
  944. try {
  945. if (socket) {
  946. sendBuffer(socket, src);
  947. receiveBuffer(socket, reply, lengthy?LENGTHY_RETRIES:NORMAL_RETRIES);
  948. break;
  949. }
  950. }
  951. catch (IJSOCK_Exception *e) {
  952. if (!nretries--) {
  953. if (firstexc) {
  954. e->Release();
  955. e = firstexc.getClear();
  956. }
  957. killSocket(tep);
  958. throw e;
  959. }
  960. StringBuffer str;
  961. e->errorMessage(str);
  962. WARNLOG("Remote File: %s, retrying (%d)",str.str(),nretries);
  963. if (firstexc)
  964. e->Release();
  965. else
  966. firstexc.setown(e);
  967. killSocket(tep);
  968. }
  969. CriticalBlock block2(CConnectionTable::crit); // this is nested with crit
  970. if (ConnectionTable) {
  971. socket.setown(ConnectionTable->lookup(tep));
  972. if (socket) {
  973. // validate existing socket by sending an 'exists' command with short time out
  974. // (use exists for backward compatibility)
  975. bool ok = false;
  976. try {
  977. MemoryBuffer sendbuf;
  978. initSendBuffer(sendbuf);
  979. MemoryBuffer replybuf;
  980. sendbuf.append((RemoteFileCommandType)RFCexists).append(filename);
  981. sendBuffer(socket, sendbuf);
  982. receiveBuffer(socket, replybuf, 0, 1024);
  983. ok = true;
  984. }
  985. catch (IException *e) {
  986. e->Release();
  987. }
  988. if (!ok)
  989. killSocket(tep);
  990. }
  991. }
  992. if (!socket) {
  993. connectSocket(tep);
  994. }
  995. }
  996. unsigned errCode;
  997. reply.read(errCode);
  998. if (errCode) {
  999. StringBuffer msg;
  1000. if (filename.get())
  1001. msg.append(filename);
  1002. ep.getUrlStr(msg.append('[')).append("] ");
  1003. size32_t pos = reply.getPos();
  1004. if (pos<reply.length()) {
  1005. size32_t len = reply.length()-pos;
  1006. const byte *rest = reply.readDirect(len);
  1007. if (errCode==RFSERR_InvalidCommand) {
  1008. const char *s = (const char *)rest;
  1009. const char *e = (const char *)rest+len;
  1010. while (*s&&(s!=e))
  1011. s++;
  1012. msg.append(s-(const char *)rest,(const char *)rest);
  1013. }
  1014. else if (len&&(rest[len-1]==0))
  1015. msg.append((const char *)rest);
  1016. else {
  1017. msg.appendf("extra data[%d]",len);
  1018. for (unsigned i=0;(i<16)&&(i<len);i++)
  1019. msg.appendf(" %2x",(int)rest[i]);
  1020. }
  1021. }
  1022. else if(errCode == 8209)
  1023. msg.append("Failed to open directory.");
  1024. else
  1025. msg.append("ERROR #").append(errCode);
  1026. #ifdef _DEBUG
  1027. ERRLOG("%s",msg.str());
  1028. PrintStackReport();
  1029. #endif
  1030. throw createDafsException(errCode,msg.str());
  1031. }
  1032. }
  1033. void sendRemoteCommand(MemoryBuffer & src, bool retry)
  1034. {
  1035. MemoryBuffer reply;
  1036. sendRemoteCommand(src, reply, retry);
  1037. }
  1038. void throwUnauthenticated(const IpAddress &ip,const char *user,unsigned err=0)
  1039. {
  1040. if (err==0)
  1041. err = RFSERR_AuthenticateFailed;
  1042. StringBuffer msg;
  1043. msg.appendf("Authentication for %s on ",user);
  1044. ip.getIpText(msg);
  1045. msg.append(" failed");
  1046. throw createDafsException(err, msg.str());
  1047. }
  1048. void sendAuthentication(const IpAddress &serverip)
  1049. {
  1050. // send my sig
  1051. // first send my sig which if stream unencrypted will get returned as a bad command
  1052. OnceKey oncekey;
  1053. genOnce(oncekey);
  1054. MemoryBuffer sendbuf;
  1055. initSendBuffer(sendbuf);
  1056. MemoryBuffer replybuf;
  1057. MemoryBuffer encbuf; // because aesEncrypt clears input
  1058. sendbuf.append((RemoteFileCommandType)RFCunlock).append(sizeof(oncekey),&oncekey);
  1059. try {
  1060. sendBuffer(socket, sendbuf);
  1061. receiveBuffer(socket, replybuf, NORMAL_RETRIES, 1024);
  1062. }
  1063. catch (IException *e)
  1064. {
  1065. EXCLOG(e,"Remote file - sendAuthentication(1)");
  1066. throw;
  1067. }
  1068. unsigned errCode;
  1069. replybuf.read(errCode);
  1070. if (errCode!=0) // no authentication required
  1071. return;
  1072. SocketEndpoint ep;
  1073. ep.setLocalHost(0);
  1074. byte ipdata[16];
  1075. size32_t ipds = ep.getNetAddress(sizeof(ipdata),&ipdata);
  1076. mergeOnce(oncekey,ipds,&ipdata);
  1077. StringBuffer username;
  1078. StringBuffer password;
  1079. IPasswordProvider * pp = queryPasswordProvider();
  1080. if (pp)
  1081. pp->getPassword(serverip, username, password);
  1082. if (!username.length())
  1083. username.append("sds_system"); // default account (note if exists should have restricted access!)
  1084. if (!password.length())
  1085. password.append("sds_man");
  1086. if (replybuf.remaining()<=sizeof(size32_t))
  1087. throwUnauthenticated(serverip,username.str());
  1088. size32_t bs;
  1089. replybuf.read(bs);
  1090. if (replybuf.remaining()<bs)
  1091. throwUnauthenticated(serverip,username.str());
  1092. MemoryBuffer skeybuf;
  1093. aesDecrypt(&oncekey,sizeof(oncekey),replybuf.readDirect(bs),bs,skeybuf);
  1094. if (skeybuf.remaining()<sizeof(OnceKey))
  1095. throwUnauthenticated(serverip,username.str());
  1096. OnceKey sokey;
  1097. skeybuf.read(sizeof(OnceKey),&sokey);
  1098. // now we have the key to use to send user/password
  1099. MemoryBuffer tosend;
  1100. tosend.append((byte)2).append(username).append(password);
  1101. initSendBuffer(sendbuf.clear());
  1102. sendbuf.append((RemoteFileCommandType)RFCunlockreply);
  1103. aesEncrypt(&sokey, sizeof(oncekey), tosend.toByteArray(), tosend.length(), encbuf);
  1104. sendbuf.append(encbuf.length());
  1105. sendbuf.append(encbuf);
  1106. try {
  1107. sendBuffer(socket, sendbuf);
  1108. receiveBuffer(socket, replybuf.clear(), NORMAL_RETRIES, 1024);
  1109. }
  1110. catch (IException *e)
  1111. {
  1112. EXCLOG(e,"Remote file - sendAuthentication(2)");
  1113. throw;
  1114. }
  1115. replybuf.read(errCode);
  1116. if (errCode==0) // suceeded!
  1117. return;
  1118. throwUnauthenticated(serverip,username.str(),errCode);
  1119. }
  1120. public:
  1121. SocketEndpoint &queryEp() { return ep; };
  1122. CRemoteBase(const SocketEndpoint &_ep, const char * _filename)
  1123. : filename(_filename)
  1124. {
  1125. ep = _ep;
  1126. }
  1127. void connect()
  1128. {
  1129. CriticalBlock block(crit);
  1130. CriticalBlock block2(CConnectionTable::crit); // this shouldn't ever block
  1131. if (AuthenticationEnabled) {
  1132. SocketEndpoint tep(ep);
  1133. setDafsEndpointPort(tep);
  1134. connectSocket(tep);
  1135. }
  1136. }
  1137. void disconnect()
  1138. {
  1139. CriticalBlock block(crit);
  1140. CriticalBlock block2(CConnectionTable::crit); // this shouldn't ever block
  1141. ISocket *s = socket.getClear();
  1142. if (ConnectionTable) {
  1143. SocketEndpoint tep(ep);
  1144. setDafsEndpointPort(tep);
  1145. ConnectionTable->remove(tep,s);
  1146. }
  1147. ::Release(s);
  1148. }
  1149. const char *queryLocalName()
  1150. {
  1151. return filename;
  1152. }
  1153. };
  1154. SocketEndpoint CRemoteBase::lastfailep;
  1155. unsigned CRemoteBase::lastfailtime;
  1156. //---------------------------------------------------------------------------
  1157. class CRemoteDirectoryIterator : public CInterface, implements IDirectoryDifferenceIterator
  1158. {
  1159. Owned<IFile> cur;
  1160. bool curvalid;
  1161. bool curisdir;
  1162. StringAttr curname;
  1163. CDateTime curdt;
  1164. __int64 cursize;
  1165. StringAttr dir;
  1166. SocketEndpoint ep;
  1167. byte *flags;
  1168. unsigned numflags;
  1169. unsigned curidx;
  1170. unsigned mask;
  1171. MemoryBuffer buf;
  1172. public:
  1173. static CriticalSection crit;
  1174. CRemoteDirectoryIterator(SocketEndpoint &_ep,const char *_dir)
  1175. : dir(_dir)
  1176. {
  1177. // an extended difference iterator starts with 2 (for bwd compatibility)
  1178. ep = _ep;
  1179. curisdir = false;
  1180. curvalid = false;
  1181. cursize = 0;
  1182. curidx = (unsigned)-1;
  1183. mask = 0;
  1184. numflags = 0;
  1185. flags = NULL;
  1186. }
  1187. bool appendBuf(MemoryBuffer &_buf)
  1188. {
  1189. buf.setSwapEndian(_buf.needSwapEndian());
  1190. byte hdr;
  1191. _buf.read(hdr);
  1192. if (hdr==2) {
  1193. _buf.read(numflags);
  1194. flags = (byte *)malloc(numflags);
  1195. _buf.read(numflags,flags);
  1196. }
  1197. else {
  1198. buf.append(hdr);
  1199. flags = NULL;
  1200. numflags = 0;
  1201. }
  1202. size32_t rest = _buf.length()-_buf.getPos();
  1203. const byte *rb = (const byte *)_buf.readDirect(rest);
  1204. bool ret = true;
  1205. if (rest&&(rb[rest-1]!=0)) {
  1206. rest--;
  1207. ret = false; // continuation
  1208. }
  1209. buf.append(rest,rb);
  1210. return ret;
  1211. }
  1212. ~CRemoteDirectoryIterator()
  1213. {
  1214. free(flags);
  1215. }
  1216. IMPLEMENT_IINTERFACE
  1217. bool first()
  1218. {
  1219. curidx = (unsigned)-1;
  1220. buf.reset();
  1221. return next();
  1222. }
  1223. bool next()
  1224. {
  1225. loop {
  1226. curidx++;
  1227. cur.clear();
  1228. curdt.clear();
  1229. curname.clear();
  1230. cursize = 0;
  1231. curisdir = false;
  1232. if (buf.getPos()>=buf.length())
  1233. return false;
  1234. byte b;
  1235. buf.read(b);
  1236. curvalid = b!=0;
  1237. if (!curvalid)
  1238. return false;
  1239. buf.read(curisdir);
  1240. buf.read(cursize);
  1241. curdt.deserialize(buf);
  1242. buf.read(curname);
  1243. // kludge for bug in old linux jlibs
  1244. if (strchr(curname,'\\')&&(getPathSepChar(dir)=='/')) {
  1245. StringBuffer temp(curname);
  1246. temp.replace('\\','/');
  1247. curname.set(temp.str());
  1248. }
  1249. if ((mask==0)||(getFlags()&mask))
  1250. break;
  1251. }
  1252. return true;
  1253. }
  1254. bool isValid()
  1255. {
  1256. return curvalid;
  1257. }
  1258. IFile & query()
  1259. {
  1260. if (!cur) {
  1261. StringBuffer full(dir);
  1262. addPathSepChar(full).append(curname);
  1263. if (ep.isNull())
  1264. cur.setown(createIFile(full.str()));
  1265. else {
  1266. RemoteFilename rfn;
  1267. rfn.setPath(ep,full.str());
  1268. cur.setown(createIFile(rfn));
  1269. }
  1270. }
  1271. return *cur;
  1272. }
  1273. StringBuffer &getName(StringBuffer &buf)
  1274. {
  1275. return buf.append(curname);
  1276. }
  1277. bool isDir()
  1278. {
  1279. return curisdir;
  1280. }
  1281. __int64 getFileSize()
  1282. {
  1283. if (curisdir)
  1284. return -1;
  1285. return cursize;
  1286. }
  1287. bool getModifiedTime(CDateTime &ret)
  1288. {
  1289. ret = curdt;
  1290. return true;
  1291. }
  1292. void setMask(unsigned _mask)
  1293. {
  1294. mask = _mask;
  1295. }
  1296. virtual unsigned getFlags()
  1297. {
  1298. if (flags&&(curidx<numflags))
  1299. return flags[curidx];
  1300. return 0;
  1301. }
  1302. static bool serialize(MemoryBuffer &mb,IDirectoryIterator *iter, size32_t bufsize, bool first)
  1303. {
  1304. bool ret = true;
  1305. byte b=1;
  1306. StringBuffer tmp;
  1307. if (first ? iter->first() : iter->next()) {
  1308. loop {
  1309. mb.append(b);
  1310. bool isdir = iter->isDir();
  1311. __int64 sz = isdir?0:iter->getFileSize();
  1312. CDateTime dt;
  1313. iter->getModifiedTime(dt);
  1314. iter->getName(tmp.clear());
  1315. mb.append(isdir).append(sz);
  1316. dt.serialize(mb);
  1317. mb.append(tmp.str());
  1318. if (bufsize&&(mb.length()>=bufsize-1)) {
  1319. ret = false;
  1320. break;
  1321. }
  1322. if (!iter->next())
  1323. break;
  1324. }
  1325. }
  1326. b = 0;
  1327. mb.append(b);
  1328. return ret;
  1329. }
  1330. static void serializeDiff(MemoryBuffer &mb,IDirectoryDifferenceIterator *iter)
  1331. {
  1332. // bit slow
  1333. MemoryBuffer flags;
  1334. ForEach(*iter)
  1335. flags.append((byte)iter->getFlags());
  1336. if (flags.length()) {
  1337. byte b = 2;
  1338. mb.append(b).append((unsigned)flags.length()).append(flags);
  1339. }
  1340. serialize(mb,iter,0,true);
  1341. }
  1342. void serialize(MemoryBuffer &mb,bool isdiff)
  1343. {
  1344. byte b;
  1345. if (isdiff&&numflags&&flags) {
  1346. b = 2;
  1347. mb.append(b).append(numflags).append(numflags,flags);
  1348. }
  1349. serialize(mb,this,0,true);
  1350. }
  1351. };
  1352. class CCritTable;
  1353. class CEndpointCS : public CriticalSection, public CInterface
  1354. {
  1355. CCritTable &table;
  1356. const SocketEndpoint ep;
  1357. public:
  1358. CEndpointCS(CCritTable &_table, const SocketEndpoint &_ep) : table(_table), ep(_ep) { }
  1359. const void *queryFindParam() const { return &ep; }
  1360. virtual void beforeDispose();
  1361. };
  1362. class CCritTable : private SimpleHashTableOf<CEndpointCS, const SocketEndpoint>
  1363. {
  1364. typedef SimpleHashTableOf<CEndpointCS, const SocketEndpoint> PARENT;
  1365. CriticalSection crit;
  1366. public:
  1367. CEndpointCS *getCrit(const SocketEndpoint &ep)
  1368. {
  1369. CriticalBlock b(crit);
  1370. Linked<CEndpointCS> clientCrit = find(ep);
  1371. if (!clientCrit || !clientCrit->isAlive()) // if !isAlive(), then it is in the process of being destroyed/removed.
  1372. {
  1373. clientCrit.setown(new CEndpointCS(*this, ep));
  1374. replace(*clientCrit); // NB table doesn't own
  1375. }
  1376. return clientCrit.getClear();
  1377. }
  1378. void removeExact(CEndpointCS *clientCrit)
  1379. {
  1380. CriticalBlock b(crit);
  1381. PARENT::removeExact(clientCrit); // NB may not exist, could have been replaced if detected !isAlive() in getCrit()
  1382. }
  1383. } *dirCSTable;
  1384. MODULE_INIT(INIT_PRIORITY_STANDARD)
  1385. {
  1386. dirCSTable = new CCritTable;
  1387. return true;
  1388. }
  1389. MODULE_EXIT()
  1390. {
  1391. delete dirCSTable;
  1392. }
  1393. void CEndpointCS::beforeDispose()
  1394. {
  1395. table.removeExact(this);
  1396. }
  1397. class CRemoteFile : public CRemoteBase, implements IFile
  1398. {
  1399. StringAttr remotefilename;
  1400. unsigned flags;
  1401. public:
  1402. IMPLEMENT_IINTERFACE
  1403. CRemoteFile(const SocketEndpoint &_ep, const char * _filename)
  1404. : CRemoteBase(_ep, _filename)
  1405. {
  1406. flags = ((unsigned)IFSHread)|((S_IRUSR|S_IWUSR)<<16);
  1407. }
  1408. bool exists()
  1409. {
  1410. MemoryBuffer sendBuffer;
  1411. initSendBuffer(sendBuffer);
  1412. MemoryBuffer replyBuffer;
  1413. sendBuffer.append((RemoteFileCommandType)RFCexists).append(filename);
  1414. sendRemoteCommand(sendBuffer, replyBuffer);
  1415. bool ok;
  1416. replyBuffer.read(ok);
  1417. return ok;
  1418. }
  1419. bool getTime(CDateTime * createTime, CDateTime * modifiedTime, CDateTime * accessedTime)
  1420. {
  1421. CDateTime dummyTime;
  1422. if (!createTime)
  1423. createTime = &dummyTime;
  1424. if (!modifiedTime)
  1425. modifiedTime = &dummyTime;
  1426. if (!accessedTime)
  1427. accessedTime = &dummyTime;
  1428. MemoryBuffer sendBuffer;
  1429. initSendBuffer(sendBuffer);
  1430. MemoryBuffer replyBuffer;
  1431. sendBuffer.append((RemoteFileCommandType)RFCgettime).append(filename);
  1432. sendRemoteCommand(sendBuffer, replyBuffer);
  1433. bool ok;
  1434. replyBuffer.read(ok);
  1435. if (ok) {
  1436. createTime->deserialize(replyBuffer);
  1437. modifiedTime->deserialize(replyBuffer);
  1438. accessedTime->deserialize(replyBuffer);
  1439. }
  1440. return ok;
  1441. }
  1442. bool setTime(const CDateTime * createTime, const CDateTime * modifiedTime, const CDateTime * accessedTime)
  1443. {
  1444. MemoryBuffer sendBuffer;
  1445. initSendBuffer(sendBuffer);
  1446. MemoryBuffer replyBuffer;
  1447. sendBuffer.append((RemoteFileCommandType)RFCsettime).append(filename);
  1448. if (createTime) {
  1449. sendBuffer.append((bool)true);
  1450. createTime->serialize(sendBuffer);
  1451. }
  1452. else
  1453. sendBuffer.append((bool)false);
  1454. if (modifiedTime) {
  1455. sendBuffer.append((bool)true);
  1456. modifiedTime->serialize(sendBuffer);
  1457. }
  1458. else
  1459. sendBuffer.append((bool)false);
  1460. if (accessedTime) {
  1461. sendBuffer.append((bool)true);
  1462. accessedTime->serialize(sendBuffer);
  1463. }
  1464. else
  1465. sendBuffer.append((bool)false);
  1466. sendRemoteCommand(sendBuffer, replyBuffer);
  1467. bool ok;
  1468. replyBuffer.read(ok);
  1469. return ok;
  1470. }
  1471. fileBool isDirectory()
  1472. {
  1473. MemoryBuffer sendBuffer;
  1474. initSendBuffer(sendBuffer);
  1475. MemoryBuffer replyBuffer;
  1476. sendBuffer.append((RemoteFileCommandType)RFCisdirectory).append(filename);
  1477. sendRemoteCommand(sendBuffer, replyBuffer);
  1478. unsigned ret;
  1479. replyBuffer.read(ret);
  1480. return (fileBool)ret;
  1481. }
  1482. fileBool isFile()
  1483. {
  1484. MemoryBuffer sendBuffer;
  1485. initSendBuffer(sendBuffer);
  1486. MemoryBuffer replyBuffer;
  1487. sendBuffer.append((RemoteFileCommandType)RFCisfile).append(filename);
  1488. sendRemoteCommand(sendBuffer, replyBuffer);
  1489. unsigned ret;
  1490. replyBuffer.read(ret);
  1491. return (fileBool)ret;
  1492. }
  1493. fileBool isReadOnly()
  1494. {
  1495. MemoryBuffer sendBuffer;
  1496. initSendBuffer(sendBuffer);
  1497. MemoryBuffer replyBuffer;
  1498. sendBuffer.append((RemoteFileCommandType)RFCisreadonly).append(filename);
  1499. sendRemoteCommand(sendBuffer, replyBuffer);
  1500. unsigned ret;
  1501. replyBuffer.read(ret);
  1502. return (fileBool)ret;
  1503. }
  1504. IFileIO * open(IFOmode mode);
  1505. IFileIO * openShared(IFOmode mode,IFSHmode shmode);
  1506. IFileAsyncIO * openAsync(IFOmode mode) { return NULL; } // not supported
  1507. const char * queryFilename()
  1508. {
  1509. if (remotefilename.isEmpty()) {
  1510. RemoteFilename rfn;
  1511. rfn.setPath(ep,filename);
  1512. StringBuffer path;
  1513. rfn.getRemotePath(path);
  1514. remotefilename.set(path);
  1515. }
  1516. return remotefilename.get();
  1517. }
  1518. void resetLocalFilename(const char *name)
  1519. {
  1520. remotefilename.clear();
  1521. filename.set(name);
  1522. }
  1523. bool remove()
  1524. {
  1525. MemoryBuffer sendBuffer;
  1526. initSendBuffer(sendBuffer);
  1527. MemoryBuffer replyBuffer;
  1528. sendBuffer.append((RemoteFileCommandType)RFCremove).append(filename);
  1529. sendRemoteCommand(sendBuffer, replyBuffer);
  1530. bool ok;
  1531. replyBuffer.read(ok);
  1532. return ok;
  1533. }
  1534. void rename(const char *newname)
  1535. {
  1536. // currently ignores directory on newname (in future versions newname will be required to be tail only and not full path)
  1537. StringBuffer path;
  1538. splitDirTail(filename,path);
  1539. StringBuffer newdir;
  1540. path.append(splitDirTail(newname,newdir));
  1541. if (newdir.length()&&(strcmp(newdir.str(),path.str())!=0))
  1542. WARNLOG("CRemoteFile::rename passed full path '%s' that may not to match original directory '%s'",newname,path.str());
  1543. MemoryBuffer sendBuffer;
  1544. initSendBuffer(sendBuffer);
  1545. MemoryBuffer replyBuffer;
  1546. sendBuffer.append((RemoteFileCommandType)RFCrename).append(filename).append(path);
  1547. sendRemoteCommand(sendBuffer, replyBuffer);
  1548. filename.set(path);
  1549. remotefilename.clear();
  1550. }
  1551. void move(const char *newname)
  1552. {
  1553. // like rename except between directories
  1554. // first create replote path
  1555. if (!newname||!*newname)
  1556. return;
  1557. RemoteFilename destrfn;
  1558. if (isPathSepChar(newname[0])&&isPathSepChar(newname[1])) {
  1559. destrfn.setRemotePath(newname);
  1560. if (!destrfn.queryEndpoint().ipequals(ep)) {
  1561. StringBuffer msg;
  1562. msg.appendf("IFile::move %s to %s, destination node must match source node", queryFilename(), newname);
  1563. throw createDafsException(RFSERR_MoveFailed,msg.str());
  1564. }
  1565. }
  1566. else
  1567. destrfn.setPath(ep,newname);
  1568. StringBuffer dest;
  1569. newname = destrfn.getLocalPath(dest).str();
  1570. MemoryBuffer sendBuffer;
  1571. initSendBuffer(sendBuffer);
  1572. MemoryBuffer replyBuffer;
  1573. StringBuffer path;
  1574. splitDirTail(filename,path);
  1575. StringBuffer newdir;
  1576. const char *newtail = splitDirTail(newname,newdir);
  1577. if (strcmp(newdir.str(),path.str())==0) {
  1578. path.append(newtail);
  1579. newname = path;
  1580. sendBuffer.append((RemoteFileCommandType)RFCrename); // use rename if we can (supported on older dafilesrv)
  1581. }
  1582. else
  1583. sendBuffer.append((RemoteFileCommandType)RFCmove);
  1584. sendBuffer.append(filename).append(newname);
  1585. sendRemoteCommand(sendBuffer, replyBuffer);
  1586. filename.set(newname);
  1587. remotefilename.clear();
  1588. }
  1589. void setReadOnly(bool set)
  1590. {
  1591. MemoryBuffer sendBuffer;
  1592. initSendBuffer(sendBuffer);
  1593. MemoryBuffer replyBuffer;
  1594. sendBuffer.append((RemoteFileCommandType)RFCsetreadonly).append(filename).append(set);
  1595. sendRemoteCommand(sendBuffer, replyBuffer);
  1596. }
  1597. offset_t size()
  1598. {
  1599. #if 1 // faster method (consistant with IFile)
  1600. // do this by using dir call (could be improved with new function but this not *too* bad)
  1601. if (isSpecialPath(filename))
  1602. return 0; // queries deemed to always exist (though don't know size).
  1603. // if needed to get size I guess could use IFileIO method and cache (bit of pain though)
  1604. StringBuffer dir;
  1605. const char *tail = splitDirTail(filename,dir);
  1606. if (!dir.length())
  1607. return false;
  1608. MemoryBuffer sendBuffer;
  1609. initSendBuffer(sendBuffer);
  1610. MemoryBuffer replyBuffer;
  1611. bool includedirs = true;
  1612. bool sub=false;
  1613. {
  1614. //Could be removed with new dafilesrv change [ (stream != 0) ], since this is not streaming.
  1615. Owned<CEndpointCS> crit = dirCSTable->getCrit(ep); // NB dirCSTable doesn't own, last reference will remove from table
  1616. CriticalBlock block(*crit);
  1617. sendBuffer.append((RemoteFileCommandType)RFCgetdir).append(dir).append(tail).append(includedirs).append(sub);
  1618. sendRemoteCommand(sendBuffer, replyBuffer);
  1619. }
  1620. // now should be 0 or 1 files returned
  1621. Owned<CRemoteDirectoryIterator> iter = new CRemoteDirectoryIterator(ep, dir.str());
  1622. iter->appendBuf(replyBuffer);
  1623. if (!iter->first())
  1624. return (offset_t)-1;
  1625. return (offset_t) iter->getFileSize();
  1626. #else
  1627. IFileIO * io = open(IFOread);
  1628. offset_t length = (offset_t)-1;
  1629. if (io)
  1630. {
  1631. length = io->size();
  1632. io->Release();
  1633. }
  1634. return length;
  1635. #endif
  1636. }
  1637. bool createDirectory()
  1638. {
  1639. MemoryBuffer sendBuffer;
  1640. initSendBuffer(sendBuffer);
  1641. MemoryBuffer replyBuffer;
  1642. sendBuffer.append((RemoteFileCommandType)RFCcreatedir).append(filename);
  1643. sendRemoteCommand(sendBuffer, replyBuffer);
  1644. bool ok;
  1645. replyBuffer.read(ok);
  1646. return ok;
  1647. }
  1648. virtual IDirectoryIterator *directoryFiles(const char *mask,bool sub,bool includedirs)
  1649. {
  1650. if (mask&&!*mask)
  1651. return createDirectoryIterator("",""); // NULL iterator
  1652. CRemoteDirectoryIterator *ret = new CRemoteDirectoryIterator(ep, filename);
  1653. byte stream=1;
  1654. Owned<CEndpointCS> crit = dirCSTable->getCrit(ep); // NB dirCSTable doesn't own, last reference will remove from table
  1655. CriticalBlock block(*crit);
  1656. loop {
  1657. MemoryBuffer sendBuffer;
  1658. initSendBuffer(sendBuffer);
  1659. MemoryBuffer replyBuffer;
  1660. sendBuffer.append((RemoteFileCommandType)RFCgetdir).append(filename).append(mask?mask:"").append(includedirs).append(sub).append(stream);
  1661. sendRemoteCommand(sendBuffer, replyBuffer);
  1662. if (ret->appendBuf(replyBuffer))
  1663. break;
  1664. stream = 2;
  1665. }
  1666. return ret;
  1667. }
  1668. IDirectoryDifferenceIterator *monitorDirectory(
  1669. IDirectoryIterator *prev=NULL, // in (NULL means use current as baseline)
  1670. const char *mask=NULL,
  1671. bool sub=false,
  1672. bool includedirs=false,
  1673. unsigned checkinterval=60*1000,
  1674. unsigned timeout=(unsigned)-1,
  1675. Semaphore *abortsem=NULL) // returns NULL if timed out
  1676. {
  1677. // abortsem not yet supported
  1678. MemoryBuffer sendBuffer;
  1679. initSendBuffer(sendBuffer);
  1680. MemoryBuffer replyBuffer;
  1681. sendBuffer.append((RemoteFileCommandType)RFCmonitordir).append(filename).append(mask?mask:"").append(includedirs).append(sub);
  1682. sendBuffer.append(checkinterval).append(timeout);
  1683. __int64 cancelid=0; // not yet used
  1684. sendBuffer.append(cancelid);
  1685. byte isprev=(prev!=NULL)?1:0;
  1686. sendBuffer.append(isprev);
  1687. if (prev)
  1688. CRemoteDirectoryIterator::serialize(sendBuffer,prev,0,true);
  1689. sendRemoteCommand(sendBuffer, replyBuffer);
  1690. byte status;
  1691. replyBuffer.read(status);
  1692. if (status==1) {
  1693. CRemoteDirectoryIterator *iter = new CRemoteDirectoryIterator(ep, filename);
  1694. iter->appendBuf(replyBuffer);
  1695. return iter;
  1696. }
  1697. return NULL;
  1698. }
  1699. bool getInfo(bool &isdir,offset_t &size,CDateTime &modtime)
  1700. {
  1701. // do this by using dir call (could be improved with new function but this not *too* bad)
  1702. StringBuffer dir;
  1703. const char *tail = splitDirTail(filename,dir);
  1704. if (!dir.length())
  1705. return false;
  1706. MemoryBuffer sendBuffer;
  1707. initSendBuffer(sendBuffer);
  1708. MemoryBuffer replyBuffer;
  1709. bool includedirs = true;
  1710. bool sub=false;
  1711. {
  1712. //Could be removed with new dafilesrv change [ (stream != 0) ], since this is not streaming.
  1713. Owned<CEndpointCS> crit = dirCSTable->getCrit(ep); // NB dirCSTable doesn't own, last reference will remove from table
  1714. CriticalBlock block(*crit);
  1715. sendBuffer.append((RemoteFileCommandType)RFCgetdir).append(dir).append(tail).append(includedirs).append(sub);
  1716. sendRemoteCommand(sendBuffer, replyBuffer);
  1717. }
  1718. // now should be 0 or 1 files returned
  1719. Owned<CRemoteDirectoryIterator> iter = new CRemoteDirectoryIterator(ep, dir.str());
  1720. iter->appendBuf(replyBuffer);
  1721. if (!iter->first())
  1722. return false;
  1723. isdir = iter->isDir();
  1724. size = (offset_t) iter->getFileSize();
  1725. iter->getModifiedTime(modtime);
  1726. return true;
  1727. }
  1728. bool setCompression(bool set)
  1729. {
  1730. assertex(!"Need to implement compress()");
  1731. return false;
  1732. }
  1733. offset_t compressedSize()
  1734. {
  1735. assertex(!"Need to implement actualSize()");
  1736. return (offset_t)-1;
  1737. }
  1738. void serialize(MemoryBuffer &tgt)
  1739. {
  1740. throwUnexpected();
  1741. }
  1742. void deserialize(MemoryBuffer &src)
  1743. {
  1744. throwUnexpected();
  1745. }
  1746. unsigned getCRC()
  1747. {
  1748. MemoryBuffer sendBuffer;
  1749. initSendBuffer(sendBuffer);
  1750. MemoryBuffer replyBuffer;
  1751. sendBuffer.append((RemoteFileCommandType)RFCgetcrc).append(filename);
  1752. sendRemoteCommand(sendBuffer, replyBuffer, true, true);
  1753. unsigned crc;
  1754. replyBuffer.read(crc);
  1755. return crc;
  1756. }
  1757. void setCreateFlags(unsigned cflags)
  1758. {
  1759. flags |= (cflags<<16);
  1760. }
  1761. void setShareMode(IFSHmode shmode)
  1762. {
  1763. flags &= ~(IFSHfull|IFSHread);
  1764. flags |= (unsigned)(shmode&(IFSHfull|IFSHread));
  1765. }
  1766. void remoteExtractBlobElements(const char * prefix, ExtractedBlobArray & extracted)
  1767. {
  1768. MemoryBuffer sendBuffer;
  1769. initSendBuffer(sendBuffer);
  1770. sendBuffer.append((RemoteFileCommandType)RFCextractblobelements).append(prefix).append(filename);
  1771. MemoryBuffer replyBuffer;
  1772. sendRemoteCommand(sendBuffer, replyBuffer, true, true); // handles error code
  1773. unsigned n;
  1774. replyBuffer.read(n);
  1775. for (unsigned i=0;i<n;i++) {
  1776. ExtractedBlobInfo *item = new ExtractedBlobInfo;
  1777. item->deserialize(replyBuffer);
  1778. extracted.append(*item);
  1779. }
  1780. }
  1781. bool copySectionAsync(const char *uuid,const RemoteFilename &dest, offset_t toOfs, offset_t fromOfs, offset_t size, ICopyFileProgress *progress, unsigned timeout)
  1782. {
  1783. // now if we get here is it can be assumed the source file is local to where we send the command
  1784. StringBuffer tos;
  1785. dest.getRemotePath(tos);
  1786. MemoryBuffer sendBuffer;
  1787. initSendBuffer(sendBuffer);
  1788. MemoryBuffer replyBuffer;
  1789. sendBuffer.append((RemoteFileCommandType)RFCcopysection).append(uuid).append(queryLocalName()).append(tos).append(toOfs).append(fromOfs).append(size).append(timeout);
  1790. sendRemoteCommand(sendBuffer, replyBuffer);
  1791. unsigned status;
  1792. replyBuffer.read(status);
  1793. if (progress) {
  1794. offset_t sizeDone;
  1795. offset_t totalSize;
  1796. replyBuffer.read(sizeDone).read(totalSize);
  1797. progress->onProgress(sizeDone,totalSize);
  1798. }
  1799. return (AsyncCommandStatus)status!=ACScontinue; // should only otherwise be done as errors raised by exception
  1800. }
  1801. void copySection(const RemoteFilename &dest, offset_t toOfs, offset_t fromOfs, offset_t size, ICopyFileProgress *progress)
  1802. {
  1803. StringBuffer uuid;
  1804. genUUID(uuid,true);
  1805. unsigned timeout = 60*1000; // check every minute
  1806. while(!copySectionAsync(uuid.str(),dest,toOfs,fromOfs,size,progress,timeout));
  1807. }
  1808. void copyTo(IFile *dest, size32_t buffersize, ICopyFileProgress *progress, bool usetmp);
  1809. virtual IMemoryMappedFile *openMemoryMapped(offset_t ofs, memsize_t len, bool write)
  1810. {
  1811. return NULL;
  1812. }
  1813. void treeCopyTo(IFile *dest,IpSubNet &subnet,IpAddress &resfrom,bool usetmp)
  1814. {
  1815. resfrom.ipset(NULL);
  1816. MemoryBuffer sendBuffer;
  1817. initSendBuffer(sendBuffer);
  1818. MemoryBuffer replyBuffer;
  1819. sendBuffer.append((RemoteFileCommandType)(usetmp?RFCtreecopytmp:RFCtreecopy));
  1820. RemoteFilename rfn;
  1821. rfn.setPath(ep,filename);
  1822. rfn.serialize(sendBuffer);
  1823. const char *d = dest->queryFilename();
  1824. if (!isAbsolutePath(d))
  1825. throw MakeStringException(-1,"treeCopyFile destination '%s' is not an absolute path", d);
  1826. rfn.setRemotePath(d);
  1827. rfn.serialize(sendBuffer);
  1828. StringBuffer tmp;
  1829. subnet.getNetText(tmp);
  1830. sendBuffer.append(tmp);
  1831. subnet.getMaskText(tmp.clear());
  1832. sendBuffer.append(tmp);
  1833. unsigned status=1;
  1834. try {
  1835. sendRemoteCommand(sendBuffer, replyBuffer);
  1836. replyBuffer.read(status);
  1837. }
  1838. catch (IDAFS_Exception *e) {
  1839. if (e->errorCode()!=RFSERR_InvalidCommand)
  1840. throw;
  1841. e->Release();
  1842. status = (unsigned)-1;
  1843. }
  1844. if (status==-1) {
  1845. resfrom.ipset(ep);
  1846. StringBuffer tmp;
  1847. WARNLOG("dafilesrv on %s does not support treeCopyTo - falling back to copyTo",resfrom.getIpText(tmp).str());
  1848. copyTo(dest,0x100000,NULL,usetmp);
  1849. status = 0;
  1850. }
  1851. else if (status==0)
  1852. resfrom.ipdeserialize(replyBuffer);
  1853. }
  1854. };
  1855. void clientCacheFileConnect(SocketEndpoint &_ep,unsigned timeout)
  1856. {
  1857. if (!timeout) {
  1858. SocketEndpoint ep(_ep);
  1859. setDafsEndpointPort(ep);
  1860. Owned<CRemoteFile> cfile = new CRemoteFile(ep, "null");
  1861. cfile->connect();
  1862. return; // frees file and adds its socket to cache
  1863. }
  1864. // timeout needed so start a thread (that may become orphaned)
  1865. class cThread: public Thread
  1866. {
  1867. SocketEndpoint ep;
  1868. public:
  1869. cThread(SocketEndpoint &_ep)
  1870. : Thread("cacheFileConnect")
  1871. {
  1872. ep = _ep;
  1873. }
  1874. int run()
  1875. {
  1876. try {
  1877. clientCacheFileConnect(ep,0);
  1878. }
  1879. catch (IException *e) {
  1880. CriticalBlock block(sect);
  1881. except.setown(e);
  1882. }
  1883. return 0;
  1884. }
  1885. Owned<IException> except;
  1886. CriticalSection sect;
  1887. } *thread;
  1888. thread = new cThread(_ep);
  1889. thread->start();
  1890. IException *e =NULL;
  1891. if (!thread->join(timeout)) {
  1892. StringBuffer msg("Timed out connecting to ");
  1893. _ep.getUrlStr(msg);
  1894. e = createDafsException(RFSERR_AuthenticateFailed,msg.str());
  1895. }
  1896. {
  1897. CriticalBlock block(thread->sect);
  1898. if (!e&&thread->except)
  1899. e = thread->except.getClear();
  1900. }
  1901. thread->Release();
  1902. if (e)
  1903. throw e;
  1904. }
  1905. void clientAddSocketToCache(SocketEndpoint &ep,ISocket *socket)
  1906. {
  1907. CriticalBlock block(CConnectionTable::crit);
  1908. if (ConnectionTable)
  1909. ConnectionTable->addLink(ep,socket);
  1910. }
  1911. IFile * createRemoteFile(SocketEndpoint &ep, const char * filename)
  1912. {
  1913. IFile *ret = createFileLocalMount(ep,filename);
  1914. if (ret)
  1915. return ret;
  1916. return new CRemoteFile(ep, filename);
  1917. }
  1918. void clientDisconnectRemoteFile(IFile *file)
  1919. {
  1920. CRemoteFile *cfile = QUERYINTERFACE(file,CRemoteFile);
  1921. if (cfile)
  1922. cfile->disconnect();
  1923. }
  1924. bool clientResetFilename(IFile *file, const char *newname) // returns false if not remote
  1925. {
  1926. CRemoteFile *cfile = QUERYINTERFACE(file,CRemoteFile);
  1927. if (!cfile)
  1928. return false;
  1929. cfile->resetLocalFilename(newname);
  1930. return true;
  1931. }
  1932. extern bool clientAsyncCopyFileSection(const char *uuid,
  1933. IFile *from, // expected to be remote
  1934. RemoteFilename &to,
  1935. offset_t toOfs, // -1 created file and copies to start
  1936. offset_t fromOfs,
  1937. offset_t size,
  1938. ICopyFileProgress *progress,
  1939. unsigned timeout) // returns true when done
  1940. {
  1941. CRemoteFile *cfile = QUERYINTERFACE(from,CRemoteFile);
  1942. if (!cfile) {
  1943. // local - do sync
  1944. from->copySection(to,toOfs,fromOfs,size,progress);
  1945. return true;
  1946. }
  1947. return cfile->copySectionAsync(uuid,to,toOfs,fromOfs, size, progress, timeout);
  1948. }
  1949. //---------------------------------------------------------------------------
  1950. class CRemoteFileIO : public CInterface, implements IFileIO
  1951. {
  1952. protected:
  1953. Linked<CRemoteFile> parent;
  1954. RemoteFileIOHandle handle;
  1955. IFOmode mode;
  1956. compatIFSHmode compatmode;
  1957. bool disconnectonexit;
  1958. public:
  1959. IMPLEMENT_IINTERFACE
  1960. CRemoteFileIO(CRemoteFile *_parent)
  1961. : parent(_parent)
  1962. {
  1963. handle = 0;
  1964. disconnectonexit = false;
  1965. }
  1966. ~CRemoteFileIO()
  1967. {
  1968. if (handle) {
  1969. try {
  1970. MemoryBuffer sendBuffer;
  1971. initSendBuffer(sendBuffer);
  1972. sendBuffer.append((RemoteFileCommandType)RFCcloseIO).append(handle);
  1973. parent->sendRemoteCommand(sendBuffer,false);
  1974. }
  1975. catch (IDAFS_Exception *e) {
  1976. if ((e->errorCode()!=RFSERR_InvalidFileIOHandle)&&(e->errorCode()!=RFSERR_NullFileIOHandle)) { // ignore already disconnected
  1977. StringBuffer s;
  1978. e->errorMessage(s);
  1979. WARNLOG("CRemoteFileIO close file: %s",s.str());
  1980. }
  1981. e->Release();
  1982. }
  1983. catch (IException *e) {
  1984. StringBuffer s;
  1985. e->errorMessage(s);
  1986. WARNLOG("CRemoteFileIO close file: %s",s.str());
  1987. e->Release();
  1988. }
  1989. }
  1990. if (disconnectonexit)
  1991. parent->disconnect();
  1992. handle = 0;
  1993. }
  1994. bool open(IFOmode _mode,compatIFSHmode _compatmode)
  1995. {
  1996. MemoryBuffer sendBuffer;
  1997. initSendBuffer(sendBuffer);
  1998. MemoryBuffer replyBuffer;
  1999. const char *localname = parent->queryLocalName();
  2000. localname = skipSpecialPath(localname);
  2001. sendBuffer.append((RemoteFileCommandType)RFCopenIO).append(localname).append((byte)_mode).append((byte)_compatmode);
  2002. parent->sendRemoteCommand(sendBuffer, replyBuffer);
  2003. replyBuffer.read(handle);
  2004. if (!handle)
  2005. return false;
  2006. switch (_mode) {
  2007. case IFOcreate:
  2008. mode = IFOwrite;
  2009. break;
  2010. case IFOcreaterw:
  2011. mode = IFOreadwrite;
  2012. break;
  2013. default:
  2014. mode = _mode;
  2015. }
  2016. compatmode = _compatmode;
  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)) {
  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. size32_t read(offset_t pos, size32_t len, void * data)
  2041. {
  2042. size32_t got;
  2043. MemoryBuffer replyBuffer;
  2044. const void *b = doRead(pos,len,replyBuffer,got,data);
  2045. if (b!=data)
  2046. memcpy(data,b,got);
  2047. return got;
  2048. }
  2049. const void *doRead(offset_t pos, size32_t len, MemoryBuffer &replyBuffer, size32_t &got, void *dstbuf)
  2050. {
  2051. unsigned tries=0;
  2052. loop {
  2053. try {
  2054. MemoryBuffer sendBuffer;
  2055. initSendBuffer(sendBuffer);
  2056. replyBuffer.clear();
  2057. sendBuffer.append((RemoteFileCommandType)RFCread).append(handle).append(pos).append(len);
  2058. parent->sendRemoteCommand(sendBuffer, replyBuffer,false);
  2059. // kludge dafilesrv versions <= 1.5e don't return error correctly
  2060. if (replyBuffer.length()>len+sizeof(size32_t)+sizeof(unsigned)) {
  2061. size32_t save = replyBuffer.getPos();
  2062. replyBuffer.reset(len+sizeof(size32_t)+sizeof(unsigned));
  2063. unsigned errCode;
  2064. replyBuffer.read(errCode);
  2065. if (errCode) {
  2066. StringBuffer msg;
  2067. parent->ep.getUrlStr(msg.append('[')).append("] ");
  2068. if (replyBuffer.getPos()<replyBuffer.length()) {
  2069. StringAttr s;
  2070. replyBuffer.read(s);
  2071. msg.append(s);
  2072. }
  2073. else
  2074. msg.append("ERROR #").append(errCode);
  2075. throw createDafsException(errCode, msg.str());
  2076. }
  2077. else
  2078. replyBuffer.reset(save);
  2079. }
  2080. replyBuffer.read(got);
  2081. if ((got>replyBuffer.remaining())||(got>len)) {
  2082. PROGLOG("Read beyond buffer %d,%d,%d",got,replyBuffer.remaining(),len);
  2083. throw createDafsException(RFSERR_ReadFailed, "Read beyond buffer");
  2084. }
  2085. return replyBuffer.readDirect(got);
  2086. }
  2087. catch (IJSOCK_Exception *e) {
  2088. EXCLOG(e,"CRemoteFileIO::read");
  2089. if (++tries>3)
  2090. throw;
  2091. WARNLOG("Retrying read of %s (%d)",parent->queryLocalName(),tries);
  2092. Owned<IException> exc = e;
  2093. if (!reopen())
  2094. throw exc.getClear();
  2095. }
  2096. }
  2097. got = 0;
  2098. return NULL;
  2099. }
  2100. size32_t write(offset_t pos, size32_t len, const void * data)
  2101. {
  2102. unsigned tries=0;
  2103. size32_t ret = 0;
  2104. loop {
  2105. try {
  2106. MemoryBuffer replyBuffer;
  2107. MemoryBuffer sendBuffer;
  2108. initSendBuffer(sendBuffer);
  2109. sendBuffer.append((RemoteFileCommandType)RFCwrite).append(handle).append(pos).append(len).append(len, data);
  2110. parent->sendRemoteCommand(sendBuffer, replyBuffer, false, true);
  2111. replyBuffer.read(ret);
  2112. break;
  2113. }
  2114. catch (IJSOCK_Exception *e) {
  2115. EXCLOG(e,"CRemoteFileIO::write");
  2116. if (++tries>3)
  2117. throw;
  2118. WARNLOG("Retrying write(%"I64F"d,%d) of %s (%d)",pos,len,parent->queryLocalName(),tries);
  2119. Owned<IException> exc = e;
  2120. if (!reopen())
  2121. throw exc.getClear();
  2122. }
  2123. }
  2124. if ((ret==(size32_t)-1) || (ret < len))
  2125. throw createDafsException(DISK_FULL_EXCEPTION_CODE,"write failed, disk full?");
  2126. return ret;
  2127. }
  2128. offset_t appendFile(IFile *file,offset_t pos,offset_t len)
  2129. {
  2130. MemoryBuffer sendBuffer;
  2131. initSendBuffer(sendBuffer);
  2132. MemoryBuffer replyBuffer;
  2133. const char * fname = file->queryFilename();
  2134. sendBuffer.append((RemoteFileCommandType)RFCappend).append(handle).append(fname).append(pos).append(len);
  2135. parent->sendRemoteCommand(sendBuffer, replyBuffer, false, true); // retry not safe
  2136. offset_t ret;
  2137. replyBuffer.read(ret);
  2138. if ((ret==(offset_t)-1) || (ret < len))
  2139. throw createDafsException(DISK_FULL_EXCEPTION_CODE,"append failed, disk full?"); // though could be file missing TBD
  2140. return ret;
  2141. }
  2142. void setSize(offset_t size)
  2143. {
  2144. MemoryBuffer sendBuffer;
  2145. initSendBuffer(sendBuffer);
  2146. MemoryBuffer replyBuffer;
  2147. sendBuffer.append((RemoteFileCommandType)RFCsetsize).append(handle).append(size);
  2148. parent->sendRemoteCommand(sendBuffer, replyBuffer, false, true);
  2149. // retry using reopen TBD
  2150. }
  2151. void setDisconnectOnExit(bool set) { disconnectonexit = set; }
  2152. };
  2153. void clientDisconnectRemoteIoOnExit(IFileIO *fileio,bool set)
  2154. {
  2155. CRemoteFileIO *cfileio = QUERYINTERFACE(fileio,CRemoteFileIO);
  2156. if (cfileio)
  2157. cfileio->setDisconnectOnExit(set);
  2158. }
  2159. IFileIO * CRemoteFile::openShared(IFOmode mode,IFSHmode shmode)
  2160. {
  2161. assertex(((unsigned)shmode&0xffffffc7)==0);
  2162. compatIFSHmode compatmode;
  2163. unsigned fileflags = (flags>>16) & (S_IRUSR|S_IWUSR|S_IXUSR|S_IRGRP|S_IWGRP|S_IXGRP|S_IROTH|S_IWOTH|S_IXOTH);
  2164. if (fileflags&S_IXUSR) // this is bit hit and miss but backward compatible
  2165. compatmode = compatIFSHexec;
  2166. else if (fileflags&(S_IWGRP|S_IWOTH))
  2167. compatmode = compatIFSHall;
  2168. else if (shmode&IFSHfull)
  2169. compatmode = compatIFSHwrite;
  2170. else if (((shmode&(IFSHread|IFSHfull))==0) && ((fileflags&(S_IRGRP|S_IROTH))==0))
  2171. compatmode = compatIFSHnone;
  2172. else
  2173. compatmode = compatIFSHread;
  2174. Owned<CRemoteFileIO> res = new CRemoteFileIO(this);
  2175. if (res->open(mode,compatmode))
  2176. return res.getClear();
  2177. return NULL;
  2178. }
  2179. IFileIO * CRemoteFile::open(IFOmode mode)
  2180. {
  2181. return openShared(mode,(IFSHmode)(flags&(IFSHread|IFSHfull)));
  2182. }
  2183. //---------------------------------------------------------------------------
  2184. void CRemoteFile::copyTo(IFile *dest, size32_t buffersize, ICopyFileProgress *progress, bool usetmp)
  2185. {
  2186. CRemoteFile *dstfile = QUERYINTERFACE(dest,CRemoteFile);
  2187. if (dstfile&&!dstfile->queryEp().isLocal()) {
  2188. StringBuffer tmpname;
  2189. Owned<IFile> destf;
  2190. RemoteFilename dest;
  2191. if (usetmp) {
  2192. makeTempCopyName(tmpname,dstfile->queryLocalName());
  2193. dest.setPath(dstfile->queryEp(),tmpname.str());
  2194. }
  2195. else
  2196. dest.setPath(dstfile->queryEp(),dstfile->queryLocalName());
  2197. destf.setown(createIFile(dest));
  2198. try {
  2199. // following may fail if new dafilesrv not deployed on src
  2200. copySection(dest,(offset_t)-1,0,(offset_t)-1,progress);
  2201. if (usetmp) {
  2202. StringAttr tail(pathTail(dstfile->queryLocalName()));
  2203. dstfile->remove();
  2204. destf->rename(tail);
  2205. }
  2206. return;
  2207. }
  2208. catch (IException *e)
  2209. {
  2210. StringBuffer s;
  2211. s.appendf("Remote File Copy (%d): ",e->errorCode());
  2212. e->errorMessage(s);
  2213. s.append(", retrying local");
  2214. WARNLOG("%s",s.str());
  2215. e->Release();
  2216. }
  2217. // delete dest
  2218. try {
  2219. destf->remove();
  2220. }
  2221. catch (IException *e)
  2222. {
  2223. EXCLOG(e,"Remote File Copy, Deleting temporary file");
  2224. e->Release();
  2225. }
  2226. }
  2227. // assumption if we get here that source remote, dest local (or equiv)
  2228. class cIntercept: implements ICopyFileIntercept
  2229. {
  2230. MemoryAttr ma;
  2231. MemoryBuffer mb;
  2232. virtual offset_t copy(IFileIO *from, IFileIO *to, offset_t ofs, size32_t sz)
  2233. {
  2234. if (ma.length()<sz)
  2235. ma.allocate(sz); // may be not used
  2236. void *buf = ma.bufferBase();
  2237. size32_t got;
  2238. CRemoteFileIO *srcio = QUERYINTERFACE(from,CRemoteFileIO);
  2239. const void *dst;
  2240. if (srcio)
  2241. dst = srcio->doRead(ofs,sz,mb.clear(),got,buf);
  2242. else {
  2243. // shouldn't ever get here if source remote
  2244. got = from->read(ofs, sz, buf);
  2245. dst = buf;
  2246. }
  2247. if (got != 0)
  2248. to->write(ofs, got, dst);
  2249. return got;
  2250. }
  2251. } intercept;
  2252. doCopyFile(dest,this,buffersize,progress,&intercept,usetmp);
  2253. }
  2254. unsigned getRemoteVersion(ISocket * socket, StringBuffer &ver)
  2255. {
  2256. static CriticalSection sect;
  2257. CriticalBlock block(sect);
  2258. if (!socket)
  2259. return 0;
  2260. unsigned ret;
  2261. MemoryBuffer sendbuf;
  2262. initSendBuffer(sendbuf);
  2263. sendbuf.append((RemoteFileCommandType)RFCgetver);
  2264. sendbuf.append((unsigned)RFCgetver);
  2265. MemoryBuffer reply;
  2266. try {
  2267. sendBuffer(socket, sendbuf);
  2268. receiveBuffer(socket, reply, 1 ,4096);
  2269. unsigned errCode;
  2270. reply.read(errCode);
  2271. if (errCode==RFSERR_InvalidCommand) {
  2272. ver.append("DS V1.0");
  2273. return 10;
  2274. }
  2275. else if (errCode==0)
  2276. ret = 11;
  2277. else if (errCode<0x10000)
  2278. return 0;
  2279. else
  2280. ret = errCode-0x10000;
  2281. }
  2282. catch (IException *e) {
  2283. EXCLOG(e);
  2284. ::Release(e);
  2285. return 0;
  2286. }
  2287. StringAttr vers;
  2288. reply.read(vers);
  2289. ver.append(vers);
  2290. return ret;
  2291. }
  2292. extern unsigned stopRemoteServer(ISocket * socket)
  2293. {
  2294. static CriticalSection sect;
  2295. CriticalBlock block(sect);
  2296. if (!socket)
  2297. return 0;
  2298. MemoryBuffer sendbuf;
  2299. initSendBuffer(sendbuf);
  2300. sendbuf.append((RemoteFileCommandType)RFCstop);
  2301. sendbuf.append((unsigned)RFCstop);
  2302. MemoryBuffer replybuf;
  2303. unsigned errCode = RFSERR_InvalidCommand;
  2304. try {
  2305. sendBuffer(socket, sendbuf);
  2306. receiveBuffer(socket, replybuf, NORMAL_RETRIES, 1024);
  2307. replybuf.read(errCode);
  2308. }
  2309. catch (IJSOCK_Exception *e) {
  2310. if ((e->errorCode()!=JSOCKERR_broken_pipe)&&(e->errorCode()!=JSOCKERR_graceful_close))
  2311. EXCLOG(e);
  2312. else
  2313. errCode = 0;
  2314. }
  2315. catch (IException *e) {
  2316. EXCLOG(e);
  2317. ::Release(e);
  2318. }
  2319. return errCode;
  2320. }
  2321. int remoteExec(ISocket * socket, const char *cmdline, const char *workdir,bool sync,
  2322. size32_t insize, void *inbuf, MemoryBuffer *outbuf)
  2323. {
  2324. if (!socket)
  2325. return -1;
  2326. bool hasoutput = (outbuf!=NULL);
  2327. if (!inbuf)
  2328. insize = 0;
  2329. MemoryBuffer sendbuf;
  2330. initSendBuffer(sendbuf);
  2331. sendbuf.append((RemoteFileCommandType)RFCexec).append(cmdline).append(workdir).append(sync).
  2332. append(hasoutput).append(insize);
  2333. if (insize)
  2334. sendbuf.append(insize, inbuf);
  2335. MemoryBuffer replybuf;
  2336. try {
  2337. sendBuffer(socket, sendbuf);
  2338. receiveBuffer(socket, replybuf, LENGTHY_RETRIES); // we don't know how long program will take really - assume <1hr
  2339. int retcode;
  2340. unsigned phandle;
  2341. size32_t outsz;
  2342. replybuf.read(retcode).read(phandle).read(outsz);
  2343. if (outsz&&outbuf)
  2344. replybuf.read(outsz,outbuf->reserve(outsz));
  2345. return retcode;
  2346. }
  2347. catch (IException *e) {
  2348. EXCLOG(e);
  2349. ::Release(e);
  2350. }
  2351. return -1;
  2352. }
  2353. int setDafsTrace(ISocket * socket,byte flags)
  2354. {
  2355. if (!socket) {
  2356. byte ret = traceFlags;
  2357. traceFlags = flags;
  2358. return ret;
  2359. }
  2360. MemoryBuffer sendbuf;
  2361. initSendBuffer(sendbuf);
  2362. sendbuf.append((RemoteFileCommandType)RFCsettrace).append(flags);
  2363. MemoryBuffer replybuf;
  2364. try {
  2365. sendBuffer(socket, sendbuf);
  2366. receiveBuffer(socket, replybuf, NORMAL_RETRIES, 1024);
  2367. int retcode;
  2368. replybuf.read(retcode);
  2369. return retcode;
  2370. }
  2371. catch (IException *e) {
  2372. EXCLOG(e);
  2373. ::Release(e);
  2374. }
  2375. return -1;
  2376. }
  2377. int getDafsInfo(ISocket * socket,StringBuffer &retstr)
  2378. {
  2379. if (!socket) {
  2380. retstr.append(VERSTRING);
  2381. return 0;
  2382. }
  2383. MemoryBuffer sendbuf;
  2384. initSendBuffer(sendbuf);
  2385. sendbuf.append((RemoteFileCommandType)RFCgetinfo);
  2386. MemoryBuffer replybuf;
  2387. try {
  2388. sendBuffer(socket, sendbuf);
  2389. receiveBuffer(socket, replybuf, 1);
  2390. int retcode;
  2391. replybuf.read(retcode);
  2392. if (retcode==0) {
  2393. StringAttr s;
  2394. replybuf.read(s);
  2395. retstr.append(s);
  2396. }
  2397. return retcode;
  2398. }
  2399. catch (IException *e) {
  2400. EXCLOG(e);
  2401. ::Release(e);
  2402. }
  2403. return -1;
  2404. }
  2405. void remoteExtractBlobElements(const SocketEndpoint &ep,const char * prefix, const char * filename, ExtractedBlobArray & extracted)
  2406. {
  2407. Owned<CRemoteFile> file = new CRemoteFile (ep,filename);
  2408. file->remoteExtractBlobElements(prefix, extracted);
  2409. }
  2410. //====================================================================================================
  2411. class CAsyncCommandManager
  2412. {
  2413. class CAsyncJob: public CInterface
  2414. {
  2415. class cThread: public Thread
  2416. {
  2417. CAsyncJob *parent;
  2418. public:
  2419. cThread(CAsyncJob *_parent)
  2420. : Thread("CAsyncJob")
  2421. {
  2422. parent = _parent;
  2423. }
  2424. int run()
  2425. {
  2426. int ret;
  2427. try {
  2428. ret = parent->run();
  2429. parent->setDone();
  2430. }
  2431. catch (IException *e)
  2432. {
  2433. parent->setException(e);
  2434. }
  2435. parent->threadsem.signal();
  2436. return ret;
  2437. }
  2438. } *thread;
  2439. StringAttr uuid;
  2440. public:
  2441. Semaphore &threadsem;
  2442. CAsyncJob(const char *_uuid,Semaphore &_threadsem)
  2443. : uuid(_uuid),threadsem(_threadsem)
  2444. {
  2445. thread = new cThread(this);
  2446. hash = hashc((const byte *)uuid.get(),uuid.length(),~0U);
  2447. }
  2448. ~CAsyncJob()
  2449. {
  2450. thread->join();
  2451. thread->Release();
  2452. }
  2453. static void destroy(CAsyncJob *j)
  2454. {
  2455. j->Release();
  2456. }
  2457. void start()
  2458. {
  2459. threadsem.wait();
  2460. thread->start();
  2461. }
  2462. void join()
  2463. {
  2464. thread->join();
  2465. }
  2466. static unsigned getHash(const char *key)
  2467. {
  2468. return hashc((const byte *)key,strlen(key),~0U);
  2469. }
  2470. static CAsyncJob* create(const char *key) { assertex(!"CAsyncJob::create not implemented"); return NULL; }
  2471. unsigned hash;
  2472. bool eq(const char *key)
  2473. {
  2474. return stricmp(key,uuid.get())==0;
  2475. }
  2476. virtual int run()=0;
  2477. virtual void setException(IException *e)=0;
  2478. virtual void setDone()=0;
  2479. };
  2480. class CAsyncCopySection: public CAsyncJob
  2481. {
  2482. Owned<IFile> src;
  2483. RemoteFilename dst;
  2484. offset_t toOfs;
  2485. offset_t fromOfs;
  2486. offset_t size;
  2487. CFPmode mode; // not yet supported
  2488. CriticalSection sect;
  2489. offset_t done;
  2490. offset_t total;
  2491. Semaphore finished;
  2492. AsyncCommandStatus status;
  2493. Owned<IException> exc;
  2494. public:
  2495. CAsyncCopySection(const char *_uuid, const char *fromFile, const char *toFile, offset_t _toOfs, offset_t _fromOfs, offset_t _size, Semaphore &threadsem)
  2496. : CAsyncJob(_uuid,threadsem)
  2497. {
  2498. status = ACScontinue;
  2499. src.setown(createIFile(fromFile));
  2500. dst.setRemotePath(toFile);
  2501. toOfs = _toOfs;
  2502. fromOfs = _fromOfs;
  2503. size = _size;
  2504. mode = CFPcontinue;
  2505. done = 0;
  2506. total = (offset_t)-1;
  2507. }
  2508. AsyncCommandStatus poll(offset_t &_done, offset_t &_total,unsigned timeout)
  2509. {
  2510. if (timeout&&finished.wait(timeout))
  2511. finished.signal(); // may need to call again
  2512. CriticalBlock block(sect);
  2513. if (exc)
  2514. throw exc.getClear();
  2515. _done = done;
  2516. _total = total;
  2517. return status;
  2518. }
  2519. int run()
  2520. {
  2521. class cProgress: implements ICopyFileProgress
  2522. {
  2523. CriticalSection &sect;
  2524. CFPmode &mode;
  2525. offset_t &done;
  2526. offset_t &total;
  2527. public:
  2528. cProgress(CriticalSection &_sect,offset_t &_done,offset_t &_total,CFPmode &_mode)
  2529. : sect(_sect), done(_done), total(_total), mode(_mode)
  2530. {
  2531. }
  2532. CFPmode onProgress(offset_t sizeDone, offset_t totalSize)
  2533. {
  2534. CriticalBlock block(sect);
  2535. done = sizeDone;
  2536. total = totalSize;
  2537. return mode;
  2538. }
  2539. } progress(sect,total,done,mode);
  2540. src->copySection(dst,toOfs, fromOfs, size, &progress); // exceptions will be handled by base class
  2541. return 0;
  2542. }
  2543. void setException(IException *e)
  2544. {
  2545. EXCLOG(e,"CAsyncCommandManager::CAsyncJob");
  2546. CriticalBlock block(sect);
  2547. if (exc.get())
  2548. e->Release();
  2549. else
  2550. exc.setown(e);
  2551. status = ACSerror;
  2552. }
  2553. void setDone()
  2554. {
  2555. CriticalBlock block(sect);
  2556. finished.signal();
  2557. status = ACSdone;
  2558. }
  2559. };
  2560. CMinHashTable<CAsyncJob> jobtable;
  2561. CriticalSection sect;
  2562. Semaphore threadsem;
  2563. public:
  2564. CAsyncCommandManager()
  2565. {
  2566. threadsem.signal(10); // max number of async jobs
  2567. }
  2568. void join()
  2569. {
  2570. CriticalBlock block(sect);
  2571. unsigned i;
  2572. CAsyncJob *j=jobtable.first(i);
  2573. while (j) {
  2574. j->join();
  2575. j=jobtable.next(i);
  2576. }
  2577. }
  2578. 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)
  2579. {
  2580. // return 0 if continuing, 1 if done
  2581. CAsyncCopySection * job;
  2582. Linked<CAsyncJob> cjob;
  2583. {
  2584. CriticalBlock block(sect);
  2585. cjob.set(jobtable.find(uuid,false));
  2586. if (cjob) {
  2587. job = QUERYINTERFACE(cjob.get(),CAsyncCopySection);
  2588. if (!job) {
  2589. throw MakeStringException(-1,"Async job ID mismatch");
  2590. }
  2591. }
  2592. else {
  2593. job = new CAsyncCopySection(uuid, fromFile, toFile, toOfs, fromOfs, size, threadsem);
  2594. cjob.setown(job);
  2595. jobtable.add(cjob.getLink());
  2596. cjob->start();
  2597. }
  2598. }
  2599. AsyncCommandStatus ret;
  2600. Owned<IException> rete;
  2601. try {
  2602. ret = job->poll(done,total,timeout);
  2603. }
  2604. catch (IException * e) {
  2605. rete.setown(e);
  2606. }
  2607. if ((ret!=ACScontinue)||rete.get()) {
  2608. job->join();
  2609. CriticalBlock block(sect);
  2610. jobtable.remove(job);
  2611. if (rete.get())
  2612. throw rete.getClear();
  2613. }
  2614. return ret;
  2615. }
  2616. };
  2617. //====================================================================================================
  2618. #define throwErr3(e,v,s) { StringBuffer msg; \
  2619. msg.appendf("ERROR: %s(%d) '%s'",#e,v,s?s:""); \
  2620. reply.append(e); reply.append(msg.str()); }
  2621. #define throwErr(e) { reply.append(e).append(#e); }
  2622. #define throwErr2(e,v) { StringBuffer tmp; tmp.append(#e).append(':').append(v); reply.append(e).append(tmp.str()); }
  2623. #define MAPCOMMAND(c,p) case c: { ret = this->p(msg, reply) ; break; }
  2624. #define MAPCOMMANDCLIENT(c,p,client) case c: { ret = this->p(msg, reply, client); break; }
  2625. #define MAPCOMMANDCLIENTTHROTTLER(c,p,client,throttler) case c: { ret = this->p(msg, reply, client, throttler); break; }
  2626. static unsigned ClientCount = 0;
  2627. static unsigned MaxClientCount = 0;
  2628. static CriticalSection ClientCountSect;
  2629. class CRemoteFileServer : public CInterface, implements IRemoteFileServer, implements IThreadFactory
  2630. {
  2631. int lasthandle;
  2632. CriticalSection sect;
  2633. Owned<ISocket> acceptsock;
  2634. Owned<ISocketSelectHandler> selecthandler;
  2635. Owned<IThreadPool> threads; // for commands
  2636. bool stopping;
  2637. unsigned clientcounttick;
  2638. unsigned closedclients;
  2639. CAsyncCommandManager asyncCommandManager;
  2640. Semaphore throttlesem;
  2641. atomic_t globallasttick;
  2642. int getNextHandle()
  2643. {
  2644. // called in sect critical block
  2645. loop {
  2646. if (lasthandle==INT_MAX)
  2647. lasthandle = 1;
  2648. else
  2649. lasthandle++;
  2650. unsigned idx1;
  2651. unsigned idx2;
  2652. if (!findHandle(lasthandle,idx1,idx2))
  2653. return lasthandle;
  2654. }
  2655. }
  2656. bool findHandle(int handle,unsigned &clientidx,unsigned &handleidx)
  2657. {
  2658. // called in sect critical block
  2659. clientidx = (unsigned)-1;
  2660. handleidx = (unsigned)-1;
  2661. ForEachItemIn(i,clients) {
  2662. CRemoteClientHandler &client = clients.item(i);
  2663. ForEachItemIn(j,client.handles) {
  2664. if (client.handles.item(j)==handle) {
  2665. handleidx = j;
  2666. clientidx = i;
  2667. return true;
  2668. }
  2669. }
  2670. }
  2671. return false;
  2672. }
  2673. struct CRemoteClientHandler: public CInterface, implements ISocketSelectNotify
  2674. {
  2675. CRemoteFileServer *parent;
  2676. Owned<ISocket> socket;
  2677. Owned<IAuthenticatedUser> user;
  2678. MemoryBuffer buf;
  2679. bool selecthandled;
  2680. size32_t left;
  2681. IArrayOf<IFileIO> openfiles; // kept in sync with handles
  2682. Owned<IDirectoryIterator> opendir;
  2683. StringAttrArray opennames; // for debug
  2684. IntArray handles;
  2685. unsigned lasttick;
  2686. atomic_t &globallasttick;
  2687. unsigned previdx; // for debug
  2688. IMPLEMENT_IINTERFACE;
  2689. CRemoteClientHandler(CRemoteFileServer *_parent,ISocket *_socket,IAuthenticatedUser *_user,atomic_t &_globallasttick)
  2690. : socket(_socket), user(_user), globallasttick(_globallasttick)
  2691. {
  2692. previdx = (unsigned)-1;
  2693. CriticalBlock block(ClientCountSect);
  2694. if (++ClientCount>MaxClientCount)
  2695. MaxClientCount = ClientCount;
  2696. if (TF_TRACE_CLIENT_CONN) {
  2697. StringBuffer s;
  2698. s.appendf("Connecting(%x) [%d,%d] to ",(unsigned)(long)this,ClientCount,MaxClientCount);
  2699. peerName(s);
  2700. PROGLOG("%s",s.str());
  2701. }
  2702. parent = _parent;
  2703. left = 0;
  2704. buf.setEndian(__BIG_ENDIAN);
  2705. selecthandled = false;
  2706. touch();
  2707. }
  2708. ~CRemoteClientHandler()
  2709. {
  2710. {
  2711. CriticalBlock block(ClientCountSect);
  2712. ClientCount--;
  2713. if (TF_TRACE_CLIENT_CONN) {
  2714. PROGLOG("Disconnecting(%x) [%d,%d] ",(unsigned)(long)this,ClientCount,MaxClientCount);
  2715. }
  2716. }
  2717. ISocket *sock = socket.getClear();
  2718. try {
  2719. sock->Release();
  2720. }
  2721. catch (IException *e) {
  2722. EXCLOG(e,"~CRemoteClientHandler");
  2723. e->Release();
  2724. }
  2725. }
  2726. bool notifySelected(ISocket *sock,unsigned selected)
  2727. {
  2728. if (TF_TRACE_FULL)
  2729. PROGLOG("notifySelected(%x)",(unsigned)(long)this);
  2730. if (sock!=socket)
  2731. WARNLOG("notifySelected - invalid socket passed");
  2732. size32_t avail = (size32_t)socket->avail_read();
  2733. if (avail)
  2734. touch();
  2735. if (left==0) {
  2736. try {
  2737. left = avail?receiveBufferSize(socket):0;
  2738. }
  2739. catch (IException *e) {
  2740. EXCLOG(e,"notifySelected(1)");
  2741. e->Release();
  2742. left = 0;
  2743. }
  2744. if (left) {
  2745. avail = (size32_t)socket->avail_read();
  2746. try {
  2747. buf.ensureCapacity(left);
  2748. }
  2749. catch (IException *e) {
  2750. EXCLOG(e,"notifySelected(2)");
  2751. e->Release();
  2752. left = 0;
  2753. // if too big then corrupted packet so read avail to try and consume
  2754. char fbuf[1024];
  2755. while (avail) {
  2756. size32_t rd = avail>sizeof(fbuf)?sizeof(fbuf):avail;
  2757. try {
  2758. socket->read(fbuf, rd); // don't need timeout here
  2759. avail -= rd;
  2760. }
  2761. catch (IException *e) {
  2762. EXCLOG(e,"notifySelected(2) flush");
  2763. e->Release();
  2764. break;
  2765. }
  2766. }
  2767. avail = 0;
  2768. left = 0;
  2769. }
  2770. }
  2771. }
  2772. size32_t toread = left>avail?avail:left;
  2773. if (toread) {
  2774. try {
  2775. socket->read(buf.reserve(toread), toread); // don't need timeout here
  2776. }
  2777. catch (IException *e) {
  2778. EXCLOG(e,"notifySelected(3)");
  2779. e->Release();
  2780. toread = left;
  2781. buf.clear();
  2782. }
  2783. }
  2784. if (TF_TRACE_FULL)
  2785. PROGLOG("notifySelected %d,%d",toread,left);
  2786. if ((left!=0)&&(avail==0)) {
  2787. WARNLOG("notifySelected: Closing mid packet, %d remaining", left);
  2788. toread = left;
  2789. buf.clear();
  2790. }
  2791. left -= toread;
  2792. if (left==0) {
  2793. // DEBUG
  2794. parent->notify(this);
  2795. }
  2796. return false;
  2797. }
  2798. void logPrevHandle()
  2799. {
  2800. if (previdx<opennames.ordinality())
  2801. PROGLOG("Previous handle(%d): %s",handles.item(previdx),opennames.item(previdx).text.get());
  2802. }
  2803. void processCommand()
  2804. {
  2805. CThrottler throttler(parent->throttleSem());
  2806. MemoryBuffer reply;
  2807. parent->dispatchCommand(buf, initSendBuffer(reply), this, &throttler);
  2808. buf.clear();
  2809. sendBuffer(socket, reply);
  2810. }
  2811. bool immediateCommand() // returns false if socket closed or failure
  2812. {
  2813. try {
  2814. buf.clear();
  2815. touch();
  2816. size32_t avail = (size32_t)socket->avail_read();
  2817. if (avail==0)
  2818. return false;
  2819. receiveBuffer(socket,buf, 5); // shouldn't timeout as data is available
  2820. touch();
  2821. if (buf.length()==0)
  2822. return false;
  2823. processCommand();
  2824. }
  2825. catch (IException *e) {
  2826. EXCLOG(e,"CRemoteClientHandler::immediateCommand");
  2827. e->Release();
  2828. buf.clear();
  2829. return false;
  2830. }
  2831. return true;
  2832. }
  2833. void process()
  2834. {
  2835. if (selecthandled)
  2836. processCommand(); // buffer already filled
  2837. else {
  2838. while (parent->threadRunningCount()<=TARGET_ACTIVE_THREADS) { // if too many threads add to select handler
  2839. int w = socket->wait_read(1000);
  2840. if (w==0)
  2841. break;
  2842. if ((w<0)||!immediateCommand()) {
  2843. if (w<0)
  2844. WARNLOG("CRemoteClientHandler::main wait_read error");
  2845. parent->onCloseSocket(this,1);
  2846. return;
  2847. }
  2848. }
  2849. selecthandled = true;
  2850. parent->addClient(this); // add to select handler
  2851. }
  2852. }
  2853. bool timedOut()
  2854. {
  2855. return (msTick()-lasttick)>CLIENT_TIMEOUT;
  2856. }
  2857. void touch()
  2858. {
  2859. lasttick = msTick();
  2860. atomic_set(&globallasttick,lasttick);
  2861. }
  2862. bool peerName(StringBuffer &buf)
  2863. {
  2864. if (socket) {
  2865. char name[256];
  2866. name[0] = 0;
  2867. int port = socket->peer_name(name,sizeof(name)-1);
  2868. if (port>=0) {
  2869. buf.append(name);
  2870. if (port)
  2871. buf.append(':').append(port);
  2872. return true;
  2873. }
  2874. }
  2875. return false;
  2876. }
  2877. bool getInfo(StringBuffer &str)
  2878. {
  2879. str.append("client(");
  2880. bool ok = peerName(str);
  2881. unsigned ms = msTick();
  2882. str.appendf("): last touch %d ms ago (%d, %d)",ms-lasttick,lasttick,ms);
  2883. ForEachItemIn(i,handles) {
  2884. str.appendf("\n %d: ",handles.item(i));
  2885. str.append(opennames.item(i).text);
  2886. }
  2887. return ok;
  2888. }
  2889. };
  2890. class cCommandProcessor: public CInterface, implements IPooledThread
  2891. {
  2892. Owned<CRemoteClientHandler> client;
  2893. public:
  2894. IMPLEMENT_IINTERFACE;
  2895. struct cCommandProcessorParams
  2896. {
  2897. CRemoteClientHandler *client;
  2898. };
  2899. void init(void *_params)
  2900. {
  2901. cCommandProcessorParams &params = *(cCommandProcessorParams *)_params;
  2902. client.setown(params.client);
  2903. }
  2904. void main()
  2905. {
  2906. // idea is that initially we process commands inline then pass over to select handler
  2907. try {
  2908. client->process();
  2909. }
  2910. catch (IException *e) {
  2911. // suppress some errors
  2912. EXCLOG(e,"cCommandProcessor::main");
  2913. e->Release();
  2914. }
  2915. try {
  2916. client.clear();
  2917. }
  2918. catch (IException *e) {
  2919. // suppress some more errors clearing client
  2920. EXCLOG(e,"cCommandProcessor::main(2)");
  2921. }
  2922. }
  2923. bool stop()
  2924. {
  2925. return true;
  2926. }
  2927. bool canReuse()
  2928. {
  2929. return false; // want to free owned osocke
  2930. }
  2931. };
  2932. IArrayOf<CRemoteClientHandler> clients;
  2933. class cImpersonateBlock
  2934. {
  2935. CRemoteClientHandler &client;
  2936. public:
  2937. cImpersonateBlock(CRemoteClientHandler &_client)
  2938. : client(_client)
  2939. {
  2940. if (client.user.get()) {
  2941. if (TF_TRACE)
  2942. PROGLOG("Impersonate user: %s",client.user->username());
  2943. client.user->impersonate();
  2944. }
  2945. }
  2946. ~cImpersonateBlock()
  2947. {
  2948. if (client.user.get()) {
  2949. if (TF_TRACE)
  2950. PROGLOG("Stop impersonating user: %s",client.user->username());
  2951. client.user->revert();
  2952. }
  2953. }
  2954. };
  2955. #define IMPERSONATE_USER(client) cImpersonateBlock ublock(client)
  2956. public:
  2957. IMPLEMENT_IINTERFACE
  2958. CRemoteFileServer()
  2959. {
  2960. throttlesem.signal(10);
  2961. lasthandle = 0;
  2962. selecthandler.setown(createSocketSelectHandler(NULL));
  2963. threads.setown(createThreadPool("CRemoteFileServerPool",this,NULL,MAX_THREADS,60*1000,
  2964. #ifdef __64BIT__
  2965. 0,
  2966. #else
  2967. 0x10000,
  2968. #endif
  2969. INFINITE,TARGET_MIN_THREADS));
  2970. stopping = false;
  2971. clientcounttick = msTick();
  2972. closedclients = 0;
  2973. atomic_set(&globallasttick,msTick());
  2974. }
  2975. ~CRemoteFileServer()
  2976. {
  2977. #ifdef _DEBUG
  2978. PROGLOG("Exiting CRemoteFileServer");
  2979. #endif
  2980. asyncCommandManager.join();
  2981. clients.kill();
  2982. #ifdef _DEBUG
  2983. PROGLOG("Exited CRemoteFileServer");
  2984. #endif
  2985. }
  2986. //MORE: The file handles should timeout after a while, and accessing an old (invalid handle)
  2987. // should throw a different exception
  2988. bool checkFileIOHandle(MemoryBuffer &reply, int handle, IFileIO *&fileio, bool del=false)
  2989. {
  2990. CriticalBlock block(sect);
  2991. fileio = NULL;
  2992. if (handle<=0) {
  2993. throwErr(RFSERR_NullFileIOHandle);
  2994. return false;
  2995. }
  2996. unsigned clientidx;
  2997. unsigned handleidx;
  2998. if (findHandle(handle,clientidx,handleidx)) {
  2999. CRemoteClientHandler &client = clients.item(clientidx);
  3000. if (del) {
  3001. client.handles.remove(handleidx);
  3002. client.openfiles.remove(handleidx);
  3003. client.opennames.remove(handleidx);
  3004. client.previdx = (unsigned)-1;
  3005. }
  3006. else {
  3007. fileio = &client.openfiles.item(handleidx);
  3008. client.previdx = handleidx;
  3009. }
  3010. return true;
  3011. }
  3012. throwErr(RFSERR_InvalidFileIOHandle);
  3013. return false;
  3014. }
  3015. void onCloseSocket(CRemoteClientHandler *client, int which)
  3016. {
  3017. if (!client)
  3018. return;
  3019. CriticalBlock block(sect);
  3020. #ifdef _DEBUG
  3021. StringBuffer s;
  3022. client->peerName(s);
  3023. PROGLOG("onCloseSocket(%d) %s",which,s.str());
  3024. #endif
  3025. if (client->socket) {
  3026. try {
  3027. selecthandler->remove(client->socket);
  3028. }
  3029. catch (IException *e) {
  3030. EXCLOG(e,"CRemoteFileServer::onCloseSocket.1");
  3031. e->Release();
  3032. }
  3033. }
  3034. try {
  3035. clients.zap(*client);
  3036. }
  3037. catch (IException *e) {
  3038. EXCLOG(e,"CRemoteFileServer::onCloseSocket.2");
  3039. e->Release();
  3040. }
  3041. }
  3042. bool cmdOpenFileIO(MemoryBuffer & msg, MemoryBuffer & reply, CRemoteClientHandler &client)
  3043. {
  3044. IMPERSONATE_USER(client);
  3045. Owned<StringAttrItem> name = new StringAttrItem;
  3046. byte mode;
  3047. byte share;
  3048. msg.read(name->text).read(mode).read(share);
  3049. try {
  3050. Owned<IFile> file = createIFile(name->text);
  3051. switch ((compatIFSHmode)share) {
  3052. case compatIFSHnone:
  3053. file->setCreateFlags(S_IRUSR|S_IWUSR);
  3054. file->setShareMode(IFSHnone);
  3055. break;
  3056. case compatIFSHread:
  3057. file->setShareMode(IFSHread);
  3058. break;
  3059. case compatIFSHwrite:
  3060. file->setShareMode(IFSHfull);
  3061. break;
  3062. case compatIFSHexec:
  3063. file->setCreateFlags(S_IRUSR|S_IWUSR|S_IXUSR|S_IRGRP|S_IXGRP|S_IROTH|S_IXOTH);
  3064. break;
  3065. case compatIFSHall:
  3066. file->setCreateFlags(S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH|S_IWOTH); // bit excessive
  3067. file->setShareMode(IFSHfull);
  3068. break;
  3069. }
  3070. if (TF_TRACE_PRE_IO)
  3071. PROGLOG("before open file '%s', (%d,%d)",name->text.get(),(int)mode,(int)share);
  3072. IFileIO *fileio = file->open((IFOmode)mode);
  3073. int handle;
  3074. if (fileio) {
  3075. CriticalBlock block(sect);
  3076. handle = getNextHandle();
  3077. client.previdx = client.opennames.ordinality();
  3078. client.handles.append(handle);
  3079. client.openfiles.append(*fileio);
  3080. client.opennames.append(*name.getLink());
  3081. }
  3082. else
  3083. handle = 0;
  3084. reply.append(RFEnoerror);
  3085. reply.append(handle);
  3086. if (TF_TRACE)
  3087. PROGLOG("open file '%s', (%d,%d) handle = %d",name->text.get(),(int)mode,(int)share,handle);
  3088. return true;
  3089. }
  3090. catch (IException *e)
  3091. {
  3092. StringBuffer s;
  3093. e->errorMessage(s);
  3094. throwErr3(RFSERR_OpenFailed,e->errorCode(),s.str());
  3095. e->Release();
  3096. }
  3097. return false;
  3098. }
  3099. bool cmdCloseFileIO(MemoryBuffer & msg, MemoryBuffer & reply)
  3100. {
  3101. int handle;
  3102. msg.read(handle);
  3103. IFileIO *fileio;
  3104. if (!checkFileIOHandle(reply, handle, fileio, true))
  3105. return false;
  3106. if (TF_TRACE)
  3107. PROGLOG("close file, handle = %d",handle);
  3108. reply.append(RFEnoerror);
  3109. return true;
  3110. }
  3111. bool cmdRead(MemoryBuffer & msg, MemoryBuffer & reply)
  3112. {
  3113. int handle;
  3114. __int64 pos;
  3115. size32_t len;
  3116. msg.read(handle).read(pos).read(len);
  3117. IFileIO *fileio;
  3118. if (!checkFileIOHandle(reply, handle, fileio))
  3119. return false;
  3120. //arrange it so we read directly into the reply buffer...
  3121. unsigned posOfErr = reply.length();
  3122. reply.append((unsigned)RFEnoerror);
  3123. size32_t numRead;
  3124. unsigned posOfLength = reply.length();
  3125. if (TF_TRACE_PRE_IO)
  3126. PROGLOG("before read file, handle = %d, toread = %d",handle,len);
  3127. void * data;
  3128. {
  3129. reply.reserve(sizeof(numRead));
  3130. data = reply.reserve(len);
  3131. }
  3132. try {
  3133. numRead = fileio->read(pos,len,data);
  3134. }
  3135. catch (IException *e)
  3136. {
  3137. reply.setWritePos(posOfErr);
  3138. StringBuffer s;
  3139. e->errorMessage(s);
  3140. throwErr3(RFSERR_ReadFailed,e->errorCode(),s.str());
  3141. e->Release();
  3142. return false;
  3143. }
  3144. if (TF_TRACE)
  3145. PROGLOG("read file, handle = %d, pos = %"I64F"d, toread = %d, read = %d",handle,pos,len,numRead);
  3146. {
  3147. reply.setLength(posOfLength + sizeof(numRead) + numRead);
  3148. reply.writeEndianDirect(posOfLength,sizeof(numRead),&numRead);
  3149. }
  3150. return true;
  3151. }
  3152. bool cmdSize(MemoryBuffer & msg, MemoryBuffer & reply)
  3153. {
  3154. int handle;
  3155. msg.read(handle);
  3156. IFileIO *fileio;
  3157. if (!checkFileIOHandle(reply, handle, fileio))
  3158. return false;
  3159. __int64 size = fileio->size();
  3160. reply.append((unsigned)RFEnoerror).append(size);
  3161. if (TF_TRACE)
  3162. PROGLOG("size file, handle = %d, size = %"I64F"d",handle,size);
  3163. return true;
  3164. }
  3165. bool cmdSetSize(MemoryBuffer & msg, MemoryBuffer & reply)
  3166. {
  3167. int handle;
  3168. offset_t size;
  3169. msg.read(handle).read(size);
  3170. IFileIO *fileio;
  3171. if (TF_TRACE)
  3172. PROGLOG("set size file, handle = %d, size = %"I64F"d",handle,size);
  3173. if (!checkFileIOHandle(reply, handle, fileio))
  3174. return false;
  3175. fileio->setSize(size);
  3176. reply.append((unsigned)RFEnoerror);
  3177. return true;
  3178. }
  3179. bool cmdWrite(MemoryBuffer & msg, MemoryBuffer & reply)
  3180. {
  3181. int handle;
  3182. __int64 pos;
  3183. size32_t len;
  3184. msg.read(handle).read(pos).read(len);
  3185. IFileIO *fileio;
  3186. if (!checkFileIOHandle(reply, handle, fileio))
  3187. return false;
  3188. const byte *data = (const byte *)msg.readDirect(len);
  3189. try {
  3190. if (TF_TRACE_PRE_IO)
  3191. PROGLOG("before write file, handle = %d, towrite = %d",handle,len);
  3192. size32_t numWritten = fileio->write(pos,len,data);
  3193. if (TF_TRACE)
  3194. PROGLOG("write file, handle = %d, towrite = %d, written = %d",handle,len,numWritten);
  3195. reply.append((unsigned)RFEnoerror).append(numWritten);
  3196. return true;
  3197. }
  3198. catch (IException *e)
  3199. {
  3200. StringBuffer s;
  3201. e->errorMessage(s);
  3202. throwErr3(RFSERR_WriteFailed,e->errorCode(),s.str());
  3203. e->Release();
  3204. }
  3205. return false;
  3206. }
  3207. bool cmdExists(MemoryBuffer & msg, MemoryBuffer & reply, CRemoteClientHandler &client)
  3208. {
  3209. IMPERSONATE_USER(client);
  3210. StringAttr name;
  3211. msg.read(name);
  3212. if (TF_TRACE)
  3213. PROGLOG("exists, '%s'",name.get());
  3214. Owned<IFile> file=createIFile(name);
  3215. try {
  3216. bool e = file->exists();
  3217. reply.append((unsigned)RFEnoerror).append(e);
  3218. return true;
  3219. }
  3220. catch (IException *e)
  3221. {
  3222. StringBuffer s;
  3223. e->errorMessage(s);
  3224. throwErr3(RFSERR_ExistsFailed,e->errorCode(),s.str());
  3225. e->Release();
  3226. }
  3227. return false;
  3228. }
  3229. bool cmdRemove(MemoryBuffer & msg, MemoryBuffer & reply,CRemoteClientHandler &client)
  3230. {
  3231. IMPERSONATE_USER(client);
  3232. StringAttr name;
  3233. msg.read(name);
  3234. if (TF_TRACE)
  3235. PROGLOG("remove, '%s'",name.get());
  3236. Owned<IFile> file=createIFile(name);
  3237. try {
  3238. bool e = file->remove();
  3239. reply.append((unsigned)RFEnoerror).append(e);
  3240. return true;
  3241. }
  3242. catch (IException *e)
  3243. {
  3244. StringBuffer s;
  3245. e->errorMessage(s);
  3246. throwErr3(RFSERR_RemoveFailed,e->errorCode(),s.str());
  3247. e->Release();
  3248. }
  3249. return false;
  3250. }
  3251. bool cmdGetVer(MemoryBuffer & msg, MemoryBuffer & reply)
  3252. {
  3253. if (TF_TRACE)
  3254. PROGLOG("getVer");
  3255. if (msg.getPos()+sizeof(unsigned)>msg.length())
  3256. reply.append((unsigned)RFEnoerror);
  3257. else
  3258. reply.append((unsigned)FILESRV_VERSION+0x10000);
  3259. reply.append(VERSTRING);
  3260. return true;
  3261. }
  3262. bool cmdRename(MemoryBuffer & msg, MemoryBuffer & reply,CRemoteClientHandler &client)
  3263. {
  3264. IMPERSONATE_USER(client);
  3265. StringAttr fromname;
  3266. msg.read(fromname);
  3267. StringAttr toname;
  3268. msg.read(toname);
  3269. if (TF_TRACE)
  3270. PROGLOG("rename, '%s' to '%s'",fromname.get(),toname.get());
  3271. Owned<IFile> file=createIFile(fromname);
  3272. try {
  3273. file->rename(toname);
  3274. reply.append((unsigned)RFEnoerror);
  3275. return true;
  3276. }
  3277. catch (IException *e)
  3278. {
  3279. StringBuffer s;
  3280. e->errorMessage(s);
  3281. throwErr3(RFSERR_RenameFailed,e->errorCode(),s.str());
  3282. e->Release();
  3283. }
  3284. return false;
  3285. }
  3286. bool cmdMove(MemoryBuffer & msg, MemoryBuffer & reply,CRemoteClientHandler &client)
  3287. {
  3288. IMPERSONATE_USER(client);
  3289. StringAttr fromname;
  3290. msg.read(fromname);
  3291. StringAttr toname;
  3292. msg.read(toname);
  3293. if (TF_TRACE)
  3294. PROGLOG("move, '%s' to '%s'",fromname.get(),toname.get());
  3295. Owned<IFile> file=createIFile(fromname);
  3296. try {
  3297. file->move(toname);
  3298. reply.append((unsigned)RFEnoerror);
  3299. return true;
  3300. }
  3301. catch (IException *e)
  3302. {
  3303. StringBuffer s;
  3304. e->errorMessage(s);
  3305. throwErr3(RFSERR_MoveFailed,e->errorCode(),s.str());
  3306. e->Release();
  3307. }
  3308. return false;
  3309. }
  3310. bool cmdCopy(MemoryBuffer & msg, MemoryBuffer & reply, CRemoteClientHandler &client)
  3311. {
  3312. IMPERSONATE_USER(client);
  3313. StringAttr fromname;
  3314. msg.read(fromname);
  3315. StringAttr toname;
  3316. msg.read(toname);
  3317. if (TF_TRACE)
  3318. PROGLOG("copy, '%s' to '%s'",fromname.get(),toname.get());
  3319. try {
  3320. copyFile(toname, fromname);
  3321. reply.append((unsigned)RFEnoerror);
  3322. return true;
  3323. }
  3324. catch (IException *e)
  3325. {
  3326. StringBuffer s;
  3327. e->errorMessage(s);
  3328. throwErr3(RFSERR_CopyFailed,e->errorCode(),s.str());
  3329. e->Release();
  3330. }
  3331. return false;
  3332. }
  3333. bool cmdAppend(MemoryBuffer & msg, MemoryBuffer & reply, CRemoteClientHandler &client)
  3334. {
  3335. IMPERSONATE_USER(client);
  3336. int handle;
  3337. __int64 pos;
  3338. __int64 len;
  3339. StringAttr srcname;
  3340. msg.read(handle).read(srcname).read(pos).read(len);
  3341. IFileIO *fileio;
  3342. if (!checkFileIOHandle(reply, handle, fileio))
  3343. return false;
  3344. try {
  3345. Owned<IFile> file = createIFile(srcname.get());
  3346. __int64 written = fileio->appendFile(file,pos,len);
  3347. if (TF_TRACE)
  3348. PROGLOG("append file, handle = %d, file=%s, pos = %"I64F"d len = %"I64F"d written = %"I64F"d",handle,srcname.get(),pos,len,written);
  3349. reply.append((unsigned)RFEnoerror).append(written);
  3350. return true;
  3351. }
  3352. catch (IException *e)
  3353. {
  3354. StringBuffer s;
  3355. e->errorMessage(s);
  3356. throwErr3(RFSERR_AppendFailed,e->errorCode(),s.str());
  3357. e->Release();
  3358. }
  3359. return false;
  3360. }
  3361. bool cmdIsFile(MemoryBuffer &msg, MemoryBuffer &reply, CRemoteClientHandler &client)
  3362. {
  3363. IMPERSONATE_USER(client);
  3364. StringAttr name;
  3365. msg.read(name);
  3366. if (TF_TRACE)
  3367. PROGLOG("isFile, '%s'",name.get());
  3368. Owned<IFile> file=createIFile(name);
  3369. try {
  3370. unsigned ret = (unsigned)file->isFile();
  3371. reply.append((unsigned)RFEnoerror).append(ret);
  3372. return true;
  3373. }
  3374. catch (IException *e)
  3375. {
  3376. StringBuffer s;
  3377. e->errorMessage(s);
  3378. throwErr3(RFSERR_IsFileFailed,e->errorCode(),s.str());
  3379. e->Release();
  3380. }
  3381. return false;
  3382. }
  3383. bool cmdIsDir(MemoryBuffer &msg, MemoryBuffer &reply, CRemoteClientHandler &client)
  3384. {
  3385. IMPERSONATE_USER(client);
  3386. StringAttr name;
  3387. msg.read(name);
  3388. if (TF_TRACE)
  3389. PROGLOG("isDir, '%s'",name.get());
  3390. Owned<IFile> file=createIFile(name);
  3391. try {
  3392. unsigned ret = (unsigned)file->isDirectory();
  3393. reply.append((unsigned)RFEnoerror).append(ret);
  3394. return true;
  3395. }
  3396. catch (IException *e)
  3397. {
  3398. StringBuffer s;
  3399. e->errorMessage(s);
  3400. throwErr3(RFSERR_IsDirectoryFailed,e->errorCode(),s.str());
  3401. e->Release();
  3402. }
  3403. return false;
  3404. }
  3405. bool cmdIsReadOnly(MemoryBuffer &msg, MemoryBuffer &reply, CRemoteClientHandler &client)
  3406. {
  3407. IMPERSONATE_USER(client);
  3408. StringAttr name;
  3409. msg.read(name);
  3410. if (TF_TRACE)
  3411. PROGLOG("isReadOnly, '%s'",name.get());
  3412. Owned<IFile> file=createIFile(name);
  3413. try {
  3414. unsigned ret = (unsigned)file->isReadOnly();
  3415. reply.append((unsigned)RFEnoerror).append(ret);
  3416. return true;
  3417. }
  3418. catch (IException *e)
  3419. {
  3420. StringBuffer s;
  3421. e->errorMessage(s);
  3422. throwErr3(RFSERR_IsReadOnlyFailed,e->errorCode(),s.str());
  3423. e->Release();
  3424. }
  3425. return false;
  3426. }
  3427. bool cmdSetReadOnly(MemoryBuffer &msg, MemoryBuffer &reply, CRemoteClientHandler &client)
  3428. {
  3429. IMPERSONATE_USER(client);
  3430. StringAttr name;
  3431. bool set;
  3432. msg.read(name).read(set);
  3433. if (TF_TRACE)
  3434. PROGLOG("setReadOnly, '%s' %d",name.get(),(int)set);
  3435. Owned<IFile> file=createIFile(name);
  3436. try {
  3437. file->setReadOnly(set);
  3438. reply.append((unsigned)RFEnoerror);
  3439. return true;
  3440. }
  3441. catch (IException *e)
  3442. {
  3443. StringBuffer s;
  3444. e->errorMessage(s);
  3445. throwErr3(RFSERR_SetReadOnlyFailed,e->errorCode(),s.str());
  3446. e->Release();
  3447. }
  3448. return false;
  3449. }
  3450. bool cmdGetTime(MemoryBuffer &msg, MemoryBuffer &reply, CRemoteClientHandler &client)
  3451. {
  3452. IMPERSONATE_USER(client);
  3453. StringAttr name;
  3454. msg.read(name);
  3455. if (TF_TRACE)
  3456. PROGLOG("getTime, '%s'",name.get());
  3457. Owned<IFile> file=createIFile(name);
  3458. CDateTime createTime;
  3459. CDateTime modifiedTime;
  3460. CDateTime accessedTime;
  3461. try {
  3462. bool ret = file->getTime(&createTime,&modifiedTime,&accessedTime);
  3463. reply.append((unsigned)RFEnoerror).append(ret);
  3464. if (ret) {
  3465. createTime.serialize(reply);
  3466. modifiedTime.serialize(reply);
  3467. accessedTime.serialize(reply);
  3468. }
  3469. return true;
  3470. }
  3471. catch (IException *e)
  3472. {
  3473. StringBuffer s;
  3474. e->errorMessage(s);
  3475. throwErr3(RFSERR_GetTimeFailed,e->errorCode(),s.str());
  3476. e->Release();
  3477. }
  3478. return false;
  3479. }
  3480. bool cmdSetTime(MemoryBuffer &msg, MemoryBuffer &reply, CRemoteClientHandler &client)
  3481. {
  3482. IMPERSONATE_USER(client);
  3483. StringAttr name;
  3484. bool creategot;
  3485. CDateTime createTime;
  3486. bool modifiedgot;
  3487. CDateTime modifiedTime;
  3488. bool accessedgot;
  3489. CDateTime accessedTime;
  3490. msg.read(name);
  3491. msg.read(creategot);
  3492. if (creategot)
  3493. createTime.deserialize(msg);
  3494. msg.read(modifiedgot);
  3495. if (modifiedgot)
  3496. modifiedTime.deserialize(msg);
  3497. msg.read(accessedgot);
  3498. if (accessedgot)
  3499. accessedTime.deserialize(msg);
  3500. if (TF_TRACE)
  3501. PROGLOG("setTime, '%s'",name.get());
  3502. Owned<IFile> file=createIFile(name);
  3503. try {
  3504. bool ret = file->setTime(creategot?&createTime:NULL,modifiedgot?&modifiedTime:NULL,accessedgot?&accessedTime:NULL);
  3505. reply.append((unsigned)RFEnoerror).append(ret);
  3506. return true;
  3507. }
  3508. catch (IException *e)
  3509. {
  3510. StringBuffer s;
  3511. e->errorMessage(s);
  3512. throwErr3(RFSERR_SetTimeFailed,e->errorCode(),s.str());
  3513. e->Release();
  3514. }
  3515. return false;
  3516. }
  3517. bool cmdCreateDir(MemoryBuffer &msg, MemoryBuffer &reply, CRemoteClientHandler &client)
  3518. {
  3519. IMPERSONATE_USER(client);
  3520. StringAttr name;
  3521. msg.read(name);
  3522. if (TF_TRACE)
  3523. PROGLOG("CreateDir, '%s'",name.get());
  3524. Owned<IFile> dir=createIFile(name);
  3525. try {
  3526. bool ret = dir->createDirectory();
  3527. reply.append((unsigned)RFEnoerror).append(ret);
  3528. return true;
  3529. }
  3530. catch (IException *e)
  3531. {
  3532. StringBuffer s;
  3533. e->errorMessage(s);
  3534. throwErr3(RFSERR_CreateDirFailed,e->errorCode(),s.str());
  3535. e->Release();
  3536. }
  3537. return false;
  3538. }
  3539. bool cmdGetDir(MemoryBuffer &msg, MemoryBuffer &reply, CRemoteClientHandler &client)
  3540. {
  3541. IMPERSONATE_USER(client);
  3542. StringAttr name;
  3543. StringAttr mask;
  3544. bool includedir;
  3545. bool sub;
  3546. byte stream = 0;
  3547. msg.read(name).read(mask).read(includedir).read(sub);
  3548. if (msg.remaining()>=sizeof(byte)) {
  3549. msg.read(stream);
  3550. if (stream==1)
  3551. client.opendir.clear();
  3552. }
  3553. if (TF_TRACE)
  3554. PROGLOG("GetDir, '%s', '%s'",name.get(),mask.get());
  3555. try {
  3556. Owned<IFile> dir=createIFile(name);
  3557. Owned<IDirectoryIterator> iter;
  3558. if (stream>1)
  3559. iter.set(client.opendir);
  3560. else {
  3561. iter.setown(dir->directoryFiles(mask.length()?mask.get():NULL,sub,includedir));
  3562. if (stream != 0)
  3563. client.opendir.set(iter);
  3564. }
  3565. if (!iter) {
  3566. reply.append((unsigned)RFSERR_GetDirFailed);
  3567. return false;
  3568. }
  3569. reply.append((unsigned)RFEnoerror);
  3570. if (CRemoteDirectoryIterator::serialize(reply,iter,stream?0x100000:0,stream<2)) {
  3571. if (stream != 0)
  3572. client.opendir.clear();
  3573. }
  3574. else {
  3575. bool cont=true;
  3576. reply.append(cont);
  3577. }
  3578. return true;
  3579. }
  3580. catch (IException *e)
  3581. {
  3582. StringBuffer s;
  3583. e->errorMessage(s);
  3584. throwErr3(RFSERR_GetDirFailed,e->errorCode(),s.str());
  3585. e->Release();
  3586. }
  3587. return false;
  3588. }
  3589. bool cmdMonitorDir(MemoryBuffer &msg, MemoryBuffer &reply, CRemoteClientHandler &client)
  3590. {
  3591. IMPERSONATE_USER(client);
  3592. StringAttr name;
  3593. StringAttr mask;
  3594. bool includedir;
  3595. bool sub;
  3596. unsigned checkinterval;
  3597. unsigned timeout;
  3598. __int64 cancelid; // not yet used
  3599. msg.read(name).read(mask).read(includedir).read(sub).read(checkinterval).read(timeout).read(cancelid);
  3600. byte isprev;
  3601. msg.read(isprev);
  3602. Owned<IDirectoryIterator> prev;
  3603. if (isprev==1) {
  3604. SocketEndpoint ep;
  3605. CRemoteDirectoryIterator *di = new CRemoteDirectoryIterator(ep,name);
  3606. di->appendBuf(msg);
  3607. prev.setown(di);
  3608. }
  3609. if (TF_TRACE)
  3610. PROGLOG("MonitorDir, '%s' '%s'",name.get(),mask.get());
  3611. try {
  3612. Owned<IFile> dir=createIFile(name);
  3613. Owned<IDirectoryDifferenceIterator> iter=dir->monitorDirectory(prev,mask.length()?mask.get():NULL,sub,includedir,checkinterval,timeout);
  3614. reply.append((unsigned)RFEnoerror);
  3615. byte state = (iter.get()==NULL)?0:1;
  3616. reply.append(state);
  3617. if (state==1)
  3618. CRemoteDirectoryIterator::serializeDiff(reply,iter);
  3619. return true;
  3620. }
  3621. catch (IException *e)
  3622. {
  3623. StringBuffer s;
  3624. e->errorMessage(s);
  3625. throwErr3(RFSERR_GetDirFailed,e->errorCode(),s.str());
  3626. e->Release();
  3627. }
  3628. return false;
  3629. }
  3630. bool cmdCopySection(MemoryBuffer &msg, MemoryBuffer &reply, CRemoteClientHandler &client)
  3631. {
  3632. IMPERSONATE_USER(client);
  3633. StringAttr uuid;
  3634. StringAttr fromFile;
  3635. StringAttr toFile;
  3636. offset_t toOfs;
  3637. offset_t fromOfs;
  3638. offset_t size;
  3639. offset_t sizeDone=0;
  3640. offset_t totalSize=(offset_t)-1;
  3641. unsigned timeout;
  3642. msg.read(uuid).read(fromFile).read(toFile).read(toOfs).read(fromOfs).read(size).read(timeout);
  3643. try {
  3644. AsyncCommandStatus status = asyncCommandManager.copySection(uuid,fromFile,toFile,toOfs,fromOfs,size,sizeDone,totalSize,timeout);
  3645. reply.append((unsigned)RFEnoerror).append((unsigned)status).append(sizeDone).append(totalSize);
  3646. }
  3647. catch (IException *e)
  3648. {
  3649. StringBuffer s;
  3650. e->errorMessage(s);
  3651. throwErr3(RFSERR_CopySectionFailed,e->errorCode(),s.str());
  3652. e->Release();
  3653. }
  3654. return true;
  3655. }
  3656. bool cmdTreeCopy(MemoryBuffer &msg, MemoryBuffer &reply, CRemoteClientHandler &client, CThrottler *throttler, bool usetmp=false)
  3657. {
  3658. IMPERSONATE_USER(client);
  3659. RemoteFilename src;
  3660. src.deserialize(msg);
  3661. RemoteFilename dst;
  3662. dst.deserialize(msg);
  3663. StringAttr net;
  3664. StringAttr mask;
  3665. msg.read(net).read(mask);
  3666. try {
  3667. IpAddress ip;
  3668. treeCopyFile(src,dst,net,mask,ip,usetmp,throttler);
  3669. unsigned status = 0;
  3670. reply.append((unsigned)RFEnoerror).append((unsigned)status);
  3671. ip.ipserialize(reply);
  3672. }
  3673. catch (IException *e)
  3674. {
  3675. StringBuffer s;
  3676. e->errorMessage(s);
  3677. throwErr3(RFSERR_TreeCopyFailed,e->errorCode(),s.str());
  3678. e->Release();
  3679. }
  3680. return true;
  3681. }
  3682. bool cmdTreeCopyTmp(MemoryBuffer &msg, MemoryBuffer &reply, CRemoteClientHandler &client, CThrottler *throttler)
  3683. {
  3684. return cmdTreeCopy(msg, reply, client, throttler, true);
  3685. }
  3686. bool cmdGetCRC(MemoryBuffer &msg, MemoryBuffer &reply, CRemoteClientHandler &client)
  3687. {
  3688. IMPERSONATE_USER(client);
  3689. StringAttr name;
  3690. msg.read(name);
  3691. if (TF_TRACE)
  3692. PROGLOG("getCRC, '%s'",name.get());
  3693. Owned<IFile> file=createIFile(name);
  3694. try {
  3695. unsigned ret = file->getCRC();
  3696. reply.append((unsigned)RFEnoerror).append(ret);
  3697. return true;
  3698. }
  3699. catch (IException *e)
  3700. {
  3701. StringBuffer s;
  3702. e->errorMessage(s);
  3703. throwErr3(RFSERR_GetCrcFailed,e->errorCode(),s.str());
  3704. e->Release();
  3705. }
  3706. return false;
  3707. }
  3708. bool cmdStop(MemoryBuffer &msg, MemoryBuffer &reply)
  3709. {
  3710. PROGLOG("Abort request received");
  3711. stopping = true;
  3712. if (acceptsock)
  3713. acceptsock->cancel_accept();
  3714. reply.append((unsigned)RFEnoerror);
  3715. return false;
  3716. }
  3717. bool cmdExec(MemoryBuffer &msg, MemoryBuffer &reply, CRemoteClientHandler &client)
  3718. {
  3719. StringAttr cmdline;
  3720. StringAttr workdir;
  3721. bool sync;
  3722. bool hasoutput;
  3723. size32_t insize;
  3724. MemoryAttr inbuf;
  3725. msg.read(cmdline).read(workdir).read(sync).read(hasoutput).read(insize);
  3726. if (insize)
  3727. msg.read(insize, inbuf.allocate(insize));
  3728. Owned<IPipeProcess> pipe = createPipeProcess();
  3729. int retcode=-1;
  3730. HANDLE phandle=(HANDLE)0;
  3731. MemoryBuffer outbuf;
  3732. if (pipe->run("EXEC",cmdline,workdir,insize!=0,hasoutput)) {
  3733. if (insize) {
  3734. pipe->write(insize, inbuf.get());
  3735. pipe->closeInput();
  3736. }
  3737. if (hasoutput) {
  3738. byte buf[4096];
  3739. loop {
  3740. size32_t read = pipe->read(sizeof(buf),buf);
  3741. if (!read)
  3742. break;
  3743. outbuf.append(read,buf);
  3744. }
  3745. }
  3746. if (sync)
  3747. retcode = pipe->wait();
  3748. else {
  3749. phandle = pipe->getProcessHandle();
  3750. retcode = 0;
  3751. }
  3752. }
  3753. size32_t outsz = outbuf.length();
  3754. reply.append(retcode).append((unsigned)phandle).append(outsz);
  3755. if (outsz)
  3756. reply.append(outbuf);
  3757. return true;
  3758. }
  3759. bool cmdSetTrace(MemoryBuffer &msg, MemoryBuffer &reply)
  3760. {
  3761. byte flags;
  3762. msg.read(flags);
  3763. int retcode=-1;
  3764. if (flags!=255) { // escape
  3765. retcode = traceFlags;
  3766. traceFlags = flags;
  3767. }
  3768. reply.append(retcode);
  3769. return true;
  3770. }
  3771. bool cmdGetInfo(MemoryBuffer &msg, MemoryBuffer &reply)
  3772. {
  3773. StringBuffer retstr;
  3774. int retcode = getInfo(retstr);
  3775. reply.append(retcode).append(retstr.str());
  3776. return true;
  3777. }
  3778. bool cmdFirewall(MemoryBuffer &msg, MemoryBuffer &reply)
  3779. {
  3780. // TBD
  3781. StringBuffer retstr;
  3782. int retcode = getInfo(retstr);
  3783. reply.append(retcode).append(retstr.str());
  3784. return true;
  3785. }
  3786. bool cmdExtractBlobElements(MemoryBuffer &msg, MemoryBuffer &reply, CRemoteClientHandler &client)
  3787. {
  3788. IMPERSONATE_USER(client);
  3789. try {
  3790. StringAttr prefix;
  3791. StringAttr filename;
  3792. msg.read(prefix).read(filename);
  3793. RemoteFilename rfn;
  3794. rfn.setLocalPath(filename);
  3795. ExtractedBlobArray extracted;
  3796. extractBlobElements(prefix, rfn, extracted);
  3797. unsigned n = extracted.ordinality();
  3798. reply.append((unsigned)RFEnoerror).append(n);
  3799. for (unsigned i=0;i<n;i++)
  3800. extracted.item(i).serialize(reply);
  3801. }
  3802. catch (IException *e) {
  3803. StringBuffer s;
  3804. e->errorMessage(s);
  3805. throwErr3(RFSERR_ExtractBlobElementsFailed,e->errorCode(),s.str());
  3806. e->Release();
  3807. }
  3808. return true;
  3809. }
  3810. bool cmdRedeploy(MemoryBuffer &msg, MemoryBuffer &reply)
  3811. {
  3812. return false; // TBD
  3813. }
  3814. bool cmdKill(MemoryBuffer & msg, MemoryBuffer & reply)
  3815. {
  3816. // TBD
  3817. throwErr2(RFSERR_InvalidCommand,(unsigned)RFCkill);
  3818. return false;
  3819. }
  3820. bool cmdUnknown(MemoryBuffer & msg, MemoryBuffer & reply,RemoteFileCommandType cmd)
  3821. {
  3822. throwErr2(RFSERR_InvalidCommand,(unsigned)cmd);
  3823. return false;
  3824. }
  3825. bool cmdUnlock(MemoryBuffer & msg, MemoryBuffer & reply,CRemoteClientHandler &client)
  3826. {
  3827. // this is an attempt to authenticate when we haven't got authentication turned on
  3828. StringBuffer s;
  3829. client.peerName(s);
  3830. if (TF_TRACE_CLIENT_STATS)
  3831. PROGLOG("Connect from %s",s.str());
  3832. throwErr2(RFSERR_InvalidCommand,(unsigned)RFCunlock);
  3833. return false;
  3834. }
  3835. bool dispatchCommand(MemoryBuffer & msg, MemoryBuffer & reply, CRemoteClientHandler *client, CThrottler *throttler)
  3836. {
  3837. RemoteFileCommandType cmd;
  3838. msg.read(cmd);
  3839. bool ret = true;
  3840. switch(cmd) {
  3841. MAPCOMMAND(RFCcloseIO, cmdCloseFileIO);
  3842. MAPCOMMANDCLIENT(RFCopenIO, cmdOpenFileIO, *client);
  3843. MAPCOMMAND(RFCread, cmdRead);
  3844. MAPCOMMAND(RFCsize, cmdSize);
  3845. MAPCOMMAND(RFCwrite, cmdWrite);
  3846. MAPCOMMANDCLIENT(RFCexists, cmdExists, *client);
  3847. MAPCOMMANDCLIENT(RFCremove, cmdRemove, *client);
  3848. MAPCOMMANDCLIENT(RFCrename, cmdRename, *client);
  3849. MAPCOMMAND(RFCgetver, cmdGetVer);
  3850. MAPCOMMANDCLIENT(RFCisfile, cmdIsFile, *client);
  3851. MAPCOMMANDCLIENT(RFCisdirectory, cmdIsDir, *client);
  3852. MAPCOMMANDCLIENT(RFCisreadonly, cmdIsReadOnly, *client);
  3853. MAPCOMMANDCLIENT(RFCsetreadonly, cmdSetReadOnly, *client);
  3854. MAPCOMMANDCLIENT(RFCgettime, cmdGetTime, *client);
  3855. MAPCOMMANDCLIENT(RFCsettime, cmdSetTime, *client);
  3856. MAPCOMMANDCLIENT(RFCcreatedir, cmdCreateDir, *client);
  3857. MAPCOMMANDCLIENT(RFCgetdir, cmdGetDir, *client);
  3858. MAPCOMMANDCLIENT(RFCmonitordir, cmdMonitorDir, *client);
  3859. MAPCOMMAND(RFCstop, cmdStop);
  3860. MAPCOMMANDCLIENT(RFCexec, cmdExec, *client);
  3861. MAPCOMMANDCLIENT(RFCextractblobelements, cmdExtractBlobElements, *client);
  3862. MAPCOMMAND(RFCkill, cmdKill);
  3863. MAPCOMMAND(RFCredeploy, cmdRedeploy); // only Windows
  3864. MAPCOMMANDCLIENT(RFCgetcrc, cmdGetCRC, *client);
  3865. MAPCOMMANDCLIENT(RFCmove, cmdMove, *client);
  3866. MAPCOMMANDCLIENT(RFCcopy, cmdCopy, *client);
  3867. MAPCOMMANDCLIENT(RFCappend, cmdAppend, *client);
  3868. MAPCOMMAND(RFCsetsize, cmdSetSize);
  3869. MAPCOMMAND(RFCsettrace, cmdSetTrace);
  3870. MAPCOMMAND(RFCgetinfo, cmdGetInfo);
  3871. MAPCOMMAND(RFCfirewall, cmdFirewall);
  3872. MAPCOMMANDCLIENT(RFCunlock, cmdUnlock, *client);
  3873. MAPCOMMANDCLIENT(RFCcopysection, cmdCopySection, *client);
  3874. MAPCOMMANDCLIENTTHROTTLER(RFCtreecopy, cmdTreeCopy, *client, throttler);
  3875. MAPCOMMANDCLIENTTHROTTLER(RFCtreecopytmp, cmdTreeCopyTmp, *client, throttler);
  3876. default:
  3877. ret = cmdUnknown(msg,reply,cmd);
  3878. }
  3879. if (!ret) { // append error string
  3880. if (reply.length()>=sizeof(unsigned)*2) {
  3881. reply.reset();
  3882. unsigned z;
  3883. unsigned e;
  3884. reply.read(z).read(e);
  3885. StringBuffer err("ERR(");
  3886. err.append(e).append(") ");
  3887. if (client&&(client->peerName(err)))
  3888. err.append(" : ");
  3889. if (e&&(reply.getPos()<reply.length())) {
  3890. StringAttr es;
  3891. reply.read(es);
  3892. err.append(" : ").append(es);
  3893. }
  3894. reply.reset();
  3895. if (cmd!=RFCunlock)
  3896. PROGLOG("%s",err.str()); // supress authentication logging
  3897. if (client)
  3898. client->logPrevHandle();
  3899. }
  3900. }
  3901. return ret;
  3902. }
  3903. virtual IPooledThread *createNew()
  3904. {
  3905. return new cCommandProcessor();
  3906. }
  3907. void run(SocketEndpoint &listenep)
  3908. {
  3909. if (listenep.isNull())
  3910. acceptsock.setown(ISocket::create(listenep.port));
  3911. else {
  3912. StringBuffer ips;
  3913. listenep.getIpText(ips);
  3914. acceptsock.setown(ISocket::create_ip(listenep.port,ips.str()));
  3915. }
  3916. selecthandler->start();
  3917. loop {
  3918. Owned<ISocket> sock;
  3919. bool sockavail;
  3920. try {
  3921. sockavail = acceptsock->wait_read(1000*60*1)!=0;
  3922. #if 0
  3923. if (!sockavail) {
  3924. JSocketStatistics stats;
  3925. getSocketStatistics(stats);
  3926. StringBuffer s;
  3927. getSocketStatisticsString(stats,s);
  3928. PROGLOG( "Socket statistics : \n%s\n",s.str());
  3929. }
  3930. #endif
  3931. }
  3932. catch (IException *e) {
  3933. EXCLOG(e,"CRemoteFileServer(1)");
  3934. e->Release();
  3935. // not sure what to do so just accept
  3936. sockavail = true;
  3937. }
  3938. if (stopping)
  3939. break;
  3940. if (sockavail) {
  3941. try {
  3942. sock.setown(acceptsock->accept(true));
  3943. if (!sock||stopping)
  3944. break;
  3945. }
  3946. catch (IException *e) {
  3947. EXCLOG(e,"CRemoteFileServer");
  3948. e->Release();
  3949. break;
  3950. }
  3951. runClient(sock.getClear());
  3952. }
  3953. else
  3954. checkTimeout();
  3955. }
  3956. if (TF_TRACE_CLIENT_STATS)
  3957. PROGLOG("CRemoteFileServer:run exiting");
  3958. selecthandler->stop(true);
  3959. }
  3960. void processUnauthenticatedCommand(RemoteFileCommandType typ,ISocket *socket, MemoryBuffer &msg)
  3961. {
  3962. // these are unauthenticated commands
  3963. switch (typ) {
  3964. case RFCgetver: break;
  3965. default:
  3966. typ = RFCinvalid;
  3967. msg.writeDirect(msg.getPos()-sizeof(RemoteFileCommandType),sizeof(RemoteFileCommandType),&typ);
  3968. }
  3969. MemoryBuffer reply;
  3970. dispatchCommand(msg, initSendBuffer(reply), NULL, NULL);
  3971. sendBuffer(socket, reply);
  3972. }
  3973. bool checkAuthentication(ISocket *socket, IAuthenticatedUser *&ret)
  3974. {
  3975. ret = NULL;
  3976. if (!AuthenticationEnabled)
  3977. return true;
  3978. MemoryBuffer reqbuf;
  3979. MemoryBuffer reply;
  3980. MemoryBuffer encbuf; // because aesEncrypt clears input
  3981. initSendBuffer(reply);
  3982. receiveBuffer(socket, reqbuf, 1);
  3983. RemoteFileCommandType typ=0;
  3984. if (reqbuf.remaining()<sizeof(RemoteFileCommandType))
  3985. return false;
  3986. reqbuf.read(typ);
  3987. if (typ!=RFCunlock) {
  3988. processUnauthenticatedCommand(typ,socket,reqbuf);
  3989. return false;
  3990. }
  3991. if (reqbuf.remaining()<sizeof(OnceKey))
  3992. return false;
  3993. OnceKey oncekey;
  3994. reqbuf.read(sizeof(oncekey),&oncekey);
  3995. IpAddress ip;
  3996. socket->getPeerAddress(ip);
  3997. byte ipdata[16];
  3998. size32_t ipds = ip.getNetAddress(sizeof(ipdata),&ipdata);
  3999. mergeOnce(oncekey,sizeof(ipdata),&ipdata); // this is clients key
  4000. OnceKey mykey;
  4001. genOnce(mykey);
  4002. reply.append((unsigned)0); // errcode
  4003. aesEncrypt(&oncekey,sizeof(oncekey),&mykey,sizeof(oncekey),encbuf);
  4004. reply.append(encbuf.length()).append(encbuf);
  4005. sendBuffer(socket, reply); // send my oncekey
  4006. reqbuf.clear();
  4007. receiveBuffer(socket, reqbuf, 1);
  4008. if (reqbuf.remaining()>sizeof(RemoteFileCommandType)+sizeof(size32_t)) {
  4009. reqbuf.read(typ);
  4010. if (typ==RFCunlockreply) {
  4011. size32_t bs;
  4012. reqbuf.read(bs);
  4013. if (bs<=reqbuf.remaining()) {
  4014. MemoryBuffer userbuf;
  4015. aesDecrypt(&mykey,sizeof(mykey),reqbuf.readDirect(bs),bs,userbuf);
  4016. byte n;
  4017. userbuf.read(n);
  4018. if (n>=2) {
  4019. StringAttr user;
  4020. StringAttr password;
  4021. userbuf.read(user).read(password);
  4022. Owned<IAuthenticatedUser> iau = createAuthenticatedUser();
  4023. if (iau->login(user,password)) {
  4024. initSendBuffer(reply.clear());
  4025. reply.append((unsigned)0);
  4026. sendBuffer(socket, reply); // send OK
  4027. ret = iau;
  4028. return true;
  4029. }
  4030. }
  4031. }
  4032. }
  4033. }
  4034. reply.clear();
  4035. throwErr(RFSERR_AuthenticateFailed);
  4036. sendBuffer(socket, reply); // send OK
  4037. return false;
  4038. }
  4039. void runClient(ISocket *sock)
  4040. {
  4041. cCommandProcessor::cCommandProcessorParams params;
  4042. IAuthenticatedUser *user=NULL;
  4043. bool authenticated = false;
  4044. try {
  4045. if (checkAuthentication(sock,user))
  4046. authenticated = true;
  4047. }
  4048. catch (IException *e) {
  4049. e->Release();
  4050. }
  4051. if (!authenticated) {
  4052. try {
  4053. sock->Release();
  4054. }
  4055. catch (IException *e) {
  4056. e->Release();
  4057. }
  4058. return;
  4059. }
  4060. params.client = new CRemoteClientHandler(this,sock,user,globallasttick);
  4061. {
  4062. CriticalBlock block(sect);
  4063. params.client->Link();
  4064. clients.append(*params.client);
  4065. }
  4066. threads->start(&params);
  4067. }
  4068. void stop()
  4069. {
  4070. // stop accept loop
  4071. if (TF_TRACE_CLIENT_STATS)
  4072. PROGLOG("CRemoteFileServer::stop");
  4073. if (acceptsock)
  4074. acceptsock->cancel_accept();
  4075. threads->stopAll();
  4076. threads->joinAll(true,60*1000);
  4077. }
  4078. bool notify(CRemoteClientHandler *_client)
  4079. {
  4080. Linked<CRemoteClientHandler> client;
  4081. client.set(_client);
  4082. if (TF_TRACE_FULL)
  4083. PROGLOG("notify %d",client->buf.length());
  4084. if (client->buf.length()) {
  4085. cCommandProcessor::cCommandProcessorParams params;
  4086. params.client = client.getClear();
  4087. threads->start(&params);
  4088. }
  4089. else
  4090. onCloseSocket(client,3); // removes owned handles
  4091. return false;
  4092. }
  4093. void addClient(CRemoteClientHandler *client)
  4094. {
  4095. if (client&&client->socket)
  4096. selecthandler->add(client->socket,SELECTMODE_READ,client);
  4097. }
  4098. void checkTimeout()
  4099. {
  4100. if (msTick()-clientcounttick>1000*60*60) {
  4101. CriticalBlock block(ClientCountSect);
  4102. if (TF_TRACE_CLIENT_STATS && (ClientCount || MaxClientCount))
  4103. PROGLOG("Client count = %d, max = %d", ClientCount, MaxClientCount);
  4104. clientcounttick = msTick();
  4105. MaxClientCount = ClientCount;
  4106. if (closedclients) {
  4107. if (TF_TRACE_CLIENT_STATS)
  4108. PROGLOG("Closed client count = %d",closedclients);
  4109. closedclients = 0;
  4110. }
  4111. }
  4112. CriticalBlock block(sect);
  4113. ForEachItemInRev(i,clients) {
  4114. CRemoteClientHandler &client = clients.item(i);
  4115. if (client.timedOut()) {
  4116. StringBuffer s;
  4117. bool ok = client.getInfo(s); // will spot duff sockets
  4118. if (ok&&(client.handles.ordinality()!=0)) {
  4119. if (TF_TRACE_CLIENT_CONN)
  4120. WARNLOG("Inactive %s",s.str());
  4121. }
  4122. else {
  4123. #ifndef _DEBUG
  4124. if (TF_TRACE_CLIENT_CONN)
  4125. #endif
  4126. PROGLOG("Timing out %s",s.str());
  4127. closedclients++;
  4128. onCloseSocket(&client,4); // removes owned handles
  4129. }
  4130. }
  4131. }
  4132. }
  4133. int getInfo(StringBuffer &str)
  4134. {
  4135. {
  4136. CriticalBlock block(ClientCountSect);
  4137. str.append(VERSTRING).append('\n');
  4138. str.appendf("Client count = %d\n",ClientCount);
  4139. str.appendf("Max client count = %d",MaxClientCount);
  4140. }
  4141. CriticalBlock block(sect);
  4142. ForEachItemIn(i,clients) {
  4143. str.append('\n').append(i).append(": ");
  4144. clients.item(i).getInfo(str);
  4145. }
  4146. return 0;
  4147. }
  4148. unsigned threadRunningCount()
  4149. {
  4150. if (!threads)
  4151. return 0;
  4152. return threads->runningCount();
  4153. }
  4154. Semaphore &throttleSem()
  4155. {
  4156. return throttlesem;
  4157. }
  4158. unsigned idleTime()
  4159. {
  4160. unsigned t = (unsigned)atomic_read(&globallasttick);
  4161. return msTick()-t;
  4162. }
  4163. };
  4164. IRemoteFileServer * createRemoteFileServer()
  4165. {
  4166. #if SIMULATE_PACKETLOSS
  4167. errorSimulationOn = false;
  4168. #endif
  4169. return new CRemoteFileServer();
  4170. }