sockfile.cpp 154 KB

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