sockfile.cpp 140 KB

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