sockfile.cpp 141 KB

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