sockfile.cpp 179 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452
  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 DECL_EXCEPTION 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. for (;;) {
  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. for (;;) {
  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. for (;;) {
  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. for (;;) {
  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. for (;;) {
  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. for (;;) {
  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. std::atomic<unsigned> ioRetries;
  1943. IFOmode mode;
  1944. compatIFSHmode compatmode;
  1945. IFEflags extraFlags;
  1946. bool disconnectonexit;
  1947. public:
  1948. IMPLEMENT_IINTERFACE
  1949. CRemoteFileIO(CRemoteFile *_parent)
  1950. : parent(_parent), ioReadCycles(0), ioWriteCycles(0), ioReadBytes(0), ioWriteBytes(0), ioReads(0), ioWrites(0), ioRetries(0)
  1951. {
  1952. handle = 0;
  1953. disconnectonexit = false;
  1954. }
  1955. ~CRemoteFileIO()
  1956. {
  1957. if (handle) {
  1958. try {
  1959. close();
  1960. }
  1961. catch (IException *e) {
  1962. StringBuffer s;
  1963. e->errorMessage(s);
  1964. WARNLOG("CRemoteFileIO close file: %s",s.str());
  1965. e->Release();
  1966. }
  1967. }
  1968. if (disconnectonexit)
  1969. parent->disconnect();
  1970. }
  1971. void close()
  1972. {
  1973. if (handle) {
  1974. try {
  1975. MemoryBuffer sendBuffer;
  1976. initSendBuffer(sendBuffer);
  1977. sendBuffer.append((RemoteFileCommandType)RFCcloseIO).append(handle);
  1978. parent->sendRemoteCommand(sendBuffer,false);
  1979. }
  1980. catch (IDAFS_Exception *e) {
  1981. if ((e->errorCode()!=RFSERR_InvalidFileIOHandle)&&(e->errorCode()!=RFSERR_NullFileIOHandle))
  1982. throw;
  1983. e->Release();
  1984. }
  1985. handle = 0;
  1986. }
  1987. }
  1988. bool open(IFOmode _mode,compatIFSHmode _compatmode,IFEflags _extraFlags=IFEnone)
  1989. {
  1990. MemoryBuffer sendBuffer;
  1991. initSendBuffer(sendBuffer);
  1992. MemoryBuffer replyBuffer;
  1993. const char *localname = parent->queryLocalName();
  1994. localname = skipSpecialPath(localname);
  1995. // also send _extraFlags
  1996. // then also send sMode, cFlags
  1997. unsigned short sMode = parent->getShareMode();
  1998. unsigned short cFlags = parent->getCreateFlags();
  1999. sendBuffer.append((RemoteFileCommandType)RFCopenIO).append(localname).append((byte)_mode).append((byte)_compatmode).append((byte)_extraFlags).append(sMode).append(cFlags);
  2000. parent->sendRemoteCommand(sendBuffer, replyBuffer);
  2001. replyBuffer.read(handle);
  2002. if (!handle)
  2003. return false;
  2004. switch (_mode) {
  2005. case IFOcreate:
  2006. mode = IFOwrite;
  2007. break;
  2008. case IFOcreaterw:
  2009. mode = IFOreadwrite;
  2010. break;
  2011. default:
  2012. mode = _mode;
  2013. break;
  2014. }
  2015. compatmode = _compatmode;
  2016. extraFlags = _extraFlags;
  2017. return true;
  2018. }
  2019. bool reopen()
  2020. {
  2021. StringBuffer s;
  2022. PROGLOG("Attempting reopen of %s on %s",parent->queryLocalName(),parent->queryEp().getUrlStr(s).str());
  2023. if (open(mode,compatmode,extraFlags)) {
  2024. return true;
  2025. }
  2026. return false;
  2027. }
  2028. offset_t size()
  2029. {
  2030. MemoryBuffer sendBuffer;
  2031. initSendBuffer(sendBuffer);
  2032. MemoryBuffer replyBuffer;
  2033. sendBuffer.append((RemoteFileCommandType)RFCsize).append(handle);
  2034. parent->sendRemoteCommand(sendBuffer, replyBuffer, false);
  2035. // Retry using reopen TBD
  2036. offset_t ret;
  2037. replyBuffer.read(ret);
  2038. return ret;
  2039. }
  2040. virtual unsigned __int64 getStatistic(StatisticKind kind)
  2041. {
  2042. switch (kind)
  2043. {
  2044. case StCycleDiskReadIOCycles:
  2045. return ioReadCycles.load(std::memory_order_relaxed);
  2046. case StCycleDiskWriteIOCycles:
  2047. return ioWriteCycles.load(std::memory_order_relaxed);
  2048. case StTimeDiskReadIO:
  2049. return cycle_to_nanosec(ioReadCycles.load(std::memory_order_relaxed));
  2050. case StTimeDiskWriteIO:
  2051. return cycle_to_nanosec(ioWriteCycles.load(std::memory_order_relaxed));
  2052. case StSizeDiskRead:
  2053. return ioReadBytes.load(std::memory_order_relaxed);
  2054. case StSizeDiskWrite:
  2055. return ioWriteBytes.load(std::memory_order_relaxed);
  2056. case StNumDiskReads:
  2057. return ioReads.load(std::memory_order_relaxed);
  2058. case StNumDiskWrites:
  2059. return ioWrites.load(std::memory_order_relaxed);
  2060. case StNumDiskRetries:
  2061. return ioRetries.load(std::memory_order_relaxed);
  2062. }
  2063. return 0;
  2064. }
  2065. size32_t read(offset_t pos, size32_t len, void * data)
  2066. {
  2067. size32_t got;
  2068. MemoryBuffer replyBuffer;
  2069. CCycleTimer timer;
  2070. const void *b;
  2071. try
  2072. {
  2073. b = doRead(pos,len,replyBuffer,got,data);
  2074. }
  2075. catch (...)
  2076. {
  2077. ioReadCycles.fetch_add(timer.elapsedCycles());
  2078. throw;
  2079. }
  2080. ioReadCycles.fetch_add(timer.elapsedCycles());
  2081. ioReadBytes.fetch_add(got);
  2082. ++ioReads;
  2083. if (b!=data)
  2084. memcpy(data,b,got);
  2085. return got;
  2086. }
  2087. virtual void flush()
  2088. {
  2089. }
  2090. const void *doRead(offset_t pos, size32_t len, MemoryBuffer &replyBuffer, size32_t &got, void *dstbuf)
  2091. {
  2092. unsigned tries=0;
  2093. for (;;) {
  2094. try {
  2095. MemoryBuffer sendBuffer;
  2096. initSendBuffer(sendBuffer);
  2097. replyBuffer.clear();
  2098. sendBuffer.append((RemoteFileCommandType)RFCread).append(handle).append(pos).append(len);
  2099. parent->sendRemoteCommand(sendBuffer, replyBuffer,false);
  2100. // kludge dafilesrv versions <= 1.5e don't return error correctly
  2101. if (replyBuffer.length()>len+sizeof(size32_t)+sizeof(unsigned)) {
  2102. size32_t save = replyBuffer.getPos();
  2103. replyBuffer.reset(len+sizeof(size32_t)+sizeof(unsigned));
  2104. unsigned errCode;
  2105. replyBuffer.read(errCode);
  2106. if (errCode) {
  2107. StringBuffer msg;
  2108. parent->ep.getUrlStr(msg.append('[')).append("] ");
  2109. if (replyBuffer.getPos()<replyBuffer.length()) {
  2110. StringAttr s;
  2111. replyBuffer.read(s);
  2112. msg.append(s);
  2113. }
  2114. else
  2115. msg.append("ERROR #").append(errCode);
  2116. throw createDafsException(errCode, msg.str());
  2117. }
  2118. else
  2119. replyBuffer.reset(save);
  2120. }
  2121. replyBuffer.read(got);
  2122. if ((got>replyBuffer.remaining())||(got>len)) {
  2123. PROGLOG("Read beyond buffer %d,%d,%d",got,replyBuffer.remaining(),len);
  2124. throw createDafsException(RFSERR_ReadFailed, "Read beyond buffer");
  2125. }
  2126. return replyBuffer.readDirect(got);
  2127. }
  2128. catch (IJSOCK_Exception *e) {
  2129. EXCLOG(e,"CRemoteFileIO::read");
  2130. if (++tries > 3)
  2131. {
  2132. ioRetries.fetch_add(tries);
  2133. throw;
  2134. }
  2135. WARNLOG("Retrying read of %s (%d)",parent->queryLocalName(),tries);
  2136. Owned<IException> exc = e;
  2137. if (!reopen())
  2138. {
  2139. ioRetries.fetch_add(tries);
  2140. throw exc.getClear();
  2141. }
  2142. }
  2143. }
  2144. if (tries)
  2145. ioRetries.fetch_add(tries);
  2146. got = 0;
  2147. return NULL;
  2148. }
  2149. size32_t write(offset_t pos, size32_t len, const void * data)
  2150. {
  2151. unsigned tries=0;
  2152. size32_t ret = 0;
  2153. CCycleTimer timer;
  2154. for (;;) {
  2155. try {
  2156. MemoryBuffer replyBuffer;
  2157. MemoryBuffer sendBuffer;
  2158. initSendBuffer(sendBuffer);
  2159. sendBuffer.append((RemoteFileCommandType)RFCwrite).append(handle).append(pos).append(len).append(len, data);
  2160. parent->sendRemoteCommand(sendBuffer, replyBuffer, false, true);
  2161. replyBuffer.read(ret);
  2162. break;
  2163. }
  2164. catch (IJSOCK_Exception *e) {
  2165. EXCLOG(e,"CRemoteFileIO::write");
  2166. if (++tries > 3)
  2167. {
  2168. ioRetries.fetch_add(tries);
  2169. ioWriteCycles.fetch_add(timer.elapsedCycles());
  2170. throw;
  2171. }
  2172. WARNLOG("Retrying write(%" I64F "d,%d) of %s (%d)",pos,len,parent->queryLocalName(),tries);
  2173. Owned<IException> exc = e;
  2174. if (!reopen())
  2175. {
  2176. ioRetries.fetch_add(tries);
  2177. ioWriteCycles.fetch_add(timer.elapsedCycles());
  2178. throw exc.getClear();
  2179. }
  2180. }
  2181. }
  2182. if (tries)
  2183. ioRetries.fetch_add(tries);
  2184. ioWriteCycles.fetch_add(timer.elapsedCycles());
  2185. ioWriteBytes.fetch_add(ret);
  2186. ++ioWrites;
  2187. if ((ret==(size32_t)-1) || (ret < len))
  2188. throw createDafsException(DISK_FULL_EXCEPTION_CODE,"write failed, disk full?");
  2189. return ret;
  2190. }
  2191. offset_t appendFile(IFile *file,offset_t pos,offset_t len)
  2192. {
  2193. MemoryBuffer sendBuffer;
  2194. initSendBuffer(sendBuffer);
  2195. MemoryBuffer replyBuffer;
  2196. const char * fname = file->queryFilename();
  2197. sendBuffer.append((RemoteFileCommandType)RFCappend).append(handle).append(fname).append(pos).append(len);
  2198. parent->sendRemoteCommand(sendBuffer, replyBuffer, false, true); // retry not safe
  2199. offset_t ret;
  2200. replyBuffer.read(ret);
  2201. if ((ret==(offset_t)-1) || (ret < len))
  2202. throw createDafsException(DISK_FULL_EXCEPTION_CODE,"append failed, disk full?"); // though could be file missing TBD
  2203. return ret;
  2204. }
  2205. void setSize(offset_t size)
  2206. {
  2207. MemoryBuffer sendBuffer;
  2208. initSendBuffer(sendBuffer);
  2209. MemoryBuffer replyBuffer;
  2210. sendBuffer.append((RemoteFileCommandType)RFCsetsize).append(handle).append(size);
  2211. parent->sendRemoteCommand(sendBuffer, replyBuffer, false, true);
  2212. // retry using reopen TBD
  2213. }
  2214. void setDisconnectOnExit(bool set) { disconnectonexit = set; }
  2215. };
  2216. void clientDisconnectRemoteIoOnExit(IFileIO *fileio,bool set)
  2217. {
  2218. CRemoteFileIO *cfileio = QUERYINTERFACE(fileio,CRemoteFileIO);
  2219. if (cfileio)
  2220. cfileio->setDisconnectOnExit(set);
  2221. }
  2222. IFileIO * CRemoteFile::openShared(IFOmode mode,IFSHmode shmode,IFEflags extraFlags)
  2223. {
  2224. assertex(((unsigned)shmode&0xffffffc7)==0);
  2225. compatIFSHmode compatmode;
  2226. unsigned fileflags = (flags>>16) & (S_IRUSR|S_IWUSR|S_IXUSR|S_IRGRP|S_IWGRP|S_IXGRP|S_IROTH|S_IWOTH|S_IXOTH);
  2227. if (fileflags&S_IXUSR) // this is bit hit and miss but backward compatible
  2228. compatmode = compatIFSHexec;
  2229. else if (fileflags&(S_IWGRP|S_IWOTH))
  2230. compatmode = compatIFSHall;
  2231. else if (shmode&IFSHfull)
  2232. compatmode = compatIFSHwrite;
  2233. else if (((shmode&(IFSHread|IFSHfull))==0) && ((fileflags&(S_IRGRP|S_IROTH))==0))
  2234. compatmode = compatIFSHnone;
  2235. else
  2236. compatmode = compatIFSHread;
  2237. Owned<CRemoteFileIO> res = new CRemoteFileIO(this);
  2238. if (res->open(mode,compatmode,extraFlags))
  2239. return res.getClear();
  2240. return NULL;
  2241. }
  2242. IFileIO * CRemoteFile::open(IFOmode mode,IFEflags extraFlags)
  2243. {
  2244. return openShared(mode,(IFSHmode)(flags&(IFSHread|IFSHfull)),extraFlags);
  2245. }
  2246. //---------------------------------------------------------------------------
  2247. void CRemoteFile::copyTo(IFile *dest, size32_t buffersize, ICopyFileProgress *progress, bool usetmp, CFflags copyFlags)
  2248. {
  2249. CRemoteFile *dstfile = QUERYINTERFACE(dest,CRemoteFile);
  2250. if (dstfile&&!dstfile->queryEp().isLocal()) {
  2251. StringBuffer tmpname;
  2252. Owned<IFile> destf;
  2253. RemoteFilename dest;
  2254. if (usetmp) {
  2255. makeTempCopyName(tmpname,dstfile->queryLocalName());
  2256. dest.setPath(dstfile->queryEp(),tmpname.str());
  2257. }
  2258. else
  2259. dest.setPath(dstfile->queryEp(),dstfile->queryLocalName());
  2260. destf.setown(createIFile(dest));
  2261. try {
  2262. // following may fail if new dafilesrv not deployed on src
  2263. copySection(dest,(offset_t)-1,0,(offset_t)-1,progress,copyFlags);
  2264. if (usetmp) {
  2265. StringAttr tail(pathTail(dstfile->queryLocalName()));
  2266. dstfile->remove();
  2267. destf->rename(tail);
  2268. }
  2269. return;
  2270. }
  2271. catch (IException *e)
  2272. {
  2273. StringBuffer s;
  2274. s.appendf("Remote File Copy (%d): ",e->errorCode());
  2275. e->errorMessage(s);
  2276. s.append(", retrying local");
  2277. WARNLOG("%s",s.str());
  2278. e->Release();
  2279. }
  2280. // delete dest
  2281. try {
  2282. destf->remove();
  2283. }
  2284. catch (IException *e)
  2285. {
  2286. EXCLOG(e,"Remote File Copy, Deleting temporary file");
  2287. e->Release();
  2288. }
  2289. }
  2290. // assumption if we get here that source remote, dest local (or equiv)
  2291. class cIntercept: implements ICopyFileIntercept
  2292. {
  2293. MemoryAttr ma;
  2294. MemoryBuffer mb;
  2295. virtual offset_t copy(IFileIO *from, IFileIO *to, offset_t ofs, size32_t sz)
  2296. {
  2297. if (ma.length()<sz)
  2298. ma.allocate(sz); // may be not used
  2299. void *buf = ma.bufferBase();
  2300. size32_t got;
  2301. CRemoteFileIO *srcio = QUERYINTERFACE(from,CRemoteFileIO);
  2302. const void *dst;
  2303. if (srcio)
  2304. dst = srcio->doRead(ofs,sz,mb.clear(),got,buf);
  2305. else {
  2306. // shouldn't ever get here if source remote
  2307. got = from->read(ofs, sz, buf);
  2308. dst = buf;
  2309. }
  2310. if (got != 0)
  2311. to->write(ofs, got, dst);
  2312. return got;
  2313. }
  2314. } intercept;
  2315. doCopyFile(dest,this,buffersize,progress,&intercept,usetmp,copyFlags);
  2316. }
  2317. unsigned getRemoteVersion(ISocket * socket, StringBuffer &ver)
  2318. {
  2319. // used to have a global critical section here
  2320. if (!socket)
  2321. return 0;
  2322. unsigned ret;
  2323. MemoryBuffer sendbuf;
  2324. initSendBuffer(sendbuf);
  2325. sendbuf.append((RemoteFileCommandType)RFCgetver);
  2326. sendbuf.append((unsigned)RFCgetver);
  2327. MemoryBuffer reply;
  2328. try {
  2329. sendBuffer(socket, sendbuf);
  2330. receiveBuffer(socket, reply, 1 ,4096);
  2331. unsigned errCode;
  2332. reply.read(errCode);
  2333. if (errCode==RFSERR_InvalidCommand) {
  2334. ver.append("DS V1.0");
  2335. return 10;
  2336. }
  2337. else if (errCode==0)
  2338. ret = 11;
  2339. else if (errCode<0x10000)
  2340. return 0;
  2341. else
  2342. ret = errCode-0x10000;
  2343. }
  2344. catch (IException *e) {
  2345. EXCLOG(e);
  2346. ::Release(e);
  2347. return 0;
  2348. }
  2349. StringAttr vers;
  2350. reply.read(vers);
  2351. ver.append(vers);
  2352. return ret;
  2353. }
  2354. extern unsigned stopRemoteServer(ISocket * socket)
  2355. {
  2356. // used to have a global critical section here
  2357. if (!socket)
  2358. return 0;
  2359. MemoryBuffer sendbuf;
  2360. initSendBuffer(sendbuf);
  2361. sendbuf.append((RemoteFileCommandType)RFCstop);
  2362. sendbuf.append((unsigned)RFCstop);
  2363. MemoryBuffer replybuf;
  2364. unsigned errCode = RFSERR_InvalidCommand;
  2365. try {
  2366. sendBuffer(socket, sendbuf);
  2367. receiveBuffer(socket, replybuf, NORMAL_RETRIES, 1024);
  2368. replybuf.read(errCode);
  2369. }
  2370. catch (IJSOCK_Exception *e) {
  2371. if ((e->errorCode()!=JSOCKERR_broken_pipe)&&(e->errorCode()!=JSOCKERR_graceful_close))
  2372. EXCLOG(e);
  2373. else
  2374. errCode = 0;
  2375. }
  2376. catch (IException *e) {
  2377. EXCLOG(e);
  2378. ::Release(e);
  2379. }
  2380. return errCode;
  2381. }
  2382. int remoteExec(ISocket * socket, const char *cmdline, const char *workdir,bool sync,
  2383. size32_t insize, void *inbuf, MemoryBuffer *outbuf)
  2384. {
  2385. if (!socket)
  2386. return -1;
  2387. bool hasoutput = (outbuf!=NULL);
  2388. if (!inbuf)
  2389. insize = 0;
  2390. MemoryBuffer sendbuf;
  2391. initSendBuffer(sendbuf);
  2392. sendbuf.append((RemoteFileCommandType)RFCexec).append(cmdline).append(workdir).append(sync).
  2393. append(hasoutput).append(insize);
  2394. if (insize)
  2395. sendbuf.append(insize, inbuf);
  2396. MemoryBuffer replybuf;
  2397. try {
  2398. sendBuffer(socket, sendbuf);
  2399. receiveBuffer(socket, replybuf, LENGTHY_RETRIES); // we don't know how long program will take really - assume <1hr
  2400. int retcode;
  2401. unsigned phandle;
  2402. size32_t outsz;
  2403. replybuf.read(retcode).read(phandle).read(outsz);
  2404. if (outsz&&outbuf)
  2405. replybuf.read(outsz,outbuf->reserve(outsz));
  2406. return retcode;
  2407. }
  2408. catch (IException *e) {
  2409. EXCLOG(e);
  2410. ::Release(e);
  2411. }
  2412. return -1;
  2413. }
  2414. int setDafsTrace(ISocket * socket,byte flags)
  2415. {
  2416. if (!socket) {
  2417. byte ret = traceFlags;
  2418. traceFlags = flags;
  2419. return ret;
  2420. }
  2421. MemoryBuffer sendbuf;
  2422. initSendBuffer(sendbuf);
  2423. sendbuf.append((RemoteFileCommandType)RFCsettrace).append(flags);
  2424. MemoryBuffer replybuf;
  2425. try {
  2426. sendBuffer(socket, sendbuf);
  2427. receiveBuffer(socket, replybuf, NORMAL_RETRIES, 1024);
  2428. int retcode;
  2429. replybuf.read(retcode);
  2430. return retcode;
  2431. }
  2432. catch (IException *e) {
  2433. EXCLOG(e);
  2434. ::Release(e);
  2435. }
  2436. return -1;
  2437. }
  2438. int setDafsThrottleLimit(ISocket * socket, ThrottleClass throttleClass, unsigned throttleLimit, unsigned throttleDelayMs, unsigned throttleCPULimit, unsigned queueLimit, StringBuffer *errMsg)
  2439. {
  2440. assertex(socket);
  2441. MemoryBuffer sendbuf;
  2442. initSendBuffer(sendbuf);
  2443. sendbuf.append((RemoteFileCommandType)RFCsetthrottle2).append((unsigned)throttleClass).append(throttleLimit);
  2444. sendbuf.append(throttleDelayMs).append(throttleCPULimit).append(queueLimit);
  2445. MemoryBuffer replybuf;
  2446. try {
  2447. sendBuffer(socket, sendbuf);
  2448. receiveBuffer(socket, replybuf, NORMAL_RETRIES, 1024);
  2449. int retcode;
  2450. replybuf.read(retcode);
  2451. if (retcode && errMsg && replybuf.remaining())
  2452. replybuf.read(*errMsg);
  2453. return retcode;
  2454. }
  2455. catch (IException *e) {
  2456. EXCLOG(e);
  2457. ::Release(e);
  2458. }
  2459. return -1;
  2460. }
  2461. int getDafsInfo(ISocket * socket, unsigned level, StringBuffer &retstr)
  2462. {
  2463. if (!socket) {
  2464. retstr.append(VERSTRING);
  2465. return 0;
  2466. }
  2467. MemoryBuffer sendbuf;
  2468. initSendBuffer(sendbuf);
  2469. sendbuf.append((RemoteFileCommandType)RFCgetinfo).append(level);
  2470. MemoryBuffer replybuf;
  2471. try {
  2472. sendBuffer(socket, sendbuf);
  2473. receiveBuffer(socket, replybuf, 1);
  2474. int retcode;
  2475. replybuf.read(retcode);
  2476. if (retcode==0) {
  2477. StringAttr s;
  2478. replybuf.read(s);
  2479. retstr.append(s);
  2480. }
  2481. return retcode;
  2482. }
  2483. catch (IException *e) {
  2484. EXCLOG(e);
  2485. ::Release(e);
  2486. }
  2487. return -1;
  2488. }
  2489. void remoteExtractBlobElements(const SocketEndpoint &ep,const char * prefix, const char * filename, ExtractedBlobArray & extracted)
  2490. {
  2491. Owned<CRemoteFile> file = new CRemoteFile (ep,filename);
  2492. file->remoteExtractBlobElements(prefix, extracted);
  2493. }
  2494. //====================================================================================================
  2495. class CAsyncCommandManager
  2496. {
  2497. class CAsyncJob: public CInterface
  2498. {
  2499. class cThread: public Thread
  2500. {
  2501. CAsyncJob *parent;
  2502. public:
  2503. cThread(CAsyncJob *_parent)
  2504. : Thread("CAsyncJob")
  2505. {
  2506. parent = _parent;
  2507. }
  2508. int run()
  2509. {
  2510. int ret = -1;
  2511. try {
  2512. ret = parent->run();
  2513. parent->setDone();
  2514. }
  2515. catch (IException *e)
  2516. {
  2517. parent->setException(e);
  2518. }
  2519. parent->signal();
  2520. return ret;
  2521. }
  2522. } *thread;
  2523. StringAttr uuid;
  2524. CAsyncCommandManager &parent;
  2525. public:
  2526. CAsyncJob(CAsyncCommandManager &_parent, const char *_uuid)
  2527. : uuid(_uuid), parent(_parent)
  2528. {
  2529. thread = new cThread(this);
  2530. hash = hashc((const byte *)uuid.get(),uuid.length(),~0U);
  2531. }
  2532. ~CAsyncJob()
  2533. {
  2534. thread->join();
  2535. thread->Release();
  2536. }
  2537. static void destroy(CAsyncJob *j)
  2538. {
  2539. j->Release();
  2540. }
  2541. void signal()
  2542. {
  2543. parent.signal();
  2544. }
  2545. void start()
  2546. {
  2547. parent.wait();
  2548. thread->start();
  2549. }
  2550. void join()
  2551. {
  2552. thread->join();
  2553. }
  2554. static unsigned getHash(const char *key)
  2555. {
  2556. return hashc((const byte *)key,strlen(key),~0U);
  2557. }
  2558. static CAsyncJob* create(const char *key) { assertex(!"CAsyncJob::create not implemented"); return NULL; }
  2559. unsigned hash;
  2560. bool eq(const char *key)
  2561. {
  2562. return stricmp(key,uuid.get())==0;
  2563. }
  2564. virtual int run()=0;
  2565. virtual void setException(IException *e)=0;
  2566. virtual void setDone()=0;
  2567. };
  2568. class CAsyncCopySection: public CAsyncJob
  2569. {
  2570. Owned<IFile> src;
  2571. RemoteFilename dst;
  2572. offset_t toOfs;
  2573. offset_t fromOfs;
  2574. offset_t size;
  2575. CFPmode mode; // not yet supported
  2576. CriticalSection sect;
  2577. offset_t done;
  2578. offset_t total;
  2579. Semaphore finished;
  2580. AsyncCommandStatus status;
  2581. Owned<IException> exc;
  2582. public:
  2583. CAsyncCopySection(CAsyncCommandManager &parent, const char *_uuid, const char *fromFile, const char *toFile, offset_t _toOfs, offset_t _fromOfs, offset_t _size)
  2584. : CAsyncJob(parent, _uuid)
  2585. {
  2586. status = ACScontinue;
  2587. src.setown(createIFile(fromFile));
  2588. dst.setRemotePath(toFile);
  2589. toOfs = _toOfs;
  2590. fromOfs = _fromOfs;
  2591. size = _size;
  2592. mode = CFPcontinue;
  2593. done = 0;
  2594. total = (offset_t)-1;
  2595. }
  2596. AsyncCommandStatus poll(offset_t &_done, offset_t &_total,unsigned timeout)
  2597. {
  2598. if (timeout&&finished.wait(timeout))
  2599. finished.signal(); // may need to call again
  2600. CriticalBlock block(sect);
  2601. if (exc)
  2602. throw exc.getClear();
  2603. _done = done;
  2604. _total = total;
  2605. return status;
  2606. }
  2607. int run()
  2608. {
  2609. class cProgress: implements ICopyFileProgress
  2610. {
  2611. CriticalSection &sect;
  2612. CFPmode &mode;
  2613. offset_t &done;
  2614. offset_t &total;
  2615. public:
  2616. cProgress(CriticalSection &_sect,offset_t &_done,offset_t &_total,CFPmode &_mode)
  2617. : sect(_sect), mode(_mode), done(_done), total(_total)
  2618. {
  2619. }
  2620. CFPmode onProgress(offset_t sizeDone, offset_t totalSize)
  2621. {
  2622. CriticalBlock block(sect);
  2623. done = sizeDone;
  2624. total = totalSize;
  2625. return mode;
  2626. }
  2627. } progress(sect,total,done,mode);
  2628. src->copySection(dst,toOfs, fromOfs, size, &progress); // exceptions will be handled by base class
  2629. return 0;
  2630. }
  2631. void setException(IException *e)
  2632. {
  2633. EXCLOG(e,"CAsyncCommandManager::CAsyncJob");
  2634. CriticalBlock block(sect);
  2635. if (exc.get())
  2636. e->Release();
  2637. else
  2638. exc.setown(e);
  2639. status = ACSerror;
  2640. }
  2641. void setDone()
  2642. {
  2643. CriticalBlock block(sect);
  2644. finished.signal();
  2645. status = ACSdone;
  2646. }
  2647. };
  2648. CMinHashTable<CAsyncJob> jobtable;
  2649. CriticalSection sect;
  2650. Semaphore threadsem;
  2651. unsigned limit;
  2652. public:
  2653. CAsyncCommandManager(unsigned _limit) : limit(_limit)
  2654. {
  2655. if (limit) // 0 == unbound
  2656. threadsem.signal(limit); // max number of async jobs
  2657. }
  2658. void join()
  2659. {
  2660. CriticalBlock block(sect);
  2661. unsigned i;
  2662. CAsyncJob *j=jobtable.first(i);
  2663. while (j) {
  2664. j->join();
  2665. j=jobtable.next(i);
  2666. }
  2667. }
  2668. void signal()
  2669. {
  2670. if (limit)
  2671. threadsem.signal();
  2672. }
  2673. void wait()
  2674. {
  2675. if (limit)
  2676. threadsem.wait();
  2677. }
  2678. 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)
  2679. {
  2680. // return 0 if continuing, 1 if done
  2681. CAsyncCopySection * job;
  2682. Linked<CAsyncJob> cjob;
  2683. {
  2684. CriticalBlock block(sect);
  2685. cjob.set(jobtable.find(uuid,false));
  2686. if (cjob) {
  2687. job = QUERYINTERFACE(cjob.get(),CAsyncCopySection);
  2688. if (!job) {
  2689. throw MakeStringException(-1,"Async job ID mismatch");
  2690. }
  2691. }
  2692. else {
  2693. job = new CAsyncCopySection(*this, uuid, fromFile, toFile, toOfs, fromOfs, size);
  2694. cjob.setown(job);
  2695. jobtable.add(cjob.getLink());
  2696. cjob->start();
  2697. }
  2698. }
  2699. AsyncCommandStatus ret = ACSerror;
  2700. Owned<IException> rete;
  2701. try {
  2702. ret = job->poll(done,total,timeout);
  2703. }
  2704. catch (IException * e) {
  2705. rete.setown(e);
  2706. }
  2707. if ((ret!=ACScontinue)||rete.get()) {
  2708. job->join();
  2709. CriticalBlock block(sect);
  2710. jobtable.remove(job);
  2711. if (rete.get())
  2712. throw rete.getClear();
  2713. }
  2714. return ret;
  2715. }
  2716. };
  2717. //====================================================================================================
  2718. inline void appendErr(MemoryBuffer &reply, unsigned e)
  2719. {
  2720. reply.append(e).append(getRFSERRText(e));
  2721. }
  2722. inline void appendErr2(MemoryBuffer &reply, unsigned e, unsigned v)
  2723. {
  2724. StringBuffer msg;
  2725. msg.append(getRFSERRText(e)).append(':').append(v);
  2726. reply.append(e).append(msg.str());
  2727. }
  2728. inline void appendErr3(MemoryBuffer &reply, unsigned e, int code, const char *errMsg)
  2729. {
  2730. StringBuffer msg;
  2731. msg.appendf("ERROR: %s(%d) '%s'", getRFSERRText(e), code, errMsg?errMsg:"");
  2732. reply.append(e);
  2733. reply.append(msg.str());
  2734. }
  2735. inline void appendCmdErr(MemoryBuffer &reply, RemoteFileCommandType e, int code, const char *errMsg)
  2736. {
  2737. StringBuffer msg;
  2738. msg.appendf("ERROR: %s(%d) '%s'", getRFCText(e), code, errMsg?errMsg:"");
  2739. // RFCOpenIO needs remapping to non-zero for client to know its an error
  2740. // perhaps we should use code here instead of e ?
  2741. unsigned err = e;
  2742. if (e == RFCopenIO)
  2743. err = RFSERR_OpenFailed;
  2744. reply.append(err);
  2745. reply.append(msg.str());
  2746. }
  2747. #define MAPCOMMAND(c,p) case c: { ret = this->p(msg, reply) ; break; }
  2748. #define MAPCOMMANDCLIENT(c,p,client) case c: { ret = this->p(msg, reply, client); break; }
  2749. #define MAPCOMMANDCLIENTTHROTTLE(c,p,client,throttler) case c: { ret = this->p(msg, reply, client, throttler); break; }
  2750. #define MAPCOMMANDSTATS(c,p,stats) case c: { ret = this->p(msg, reply, stats); break; }
  2751. #define MAPCOMMANDCLIENTSTATS(c,p,client,stats) case c: { ret = this->p(msg, reply, client, stats); break; }
  2752. static unsigned ClientCount = 0;
  2753. static unsigned MaxClientCount = 0;
  2754. static CriticalSection ClientCountSect;
  2755. #define DEFAULT_THROTTLOG_LOG_INTERVAL_SECS 60 // log total throttled delay period
  2756. class CClientStats : public CInterface
  2757. {
  2758. public:
  2759. CClientStats(const char *_client) : client(_client), count(0), bRead(0), bWritten(0) { }
  2760. const char *queryFindString() const { return client; }
  2761. inline void addRead(unsigned __int64 len)
  2762. {
  2763. bRead += len;
  2764. }
  2765. inline void addWrite(unsigned __int64 len)
  2766. {
  2767. bWritten += len;
  2768. }
  2769. void getStatus(StringBuffer & info) const
  2770. {
  2771. info.appendf("Client %s - %" I64F "d requests handled, bytes read = %" I64F "d, bytes written = % " I64F "d",
  2772. client.get(), count, bRead.load(), bWritten.load()).newline();
  2773. }
  2774. StringAttr client;
  2775. unsigned __int64 count;
  2776. std::atomic<unsigned __int64> bRead;
  2777. std::atomic<unsigned __int64> bWritten;
  2778. };
  2779. class CClientStatsTable : public OwningStringSuperHashTableOf<CClientStats>
  2780. {
  2781. typedef OwningStringSuperHashTableOf<CClientStats> PARENT;
  2782. CriticalSection crit;
  2783. unsigned cmdStats[RFCmax];
  2784. static int compareElement(void* const *ll, void* const *rr)
  2785. {
  2786. const CClientStats *l = (const CClientStats *) *ll;
  2787. const CClientStats *r = (const CClientStats *) *rr;
  2788. if (l->count == r->count)
  2789. return 0;
  2790. else if (l->count<r->count)
  2791. return 1;
  2792. else
  2793. return -1;
  2794. }
  2795. public:
  2796. CClientStatsTable()
  2797. {
  2798. memset(&cmdStats[0], 0, sizeof(cmdStats));
  2799. }
  2800. ~CClientStatsTable()
  2801. {
  2802. _releaseAll();
  2803. }
  2804. CClientStats *getClientReference(RemoteFileCommandType cmd, const char *client)
  2805. {
  2806. CriticalBlock b(crit);
  2807. CClientStats *stats = PARENT::find(client);
  2808. if (!stats)
  2809. {
  2810. stats = new CClientStats(client);
  2811. PARENT::replace(*stats);
  2812. }
  2813. if (cmd<RFCmax) // i.e. ignore duff command (which will be traced), but still record client connected
  2814. cmdStats[cmd]++;
  2815. ++stats->count;
  2816. return LINK(stats);
  2817. }
  2818. StringBuffer &getInfo(StringBuffer &info, unsigned level=1)
  2819. {
  2820. CriticalBlock b(crit);
  2821. unsigned __int64 totalCmds = 0;
  2822. for (unsigned c=0; c<RFCmax; c++)
  2823. totalCmds += cmdStats[c];
  2824. unsigned totalClients = PARENT::ordinality();
  2825. info.appendf("Commands processed = %" I64F "u, unique clients = %u", totalCmds, totalClients);
  2826. if (totalCmds)
  2827. {
  2828. info.append("Command stats:").newline();
  2829. for (unsigned c=0; c<RFCmax; c++)
  2830. {
  2831. unsigned __int64 count = cmdStats[c];
  2832. if (count)
  2833. info.append(getRFCText(c)).append(": ").append(count).newline();
  2834. }
  2835. }
  2836. if (totalClients)
  2837. {
  2838. SuperHashIteratorOf<CClientStats> iter(*this);
  2839. PointerArrayOf<CClientStats> elements;
  2840. ForEach(iter)
  2841. {
  2842. CClientStats &elem = iter.query();
  2843. elements.append(&elem);
  2844. }
  2845. elements.sort(&compareElement);
  2846. if (level < 10)
  2847. {
  2848. // list up to 10 clients ordered by # of commands processed
  2849. unsigned max=elements.ordinality();
  2850. if (max>10)
  2851. max = 10; // cap
  2852. info.append("Top 10 clients:").newline();
  2853. for (unsigned e=0; e<max; e++)
  2854. {
  2855. const CClientStats &element = *elements.item(e);
  2856. element.getStatus(info);
  2857. }
  2858. }
  2859. else // list all
  2860. {
  2861. info.append("All clients:").newline();
  2862. ForEachItemIn(e, elements)
  2863. {
  2864. const CClientStats &element = *elements.item(e);
  2865. element.getStatus(info);
  2866. }
  2867. }
  2868. }
  2869. return info;
  2870. }
  2871. void reset()
  2872. {
  2873. CriticalBlock b(crit);
  2874. memset(&cmdStats[0], 0, sizeof(cmdStats));
  2875. kill();
  2876. }
  2877. };
  2878. class CRemoteFileServer : implements IRemoteFileServer, public CInterface
  2879. {
  2880. class CThrottler;
  2881. class CRemoteClientHandler : implements ISocketSelectNotify, public CInterface
  2882. {
  2883. public:
  2884. CRemoteFileServer *parent;
  2885. Owned<ISocket> socket;
  2886. StringAttr peerName;
  2887. Owned<IAuthenticatedUser> user;
  2888. MemoryBuffer msg;
  2889. bool selecthandled;
  2890. size32_t left;
  2891. IArrayOf<IFileIO> openfiles; // kept in sync with handles
  2892. Owned<IDirectoryIterator> opendir;
  2893. StringAttrArray opennames; // for debug
  2894. IntArray handles;
  2895. unsigned lasttick, lastInactiveTick;
  2896. atomic_t &globallasttick;
  2897. unsigned previdx; // for debug
  2898. IMPLEMENT_IINTERFACE;
  2899. CRemoteClientHandler(CRemoteFileServer *_parent,ISocket *_socket,IAuthenticatedUser *_user,atomic_t &_globallasttick)
  2900. : socket(_socket), user(_user), globallasttick(_globallasttick)
  2901. {
  2902. previdx = (unsigned)-1;
  2903. StringBuffer peerBuf;
  2904. char name[256];
  2905. name[0] = 0;
  2906. int port = socket->peer_name(name,sizeof(name)-1);
  2907. if (port>=0)
  2908. {
  2909. peerBuf.append(name);
  2910. if (port)
  2911. peerBuf.append(':').append(port);
  2912. peerName.set(peerBuf);
  2913. }
  2914. else
  2915. {
  2916. /* There's a possibility the socket closed before got here, in which case, peer name is unavailable
  2917. * May potentially be unavailable for other reasons also.
  2918. * Must be set, as used in client stats HT.
  2919. * If socket closed, the handler will start up but notice closed and quit
  2920. */
  2921. peerName.set("UNKNOWN PEER NAME");
  2922. }
  2923. {
  2924. CriticalBlock block(ClientCountSect);
  2925. if (++ClientCount>MaxClientCount)
  2926. MaxClientCount = ClientCount;
  2927. if (TF_TRACE_CLIENT_CONN)
  2928. {
  2929. StringBuffer s;
  2930. s.appendf("Connecting(%p) [%d,%d] to ",this,ClientCount,MaxClientCount);
  2931. s.append(peerName);
  2932. PROGLOG("%s", s.str());
  2933. }
  2934. }
  2935. parent = _parent;
  2936. left = 0;
  2937. msg.setEndian(__BIG_ENDIAN);
  2938. selecthandled = false;
  2939. touch();
  2940. }
  2941. ~CRemoteClientHandler()
  2942. {
  2943. {
  2944. CriticalBlock block(ClientCountSect);
  2945. ClientCount--;
  2946. if (TF_TRACE_CLIENT_CONN) {
  2947. PROGLOG("Disconnecting(%p) [%d,%d] ",this,ClientCount,MaxClientCount);
  2948. }
  2949. }
  2950. ISocket *sock = socket.getClear();
  2951. try {
  2952. sock->Release();
  2953. }
  2954. catch (IException *e) {
  2955. EXCLOG(e,"~CRemoteClientHandler");
  2956. e->Release();
  2957. }
  2958. }
  2959. bool notifySelected(ISocket *sock,unsigned selected)
  2960. {
  2961. if (TF_TRACE_FULL)
  2962. PROGLOG("notifySelected(%p)",this);
  2963. if (sock!=socket)
  2964. WARNLOG("notifySelected - invalid socket passed");
  2965. size32_t avail = (size32_t)socket->avail_read();
  2966. if (avail)
  2967. touch();
  2968. if (left==0)
  2969. {
  2970. try
  2971. {
  2972. left = avail?receiveBufferSize(socket):0;
  2973. }
  2974. catch (IException *e)
  2975. {
  2976. EXCLOG(e,"notifySelected(1)");
  2977. e->Release();
  2978. left = 0;
  2979. }
  2980. if (left)
  2981. {
  2982. avail = (size32_t)socket->avail_read();
  2983. try
  2984. {
  2985. msg.ensureCapacity(left);
  2986. }
  2987. catch (IException *e)
  2988. {
  2989. EXCLOG(e,"notifySelected(2)");
  2990. e->Release();
  2991. left = 0;
  2992. // if too big then corrupted packet so read avail to try and consume
  2993. char fbuf[1024];
  2994. while (avail)
  2995. {
  2996. size32_t rd = avail>sizeof(fbuf)?sizeof(fbuf):avail;
  2997. try
  2998. {
  2999. socket->read(fbuf, rd); // don't need timeout here
  3000. avail -= rd;
  3001. }
  3002. catch (IException *e)
  3003. {
  3004. EXCLOG(e,"notifySelected(2) flush");
  3005. e->Release();
  3006. break;
  3007. }
  3008. }
  3009. avail = 0;
  3010. left = 0;
  3011. }
  3012. }
  3013. }
  3014. size32_t toread = left>avail?avail:left;
  3015. if (toread)
  3016. {
  3017. try
  3018. {
  3019. socket->read(msg.reserve(toread), toread); // don't need timeout here
  3020. }
  3021. catch (IException *e)
  3022. {
  3023. EXCLOG(e,"notifySelected(3)");
  3024. e->Release();
  3025. toread = left;
  3026. msg.clear();
  3027. }
  3028. }
  3029. if (TF_TRACE_FULL)
  3030. PROGLOG("notifySelected %d,%d",toread,left);
  3031. if ((left!=0)&&(avail==0))
  3032. {
  3033. WARNLOG("notifySelected: Closing mid packet, %d remaining", left);
  3034. toread = left;
  3035. msg.clear();
  3036. }
  3037. left -= toread;
  3038. if (left==0)
  3039. {
  3040. // DEBUG
  3041. parent->notify(this, msg); // consumes msg
  3042. }
  3043. return false;
  3044. }
  3045. void logPrevHandle()
  3046. {
  3047. if (previdx<opennames.ordinality())
  3048. PROGLOG("Previous handle(%d): %s",handles.item(previdx),opennames.item(previdx).text.get());
  3049. }
  3050. bool throttleCommand(MemoryBuffer &msg)
  3051. {
  3052. RemoteFileCommandType cmd = RFCunknown;
  3053. Owned<IException> e;
  3054. try
  3055. {
  3056. msg.read(cmd);
  3057. parent->throttleCommand(cmd, msg, this);
  3058. return true;
  3059. }
  3060. catch (IException *_e)
  3061. {
  3062. e.setown(_e);
  3063. }
  3064. /* processCommand() will handle most exception and replies,
  3065. * but if throttleCommand fails before it gets that far, this will handle
  3066. */
  3067. MemoryBuffer reply;
  3068. initSendBuffer(reply);
  3069. StringBuffer s;
  3070. e->errorMessage(s);
  3071. appendCmdErr(reply, cmd, e->errorCode(), s.str());
  3072. parent->appendError(cmd, this, cmd, reply);
  3073. sendBuffer(socket, reply);
  3074. return false;
  3075. }
  3076. void processCommand(RemoteFileCommandType cmd, MemoryBuffer &msg, CThrottler *throttler)
  3077. {
  3078. MemoryBuffer reply;
  3079. parent->processCommand(cmd, msg, initSendBuffer(reply), this, throttler);
  3080. sendBuffer(socket, reply);
  3081. }
  3082. bool immediateCommand() // returns false if socket closed or failure
  3083. {
  3084. MemoryBuffer msg;
  3085. msg.setEndian(__BIG_ENDIAN);
  3086. touch();
  3087. size32_t avail = (size32_t)socket->avail_read();
  3088. if (avail==0)
  3089. return false;
  3090. receiveBuffer(socket, msg, 5); // shouldn't timeout as data is available
  3091. touch();
  3092. if (msg.length()==0)
  3093. return false;
  3094. return throttleCommand(msg);
  3095. }
  3096. void process(MemoryBuffer &msg)
  3097. {
  3098. if (selecthandled)
  3099. throttleCommand(msg);
  3100. else
  3101. {
  3102. // msg only used/filled if process() has been triggered by notify()
  3103. while (parent->threadRunningCount()<=parent->targetActiveThreads) // if too many threads add to select handler
  3104. {
  3105. int w;
  3106. try
  3107. {
  3108. w = socket->wait_read(1000);
  3109. }
  3110. catch (IException *e)
  3111. {
  3112. EXCLOG(e, "CRemoteClientHandler::main wait_read error");
  3113. e->Release();
  3114. parent->onCloseSocket(this,1);
  3115. return;
  3116. }
  3117. if (w==0)
  3118. break;
  3119. if ((w<0)||!immediateCommand())
  3120. {
  3121. if (w<0)
  3122. WARNLOG("CRemoteClientHandler::main wait_read error");
  3123. parent->onCloseSocket(this,1);
  3124. return;
  3125. }
  3126. }
  3127. /* This is a bit confusing..
  3128. * The addClient below, adds this request to a selecthandler handled by another thread
  3129. * and passes ownership of 'this' (CRemoteClientHandler)
  3130. *
  3131. * When notified, the selecthandler will launch a new pool thread to handle the request
  3132. * If the pool thread limit is hit, the selecthandler will be blocked [ see comment in CRemoteFileServer::notify() ]
  3133. *
  3134. * Either way, a thread pool slot is occupied when processing a request.
  3135. * Blocked threads, will be blocked for up to 1 minute (as defined by createThreadPool call)
  3136. * IOW, if there are lots of incoming clients that can't be serviced by the CThrottler limit,
  3137. * a large number of pool threads will build up after a while.
  3138. *
  3139. * The CThrottler mechanism, imposes a further hard limit on how many concurrent request threads can be active.
  3140. * If the thread pool had an absolute limit (instead of just introducing a delay), then I don't see the point
  3141. * in this additional layer of throttling..
  3142. */
  3143. selecthandled = true;
  3144. parent->addClient(this); // add to select handler
  3145. // NB: this (CRemoteClientHandler) is now linked by the selecthandler and owned by the 'clients' list
  3146. }
  3147. }
  3148. bool timedOut()
  3149. {
  3150. return (msTick()-lasttick)>CLIENT_TIMEOUT;
  3151. }
  3152. bool inactiveTimedOut()
  3153. {
  3154. unsigned ms = msTick();
  3155. if ((ms-lastInactiveTick)>CLIENT_INACTIVEWARNING_TIMEOUT)
  3156. {
  3157. lastInactiveTick = ms;
  3158. return true;
  3159. }
  3160. return false;
  3161. }
  3162. void touch()
  3163. {
  3164. lastInactiveTick = lasttick = msTick();
  3165. atomic_set(&globallasttick,lasttick);
  3166. }
  3167. const char *queryPeerName()
  3168. {
  3169. return peerName;
  3170. }
  3171. bool getInfo(StringBuffer &str)
  3172. {
  3173. str.append("client(");
  3174. const char *name = queryPeerName();
  3175. bool ok;
  3176. if (name)
  3177. {
  3178. ok = true;
  3179. str.append(name);
  3180. }
  3181. else
  3182. ok = false;
  3183. unsigned ms = msTick();
  3184. str.appendf("): last touch %d ms ago (%d, %d)",ms-lasttick,lasttick,ms);
  3185. ForEachItemIn(i,handles) {
  3186. str.appendf("\n %d: ",handles.item(i));
  3187. str.append(opennames.item(i).text);
  3188. }
  3189. return ok;
  3190. }
  3191. };
  3192. class CThrottleQueueItem : public CSimpleInterface
  3193. {
  3194. public:
  3195. RemoteFileCommandType cmd;
  3196. Linked<CRemoteClientHandler> client;
  3197. MemoryBuffer msg;
  3198. CCycleTimer timer;
  3199. CThrottleQueueItem(RemoteFileCommandType _cmd, MemoryBuffer &_msg, CRemoteClientHandler *_client) : cmd(_cmd), client(_client)
  3200. {
  3201. msg.swapWith(_msg);
  3202. }
  3203. };
  3204. class CThrottler
  3205. {
  3206. Semaphore sem;
  3207. CriticalSection crit, configureCrit;
  3208. StringAttr title;
  3209. unsigned limit, delayMs, cpuThreshold, queueLimit;
  3210. unsigned disabledLimit;
  3211. unsigned __int64 totalThrottleDelay;
  3212. CCycleTimer totalThrottleDelayTimer;
  3213. QueueOf<CThrottleQueueItem, false> queue;
  3214. unsigned statsIntervalSecs;
  3215. public:
  3216. CThrottler(const char *_title) : title(_title)
  3217. {
  3218. totalThrottleDelay = 0;
  3219. limit = 0;
  3220. delayMs = DEFAULT_STDCMD_THROTTLEDELAYMS;
  3221. cpuThreshold = DEFAULT_STDCMD_THROTTLECPULIMIT;
  3222. disabledLimit = 0;
  3223. queueLimit = DEFAULT_STDCMD_THROTTLEQUEUELIMIT;
  3224. statsIntervalSecs = DEFAULT_STDCMD_THROTTLECPULIMIT;
  3225. }
  3226. ~CThrottler()
  3227. {
  3228. for (;;)
  3229. {
  3230. Owned<CThrottleQueueItem> item = queue.dequeue();
  3231. if (!item)
  3232. break;
  3233. }
  3234. }
  3235. unsigned queryLimit() const { return limit; }
  3236. unsigned queryDelayMs() const { return delayMs; };;
  3237. unsigned queryCpuThreshold() const { return cpuThreshold; }
  3238. unsigned queryQueueLimit() const { return queueLimit; }
  3239. StringBuffer &getInfoSummary(StringBuffer &info)
  3240. {
  3241. info.appendf("Throttler(%s) - limit=%u, delayMs=%u, cpuThreshold=%u, queueLimit=%u", title.get(), limit, delayMs, cpuThreshold, queueLimit).newline();
  3242. unsigned elapsedSecs = totalThrottleDelayTimer.elapsedMs()/1000;
  3243. time_t simple;
  3244. time(&simple);
  3245. simple -= elapsedSecs;
  3246. CDateTime dt;
  3247. dt.set(simple);
  3248. StringBuffer dateStr;
  3249. dt.getTimeString(dateStr, true);
  3250. info.appendf("Throttler(%s): statistics since %s", title.get(), dateStr.str()).newline();
  3251. info.appendf("Total delay of %0.2f seconds", ((double)totalThrottleDelay)/1000).newline();
  3252. info.appendf("Requests currently queued: %u", queue.ordinality());
  3253. return info;
  3254. }
  3255. void getInfo(StringBuffer &info)
  3256. {
  3257. CriticalBlock b(crit);
  3258. getInfoSummary(info).newline();
  3259. }
  3260. void configure(unsigned _limit, unsigned _delayMs, unsigned _cpuThreshold, unsigned _queueLimit)
  3261. {
  3262. if (_limit > THROTTLE_MAX_LIMIT || _delayMs > THROTTLE_MAX_DELAYMS || _cpuThreshold > THROTTLE_MAX_CPUTHRESHOLD || _queueLimit > THROTTLE_MAX_QUEUELIMIT)
  3263. 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)",
  3264. title.str(), _limit, THROTTLE_MAX_LIMIT, _delayMs, THROTTLE_MAX_DELAYMS, _cpuThreshold,
  3265. THROTTLE_MAX_CPUTHRESHOLD, _queueLimit, THROTTLE_MAX_QUEUELIMIT);
  3266. CriticalBlock b(configureCrit);
  3267. int delta = 0;
  3268. if (_limit)
  3269. {
  3270. if (disabledLimit) // if transitioning from disabled to some throttling
  3271. {
  3272. assertex(0 == limit);
  3273. delta = _limit - disabledLimit; // + or -
  3274. disabledLimit = 0;
  3275. }
  3276. else
  3277. delta = _limit - limit; // + or -
  3278. }
  3279. else if (0 == disabledLimit)
  3280. {
  3281. PROGLOG("Throttler(%s): disabled, previous limit: %u", title.get(), limit);
  3282. /* disabling - set limit immediately to let all new transaction through.
  3283. * NB: the semaphore signals are not consumed in this case, because transactions could be waiting on it.
  3284. * Instead the existing 'limit' is kept in 'disabledLimit', so that if/when throttling is
  3285. * re-enabled, it is used as a basis for increasing or consuming the semaphore signal count.
  3286. */
  3287. disabledLimit = limit;
  3288. limit = 0;
  3289. }
  3290. if (delta > 0)
  3291. {
  3292. PROGLOG("Throttler(%s): Increasing limit from %u to %u", title.get(), limit, _limit);
  3293. sem.signal(delta);
  3294. limit = _limit;
  3295. // NB: If throttling was off, this doesn't effect transactions in progress, i.e. will only throttle new transactions coming in.
  3296. }
  3297. else if (delta < 0)
  3298. {
  3299. PROGLOG("Throttler(%s): Reducing limit from %u to %u", title.get(), limit, _limit);
  3300. // NB: This is not expected to take long
  3301. CCycleTimer timer;
  3302. while (delta < 0)
  3303. {
  3304. if (sem.wait(1000))
  3305. ++delta;
  3306. else
  3307. 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);
  3308. }
  3309. limit = _limit;
  3310. // NB: doesn't include transactions in progress, i.e. will only throttle new transactions coming in.
  3311. }
  3312. if (_delayMs != delayMs)
  3313. {
  3314. PROGLOG("Throttler(%s): New delayMs=%u, previous: %u", title.get(), _delayMs, delayMs);
  3315. delayMs = _delayMs;
  3316. }
  3317. if (_cpuThreshold != cpuThreshold)
  3318. {
  3319. PROGLOG("Throttler(%s): New cpuThreshold=%u, previous: %u", title.get(), _cpuThreshold, cpuThreshold);
  3320. cpuThreshold = _cpuThreshold;
  3321. }
  3322. if (((unsigned)-1) != _queueLimit && _queueLimit != queueLimit)
  3323. {
  3324. PROGLOG("Throttler(%s): New queueLimit=%u%s, previous: %u", title.get(), _queueLimit, 0==_queueLimit?"(disabled)":"", queueLimit);
  3325. queueLimit = _queueLimit;
  3326. }
  3327. }
  3328. void setStatsInterval(unsigned _statsIntervalSecs)
  3329. {
  3330. if (_statsIntervalSecs != statsIntervalSecs)
  3331. {
  3332. PROGLOG("Throttler(%s): New statsIntervalSecs=%u, previous: %u", title.get(), _statsIntervalSecs, statsIntervalSecs);
  3333. statsIntervalSecs = _statsIntervalSecs;
  3334. }
  3335. }
  3336. void take(RemoteFileCommandType cmd) // cmd for info. only
  3337. {
  3338. for (;;)
  3339. {
  3340. if (sem.wait(delayMs))
  3341. return;
  3342. PROGLOG("Throttler(%s): transaction delayed [cmd=%s]", title.get(), getRFCText(cmd));
  3343. }
  3344. }
  3345. void release()
  3346. {
  3347. sem.signal();
  3348. }
  3349. StringBuffer &getStats(StringBuffer &stats, bool reset)
  3350. {
  3351. CriticalBlock b(crit);
  3352. getInfoSummary(stats);
  3353. if (reset)
  3354. {
  3355. totalThrottleDelayTimer.reset();
  3356. totalThrottleDelay = 0;
  3357. }
  3358. return stats;
  3359. }
  3360. void addCommand(RemoteFileCommandType cmd, MemoryBuffer &msg, CRemoteClientHandler *client)
  3361. {
  3362. CCycleTimer timer;
  3363. Owned<IException> exception;
  3364. bool hadSem = true;
  3365. if (!sem.wait(delayMs))
  3366. {
  3367. CriticalBlock b(crit);
  3368. if (!sem.wait(0)) // check hasn't become available
  3369. {
  3370. unsigned cpu = getLatestCPUUsage();
  3371. if (getLatestCPUUsage()<cpuThreshold)
  3372. {
  3373. /* Allow to proceed, despite hitting throttle limit because CPU < threshold
  3374. * NB: The overall number of threads is still capped by the thread pool.
  3375. */
  3376. unsigned ms = timer.elapsedMs();
  3377. totalThrottleDelay += ms;
  3378. PROGLOG("Throttler(%s): transaction delayed [cmd=%s] for : %u milliseconds, proceeding as cpu(%u)<throttleCPULimit(%u)", title.get(), getRFCText(cmd), cpu, ms, cpuThreshold);
  3379. hadSem = false;
  3380. }
  3381. else
  3382. {
  3383. if (queueLimit && queue.ordinality()>=queueLimit)
  3384. throw MakeStringException(0, "Throttler(%s), the maxiumum number of items are queued (%u), rejecting new command[%s]", title.str(), queue.ordinality(), getRFCText(cmd));
  3385. queue.enqueue(new CThrottleQueueItem(cmd, msg, client)); // NB: takes over ownership of 'client' from running thread
  3386. PROGLOG("Throttler(%s): transaction delayed [cmd=%s], queuing (%u queueud), [client=%p, sock=%u]", title.get(), getRFCText(cmd), queue.ordinality(), client, client->socket->OShandle());
  3387. return;
  3388. }
  3389. }
  3390. }
  3391. /* Guarantee that sem is released.
  3392. * Should normally release on clean exit when queue is empty.
  3393. */
  3394. struct ReleaseSem
  3395. {
  3396. Semaphore *sem;
  3397. ReleaseSem(Semaphore *_sem) { sem = _sem; }
  3398. ~ReleaseSem() { if (sem) sem->signal(); }
  3399. } releaseSem(hadSem?&sem:NULL);
  3400. /* Whilst holding on this throttle slot (i.e. before signalling semaphore back), process
  3401. * queued items. NB: other threads that are finishing will do also.
  3402. * Queued items are processed 1st, then the current request, then anything that was queued when handling current request
  3403. * Throttle slot (semaphore) is only given back when no more to do.
  3404. */
  3405. Linked<CRemoteClientHandler> currentClient;
  3406. MemoryBuffer currentMsg;
  3407. unsigned ms;
  3408. for (;;)
  3409. {
  3410. RemoteFileCommandType currentCmd;
  3411. {
  3412. CriticalBlock b(crit);
  3413. Owned<CThrottleQueueItem> item = queue.dequeue();
  3414. if (item)
  3415. {
  3416. currentCmd = item->cmd;
  3417. currentClient.setown(item->client.getClear());
  3418. currentMsg.swapWith(item->msg);
  3419. ms = item->timer.elapsedMs();
  3420. }
  3421. else
  3422. {
  3423. if (NULL == client) // previously handled and queue empty
  3424. {
  3425. /* Commands are only queued if semaphore is exhaused (checked inside crit)
  3426. * so only signal the semaphore inside the crit, after checking if there are no queued items
  3427. */
  3428. if (hadSem)
  3429. {
  3430. releaseSem.sem = NULL;
  3431. sem.signal();
  3432. }
  3433. break;
  3434. }
  3435. currentCmd = cmd;
  3436. currentClient.set(client); // process current request after dealing with queue
  3437. currentMsg.swapWith(msg);
  3438. ms = timer.elapsedMs();
  3439. client = NULL;
  3440. }
  3441. }
  3442. if (ms >= 1000)
  3443. {
  3444. if (ms>delayMs)
  3445. PROGLOG("Throttler(%s): transaction delayed [cmd=%s] for : %u seconds", title.get(), getRFCText(currentCmd), ms/1000);
  3446. }
  3447. {
  3448. CriticalBlock b(crit);
  3449. totalThrottleDelay += ms;
  3450. }
  3451. try
  3452. {
  3453. currentClient->processCommand(currentCmd, currentMsg, this);
  3454. }
  3455. catch (IException *e)
  3456. {
  3457. EXCLOG(e, "addCommand: processCommand failed");
  3458. e->Release();
  3459. }
  3460. }
  3461. }
  3462. };
  3463. // temporarily release a throttler slot
  3464. class CThrottleReleaseBlock
  3465. {
  3466. CThrottler &throttler;
  3467. RemoteFileCommandType cmd;
  3468. public:
  3469. CThrottleReleaseBlock(CThrottler &_throttler, RemoteFileCommandType _cmd) : throttler(_throttler), cmd(_cmd)
  3470. {
  3471. throttler.release();
  3472. }
  3473. ~CThrottleReleaseBlock()
  3474. {
  3475. throttler.take(cmd);
  3476. }
  3477. };
  3478. int lasthandle;
  3479. CriticalSection sect;
  3480. Owned<ISocket> acceptsock;
  3481. Owned<ISocket> rejectsock;//used to immediately reject nonsecure connection requests when in secure mode
  3482. Owned<ISocketSelectHandler> selecthandler;
  3483. Owned<IThreadPool> threads; // for commands
  3484. bool stopping;
  3485. unsigned clientcounttick;
  3486. unsigned closedclients;
  3487. CAsyncCommandManager asyncCommandManager;
  3488. CThrottler stdCmdThrottler, slowCmdThrottler;
  3489. CClientStatsTable clientStatsTable;
  3490. atomic_t globallasttick;
  3491. unsigned targetActiveThreads;
  3492. int getNextHandle()
  3493. {
  3494. // called in sect critical block
  3495. for (;;) {
  3496. if (lasthandle==INT_MAX)
  3497. lasthandle = 1;
  3498. else
  3499. lasthandle++;
  3500. unsigned idx1;
  3501. unsigned idx2;
  3502. if (!findHandle(lasthandle,idx1,idx2))
  3503. return lasthandle;
  3504. }
  3505. }
  3506. bool findHandle(int handle,unsigned &clientidx,unsigned &handleidx)
  3507. {
  3508. // called in sect critical block
  3509. clientidx = (unsigned)-1;
  3510. handleidx = (unsigned)-1;
  3511. ForEachItemIn(i,clients) {
  3512. CRemoteClientHandler &client = clients.item(i);
  3513. ForEachItemIn(j,client.handles) {
  3514. if (client.handles.item(j)==handle) {
  3515. handleidx = j;
  3516. clientidx = i;
  3517. return true;
  3518. }
  3519. }
  3520. }
  3521. return false;
  3522. }
  3523. class cCommandProcessor: public CInterface, implements IPooledThread
  3524. {
  3525. Owned<CRemoteClientHandler> client;
  3526. MemoryBuffer msg;
  3527. public:
  3528. IMPLEMENT_IINTERFACE;
  3529. struct cCommandProcessorParams
  3530. {
  3531. cCommandProcessorParams() { msg.setEndian(__BIG_ENDIAN); }
  3532. CRemoteClientHandler *client;
  3533. MemoryBuffer msg;
  3534. };
  3535. void init(void *_params)
  3536. {
  3537. cCommandProcessorParams &params = *(cCommandProcessorParams *)_params;
  3538. client.setown(params.client);
  3539. msg.swapWith(params.msg);
  3540. }
  3541. void main()
  3542. {
  3543. // idea is that initially we process commands inline then pass over to select handler
  3544. try
  3545. {
  3546. client->process(msg);
  3547. }
  3548. catch (IException *e)
  3549. {
  3550. // suppress some errors
  3551. EXCLOG(e,"cCommandProcessor::main");
  3552. e->Release();
  3553. }
  3554. try
  3555. {
  3556. client.clear();
  3557. }
  3558. catch (IException *e)
  3559. {
  3560. // suppress some more errors clearing client
  3561. EXCLOG(e,"cCommandProcessor::main(2)");
  3562. e->Release();
  3563. }
  3564. }
  3565. bool stop()
  3566. {
  3567. return true;
  3568. }
  3569. bool canReuse()
  3570. {
  3571. return false; // want to free owned socket
  3572. }
  3573. };
  3574. IArrayOf<CRemoteClientHandler> clients;
  3575. class cImpersonateBlock
  3576. {
  3577. CRemoteClientHandler &client;
  3578. public:
  3579. cImpersonateBlock(CRemoteClientHandler &_client)
  3580. : client(_client)
  3581. {
  3582. if (client.user.get()) {
  3583. if (TF_TRACE)
  3584. PROGLOG("Impersonate user: %s",client.user->username());
  3585. client.user->impersonate();
  3586. }
  3587. }
  3588. ~cImpersonateBlock()
  3589. {
  3590. if (client.user.get()) {
  3591. if (TF_TRACE)
  3592. PROGLOG("Stop impersonating user: %s",client.user->username());
  3593. client.user->revert();
  3594. }
  3595. }
  3596. };
  3597. #define IMPERSONATE_USER(client) cImpersonateBlock ublock(client)
  3598. public:
  3599. IMPLEMENT_IINTERFACE
  3600. CRemoteFileServer(unsigned maxThreads, unsigned maxThreadsDelayMs, unsigned maxAsyncCopy)
  3601. : asyncCommandManager(maxAsyncCopy), stdCmdThrottler("stdCmdThrotlter"), slowCmdThrottler("slowCmdThrotlter")
  3602. {
  3603. lasthandle = 0;
  3604. selecthandler.setown(createSocketSelectHandler(NULL));
  3605. stdCmdThrottler.configure(DEFAULT_STDCMD_PARALLELREQUESTLIMIT, DEFAULT_STDCMD_THROTTLEDELAYMS, DEFAULT_STDCMD_THROTTLECPULIMIT, DEFAULT_STDCMD_THROTTLEQUEUELIMIT);
  3606. slowCmdThrottler.configure(DEFAULT_SLOWCMD_PARALLELREQUESTLIMIT, DEFAULT_SLOWCMD_THROTTLEDELAYMS, DEFAULT_SLOWCMD_THROTTLECPULIMIT, DEFAULT_SLOWCMD_THROTTLEQUEUELIMIT);
  3607. unsigned targetMinThreads=maxThreads*20/100; // 20%
  3608. if (0 == targetMinThreads) targetMinThreads = 1;
  3609. targetActiveThreads=maxThreads*80/100; // 80%
  3610. if (0 == targetActiveThreads) targetActiveThreads = 1;
  3611. class CCommandFactory : public CSimpleInterfaceOf<IThreadFactory>
  3612. {
  3613. CRemoteFileServer &parent;
  3614. public:
  3615. CCommandFactory(CRemoteFileServer &_parent) : parent(_parent) { }
  3616. virtual IPooledThread *createNew()
  3617. {
  3618. return parent.createCommandProcessor();
  3619. }
  3620. };
  3621. Owned<IThreadFactory> factory = new CCommandFactory(*this); // NB: pool links factory, so takes ownership
  3622. threads.setown(createThreadPool("CRemoteFileServerPool", factory, NULL, maxThreads, maxThreadsDelayMs,
  3623. #ifdef __64BIT__
  3624. 0, // Unlimited stack size
  3625. #else
  3626. 0x10000,
  3627. #endif
  3628. INFINITE,targetMinThreads));
  3629. threads->setStartDelayTracing(60); // trace amount delayed every minute.
  3630. PROGLOG("CRemoteFileServer: maxThreads = %u, maxThreadsDelayMs = %u, maxAsyncCopy = %u", maxThreads, maxThreadsDelayMs, maxAsyncCopy);
  3631. stopping = false;
  3632. clientcounttick = msTick();
  3633. closedclients = 0;
  3634. atomic_set(&globallasttick,msTick());
  3635. }
  3636. ~CRemoteFileServer()
  3637. {
  3638. #ifdef _DEBUG
  3639. PROGLOG("Exiting CRemoteFileServer");
  3640. #endif
  3641. asyncCommandManager.join();
  3642. clients.kill();
  3643. #ifdef _DEBUG
  3644. PROGLOG("Exited CRemoteFileServer");
  3645. #endif
  3646. }
  3647. //MORE: The file handles should timeout after a while, and accessing an old (invalid handle)
  3648. // should throw a different exception
  3649. bool checkFileIOHandle(MemoryBuffer &reply, int handle, IFileIO *&fileio, bool del=false)
  3650. {
  3651. CriticalBlock block(sect);
  3652. fileio = NULL;
  3653. if (handle<=0) {
  3654. appendErr(reply, RFSERR_NullFileIOHandle);
  3655. return false;
  3656. }
  3657. unsigned clientidx;
  3658. unsigned handleidx;
  3659. if (findHandle(handle,clientidx,handleidx)) {
  3660. CRemoteClientHandler &client = clients.item(clientidx);
  3661. if (del) {
  3662. client.handles.remove(handleidx);
  3663. client.openfiles.remove(handleidx);
  3664. client.opennames.remove(handleidx);
  3665. client.previdx = (unsigned)-1;
  3666. }
  3667. else {
  3668. fileio = &client.openfiles.item(handleidx);
  3669. client.previdx = handleidx;
  3670. }
  3671. return true;
  3672. }
  3673. appendErr(reply, RFSERR_InvalidFileIOHandle);
  3674. return false;
  3675. }
  3676. void onCloseSocket(CRemoteClientHandler *client, int which)
  3677. {
  3678. if (!client)
  3679. return;
  3680. CriticalBlock block(sect);
  3681. #ifdef _DEBUG
  3682. StringBuffer s(client->queryPeerName());
  3683. PROGLOG("onCloseSocket(%d) %s",which,s.str());
  3684. #endif
  3685. if (client->socket)
  3686. {
  3687. try
  3688. {
  3689. /* JCSMORE - shouldn't this really be dependent on whether selecthandled=true
  3690. * It has not been added to the selecthandler
  3691. * Harmless, but wasteful if so.
  3692. */
  3693. selecthandler->remove(client->socket);
  3694. }
  3695. catch (IException *e) {
  3696. EXCLOG(e,"CRemoteFileServer::onCloseSocket.1");
  3697. e->Release();
  3698. }
  3699. }
  3700. try {
  3701. clients.zap(*client);
  3702. }
  3703. catch (IException *e) {
  3704. EXCLOG(e,"CRemoteFileServer::onCloseSocket.2");
  3705. e->Release();
  3706. }
  3707. }
  3708. bool cmdOpenFileIO(MemoryBuffer & msg, MemoryBuffer & reply, CRemoteClientHandler &client)
  3709. {
  3710. IMPERSONATE_USER(client);
  3711. Owned<StringAttrItem> name = new StringAttrItem;
  3712. byte mode;
  3713. byte share;
  3714. msg.read(name->text).read(mode).read(share);
  3715. // also try to recv extra byte
  3716. byte extra = 0;
  3717. unsigned short sMode = IFUnone;
  3718. unsigned short cFlags = IFUnone;
  3719. if (msg.remaining() >= sizeof(byte))
  3720. {
  3721. msg.read(extra);
  3722. // and then try to recv extra sMode, cFlags (always sent together)
  3723. if (msg.remaining() >= (sizeof(sMode) + sizeof(cFlags)))
  3724. msg.read(sMode).read(cFlags);
  3725. }
  3726. IFEflags extraFlags = (IFEflags)extra;
  3727. // none => nocache for remote (hint)
  3728. // can revert to previous behavior with conf file setting "allow_pgcache_flush=false"
  3729. if (extraFlags == IFEnone)
  3730. extraFlags = IFEnocache;
  3731. Owned<IFile> file = createIFile(name->text);
  3732. switch ((compatIFSHmode)share) {
  3733. case compatIFSHnone:
  3734. file->setCreateFlags(S_IRUSR|S_IWUSR);
  3735. file->setShareMode(IFSHnone);
  3736. break;
  3737. case compatIFSHread:
  3738. file->setShareMode(IFSHread);
  3739. break;
  3740. case compatIFSHwrite:
  3741. file->setShareMode(IFSHfull);
  3742. break;
  3743. case compatIFSHexec:
  3744. file->setCreateFlags(S_IRUSR|S_IWUSR|S_IXUSR|S_IRGRP|S_IXGRP|S_IROTH|S_IXOTH);
  3745. break;
  3746. case compatIFSHall:
  3747. file->setCreateFlags(S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH|S_IWOTH); // bit excessive
  3748. file->setShareMode(IFSHfull);
  3749. break;
  3750. }
  3751. // use sMode, cFlags if sent
  3752. if (sMode != IFUnone && cFlags != IFUnone)
  3753. {
  3754. file->setCreateFlags(cFlags);
  3755. file->setShareMode((IFSHmode)sMode);
  3756. }
  3757. if (TF_TRACE_PRE_IO)
  3758. PROGLOG("before open file '%s', (%d,%d,%d,%d,0%o)",name->text.get(),(int)mode,(int)share,extraFlags,sMode,cFlags);
  3759. IFileIO *fileio = file->open((IFOmode)mode,extraFlags);
  3760. int handle;
  3761. if (fileio) {
  3762. CriticalBlock block(sect);
  3763. handle = getNextHandle();
  3764. client.previdx = client.opennames.ordinality();
  3765. client.handles.append(handle);
  3766. client.openfiles.append(*fileio);
  3767. client.opennames.append(*name.getLink());
  3768. }
  3769. else
  3770. handle = 0;
  3771. reply.append(RFEnoerror);
  3772. reply.append(handle);
  3773. if (TF_TRACE)
  3774. PROGLOG("open file '%s', (%d,%d) handle = %d",name->text.get(),(int)mode,(int)share,handle);
  3775. return true;
  3776. }
  3777. bool cmdCloseFileIO(MemoryBuffer & msg, MemoryBuffer & reply)
  3778. {
  3779. int handle;
  3780. msg.read(handle);
  3781. IFileIO *fileio;
  3782. if (!checkFileIOHandle(reply, handle, fileio, true))
  3783. return false;
  3784. if (TF_TRACE)
  3785. PROGLOG("close file, handle = %d",handle);
  3786. reply.append(RFEnoerror);
  3787. return true;
  3788. }
  3789. bool cmdRead(MemoryBuffer & msg, MemoryBuffer & reply, CClientStats &stats)
  3790. {
  3791. int handle;
  3792. __int64 pos;
  3793. size32_t len;
  3794. msg.read(handle).read(pos).read(len);
  3795. IFileIO *fileio;
  3796. if (!checkFileIOHandle(reply, handle, fileio))
  3797. return false;
  3798. //arrange it so we read directly into the reply buffer...
  3799. unsigned posOfErr = reply.length();
  3800. reply.append((unsigned)RFEnoerror);
  3801. size32_t numRead;
  3802. unsigned posOfLength = reply.length();
  3803. if (TF_TRACE_PRE_IO)
  3804. PROGLOG("before read file, handle = %d, toread = %d",handle,len);
  3805. void * data;
  3806. {
  3807. reply.reserve(sizeof(numRead));
  3808. data = reply.reserve(len);
  3809. }
  3810. try {
  3811. numRead = fileio->read(pos,len,data);
  3812. }
  3813. catch (IException *e)
  3814. {
  3815. reply.setWritePos(posOfErr);
  3816. StringBuffer s;
  3817. e->errorMessage(s);
  3818. appendErr3(reply, RFSERR_ReadFailed, e->errorCode(), s.str());
  3819. e->Release();
  3820. return false;
  3821. }
  3822. stats.addRead(len);
  3823. if (TF_TRACE)
  3824. PROGLOG("read file, handle = %d, pos = %" I64F "d, toread = %d, read = %d",handle,pos,len,numRead);
  3825. {
  3826. reply.setLength(posOfLength + sizeof(numRead) + numRead);
  3827. reply.writeEndianDirect(posOfLength,sizeof(numRead),&numRead);
  3828. }
  3829. return true;
  3830. }
  3831. bool cmdSize(MemoryBuffer & msg, MemoryBuffer & reply)
  3832. {
  3833. int handle;
  3834. msg.read(handle);
  3835. IFileIO *fileio;
  3836. if (!checkFileIOHandle(reply, handle, fileio))
  3837. return false;
  3838. __int64 size = fileio->size();
  3839. reply.append((unsigned)RFEnoerror).append(size);
  3840. if (TF_TRACE)
  3841. PROGLOG("size file, handle = %d, size = %" I64F "d",handle,size);
  3842. return true;
  3843. }
  3844. bool cmdSetSize(MemoryBuffer & msg, MemoryBuffer & reply)
  3845. {
  3846. int handle;
  3847. offset_t size;
  3848. msg.read(handle).read(size);
  3849. IFileIO *fileio;
  3850. if (TF_TRACE)
  3851. PROGLOG("set size file, handle = %d, size = %" I64F "d",handle,size);
  3852. if (!checkFileIOHandle(reply, handle, fileio))
  3853. return false;
  3854. fileio->setSize(size);
  3855. reply.append((unsigned)RFEnoerror);
  3856. return true;
  3857. }
  3858. bool cmdWrite(MemoryBuffer & msg, MemoryBuffer & reply, CClientStats &stats)
  3859. {
  3860. int handle;
  3861. __int64 pos;
  3862. size32_t len;
  3863. msg.read(handle).read(pos).read(len);
  3864. IFileIO *fileio;
  3865. if (!checkFileIOHandle(reply, handle, fileio))
  3866. return false;
  3867. const byte *data = (const byte *)msg.readDirect(len);
  3868. if (TF_TRACE_PRE_IO)
  3869. PROGLOG("before write file, handle = %d, towrite = %d",handle,len);
  3870. size32_t numWritten = fileio->write(pos,len,data);
  3871. stats.addWrite(numWritten);
  3872. if (TF_TRACE)
  3873. PROGLOG("write file, handle = %d, towrite = %d, written = %d",handle,len,numWritten);
  3874. reply.append((unsigned)RFEnoerror).append(numWritten);
  3875. return true;
  3876. }
  3877. bool cmdExists(MemoryBuffer & msg, MemoryBuffer & reply, CRemoteClientHandler &client)
  3878. {
  3879. IMPERSONATE_USER(client);
  3880. StringAttr name;
  3881. msg.read(name);
  3882. if (TF_TRACE)
  3883. PROGLOG("exists, '%s'",name.get());
  3884. Owned<IFile> file=createIFile(name);
  3885. bool e = file->exists();
  3886. reply.append((unsigned)RFEnoerror).append(e);
  3887. return true;
  3888. }
  3889. bool cmdRemove(MemoryBuffer & msg, MemoryBuffer & reply,CRemoteClientHandler &client)
  3890. {
  3891. IMPERSONATE_USER(client);
  3892. StringAttr name;
  3893. msg.read(name);
  3894. if (TF_TRACE)
  3895. PROGLOG("remove, '%s'",name.get());
  3896. Owned<IFile> file=createIFile(name);
  3897. bool e = file->remove();
  3898. reply.append((unsigned)RFEnoerror).append(e);
  3899. return true;
  3900. }
  3901. bool cmdGetVer(MemoryBuffer & msg, MemoryBuffer & reply)
  3902. {
  3903. if (TF_TRACE)
  3904. PROGLOG("getVer");
  3905. if (msg.getPos()+sizeof(unsigned)>msg.length())
  3906. reply.append((unsigned)RFEnoerror);
  3907. else
  3908. reply.append((unsigned)FILESRV_VERSION+0x10000);
  3909. reply.append(VERSTRING);
  3910. return true;
  3911. }
  3912. bool cmdRename(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("rename, '%s' to '%s'",fromname.get(),toname.get());
  3921. Owned<IFile> file=createIFile(fromname);
  3922. file->rename(toname);
  3923. reply.append((unsigned)RFEnoerror);
  3924. return true;
  3925. return false;
  3926. }
  3927. bool cmdMove(MemoryBuffer & msg, MemoryBuffer & reply,CRemoteClientHandler &client)
  3928. {
  3929. IMPERSONATE_USER(client);
  3930. StringAttr fromname;
  3931. msg.read(fromname);
  3932. StringAttr toname;
  3933. msg.read(toname);
  3934. if (TF_TRACE)
  3935. PROGLOG("move, '%s' to '%s'",fromname.get(),toname.get());
  3936. Owned<IFile> file=createIFile(fromname);
  3937. file->move(toname);
  3938. reply.append((unsigned)RFEnoerror);
  3939. return true;
  3940. return false;
  3941. }
  3942. bool cmdCopy(MemoryBuffer & msg, MemoryBuffer & reply, CRemoteClientHandler &client)
  3943. {
  3944. IMPERSONATE_USER(client);
  3945. StringAttr fromname;
  3946. msg.read(fromname);
  3947. StringAttr toname;
  3948. msg.read(toname);
  3949. if (TF_TRACE)
  3950. PROGLOG("copy, '%s' to '%s'",fromname.get(),toname.get());
  3951. copyFile(toname, fromname);
  3952. reply.append((unsigned)RFEnoerror);
  3953. return true;
  3954. }
  3955. bool cmdAppend(MemoryBuffer & msg, MemoryBuffer & reply, CRemoteClientHandler &client, CClientStats &stats)
  3956. {
  3957. IMPERSONATE_USER(client);
  3958. int handle;
  3959. __int64 pos;
  3960. __int64 len;
  3961. StringAttr srcname;
  3962. msg.read(handle).read(srcname).read(pos).read(len);
  3963. IFileIO *fileio;
  3964. if (!checkFileIOHandle(reply, handle, fileio))
  3965. return false;
  3966. Owned<IFile> file = createIFile(srcname.get());
  3967. __int64 written = fileio->appendFile(file,pos,len);
  3968. stats.addWrite(written);
  3969. if (TF_TRACE)
  3970. PROGLOG("append file, handle = %d, file=%s, pos = %" I64F "d len = %" I64F "d written = %" I64F "d",handle,srcname.get(),pos,len,written);
  3971. reply.append((unsigned)RFEnoerror).append(written);
  3972. return true;
  3973. }
  3974. bool cmdIsFile(MemoryBuffer &msg, MemoryBuffer &reply, CRemoteClientHandler &client)
  3975. {
  3976. IMPERSONATE_USER(client);
  3977. StringAttr name;
  3978. msg.read(name);
  3979. if (TF_TRACE)
  3980. PROGLOG("isFile, '%s'",name.get());
  3981. Owned<IFile> file=createIFile(name);
  3982. unsigned ret = (unsigned)file->isFile();
  3983. reply.append((unsigned)RFEnoerror).append(ret);
  3984. return true;
  3985. }
  3986. bool cmdIsDir(MemoryBuffer &msg, MemoryBuffer &reply, CRemoteClientHandler &client)
  3987. {
  3988. IMPERSONATE_USER(client);
  3989. StringAttr name;
  3990. msg.read(name);
  3991. if (TF_TRACE)
  3992. PROGLOG("isDir, '%s'",name.get());
  3993. Owned<IFile> file=createIFile(name);
  3994. unsigned ret = (unsigned)file->isDirectory();
  3995. reply.append((unsigned)RFEnoerror).append(ret);
  3996. return true;
  3997. }
  3998. bool cmdIsReadOnly(MemoryBuffer &msg, MemoryBuffer &reply, CRemoteClientHandler &client)
  3999. {
  4000. IMPERSONATE_USER(client);
  4001. StringAttr name;
  4002. msg.read(name);
  4003. if (TF_TRACE)
  4004. PROGLOG("isReadOnly, '%s'",name.get());
  4005. Owned<IFile> file=createIFile(name);
  4006. unsigned ret = (unsigned)file->isReadOnly();
  4007. reply.append((unsigned)RFEnoerror).append(ret);
  4008. return true;
  4009. }
  4010. bool cmdSetReadOnly(MemoryBuffer &msg, MemoryBuffer &reply, CRemoteClientHandler &client)
  4011. {
  4012. IMPERSONATE_USER(client);
  4013. StringAttr name;
  4014. bool set;
  4015. msg.read(name).read(set);
  4016. if (TF_TRACE)
  4017. PROGLOG("setReadOnly, '%s' %d",name.get(),(int)set);
  4018. Owned<IFile> file=createIFile(name);
  4019. file->setReadOnly(set);
  4020. reply.append((unsigned)RFEnoerror);
  4021. return true;
  4022. }
  4023. bool cmdSetFilePerms(MemoryBuffer &msg, MemoryBuffer &reply, CRemoteClientHandler &client)
  4024. {
  4025. IMPERSONATE_USER(client);
  4026. StringAttr name;
  4027. unsigned fPerms;
  4028. msg.read(name).read(fPerms);
  4029. if (TF_TRACE)
  4030. PROGLOG("setFilePerms, '%s' 0%o",name.get(),fPerms);
  4031. Owned<IFile> file=createIFile(name);
  4032. file->setFilePermissions(fPerms);
  4033. reply.append((unsigned)RFEnoerror);
  4034. return true;
  4035. }
  4036. bool cmdGetTime(MemoryBuffer &msg, MemoryBuffer &reply, CRemoteClientHandler &client)
  4037. {
  4038. IMPERSONATE_USER(client);
  4039. StringAttr name;
  4040. msg.read(name);
  4041. if (TF_TRACE)
  4042. PROGLOG("getTime, '%s'",name.get());
  4043. Owned<IFile> file=createIFile(name);
  4044. CDateTime createTime;
  4045. CDateTime modifiedTime;
  4046. CDateTime accessedTime;
  4047. bool ret = file->getTime(&createTime,&modifiedTime,&accessedTime);
  4048. reply.append((unsigned)RFEnoerror).append(ret);
  4049. if (ret) {
  4050. createTime.serialize(reply);
  4051. modifiedTime.serialize(reply);
  4052. accessedTime.serialize(reply);
  4053. }
  4054. return true;
  4055. }
  4056. bool cmdSetTime(MemoryBuffer &msg, MemoryBuffer &reply, CRemoteClientHandler &client)
  4057. {
  4058. IMPERSONATE_USER(client);
  4059. StringAttr name;
  4060. bool creategot;
  4061. CDateTime createTime;
  4062. bool modifiedgot;
  4063. CDateTime modifiedTime;
  4064. bool accessedgot;
  4065. CDateTime accessedTime;
  4066. msg.read(name);
  4067. msg.read(creategot);
  4068. if (creategot)
  4069. createTime.deserialize(msg);
  4070. msg.read(modifiedgot);
  4071. if (modifiedgot)
  4072. modifiedTime.deserialize(msg);
  4073. msg.read(accessedgot);
  4074. if (accessedgot)
  4075. accessedTime.deserialize(msg);
  4076. if (TF_TRACE)
  4077. PROGLOG("setTime, '%s'",name.get());
  4078. Owned<IFile> file=createIFile(name);
  4079. bool ret = file->setTime(creategot?&createTime:NULL,modifiedgot?&modifiedTime:NULL,accessedgot?&accessedTime:NULL);
  4080. reply.append((unsigned)RFEnoerror).append(ret);
  4081. return true;
  4082. }
  4083. bool cmdCreateDir(MemoryBuffer &msg, MemoryBuffer &reply, CRemoteClientHandler &client)
  4084. {
  4085. IMPERSONATE_USER(client);
  4086. StringAttr name;
  4087. msg.read(name);
  4088. if (TF_TRACE)
  4089. PROGLOG("CreateDir, '%s'",name.get());
  4090. Owned<IFile> dir=createIFile(name);
  4091. bool ret = dir->createDirectory();
  4092. reply.append((unsigned)RFEnoerror).append(ret);
  4093. return true;
  4094. }
  4095. bool cmdGetDir(MemoryBuffer &msg, MemoryBuffer &reply, CRemoteClientHandler &client)
  4096. {
  4097. IMPERSONATE_USER(client);
  4098. StringAttr name;
  4099. StringAttr mask;
  4100. bool includedir;
  4101. bool sub;
  4102. byte stream = 0;
  4103. msg.read(name).read(mask).read(includedir).read(sub);
  4104. if (msg.remaining()>=sizeof(byte)) {
  4105. msg.read(stream);
  4106. if (stream==1)
  4107. client.opendir.clear();
  4108. }
  4109. if (TF_TRACE)
  4110. PROGLOG("GetDir, '%s', '%s'",name.get(),mask.get());
  4111. Owned<IFile> dir=createIFile(name);
  4112. Owned<IDirectoryIterator> iter;
  4113. if (stream>1)
  4114. iter.set(client.opendir);
  4115. else {
  4116. iter.setown(dir->directoryFiles(mask.length()?mask.get():NULL,sub,includedir));
  4117. if (stream != 0)
  4118. client.opendir.set(iter);
  4119. }
  4120. if (!iter) {
  4121. reply.append((unsigned)RFSERR_GetDirFailed);
  4122. return false;
  4123. }
  4124. reply.append((unsigned)RFEnoerror);
  4125. if (CRemoteDirectoryIterator::serialize(reply,iter,stream?0x100000:0,stream<2)) {
  4126. if (stream != 0)
  4127. client.opendir.clear();
  4128. }
  4129. else {
  4130. bool cont=true;
  4131. reply.append(cont);
  4132. }
  4133. return true;
  4134. }
  4135. bool cmdMonitorDir(MemoryBuffer &msg, MemoryBuffer &reply, CRemoteClientHandler &client)
  4136. {
  4137. IMPERSONATE_USER(client);
  4138. StringAttr name;
  4139. StringAttr mask;
  4140. bool includedir;
  4141. bool sub;
  4142. unsigned checkinterval;
  4143. unsigned timeout;
  4144. __int64 cancelid; // not yet used
  4145. msg.read(name).read(mask).read(includedir).read(sub).read(checkinterval).read(timeout).read(cancelid);
  4146. byte isprev;
  4147. msg.read(isprev);
  4148. Owned<IDirectoryIterator> prev;
  4149. if (isprev==1) {
  4150. SocketEndpoint ep;
  4151. CRemoteDirectoryIterator *di = new CRemoteDirectoryIterator(ep,name);
  4152. di->appendBuf(msg);
  4153. prev.setown(di);
  4154. }
  4155. if (TF_TRACE)
  4156. PROGLOG("MonitorDir, '%s' '%s'",name.get(),mask.get());
  4157. Owned<IFile> dir=createIFile(name);
  4158. Owned<IDirectoryDifferenceIterator> iter=dir->monitorDirectory(prev,mask.length()?mask.get():NULL,sub,includedir,checkinterval,timeout);
  4159. reply.append((unsigned)RFEnoerror);
  4160. byte state = (iter.get()==NULL)?0:1;
  4161. reply.append(state);
  4162. if (state==1)
  4163. CRemoteDirectoryIterator::serializeDiff(reply,iter);
  4164. return true;
  4165. }
  4166. bool cmdCopySection(MemoryBuffer &msg, MemoryBuffer &reply, CRemoteClientHandler &client)
  4167. {
  4168. IMPERSONATE_USER(client);
  4169. StringAttr uuid;
  4170. StringAttr fromFile;
  4171. StringAttr toFile;
  4172. offset_t toOfs;
  4173. offset_t fromOfs;
  4174. offset_t size;
  4175. offset_t sizeDone=0;
  4176. offset_t totalSize=(offset_t)-1;
  4177. unsigned timeout;
  4178. msg.read(uuid).read(fromFile).read(toFile).read(toOfs).read(fromOfs).read(size).read(timeout);
  4179. AsyncCommandStatus status = asyncCommandManager.copySection(uuid,fromFile,toFile,toOfs,fromOfs,size,sizeDone,totalSize,timeout);
  4180. reply.append((unsigned)RFEnoerror).append((unsigned)status).append(sizeDone).append(totalSize);
  4181. return true;
  4182. }
  4183. static void treeCopyFile(RemoteFilename &srcfn, RemoteFilename &dstfn, const char *net, const char *mask, IpAddress &ip, bool usetmp, CThrottler *throttler, CFflags copyFlags=CFnone)
  4184. {
  4185. unsigned start = msTick();
  4186. Owned<IFile> dstfile = createIFile(dstfn);
  4187. // the following is really to check the dest node is up and working (otherwise not much point in continuing!)
  4188. if (dstfile->exists())
  4189. PROGLOG("TREECOPY overwriting '%s'",dstfile->queryFilename());
  4190. Owned<IFile> srcfile = createIFile(srcfn);
  4191. unsigned lastmin = 0;
  4192. if (!srcfn.queryIP().ipequals(dstfn.queryIP())) {
  4193. CriticalBlock block(treeCopyCrit);
  4194. for (;;) {
  4195. CDateTime dt;
  4196. offset_t sz;
  4197. try {
  4198. sz = srcfile->size();
  4199. if (sz==(offset_t)-1) {
  4200. if (TF_TRACE_TREE_COPY)
  4201. PROGLOG("TREECOPY source not found '%s'",srcfile->queryFilename());
  4202. break;
  4203. }
  4204. srcfile->getTime(NULL,&dt,NULL);
  4205. }
  4206. catch (IException *e) {
  4207. EXCLOG(e,"treeCopyFile(1)");
  4208. e->Release();
  4209. break;
  4210. }
  4211. Linked<CTreeCopyItem> tc;
  4212. unsigned now = msTick();
  4213. ForEachItemInRev(i1,treeCopyArray) {
  4214. CTreeCopyItem &item = treeCopyArray.item(i1);
  4215. // prune old entries (not strictly needed buf I think better)
  4216. if (now-item.lastused>TREECOPYPRUNETIME)
  4217. treeCopyArray.remove(i1);
  4218. else if (!tc.get()&&item.equals(srcfn,net,mask,sz,dt)) {
  4219. tc.set(&item);
  4220. item.lastused = now;
  4221. }
  4222. }
  4223. if (!tc.get()) {
  4224. if (treeCopyArray.ordinality()>=TREECOPY_CACHE_SIZE)
  4225. treeCopyArray.remove(0);
  4226. tc.setown(new CTreeCopyItem(srcfn,net,mask,sz,dt));
  4227. treeCopyArray.append(*tc.getLink());
  4228. }
  4229. ForEachItemInRev(cand,tc->loc) { // rev to choose copied locations first (maybe optional?)
  4230. if (!tc->busy->testSet(cand)) {
  4231. // check file accessible and matches
  4232. if (!cand&&dstfn.equals(tc->loc.item(cand))) // hmm trying to overwrite existing, better humor
  4233. continue;
  4234. bool ok = true;
  4235. Owned<IFile> rmtfile = createIFile(tc->loc.item(cand));
  4236. if (cand) { // only need to check if remote
  4237. try {
  4238. if (rmtfile->size()!=sz)
  4239. ok = false;
  4240. else {
  4241. CDateTime fdt;
  4242. rmtfile->getTime(NULL,&fdt,NULL);
  4243. ok = fdt.equals(dt);
  4244. }
  4245. }
  4246. catch (IException *e) {
  4247. EXCLOG(e,"treeCopyFile(2)");
  4248. e->Release();
  4249. ok = false;
  4250. }
  4251. }
  4252. if (ok) { // if not ok leave 'busy'
  4253. // finally lets try and copy!
  4254. try {
  4255. if (TF_TRACE_TREE_COPY)
  4256. PROGLOG("TREECOPY(started) %s to %s",rmtfile->queryFilename(),dstfile->queryFilename());
  4257. {
  4258. CriticalUnblock unblock(treeCopyCrit); // note we have tc linked
  4259. rmtfile->copyTo(dstfile,DEFAULT_COPY_BLKSIZE,NULL,usetmp,copyFlags);
  4260. }
  4261. if (TF_TRACE_TREE_COPY)
  4262. PROGLOG("TREECOPY(done) %s to %s",rmtfile->queryFilename(),dstfile->queryFilename());
  4263. tc->busy->set(cand,false);
  4264. if (treeCopyWaiting)
  4265. treeCopySem.signal((treeCopyWaiting>1)?2:1);
  4266. // add to known locations
  4267. tc->busy->set(tc->loc.ordinality(),false); // prob already is clear
  4268. tc->loc.append(dstfn);
  4269. ip.ipset(tc->loc.item(cand).queryIP());
  4270. return;
  4271. }
  4272. catch (IException *e) {
  4273. if (cand==0) {
  4274. tc->busy->set(0,false); // don't leave busy
  4275. if (treeCopyWaiting)
  4276. treeCopySem.signal();
  4277. throw; // what more can we do!
  4278. }
  4279. EXCLOG(e,"treeCopyFile(3)");
  4280. e->Release();
  4281. }
  4282. }
  4283. }
  4284. }
  4285. // all locations busy
  4286. if (msTick()-start>TREECOPYTIMEOUT) {
  4287. WARNLOG("Treecopy %s wait timed out", srcfile->queryFilename());
  4288. break;
  4289. }
  4290. treeCopyWaiting++; // note this isn't precise - just indication
  4291. {
  4292. CriticalUnblock unblock(treeCopyCrit);
  4293. if (throttler)
  4294. {
  4295. CThrottleReleaseBlock block(*throttler, RFCtreecopy);
  4296. treeCopySem.wait(TREECOPYPOLLTIME);
  4297. }
  4298. else
  4299. treeCopySem.wait(TREECOPYPOLLTIME);
  4300. }
  4301. treeCopyWaiting--;
  4302. if ((msTick()-start)/10*1000!=lastmin) {
  4303. lastmin = (msTick()-start)/10*1000;
  4304. PROGLOG("treeCopyFile delayed: %s to %s",srcfile->queryFilename(),dstfile->queryFilename());
  4305. }
  4306. }
  4307. }
  4308. else if (TF_TRACE_TREE_COPY)
  4309. PROGLOG("TREECOPY source on same node as destination");
  4310. if (TF_TRACE_TREE_COPY)
  4311. PROGLOG("TREECOPY(started,fallback) %s to %s",srcfile->queryFilename(),dstfile->queryFilename());
  4312. try {
  4313. GetHostIp(ip);
  4314. srcfile->copyTo(dstfile,DEFAULT_COPY_BLKSIZE,NULL,usetmp,copyFlags);
  4315. }
  4316. catch (IException *e) {
  4317. EXCLOG(e,"TREECOPY(done,fallback)");
  4318. throw;
  4319. }
  4320. if (TF_TRACE_TREE_COPY)
  4321. PROGLOG("TREECOPY(done,fallback) %s to %s",srcfile->queryFilename(),dstfile->queryFilename());
  4322. }
  4323. bool cmdTreeCopy(MemoryBuffer &msg, MemoryBuffer &reply, CRemoteClientHandler &client, CThrottler *throttler, bool usetmp=false)
  4324. {
  4325. IMPERSONATE_USER(client);
  4326. RemoteFilename src;
  4327. src.deserialize(msg);
  4328. RemoteFilename dst;
  4329. dst.deserialize(msg);
  4330. StringAttr net;
  4331. StringAttr mask;
  4332. msg.read(net).read(mask);
  4333. IpAddress ip;
  4334. treeCopyFile(src,dst,net,mask,ip,usetmp,throttler);
  4335. unsigned status = 0;
  4336. reply.append((unsigned)RFEnoerror).append((unsigned)status);
  4337. ip.ipserialize(reply);
  4338. return true;
  4339. }
  4340. bool cmdTreeCopyTmp(MemoryBuffer &msg, MemoryBuffer &reply, CRemoteClientHandler &client, CThrottler *throttler)
  4341. {
  4342. return cmdTreeCopy(msg, reply, client, throttler, true);
  4343. }
  4344. bool cmdGetCRC(MemoryBuffer &msg, MemoryBuffer &reply, CRemoteClientHandler &client)
  4345. {
  4346. IMPERSONATE_USER(client);
  4347. StringAttr name;
  4348. msg.read(name);
  4349. if (TF_TRACE)
  4350. PROGLOG("getCRC, '%s'",name.get());
  4351. Owned<IFile> file=createIFile(name);
  4352. unsigned ret = file->getCRC();
  4353. reply.append((unsigned)RFEnoerror).append(ret);
  4354. return true;
  4355. }
  4356. bool cmdStop(MemoryBuffer &msg, MemoryBuffer &reply)
  4357. {
  4358. PROGLOG("Abort request received");
  4359. stopping = true;
  4360. if (acceptsock)
  4361. acceptsock->cancel_accept();
  4362. if (rejectsock)
  4363. rejectsock->cancel_accept();
  4364. reply.append((unsigned)RFEnoerror);
  4365. return false;
  4366. }
  4367. bool cmdExec(MemoryBuffer &msg, MemoryBuffer &reply, CRemoteClientHandler &client)
  4368. {
  4369. StringAttr cmdline;
  4370. StringAttr workdir;
  4371. bool sync;
  4372. bool hasoutput;
  4373. size32_t insize;
  4374. MemoryAttr inbuf;
  4375. msg.read(cmdline).read(workdir).read(sync).read(hasoutput).read(insize);
  4376. if (insize)
  4377. msg.read(insize, inbuf.allocate(insize));
  4378. Owned<IPipeProcess> pipe = createPipeProcess();
  4379. int retcode=-1;
  4380. HANDLE phandle=(HANDLE)0;
  4381. MemoryBuffer outbuf;
  4382. if (pipe->run("EXEC",cmdline,workdir,insize!=0,hasoutput)) {
  4383. if (insize) {
  4384. pipe->write(insize, inbuf.get());
  4385. pipe->closeInput();
  4386. }
  4387. if (hasoutput) {
  4388. byte buf[4096];
  4389. for (;;) {
  4390. size32_t read = pipe->read(sizeof(buf),buf);
  4391. if (!read)
  4392. break;
  4393. outbuf.append(read,buf);
  4394. }
  4395. }
  4396. if (sync)
  4397. retcode = pipe->wait();
  4398. else {
  4399. phandle = pipe->getProcessHandle();
  4400. retcode = 0;
  4401. }
  4402. }
  4403. size32_t outsz = outbuf.length();
  4404. reply.append(retcode).append((unsigned)phandle).append(outsz);
  4405. if (outsz)
  4406. reply.append(outbuf);
  4407. return true;
  4408. }
  4409. bool cmdSetTrace(MemoryBuffer &msg, MemoryBuffer &reply)
  4410. {
  4411. byte flags;
  4412. msg.read(flags);
  4413. int retcode=-1;
  4414. if (flags!=255) { // escape
  4415. retcode = traceFlags;
  4416. traceFlags = flags;
  4417. }
  4418. reply.append(retcode);
  4419. return true;
  4420. }
  4421. bool cmdGetInfo(MemoryBuffer &msg, MemoryBuffer &reply)
  4422. {
  4423. unsigned level=1;
  4424. if (msg.remaining() >= sizeof(unsigned))
  4425. msg.read(level);
  4426. StringBuffer retstr;
  4427. getInfo(retstr, level);
  4428. reply.append(0).append(retstr.str());
  4429. return true;
  4430. }
  4431. bool cmdFirewall(MemoryBuffer &msg, MemoryBuffer &reply)
  4432. {
  4433. // TBD
  4434. StringBuffer retstr;
  4435. getInfo(retstr);
  4436. reply.append(0).append(retstr.str());
  4437. return true;
  4438. }
  4439. bool cmdExtractBlobElements(MemoryBuffer &msg, MemoryBuffer &reply, CRemoteClientHandler &client)
  4440. {
  4441. IMPERSONATE_USER(client);
  4442. StringAttr prefix;
  4443. StringAttr filename;
  4444. msg.read(prefix).read(filename);
  4445. RemoteFilename rfn;
  4446. rfn.setLocalPath(filename);
  4447. ExtractedBlobArray extracted;
  4448. extractBlobElements(prefix, rfn, extracted);
  4449. unsigned n = extracted.ordinality();
  4450. reply.append((unsigned)RFEnoerror).append(n);
  4451. for (unsigned i=0;i<n;i++)
  4452. extracted.item(i).serialize(reply);
  4453. return true;
  4454. }
  4455. bool cmdRedeploy(MemoryBuffer &msg, MemoryBuffer &reply)
  4456. {
  4457. return false; // TBD
  4458. }
  4459. bool cmdKill(MemoryBuffer & msg, MemoryBuffer & reply)
  4460. {
  4461. // TBD
  4462. appendErr2(reply, RFSERR_InvalidCommand, RFCkill);
  4463. return false;
  4464. }
  4465. bool cmdUnknown(MemoryBuffer & msg, MemoryBuffer & reply,RemoteFileCommandType cmd)
  4466. {
  4467. appendErr2(reply, RFSERR_InvalidCommand, cmd);
  4468. return false;
  4469. }
  4470. bool cmdUnlock(MemoryBuffer & msg, MemoryBuffer & reply,CRemoteClientHandler &client)
  4471. {
  4472. // this is an attempt to authenticate when we haven't got authentication turned on
  4473. if (TF_TRACE_CLIENT_STATS)
  4474. {
  4475. StringBuffer s(client.queryPeerName());
  4476. PROGLOG("Connect from %s",s.str());
  4477. }
  4478. appendErr2(reply, RFSERR_InvalidCommand, RFCunlock);
  4479. return false;
  4480. }
  4481. // legacy version
  4482. bool cmdSetThrottle(MemoryBuffer & msg, MemoryBuffer & reply)
  4483. {
  4484. unsigned limit, delayMs, cpuThreshold;
  4485. msg.read(limit);
  4486. msg.read(delayMs);
  4487. msg.read(cpuThreshold);
  4488. stdCmdThrottler.configure(limit, delayMs, cpuThreshold, (unsigned)-1);
  4489. reply.append((unsigned)RFEnoerror);
  4490. return true;
  4491. }
  4492. bool cmdSetThrottle2(MemoryBuffer & msg, MemoryBuffer & reply)
  4493. {
  4494. unsigned throttleClass, limit, delayMs, cpuThreshold, queueLimit;
  4495. msg.read(throttleClass);
  4496. msg.read(limit);
  4497. msg.read(delayMs);
  4498. msg.read(cpuThreshold);
  4499. msg.read(queueLimit);
  4500. setThrottle((ThrottleClass)throttleClass, limit, delayMs, cpuThreshold, queueLimit);
  4501. reply.append((unsigned)RFEnoerror);
  4502. return true;
  4503. }
  4504. void appendError(RemoteFileCommandType cmd, CRemoteClientHandler *client, unsigned ret, MemoryBuffer &reply)
  4505. {
  4506. if (reply.length()>=sizeof(unsigned)*2)
  4507. {
  4508. reply.reset();
  4509. unsigned z;
  4510. unsigned e;
  4511. reply.read(z).read(e);
  4512. StringBuffer err("ERR(");
  4513. err.append(e).append(") ");
  4514. if (client)
  4515. {
  4516. const char *peer = client->queryPeerName();
  4517. if (peer)
  4518. err.append(peer);
  4519. }
  4520. if (e&&(reply.getPos()<reply.length()))
  4521. {
  4522. StringAttr es;
  4523. reply.read(es);
  4524. err.append(" : ").append(es);
  4525. }
  4526. reply.reset();
  4527. if (cmd!=RFCunlock)
  4528. PROGLOG("%s",err.str()); // supress authentication logging
  4529. if (client)
  4530. client->logPrevHandle();
  4531. }
  4532. }
  4533. void throttleCommand(RemoteFileCommandType cmd, MemoryBuffer &msg, CRemoteClientHandler *client)
  4534. {
  4535. switch(cmd)
  4536. {
  4537. case RFCexec:
  4538. case RFCgetcrc:
  4539. case RFCcopy:
  4540. case RFCappend:
  4541. case RFCtreecopy:
  4542. case RFCtreecopytmp:
  4543. slowCmdThrottler.addCommand(cmd, msg, client);
  4544. return;
  4545. case RFCcloseIO:
  4546. case RFCopenIO:
  4547. case RFCread:
  4548. case RFCsize:
  4549. case RFCwrite:
  4550. case RFCexists:
  4551. case RFCremove:
  4552. case RFCrename:
  4553. case RFCgetver:
  4554. case RFCisfile:
  4555. case RFCisdirectory:
  4556. case RFCisreadonly:
  4557. case RFCsetreadonly:
  4558. case RFCsetfileperms:
  4559. case RFCgettime:
  4560. case RFCsettime:
  4561. case RFCcreatedir:
  4562. case RFCgetdir:
  4563. case RFCmonitordir:
  4564. case RFCstop:
  4565. case RFCextractblobelements:
  4566. case RFCkill:
  4567. case RFCredeploy:
  4568. case RFCmove:
  4569. case RFCsetsize:
  4570. case RFCsettrace:
  4571. case RFCgetinfo:
  4572. case RFCfirewall:
  4573. case RFCunlock:
  4574. stdCmdThrottler.addCommand(cmd, msg, client);
  4575. return;
  4576. // NB: The following commands are still bound by the the thread pool
  4577. case RFCsetthrottle: // legacy version
  4578. case RFCsetthrottle2:
  4579. case RFCcopysection: // slightly odd, but has it's own limit
  4580. default:
  4581. {
  4582. client->processCommand(cmd, msg, NULL);
  4583. break;
  4584. }
  4585. }
  4586. }
  4587. bool processCommand(RemoteFileCommandType cmd, MemoryBuffer & msg, MemoryBuffer & reply, CRemoteClientHandler *client, CThrottler *throttler)
  4588. {
  4589. Owned<CClientStats> stats = clientStatsTable.getClientReference(cmd, client->queryPeerName());
  4590. bool ret = true;
  4591. try
  4592. {
  4593. switch(cmd)
  4594. {
  4595. MAPCOMMANDSTATS(RFCread, cmdRead, *stats);
  4596. MAPCOMMANDSTATS(RFCwrite, cmdWrite, *stats);
  4597. MAPCOMMANDCLIENTSTATS(RFCappend, cmdAppend, *client, *stats);
  4598. MAPCOMMAND(RFCcloseIO, cmdCloseFileIO);
  4599. MAPCOMMANDCLIENT(RFCopenIO, cmdOpenFileIO, *client);
  4600. MAPCOMMAND(RFCsize, cmdSize);
  4601. MAPCOMMANDCLIENT(RFCexists, cmdExists, *client);
  4602. MAPCOMMANDCLIENT(RFCremove, cmdRemove, *client);
  4603. MAPCOMMANDCLIENT(RFCrename, cmdRename, *client);
  4604. MAPCOMMAND(RFCgetver, cmdGetVer);
  4605. MAPCOMMANDCLIENT(RFCisfile, cmdIsFile, *client);
  4606. MAPCOMMANDCLIENT(RFCisdirectory, cmdIsDir, *client);
  4607. MAPCOMMANDCLIENT(RFCisreadonly, cmdIsReadOnly, *client);
  4608. MAPCOMMANDCLIENT(RFCsetreadonly, cmdSetReadOnly, *client);
  4609. MAPCOMMANDCLIENT(RFCsetfileperms, cmdSetFilePerms, *client);
  4610. MAPCOMMANDCLIENT(RFCgettime, cmdGetTime, *client);
  4611. MAPCOMMANDCLIENT(RFCsettime, cmdSetTime, *client);
  4612. MAPCOMMANDCLIENT(RFCcreatedir, cmdCreateDir, *client);
  4613. MAPCOMMANDCLIENT(RFCgetdir, cmdGetDir, *client);
  4614. MAPCOMMANDCLIENT(RFCmonitordir, cmdMonitorDir, *client);
  4615. MAPCOMMAND(RFCstop, cmdStop);
  4616. MAPCOMMANDCLIENT(RFCexec, cmdExec, *client);
  4617. MAPCOMMANDCLIENT(RFCextractblobelements, cmdExtractBlobElements, *client);
  4618. MAPCOMMAND(RFCkill, cmdKill);
  4619. MAPCOMMAND(RFCredeploy, cmdRedeploy); // only Windows
  4620. MAPCOMMANDCLIENT(RFCgetcrc, cmdGetCRC, *client);
  4621. MAPCOMMANDCLIENT(RFCmove, cmdMove, *client);
  4622. MAPCOMMANDCLIENT(RFCcopy, cmdCopy, *client);
  4623. MAPCOMMAND(RFCsetsize, cmdSetSize);
  4624. MAPCOMMAND(RFCsettrace, cmdSetTrace);
  4625. MAPCOMMAND(RFCgetinfo, cmdGetInfo);
  4626. MAPCOMMAND(RFCfirewall, cmdFirewall);
  4627. MAPCOMMANDCLIENT(RFCunlock, cmdUnlock, *client);
  4628. MAPCOMMANDCLIENT(RFCcopysection, cmdCopySection, *client);
  4629. MAPCOMMANDCLIENTTHROTTLE(RFCtreecopy, cmdTreeCopy, *client, &slowCmdThrottler);
  4630. MAPCOMMANDCLIENTTHROTTLE(RFCtreecopytmp, cmdTreeCopyTmp, *client, &slowCmdThrottler);
  4631. MAPCOMMAND(RFCsetthrottle, cmdSetThrottle); // legacy version
  4632. MAPCOMMAND(RFCsetthrottle2, cmdSetThrottle2);
  4633. default:
  4634. ret = cmdUnknown(msg,reply,cmd);
  4635. break;
  4636. }
  4637. }
  4638. catch (IException *e)
  4639. {
  4640. ret = false;
  4641. StringBuffer s;
  4642. e->errorMessage(s);
  4643. appendCmdErr(reply, cmd, e->errorCode(), s.str());
  4644. e->Release();
  4645. }
  4646. if (!ret) // append error string
  4647. appendError(cmd, client, cmd, reply);
  4648. return ret;
  4649. }
  4650. IPooledThread *createCommandProcessor()
  4651. {
  4652. return new cCommandProcessor();
  4653. }
  4654. void run(SocketEndpoint &listenep, bool useSSL)
  4655. {
  4656. if (listenep.isNull())
  4657. acceptsock.setown(ISocket::create(listenep.port));
  4658. else {
  4659. StringBuffer ips;
  4660. listenep.getIpText(ips);
  4661. acceptsock.setown(ISocket::create_ip(listenep.port,ips.str()));
  4662. }
  4663. if (useSSL) {
  4664. if (!securitySettings.certificate)
  4665. throw createDafsException(DAFSERR_connection_failed,"SSL Certificate information not found in environment.conf");
  4666. if (listenep.port <= 0)
  4667. {
  4668. assertex(FALSE);//should never get here
  4669. listenep.port = securitySettings.daFileSrvPort;
  4670. }
  4671. //Create unsecure socket to reject non-ssl client requests
  4672. if (listenep.isNull())
  4673. rejectsock.setown(ISocket::create(DAFILESRV_PORT));
  4674. else
  4675. {
  4676. StringBuffer ips;
  4677. listenep.getIpText(ips);
  4678. rejectsock.setown(ISocket::create_ip(DAFILESRV_PORT,ips.str()));
  4679. }
  4680. }
  4681. #ifdef _DEBUG
  4682. StringBuffer sb;
  4683. listenep.getUrlStr(sb);
  4684. DBGLOG("Server accepting %sfrom %s", useSSL?"SECURE ":"", sb.str());
  4685. #endif
  4686. selecthandler->start();
  4687. UnsignedArray readSocks;
  4688. if (useSSL)
  4689. {
  4690. readSocks.append(acceptsock->OShandle());
  4691. readSocks.append(rejectsock->OShandle());
  4692. }
  4693. for (;;) {
  4694. Owned<ISocket> sock;
  4695. bool sockavail = false;
  4696. try {
  4697. if (!useSSL)
  4698. sockavail = acceptsock->wait_read(1000*60*1)!=0;
  4699. else
  4700. {
  4701. UnsignedArray waitingSocks;
  4702. //SSL Enabled. Listen for non SSL connection on DAFILESRV_PORT and reject them
  4703. int numReady = wait_read_multiple(readSocks, 1000*60*1, waitingSocks);
  4704. if (numReady)
  4705. {
  4706. for (int idx = 0; idx < numReady; idx++)
  4707. {
  4708. if (waitingSocks.item(idx) == rejectsock->OShandle())
  4709. {
  4710. //Unsecure connection attemped, reject !
  4711. Owned<ISocket> s;
  4712. s.setown(rejectsock->accept(true));
  4713. IpAddress ip;
  4714. StringBuffer sb;
  4715. s->getPeerAddress(ip);
  4716. ip.getIpText(sb);
  4717. DBGLOG("Rejecting nonsecure connect from %s",sb.str());
  4718. s->close();
  4719. }
  4720. else
  4721. {
  4722. sockavail = true;
  4723. }
  4724. }
  4725. }
  4726. }
  4727. #if 0
  4728. if (!sockavail) {
  4729. JSocketStatistics stats;
  4730. getSocketStatistics(stats);
  4731. StringBuffer s;
  4732. getSocketStatisticsString(stats,s);
  4733. PROGLOG( "Socket statistics : \n%s\n",s.str());
  4734. }
  4735. #endif
  4736. }
  4737. catch (IException *e) {
  4738. EXCLOG(e,"CRemoteFileServer(1)");
  4739. e->Release();
  4740. // not sure what to do so just accept
  4741. sockavail = true;
  4742. }
  4743. if (stopping)
  4744. break;
  4745. if (sockavail) {
  4746. try {
  4747. sock.setown(acceptsock->accept(true));
  4748. if (useSSL)
  4749. {
  4750. #ifdef _USE_OPENSSL
  4751. Owned<ISecureSocket> ssock = createSecureSocket(sock.getClear(), ServerSocket);
  4752. int status = ssock->secure_accept();
  4753. if (status < 0)
  4754. throw createDafsException(DAFSERR_connection_failed,"Failure to establish secure connection");
  4755. sock.setown(ssock.getLink());
  4756. #else
  4757. throw createDafsException(DAFSERR_connection_failed,"Failure to establish secure connection: OpenSSL disabled in build");
  4758. #endif
  4759. }
  4760. if (!sock||stopping)
  4761. break;
  4762. runClient(sock.getClear());
  4763. }
  4764. catch (IException *e) {
  4765. EXCLOG(e,"CRemoteFileServer");
  4766. e->Release();
  4767. sock.clear();
  4768. if (!QUERYINTERFACE(e, IJSOCK_Exception))
  4769. break;
  4770. }
  4771. }
  4772. else
  4773. checkTimeout();
  4774. }
  4775. if (TF_TRACE_CLIENT_STATS)
  4776. PROGLOG("CRemoteFileServer:run exiting");
  4777. selecthandler->stop(true);
  4778. }
  4779. void processUnauthenticatedCommand(RemoteFileCommandType cmd, ISocket *socket, MemoryBuffer &msg)
  4780. {
  4781. // these are unauthenticated commands
  4782. if (cmd != RFCgetver)
  4783. cmd = RFCinvalid;
  4784. MemoryBuffer reply;
  4785. processCommand(cmd, msg, initSendBuffer(reply), NULL, NULL);
  4786. sendBuffer(socket, reply);
  4787. }
  4788. bool checkAuthentication(ISocket *socket, IAuthenticatedUser *&ret)
  4789. {
  4790. ret = NULL;
  4791. if (!AuthenticationEnabled)
  4792. return true;
  4793. MemoryBuffer reqbuf;
  4794. MemoryBuffer reply;
  4795. MemoryBuffer encbuf; // because aesEncrypt clears input
  4796. initSendBuffer(reply);
  4797. receiveBuffer(socket, reqbuf, 1);
  4798. RemoteFileCommandType typ=0;
  4799. if (reqbuf.remaining()<sizeof(RemoteFileCommandType))
  4800. return false;
  4801. reqbuf.read(typ);
  4802. if (typ!=RFCunlock) {
  4803. processUnauthenticatedCommand(typ,socket,reqbuf);
  4804. return false;
  4805. }
  4806. if (reqbuf.remaining()<sizeof(OnceKey))
  4807. return false;
  4808. OnceKey oncekey;
  4809. reqbuf.read(sizeof(oncekey),&oncekey);
  4810. IpAddress ip;
  4811. socket->getPeerAddress(ip);
  4812. byte ipdata[16];
  4813. ip.getNetAddress(sizeof(ipdata),&ipdata);
  4814. mergeOnce(oncekey,sizeof(ipdata),&ipdata); // this is clients key
  4815. OnceKey mykey;
  4816. genOnce(mykey);
  4817. reply.append((unsigned)0); // errcode
  4818. aesEncrypt(&oncekey,sizeof(oncekey),&mykey,sizeof(oncekey),encbuf);
  4819. reply.append(encbuf.length()).append(encbuf);
  4820. sendBuffer(socket, reply); // send my oncekey
  4821. reqbuf.clear();
  4822. receiveBuffer(socket, reqbuf, 1);
  4823. if (reqbuf.remaining()>sizeof(RemoteFileCommandType)+sizeof(size32_t)) {
  4824. reqbuf.read(typ);
  4825. if (typ==RFCunlockreply) {
  4826. size32_t bs;
  4827. reqbuf.read(bs);
  4828. if (bs<=reqbuf.remaining()) {
  4829. MemoryBuffer userbuf;
  4830. aesDecrypt(&mykey,sizeof(mykey),reqbuf.readDirect(bs),bs,userbuf);
  4831. byte n;
  4832. userbuf.read(n);
  4833. if (n>=2) {
  4834. StringAttr user;
  4835. StringAttr password;
  4836. userbuf.read(user).read(password);
  4837. Owned<IAuthenticatedUser> iau = createAuthenticatedUser();
  4838. if (iau->login(user,password)) {
  4839. initSendBuffer(reply.clear());
  4840. reply.append((unsigned)0);
  4841. sendBuffer(socket, reply); // send OK
  4842. ret = iau;
  4843. return true;
  4844. }
  4845. }
  4846. }
  4847. }
  4848. }
  4849. reply.clear();
  4850. appendErr(reply, RFSERR_AuthenticateFailed);
  4851. sendBuffer(socket, reply); // send OK
  4852. return false;
  4853. }
  4854. void runClient(ISocket *sock)
  4855. {
  4856. cCommandProcessor::cCommandProcessorParams params;
  4857. IAuthenticatedUser *user=NULL;
  4858. bool authenticated = false;
  4859. try {
  4860. if (checkAuthentication(sock,user))
  4861. authenticated = true;
  4862. }
  4863. catch (IException *e) {
  4864. e->Release();
  4865. }
  4866. if (!authenticated) {
  4867. try {
  4868. sock->Release();
  4869. }
  4870. catch (IException *e) {
  4871. e->Release();
  4872. }
  4873. return;
  4874. }
  4875. params.client = new CRemoteClientHandler(this,sock,user,globallasttick);
  4876. {
  4877. CriticalBlock block(sect);
  4878. clients.append(*LINK(params.client));
  4879. }
  4880. // NB: This could be blocked, by thread pool limit
  4881. threads->start(&params);
  4882. }
  4883. void stop()
  4884. {
  4885. // stop accept loop
  4886. if (TF_TRACE_CLIENT_STATS)
  4887. PROGLOG("CRemoteFileServer::stop");
  4888. if (acceptsock)
  4889. acceptsock->cancel_accept();
  4890. if (rejectsock)
  4891. rejectsock->cancel_accept();
  4892. threads->stopAll();
  4893. threads->joinAll(true,60*1000);
  4894. }
  4895. bool notify(CRemoteClientHandler *_client, MemoryBuffer &msg)
  4896. {
  4897. Linked<CRemoteClientHandler> client;
  4898. client.set(_client);
  4899. if (TF_TRACE_FULL)
  4900. PROGLOG("notify %d", msg.length());
  4901. if (msg.length())
  4902. {
  4903. if (TF_TRACE_FULL)
  4904. PROGLOG("notify CRemoteClientHandler(%p), msg length=%u", _client, msg.length());
  4905. cCommandProcessor::cCommandProcessorParams params;
  4906. params.client = client.getClear();
  4907. params.msg.swapWith(msg);
  4908. /* This can block because the thread pool is full and therefore block the selecthandler
  4909. * This is akin to the main server blocking post accept() for the same reason.
  4910. */
  4911. threads->start(&params);
  4912. }
  4913. else
  4914. onCloseSocket(client,3); // removes owned handles
  4915. return false;
  4916. }
  4917. void addClient(CRemoteClientHandler *client)
  4918. {
  4919. if (client&&client->socket)
  4920. selecthandler->add(client->socket,SELECTMODE_READ,client);
  4921. }
  4922. void checkTimeout()
  4923. {
  4924. if (msTick()-clientcounttick>1000*60*60) {
  4925. CriticalBlock block(ClientCountSect);
  4926. if (TF_TRACE_CLIENT_STATS && (ClientCount || MaxClientCount))
  4927. PROGLOG("Client count = %d, max = %d", ClientCount, MaxClientCount);
  4928. clientcounttick = msTick();
  4929. MaxClientCount = ClientCount;
  4930. if (closedclients) {
  4931. if (TF_TRACE_CLIENT_STATS)
  4932. PROGLOG("Closed client count = %d",closedclients);
  4933. closedclients = 0;
  4934. }
  4935. }
  4936. CriticalBlock block(sect);
  4937. ForEachItemInRev(i,clients) {
  4938. CRemoteClientHandler &client = clients.item(i);
  4939. if (client.timedOut()) {
  4940. StringBuffer s;
  4941. bool ok = client.getInfo(s); // will spot duff sockets
  4942. if (ok&&(client.handles.ordinality()!=0)) {
  4943. if (TF_TRACE_CLIENT_CONN && client.inactiveTimedOut())
  4944. WARNLOG("Inactive %s",s.str());
  4945. }
  4946. else {
  4947. #ifndef _DEBUG
  4948. if (TF_TRACE_CLIENT_CONN)
  4949. #endif
  4950. PROGLOG("Timing out %s",s.str());
  4951. closedclients++;
  4952. onCloseSocket(&client,4); // removes owned handles
  4953. }
  4954. }
  4955. }
  4956. }
  4957. void getInfo(StringBuffer &info, unsigned level=1)
  4958. {
  4959. {
  4960. CriticalBlock block(ClientCountSect);
  4961. info.append(VERSTRING).append('\n');
  4962. info.appendf("Client count = %d\n",ClientCount);
  4963. info.appendf("Max client count = %d",MaxClientCount);
  4964. }
  4965. CriticalBlock block(sect);
  4966. ForEachItemIn(i,clients)
  4967. {
  4968. info.newline().append(i).append(": ");
  4969. clients.item(i).getInfo(info);
  4970. }
  4971. info.newline().appendf("Running threads: %u", threadRunningCount());
  4972. info.newline();
  4973. stdCmdThrottler.getInfo(info);
  4974. info.newline();
  4975. slowCmdThrottler.getInfo(info);
  4976. clientStatsTable.getInfo(info, level);
  4977. }
  4978. unsigned threadRunningCount()
  4979. {
  4980. if (!threads)
  4981. return 0;
  4982. return threads->runningCount();
  4983. }
  4984. unsigned idleTime()
  4985. {
  4986. unsigned t = (unsigned)atomic_read(&globallasttick);
  4987. return msTick()-t;
  4988. }
  4989. void setThrottle(ThrottleClass throttleClass, unsigned limit, unsigned delayMs, unsigned cpuThreshold, unsigned queueLimit)
  4990. {
  4991. switch (throttleClass)
  4992. {
  4993. case ThrottleStd:
  4994. stdCmdThrottler.configure(limit, delayMs, cpuThreshold, queueLimit);
  4995. break;
  4996. case ThrottleSlow:
  4997. slowCmdThrottler.configure(limit, delayMs, cpuThreshold, queueLimit);
  4998. break;
  4999. default:
  5000. {
  5001. StringBuffer availableClasses("{ ");
  5002. for (unsigned c=0; c<ThrottleClassMax; c++)
  5003. {
  5004. availableClasses.append(c).append(" = ").append(getThrottleClassText((ThrottleClass)c));
  5005. if (c+1<ThrottleClassMax)
  5006. availableClasses.append(", ");
  5007. }
  5008. availableClasses.append(" }");
  5009. throw MakeStringException(0, "Unknown throttle class: %u, available classes are: %s", (unsigned)throttleClass, availableClasses.str());
  5010. }
  5011. }
  5012. }
  5013. StringBuffer &getStats(StringBuffer &stats, bool reset)
  5014. {
  5015. CriticalBlock block(sect);
  5016. stdCmdThrottler.getStats(stats, reset).newline();
  5017. slowCmdThrottler.getStats(stats, reset);
  5018. if (reset)
  5019. clientStatsTable.reset();
  5020. return stats;
  5021. }
  5022. };
  5023. IRemoteFileServer * createRemoteFileServer(unsigned maxThreads, unsigned maxThreadsDelayMs, unsigned maxAsyncCopy)
  5024. {
  5025. #if SIMULATE_PACKETLOSS
  5026. errorSimulationOn = false;
  5027. #endif
  5028. return new CRemoteFileServer(maxThreads, maxThreadsDelayMs, maxAsyncCopy);
  5029. }