sockfile.cpp 174 KB

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