sockfile.cpp 148 KB

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