sockfile.cpp 142 KB

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