sockfile.cpp 138 KB

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