sockfile.cpp 178 KB

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