sockfile.cpp 174 KB

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