jfile.cpp 192 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110
  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. #include "platform.h"
  14. #ifdef _WIN32
  15. #include <errno.h>
  16. //#include <winsock.h> // for TransmitFile
  17. #endif
  18. #include <sys/types.h>
  19. #include <sys/stat.h>
  20. #include <algorithm>
  21. #if defined (__linux__) || defined (__APPLE__)
  22. #include <time.h>
  23. #include <dirent.h>
  24. #include <utime.h>
  25. #include <sys/syscall.h>
  26. #include <sys/mman.h>
  27. #endif
  28. #if defined (__linux__)
  29. #include <sys/vfs.h>
  30. #include <sys/sendfile.h>
  31. #endif
  32. #if defined (__APPLE__)
  33. #include <sys/mount.h>
  34. #undef MIN
  35. #endif
  36. #include "time.h"
  37. #include "jerror.hpp"
  38. #include "jlib.hpp"
  39. #include "jio.hpp"
  40. #include "jmisc.hpp"
  41. #include "jsort.hpp"
  42. #include "jmutex.hpp"
  43. #include "jfile.hpp"
  44. #include "jfile.ipp"
  45. #include <limits.h>
  46. #include "jexcept.hpp"
  47. #include "jsocket.hpp" // for IpAddress
  48. #include "jregexp.hpp"
  49. #include "portlist.h"
  50. #include "build-config.h"
  51. #include "jprop.hpp"
  52. // #define REMOTE_DISCONNECT_ON_DESTRUCTOR // enable to disconnect on IFile destructor
  53. // this should not be enabled in WindowRemoteDirectory used
  54. //#define CHECK_FILE_IO // If enabled, reads and writes are checked for sensible parameters
  55. #ifdef _DEBUG
  56. #define ASSERTEX(e) assertex(e);
  57. #else
  58. #define ASSERTEX(e)
  59. #endif
  60. #ifdef __64BIT__
  61. #define DEFAULT_STREAM_BUFFER_SIZE 0x100000
  62. #else
  63. // Restrict buffer sizes on 32-bit systems
  64. #define DEFAULT_STREAM_BUFFER_SIZE 0x10000
  65. #endif
  66. #ifdef _WIN32
  67. #define NULLFILE INVALID_HANDLE_VALUE
  68. #else
  69. #define NULLFILE -1
  70. #endif
  71. // #define CFILEIOTRACE 1
  72. static IFile *createIFileByHook(const RemoteFilename & filename);
  73. static IFile *createContainedIFileByHook(const char *filename);
  74. static inline bool isPCFlushAllowed();
  75. static char ShareChar='$';
  76. bool isShareChar(char c)
  77. {
  78. return (c==ShareChar)||(c=='$');
  79. }
  80. char getShareChar()
  81. {
  82. return ShareChar;
  83. }
  84. void setShareChar(char c)
  85. {
  86. ShareChar = c;
  87. }
  88. StringBuffer &setPathDrive(StringBuffer &filename,unsigned drvnum)
  89. {
  90. return swapPathDrive(filename,(unsigned)-1,drvnum);
  91. }
  92. unsigned getPathDrive(const char *s)
  93. {
  94. char c = *s;
  95. if (isPathSepChar(c)&&(s[1]==c)) {
  96. s = strchr(s+2,c);
  97. if (!s)
  98. return 0;
  99. }
  100. if (isPathSepChar(c))
  101. s++;
  102. if (*s&&((s[1]==':')||(isShareChar(s[1]))))
  103. return *s-'c';
  104. return 0;
  105. }
  106. StringBuffer &swapPathDrive(StringBuffer &filename,unsigned fromdrvnum,unsigned todrvnum,const char *frommask,const char *tomask)
  107. {
  108. const char *s = filename.str();
  109. char c = *s;
  110. if (isPathSepChar(c)&&(s[1]==c)) {
  111. s = strchr(s+2,c);
  112. if (!s)
  113. return filename;
  114. }
  115. if (isPathSepChar(c))
  116. s++;
  117. if (*s&&((fromdrvnum==(unsigned)-1)||(*s==(char) (fromdrvnum+'c')))&&((s[1]==':')||(isShareChar(s[1]))))
  118. filename.setCharAt((size32_t)(s-filename.str()),todrvnum+'c');
  119. else if (frommask&&*frommask) { // OSS
  120. StringBuffer tmp;
  121. if (replaceConfigurationDirectoryEntry(filename.str(),frommask,tomask, tmp))
  122. tmp.swapWith(filename);
  123. }
  124. return filename;
  125. }
  126. StringBuffer &getStandardPosixPath(StringBuffer &result, const char *path)
  127. {
  128. result.set(path);
  129. const char *s = result.trim().replace('\\', '/').str();
  130. bool startWithPathSepChar = isPathSepChar(s[0]);
  131. if (startWithPathSepChar)
  132. s++;
  133. if (*s && ((s[1]==':') || isShareChar(s[1])))
  134. {
  135. char c = tolower(s[0]);
  136. if (!startWithPathSepChar)
  137. result.insert(0, '/');
  138. result.setCharAt(1, c);
  139. result.setCharAt(2, '$');
  140. }
  141. return result;
  142. }
  143. const char *pathTail(const char *path)
  144. {
  145. if (!path)
  146. return NULL;
  147. const char *tail=path;
  148. const char *s = path;
  149. while (*s)
  150. if (isPathSepChar(*(s++)))
  151. tail = s;
  152. return tail;
  153. }
  154. const char * pathExtension(const char * path)
  155. {
  156. const char * tail = pathTail(path);
  157. if (tail)
  158. return strrchr(tail, '.');
  159. return NULL;
  160. }
  161. bool checkFileExists(const char * filename)
  162. {
  163. #ifdef _WIN32
  164. for (unsigned i=0;i<10;i++) {
  165. DWORD ret = (DWORD)GetFileAttributes(filename);
  166. if (ret!=(DWORD)-1)
  167. return true;
  168. DWORD err = GetLastError();
  169. if (err!=ERROR_IO_PENDING)
  170. break;
  171. Sleep(100*i);
  172. }
  173. return false;
  174. #else
  175. struct stat info;
  176. return (stat(filename, &info) == 0);
  177. #endif
  178. }
  179. bool checkDirExists(const char * filename)
  180. {
  181. #ifdef _WIN32
  182. DWORD attr = GetFileAttributes(filename);
  183. return (attr != (DWORD)-1)&&(attr & FILE_ATTRIBUTE_DIRECTORY);
  184. #else
  185. struct stat info;
  186. if (stat(filename, &info) != 0)
  187. return false;
  188. return S_ISDIR(info.st_mode);
  189. #endif
  190. }
  191. static void set_inherit(HANDLE handle, bool inherit)
  192. {
  193. #ifndef _WIN32
  194. long flag = fcntl(handle, F_GETFD);
  195. if(inherit)
  196. flag &= ~FD_CLOEXEC;
  197. else
  198. flag |= FD_CLOEXEC;
  199. fcntl(handle, F_SETFD, flag);
  200. #endif
  201. }
  202. static StringBuffer &getLocalOrRemoteName(StringBuffer &name,const RemoteFilename & filename)
  203. {
  204. if (filename.isLocal()&&!filename.isNull()) {
  205. filename.getLocalPath(name);
  206. #ifdef _WIN32
  207. // kludge to allow local linux paths on windows
  208. const char *n=name.str();
  209. if (n[0]=='/') {
  210. StringBuffer tmp;
  211. if (isShareChar(n[2])) {
  212. tmp.append(n[1]).append(':');
  213. n+=3;
  214. }
  215. while (*n) {
  216. if (*n=='/')
  217. tmp.append('\\');
  218. else
  219. tmp.append(*n);
  220. n++;
  221. }
  222. name.clear().append(tmp);
  223. }
  224. #endif
  225. }
  226. else
  227. filename.getRemotePath(name);
  228. return name;
  229. }
  230. CFile::CFile(const char * _filename)
  231. {
  232. filename.set(_filename);
  233. flags = ((unsigned)IFSHread)|((S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH|S_IWOTH)<<16);
  234. }
  235. void CFile::setCreateFlags(unsigned short cflags)
  236. {
  237. flags &= 0xffff;
  238. flags |= ((unsigned)cflags<<16);
  239. }
  240. void CFile::setShareMode(IFSHmode shmode)
  241. {
  242. flags &= ~(IFSHfull|IFSHread);
  243. flags |= (unsigned)(shmode&(IFSHfull|IFSHread));
  244. }
  245. bool CFile::exists()
  246. {
  247. if (stdIoHandle(filename)>=0)
  248. return true;
  249. return checkFileExists(filename);
  250. }
  251. #ifdef _WIN32
  252. bool WindowsCreateDirectory(const char * path)
  253. {
  254. unsigned retry = 0;
  255. for (;;) {
  256. if (CreateDirectory(path, NULL))
  257. return true;
  258. DWORD err = GetLastError();
  259. if ((err==ERROR_FILE_NOT_FOUND) || (err==ERROR_PATH_NOT_FOUND) || (err==ERROR_FILE_EXISTS) || (err==ERROR_CANNOT_MAKE) || (err==ERROR_ACCESS_DENIED))
  260. break;
  261. else if (err==ERROR_ALREADY_EXISTS) {
  262. DWORD attr = GetFileAttributes(path);
  263. if ((attr != -1)&&( attr & FILE_ATTRIBUTE_DIRECTORY))
  264. return true;
  265. return false;
  266. }
  267. if ((retry++==10)|| // some or all of the following can occur when the domain controller gets busy
  268. // retrying improves chance of success
  269. ((err!=ERROR_NETNAME_DELETED)&&(err!=ERROR_DEV_NOT_EXIST)&&(err!=ERROR_GEN_FAILURE)&&(err!=ERROR_NETWORK_BUSY)&&(err!=ERROR_BAD_NET_NAME)))
  270. return false;
  271. //PROGLOG("Retrying(%d) WindowsCreateDirectory %s, err=%d",retry,filename,err);
  272. Sleep(retry*100);
  273. }
  274. return false;
  275. }
  276. #else
  277. bool LinuxCreateDirectory(const char * path)
  278. {
  279. if (!path)
  280. return false;
  281. if (CreateDirectory(path, NULL))
  282. return true;
  283. else
  284. {
  285. if (EEXIST == errno)
  286. {
  287. struct stat info;
  288. if (stat(path, &info) != 0)
  289. return false;
  290. return S_ISDIR(info.st_mode);
  291. }
  292. }
  293. return false;
  294. }
  295. #endif
  296. bool localCreateDirectory(const char *name)
  297. {
  298. if (!name)
  299. return false;
  300. size32_t l = (size32_t)strlen(name);
  301. if (l==0)
  302. return true;
  303. if (isPathSepChar(name[0])&&((l==1)||(isPathSepChar(name[1])&&!containsPathSepChar(name+2))))
  304. return true;
  305. #ifdef _WIN32
  306. if (name[1]==':') {
  307. if ((l==2)||((l==3)&&isPathSepChar(name[2])))
  308. return true;
  309. }
  310. #endif
  311. if (checkDirExists(name))
  312. return true;
  313. #ifdef _WIN32
  314. if (WindowsCreateDirectory(name))
  315. #else
  316. if (LinuxCreateDirectory(name))
  317. #endif
  318. return true;
  319. if (isPathSepChar(name[l-1])) l--;
  320. while (l&&!isPathSepChar(name[l-1]))
  321. l--;
  322. if (l<=1)
  323. return true;
  324. StringAttr parent(name,l-1);
  325. if (!localCreateDirectory(parent.get()))
  326. return false;
  327. #ifdef _WIN32
  328. return (WindowsCreateDirectory(name));
  329. #else
  330. return (LinuxCreateDirectory(name));
  331. #endif
  332. }
  333. bool CFile::createDirectory()
  334. {
  335. return localCreateDirectory(filename);
  336. }
  337. #ifdef _WIN32
  338. union TimeIntegerUnion
  339. {
  340. FILETIME ft;
  341. ULARGE_INTEGER l;
  342. };
  343. void FILETIMEtoIDateTime(CDateTime * target, const FILETIME & ft)
  344. {
  345. if (target)
  346. {
  347. TimeIntegerUnion u;
  348. memcpy(&u, &ft, sizeof(ft));
  349. unsigned __int64 hundredNanoseconds = (u.l.QuadPart % 10000000);
  350. u.l.QuadPart -= hundredNanoseconds;
  351. SYSTEMTIME systime;
  352. FileTimeToSystemTime(&u.ft, &systime);
  353. target->set(systime.wYear, systime.wMonth, systime.wDay, systime.wHour, systime.wMinute, systime.wSecond, (unsigned)(hundredNanoseconds*100));
  354. }
  355. }
  356. FILETIME * IDateTimetoFILETIME(FILETIME & ft, const CDateTime * dt)
  357. {
  358. if (!dt)
  359. return NULL;
  360. SYSTEMTIME systime;
  361. TimeIntegerUnion u;
  362. unsigned wYear, wMonth, wDay, wHour, wMinute, wSecond, nanoSeconds;
  363. dt->getDate(wYear, wMonth, wDay);
  364. dt->getTime(wHour, wMinute, wSecond, nanoSeconds);
  365. systime.wYear = wYear;
  366. systime.wMonth = wMonth;
  367. systime.wDay = wDay;
  368. systime.wHour = wHour;
  369. systime.wMinute = wMinute;
  370. systime.wSecond = wSecond;
  371. systime.wMilliseconds = 0;
  372. SystemTimeToFileTime(&systime, &u.ft);
  373. //Adjust the fractions of a second ourselves because the function above is only accurate to milli seconds.
  374. u.l.QuadPart += (nanoSeconds / 100);
  375. memcpy(&ft, &u, sizeof(ft));
  376. return &ft;
  377. }
  378. #endif
  379. bool CFile::getTime(CDateTime * createTime, CDateTime * modifiedTime, CDateTime * accessedTime)
  380. {
  381. #ifdef _WIN32
  382. //MORE could use GetFileAttributesEx() if we were allowed...
  383. FILETIME timeCreated, timeModified, timeAccessed;
  384. HANDLE handle = CreateFile(filename, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL);
  385. if (handle==(HANDLE)-1)
  386. return false;
  387. GetFileTime(handle, &timeCreated, &timeAccessed, &timeModified);
  388. CloseHandle(handle);
  389. FILETIMEtoIDateTime(createTime, timeCreated);
  390. FILETIMEtoIDateTime(modifiedTime, timeModified);
  391. FILETIMEtoIDateTime(accessedTime, timeAccessed);
  392. #else
  393. struct stat info;
  394. if (stat(filename, &info) != 0)
  395. return false;
  396. timetToIDateTime(accessedTime, info.st_atime);
  397. timetToIDateTime(createTime, info.st_ctime);
  398. timetToIDateTime(modifiedTime, info.st_mtime);
  399. #endif
  400. return true;
  401. }
  402. bool CFile::setTime(const CDateTime * createTime, const CDateTime * modifiedTime, const CDateTime * accessedTime)
  403. {
  404. #ifdef _WIN32
  405. FILETIME timeCreated, timeModified, timeAccessed;
  406. FILETIME *pTimeCreated, *pTimeModified, *pTimeAccessed;
  407. pTimeCreated = IDateTimetoFILETIME(timeCreated, createTime);
  408. pTimeModified = IDateTimetoFILETIME(timeModified, modifiedTime);
  409. pTimeAccessed = IDateTimetoFILETIME(timeAccessed, accessedTime);
  410. HANDLE handle = CreateFile(filename, GENERIC_WRITE, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL);
  411. if (!handle)
  412. return false;
  413. SetFileTime(handle, pTimeCreated, pTimeAccessed, pTimeModified);
  414. CloseHandle(handle);
  415. return true;
  416. #else
  417. struct utimbuf am;
  418. if (!accessedTime||!modifiedTime) {
  419. struct stat info;
  420. if (stat(filename, &info) != 0)
  421. return false;
  422. am.actime = info.st_atime;
  423. am.modtime = info.st_mtime;
  424. }
  425. if (accessedTime)
  426. am.actime = timetFromIDateTime (accessedTime);
  427. if (modifiedTime)
  428. am.modtime = timetFromIDateTime (modifiedTime);
  429. return (utime(filename, &am)==0);
  430. #endif
  431. }
  432. fileBool CFile::isDirectory()
  433. {
  434. #ifdef _WIN32
  435. DWORD attr = GetFileAttributes(filename);
  436. if (attr == -1)
  437. return fileBool::notFound;
  438. return ( attr & FILE_ATTRIBUTE_DIRECTORY) ? fileBool::foundYes : fileBool::foundNo;
  439. #else
  440. struct stat info;
  441. if (stat(filename, &info) != 0)
  442. return fileBool::notFound;
  443. return S_ISDIR(info.st_mode) ? fileBool::foundYes : fileBool::foundNo;
  444. #endif
  445. }
  446. fileBool CFile::isFile()
  447. {
  448. if (stdIoHandle(filename)>=0)
  449. return fileBool::foundYes;
  450. #ifdef _WIN32
  451. DWORD attr = GetFileAttributes(filename);
  452. if (attr == -1)
  453. return fileBool::notFound;
  454. return ( attr & FILE_ATTRIBUTE_DIRECTORY) ? fileBool::foundNo : fileBool::foundYes;
  455. #else
  456. struct stat info;
  457. if (stat(filename, &info) != 0)
  458. return fileBool::notFound;
  459. return S_ISREG(info.st_mode) ? fileBool::foundYes : fileBool::foundNo;
  460. #endif
  461. }
  462. fileBool CFile::isReadOnly()
  463. {
  464. #ifdef _WIN32
  465. DWORD attr = GetFileAttributes(filename);
  466. if (attr == -1)
  467. return fileBool::notFound;
  468. return ( attr & FILE_ATTRIBUTE_READONLY) ? fileBool::foundYes : fileBool::foundNo;
  469. #else
  470. struct stat info;
  471. if (stat(filename, &info) != 0)
  472. return fileBool::notFound;
  473. //MORE: I think this is correct, but someone with better unix knowledge should check!
  474. return (info.st_mode & (S_IWUSR|S_IWGRP|S_IWOTH)) ? fileBool::foundNo : fileBool::foundYes;
  475. #endif
  476. }
  477. #ifndef _WIN32
  478. static bool setShareLock(int fd,IFSHmode share)
  479. {
  480. struct flock fl;
  481. do {
  482. memset(&fl,0,sizeof(fl));
  483. if (share==IFSHnone)
  484. fl.l_type = F_WRLCK;
  485. else if (share==IFSHread)
  486. fl.l_type = F_RDLCK;
  487. else
  488. fl.l_type = F_UNLCK;
  489. fl.l_whence = SEEK_SET;
  490. fl.l_pid = getpid();
  491. if (fcntl(fd, F_SETLK, &fl) != -1)
  492. return true;
  493. } while (errno==EINTR);
  494. if ((errno!=EAGAIN)&&(errno!=EACCES))
  495. IERRLOG("setShareLock failure %d, mode %d", errno,(int)share);
  496. return (share==IFSHfull); // always return true for full
  497. }
  498. #endif
  499. HANDLE CFile::openHandle(IFOmode mode, IFSHmode sharemode, bool async, int stdh)
  500. {
  501. HANDLE handle = NULLFILE;
  502. #ifdef _WIN32
  503. if (stdh>=0) {
  504. DWORD mode;
  505. switch (stdh) {
  506. case 0: mode = STD_INPUT_HANDLE; break;
  507. case 1: mode = STD_OUTPUT_HANDLE; break;
  508. case 2: mode = STD_ERROR_HANDLE; break;
  509. default:
  510. return handle;
  511. }
  512. DuplicateHandle(GetCurrentProcess(), GetStdHandle(mode), GetCurrentProcess(), &handle , 0, FALSE, DUPLICATE_SAME_ACCESS);
  513. return handle;
  514. }
  515. DWORD share = 0;
  516. switch (sharemode) {
  517. case (IFSHfull|IFSHread):
  518. case IFSHfull:
  519. share |= FILE_SHARE_WRITE;
  520. // fall through
  521. case IFSHread:
  522. share |= FILE_SHARE_READ;
  523. }
  524. DWORD fflags = async?FILE_FLAG_OVERLAPPED:0;
  525. if (async&&(mode==IFOread))
  526. fflags |= FILE_FLAG_SEQUENTIAL_SCAN;
  527. switch (mode) {
  528. case IFOcreate:
  529. handle = CreateFile(filename, GENERIC_WRITE, share, NULL, CREATE_ALWAYS, fflags, NULL);
  530. break;
  531. case IFOread:
  532. handle = CreateFile(filename, GENERIC_READ, share, NULL, OPEN_EXISTING, fflags, NULL);
  533. break;
  534. case IFOwrite:
  535. handle = CreateFile(filename, GENERIC_WRITE, share, NULL, OPEN_ALWAYS, fflags, NULL);
  536. break;
  537. case IFOcreaterw:
  538. handle = CreateFile(filename, GENERIC_WRITE|GENERIC_READ, share, NULL, CREATE_ALWAYS, fflags, NULL);
  539. break;
  540. case IFOreadwrite:
  541. handle = CreateFile(filename, GENERIC_WRITE|GENERIC_READ, share, NULL, OPEN_ALWAYS, fflags, NULL);
  542. break;
  543. }
  544. if (handle == NULLFILE)
  545. {
  546. DWORD err = GetLastError();
  547. if ((IFOread!=mode) || ((err!=ERROR_FILE_NOT_FOUND) && (err!=ERROR_PATH_NOT_FOUND)))
  548. throw makeOsExceptionV(err,"CFile::open %s (%x, %x)", filename.get(), mode, share);
  549. return NULLFILE;
  550. }
  551. #else
  552. if (stdh>=0)
  553. return (HANDLE)dup(stdh);
  554. unsigned fileflags = (flags>>16) & (S_IRUSR|S_IWUSR|S_IXUSR|S_IRGRP|S_IWGRP|S_IXGRP|S_IROTH|S_IWOTH|S_IXOTH);
  555. unsigned openflags;
  556. switch (mode) {
  557. case IFOcreate:
  558. openflags = O_WRONLY | O_CREAT | O_TRUNC;
  559. break;
  560. case IFOread:
  561. openflags = O_RDONLY;
  562. break;
  563. case IFOwrite:
  564. openflags = O_WRONLY | O_CREAT;
  565. break;
  566. case IFOcreaterw:
  567. openflags = O_RDWR | O_CREAT | O_TRUNC;
  568. break;
  569. case IFOreadwrite:
  570. openflags = O_RDWR | O_CREAT;
  571. break;
  572. default:
  573. return NULLFILE;
  574. }
  575. handle = _lopen(filename.get(), openflags, fileflags);
  576. if (handle == -1)
  577. {
  578. if ((IFOread!=mode) || (errno != ENOENT))
  579. throw makeErrnoExceptionV(errno, "CFile::open %s", filename.get());
  580. return NULLFILE;
  581. }
  582. // check not a directory (compatible with windows)
  583. struct stat info;
  584. if (fstat(handle, &info) == -1) {
  585. int err = errno;
  586. close(handle);
  587. handle = NULLFILE;
  588. throw makeErrnoExceptionV(err, "CFile::open fstat %s", filename.get());
  589. }
  590. if (S_ISDIR(info.st_mode)) {
  591. close(handle);
  592. handle = NULLFILE;
  593. throw makeErrnoExceptionV(EISDIR, "CFile::open %s", filename.get());
  594. }
  595. #ifdef CFILEIOTRACE
  596. DBGLOG("CFile::openHandle(%s,%d) returns %d", filename.get(), mode, handle);
  597. #endif
  598. #endif
  599. return handle;
  600. }
  601. IFileIO * CFile::open(IFOmode mode,IFEflags extraFlags)
  602. {
  603. // we may want mode dependant defaults later
  604. return openShared(mode,(IFSHmode)(flags&(IFSHfull|IFSHread)),extraFlags);
  605. }
  606. IFileAsyncIO * CFile::openAsync(IFOmode mode)
  607. {
  608. HANDLE handle = openHandle(mode,IFSHread,true); // I don't think we want shared write to an async file
  609. #ifndef _WIN32
  610. set_inherit(handle, false);
  611. #endif
  612. return new CFileAsyncIO(handle,IFSHread);
  613. }
  614. const char * CFile::queryFilename()
  615. {
  616. return filename;
  617. }
  618. bool CFile::remove()
  619. {
  620. #ifdef _WIN32
  621. unsigned retry = 0;
  622. for (;;) {
  623. if (isDirectory()==fileBool::foundYes) {
  624. if (RemoveDirectory(filename) != 0)
  625. return true;
  626. }
  627. else {
  628. if (DeleteFile(filename) != 0)
  629. return true;
  630. }
  631. DWORD err = GetLastError();
  632. if ( (err==ERROR_FILE_NOT_FOUND) || (err==ERROR_PATH_NOT_FOUND) )
  633. break;
  634. if ((retry++==10)|| // some or all of the following can occur when the domain controller gets busy
  635. // retrying improves chance of success
  636. ((err!=ERROR_NETNAME_DELETED)&&(err!=ERROR_DEV_NOT_EXIST)&&(err!=ERROR_GEN_FAILURE)&&(err!=ERROR_NETWORK_BUSY)&&(err!=ERROR_BAD_NET_NAME)))
  637. throw makeOsExceptionV(err, "CFile::remove %s", filename.get());
  638. //PROGLOG("Retrying(%d) DeleteFile %s, err=%d",retry,filename,err);
  639. Sleep(retry*100);
  640. }
  641. return false;
  642. #else
  643. if (isDirectory()==fileBool::foundYes) {
  644. if (rmdir(filename) == 0)
  645. return true;
  646. }
  647. else {
  648. if (unlink(filename) == 0)
  649. return true;
  650. }
  651. if (ENOENT!=errno)
  652. throw makeErrnoExceptionV("CFile::remove %s", filename.get());
  653. return false;
  654. #endif
  655. }
  656. void CFile::rename(const char *newname)
  657. {
  658. // now hopefully newname is just file tail
  659. // however we do allow full paths and extract tail, warning if the directory appears to mismatch
  660. StringBuffer path;
  661. splitDirTail(filename,path);
  662. StringBuffer newdir;
  663. const char *tail = splitDirTail(newname,newdir);
  664. if (path.length()&&newdir.length()) {
  665. if (strcmp(newdir.str(),path.str())!=0)
  666. IWARNLOG("CFile::rename '%s' to '%s' : directory mismatch",filename.get(),newname);
  667. }
  668. const char *dst = path.append(tail);
  669. if (isPathSepChar(dst[0])&&(dst[1]==dst[0])) { // hmm is share - convert to local path
  670. RemoteFilename rfn;
  671. rfn.setRemotePath(dst);
  672. if (rfn.isLocal())
  673. dst = rfn.getLocalPath(path.clear()).str();
  674. }
  675. if (-1 == ::rename(filename, dst))
  676. throw makeErrnoExceptionV("CFile::rename(%s, %s)", filename.get(),dst);
  677. filename.set(path);
  678. }
  679. void CFile::move(const char *newname)
  680. {
  681. if (!newname||!*newname)
  682. return;
  683. StringBuffer path;
  684. if (isPathSepChar(newname[0])&&(newname[1]==newname[0])) { // hmm is share - convert to local path
  685. RemoteFilename rfn;
  686. rfn.setRemotePath(newname);
  687. if (rfn.isLocal())
  688. newname = rfn.getLocalPath(path.clear()).str();
  689. }
  690. #ifdef _WIN32
  691. unsigned retry = 0;
  692. for (;;) {
  693. if (MoveFileEx(filename.get(),newname, MOVEFILE_REPLACE_EXISTING))
  694. return;
  695. DWORD err = GetLastError();
  696. if ((retry++==10)|| // some or all of the following can occur when the domain controller gets busy
  697. // retrying improves chance of success
  698. ((err!=ERROR_NETNAME_DELETED)&&(err!=ERROR_DEV_NOT_EXIST)&&(err!=ERROR_GEN_FAILURE)&&(err!=ERROR_NETWORK_BUSY)&&(err!=ERROR_BAD_NET_NAME)))
  699. throw makeOsExceptionV(err, "CFile::move(%s, %s)", filename.get(), newname);
  700. Sleep(retry*100);
  701. }
  702. #else
  703. int ret=::rename(filename.get(),newname);
  704. if (ret==-1)
  705. throw makeErrnoExceptionV("CFile::move(%s, %s)", filename.get(), newname);
  706. #endif
  707. filename.set(newname);
  708. }
  709. #ifdef _WIN32
  710. DWORD CALLBACK fastCopyProgressRoutine(
  711. LARGE_INTEGER TotalFileSize,
  712. LARGE_INTEGER TotalBytesTransferred,
  713. LARGE_INTEGER StreamSize,
  714. LARGE_INTEGER StreamBytesTransferred,
  715. DWORD dwStreamNumber,
  716. DWORD dwCallbackReason,
  717. HANDLE hSourceFile,
  718. HANDLE hDestinationFile,
  719. LPVOID lpData
  720. )
  721. {
  722. if (TotalBytesTransferred.QuadPart<=TotalFileSize.QuadPart)
  723. {
  724. CFPmode status = ((ICopyFileProgress *)lpData)->onProgress(TotalBytesTransferred.QuadPart,TotalFileSize.QuadPart);
  725. switch (status)
  726. {
  727. case CFPcontinue:
  728. return PROGRESS_CONTINUE;
  729. case CFPstop:
  730. return PROGRESS_STOP;
  731. default:
  732. return PROGRESS_CANCEL;
  733. }
  734. }
  735. return PROGRESS_CONTINUE;
  736. }
  737. #endif
  738. bool CFile::fastCopyFile(CFile &target, size32_t buffersize, ICopyFileProgress *progress)
  739. {
  740. // only currently supported for windows
  741. #ifdef _WIN32
  742. unsigned retry = 0;
  743. for (;;) {
  744. BOOL cancel=FALSE;
  745. if (CopyFileEx(queryFilename(),target.queryFilename(),progress?fastCopyProgressRoutine:NULL,progress?progress:NULL,&cancel,0))
  746. break;
  747. DWORD err = GetLastError();
  748. if ( (err==ERROR_FILE_NOT_FOUND) || (err==ERROR_PATH_NOT_FOUND) )
  749. return false;
  750. if ((retry++==10)|| // some or all of the following can occur when the domain controller gets busy
  751. // retrying improves chance of success
  752. ((err!=ERROR_NETNAME_DELETED)&&(err!=ERROR_DEV_NOT_EXIST)&&(err!=ERROR_GEN_FAILURE)&&(err!=ERROR_NETWORK_BUSY)&&(err!=ERROR_BAD_NET_NAME)))
  753. return false;
  754. Sleep(retry*100);
  755. }
  756. return true;
  757. #else
  758. return false;
  759. #endif
  760. }
  761. void CFile::copySection(const RemoteFilename &dest, offset_t toOfs, offset_t fromOfs, offset_t size, ICopyFileProgress *progress, CFflags copyFlags)
  762. {
  763. // check to see if src and target are remote
  764. Owned<IFile> target = createIFile(dest);
  765. const size32_t buffersize = DEFAULT_COPY_BLKSIZE;
  766. IFOmode omode = IFOwrite;
  767. if (toOfs==(offset_t)-1) {
  768. if (fromOfs==0) {
  769. copyFile(target,this,buffersize,progress,copyFlags);
  770. return;
  771. }
  772. omode = IFOcreate;
  773. toOfs = 0;
  774. }
  775. IFEflags tgtFlags = IFEnone;
  776. if (copyFlags & CFflush_write)
  777. tgtFlags = IFEnocache;
  778. OwnedIFileIO targetIO = target->open(omode, tgtFlags);
  779. if (!targetIO)
  780. throw MakeStringException(-1, "copyFile: target path '%s' could not be created", target->queryFilename());
  781. MemoryAttr mb;
  782. void * buffer = mb.allocate(buffersize);
  783. IFEflags srcFlags = IFEnone;
  784. if (copyFlags & CFflush_read)
  785. srcFlags = IFEnocache;
  786. OwnedIFileIO sourceIO = open(IFOread, srcFlags);
  787. if (!sourceIO)
  788. throw MakeStringException(-1, "copySection: source '%s' not found", queryFilename());
  789. offset_t offset = 0;
  790. offset_t total;
  791. try
  792. {
  793. total = sourceIO->size();
  794. if (total<fromOfs)
  795. total = 0;
  796. else
  797. total -= fromOfs;
  798. if (total>size)
  799. total = size;
  800. while (offset<total)
  801. {
  802. size32_t got = sourceIO->read(fromOfs+offset, (buffersize>total-offset)?((size32_t)(total-offset)):buffersize, buffer);
  803. if (got == 0)
  804. break;
  805. targetIO->write(offset+toOfs, got, buffer);
  806. offset += got;
  807. if (progress && progress->onProgress(offset, total) != CFPcontinue)
  808. break;
  809. }
  810. }
  811. catch (IException *e)
  812. {
  813. StringBuffer s;
  814. s.append("copyFile target=").append(target->queryFilename()).append(" source=").append(queryFilename()).append("; read/write failure").append(": ");
  815. e->errorMessage(s);
  816. IException *e2 = makeOsExceptionV(e->errorCode(), "%s", s.str());
  817. e->Release();
  818. throw e2;
  819. }
  820. }
  821. void CFile::copyTo(IFile *dest, size32_t buffersize, ICopyFileProgress *progress,bool usetmp,CFflags copyFlags)
  822. {
  823. doCopyFile(dest,this,buffersize,progress,NULL,usetmp,copyFlags);
  824. }
  825. void CFile::setReadOnly(bool ro)
  826. {
  827. #ifdef _WIN32
  828. if (!SetFileAttributes(filename, ro ? FILE_ATTRIBUTE_READONLY : FILE_ATTRIBUTE_NORMAL))
  829. {
  830. DWORD err = GetLastError();
  831. if ( (err!=ERROR_FILE_NOT_FOUND) && (err!=ERROR_PATH_NOT_FOUND) )
  832. throw makeOsExceptionV(err, "CFile::setReadOnly %s", filename.get());
  833. }
  834. #else
  835. struct stat info;
  836. if (stat(filename, &info) != 0)
  837. throw makeErrnoExceptionV("CFile::setReadOnly() %s", filename.get());
  838. // not sure correct but consistant with isReadOnly
  839. if (ro)
  840. info.st_mode &= ~(S_IWUSR|S_IWGRP|S_IWOTH);
  841. else
  842. info.st_mode |= (S_IWUSR|S_IWGRP|S_IWOTH);
  843. chmod(filename, info.st_mode);
  844. #endif
  845. }
  846. void CFile::setFilePermissions(unsigned fPerms)
  847. {
  848. #ifndef _WIN32
  849. struct stat info;
  850. if (stat(filename, &info) != 0)
  851. throw makeErrnoExceptionV("CFile::setFilePermissions() %s", filename.get());
  852. if (chmod(filename, fPerms&0777) != 0)
  853. throw makeErrnoExceptionV("CFile::setFilePermissions() %s", filename.get());
  854. #endif
  855. }
  856. offset_t CFile::size()
  857. {
  858. if (stdIoHandle(filename)>=0)
  859. return 0; // dummy value
  860. #ifdef _WIN32
  861. WIN32_FILE_ATTRIBUTE_DATA info;
  862. if (GetFileAttributesEx(filename, GetFileExInfoStandard, &info) != 0) {
  863. LARGE_INTEGER x;
  864. x.LowPart = info.nFileSizeLow;
  865. x.HighPart = info.nFileSizeHigh;
  866. return (offset_t)x.QuadPart;
  867. }
  868. #else
  869. struct stat info;
  870. if (stat(filename, &info) == 0)
  871. return info.st_size;
  872. #endif
  873. #if 0
  874. // we could try opening but I don't think needed
  875. Owned<IFileIO>io = openShared(IFOread,IFSHfull);
  876. if (io)
  877. return io->size();
  878. #endif
  879. return (offset_t)-1;
  880. }
  881. bool CFile::setCompression(bool set)
  882. {
  883. #ifdef _WIN32
  884. DWORD attr=::GetFileAttributes(filename.get());
  885. if(attr==-1)
  886. throw makeOsExceptionV(::GetLastError(), "CFile::setCompression %s", filename.get());
  887. if (((attr & FILE_ATTRIBUTE_COMPRESSED) != 0) == set)
  888. return true;
  889. HANDLE handle=::CreateFile(filename.get(),GENERIC_READ|GENERIC_WRITE,0,NULL,OPEN_EXISTING,FILE_FLAG_BACKUP_SEMANTICS,NULL);
  890. if(handle==INVALID_HANDLE_VALUE)
  891. throw makeOsExceptionV(::GetLastError(), "CFile::setCompression %s", filename.get());
  892. USHORT compression=set ? COMPRESSION_FORMAT_DEFAULT : COMPRESSION_FORMAT_NONE;
  893. DWORD bytes;
  894. if(::DeviceIoControl(handle, FSCTL_SET_COMPRESSION, &compression, sizeof(compression), NULL, 0, &bytes, NULL))
  895. {
  896. ::CloseHandle(handle);
  897. return true;
  898. }
  899. DWORD err=::GetLastError();
  900. ::CloseHandle(handle);
  901. throw makeOsExceptionV(err, "CFile::setCompression %s", filename.get());
  902. #else
  903. return false;
  904. #endif
  905. }
  906. offset_t CFile::compressedSize()
  907. {
  908. #ifdef _WIN32
  909. DWORD hi, lo=::GetCompressedFileSize(filename.get(),&hi), err;
  910. if(lo==INVALID_FILE_SIZE && (err=::GetLastError())!=NO_ERROR)
  911. {
  912. if ( (err!=ERROR_FILE_NOT_FOUND) && (err!=ERROR_PATH_NOT_FOUND) )
  913. throw makeOsExceptionV(err,"CFile::compressedSize %s", filename.get());
  914. return -1;
  915. }
  916. return makeint64(hi,lo);
  917. #else
  918. return size();
  919. #endif
  920. }
  921. class CDiscretionaryFileLock: implements IDiscretionaryLock, public CInterface
  922. {
  923. bool locked;
  924. bool excllock;
  925. Linked<IFile> file;
  926. Linked<IFileIO> fileio;
  927. HANDLE handle;
  928. public:
  929. CDiscretionaryFileLock(IFile *_file)
  930. : file(_file)
  931. {
  932. excllock = false;
  933. locked = false;
  934. #ifdef _WIN32
  935. handle=::CreateFile(file->queryFilename(),GENERIC_READ,FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE,NULL,OPEN_EXISTING,FILE_FLAG_BACKUP_SEMANTICS,NULL);
  936. if(handle==INVALID_HANDLE_VALUE)
  937. {
  938. handle = NULLFILE;
  939. throw makeOsExceptionV(GetLastError(), "CDiscretionaryFileLock::openhandle %s", file->queryFilename());
  940. }
  941. #else
  942. handle = _lopen(file->queryFilename(), O_RDONLY, 0);
  943. if (handle == -1)
  944. {
  945. handle = NULLFILE;
  946. throw makeErrnoExceptionV(errno, "CDiscretionaryFileLock::openhandle %s", file->queryFilename());
  947. }
  948. #endif
  949. }
  950. CDiscretionaryFileLock(IFileIO *_fileio)
  951. : fileio(_fileio)
  952. {
  953. excllock = false;
  954. locked = false;
  955. handle = NULLFILE;
  956. CFileIO *cfileio = QUERYINTERFACE(_fileio,CFileIO);
  957. if (cfileio)
  958. handle = cfileio->queryHandle();
  959. if (handle==NULLFILE)
  960. throw makeStringException(-1, "CDiscretionaryFileLock - invalid parameter");
  961. }
  962. ~CDiscretionaryFileLock()
  963. {
  964. if (locked)
  965. unlock();
  966. if ((handle!=NULLFILE)&&!fileio.get())
  967. #ifdef _WIN32
  968. CloseHandle(handle);
  969. #else
  970. _lclose(handle);
  971. #endif
  972. }
  973. IMPLEMENT_IINTERFACE;
  974. virtual bool isLocked() { return (handle!=NULLFILE); }
  975. virtual bool isExclusiveLocked() { return excllock; }
  976. bool lock(bool exclusive=true, unsigned timeout=INFINITE)
  977. {
  978. if (locked) {
  979. if (exclusive) {
  980. if (excllock)
  981. return true;
  982. unlock(); // have to unlock - unfortunate as means no window-less change mode
  983. }
  984. else {
  985. if (!excllock)
  986. return true;
  987. unlock(); // have to unlock - unfortunate as means no window-less change mode
  988. }
  989. }
  990. unsigned interval = 1;
  991. unsigned start = msTick();
  992. for (;;) {
  993. #ifdef _WIN32
  994. OVERLAPPED overlapped;
  995. memset(&overlapped,0,sizeof(overlapped));
  996. if (LockFileEx(handle,
  997. (exclusive?LOCKFILE_EXCLUSIVE_LOCK:0)|((timeout==INFINITE)?0:LOCKFILE_FAIL_IMMEDIATELY),
  998. 0,1,0,&overlapped))
  999. break;
  1000. DWORD err = ::GetLastError();
  1001. if (err!=ERROR_LOCK_VIOLATION)
  1002. throw makeOsException(err, "CDiscretionaryFileLock::lock");
  1003. #else
  1004. if (setShareLock(handle,exclusive?IFSHnone:IFSHread))
  1005. break;
  1006. #endif
  1007. unsigned now = msTick();
  1008. if (now-start>=timeout)
  1009. return false;
  1010. if (interval>timeout-now+start)
  1011. interval = timeout-now+start;
  1012. Sleep(interval);
  1013. interval *= 2;
  1014. if (interval>1000)
  1015. interval = 1000;
  1016. }
  1017. excllock = exclusive;
  1018. locked = true;
  1019. return true;
  1020. }
  1021. void unlock()
  1022. {
  1023. if (handle!=NULLFILE)
  1024. {
  1025. #ifdef _WIN32
  1026. OVERLAPPED overlapped;
  1027. memset(&overlapped,0,sizeof(overlapped));
  1028. if (!UnlockFileEx(handle,0,1,0,&overlapped))
  1029. throw makeOsException(::GetLastError(), "CDiscretionaryFileLock::unlockhandle");
  1030. #else
  1031. setShareLock(handle,IFSHfull);
  1032. #endif
  1033. }
  1034. }
  1035. };
  1036. IDiscretionaryLock *createDiscretionaryLock(IFile *file)
  1037. {
  1038. return new CDiscretionaryFileLock(file);
  1039. }
  1040. IDiscretionaryLock *createDiscretionaryLock(IFileIO *fileio)
  1041. {
  1042. return new CDiscretionaryFileLock(fileio);
  1043. }
  1044. unsigned CFile::getCRC()
  1045. {
  1046. if (stdIoHandle(filename)>=0)
  1047. return 0; // dummy value
  1048. unsigned crc=~0;
  1049. MemoryAttr ma;
  1050. void *buf = ma.allocate(0x10000);
  1051. Owned<IFileIO> fileio = open(IFOread);
  1052. if (fileio) {
  1053. offset_t pos=0;
  1054. for (;;) {
  1055. size32_t rd = fileio->read(pos,0x10000,buf);
  1056. if (!rd)
  1057. break;
  1058. crc=crc32((const char *)buf,rd,crc);
  1059. pos += rd;
  1060. }
  1061. }
  1062. return ~crc;
  1063. }
  1064. //---------------------------------------------------------------------------
  1065. #ifdef _WIN32
  1066. static bool parseShare(const char *filename,IpAddress &machine,StringBuffer &share)
  1067. { // windows share parsing
  1068. if (!filename||!isPathSepChar(filename[0])||(filename[0]!=filename[1]))
  1069. return false;
  1070. const char *start = filename+2;
  1071. const char * end = start;
  1072. while (*end && !isPathSepChar(*end))
  1073. end++;
  1074. if (!*end)
  1075. return false;
  1076. StringBuffer ipText(end-start, start);
  1077. machine.ipset(ipText.str());
  1078. end++;
  1079. while (*end && !isPathSepChar(*end))
  1080. end++;
  1081. start = filename;
  1082. while (start!=end) {
  1083. if (*start=='/')
  1084. share.append('\\');
  1085. else
  1086. share.append(*start);
  1087. start++;
  1088. }
  1089. return true;
  1090. }
  1091. static CriticalSection connectcrit;
  1092. static bool connectToExternalDrive(const char * const filename)
  1093. {
  1094. #if 0
  1095. //The following code used the passwordProvider. Retained in case similar code is needed in the future.
  1096. CriticalBlock block(connectcrit);
  1097. if (!passwordProvider)
  1098. return false;
  1099. StringBuffer share, username, password;
  1100. IpAddress ip;
  1101. if (!parseShare(filename,ip,share))
  1102. return false;
  1103. if (!passwordProvider->getPassword(ip, username, password))
  1104. return false;
  1105. // first see if connected
  1106. char buf[255];
  1107. buf[0] = 0;
  1108. DWORD len = sizeof(buf);
  1109. DWORD err = WNetGetUser(share.str(),buf,&len);
  1110. if ((err==0)&&(stricmp(username.str(),buf)==0)) {
  1111. // check can access share as well
  1112. for (unsigned i=0;i<10;i++) {
  1113. DWORD ret = (DWORD)GetFileAttributes(share.str());
  1114. DWORD err = (ret==(DWORD)-1)?GetLastError():0;
  1115. if (err!=ERROR_IO_INCOMPLETE)
  1116. break;
  1117. Sleep(100*i);
  1118. }
  1119. if (err==0)
  1120. return true;
  1121. }
  1122. for (unsigned retry=0;retry<5;retry++) {
  1123. NETRESOURCE res;
  1124. memset(&res, 0, sizeof(res));
  1125. res.dwType = RESOURCETYPE_DISK;
  1126. res.lpRemoteName = (char *)share.str();
  1127. err = WNetAddConnection2(&res, password.str(), username.str(), 0);
  1128. if (err) {
  1129. if (err==ERROR_SESSION_CREDENTIAL_CONFLICT) {
  1130. WNetCancelConnection2(res.lpRemoteName, 0, false);
  1131. err = WNetAddConnection2(&res, password.str(), username.str(), 0);
  1132. }
  1133. if (err)
  1134. IERRLOG("WNetAddConnection2(%d): connecting to %s, User: %s",err,res.lpRemoteName,username.str());
  1135. }
  1136. if (err==0)
  1137. return true;
  1138. Sleep(retry*100);
  1139. }
  1140. #endif
  1141. return false;
  1142. }
  1143. static void disconnectFromExternalDrive(const char * const filename)
  1144. {
  1145. CriticalBlock block(connectcrit);
  1146. StringBuffer share;
  1147. IpAddress ip;
  1148. if (!parseShare(filename,ip,share))
  1149. return;
  1150. if (share.length()&&isShareChar(share.charAt(share.length())))
  1151. WNetCancelConnection2((char *)share.str(), 0, 0);
  1152. }
  1153. class CWindowsRemoteFile : implements IFile, public CInterface
  1154. {
  1155. IFile *ifile;
  1156. StringAttr filename;
  1157. bool connected;
  1158. inline bool connect()
  1159. {
  1160. if (!connected)
  1161. connected = connectToExternalDrive(filename);
  1162. return connected;
  1163. }
  1164. public:
  1165. CWindowsRemoteFile(const char * _filename)
  1166. : filename(_filename)
  1167. {
  1168. connected = false;
  1169. ifile = new CFile(_filename);
  1170. }
  1171. ~CWindowsRemoteFile()
  1172. {
  1173. ifile->Release();
  1174. #ifdef REMOTE_DISCONNECT_ON_DESTRUCTOR
  1175. if (connected)
  1176. disconnectFromExternalDrive(filename);
  1177. #endif
  1178. }
  1179. IMPLEMENT_IINTERFACE
  1180. virtual bool exists()
  1181. {
  1182. connect();
  1183. return ifile->exists();
  1184. }
  1185. virtual bool getTime(CDateTime * createTime, CDateTime * modifiedTime, CDateTime * accessedTime)
  1186. {
  1187. connect();
  1188. return ifile->getTime(createTime, modifiedTime, accessedTime);
  1189. }
  1190. virtual bool setTime(const CDateTime * createTime, const CDateTime * modifiedTime, const CDateTime * accessedTime)
  1191. {
  1192. connect();
  1193. if (ifile->setTime(createTime, modifiedTime, accessedTime))
  1194. return true;
  1195. if (connected||!connect())
  1196. return false;
  1197. return ifile->setTime(createTime, modifiedTime, accessedTime);
  1198. }
  1199. virtual fileBool isDirectory()
  1200. {
  1201. connect();
  1202. fileBool ok = ifile->isDirectory();
  1203. if (ok == fileBool::notFound && !connected && connect())
  1204. ok = ifile->isDirectory();
  1205. return ok;
  1206. }
  1207. virtual fileBool isFile()
  1208. {
  1209. connect();
  1210. fileBool ok = ifile->isFile();
  1211. if (ok == fileBool::notFound && !connected && connect())
  1212. ok = ifile->isFile();
  1213. return ok;
  1214. }
  1215. virtual fileBool isReadOnly()
  1216. {
  1217. connect();
  1218. fileBool ok = ifile->isReadOnly();
  1219. if (ok == fileBool::notFound && !connected && connect())
  1220. ok = ifile->isFile();
  1221. return ok;
  1222. }
  1223. virtual IFileIO * open(IFOmode mode,IFEflags extraFlags=IFEnone)
  1224. {
  1225. connect();
  1226. return ifile->open(mode,extraFlags);
  1227. }
  1228. virtual IFileIO * openShared(IFOmode mode,IFSHmode shared,IFEflags extraFlags=IFEnone)
  1229. {
  1230. connect();
  1231. return ifile->openShared(mode,shared,extraFlags);
  1232. }
  1233. virtual IFileAsyncIO * openAsync(IFOmode mode)
  1234. {
  1235. connect();
  1236. return ifile->openAsync(mode);
  1237. }
  1238. virtual const char * queryFilename()
  1239. {
  1240. return ifile->queryFilename();
  1241. }
  1242. virtual bool remove()
  1243. {
  1244. connect();
  1245. unsigned attempt=0; \
  1246. return ifile->remove();
  1247. }
  1248. virtual void rename(const char *newname)
  1249. {
  1250. connect();
  1251. StringBuffer path;
  1252. splitDirTail(filename,path);
  1253. StringBuffer newdir;
  1254. const char *tail = splitDirTail(newname,newdir);
  1255. if ((newname[0]=='\\')&&(newname[1]=='\\')) { // rename to remote
  1256. if (path.length()&&newdir.length()) {
  1257. if (strcmp(newdir.str(),path.str())!=0)
  1258. IWARNLOG("CWindowsRemoteFile '%s' to '%s' : directory mismatch",filename.get(),newname);
  1259. }
  1260. newname = tail; // just rename using tail
  1261. }
  1262. ifile->rename(newname);
  1263. path.append(tail);
  1264. filename.set(path);
  1265. }
  1266. virtual void move(const char *newName)
  1267. {
  1268. connect();
  1269. ifile->move(newName);
  1270. filename.set(ifile->queryFilename());
  1271. }
  1272. virtual void setReadOnly(bool ro)
  1273. {
  1274. connect();
  1275. ifile->setReadOnly(ro);
  1276. }
  1277. virtual void setFilePermissions(unsigned fPerms)
  1278. {
  1279. connect();
  1280. ifile->setFilePermissions(fPerms);
  1281. }
  1282. virtual offset_t size()
  1283. {
  1284. connect();
  1285. offset_t ret=ifile->size();
  1286. if ((ret==(offset_t)-1)&&!connected&&connect())
  1287. ret=ifile->size();
  1288. return ret;
  1289. }
  1290. virtual bool setCompression(bool set)
  1291. {
  1292. connect();
  1293. return ifile->setCompression(set);
  1294. }
  1295. virtual offset_t compressedSize()
  1296. {
  1297. connect();
  1298. return ifile->compressedSize();
  1299. }
  1300. bool fastCopyFile(CWindowsRemoteFile &target, size32_t buffersize, ICopyFileProgress *progress)
  1301. {
  1302. #ifdef _WIN32
  1303. CFile *src = QUERYINTERFACE(ifile,CFile);
  1304. if (!src)
  1305. return false;
  1306. CFile *dst = QUERYINTERFACE(target.ifile,CFile);
  1307. if (!dst)
  1308. return false;
  1309. target.isFile(); // encourage connect on target
  1310. connect();
  1311. return src->fastCopyFile(*dst, buffersize, progress);
  1312. #else
  1313. return false;
  1314. #endif
  1315. }
  1316. bool fastCopyFile(CFile &target, size32_t buffersize, ICopyFileProgress *progress)
  1317. {
  1318. #ifdef _WIN32
  1319. CFile *src = QUERYINTERFACE(ifile,CFile);
  1320. if (!src)
  1321. return false;
  1322. connect();
  1323. return src->fastCopyFile(target, buffersize, progress);
  1324. #else
  1325. return false;
  1326. #endif
  1327. }
  1328. bool fastCopyFileRev(CFile &src, size32_t buffersize, ICopyFileProgress *progress)
  1329. {
  1330. #ifdef _WIN32
  1331. CFile *dst = QUERYINTERFACE(ifile,CFile);
  1332. if (!dst)
  1333. return false;
  1334. connect();
  1335. return src.fastCopyFile(*dst, buffersize, progress);
  1336. #else
  1337. return false;
  1338. #endif
  1339. }
  1340. void copyTo(IFile *dest, size32_t buffersize, ICopyFileProgress *progress, bool usetmp,CFflags copyFlags)
  1341. {
  1342. doCopyFile(dest,this,buffersize,progress,NULL,usetmp,copyFlags);
  1343. }
  1344. bool createDirectory()
  1345. {
  1346. connect();
  1347. return localCreateDirectory(filename);
  1348. }
  1349. IDirectoryIterator *directoryFiles(const char *mask,bool sub,bool includedirs)
  1350. {
  1351. connect();
  1352. return ifile->directoryFiles(mask,sub,includedirs);
  1353. }
  1354. IDirectoryDifferenceIterator *monitorDirectory(
  1355. IDirectoryIterator *prev=NULL, // in (NULL means use current as baseline)
  1356. const char *mask=NULL,
  1357. bool sub=false,
  1358. bool includedirs=false,
  1359. unsigned checkinterval=60*1000,
  1360. unsigned timeout=(unsigned)-1,
  1361. Semaphore *abortsem=NULL) // returns NULL if timed out or abortsem signalled
  1362. {
  1363. connect();
  1364. return ifile->monitorDirectory(prev,mask,sub,includedirs,checkinterval,timeout,abortsem);
  1365. }
  1366. bool getInfo(bool &isdir,offset_t &size,CDateTime &modtime)
  1367. {
  1368. connect();
  1369. return ifile->getInfo(isdir,size,modtime);
  1370. }
  1371. unsigned getCRC()
  1372. {
  1373. connect();
  1374. return ifile->getCRC();
  1375. }
  1376. void setCreateFlags(unsigned short cflags)
  1377. {
  1378. ifile->setCreateFlags(cflags);
  1379. }
  1380. void setShareMode(IFSHmode shmode)
  1381. {
  1382. ifile->setShareMode(shmode);
  1383. }
  1384. void copySection(const RemoteFilename &dest, offset_t toOfs, offset_t fromOfs, offset_t size, ICopyFileProgress *progress, CFflags copyFlags)
  1385. {
  1386. connect();
  1387. ifile->copySection(dest,toOfs,fromOfs,size,progress,copyFlags);
  1388. }
  1389. IMemoryMappedFile *openMemoryMapped(offset_t ofs, memsize_t len, bool write)
  1390. {
  1391. throw MakeStringException(-1,"Remote file cannot be memory mapped");
  1392. return NULL;
  1393. }
  1394. };
  1395. #endif
  1396. IFileIO *_createIFileIO(const void *buffer, unsigned sz, bool readOnly)
  1397. {
  1398. class CMemoryBufferIO : implements IFileIO, public CInterface
  1399. {
  1400. MemoryBuffer mb;
  1401. void *buffer;
  1402. size32_t sz;
  1403. bool readOnly;
  1404. public:
  1405. IMPLEMENT_IINTERFACE;
  1406. CMemoryBufferIO(const void *_buffer, unsigned _sz, bool _readOnly) : readOnly(_readOnly)
  1407. {
  1408. // JCSMORE - should probably have copy as option
  1409. mb.append(_sz, _buffer);
  1410. buffer = (void *)mb.toByteArray();
  1411. sz = mb.length();
  1412. }
  1413. virtual size32_t read(offset_t pos, size32_t len, void * data)
  1414. {
  1415. if (pos>sz)
  1416. throw MakeStringException(-1, "CMemoryBufferIO: read beyond end of buffer pos=%" I64F "d, len=%d, buffer length=%d", pos, len, mb.length());
  1417. if (pos+len > sz)
  1418. len = (size32_t)(sz-pos);
  1419. memcpy(data, (byte *)buffer+pos, len);
  1420. return len;
  1421. }
  1422. virtual offset_t size() { return sz; }
  1423. virtual size32_t write(offset_t pos, size32_t len, const void * data)
  1424. {
  1425. assertex(!readOnly);
  1426. if (pos+len>sz)
  1427. throw MakeStringException(-1, "CMemoryBufferIO: UNIMPLEMENTED, writing beyond buffer, pos=%" I64F "d, len=%d, buffer length=%d", pos, len, mb.length());
  1428. memcpy((byte *)buffer+pos, data, len);
  1429. return len;
  1430. }
  1431. virtual void flush() {}
  1432. virtual void close() {}
  1433. virtual unsigned __int64 getStatistic(StatisticKind kind)
  1434. {
  1435. return 0;
  1436. }
  1437. virtual void setSize(offset_t size)
  1438. {
  1439. if (size > mb.length())
  1440. throw MakeStringException(-1, "CMemoryBufferIO: UNIMPLEMENTED, setting size %" I64F "d beyond end of buffer, buffer length=%d", size, mb.length());
  1441. mb.setLength((size32_t)size);
  1442. }
  1443. offset_t appendFile(IFile *file,offset_t pos,offset_t len)
  1444. {
  1445. if (!file)
  1446. return 0;
  1447. const size32_t buffsize = 0x10000;
  1448. void * buffer = mb.reserve(buffsize);
  1449. Owned<IFileIO> fileio = file->open(IFOread);
  1450. offset_t ret=0;
  1451. while (len) {
  1452. size32_t toread = (len>=buffsize)?buffsize:(size32_t)len;
  1453. size32_t read = fileio->read(pos,toread,buffer);
  1454. if (read<buffsize)
  1455. mb.setLength(mb.length()+read-buffsize);
  1456. if (read==0)
  1457. break;
  1458. pos += read;
  1459. len -= read;
  1460. ret += read;
  1461. }
  1462. return ret;
  1463. }
  1464. };
  1465. return new CMemoryBufferIO(buffer, sz, readOnly);
  1466. }
  1467. IFileIO * createIFileI(unsigned len, const void * buffer)
  1468. {
  1469. return _createIFileIO((void *)buffer, len, true);
  1470. }
  1471. IFileIO * createIFileIO(unsigned len, void * buffer)
  1472. {
  1473. return _createIFileIO(buffer, len, false);
  1474. }
  1475. IFileIO * createIFileIO(StringBuffer & buffer)
  1476. {
  1477. return _createIFileIO((void *)buffer.str(), buffer.length(), true);
  1478. }
  1479. IFileIO * createIFileIO(MemoryBuffer & buffer)
  1480. {
  1481. return _createIFileIO(buffer.toByteArray(), buffer.length(), false);
  1482. }
  1483. //---------------------------------------------------------------------------
  1484. class jlib_decl CSequentialFileIO : public CFileIO
  1485. {
  1486. offset_t pos;
  1487. void checkPos(const char *fn,offset_t _pos)
  1488. {
  1489. if (_pos!=pos)
  1490. throw MakeStringException(-1, "CSequentialFileIO %s out of sequence (%" I64F "d,%" I64F "d)",fn,pos,_pos);
  1491. }
  1492. public:
  1493. CSequentialFileIO(HANDLE h,IFOmode _openmode,IFSHmode _sharemode,IFEflags _extraFlags)
  1494. : CFileIO(h,_openmode,_sharemode,_extraFlags)
  1495. {
  1496. pos = 0;
  1497. }
  1498. ~CSequentialFileIO()
  1499. {
  1500. }
  1501. size32_t read(offset_t _pos, size32_t len, void * data)
  1502. {
  1503. checkPos("read",_pos);
  1504. #ifdef _WIN32
  1505. // Can't use checked_read because don't have the c fileno for it
  1506. DWORD numRead;
  1507. if (ReadFile(file,data,len,&numRead,NULL) == 0) {
  1508. DWORD err = GetLastError();
  1509. if (err==ERROR_BROKEN_PIPE) // windows returns this at end of pipe
  1510. return 0;
  1511. throw makeOsException(GetLastError(),"CSequentialFileIO::read");
  1512. }
  1513. size32_t ret = (size32_t)numRead;
  1514. #else
  1515. size32_t ret = checked_read(file, data, len);
  1516. #endif
  1517. pos += ret;
  1518. return ret;
  1519. }
  1520. virtual size32_t write(offset_t _pos, size32_t len, const void * data)
  1521. {
  1522. checkPos("write",_pos);
  1523. size32_t ret;
  1524. #ifdef _WIN32
  1525. DWORD numWritten;
  1526. if (!WriteFile(file, data, len, &numWritten, NULL))
  1527. throw makeOsException(GetLastError(), "CSequentialFileIO::write");
  1528. if (numWritten != len)
  1529. throw makeOsException(DISK_FULL_EXCEPTION_CODE, "CSequentialFileIO::write");
  1530. ret = (size32_t) numWritten;
  1531. #else
  1532. ret = ::write(file,data,len);
  1533. if (ret==(size32_t)-1)
  1534. {
  1535. PrintStackReport();
  1536. IERRLOG("errno(%d): %" I64F "d %u",errno,pos,len);
  1537. throw makeErrnoException(errno, "CFileIO::write");
  1538. }
  1539. if (ret<len)
  1540. throw makeOsException(DISK_FULL_EXCEPTION_CODE, "CSequentialFileIO::write");
  1541. #endif
  1542. pos += ret;
  1543. return ret;
  1544. }
  1545. };
  1546. IFileIO * CFile::openShared(IFOmode mode,IFSHmode share,IFEflags extraFlags)
  1547. {
  1548. int stdh = stdIoHandle(filename);
  1549. HANDLE handle = openHandle(mode,share,false, stdh);
  1550. if (handle==NULLFILE)
  1551. return NULL;
  1552. #ifndef _WIN32
  1553. set_inherit(handle, false);
  1554. #endif
  1555. if (stdh>=0)
  1556. return new CSequentialFileIO(handle,mode,share,extraFlags);
  1557. Owned<IFileIO> io = new CFileIO(handle,mode,share,extraFlags);
  1558. #ifdef CHECK_FILE_IO
  1559. return new CCheckingFileIO(filename, io);
  1560. #else
  1561. return io.getClear();
  1562. #endif
  1563. }
  1564. //---------------------------------------------------------------------------
  1565. extern jlib_decl IFileIO *createIFileIO(HANDLE handle,IFOmode openmode,IFEflags extraFlags)
  1566. {
  1567. return new CFileIO(handle,openmode,IFSHfull,extraFlags);
  1568. }
  1569. offset_t CFileIO::appendFile(IFile *file,offset_t pos,offset_t len)
  1570. {
  1571. if (!file)
  1572. return 0;
  1573. CriticalBlock procedure(cs);
  1574. MemoryAttr mb;
  1575. const size32_t buffsize = 0x10000;
  1576. void * buffer = mb.allocate(buffsize);
  1577. Owned<IFileIO> fileio = file->open(IFOread);
  1578. offset_t ret=0;
  1579. offset_t outp = size();
  1580. while (len) {
  1581. size32_t toread = (len>=buffsize) ? buffsize : (size32_t)len;
  1582. size32_t read = fileio->read(pos,toread,buffer);
  1583. if (read==0)
  1584. break;
  1585. size32_t wr = write(outp,read,buffer);
  1586. pos += read;
  1587. outp += wr;
  1588. len -= read;
  1589. ret += wr;
  1590. if (wr!=read)
  1591. break;
  1592. }
  1593. return ret;
  1594. }
  1595. unsigned __int64 CFileIO::getStatistic(StatisticKind kind)
  1596. {
  1597. return stats.getStatistic(kind);
  1598. }
  1599. #ifdef _WIN32
  1600. //-- Windows implementation -------------------------------------------------
  1601. CFileIO::CFileIO(HANDLE handle, IFOmode _openmode, IFSHmode _sharemode, IFEflags _extraFlags)
  1602. : unflushedReadBytes(0), unflushedWriteBytes(0)
  1603. {
  1604. assertex(handle != NULLFILE);
  1605. throwOnError = false;
  1606. file = handle;
  1607. sharemode = _sharemode;
  1608. openmode = _openmode;
  1609. extraFlags = _extraFlags; // page cache flush option silently ignored on Windows for now
  1610. if (extraFlags & IFEnocache)
  1611. if (!isPCFlushAllowed())
  1612. extraFlags = static_cast<IFEflags>(extraFlags & ~IFEnocache);
  1613. }
  1614. CFileIO::~CFileIO()
  1615. {
  1616. try
  1617. {
  1618. //note this will not call the virtual close() if anyone ever derived from this class.
  1619. //the clean fix is to move this code to beforeDispose()
  1620. close();
  1621. }
  1622. catch (IException * e)
  1623. {
  1624. EXCLOG(e, "CFileIO::~CFileIO");
  1625. e->Release();
  1626. }
  1627. }
  1628. void CFileIO::close()
  1629. {
  1630. if (file != NULLFILE)
  1631. {
  1632. if (!CloseHandle(file))
  1633. throw makeOsException(GetLastError(),"CFileIO::close");
  1634. }
  1635. file = NULLFILE;
  1636. }
  1637. void CFileIO::flush()
  1638. {
  1639. if (!FlushFileBuffers(file))
  1640. throw makeOsException(GetLastError(),"CFileIO::flush");
  1641. }
  1642. offset_t CFileIO::size()
  1643. {
  1644. LARGE_INTEGER pos;
  1645. pos.LowPart = GetFileSize(file, (unsigned long *)&pos.HighPart);
  1646. if (pos.LowPart==-1) {
  1647. DWORD err = GetLastError();
  1648. if (err!=0)
  1649. throw makeOsException(err,"CFileIO::size");
  1650. }
  1651. return pos.QuadPart;
  1652. }
  1653. size32_t CFileIO::read(offset_t pos, size32_t len, void * data)
  1654. {
  1655. CriticalBlock procedure(cs);
  1656. CCycleTimer timer;
  1657. DWORD numRead;
  1658. setPos(pos);
  1659. if (ReadFile(file,data,len,&numRead,NULL) == 0)
  1660. throw makeOsException(GetLastError(),"CFileIO::read");
  1661. stats.ioReadCycles.fetch_add(timer.elapsedCycles());
  1662. stats.ioReadBytes.fetch_add(numRead);
  1663. ++stats.ioReads;
  1664. return (size32_t)numRead;
  1665. }
  1666. void CFileIO::setPos(offset_t newPos)
  1667. {
  1668. LARGE_INTEGER tempPos;
  1669. tempPos.QuadPart = newPos;
  1670. tempPos.LowPart = SetFilePointer(file, tempPos.LowPart, &tempPos.HighPart, FILE_BEGIN);
  1671. }
  1672. size32_t CFileIO::write(offset_t pos, size32_t len, const void * data)
  1673. {
  1674. CriticalBlock procedure(cs);
  1675. CCycleTimer timer;
  1676. DWORD numWritten;
  1677. setPos(pos);
  1678. if (!WriteFile(file,data,len,&numWritten,NULL))
  1679. throw makeOsException(GetLastError(),"CFileIO::write");
  1680. if (numWritten != len)
  1681. throw makeOsException(DISK_FULL_EXCEPTION_CODE,"CFileIO::write");
  1682. stats.ioWriteCycles.fetch_add(timer.elapsedCycles());
  1683. stats.ioWriteBytes.fetch_add(numWritten);
  1684. ++stats.ioWrites;
  1685. return (size32_t)numWritten;
  1686. }
  1687. void CFileIO::setSize(offset_t pos)
  1688. {
  1689. CriticalBlock procedure(cs);
  1690. setPos(pos);
  1691. if (!SetEndOfFile(file))
  1692. throw makeOsException(GetLastError(), "CFileIO::setSize");
  1693. }
  1694. #else
  1695. //-- Unix implementation ----------------------------------------------------
  1696. // More errorno checking TBD
  1697. CFileIO::CFileIO(HANDLE handle, IFOmode _openmode, IFSHmode _sharemode, IFEflags _extraFlags)
  1698. : unflushedReadBytes(0), unflushedWriteBytes(0)
  1699. {
  1700. assertex(handle != NULLFILE);
  1701. throwOnError = false;
  1702. file = handle;
  1703. sharemode = _sharemode;
  1704. openmode = _openmode;
  1705. extraFlags = _extraFlags;
  1706. if (extraFlags & IFEnocache)
  1707. if (!isPCFlushAllowed())
  1708. extraFlags = static_cast<IFEflags>(extraFlags & ~IFEnocache);
  1709. #ifdef CFILEIOTRACE
  1710. DBGLOG("CFileIO::CfileIO(%d,%d,%d,%d)", handle, _openmode, _sharemode, _extraFlags);
  1711. #endif
  1712. }
  1713. CFileIO::~CFileIO()
  1714. {
  1715. try
  1716. {
  1717. close();
  1718. }
  1719. catch (IException * e)
  1720. {
  1721. EXCLOG(e, "CFileIO::~CFileIO");
  1722. e->Release();
  1723. }
  1724. }
  1725. void CFileIO::close()
  1726. {
  1727. if (file != NULLFILE)
  1728. {
  1729. #ifdef CFILEIOTRACE
  1730. DBGLOG("CFileIO::close(%d), extraFlags = %d", file, extraFlags);
  1731. #endif
  1732. if (extraFlags & IFEnocache)
  1733. {
  1734. if (openmode != IFOread)
  1735. {
  1736. #ifdef F_FULLFSYNC
  1737. fcntl(file, F_FULLFSYNC);
  1738. #else
  1739. fdatasync(file);
  1740. #endif
  1741. }
  1742. #ifdef POSIX_FADV_DONTNEED
  1743. posix_fadvise(file, 0, 0, POSIX_FADV_DONTNEED);
  1744. #endif
  1745. }
  1746. if (::close(file) < 0)
  1747. throw makeErrnoException(errno, "CFileIO::close");
  1748. file=NULLFILE;
  1749. }
  1750. }
  1751. void CFileIO::flush()
  1752. {
  1753. CriticalBlock procedure(cs);
  1754. #ifdef F_FULLFSYNC
  1755. if (fcntl(file, F_FULLFSYNC) != 0)
  1756. #else
  1757. if (fdatasync(file) != 0)
  1758. #endif
  1759. throw makeOsException(DISK_FULL_EXCEPTION_CODE, "CFileIO::flush");
  1760. #ifdef POSIX_FADV_DONTNEED
  1761. if (extraFlags & IFEnocache)
  1762. posix_fadvise(file, 0, 0, POSIX_FADV_DONTNEED);
  1763. #endif
  1764. }
  1765. offset_t CFileIO::size()
  1766. {
  1767. CriticalBlock procedure(cs);
  1768. offset_t savedPos = lseek(file,0,SEEK_CUR);
  1769. offset_t length = lseek(file,0,SEEK_END);
  1770. setPos(savedPos);
  1771. return length;
  1772. }
  1773. size32_t CFileIO::read(offset_t pos, size32_t len, void * data)
  1774. {
  1775. if (0==len) return 0;
  1776. CCycleTimer timer;
  1777. size32_t ret = checked_pread(file, data, len, pos);
  1778. stats.ioReadCycles.fetch_add(timer.elapsedCycles());
  1779. stats.ioReadBytes.fetch_add(ret);
  1780. ++stats.ioReads;
  1781. if ( (extraFlags & IFEnocache) && (ret > 0) )
  1782. {
  1783. if (unflushedReadBytes.add_fetch(ret) >= PGCFLUSH_BLKSIZE)
  1784. {
  1785. unflushedReadBytes.store(0);
  1786. #ifdef POSIX_FADV_DONTNEED
  1787. posix_fadvise(file, 0, 0, POSIX_FADV_DONTNEED);
  1788. #endif
  1789. }
  1790. }
  1791. return ret;
  1792. }
  1793. void CFileIO::setPos(offset_t newPos)
  1794. {
  1795. if (file != NULLFILE)
  1796. _llseek(file,newPos,SEEK_SET);
  1797. }
  1798. static void sync_file_region(int fd, offset_t offset, offset_t nbytes)
  1799. {
  1800. #if defined(__linux__) && defined(__NR_sync_file_range)
  1801. (void)syscall(__NR_sync_file_range, fd, offset,
  1802. nbytes, SYNC_FILE_RANGE_WAIT_BEFORE | SYNC_FILE_RANGE_WRITE);
  1803. #elif defined(F_FULLFSYNC)
  1804. fcntl(fd, F_FULLFSYNC);
  1805. #else
  1806. fdatasync(fd);
  1807. #endif
  1808. }
  1809. size32_t CFileIO::write(offset_t pos, size32_t len, const void * data)
  1810. {
  1811. CCycleTimer timer;
  1812. size32_t ret = pwrite(file,data,len,pos);
  1813. stats.ioWriteCycles.fetch_add(timer.elapsedCycles());
  1814. stats.ioWriteBytes.fetch_add(ret);
  1815. ++stats.ioWrites;
  1816. if (ret==(size32_t)-1)
  1817. throw makeErrnoException(errno, "CFileIO::write");
  1818. if (ret<len)
  1819. throw makeOsException(DISK_FULL_EXCEPTION_CODE, "CFileIO::write");
  1820. if ( (extraFlags & IFEnocache) && (ret > 0) )
  1821. {
  1822. if (unflushedWriteBytes.add_fetch(ret) >= PGCFLUSH_BLKSIZE)
  1823. {
  1824. unflushedWriteBytes.store(0);
  1825. // [possibly] non-blocking request to write-out dirty pages
  1826. sync_file_region(file, 0, 0);
  1827. #ifdef POSIX_FADV_DONTNEED
  1828. // flush written-out pages
  1829. posix_fadvise(file, 0, 0, POSIX_FADV_DONTNEED);
  1830. #endif
  1831. }
  1832. }
  1833. return ret;
  1834. }
  1835. void CFileIO::setSize(offset_t pos)
  1836. {
  1837. if (0 != ftruncate(file, pos))
  1838. throw makeErrnoException(errno, "CFileIO::setSize");
  1839. }
  1840. #endif
  1841. //---------------------------------------------------------------------------
  1842. CFileRangeIO::CFileRangeIO(IFileIO * _io, offset_t _headerSize, offset_t _maxLength)
  1843. {
  1844. io.set(_io);
  1845. headerSize = _headerSize;
  1846. maxLength = _maxLength;
  1847. }
  1848. size32_t CFileRangeIO::read(offset_t pos, size32_t len, void * data)
  1849. {
  1850. if (pos + len > maxLength)
  1851. {
  1852. if (pos > maxLength)
  1853. pos = maxLength;
  1854. len = (size32_t)(maxLength - pos);
  1855. }
  1856. return io->read(pos+headerSize, len, data);
  1857. }
  1858. offset_t CFileRangeIO::size()
  1859. {
  1860. return maxLength;
  1861. }
  1862. size32_t CFileRangeIO::write(offset_t pos, size32_t len, const void * data)
  1863. {
  1864. if (pos + len > maxLength)
  1865. {
  1866. if (pos > maxLength)
  1867. pos = maxLength;
  1868. len = (size32_t)(maxLength - pos);
  1869. }
  1870. return io->write(pos+headerSize, len, data);
  1871. }
  1872. //--------------------------------------------------------------------------
  1873. CCheckingFileIO::~CCheckingFileIO()
  1874. {
  1875. if (lastWriteSize && !closed)
  1876. report("FileCheck: IO for File %s destroyed before closing", filename.str());
  1877. }
  1878. size32_t CCheckingFileIO::read(offset_t pos, size32_t len, void * data)
  1879. {
  1880. CriticalBlock block(cs);
  1881. if ((pos == lastReadPos) && (len < minSeqReadSize) && (pos + len != size()))
  1882. report("FileCheck: Sequential read [%s] of %u is < %u", filename.str(), len, minSeqReadSize);
  1883. size32_t numRead = io->read(pos, len, data);
  1884. lastReadPos = pos + numRead;
  1885. return numRead;
  1886. }
  1887. offset_t CCheckingFileIO::size()
  1888. {
  1889. return io->size();
  1890. }
  1891. size32_t CCheckingFileIO::write(offset_t pos, size32_t len, const void * data)
  1892. {
  1893. CriticalBlock block(cs);
  1894. if (len != 0)
  1895. {
  1896. if ((lastWriteSize != 0) && (lastWriteSize < minWriteSize))
  1897. report("FileCheck: Sequential write to [%s] of size %u before offset %" I64F "u of %u is < %u", filename.str(), lastWriteSize, pos, len, minWriteSize);
  1898. lastWriteSize = len;
  1899. }
  1900. else
  1901. report("FileCheck: Unexpected zero byte write on %s at offset %" I64F "u", filename.str(), pos);
  1902. return io->write(pos, len, data);
  1903. }
  1904. void CCheckingFileIO::setSize(offset_t size)
  1905. {
  1906. io->setSize(size);
  1907. }
  1908. offset_t CCheckingFileIO::appendFile(IFile *file,offset_t pos,offset_t len)
  1909. {
  1910. return io->appendFile(file, pos, len);
  1911. }
  1912. void CCheckingFileIO::flush()
  1913. {
  1914. io->flush();
  1915. }
  1916. void CCheckingFileIO::close()
  1917. {
  1918. io->close();
  1919. closed = true;
  1920. }
  1921. unsigned __int64 CCheckingFileIO::getStatistic(StatisticKind kind)
  1922. {
  1923. return io->getStatistic(kind);
  1924. }
  1925. void CCheckingFileIO::report(const char * format, ...)
  1926. {
  1927. va_list args;
  1928. va_start(args, format);
  1929. VALOG(MCinternalError, unknownJob, format, args);
  1930. va_end(args);
  1931. if (!traced)
  1932. {
  1933. printStackReport();
  1934. traced = true;
  1935. }
  1936. }
  1937. //--------------------------------------------------------------------------
  1938. CFileAsyncIO::~CFileAsyncIO()
  1939. {
  1940. try
  1941. {
  1942. close();
  1943. }
  1944. catch (IException * e)
  1945. {
  1946. EXCLOG(e, "CFileAsyncIO::~CFileAsyncIO");
  1947. e->Release();
  1948. }
  1949. }
  1950. void CFileAsyncIO::flush()
  1951. {
  1952. // wait for all outstanding results
  1953. CriticalBlock block(cs);
  1954. ForEachItemInRev(i,results) {
  1955. size32_t dummy;
  1956. results.item(i).getResult(dummy,true);
  1957. }
  1958. }
  1959. offset_t CFileAsyncIO::appendFile(IFile *file,offset_t pos,offset_t len)
  1960. {
  1961. // will implemented if needed
  1962. UNIMPLEMENTED;
  1963. }
  1964. unsigned __int64 CFileAsyncIO::getStatistic(StatisticKind kind)
  1965. {
  1966. //MORE: Could implement - but I don't think this class is currently used
  1967. return 0;
  1968. }
  1969. #ifdef _WIN32
  1970. //-- Windows implementation -------------------------------------------------
  1971. class CFileAsyncResult: implements IFileAsyncResult, public CInterface
  1972. {
  1973. protected: friend class CFileAsyncIO;
  1974. OVERLAPPED overlapped;
  1975. DWORD value;
  1976. DWORD wrsize;
  1977. CFileAsyncIO *parent;
  1978. public:
  1979. IMPLEMENT_IINTERFACE;
  1980. CFileAsyncResult(offset_t offset,size32_t _wrsize)
  1981. {
  1982. parent = NULL;
  1983. memset(&overlapped,0,sizeof(overlapped));
  1984. overlapped.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
  1985. overlapped.Offset = (DWORD)offset;
  1986. overlapped.OffsetHigh = (DWORD)(offset>>32);
  1987. value = (size32_t)-1;
  1988. wrsize = _wrsize;
  1989. }
  1990. ~CFileAsyncResult()
  1991. {
  1992. size32_t dummy;
  1993. getResult(dummy,true);
  1994. CloseHandle(overlapped.hEvent);
  1995. }
  1996. bool getResult(size32_t &ret,bool wait)
  1997. {
  1998. if (value==(size32_t)-1) {
  1999. if (parent) {
  2000. if (GetOverlappedResult(parent->file,&overlapped,&value,wait)==0) {
  2001. int err = GetLastError();
  2002. if (err==ERROR_IO_INCOMPLETE)
  2003. return false;
  2004. if (err!=ERROR_HANDLE_EOF) {
  2005. CriticalBlock block(parent->cs);
  2006. parent->results.zap(*this,true); // don't delete as array does not own
  2007. parent = NULL;
  2008. throw makeOsException(err,"CFileAsyncResult::getResult");
  2009. }
  2010. value = 0;
  2011. }
  2012. CriticalBlock block(parent->cs);
  2013. parent->results.zap(*this,true); // don't delete as array does not own
  2014. parent = NULL;
  2015. }
  2016. else
  2017. return false;
  2018. }
  2019. ret = value;
  2020. if (value<wrsize)
  2021. throw makeOsException(DISK_FULL_EXCEPTION_CODE,"CFileAsyncResult::getResult");
  2022. return true;
  2023. }
  2024. };
  2025. CFileAsyncIO::CFileAsyncIO(HANDLE handle, IFSHmode _sharemode)
  2026. {
  2027. assertex(handle != NULLFILE);
  2028. throwOnError = false;
  2029. file = handle;
  2030. sharemode = _sharemode;
  2031. }
  2032. void CFileAsyncIO::close()
  2033. {
  2034. flush();
  2035. // wait for all outstanding results
  2036. if (file != NULLFILE)
  2037. {
  2038. if (!CloseHandle(file))
  2039. throw makeOsException(GetLastError(),"CFileAsyncIO::close");
  2040. }
  2041. file = NULLFILE;
  2042. }
  2043. offset_t CFileAsyncIO::size()
  2044. {
  2045. LARGE_INTEGER pos;
  2046. pos.LowPart = GetFileSize(file, (unsigned long *)&pos.HighPart);
  2047. if (pos.LowPart==-1) {
  2048. DWORD err = GetLastError();
  2049. if (err!=0)
  2050. throw makeOsException(GetLastError(),"CFileAsyncIO::size");
  2051. }
  2052. return pos.QuadPart;
  2053. }
  2054. size32_t CFileAsyncIO::read(offset_t pos, size32_t len, void * data)
  2055. {
  2056. Owned<IFileAsyncResult> res = readAsync(pos,len,data);
  2057. size32_t ret;
  2058. res->getResult(ret,true);
  2059. return ret;
  2060. }
  2061. size32_t CFileAsyncIO::write(offset_t pos, size32_t len, const void * data)
  2062. {
  2063. Owned<IFileAsyncResult> res = writeAsync(pos,len,data);
  2064. size32_t ret;
  2065. res->getResult(ret,true);
  2066. return ret;
  2067. }
  2068. void CFileAsyncIO::setSize(offset_t size)
  2069. {
  2070. LARGE_INTEGER tempPos;
  2071. tempPos.QuadPart = size;
  2072. tempPos.LowPart = SetFilePointer(file, tempPos.LowPart, &tempPos.HighPart, FILE_BEGIN);
  2073. if (!SetEndOfFile(file))
  2074. throw makeOsException(GetLastError(), "CFileIO::setSize");
  2075. }
  2076. IFileAsyncResult *CFileAsyncIO::readAsync(offset_t pos, size32_t len, void * data)
  2077. {
  2078. CFileAsyncResult *res = new CFileAsyncResult(pos,0);
  2079. DWORD val;
  2080. if (ReadFile(file,data,len,&val,&res->overlapped) == 0) {
  2081. int err = GetLastError();
  2082. if (err == ERROR_HANDLE_EOF) { // bit weird
  2083. res->value = 0; // won't need to wait
  2084. }
  2085. else if (err == ERROR_IO_PENDING) {
  2086. CriticalBlock block(cs);
  2087. res->parent = this;
  2088. results.append(*res);
  2089. }
  2090. else
  2091. throw makeOsException(GetLastError(),"CFileIO::readAsync");
  2092. }
  2093. else {
  2094. res->value = val; // won't need to wait
  2095. }
  2096. return res;
  2097. }
  2098. IFileAsyncResult *CFileAsyncIO::writeAsync(offset_t pos, size32_t len, const void * data)
  2099. {
  2100. CFileAsyncResult *res = new CFileAsyncResult(pos,len);
  2101. DWORD val;
  2102. if (WriteFile(file,data,len,&val,&res->overlapped) == 0) {
  2103. int err = GetLastError();
  2104. if (err != ERROR_IO_PENDING)
  2105. throw makeOsException(GetLastError(),"CFileIO::writeAsync");
  2106. CriticalBlock block(cs);
  2107. res->parent = this;
  2108. results.append(*res);
  2109. }
  2110. else {
  2111. res->value = val; // wont need to wait
  2112. }
  2113. return res;
  2114. }
  2115. #else
  2116. //-- Unix implementation ----------------------------------------------------
  2117. class CFileAsyncResult: implements IFileAsyncResult, public CInterface
  2118. {
  2119. protected:
  2120. friend class CFileAsyncIO;
  2121. DWORD value;
  2122. DWORD wrsize;
  2123. aiocb cb;
  2124. public:
  2125. IMPLEMENT_IINTERFACE;
  2126. CFileAsyncResult(offset_t offset,size32_t _wrsize)
  2127. {
  2128. value = (size32_t)-1;
  2129. wrsize = _wrsize;
  2130. }
  2131. ~CFileAsyncResult()
  2132. {
  2133. size32_t dummy;
  2134. getResult(dummy,true);
  2135. }
  2136. bool getResult(size32_t &ret,bool wait)
  2137. {
  2138. if (value==(size32_t)-1) {
  2139. for (;;) {
  2140. int aio_errno = aio_error(&cb);
  2141. if (aio_errno==ECANCELED)
  2142. return false;
  2143. if (aio_errno != EINPROGRESS)
  2144. {
  2145. if (aio_errno)
  2146. throw makeErrnoException(aio_errno, "CFileAsyncResult::getResult");
  2147. value = aio_return(&cb);
  2148. if (value<wrsize)
  2149. throw makeOsException(DISK_FULL_EXCEPTION_CODE, "CFileAsyncResult::getResult");
  2150. break;
  2151. }
  2152. if (!wait)
  2153. return false;
  2154. for (;;) {
  2155. struct timespec timeout;
  2156. timeout.tv_sec = 60*60*24; // a long time
  2157. timeout.tv_nsec = 0;
  2158. aiocb * cb_list[1];
  2159. cb_list[0] = &cb;
  2160. int rc = aio_suspend(cb_list, 1, &timeout);
  2161. if ((rc == 0)||(errno != EAGAIN))
  2162. break;
  2163. if (rc==ECANCELED)
  2164. return false;
  2165. }
  2166. }
  2167. }
  2168. ret = value;
  2169. return true;
  2170. }
  2171. };
  2172. CFileAsyncIO::CFileAsyncIO(HANDLE handle, IFSHmode _sharemode)
  2173. {
  2174. assertex(handle != NULLFILE);
  2175. throwOnError = false;
  2176. file = handle;
  2177. sharemode = _sharemode;
  2178. }
  2179. void CFileAsyncIO::close()
  2180. {
  2181. if (file != NULLFILE)
  2182. {
  2183. aio_cancel(file,NULL);
  2184. if (_lclose(file) < 0)
  2185. throw makeErrnoException(errno, "CFileAsyncIO::close");
  2186. }
  2187. file=NULLFILE;
  2188. }
  2189. offset_t CFileAsyncIO::size()
  2190. {
  2191. CriticalBlock procedure(cs);
  2192. offset_t savedPos = _llseek(file,0,SEEK_CUR);
  2193. offset_t length = _llseek(file,0,SEEK_END);
  2194. _llseek(file, savedPos, SEEK_SET);
  2195. return length;
  2196. }
  2197. size32_t CFileAsyncIO::read(offset_t pos, size32_t len, void * data)
  2198. {
  2199. CriticalBlock procedure(cs);
  2200. _llseek(file,pos,SEEK_SET);
  2201. size32_t ret = _lread(file,data,len);
  2202. if (ret==(size32_t)-1)
  2203. throw makeErrnoException(errno, "CFileAsyncIO::read");
  2204. return ret;
  2205. }
  2206. size32_t CFileAsyncIO::write(offset_t pos, size32_t len, const void * data)
  2207. {
  2208. CriticalBlock procedure(cs);
  2209. _llseek(file,pos,SEEK_SET);
  2210. size32_t ret = _lwrite(file,data,len);
  2211. if (ret==(size32_t)-1)
  2212. throw makeErrnoException(errno, "CFileAsyncIO::write");
  2213. return ret;
  2214. }
  2215. void CFileAsyncIO::setSize(offset_t pos)
  2216. {
  2217. CriticalBlock procedure(cs);
  2218. if ((file != NULLFILE)&&(0 != ftruncate(file, pos)))
  2219. throw makeErrnoException(errno, "CFileIO::setSize");
  2220. }
  2221. IFileAsyncResult *CFileAsyncIO::readAsync(offset_t pos, size32_t len, void * data)
  2222. {
  2223. CFileAsyncResult *res = new CFileAsyncResult(pos,0);
  2224. bzero( &(res->cb), sizeof (struct aiocb));
  2225. res->cb.aio_fildes = file;
  2226. res->cb.aio_offset = pos;
  2227. res->cb.aio_buf = data;
  2228. res->cb.aio_nbytes = len;
  2229. res->cb.aio_sigevent.sigev_notify = SIGEV_NONE;
  2230. int retval = aio_read(&(res->cb));
  2231. if (retval==-1)
  2232. throw makeErrnoException(errno, "CFileAsyncIO::readAsync");
  2233. return res;
  2234. }
  2235. IFileAsyncResult *CFileAsyncIO::writeAsync(offset_t pos, size32_t len, const void * data)
  2236. {
  2237. CFileAsyncResult *res = new CFileAsyncResult(pos,len);
  2238. bzero( &(res->cb), sizeof (struct aiocb));
  2239. res->cb.aio_fildes = file;
  2240. res->cb.aio_offset = pos;
  2241. res->cb.aio_buf = (void*)data;
  2242. res->cb.aio_nbytes = len;
  2243. res->cb.aio_sigevent.sigev_signo = SIGUSR1;
  2244. res->cb.aio_sigevent.sigev_notify = SIGEV_NONE;
  2245. res->cb.aio_sigevent.sigev_value.sival_ptr = (void*)res;
  2246. int retval = aio_write(&(res->cb));
  2247. if (retval==-1)
  2248. throw makeErrnoException(errno, "CFileAsyncIO::writeAsync");
  2249. return res;
  2250. }
  2251. #endif
  2252. //---------------------------------------------------------------------------
  2253. CFileIOStream::CFileIOStream(IFileIO * _io)
  2254. {
  2255. io.set(_io);
  2256. curOffset = 0;
  2257. }
  2258. void CFileIOStream::flush()
  2259. {
  2260. }
  2261. size32_t CFileIOStream::read(size32_t len, void * data)
  2262. {
  2263. size32_t numRead = io->read(curOffset, len, data);
  2264. curOffset += numRead;
  2265. return numRead;
  2266. }
  2267. void CFileIOStream::seek(offset_t pos, IFSmode origin)
  2268. {
  2269. switch (origin)
  2270. {
  2271. case IFScurrent:
  2272. curOffset += pos;
  2273. break;
  2274. case IFSend:
  2275. curOffset = io->size() + pos;
  2276. break;
  2277. case IFSbegin:
  2278. curOffset = pos;
  2279. break;
  2280. }
  2281. }
  2282. offset_t CFileIOStream::size()
  2283. {
  2284. return io->size();
  2285. }
  2286. offset_t CFileIOStream::tell()
  2287. {
  2288. return curOffset;
  2289. }
  2290. size32_t CFileIOStream::write(size32_t len, const void * data)
  2291. {
  2292. size32_t numWritten = io->write(curOffset, len, data);
  2293. curOffset += numWritten;
  2294. return numWritten;
  2295. }
  2296. //---------------------------------------------------------------------------
  2297. CNoSeekFileIOStream::CNoSeekFileIOStream(IFileIOStream * _stream) : stream(_stream)
  2298. {
  2299. }
  2300. void CNoSeekFileIOStream::flush()
  2301. {
  2302. stream->flush();
  2303. }
  2304. size32_t CNoSeekFileIOStream::read(size32_t len, void * data)
  2305. {
  2306. return stream->read(len, data);
  2307. }
  2308. void CNoSeekFileIOStream::seek(offset_t pos, IFSmode origin)
  2309. {
  2310. offset_t prevOffset = stream->tell();
  2311. offset_t nextOffset = 0;
  2312. switch (origin)
  2313. {
  2314. case IFScurrent:
  2315. nextOffset = prevOffset + pos;
  2316. break;
  2317. case IFSend:
  2318. nextOffset = stream->size() + pos;
  2319. break;
  2320. case IFSbegin:
  2321. nextOffset = pos;
  2322. break;
  2323. }
  2324. if (prevOffset != nextOffset)
  2325. throw makeStringExceptionV(0, "Seek on non-seekable CFileIOStream (from %" I64F "u to %" I64F "u)", prevOffset, nextOffset);
  2326. //No need to call stream->seek since it will have no effect
  2327. }
  2328. offset_t CNoSeekFileIOStream::size()
  2329. {
  2330. return stream->size();
  2331. }
  2332. offset_t CNoSeekFileIOStream::tell()
  2333. {
  2334. return stream->tell();
  2335. }
  2336. size32_t CNoSeekFileIOStream::write(size32_t len, const void * data)
  2337. {
  2338. return stream->write(len, data);
  2339. }
  2340. //---------------------------------------------------------------------------
  2341. class CBufferedFileIOStreamBase : public CBufferedIOStreamBase, implements IFileIOStream
  2342. {
  2343. protected:
  2344. virtual offset_t directSize() = 0;
  2345. offset_t curOffset;
  2346. public:
  2347. IMPLEMENT_IINTERFACE;
  2348. CBufferedFileIOStreamBase(unsigned bufSize) : CBufferedIOStreamBase(bufSize), curOffset(0) { }
  2349. virtual void flush() { doflush(); }
  2350. void seek(offset_t pos, IFSmode origin)
  2351. {
  2352. offset_t newOffset = 0;
  2353. switch (origin)
  2354. {
  2355. case IFScurrent:
  2356. newOffset = tell() + pos;
  2357. break;
  2358. case IFSend:
  2359. newOffset = size() + pos;
  2360. break;
  2361. case IFSbegin:
  2362. newOffset = pos;
  2363. break;
  2364. default:
  2365. throwUnexpected();
  2366. }
  2367. if (reading)
  2368. {
  2369. // slightly weird but curoffset is end of buffer when reading
  2370. if ((newOffset >= curOffset-numInBuffer) && (newOffset <= curOffset))
  2371. {
  2372. curBufferOffset = (size32_t)(newOffset - (curOffset-numInBuffer));
  2373. return;
  2374. }
  2375. }
  2376. else
  2377. {
  2378. if ((newOffset >= curOffset) && (newOffset <= curOffset + numInBuffer))
  2379. {
  2380. curBufferOffset = (size32_t)(newOffset - curOffset);
  2381. return;
  2382. }
  2383. flush();
  2384. }
  2385. curOffset = newOffset;
  2386. numInBuffer = 0;
  2387. curBufferOffset = 0;
  2388. }
  2389. offset_t size()
  2390. {
  2391. offset_t curSize = directSize();
  2392. if (!reading)
  2393. curSize = std::max(curSize, curOffset + numInBuffer);
  2394. return curSize;
  2395. }
  2396. offset_t tell()
  2397. {
  2398. if (reading)
  2399. return curOffset - numInBuffer + curBufferOffset;
  2400. return curOffset + curBufferOffset;
  2401. }
  2402. size32_t read(size32_t len, void * data)
  2403. {
  2404. return CBufferedIOStreamBase::doread(len, data);
  2405. }
  2406. size32_t write(size32_t len, const void * data)
  2407. {
  2408. if (reading)
  2409. curOffset -= bytesRemaining();
  2410. return CBufferedIOStreamBase::dowrite(len, data);
  2411. }
  2412. };
  2413. class CBufferedFileIOStream : public CBufferedFileIOStreamBase
  2414. {
  2415. public:
  2416. CBufferedFileIOStream(IFileIO * _io, unsigned _bufferSize) : CBufferedFileIOStreamBase(_bufferSize), io(_io)
  2417. {
  2418. buffer = new byte[_bufferSize];
  2419. }
  2420. ~CBufferedFileIOStream()
  2421. {
  2422. flush();
  2423. delete [] buffer;
  2424. }
  2425. protected:
  2426. virtual void doflush()
  2427. {
  2428. if (!reading && numInBuffer)
  2429. {
  2430. try {
  2431. io->write(curOffset, numInBuffer, buffer);
  2432. }
  2433. catch (IException *) {
  2434. // if we get exception, clear buffer so doen't reoccur on destructor as well
  2435. numInBuffer = 0;
  2436. curBufferOffset = 0;
  2437. throw;
  2438. }
  2439. curOffset += curBufferOffset;
  2440. numInBuffer = 0;
  2441. curBufferOffset = 0;
  2442. }
  2443. }
  2444. virtual bool fillBuffer()
  2445. {
  2446. reading = true;
  2447. numInBuffer = io->read(curOffset, bufferSize, buffer);
  2448. curOffset += numInBuffer;
  2449. curBufferOffset = 0;
  2450. return numInBuffer!=0;
  2451. }
  2452. virtual size32_t directRead(size32_t len, void * data)
  2453. {
  2454. size32_t sz = io->read(curOffset,len,data);
  2455. curOffset += sz;
  2456. return sz;
  2457. }
  2458. virtual size32_t directWrite(size32_t len, const void * data)
  2459. {
  2460. size32_t sz = io->write(curOffset,len,data);
  2461. curOffset += sz;
  2462. return sz;
  2463. }
  2464. virtual offset_t directSize() { return io->size(); }
  2465. protected:
  2466. IFileIOAttr io;
  2467. };
  2468. //---------------------------------------------------------------------------
  2469. class CBufferedAsyncIOStream: public CBufferedFileIOStreamBase
  2470. {
  2471. Linked<IFileAsyncIO> io;
  2472. byte * blk1;
  2473. byte * blk2;
  2474. IFileAsyncResult *readasyncres;
  2475. IFileAsyncResult *writeasyncres;
  2476. bool readeof;
  2477. public:
  2478. CBufferedAsyncIOStream(IFileAsyncIO * _io, size32_t _bufferSize)
  2479. : CBufferedFileIOStreamBase(_bufferSize/2), io(_io)
  2480. {
  2481. blk1 = new byte[bufferSize];
  2482. blk2 = new byte[bufferSize];
  2483. buffer = blk1;
  2484. readasyncres = NULL;
  2485. writeasyncres = NULL;
  2486. readeof = false;
  2487. minDirectSize = (size32_t)-1; // async always writes using buffer
  2488. }
  2489. ~CBufferedAsyncIOStream()
  2490. {
  2491. flush();
  2492. waitAsyncWrite();
  2493. waitAsyncRead();
  2494. delete [] blk1;
  2495. delete [] blk2;
  2496. }
  2497. void waitAsyncWrite()
  2498. {
  2499. if (writeasyncres) {
  2500. size32_t res;
  2501. writeasyncres->getResult(res,true);
  2502. writeasyncres->Release();
  2503. writeasyncres = NULL;
  2504. }
  2505. }
  2506. size32_t waitAsyncRead()
  2507. {
  2508. size32_t res = 0;
  2509. if (readasyncres) {
  2510. readasyncres->getResult(res,true);
  2511. readasyncres->Release();
  2512. readasyncres = NULL;
  2513. }
  2514. return res;
  2515. }
  2516. void primeAsyncRead(offset_t pos,size32_t size, void *dst)
  2517. {
  2518. assertex(!readasyncres);
  2519. readasyncres = io->readAsync(pos, size, dst);
  2520. }
  2521. void primeAsyncWrite(offset_t pos,size32_t size, const void *src)
  2522. {
  2523. assertex(!writeasyncres);
  2524. writeasyncres = io->writeAsync(pos, size, src);
  2525. }
  2526. // CBufferedFileIOStream overloads
  2527. virtual bool fillBuffer()
  2528. {
  2529. if (!reading) {
  2530. waitAsyncWrite();
  2531. reading = true;
  2532. }
  2533. if (readeof) {
  2534. numInBuffer = 0;
  2535. curBufferOffset = 0;
  2536. return false;
  2537. }
  2538. buffer=(buffer==blk1)?blk2:blk1;
  2539. if (readasyncres==NULL) // first time
  2540. primeAsyncRead(curOffset, bufferSize, buffer);
  2541. numInBuffer = waitAsyncRead();
  2542. curOffset += numInBuffer;
  2543. curBufferOffset = 0;
  2544. if (numInBuffer)
  2545. primeAsyncRead(curOffset, bufferSize, (buffer==blk1)?blk2:blk1);
  2546. else
  2547. readeof = true;
  2548. return !readeof;
  2549. }
  2550. virtual void doflush()
  2551. {
  2552. if (!reading && numInBuffer)
  2553. {
  2554. waitAsyncWrite();
  2555. primeAsyncWrite(curOffset, numInBuffer, buffer);
  2556. buffer=(buffer==blk1)?blk2:blk1;
  2557. curOffset += curBufferOffset;
  2558. numInBuffer = 0;
  2559. curBufferOffset = 0;
  2560. }
  2561. }
  2562. virtual size32_t directRead(size32_t len, void * data) { assertex(false); return 0; } // shouldn't get called
  2563. virtual size32_t directWrite(size32_t len, const void * data) { assertex(false); return 0; } // shouldn't get called
  2564. virtual offset_t directSize() { waitAsyncWrite(); return io->size(); }
  2565. };
  2566. //-- Helper routines --------------------------------------------------------
  2567. enum GblFlushEnum { FLUSH_INIT, FLUSH_DISALLOWED, FLUSH_ALLOWED };
  2568. static GblFlushEnum gbl_flush_allowed = FLUSH_INIT;
  2569. static CriticalSection flushsect;
  2570. static inline bool isPCFlushAllowed()
  2571. {
  2572. CriticalBlock block(flushsect);
  2573. if (gbl_flush_allowed == FLUSH_INIT)
  2574. {
  2575. if (queryEnvironmentConf().getPropBool("allow_pgcache_flush", true))
  2576. gbl_flush_allowed = FLUSH_ALLOWED;
  2577. else
  2578. gbl_flush_allowed = FLUSH_DISALLOWED;
  2579. }
  2580. if (gbl_flush_allowed == FLUSH_ALLOWED)
  2581. return true;
  2582. return false;
  2583. }
  2584. static inline size32_t doread(IFileIOStream * stream,void *dst, size32_t size)
  2585. {
  2586. size32_t toread=size;
  2587. while (toread)
  2588. {
  2589. int read = stream->read(toread, dst);
  2590. if (!read)
  2591. return size-toread;
  2592. toread -= read;
  2593. dst = (char *) dst + read;
  2594. }
  2595. return size;
  2596. }
  2597. CIOStreamReadWriteSeq::CIOStreamReadWriteSeq(IFileIOStream * _stream, offset_t _offset, size32_t _size)
  2598. {
  2599. stream.set(_stream);
  2600. // stream->setThrowOnError(true);
  2601. size = _size;
  2602. offset = _offset; // assumption that stream at correct location already
  2603. }
  2604. void CIOStreamReadWriteSeq::put(const void *src)
  2605. {
  2606. stream->write(size, src);
  2607. }
  2608. void CIOStreamReadWriteSeq::putn(const void *src, unsigned n)
  2609. {
  2610. stream->write(size*n, src);
  2611. }
  2612. void CIOStreamReadWriteSeq::flush()
  2613. {
  2614. stream->flush();
  2615. }
  2616. offset_t CIOStreamReadWriteSeq::getPosition()
  2617. {
  2618. return stream->tell();
  2619. }
  2620. bool CIOStreamReadWriteSeq::get(void *dst)
  2621. {
  2622. return doread(stream,dst,size)==size;
  2623. }
  2624. unsigned CIOStreamReadWriteSeq::getn(void *dst, unsigned n)
  2625. {
  2626. return doread(stream,dst,size*n)/size;
  2627. }
  2628. void CIOStreamReadWriteSeq::reset()
  2629. {
  2630. stream->seek(offset, IFSbegin);
  2631. }
  2632. //-- Helper routines --------------------------------------------------------
  2633. size32_t read(IFileIO * in, offset_t pos, size32_t len, MemoryBuffer & buffer)
  2634. {
  2635. const size32_t checkLengthLimit = 0x1000;
  2636. if (len >= checkLengthLimit)
  2637. {
  2638. //Don't allocate a stupid amount of memory....
  2639. offset_t fileLength = in->size();
  2640. if (pos > fileLength)
  2641. pos = fileLength;
  2642. if ((len == (size32_t)-1) || (pos + len > fileLength))
  2643. len = (size32_t)(fileLength - pos);
  2644. }
  2645. void * data = buffer.reserve(len);
  2646. size32_t lenRead = in->read(pos, len, data);
  2647. if (lenRead != len)
  2648. buffer.rewrite(buffer.length() - (len - lenRead));
  2649. return lenRead;
  2650. }
  2651. void renameFile(const char *target, const char *source, bool overwritetarget)
  2652. {
  2653. OwnedIFile src = createIFile(source);
  2654. if (!src)
  2655. throw MakeStringException(-1, "renameFile: source '%s' not found", source);
  2656. if (src->isFile()!=fileBool::foundYes)
  2657. throw MakeStringException(-1, "renameFile: source '%s' is not a valid file", source);
  2658. if (src->isReadOnly()!=fileBool::foundNo)
  2659. throw MakeStringException(-1, "renameFile: source '%s' is readonly", source);
  2660. OwnedIFile tgt = createIFile(target);
  2661. if (!tgt)
  2662. throw MakeStringException(-1, "renameFile: target path '%s' could not be created", target);
  2663. if (tgt->exists() && !overwritetarget)
  2664. throw MakeStringException(-1, "renameFile: target file already exists: '%s' will not overwrite", target);
  2665. src->rename(target);
  2666. }
  2667. void copyFile(const char *target, const char *source, size32_t buffersize, ICopyFileProgress *progress, CFflags copyFlags)
  2668. {
  2669. OwnedIFile src = createIFile(source);
  2670. if (!src)
  2671. throw MakeStringException(-1, "copyFile: source '%s' not found", source);
  2672. OwnedIFile tgt = createIFile(target);
  2673. if (!tgt)
  2674. throw MakeStringException(-1, "copyFile: target path '%s' could not be created", target);
  2675. copyFile(tgt, src, buffersize, progress, copyFlags);
  2676. }
  2677. void copyFile(IFile * target, IFile * source, size32_t buffersize, ICopyFileProgress *progress, CFflags copyFlags)
  2678. {
  2679. source->copyTo(target, buffersize, progress, false, copyFlags);
  2680. }
  2681. void doCopyFile(IFile * target, IFile * source, size32_t buffersize, ICopyFileProgress *progress, ICopyFileIntercept *copyintercept, bool usetmp, CFflags copyFlags)
  2682. {
  2683. if (!buffersize)
  2684. buffersize = DEFAULT_COPY_BLKSIZE;
  2685. #ifdef _WIN32
  2686. if (!usetmp) {
  2687. CFile *src = QUERYINTERFACE(source,CFile);
  2688. CFile *dst = QUERYINTERFACE(target,CFile);
  2689. if (src) {
  2690. if (dst) {
  2691. if (src->fastCopyFile(*dst, buffersize, progress))
  2692. return;
  2693. }
  2694. CWindowsRemoteFile *dst2 = QUERYINTERFACE(target,CWindowsRemoteFile);
  2695. if (dst2) {
  2696. if (dst2->fastCopyFileRev(*src, buffersize, progress))
  2697. return;
  2698. }
  2699. }
  2700. CWindowsRemoteFile *src2 = QUERYINTERFACE(source,CWindowsRemoteFile);
  2701. if (src2) {
  2702. if (dst) {
  2703. if (src2->fastCopyFile(*dst,buffersize, progress))
  2704. return;
  2705. }
  2706. CWindowsRemoteFile *dst2 = QUERYINTERFACE(target,CWindowsRemoteFile);
  2707. if (dst2) {
  2708. if (src2->fastCopyFile(*dst2, buffersize, progress))
  2709. return;
  2710. }
  2711. }
  2712. }
  2713. #endif
  2714. IFEflags srcFlags = IFEnone;
  2715. if (copyFlags & CFflush_read)
  2716. srcFlags = IFEnocache;
  2717. OwnedIFileIO sourceIO = source->open(IFOread, srcFlags);
  2718. if (!sourceIO)
  2719. throw MakeStringException(-1, "copyFile: source '%s' not found", source->queryFilename());
  2720. #ifdef __linux__
  2721. // this is not really needed in windows - if it is we will have to
  2722. // test the file extenstion - .exe, .bat
  2723. struct stat info;
  2724. if (stat(source->queryFilename(), &info) == 0) // cannot fail - exception would have been thrown above
  2725. target->setCreateFlags(info.st_mode&(S_IRUSR|S_IRGRP|S_IROTH|S_IWUSR|S_IWGRP|S_IWOTH|S_IXUSR|S_IXGRP|S_IXOTH));
  2726. #endif
  2727. Owned<IFileIO> targetIO;
  2728. Owned<IFile> tmpfile;
  2729. IFile *dest;
  2730. if (usetmp) {
  2731. StringBuffer tmpname;
  2732. makeTempCopyName(tmpname,target->queryFilename());
  2733. tmpfile.setown(createIFile(tmpname.str()));
  2734. dest = tmpfile;
  2735. }
  2736. else
  2737. dest = target;
  2738. IFEflags tgtFlags = IFEnone;
  2739. if (copyFlags & CFflush_write)
  2740. tgtFlags = IFEnocache;
  2741. targetIO.setown(dest->open(IFOcreate, tgtFlags));
  2742. if (!targetIO)
  2743. throw MakeStringException(-1, "copyFile: target path '%s' could not be created", dest->queryFilename());
  2744. MemoryAttr mb;
  2745. void * buffer = copyintercept?NULL:mb.allocate(buffersize);
  2746. offset_t offset = 0;
  2747. offset_t total = 0;
  2748. Owned<IException> exc;
  2749. try
  2750. {
  2751. if (progress)
  2752. total = sourceIO->size(); // only needed for progress
  2753. for (;;)
  2754. {
  2755. size32_t got;
  2756. if (copyintercept) {
  2757. got = (size32_t)copyintercept->copy(sourceIO,targetIO,offset,buffersize);
  2758. if (got == 0)
  2759. break;
  2760. }
  2761. else {
  2762. got = sourceIO->read(offset, buffersize, buffer);
  2763. if (got == 0)
  2764. break;
  2765. targetIO->write(offset, got, buffer);
  2766. }
  2767. offset += got;
  2768. if (progress && progress->onProgress(offset, total) != CFPcontinue)
  2769. break;
  2770. }
  2771. targetIO.clear();
  2772. if (usetmp) {
  2773. StringAttr tail(pathTail(target->queryFilename()));
  2774. target->remove();
  2775. dest->rename(tail);
  2776. }
  2777. }
  2778. catch (IException *e)
  2779. {
  2780. // try to delete partial copy
  2781. StringBuffer s;
  2782. s.append("copyFile target=").append(dest->queryFilename()).append(" source=").append(source->queryFilename()).appendf("; read/write failure (%d): ",e->errorCode());
  2783. exc.setown(MakeStringException(e->errorCode(), "%s", s.str()));
  2784. e->Release();
  2785. EXCLOG(exc, "doCopyFile");
  2786. }
  2787. if (exc.get()) {
  2788. try {
  2789. sourceIO.clear();
  2790. }
  2791. catch (IException *e) {
  2792. EXCLOG(e, "doCopyFile closing source");
  2793. e->Release();
  2794. }
  2795. try {
  2796. targetIO.clear();
  2797. }
  2798. catch (IException *e) {
  2799. EXCLOG(e, "doCopyFile closing dest");
  2800. e->Release();
  2801. }
  2802. try {
  2803. dest->remove();
  2804. }
  2805. catch (IException *e) {
  2806. StringBuffer s;
  2807. EXCLOG(e, s.clear().append("Removing partial copy file: ").append(dest->queryFilename()).str());
  2808. e->Release();
  2809. }
  2810. throw exc.getClear();
  2811. }
  2812. CDateTime createTime, modifiedTime;
  2813. if (source->getTime(&createTime, &modifiedTime, NULL))
  2814. target->setTime(&createTime, &modifiedTime, NULL);
  2815. }
  2816. void makeTempCopyName(StringBuffer &tmpname,const char *destname)
  2817. {
  2818. // simple for the moment (maybe used uid later)
  2819. tmpname.append(destname).append("__");
  2820. #ifdef _WIN32
  2821. genUUID(tmpname,true);
  2822. #else
  2823. genUUID(tmpname);
  2824. #endif
  2825. tmpname.append(".tmp");
  2826. }
  2827. //---------------------------------------------------------------------------
  2828. #ifndef _WIN32
  2829. /// This code is dangerous - pass it arrays smaller than _MAX_xxx and it will write off the end even if you KNOW your strings would fit
  2830. // Should NOT use strncpy here
  2831. void _splitpath(const char *path, char *drive, char *dir, char *fname, char *ext)
  2832. {
  2833. strncpy(dir, path, (_MAX_DIR-1));
  2834. char* last = strrchr(dir, '.');
  2835. if (last != NULL)
  2836. {
  2837. if (strrchr(last, PATHSEPCHAR)==NULL)
  2838. {
  2839. strncpy(ext, last, (_MAX_EXT-1));
  2840. *last = '\0';
  2841. }
  2842. else
  2843. {
  2844. *ext = '\0';
  2845. }
  2846. }
  2847. else
  2848. {
  2849. *ext = '\0';
  2850. }
  2851. last = strrchr(dir, PATHSEPCHAR);
  2852. if (last != NULL)
  2853. {
  2854. strncpy(fname, ++last, (_MAX_FNAME-1));
  2855. *last = '\0';
  2856. }
  2857. else
  2858. {
  2859. strncpy(fname, dir, (_MAX_FNAME-1));
  2860. *dir = '\0';
  2861. }
  2862. *drive = '\0';
  2863. }
  2864. #endif
  2865. void splitFilename(const char * filename, StringBuffer * drive, StringBuffer * path, StringBuffer * tail, StringBuffer * ext, bool longExt)
  2866. {
  2867. char tdrive[_MAX_DRIVE];
  2868. char tdir[_MAX_DIR];
  2869. char ttail[_MAX_FNAME];
  2870. char text[_MAX_EXT];
  2871. ::_splitpath(filename, tdrive, tdir, ttail, text);
  2872. char *longExtStart = longExt ? strchr(ttail, '.') : NULL;
  2873. if (drive)
  2874. drive->append(tdrive);
  2875. if (path)
  2876. path->append(tdir);
  2877. if (tail)
  2878. tail->append(longExtStart ? longExtStart-ttail : strlen(ttail), ttail);
  2879. if (ext)
  2880. {
  2881. if (longExtStart)
  2882. ext->append(longExtStart);
  2883. ext->append(text);
  2884. }
  2885. }
  2886. StringBuffer &createUNCFilename(const char * filename, StringBuffer &UNC, bool useHostNames)
  2887. {
  2888. char buf[255];
  2889. #ifdef _WIN32
  2890. char *dummy;
  2891. GetFullPathName(filename, sizeof(buf), buf, &dummy);
  2892. if (buf[1]==':')
  2893. {
  2894. // MORE - assumes it's a local drive not a mapped one
  2895. UNC.append("\\\\");
  2896. if (useHostNames)
  2897. UNC.append(GetCachedHostName());
  2898. else
  2899. queryHostIP().getIpText(UNC);
  2900. UNC.append("\\").append((char)tolower(buf[0])).append(getShareChar()).append(buf+2);
  2901. }
  2902. else
  2903. {
  2904. assertex(buf[0]=='\\' && buf[1]=='\\');
  2905. UNC.append(buf);
  2906. }
  2907. return UNC;
  2908. #else
  2909. if (filename[0]=='/' && filename[1]=='/')
  2910. UNC.append(filename);
  2911. else
  2912. {
  2913. UNC.append("//");
  2914. if (useHostNames)
  2915. UNC.append(GetCachedHostName());
  2916. else
  2917. queryHostIP().getIpText(UNC);
  2918. if (*filename != '/')
  2919. {
  2920. if (!GetCurrentDirectory(sizeof(buf), buf)) {
  2921. IERRLOG("createUNCFilename: Current directory path too big, bailing out");
  2922. throwUnexpected();
  2923. }
  2924. UNC.append(buf).append("/");
  2925. }
  2926. UNC.append(filename);
  2927. }
  2928. return UNC;
  2929. #endif
  2930. }
  2931. bool splitUNCFilename(const char * filename, StringBuffer * machine, StringBuffer * path, StringBuffer * tail, StringBuffer * ext)
  2932. {
  2933. if (!filename || !isPathSepChar(filename[0]) || !isPathSepChar(filename[1]))
  2934. return false;
  2935. const char * cur = filename+2;
  2936. while (*cur && !isPathSepChar(*cur))
  2937. cur++;
  2938. if (!*cur)
  2939. return false;
  2940. const char * startPath = cur;
  2941. const char * lastExt = NULL;
  2942. const char * startTail = NULL;
  2943. char next;
  2944. while ((next = *cur) != 0)
  2945. {
  2946. if (isPathSepChar(next))
  2947. {
  2948. lastExt = NULL;
  2949. startTail = cur+1;
  2950. }
  2951. else if (next == '.')
  2952. lastExt = cur;
  2953. cur++;
  2954. }
  2955. assertex(startTail);
  2956. if (machine)
  2957. machine->append(startPath-filename, filename);
  2958. if (path)
  2959. path->append(startTail - startPath, startPath);
  2960. if (lastExt)
  2961. {
  2962. if (tail)
  2963. tail->append(lastExt - startTail, startTail);
  2964. if (ext)
  2965. ext->append(lastExt);
  2966. }
  2967. else
  2968. {
  2969. if (tail)
  2970. tail->append(startTail);
  2971. }
  2972. return true;
  2973. }
  2974. /**
  2975. * Ensure the filename has desired extension.
  2976. * If it has no extension, add the desired extension, return true.
  2977. * If it has an extension different from the desiredExtension, return false.
  2978. * Otherwise, return true.
  2979. */
  2980. bool ensureFileExtension(StringBuffer& filename, const char* desiredExtension)
  2981. {
  2982. char drive[_MAX_DRIVE];
  2983. char dir[_MAX_DIR];
  2984. char fname[_MAX_FNAME];
  2985. char ext[_MAX_EXT];
  2986. _splitpath(filename.str(), drive, dir, fname, ext);
  2987. if (ext[0]==0)
  2988. {
  2989. filename.append(desiredExtension);
  2990. return true;
  2991. }
  2992. if (strcmp(ext,desiredExtension)!=0)
  2993. return false;
  2994. return true;
  2995. }
  2996. /* Get full file name. If noExtension is true, the extension (if any) will be trimmed */
  2997. StringBuffer& getFullFileName(StringBuffer& filename, bool noExtension)
  2998. {
  2999. char drive[_MAX_DRIVE];
  3000. char dir[_MAX_DIR];
  3001. char fname[_MAX_FNAME];
  3002. char ext[_MAX_EXT];
  3003. _splitpath(filename.str(), drive, dir, fname, ext);
  3004. filename.clear();
  3005. filename.append(drive).append(dir).append(fname);
  3006. if (!noExtension)
  3007. filename.append(ext);
  3008. return filename;
  3009. }
  3010. /* Get the file name only. If noExtension is true, the extension (if any) will be trimmed */
  3011. StringBuffer& getFileNameOnly(StringBuffer& filename, bool noExtension)
  3012. {
  3013. char drive[_MAX_DRIVE];
  3014. char dir[_MAX_DIR];
  3015. char fname[_MAX_FNAME];
  3016. char ext[_MAX_EXT];
  3017. _splitpath(filename.str(), drive, dir, fname, ext);
  3018. filename.clear();
  3019. filename.append(fname);
  3020. if (!noExtension)
  3021. filename.append(ext);
  3022. return filename;
  3023. }
  3024. //---------------------------------------------------------------------------
  3025. class CNullDirectoryIterator : implements IDirectoryIterator, public CInterface
  3026. {
  3027. public:
  3028. IMPLEMENT_IINTERFACE;
  3029. bool first()
  3030. {
  3031. return false;
  3032. }
  3033. bool next()
  3034. {
  3035. return false;
  3036. }
  3037. StringBuffer &getName(StringBuffer &buf)
  3038. {
  3039. return buf;
  3040. }
  3041. __int64 getFileSize()
  3042. {
  3043. return -1;
  3044. }
  3045. bool getModifiedTime(CDateTime &ret)
  3046. {
  3047. return false;
  3048. }
  3049. virtual bool isValid() { return false; }
  3050. virtual IFile & query() { throwUnexpected(); }
  3051. virtual bool isDir() { return false; }
  3052. };
  3053. extern jlib_decl IDirectoryIterator *createNullDirectoryIterator()
  3054. {
  3055. return new CNullDirectoryIterator;
  3056. }
  3057. class CDirectoryIterator : implements IDirectoryIterator, public CInterface
  3058. {
  3059. public:
  3060. CDirectoryIterator(const char * _path, const char * _mask, bool _sub, bool _includedir)
  3061. {
  3062. StringBuffer tmp;
  3063. if (!_path || !*_path)
  3064. _path = "." PATHSEPSTR;
  3065. else if (_path[strlen(_path)-1] != PATHSEPCHAR)
  3066. _path = tmp.append(_path).append(PATHSEPCHAR);
  3067. path.set(_path);
  3068. mask.set(_mask);
  3069. sub = _sub;
  3070. includedir = _includedir;
  3071. subidx = 0;
  3072. curisdir = false;
  3073. }
  3074. IMPLEMENT_IINTERFACE
  3075. virtual bool first()=0;
  3076. virtual bool next()=0;
  3077. virtual bool isValid() { return cur != NULL; }
  3078. virtual IFile & query() { return *cur; }
  3079. virtual StringBuffer &getName(StringBuffer &buf)=0;
  3080. virtual bool isDir() { return curisdir; }
  3081. protected:
  3082. Owned<IFile> cur;
  3083. bool curisdir;
  3084. StringAttr path;
  3085. StringAttr mask;
  3086. bool includedir;
  3087. bool sub; // TBD
  3088. StringAttrArray subpaths;
  3089. unsigned subidx; // -1 to index subpaths
  3090. };
  3091. #ifdef _WIN32
  3092. class CWindowsDirectoryIterator : public CDirectoryIterator
  3093. {
  3094. WIN32_FIND_DATA info;
  3095. HANDLE handle;
  3096. bool setCurrent()
  3097. {
  3098. if (strcmp(info.cFileName, ".") == 0 || strcmp(info.cFileName, "..") == 0)
  3099. return false;
  3100. bool match = (!mask.length() || WildMatch(info.cFileName, mask, true));
  3101. curisdir = (info.dwFileAttributes&FILE_ATTRIBUTE_DIRECTORY)!=0;
  3102. if (!match&&!curisdir)
  3103. return false;
  3104. StringBuffer f(path);
  3105. if (subidx)
  3106. f.append(subpaths.item(subidx-1).text).append('\\');
  3107. f.append(info.cFileName);
  3108. if (curisdir) {
  3109. if (sub) {
  3110. const char *s = f.str()+path.length();
  3111. unsigned i;
  3112. for (i=0;i<subpaths.ordinality();i++)
  3113. if (stricmp(subpaths.item(i).text,s)==0)
  3114. break;
  3115. if (i==subpaths.ordinality())
  3116. subpaths.append(*new StringAttrItem(s));
  3117. }
  3118. if (!includedir)
  3119. return false;
  3120. }
  3121. if (!match)
  3122. return false;
  3123. cur.setown(createIFile(f.str()));
  3124. return true;
  3125. }
  3126. bool open()
  3127. {
  3128. close();
  3129. while (subidx<=subpaths.ordinality()) {
  3130. StringBuffer location(path);
  3131. if (subidx)
  3132. location.append(subpaths.item(subidx-1).text).append('\\');
  3133. location.append("*");
  3134. handle = FindFirstFile(location.str(), &info);
  3135. if (handle != INVALID_HANDLE_VALUE)
  3136. return true;
  3137. subidx++;
  3138. }
  3139. return false;
  3140. }
  3141. void close()
  3142. {
  3143. cur.clear();
  3144. if (handle != INVALID_HANDLE_VALUE) {
  3145. FindClose(handle);
  3146. handle = INVALID_HANDLE_VALUE;
  3147. }
  3148. };
  3149. public:
  3150. CWindowsDirectoryIterator(const char * _path, const char * _mask, bool _sub, bool _includedir)
  3151. : CDirectoryIterator(_path,_mask,_sub,_includedir)
  3152. {
  3153. handle = INVALID_HANDLE_VALUE;
  3154. }
  3155. ~CWindowsDirectoryIterator()
  3156. {
  3157. close();
  3158. }
  3159. bool first()
  3160. {
  3161. subpaths.kill();
  3162. subidx = 0;
  3163. if (!open())
  3164. return false;
  3165. if (setCurrent())
  3166. return true;
  3167. return next();
  3168. }
  3169. bool next()
  3170. {
  3171. for (;;) {
  3172. for (;;) {
  3173. if (!FindNextFile(handle, &info))
  3174. break;
  3175. if (setCurrent())
  3176. return true;
  3177. }
  3178. subidx++;
  3179. if (!open())
  3180. break;
  3181. if (setCurrent())
  3182. return true;
  3183. }
  3184. return false;
  3185. }
  3186. StringBuffer &getName(StringBuffer &buf)
  3187. {
  3188. if (subidx)
  3189. buf.append(subpaths.item(subidx-1).text).append('\\');
  3190. return buf.append(info.cFileName);
  3191. }
  3192. __int64 getFileSize()
  3193. {
  3194. if (curisdir)
  3195. return -1;
  3196. LARGE_INTEGER x;
  3197. x.LowPart = info.nFileSizeLow;
  3198. x.HighPart = info.nFileSizeHigh;
  3199. return x.QuadPart;
  3200. }
  3201. bool getModifiedTime(CDateTime &ret)
  3202. {
  3203. FILETIMEtoIDateTime(&ret, info.ftLastWriteTime);
  3204. return true;
  3205. }
  3206. };
  3207. IDirectoryIterator * createDirectoryIterator(const char * path, const char * mask, bool sub, bool includedirs)
  3208. {
  3209. if (mask&&!*mask) // only NULL is wild
  3210. return new CNullDirectoryIterator;
  3211. if (!path || !*path) // cur directory so no point in checking for remote etc.
  3212. return new CWindowsDirectoryIterator(path, mask,sub,includedirs);
  3213. OwnedIFile iFile = createIFile(path);
  3214. if (!iFile||(iFile->isDirectory()!=fileBool::foundYes))
  3215. return new CNullDirectoryIterator;
  3216. return iFile->directoryFiles(mask, sub, includedirs);
  3217. }
  3218. IDirectoryIterator *CFile::directoryFiles(const char *mask,bool sub,bool includedirs)
  3219. {
  3220. if ((mask&&!*mask)|| // only NULL is wild
  3221. (isDirectory()!=fileBool::foundYes))
  3222. return new CNullDirectoryIterator;
  3223. return new CWindowsDirectoryIterator(filename, mask,sub,includedirs);
  3224. }
  3225. bool CFile::getInfo(bool &isdir,offset_t &size,CDateTime &modtime)
  3226. {
  3227. WIN32_FILE_ATTRIBUTE_DATA info;
  3228. if (GetFileAttributesEx(filename, GetFileExInfoStandard, &info) != 0) {
  3229. LARGE_INTEGER x;
  3230. x.LowPart = info.nFileSizeLow;
  3231. x.HighPart = info.nFileSizeHigh;
  3232. size = (offset_t)x.QuadPart;
  3233. isdir = (info.dwFileAttributes != (DWORD)-1)&&(info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY);
  3234. FILETIMEtoIDateTime(&modtime, info.ftLastWriteTime);
  3235. return true;
  3236. }
  3237. size = 0;
  3238. modtime.clear();
  3239. isdir = false;
  3240. return false;
  3241. }
  3242. #else
  3243. class CLinuxDirectoryIterator : public CDirectoryIterator
  3244. {
  3245. StringAttr tail;
  3246. DIR * handle;
  3247. struct stat st;
  3248. bool gotst;
  3249. CriticalSection sect;
  3250. bool loadst()
  3251. {
  3252. if (!gotst&&cur)
  3253. gotst = (stat(cur->queryFilename(), &st) == 0);
  3254. return gotst;
  3255. }
  3256. public:
  3257. CLinuxDirectoryIterator(const char * _path, const char * _mask, bool _sub,bool _includedir)
  3258. : CDirectoryIterator(_path,_mask,_sub,_includedir)
  3259. {
  3260. handle = NULL;
  3261. gotst = false;
  3262. }
  3263. ~CLinuxDirectoryIterator()
  3264. {
  3265. close();
  3266. }
  3267. bool open()
  3268. {
  3269. close();
  3270. while (subidx<=subpaths.ordinality()) {
  3271. StringBuffer location(path);
  3272. if (subidx)
  3273. location.append(subpaths.item(subidx-1).text);
  3274. // not sure if should remove trailing '/'
  3275. handle = ::opendir(location.str());
  3276. // better error handling here?
  3277. if (handle)
  3278. return true;
  3279. subidx++;
  3280. }
  3281. return false;
  3282. }
  3283. void close()
  3284. {
  3285. cur.clear();
  3286. if (handle) {
  3287. closedir(handle);
  3288. handle = NULL;
  3289. }
  3290. }
  3291. bool first()
  3292. {
  3293. subpaths.kill();
  3294. subidx = 0;
  3295. if (open())
  3296. return next();
  3297. return false;
  3298. }
  3299. bool next()
  3300. {
  3301. for (;;) {
  3302. struct dirent *entry;
  3303. for (;;) {
  3304. gotst = false;
  3305. CriticalBlock b(sect);
  3306. entry = readdir(handle);
  3307. // need better checking here?
  3308. if (!entry)
  3309. break;
  3310. if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0)
  3311. continue;
  3312. bool match = (!mask.length() || WildMatch(entry->d_name, mask, false));
  3313. curisdir = (entry->d_type==DT_DIR);
  3314. bool islnk = (entry->d_type==DT_LNK);
  3315. bool isunknown = (entry->d_type==DT_UNKNOWN); // to work around xfs bug
  3316. if (match||curisdir||islnk||isunknown) {
  3317. StringBuffer f(path);
  3318. if (subidx)
  3319. f.append(subpaths.item(subidx-1).text).append('/');
  3320. f.append(entry->d_name);
  3321. if (islnk||isunknown) {
  3322. struct stat info;
  3323. if (stat(f.str(), &info) == 0) // will follow link
  3324. curisdir = S_ISDIR(info.st_mode);
  3325. else
  3326. curisdir = false;
  3327. }
  3328. if (curisdir) {
  3329. if (sub) {
  3330. const char *s = f.str()+path.length();
  3331. unsigned i;
  3332. for (i=0;i<subpaths.ordinality();i++)
  3333. if (strcmp(subpaths.item(i).text,s)==0)
  3334. break;
  3335. if (i==subpaths.ordinality())
  3336. subpaths.append(*new StringAttrItem(s));
  3337. }
  3338. if (!includedir)
  3339. match = false;
  3340. }
  3341. if (match) {
  3342. tail.set(entry->d_name);
  3343. cur.setown(createIFile(f.str()));
  3344. return true;
  3345. }
  3346. }
  3347. }
  3348. subidx++;
  3349. if (!open())
  3350. break;
  3351. }
  3352. return false;
  3353. }
  3354. StringBuffer &getName(StringBuffer &buf)
  3355. {
  3356. if (subidx)
  3357. buf.append(subpaths.item(subidx-1).text).append('/');
  3358. return buf.append(tail);
  3359. }
  3360. __int64 getFileSize()
  3361. {
  3362. if (curisdir)
  3363. return -1;
  3364. if (!loadst())
  3365. return -1;
  3366. return st.st_size ;
  3367. }
  3368. bool getModifiedTime(CDateTime &ret)
  3369. {
  3370. if (!loadst())
  3371. return false;
  3372. timetToIDateTime(&ret,st.st_mtime);
  3373. return true;
  3374. }
  3375. };
  3376. IDirectoryIterator * createDirectoryIterator(const char * path, const char * mask, bool sub, bool includedirs)
  3377. {
  3378. if (mask&&!*mask) // only NULL is wild
  3379. return new CNullDirectoryIterator;
  3380. if (!path || !*path) // no point in checking for remote etc.
  3381. return new CLinuxDirectoryIterator(path, mask,sub,includedirs);
  3382. OwnedIFile iFile = createIFile(path);
  3383. if (!iFile||(iFile->isDirectory()!=fileBool::foundYes))
  3384. return new CNullDirectoryIterator;
  3385. return iFile->directoryFiles(mask, sub, includedirs);
  3386. }
  3387. IDirectoryIterator *CFile::directoryFiles(const char *mask,bool sub,bool includedirs)
  3388. {
  3389. if ((mask&&!*mask)|| // only NULL is wild
  3390. (isDirectory()!=fileBool::foundYes))
  3391. return new CNullDirectoryIterator;
  3392. return new CLinuxDirectoryIterator(filename, mask,sub,includedirs);
  3393. }
  3394. bool CFile::getInfo(bool &isdir,offset_t &size,CDateTime &modtime)
  3395. {
  3396. struct stat info;
  3397. if (stat(filename, &info) == 0) {
  3398. size = (offset_t)info.st_size;
  3399. isdir = S_ISDIR(info.st_mode);
  3400. timetToIDateTime(&modtime, info.st_mtime);
  3401. return true;
  3402. }
  3403. size = 0;
  3404. modtime.clear();
  3405. isdir = false;
  3406. return false;
  3407. }
  3408. #endif
  3409. class CDirEntry: extends CInterface
  3410. {
  3411. public:
  3412. StringAttr name;
  3413. Owned<IFile> file;
  3414. __int64 size;
  3415. CDateTime modified;
  3416. byte flags; // IDDI*
  3417. bool isdir;
  3418. CDirEntry(IDirectoryIterator *iter)
  3419. {
  3420. StringBuffer n;
  3421. name.set(iter->getName(n).str());
  3422. size = iter->getFileSize();
  3423. iter->getModifiedTime(modified);
  3424. file.set(&iter->query());
  3425. flags = 0;
  3426. isdir = iter->isDir();
  3427. }
  3428. bool match(byte f)
  3429. {
  3430. return (flags==0)||((f&flags)!=0);
  3431. }
  3432. int compare(const CDirEntry *e)
  3433. {
  3434. return strcmp(name.get(),e->name.get());
  3435. }
  3436. int compareProp(const CDirEntry *e)
  3437. {
  3438. int c = compare(e);
  3439. if (c)
  3440. return c;
  3441. if (isdir!=e->isdir)
  3442. return isdir?-1:1;
  3443. if (size!=e->size)
  3444. return (size<e->size)?-1:1;
  3445. return modified.compare(e->modified,false);
  3446. }
  3447. };
  3448. class CDirectoryDifferenceIterator : public CIArrayOf<CDirEntry>, extends CInterface, implements IDirectoryDifferenceIterator
  3449. {
  3450. static int compare(CInterface * const *_a, CInterface * const *_b)
  3451. {
  3452. CDirEntry *a = *(CDirEntry **)_a;
  3453. CDirEntry *b = *(CDirEntry **)_b;
  3454. return a->compare(b);
  3455. }
  3456. unsigned idx;
  3457. byte mask;
  3458. public:
  3459. IMPLEMENT_IINTERFACE;
  3460. CDirectoryDifferenceIterator(IDirectoryIterator *iter, CDirectoryDifferenceIterator *cmp)
  3461. {
  3462. mask = IDDIstandard;
  3463. idx = 0;
  3464. ForEach(*iter)
  3465. append(*new CDirEntry(iter));
  3466. CIArrayOf<CDirEntry>::sort(compare);
  3467. if (cmp) { // assumes cmp sorted
  3468. unsigned i = 0;
  3469. unsigned ni = ordinality();
  3470. unsigned j = 0;
  3471. unsigned nj = cmp->ordinality();
  3472. for (;;) {
  3473. CDirEntry *a = NULL;
  3474. CDirEntry *b = NULL;
  3475. if (i>=ni) {
  3476. if (j>=nj)
  3477. break;
  3478. b = &cmp->item(j++);
  3479. }
  3480. else if (j>=nj) {
  3481. a = &item(i++);
  3482. }
  3483. else {
  3484. a = &item(i);
  3485. b = &cmp->item(j);
  3486. int c = a->compare(b);
  3487. if (c==0) {
  3488. if (a->compareProp(b)==0) {
  3489. a->flags = IDDIunchanged;
  3490. a = NULL;
  3491. b = NULL;
  3492. }
  3493. i++;
  3494. j++;
  3495. }
  3496. else if (c<0) {
  3497. b = NULL;
  3498. i++;
  3499. }
  3500. else {
  3501. a = NULL;
  3502. j++;
  3503. }
  3504. }
  3505. if (a) {
  3506. if (b)
  3507. a->flags|=IDDImodified;
  3508. else
  3509. a->flags|=IDDIadded;
  3510. }
  3511. else if (b) {
  3512. b->Link();
  3513. b->flags = IDDIdeleted;
  3514. add(*b,i);
  3515. i++;
  3516. ni++;
  3517. }
  3518. }
  3519. }
  3520. }
  3521. virtual bool first()
  3522. {
  3523. idx = 0;
  3524. while (idx<ordinality()) {
  3525. if (item(idx).match(mask))
  3526. return true;
  3527. idx++;
  3528. }
  3529. return false;
  3530. }
  3531. virtual bool next()
  3532. {
  3533. idx++;
  3534. while (idx<ordinality()) {
  3535. if (item(idx).match(mask))
  3536. return true;
  3537. idx++;
  3538. }
  3539. return false;
  3540. }
  3541. virtual bool isValid()
  3542. {
  3543. return (idx<ordinality());
  3544. }
  3545. virtual IFile & query()
  3546. {
  3547. if (isValid())
  3548. return *item(idx).file;
  3549. throwUnexpected();
  3550. }
  3551. virtual StringBuffer &getName(StringBuffer &buf)
  3552. {
  3553. if (isValid())
  3554. buf.append(item(idx).name);
  3555. return buf;
  3556. }
  3557. virtual bool isDir()
  3558. {
  3559. if (isValid())
  3560. return item(idx).isdir;
  3561. return false;
  3562. }
  3563. __int64 getFileSize()
  3564. {
  3565. if (isValid())
  3566. return item(idx).isdir?0:item(idx).size;
  3567. return 0;
  3568. }
  3569. virtual bool getModifiedTime(CDateTime &ret)
  3570. {
  3571. if (isValid()) {
  3572. ret.set(item(idx).modified);
  3573. }
  3574. return false;
  3575. }
  3576. virtual void setMask(unsigned _mask)
  3577. {
  3578. mask = (byte)_mask;
  3579. }
  3580. virtual unsigned getFlags()
  3581. {
  3582. if (isValid())
  3583. return item(idx).flags;
  3584. return 0;
  3585. }
  3586. unsigned numChanges()
  3587. {
  3588. unsigned ret=0;
  3589. ForEachItemIn(i,*this) {
  3590. byte f = item(i).flags;
  3591. if ((f!=0)&&(f!=IDDIunchanged))
  3592. ret++;
  3593. }
  3594. return ret;
  3595. }
  3596. };
  3597. IDirectoryDifferenceIterator *CFile::monitorDirectory(IDirectoryIterator *_prev, // in
  3598. const char *mask,
  3599. bool sub,
  3600. bool includedirs,
  3601. unsigned checkinterval,
  3602. unsigned timeout,
  3603. Semaphore *abortsem)
  3604. {
  3605. Linked<IDirectoryIterator> prev;
  3606. if (_prev)
  3607. prev.set(_prev);
  3608. else
  3609. prev.setown(directoryFiles(mask,sub,includedirs));
  3610. if (!prev)
  3611. return NULL;
  3612. Owned<CDirectoryDifferenceIterator> base = new CDirectoryDifferenceIterator(prev,NULL);
  3613. prev.clear(); // not needed now
  3614. unsigned start=msTick();
  3615. for (;;) {
  3616. if (abortsem) {
  3617. if (abortsem->wait(checkinterval))
  3618. break;
  3619. }
  3620. else
  3621. Sleep(checkinterval);
  3622. Owned<IDirectoryIterator> current = directoryFiles(mask,sub,includedirs);
  3623. if (!current)
  3624. break;
  3625. Owned<CDirectoryDifferenceIterator> cmp = new CDirectoryDifferenceIterator(current,base);
  3626. current.clear();
  3627. if (cmp->numChanges())
  3628. return cmp.getClear();
  3629. if (msTick()-start>timeout)
  3630. break;
  3631. }
  3632. return NULL; // timed out
  3633. }
  3634. //---------------------------------------------------------------------------
  3635. bool recursiveCreateDirectory(const char * path)
  3636. {
  3637. Owned<IFile> file = createIFile(path);
  3638. if (!file)
  3639. return false;
  3640. return file->createDirectory();
  3641. }
  3642. bool recursiveCreateDirectoryForFile(const char *fullFileName)
  3643. {
  3644. StringBuffer path;
  3645. splitFilename(fullFileName, &path, &path, NULL, NULL);
  3646. return recursiveCreateDirectory(path.str());
  3647. }
  3648. void recursiveRemoveDirectory(IFile *dir)
  3649. {
  3650. Owned<IDirectoryIterator> files = dir->directoryFiles(NULL, false, true);
  3651. ForEach(*files)
  3652. {
  3653. IFile *thisFile = &files->query();
  3654. if (thisFile->isDirectory()==fileBool::foundYes)
  3655. recursiveRemoveDirectory(thisFile);
  3656. else
  3657. {
  3658. thisFile->setReadOnly(false);
  3659. thisFile->remove();
  3660. }
  3661. }
  3662. dir->remove();
  3663. }
  3664. void recursiveRemoveDirectory(const char *dir)
  3665. {
  3666. Owned<IFile> f = createIFile(dir);
  3667. if (f->isDirectory()==fileBool::foundYes)
  3668. recursiveRemoveDirectory(f);
  3669. }
  3670. //---------------------------------------------------------------------------
  3671. size32_t DirectBufferI::read(offset_t pos, size32_t len, void * data)
  3672. {
  3673. if (pos + len > buffLen)
  3674. {
  3675. if (pos > buffLen)
  3676. pos = buffLen;
  3677. len = (size32_t)(buffLen - pos);
  3678. }
  3679. memcpy(data, buffer+pos, len);
  3680. return len;
  3681. }
  3682. size32_t DirectBufferI::write(offset_t pos, size32_t len, const void * data)
  3683. {
  3684. UNIMPLEMENTED;
  3685. }
  3686. size32_t DirectBufferIO::write(offset_t pos, size32_t len, const void * data)
  3687. {
  3688. if (pos + len > buffLen)
  3689. {
  3690. if (pos > buffLen)
  3691. pos = buffLen;
  3692. len = (size32_t)(buffLen - pos);
  3693. }
  3694. memcpy(buffer+pos, data, len);
  3695. return len;
  3696. }
  3697. //---------------------------------------------------------------------------
  3698. IFile * createIFile(const char * filename)
  3699. {
  3700. if (isEmptyString(filename))
  3701. return new CFile(""); // this is in effect a null implementation
  3702. IFile *ret = createContainedIFileByHook(filename);
  3703. if (ret)
  3704. return ret;
  3705. RemoteFilename rfn;
  3706. rfn.setRemotePath(filename);
  3707. if (rfn.isNull())
  3708. throw MakeStringException(-1, "CreateIFile cannot resolve %s", filename);
  3709. ret = createIFileByHook(rfn); // use daliservix in preference
  3710. if (ret)
  3711. return ret;
  3712. // NB: This is forcing OS path access if not a url beginning '//' or '\\'
  3713. bool linremote=(memcmp(filename,"//",2)==0);
  3714. if (!linremote&&(memcmp(filename,"\\\\",2)!=0)) // see if remote looking
  3715. return new CFile(filename);
  3716. if (rfn.isLocal())
  3717. {
  3718. StringBuffer tmplocal;
  3719. rfn.getLocalPath(tmplocal);
  3720. return new CFile(tmplocal);
  3721. }
  3722. /* NB: to get here, no hook has returned a result and the file is non-local and prefixed with // or \\ */
  3723. #ifdef _WIN32
  3724. /* NB: this windows specific code below should really be refactored into the standard
  3725. * hook mechanism. And any path translation should be left/done on the remote side
  3726. * once it gets to dafilersv.
  3727. */
  3728. StringBuffer tmplocal;
  3729. if (linremote||(rfn.queryEndpoint().port!=0))
  3730. {
  3731. while (*filename) // no daliservix so swap '/' for '\' and hope for best
  3732. {
  3733. if (*filename=='/')
  3734. tmplocal.append('\\');
  3735. else
  3736. tmplocal.append(*filename);
  3737. filename++;
  3738. }
  3739. filename =tmplocal.str();
  3740. }
  3741. return new CWindowsRemoteFile(filename);
  3742. #else
  3743. #ifdef USE_SAMBA
  3744. if (memcmp(filename, "//", 2) == 0)
  3745. {
  3746. StringBuffer smbfile("smb:");
  3747. smbfile.append(filename);
  3748. return new CSambaRemoteFile(smbfile.str());
  3749. }
  3750. if (memcmp(filename, "\\\\", 2) == 0)
  3751. {
  3752. StringBuffer smbfile("smb:");
  3753. int i = 0;
  3754. while(filename[i])
  3755. {
  3756. if(filename[i] == '\\')
  3757. smbfile.append('/');
  3758. else
  3759. smbfile.append(filename[i]);
  3760. i++;
  3761. }
  3762. return new CSambaRemoteFile(smbfile.str());
  3763. }
  3764. #else
  3765. if (memcmp(filename,"smb://",6)==0) // don't support samba - try remote
  3766. return createIFile(filename+4);
  3767. #endif
  3768. throw MakeStringException(-1, "createIFile: cannot attach to %s", filename);
  3769. #endif
  3770. }
  3771. IFileIOStream * createIOStream(IFileIO * file)
  3772. {
  3773. return new CFileIOStream(file);
  3774. }
  3775. IFileIOStream * createNoSeekIOStream(IFileIOStream * stream)
  3776. {
  3777. return new CNoSeekFileIOStream(stream);
  3778. }
  3779. IFileIO * createIORange(IFileIO * io, offset_t header, offset_t length)
  3780. {
  3781. return new CFileRangeIO(io, header, length);
  3782. }
  3783. IFileIOStream * createBufferedIOStream(IFileIO * io, unsigned bufsize)
  3784. {
  3785. if (bufsize == (unsigned)-1)
  3786. bufsize = DEFAULT_BUFFER_SIZE;
  3787. return new CBufferedFileIOStream(io, bufsize);
  3788. }
  3789. IFileIOStream * createBufferedAsyncIOStream(IFileAsyncIO * io, unsigned bufsize)
  3790. {
  3791. if (bufsize == (unsigned)-1)
  3792. bufsize = DEFAULT_BUFFER_SIZE*2;
  3793. return new CBufferedAsyncIOStream(io, bufsize);
  3794. }
  3795. IReadSeq *createReadSeq(IFileIOStream * stream, offset_t offset, size32_t size)
  3796. {
  3797. return new CIOStreamReadWriteSeq(stream, offset, size);
  3798. }
  3799. IWriteSeq *createWriteSeq(IFileIOStream * stream, size32_t size)
  3800. {
  3801. return new CIOStreamReadWriteSeq(stream, 0, size);
  3802. }
  3803. extern jlib_decl offset_t filesize(const char *name)
  3804. {
  3805. CFile f(name);
  3806. return f.size();
  3807. }
  3808. extern jlib_decl offset_t getFreeSpace(const char* name)
  3809. {
  3810. offset_t freeBytesToCaller;
  3811. #ifdef _WIN32
  3812. offset_t totalBytes;
  3813. offset_t freeBytes;
  3814. int fResult = GetDiskFreeSpaceEx (name,
  3815. (PULARGE_INTEGER)&freeBytesToCaller,
  3816. (PULARGE_INTEGER)&totalBytes,
  3817. (PULARGE_INTEGER)&freeBytes);
  3818. if (fResult == 0) // error
  3819. {
  3820. return 0;
  3821. }
  3822. #elif defined (__linux__) || defined (__APPLE__)
  3823. struct statfs buf;
  3824. int fResult = statfs(name, &buf);
  3825. if (fResult == -1) // error
  3826. {
  3827. return 0;
  3828. }
  3829. // from "man statfs the def of f_bavail and f_bsize...
  3830. // mult "free blocks avail to non-superuser" by "optimal transfer block size" to get the available size
  3831. freeBytesToCaller = (offset_t)buf.f_bavail * buf.f_bsize;
  3832. #else
  3833. UNIMPLEMENTED;
  3834. #endif
  3835. return freeBytesToCaller;
  3836. }
  3837. extern jlib_decl void createHardLink(const char* fileName, const char* existingFileName)
  3838. {
  3839. #ifdef _WIN32
  3840. // requirements...need to make sure that the directory already exists
  3841. // and the 2 directories need to be on the same drive
  3842. if (!CreateHardLink(fileName, existingFileName, NULL))
  3843. {
  3844. LPVOID lpMsgBuf;
  3845. FormatMessage(
  3846. FORMAT_MESSAGE_ALLOCATE_BUFFER |
  3847. FORMAT_MESSAGE_FROM_SYSTEM |
  3848. FORMAT_MESSAGE_IGNORE_INSERTS,
  3849. NULL,
  3850. GetLastError(),
  3851. MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
  3852. (LPTSTR) &lpMsgBuf,
  3853. 0,
  3854. NULL
  3855. );
  3856. StringBuffer err;
  3857. err.appendf("Failed to create log alias %s for %s: %s", fileName, existingFileName, lpMsgBuf);
  3858. LocalFree( lpMsgBuf );
  3859. throw MakeStringException(-1, "createHardLink:: %s.",err.str());
  3860. }
  3861. #else
  3862. if (link(existingFileName, fileName) != 0) // error
  3863. throw MakeStringException(-1, "Failed to create log alias %s for %s: error code = %d", fileName, existingFileName, errno);
  3864. #endif
  3865. }
  3866. #if 0
  3867. void testDirectory()
  3868. {
  3869. //setDefaultUser("administrator", "password");
  3870. Owned<IFile> dir = createIFile("\\test1\\gavin\\home\\base");
  3871. dir->createDirectory();
  3872. Owned<IFile> dir2 = createIFile("\\test1\\gavin\\home\\base2\\");
  3873. dir2->createDirectory();
  3874. dir2->createDirectory();
  3875. Owned<IFile> dir3 = createIFile("c:\\test1\\gavin\\home2\\base");
  3876. dir3->createDirectory();
  3877. Owned<IFile> dir4 = createIFile("\\\\ghalliday\\c$\\test1\\gavin\\home3\\base");
  3878. dir4->createDirectory();
  3879. Owned<IFile> dir5 = createIFile("\\\\192.168.1.3\\d$\\test2\\gavin\\home3\\base");
  3880. dir5->createDirectory();
  3881. StringBuffer x;
  3882. x.clear();
  3883. splitUNCFilename("\\\\127.0.0.1\\gavin\\abc.ext", &x, &x, &x, &x);
  3884. x.clear();
  3885. splitUNCFilename("\\\\127.0.0.1\\gavin\\abc.ext\\etc", &x, &x, &x, &x);
  3886. x.clear();
  3887. splitUNCFilename("\\\\127.0.0.1\\", &x, &x, &x, &x);
  3888. }
  3889. #endif
  3890. // -- RemoteFilename class (file location encapsulation)
  3891. //#define _TRACERFN
  3892. void RemoteFilename::badFilename(const char * filename)
  3893. {
  3894. throw MakeStringException(-1, "Badly formatted file entry %s", filename);
  3895. }
  3896. bool RemoteFilename::equals(const RemoteFilename & other) const
  3897. {
  3898. if (isNull())
  3899. return other.isNull();
  3900. if (other.isNull())
  3901. return false;
  3902. if (!ep.ipequals(other.ep)) // only use ip for compare
  3903. return false;
  3904. if (isUnixPath()) { // case sensitive
  3905. if (localhead.length()&&other.localhead.length()) {
  3906. if (strcmp(localhead.get(),other.localhead.get())!=0)
  3907. return false;
  3908. }
  3909. else if (sharehead.length()&&other.sharehead.length()) {
  3910. if (strcmp(sharehead.get(),other.sharehead.get())!=0)
  3911. return false;
  3912. }
  3913. else if (sharehead.length()!=other.sharehead.length())
  3914. return false;
  3915. if (strcmp(tailpath.get(),other.tailpath.get())!=0)
  3916. return false;
  3917. }
  3918. else {
  3919. if (localhead.length()&&other.localhead.length()) {
  3920. if (stricmp(localhead.get(),other.localhead.get())!=0)
  3921. return false;
  3922. }
  3923. else if (sharehead.length()&&other.sharehead.length()) {
  3924. if (stricmp(sharehead.get(),other.sharehead.get())!=0)
  3925. return false;
  3926. }
  3927. else if (sharehead.length()!=other.sharehead.length())
  3928. return false;
  3929. if (stricmp(tailpath.get(),other.tailpath.get())!=0)
  3930. return false;
  3931. }
  3932. return true;
  3933. }
  3934. bool RemoteFilename::isNull() const
  3935. {
  3936. return (ep.isNull()||(tailpath.length()==0));
  3937. }
  3938. void RemoteFilename::clear()
  3939. {
  3940. ep.set(NULL, 0);
  3941. localhead.clear();
  3942. sharehead.clear();
  3943. tailpath.clear();
  3944. }
  3945. void RemoteFilename::serialize(MemoryBuffer & out)
  3946. {
  3947. ep.serialize(out);
  3948. out.append(localhead);
  3949. out.append(sharehead);
  3950. out.append(tailpath);
  3951. }
  3952. void RemoteFilename::deserialize(MemoryBuffer & in)
  3953. {
  3954. ep.deserialize(in);
  3955. in.read(localhead);
  3956. in.read(sharehead);
  3957. in.read(tailpath);
  3958. }
  3959. StringBuffer & RemoteFilename::getTail(StringBuffer &name) const
  3960. {
  3961. split(NULL, NULL, &name, &name);
  3962. return name;
  3963. }
  3964. StringBuffer & RemoteFilename::getPath(StringBuffer & name) const
  3965. {
  3966. if (isLocal())
  3967. return getLocalPath(name);
  3968. else
  3969. return getRemotePath(name);
  3970. }
  3971. bool RemoteFilename::isUnixPath() const // bit arbitrary
  3972. {
  3973. if (tailpath.length()!=0) {
  3974. char c = tailpath[0];
  3975. if (c=='/')
  3976. return true;
  3977. if (c=='\\')
  3978. return false;
  3979. }
  3980. if (sharehead.length()!=0) {
  3981. char c = sharehead[0];
  3982. if (c=='/')
  3983. return true;
  3984. if (c=='\\')
  3985. return false;
  3986. }
  3987. if (localhead.length()!=0) {
  3988. const char *s=localhead;
  3989. if (*s=='/')
  3990. return true;
  3991. if ((s[1]==':')&&(s[2]=='/'))
  3992. return false;
  3993. // those are the expected cases, otherwise look for first separator (legacy)
  3994. while (*s) {
  3995. if (*s=='\\')
  3996. return false;
  3997. s++;
  3998. if (*s=='/')
  3999. return true;
  4000. }
  4001. }
  4002. #ifdef _WIN32 // assume local on starting machine
  4003. return false;
  4004. #else
  4005. return true;
  4006. #endif
  4007. }
  4008. bool RemoteFilename::isUrl() const
  4009. {
  4010. return ::isUrl(tailpath);
  4011. }
  4012. char RemoteFilename::getPathSeparator() const
  4013. {
  4014. return isUnixPath()?'/':'\\';
  4015. }
  4016. StringBuffer & RemoteFilename::getLocalPath(StringBuffer & out) const
  4017. {
  4018. if (tailpath.length()!=0) {
  4019. out.append(localhead).append(tailpath);
  4020. }
  4021. #ifdef _TRACERFN
  4022. StringBuffer eps;
  4023. PROGLOG("getLocalPath '%s' '%s' '%s' -> '%s'",sharehead.get()?sharehead.get():"NULL",localhead.get()?localhead.get():"NULL",tailpath.get()?tailpath.get():"NULL",out.str());
  4024. #endif
  4025. return out;
  4026. }
  4027. StringBuffer & RemoteFilename::getRemotePath(StringBuffer & out) const
  4028. { // this creates a name that can be used by windows or linux
  4029. // Any filenames in the format protocol:// should not be converted to //ip:....
  4030. if (isUrl())
  4031. return getLocalPath(out);
  4032. char c=getPathSeparator();
  4033. out.append(c).append(c);
  4034. ep.getUrlStr(out);
  4035. const char *fn;
  4036. StringBuffer loc;
  4037. if (sharehead.length())
  4038. fn = loc.append(sharehead).append(tailpath).str();
  4039. else // try and guess from just tail (may likely fail other than for windows)
  4040. fn=getLocalPath(loc).str();
  4041. if ((fn[1]==':') && (fn[2]=='/' || fn[2]=='\\')) { // windows \\d$
  4042. out.append((char)tolower(c)).append(*fn).append(getShareChar());
  4043. fn+=2;
  4044. }
  4045. out.append(fn);
  4046. #ifdef _TRACERFN
  4047. StringBuffer eps;
  4048. PROGLOG("getRemotePath '%s' '%s' '%s' -> '%s'",sharehead.get()?sharehead.get():"NULL",localhead.get()?localhead.get():"NULL",tailpath.get()?tailpath.get():"NULL",out.str());
  4049. #endif
  4050. return out;
  4051. }
  4052. const FileSystemProperties & RemoteFilename::queryFileSystemProperties() const
  4053. {
  4054. return ::queryFileSystemProperties(tailpath);
  4055. }
  4056. bool RemoteFilename::isLocal() const
  4057. {
  4058. if (ep.port&&(ep.port!=DAFILESRV_PORT && ep.port!=SECURE_DAFILESRV_PORT))
  4059. return false; // treat non-dafilesrv port as remote
  4060. return ep.isLocal() || ep.isNull();
  4061. }
  4062. void RemoteFilename::set(const RemoteFilename & other)
  4063. {
  4064. ep.set(other.ep);
  4065. localhead.set(other.localhead);
  4066. sharehead.set(other.sharehead);
  4067. tailpath.set(other.tailpath);
  4068. }
  4069. void RemoteFilename::setExtension(const char * newext)
  4070. {
  4071. const char * dot = NULL;
  4072. const char * start = tailpath;
  4073. const char * cur = start;
  4074. const char pathSep=getPathSeparator();
  4075. while (*cur)
  4076. {
  4077. // if it is a "." inside the path then skip it.
  4078. if (dot && (*cur == pathSep))
  4079. dot = NULL;
  4080. else if (*cur == '.')
  4081. dot = cur;
  4082. cur++;
  4083. }
  4084. StringBuffer newtail;
  4085. if (dot)
  4086. newtail.append(dot-start,start);
  4087. else
  4088. newtail.append(start);
  4089. if (newext)
  4090. {
  4091. if (newext[0] != '.')
  4092. newtail.append('.');
  4093. newtail.append(newext);
  4094. }
  4095. tailpath.set(newtail);
  4096. }
  4097. void RemoteFilename::setPath(const SocketEndpoint & _ep, const char * _filename)
  4098. {
  4099. const char * filename=_filename;
  4100. StringBuffer full;
  4101. ep.set(_ep);
  4102. localhead.clear();
  4103. sharehead.clear();
  4104. if (filename&&*filename) {
  4105. if (isSpecialPath(filename)) {
  4106. tailpath.set(filename);
  4107. return;
  4108. }
  4109. if (isLocal()&&!isAbsolutePath(filename)) {
  4110. char dir[_MAX_PATH];
  4111. if (!GetCurrentDirectory(sizeof(dir), dir)) {
  4112. IERRLOG("RemoteFilename::setPath: Current directory path too big, bailing out");
  4113. throwUnexpected();
  4114. }
  4115. if (*filename==PATHSEPCHAR) {
  4116. #ifdef _WIN32
  4117. if (*dir && (dir[1]==':'))
  4118. dir[2] = 0;
  4119. #endif
  4120. filename++;
  4121. }
  4122. full.append(dir);
  4123. if (full.charAt(full.length()-1) != PATHSEPCHAR)
  4124. full.append(PATHSEPCHAR);
  4125. full.append(filename);
  4126. filename = full.str();
  4127. }
  4128. bool isunix;
  4129. if (filename[0]=='/')
  4130. isunix=true;
  4131. else if (filename[0]=='\\')
  4132. isunix=false;
  4133. else if ((filename[1]==':')&&(filename[2]=='\\'))
  4134. isunix = false;
  4135. else // invalid call really as supposed to be full local path!
  4136. #ifdef _WIN32
  4137. isunix = false;
  4138. #else
  4139. isunix = true;
  4140. #endif
  4141. StringBuffer tmpxlat;
  4142. char sepchar = isunix?'/':'\\';
  4143. char altchar = isunix?'\\':'/';
  4144. // fix mixed separator path
  4145. if (strchr(filename,altchar)) {
  4146. while (*filename) {
  4147. if (*filename==altchar)
  4148. tmpxlat.append(sepchar);
  4149. else
  4150. tmpxlat.append(*filename);
  4151. filename++;
  4152. }
  4153. filename = tmpxlat.str();
  4154. }
  4155. if (isunix) {
  4156. if (filename[0]=='/') {
  4157. const char *tail;
  4158. tail=strchr(filename+1,'/');
  4159. if (tail) {
  4160. sharehead.set(filename,tail-filename); // we don't know share so guess same as leading dir
  4161. localhead.set(filename,tail-filename);
  4162. filename = tail;
  4163. }
  4164. }
  4165. }
  4166. else { // windows can guess anonymous share
  4167. StringBuffer sharestr;
  4168. if ((filename[1]==':')&&(filename[2]=='\\')) { // this should be always true if true full windows path
  4169. localhead.set(filename,2);
  4170. sharestr.append('\\').append((char)tolower(filename[0])).append(getShareChar());
  4171. filename += 2;
  4172. }
  4173. else if (filename[0]=='\\') {
  4174. const char *tail = strchr(filename+1,'\\');
  4175. if (tail) {
  4176. sharestr.append(tail-filename,filename);
  4177. localhead.set(filename,tail-filename);
  4178. filename = tail;
  4179. }
  4180. else {
  4181. localhead.set("c:");
  4182. sharestr.append("\\c").append(getShareChar());
  4183. }
  4184. }
  4185. sharehead.set(sharestr);
  4186. }
  4187. tailpath.set(filename);
  4188. }
  4189. else
  4190. tailpath.clear();
  4191. #ifdef _TRACERFN
  4192. StringBuffer eps;
  4193. PROGLOG("setPath (%s,%s) -> '%s' '%s' '%s'",ep.getUrlStr(eps).str(),_filename?_filename:"NULL",sharehead.get()?sharehead.get():"NULL",localhead.get()?localhead.get():"NULL",tailpath.get()?tailpath.get():"NULL");
  4194. #endif
  4195. }
  4196. void RemoteFilename::setRemotePath(const char * _url,const char *localpath)
  4197. {
  4198. // url should be full (share) path including ep
  4199. const char *url=_url;
  4200. // if ep not included then assume local (bit weird though)
  4201. char sep = url?url[0]:0;
  4202. if (isPathSepChar(sep)&&(sep==url[1])) {
  4203. url+=2;
  4204. const char *end = findPathSepChar(url);
  4205. if (end) {
  4206. StringBuffer eps(end-url,url);
  4207. ep.set(eps.str());
  4208. url = end;
  4209. }
  4210. else {
  4211. ep.set(NULL,0);
  4212. url--; // don't know what is going on!
  4213. }
  4214. if (isPathSepChar(*url)||!*url)
  4215. sep = *url;
  4216. }
  4217. else
  4218. ep.setLocalHost(0);
  4219. if (localpath&&*localpath)
  4220. setPath(ep,localpath);
  4221. else {
  4222. localhead.clear();
  4223. sharehead.clear();
  4224. tailpath.clear();
  4225. }
  4226. if (sep&&*url) {
  4227. // url should point to the share now
  4228. const char *tail=findPathSepChar(url+1);
  4229. if (tail) { // hopefully must be!
  4230. sharehead.set(url,tail-url);
  4231. url = tail;
  4232. }
  4233. if (localhead.length()==0) { // we don't know so guess
  4234. if (sharehead.length()!=0) {
  4235. const char *share=sharehead.get();
  4236. if (sep=='\\') {
  4237. StringBuffer locstr;
  4238. if (sharehead.length()>2) {
  4239. if (isShareChar(share[2])) {
  4240. locstr.append(share[1]).append(':');
  4241. share+=3;
  4242. }
  4243. else // we haven't a clue!
  4244. locstr.append("c:");
  4245. }
  4246. else if (sharehead[1]!='$') // data format
  4247. locstr.append("c:");
  4248. locstr.append(share);
  4249. localhead.set(locstr);
  4250. }
  4251. else { // we haven't a clue so assume same as share
  4252. localhead.set(sharehead);
  4253. }
  4254. }
  4255. }
  4256. }
  4257. if (tailpath.length()==0)
  4258. tailpath.set(url);
  4259. #ifdef _TRACERFN
  4260. StringBuffer eps;
  4261. PROGLOG("setRemotePath ('%s','%s') -> '%s' '%s' '%s'",_url,localpath?localpath:"NULL",sharehead.get()?sharehead.get():"NULL",localhead.get()?localhead.get():"NULL",tailpath.get()?tailpath.get():"NULL");
  4262. #endif
  4263. }
  4264. void RemoteFilename::setLocalPath(const char *filename)
  4265. {
  4266. SocketEndpoint localEP;
  4267. localEP.setLocalHost(0);
  4268. setPath(localEP, filename);
  4269. }
  4270. void RemoteFilename::split(StringBuffer * drive, StringBuffer * path, StringBuffer * tail, StringBuffer * ext) const
  4271. {
  4272. StringBuffer localname;
  4273. const char *s = getLocalPath(localname).str();
  4274. char sep;
  4275. if (isUnixPath())
  4276. sep = '/';
  4277. else {
  4278. sep = '\\';
  4279. if (s[1]==':') {
  4280. if (drive)
  4281. drive->append(2,s);
  4282. s+=2;
  4283. }
  4284. }
  4285. const char *t=NULL;
  4286. const char *e=s;
  4287. while (*e) {
  4288. if (*e==sep)
  4289. t = e+1;
  4290. e++;
  4291. }
  4292. if (t) {
  4293. if (path)
  4294. path->append(t-s, s);
  4295. s=t;
  4296. }
  4297. if (!tail&&!ext)
  4298. return;
  4299. t = NULL;
  4300. e=s;
  4301. while (*e) {
  4302. if (*e=='.') // NB final extension
  4303. t = e;
  4304. e++;
  4305. }
  4306. if (t) {
  4307. if (tail)
  4308. tail->append(t-s,s);
  4309. if (ext)
  4310. ext->append(e-t,t);
  4311. }
  4312. else if (tail)
  4313. tail->append(e-s,s);
  4314. }
  4315. void RemoteMultiFilename::append(const char *mpath,const char *defaultdir)
  4316. {
  4317. StringArray paths;
  4318. expand(mpath, paths);
  4319. StringBuffer fullpath;
  4320. StringBuffer deftmp;
  4321. if (paths.ordinality()&&(defaultdir==NULL)&&isAbsolutePath(paths.item(0))) {
  4322. splitDirTail(paths.item(0),deftmp);
  4323. defaultdir = deftmp.str();
  4324. }
  4325. ForEachItemIn(i,paths) {
  4326. const char *filename = paths.item(i);
  4327. RemoteFilename rfn;
  4328. if (isPathSepChar(*filename)&&isPathSepChar(filename[1])) // full URL
  4329. rfn.setRemotePath(filename);
  4330. else {
  4331. if (defaultdir&&!isAbsolutePath(filename))
  4332. filename = addPathSepChar(fullpath.clear().append(defaultdir)).append(filename).str();
  4333. rfn.setPath(ep,filename);
  4334. }
  4335. append(rfn);
  4336. }
  4337. }
  4338. void RemoteMultiFilename::append(const RemoteFilename &inrfn)
  4339. {
  4340. RemoteFilename rfn;
  4341. rfn.set(inrfn);
  4342. if (ep.isNull())
  4343. ep = rfn.queryEndpoint();
  4344. else if (rfn.queryIP().isNull()) {
  4345. rfn.setEp(ep);
  4346. }
  4347. else if (!rfn.queryIP().ipequals(ep)) {
  4348. StringBuffer path;
  4349. rfn.getRemotePath(path);
  4350. throw MakeStringException(-1, "Component file IP does not match: %s", path.str());
  4351. }
  4352. RemoteFilenameArray::append(rfn);
  4353. }
  4354. void RemoteMultiFilename::deserialize(MemoryBuffer & in)
  4355. {
  4356. clear();
  4357. ep.deserialize(in);
  4358. unsigned n;
  4359. in.read(n);
  4360. StringBuffer last;
  4361. StringBuffer filename;
  4362. RemoteFilename rfn;
  4363. for (unsigned i=0;i<n;i++) {
  4364. byte l;
  4365. in.read(l);
  4366. filename.clear();
  4367. if (l)
  4368. filename.append((size32_t)l,last.str());
  4369. StringAttr s;
  4370. in.read(s);
  4371. filename.append(s);
  4372. rfn.setPath(ep,filename.str());
  4373. RemoteFilenameArray::append(rfn);
  4374. last.swapWith(filename);
  4375. }
  4376. }
  4377. void RemoteMultiFilename::serialize(MemoryBuffer & out)
  4378. {
  4379. ep.serialize(out);
  4380. unsigned n=ordinality();
  4381. out.append(n);
  4382. // do simple compression
  4383. StringBuffer last;
  4384. StringBuffer filename;
  4385. for (unsigned i=0;i<n;i++) {
  4386. item(i).getLocalPath(filename.clear());
  4387. const char *s1 = last.str();
  4388. const char *s2 = filename.str();
  4389. byte l=0;
  4390. while ((l<255)&&*s1&&*s2&&(*s1==*s2)) {
  4391. s1++;
  4392. s2++;
  4393. l++;
  4394. }
  4395. out.append(l);
  4396. out.append(s2);
  4397. last.swapWith(filename);
  4398. }
  4399. }
  4400. bool RemoteMultiFilename::isWild(unsigned idx) const
  4401. {
  4402. if (idx==(unsigned)-1) {
  4403. ForEachItem(i)
  4404. if (isWild(i))
  4405. return true;
  4406. }
  4407. else {
  4408. StringBuffer s;
  4409. item(idx).getTail(s);
  4410. if (containsFileWildcard(s.str()))
  4411. return true;
  4412. }
  4413. return false;
  4414. }
  4415. void RemoteMultiFilename::expandWild()
  4416. {
  4417. bool anywild = false;
  4418. BoolArray iswild;
  4419. ForEachItem(i1) {
  4420. if (isWild(i1)) {
  4421. anywild = true;
  4422. iswild.append(true);
  4423. }
  4424. else
  4425. iswild.append(false);
  4426. }
  4427. if (!anywild)
  4428. return; // nothing to do
  4429. // first cache old values (bit long winded but want to preserve order)
  4430. RemoteFilenameArray tmpa;
  4431. Int64Array tmpsz;
  4432. ForEachItem(i2) {
  4433. RemoteFilename rfn(item(i2));
  4434. tmpa.append(rfn);
  4435. if (i2<sizescache.ordinality())
  4436. tmpsz.append(sizescache.item(i2));
  4437. else
  4438. tmpsz.append(-1);
  4439. }
  4440. RemoteFilenameArray::kill();
  4441. sizescache.kill();
  4442. ForEachItemIn(i3,tmpa) {
  4443. RemoteFilename rfn(tmpa.item(i3));
  4444. if (iswild.item(i3)) {
  4445. StringBuffer name;
  4446. rfn.getLocalPath(name);
  4447. const char *s=name.str();
  4448. const char *t=s;
  4449. for (;;) {
  4450. const char *sep=findPathSepChar(t);
  4451. if (!sep)
  4452. break;
  4453. t = sep+1;
  4454. }
  4455. StringAttr tail(t);
  4456. name.setLength(t-s);
  4457. rfn.setPath(rfn.queryEndpoint(),name);
  4458. Owned<IFile> dir = createIFile(rfn);
  4459. Owned<IDirectoryIterator> iter = dir->directoryFiles(tail.get());
  4460. ForEach(*iter) {
  4461. append(iter->query().queryFilename());
  4462. sizescache.append(iter->getFileSize());
  4463. }
  4464. }
  4465. else {
  4466. append(rfn);
  4467. sizescache.append(tmpsz.item(i3));
  4468. }
  4469. }
  4470. }
  4471. offset_t RemoteMultiFilename::getSize(unsigned i)
  4472. {
  4473. __int64 ret = (i<sizescache.ordinality())?sizescache.item(i):-1;
  4474. if (ret==-1) {
  4475. RemoteFilename rfn(item(i));
  4476. Owned<IFile> file = createIFile(rfn);
  4477. ret = file->size();
  4478. }
  4479. return (offset_t)ret;
  4480. }
  4481. void RemoteMultiFilename::setIp(const IpAddress & ip)
  4482. {
  4483. ep.ipset(ip);
  4484. ForEachItem(i)
  4485. element(i).setIp(ip);
  4486. }
  4487. void RemoteMultiFilename::setEp(const SocketEndpoint & _ep)
  4488. {
  4489. ep.set(_ep);
  4490. ForEachItem(i)
  4491. element(i).setEp(_ep);
  4492. }
  4493. void RemoteMultiFilename::setPort(unsigned short port)
  4494. {
  4495. ep.port = port;
  4496. ForEachItem(i)
  4497. element(i).setPort(port);
  4498. }
  4499. void RemoteMultiFilename::set(const RemoteMultiFilename & other)
  4500. {
  4501. clear();
  4502. ep.set(other.ep);
  4503. ForEachItemIn(i,other) {
  4504. append(other.item(i));
  4505. if (i<other.sizescache.ordinality())
  4506. sizescache.append(other.sizescache.item(i));
  4507. }
  4508. }
  4509. bool RemoteMultiFilename::equals(const RemoteMultiFilename & other)
  4510. {
  4511. if (!ep.equals(other.ep))
  4512. return false;
  4513. if (ordinality()!=other.ordinality())
  4514. return false;
  4515. ForEachItem(i)
  4516. if (!item(i).equals(other.item(i)))
  4517. return false;
  4518. return true;
  4519. }
  4520. void RemoteMultiFilename::expand(const char *mpath, StringArray &array)
  4521. {
  4522. StringBuffer path;
  4523. StringBuffer fullpath;
  4524. for (;;) {
  4525. while (isspace(*mpath))
  4526. mpath++;
  4527. if (!*mpath)
  4528. break;
  4529. bool inquote=false;
  4530. while (*mpath) {
  4531. if (*mpath=='"') {
  4532. mpath++;
  4533. if (inquote) {
  4534. if (*mpath!='"') {
  4535. inquote = false;
  4536. continue;
  4537. }
  4538. }
  4539. else {
  4540. inquote = true;
  4541. continue;
  4542. }
  4543. }
  4544. if ((*mpath==',')&&!inquote) {
  4545. mpath++;
  4546. break;
  4547. }
  4548. path.append(*mpath);
  4549. mpath++;
  4550. }
  4551. path.clip();
  4552. if (path.length()) {
  4553. array.append(path.str());
  4554. path.clear();
  4555. }
  4556. }
  4557. }
  4558. void RemoteMultiFilename::tostr(StringArray &array,StringBuffer &out)
  4559. {
  4560. ForEachItemIn(i,array) {
  4561. const char *s = array.item(i);
  4562. if (!s||!*s)
  4563. continue;
  4564. if (i!=0)
  4565. out.append(',');
  4566. bool needquote=false;
  4567. for (const char *e=s;*e;e++)
  4568. if (isspace(*e)||(*e==',')) {
  4569. needquote = true;
  4570. break;
  4571. }
  4572. if (needquote)
  4573. out.append('"');
  4574. out.append(s);
  4575. if (needquote)
  4576. out.append('"');
  4577. }
  4578. }
  4579. //===================================================================================================
  4580. static IArrayOf<IContainedFileHook> containedFileHooks;
  4581. static ReadWriteLock containedFileHookLock;
  4582. void addContainedFileHook(IContainedFileHook *hook)
  4583. {
  4584. if (hook)
  4585. {
  4586. hook->Link();
  4587. WriteLockBlock block(containedFileHookLock);
  4588. containedFileHooks.append(*hook);
  4589. }
  4590. }
  4591. void removeContainedFileHook(IContainedFileHook *hook)
  4592. {
  4593. WriteLockBlock block(containedFileHookLock);
  4594. containedFileHooks.zap(*hook);
  4595. }
  4596. static IFile *createContainedIFileByHook(const char *filename)
  4597. {
  4598. ReadLockBlock block(containedFileHookLock);
  4599. ForEachItemIn(i, containedFileHooks)
  4600. {
  4601. IFile * ret = containedFileHooks.item(i).createIFile(filename);
  4602. if (ret)
  4603. return ret;
  4604. }
  4605. return NULL;
  4606. }
  4607. static IArrayOf<IRemoteFileCreateHook> remoteFileHooks;
  4608. static ReadWriteLock remoteFileHookLock;
  4609. void addIFileCreateHook(IRemoteFileCreateHook *hook)
  4610. {
  4611. if (hook)
  4612. {
  4613. hook->Link();
  4614. WriteLockBlock block(remoteFileHookLock);
  4615. remoteFileHooks.append(*hook);
  4616. }
  4617. }
  4618. void removeIFileCreateHook(IRemoteFileCreateHook *hook)
  4619. {
  4620. WriteLockBlock block(remoteFileHookLock);
  4621. remoteFileHooks.zap(*hook);
  4622. }
  4623. static IFile *createIFileByHook(const RemoteFilename & filename)
  4624. {
  4625. ReadLockBlock block(remoteFileHookLock);
  4626. ForEachItemIn(i, remoteFileHooks)
  4627. {
  4628. IFile * ret = remoteFileHooks.item(i).createIFile(filename);
  4629. if (ret)
  4630. return ret;
  4631. }
  4632. return NULL;
  4633. }
  4634. IFile * createIFile(const RemoteFilename & filename)
  4635. {
  4636. IFile * ret = createIFileByHook(filename);
  4637. if (ret)
  4638. return ret;
  4639. StringBuffer name;
  4640. return createIFile(getLocalOrRemoteName(name,filename).str());
  4641. }
  4642. StringBuffer &makePathUniversal(const char *path, StringBuffer &out)
  4643. {
  4644. if (!path||!*path)
  4645. return out;
  4646. if (path[1]==':')
  4647. {
  4648. out.append('/').append(*path);
  4649. path+=2;
  4650. }
  4651. for (; *path; path++)
  4652. out.append(isPathSepChar(*path) ? '/' : *path);
  4653. return out;
  4654. }
  4655. // A filename is a URL if it starts xxxx://
  4656. bool isUrl(const char *path)
  4657. {
  4658. if (!path||!*path)
  4659. return false;
  4660. const char * cur = path;
  4661. for (;;)
  4662. {
  4663. switch (*cur++)
  4664. {
  4665. case '/':
  4666. case '\\':
  4667. case '\0':
  4668. return false;
  4669. case ':':
  4670. return cur[0]=='/' && cur[1]=='/';
  4671. }
  4672. }
  4673. }
  4674. //Treat a filename as absolute if:
  4675. // a) The filename begins with a path separator character e.g. /home/hpcc/blah \Users\hpcc\blah
  4676. // b) If there is a colon before the first path separator e.g. c:\Users\hpcc\blah s3://mycontainer/myblob
  4677. //
  4678. // Do not match:
  4679. // A) regress::myfile::x::y
  4680. // B) local/mydir
  4681. // C) mylocal
  4682. bool isAbsolutePath(const char *path)
  4683. {
  4684. if (!path||!*path)
  4685. return false;
  4686. if (isPathSepChar(path[0]))
  4687. return true;
  4688. const char * cur = path;
  4689. bool hadColon = false;
  4690. for (;;)
  4691. {
  4692. switch (*cur++)
  4693. {
  4694. case '/':
  4695. case '\\':
  4696. return hadColon;
  4697. case '\0':
  4698. return false;
  4699. case ':':
  4700. hadColon = true;
  4701. break;
  4702. }
  4703. }
  4704. }
  4705. //Treat a filename as remote if:
  4706. // a) The filename begins \\ or //
  4707. // b) The filename begins xxx://
  4708. //
  4709. bool isRemotePath(const char *path)
  4710. {
  4711. if (!path||!*path)
  4712. return false;
  4713. if (isPathSepChar(path[0]) && isPathSepChar(path[1]))
  4714. return true;
  4715. const char * cur = path;
  4716. for (;;)
  4717. {
  4718. switch (*cur++)
  4719. {
  4720. case '/':
  4721. case '\\':
  4722. case '\0':
  4723. return false;
  4724. case ':':
  4725. return cur[0]=='/' && cur[1]=='/';
  4726. }
  4727. }
  4728. }
  4729. StringBuffer &makeAbsolutePath(const char *relpath,StringBuffer &out, bool mustExist)
  4730. {
  4731. // NOTE - this function also normalizes the supplied path to remove . and .. references
  4732. if (isRemotePath(relpath))
  4733. {
  4734. if (mustExist)
  4735. {
  4736. OwnedIFile iFile = createIFile(relpath);
  4737. if (!iFile->exists())
  4738. throw makeStringExceptionV(-1, "makeAbsolutePath: could not resolve absolute path for %s", relpath);
  4739. }
  4740. return out.append(relpath); // if remote then already should be absolute
  4741. }
  4742. #ifdef _WIN32
  4743. char rPath[MAX_PATH];
  4744. char *filepart;
  4745. if (!relpath || '\0' == *relpath)
  4746. relpath = ".";
  4747. DWORD res = GetFullPathName(relpath, sizeof(rPath), rPath, &filepart);
  4748. if (0 == res)
  4749. throw makeOsExceptionV(GetLastError(), "makeAbsolutePath: could not resolve absolute path for %s", relpath);
  4750. else if (mustExist)
  4751. {
  4752. OwnedIFile iFile = createIFile(rPath);
  4753. if (!iFile->exists())
  4754. throw makeStringExceptionV(-1, "makeAbsolutePath: could not resolve absolute path for %s", rPath);
  4755. }
  4756. out.append(rPath);
  4757. #else
  4758. StringBuffer expanded;
  4759. //Expand ~ on the front of a filename - useful for paths not passed on the command line
  4760. //Note, it does not support the ~user/ version of the syntax
  4761. if ((*relpath == '~') && isPathSepChar(relpath[1]))
  4762. {
  4763. getHomeDir(expanded);
  4764. expanded.append(relpath+1);
  4765. relpath = expanded.str();
  4766. }
  4767. char rPath[PATH_MAX];
  4768. if (mustExist)
  4769. {
  4770. if (!realpath(relpath, rPath))
  4771. throw makeErrnoExceptionV(errno, "makeAbsolutePath: could not resolve absolute path for %s", relpath);
  4772. out.append(rPath);
  4773. }
  4774. else
  4775. {
  4776. // no error, will attempt to resolve(realpath) as much of relpath as possible and append rest
  4777. if (strlen(relpath))
  4778. {
  4779. const char *end = relpath+strlen(relpath);
  4780. const char *path = relpath;
  4781. const char *tail = end;
  4782. StringBuffer head;
  4783. for (;;)
  4784. {
  4785. if (realpath(path,rPath))
  4786. {
  4787. out.append(rPath);
  4788. if (tail != end)
  4789. out.append(tail);
  4790. return removeTrailingPathSepChar(out);
  4791. }
  4792. // mark next tail
  4793. for (;;)
  4794. {
  4795. --tail;
  4796. if (tail == relpath)
  4797. break;
  4798. else if ('/' == *tail)
  4799. break;
  4800. }
  4801. if (tail == relpath)
  4802. break; // bail out and guess
  4803. head.clear().append(tail-relpath, relpath);
  4804. path = head.str();
  4805. }
  4806. }
  4807. if (isAbsolutePath(relpath))
  4808. out.append(relpath);
  4809. else
  4810. {
  4811. appendCurrentDirectory(out, true);
  4812. if (strlen(relpath))
  4813. addPathSepChar(out).append(relpath);
  4814. }
  4815. }
  4816. #endif
  4817. return removeTrailingPathSepChar(out);
  4818. }
  4819. StringBuffer &makeAbsolutePath(StringBuffer &relpath,bool mustExist)
  4820. {
  4821. StringBuffer out;
  4822. makeAbsolutePath(relpath.str(),out,mustExist);
  4823. relpath.swapWith(out);
  4824. return relpath;
  4825. }
  4826. StringBuffer &makeAbsolutePath(const char *relpath, const char *basedir, StringBuffer &out)
  4827. {
  4828. StringBuffer combined;
  4829. if (basedir && !isAbsolutePath(relpath))
  4830. relpath = combined.append(basedir).append(relpath);
  4831. return makeAbsolutePath(relpath, out);
  4832. }
  4833. const char *splitRelativePath(const char *full,const char *basedir,StringBuffer &reldir)
  4834. {
  4835. if (basedir&&*basedir) {
  4836. size_t bl = strlen(basedir);
  4837. if (isPathSepChar(basedir[bl-1]))
  4838. bl--;
  4839. if ((memicmp(full,basedir,bl)==0)&&isPathSepChar(full[bl]))
  4840. full += bl+1;
  4841. }
  4842. const char *t = full;
  4843. for (;;) {
  4844. const char *n = findPathSepChar(t);
  4845. if (!n)
  4846. break;
  4847. t = n+1;
  4848. }
  4849. if (t!=full)
  4850. reldir.append(t-full,full);
  4851. return t;
  4852. }
  4853. const char *splitDirMultiTail(const char *multipath,StringBuffer &dir,StringBuffer &tail)
  4854. {
  4855. // the first directory is the significant one
  4856. // others only removed if same
  4857. dir.clear();
  4858. StringArray files;
  4859. RemoteMultiFilename::expand(multipath,files);
  4860. StringBuffer reldir;
  4861. ForEachItemIn(i,files) {
  4862. const char *s = files.item(i);
  4863. if (i==0) {
  4864. if (isAbsolutePath(s)) {
  4865. StringAttr tail(splitDirTail(s,dir));
  4866. if (dir.length())
  4867. files.replace(tail,i);
  4868. }
  4869. }
  4870. else if (dir.length()) {
  4871. s= splitRelativePath(s,dir.str(),reldir.clear());
  4872. if (reldir.length()) {
  4873. reldir.append(s);
  4874. files.replace(reldir.str(),i);
  4875. }
  4876. }
  4877. }
  4878. RemoteMultiFilename::tostr(files,tail);
  4879. return tail.str();
  4880. }
  4881. StringBuffer &mergeDirMultiTail(const char *dir,const char *tail, StringBuffer &multipath)
  4882. {
  4883. StringArray files;
  4884. RemoteMultiFilename::expand(tail,files);
  4885. StringBuffer reldir;
  4886. if (dir && *dir) {
  4887. ForEachItemIn(i,files) {
  4888. const char *s = files.item(i);
  4889. if (!isAbsolutePath(s)) {
  4890. reldir.clear().append(dir);
  4891. addPathSepChar(reldir).append(s);
  4892. files.replace(reldir.str(),i);
  4893. }
  4894. }
  4895. }
  4896. RemoteMultiFilename::tostr(files,multipath);
  4897. return multipath;
  4898. }
  4899. StringBuffer &removeRelativeMultiPath(const char *full,const char *reldir,StringBuffer &res)
  4900. {
  4901. StringArray files;
  4902. RemoteMultiFilename::expand(full,files);
  4903. StringBuffer tmp1;
  4904. StringBuffer tmp2;
  4905. StringBuffer dir;
  4906. ForEachItemIn(i,files) {
  4907. const char *s = files.item(i);
  4908. if (isAbsolutePath(s)) {
  4909. if (!dir.length())
  4910. splitDirTail(s,dir);
  4911. }
  4912. else if (dir.length()) {
  4913. tmp1.clear().append(dir);
  4914. addPathSepChar(tmp1).append(s);
  4915. s = tmp1.str();
  4916. }
  4917. s = splitRelativePath(s,reldir,tmp2.clear());
  4918. tmp2.append(s);
  4919. files.replace(tmp2.str(),i);
  4920. }
  4921. RemoteMultiFilename::tostr(files,res);
  4922. return res;
  4923. }
  4924. // removes basedir if matches, returns relative multipath
  4925. //===================================================================================================
  4926. ExtractedBlobInfo::ExtractedBlobInfo(const char * _filename, offset_t _length, offset_t _offset)
  4927. {
  4928. filename.set(_filename);
  4929. length = _length;
  4930. offset = _offset;
  4931. }
  4932. void ExtractedBlobInfo::serialize(MemoryBuffer & buffer)
  4933. {
  4934. ::serialize(buffer, filename.get());
  4935. buffer.append(length).append(offset);
  4936. }
  4937. void ExtractedBlobInfo::deserialize(MemoryBuffer & buffer)
  4938. {
  4939. ::deserialize(buffer, filename);
  4940. buffer.read(length).read(offset);
  4941. }
  4942. //----------------------------------------------------------------------------
  4943. #define DFTERR_InvalidSplitPrefixFormat 8091
  4944. #define DFTERR_InvalidSplitPrefixFormat_Text "Cannot process file %s using the splitprefix supplied"
  4945. static void * readLength(MemoryBuffer & buffer, IFileIOStream * in, size_t len, const char * filenameText)
  4946. {
  4947. void * ptr = buffer.clear().reserve(len);
  4948. if (in->read(len, ptr) != len)
  4949. throwError1(DFTERR_InvalidSplitPrefixFormat, filenameText);
  4950. return ptr;
  4951. }
  4952. void extractBlobElements(const char * prefix, const RemoteFilename &filename, ExtractedBlobArray & extracted)
  4953. {
  4954. StringBuffer filenameText;
  4955. filename.getPath(filenameText);
  4956. Owned<IFile> file = createIFile(filename);
  4957. Owned<IFileIO> inIO = file->open(IFOread);
  4958. if (!inIO)
  4959. throw MakeStringException(-1, "extractBlobElements: file '%s' not found", filenameText.str());
  4960. Owned<IFileIOStream> in = createIOStream(inIO);
  4961. MemoryBuffer buffer;
  4962. offset_t endOffset = in->size();
  4963. while (in->tell() != endOffset)
  4964. {
  4965. StringAttr blobFilename;
  4966. offset_t blobLength = (offset_t)-1;
  4967. const char * finger = prefix;
  4968. while (finger)
  4969. {
  4970. StringAttr command;
  4971. const char * comma = strchr(finger, ',');
  4972. if (comma)
  4973. {
  4974. command.set(finger, comma-finger);
  4975. finger = comma+1;
  4976. }
  4977. else
  4978. {
  4979. command.set(finger);
  4980. finger = NULL;
  4981. }
  4982. command.toUpperCase();
  4983. if (memcmp(command, "FILENAME", 8) == 0)
  4984. {
  4985. if (command[8] == ':')
  4986. {
  4987. unsigned maxLen = atoi(command+9);
  4988. const char * nameptr = (const char *)readLength(buffer, in, maxLen, filenameText.str());
  4989. blobFilename.set(nameptr, maxLen);
  4990. }
  4991. else
  4992. {
  4993. unsigned * lenptr = (unsigned *)readLength(buffer, in, sizeof(unsigned), filenameText.str());
  4994. #if __BYTE_ORDER != __LITTLE_ENDIAN
  4995. _rev(sizeof(*lenptr), lenptr);
  4996. #endif
  4997. unsigned filenamelen = *lenptr;
  4998. const char * nameptr = (const char *)readLength(buffer, in, filenamelen, filenameText.str());
  4999. blobFilename.set(nameptr, filenamelen);
  5000. }
  5001. }
  5002. else if ((memcmp(command, "FILESIZE", 8) == 0) || (command.length() == 2))
  5003. {
  5004. const char * format = command;
  5005. if (memcmp(format, "FILESIZE", 8) == 0)
  5006. {
  5007. if (format[8] == ':')
  5008. format = format+9;
  5009. else
  5010. format = "L4";
  5011. }
  5012. bool bigEndian;
  5013. char c = format[0];
  5014. if (c == 'B')
  5015. bigEndian = true;
  5016. else if (c == 'L')
  5017. bigEndian = false;
  5018. else
  5019. throwError1(DFTERR_InvalidSplitPrefixFormat, format);
  5020. c = format[1];
  5021. if ((c <= '0') || (c > '8'))
  5022. throwError1(DFTERR_InvalidSplitPrefixFormat, format);
  5023. unsigned length = (c - '0');
  5024. byte * lenptr = (byte *)readLength(buffer, in, length, filenameText.str());
  5025. if (!bigEndian)
  5026. _rev(length, lenptr);
  5027. blobLength = 0;
  5028. for (unsigned i=0; i<length; i++)
  5029. {
  5030. blobLength = (blobLength << 8) | lenptr[i];
  5031. }
  5032. }
  5033. else if (memcmp(command, "SKIP:", 5) == 0)
  5034. {
  5035. unsigned skipLen = atoi(command+5);
  5036. in->seek(in->tell()+skipLen, IFSbegin);
  5037. }
  5038. else if (memcmp(command, "SEQ:", 4) == 0)
  5039. {
  5040. unsigned skipLen = atoi(command+4);
  5041. in->seek(in->tell()+skipLen, IFSbegin);
  5042. }
  5043. else
  5044. throwError1(DFTERR_InvalidSplitPrefixFormat, command.get());
  5045. }
  5046. if ((blobLength == (offset_t)-1) || !blobFilename.get())
  5047. throwError1(DFTERR_InvalidSplitPrefixFormat, filenameText.str());
  5048. offset_t blobOffset = in->tell();
  5049. extracted.append(* new ExtractedBlobInfo(blobFilename, blobLength, blobOffset));
  5050. in->seek(blobOffset + blobLength, IFSbegin);
  5051. }
  5052. }
  5053. bool mountDrive(const char *drv,const RemoteFilename &rfn)
  5054. {
  5055. #ifdef _WIN32
  5056. return false;
  5057. #else
  5058. unmountDrive(drv);
  5059. localCreateDirectory(drv);
  5060. int ret;
  5061. for (unsigned vtry=0;vtry<2;vtry++) {
  5062. StringBuffer cmd;
  5063. cmd.append("mount ");
  5064. rfn.queryIP().getIpText(cmd);
  5065. cmd.append(':');
  5066. rfn.getLocalPath(cmd);
  5067. cmd.append(' ').append(drv).append(" -t nfs ");
  5068. if (vtry==0)
  5069. cmd.append("-o nfsvers=v3 "); // prefer v3
  5070. cmd.append("2> /dev/null");
  5071. ret = system(cmd.str());
  5072. if (ret==0)
  5073. break;
  5074. }
  5075. return (ret==0);
  5076. #endif
  5077. }
  5078. bool unmountDrive(const char *drv)
  5079. {
  5080. #ifdef _WIN32
  5081. return false;
  5082. #else
  5083. StringBuffer cmd;
  5084. cmd.append("umount ").append(drv).append(" 2> /dev/null");
  5085. int ret = system(cmd.str());
  5086. return (ret==0);
  5087. #endif
  5088. }
  5089. IFileIO *createUniqueFile(const char *dir, const char *prefix, const char *ext, StringBuffer &filename, IFOmode mode)
  5090. {
  5091. CDateTime dt;
  5092. dt.setNow();
  5093. unsigned t = (unsigned)dt.getSimple();
  5094. unsigned attempts = 5; // max attempts
  5095. if (!ext || !*ext)
  5096. ext = "tmp";
  5097. for (;;)
  5098. {
  5099. filename.clear();
  5100. if (dir)
  5101. {
  5102. filename.append(dir);
  5103. addPathSepChar(filename);
  5104. }
  5105. if (prefix && *prefix)
  5106. filename.append(prefix);
  5107. else
  5108. filename.append("uniq");
  5109. filename.appendf("_%" I64F "x.%x.%x.%s", (__int64)GetCurrentThreadId(), (unsigned)GetCurrentProcessId(), t, ext);
  5110. OwnedIFile iFile = createIFile(filename.str());
  5111. if (!iFile->exists())
  5112. {
  5113. try { return iFile->openShared(mode, IFSHnone); } // NB: could be null if path not found
  5114. catch (IException *e)
  5115. {
  5116. EXCLOG(e, "createUniqueFile");
  5117. e->Release();
  5118. }
  5119. }
  5120. if (0 == --attempts)
  5121. return nullptr;
  5122. t += getRandom();
  5123. }
  5124. }
  5125. unsigned sortDirectory( CIArrayOf<CDirectoryEntry> &sortedfiles,
  5126. IDirectoryIterator &iter,
  5127. SortDirectoryMode mode,
  5128. bool rev,
  5129. bool includedirs
  5130. )
  5131. {
  5132. sortedfiles.kill();
  5133. StringBuffer name;
  5134. ForEach(iter) {
  5135. if (!iter.isDir()||includedirs)
  5136. sortedfiles.append(*new CDirectoryEntry(iter));
  5137. }
  5138. if (mode!=SD_nosort) {
  5139. struct icmp: implements ICompare
  5140. {
  5141. SortDirectoryMode mode;
  5142. bool rev;
  5143. int docompare(const void *l,const void *r) const
  5144. {
  5145. int ret=0;
  5146. const CDirectoryEntry *dl = (const CDirectoryEntry *)l;
  5147. const CDirectoryEntry *dr = (const CDirectoryEntry *)r;
  5148. switch (mode) {
  5149. case SD_byname:
  5150. ret = strcmp(dl->name,dr->name);
  5151. break;
  5152. case SD_bynameNC:
  5153. ret = stricmp(dl->name,dr->name);
  5154. break;
  5155. case SD_bydate:
  5156. ret = dl->modifiedTime.compare(dr->modifiedTime);
  5157. break;
  5158. case SD_bysize:
  5159. ret = (dl->size>dr->size)?1:((dl->size<dr->size)?-1:0);
  5160. break;
  5161. }
  5162. if (rev)
  5163. ret = -ret;
  5164. return ret;
  5165. }
  5166. } cmp;
  5167. cmp.mode = mode;
  5168. cmp.rev = rev;
  5169. qsortvec((void **)sortedfiles.getArray(), sortedfiles.ordinality(), cmp);
  5170. }
  5171. return sortedfiles.ordinality();
  5172. }
  5173. class CReplicatedFile : implements IReplicatedFile, public CInterface
  5174. {
  5175. RemoteFilenameArray copies;
  5176. public:
  5177. IMPLEMENT_IINTERFACE;
  5178. RemoteFilenameArray &queryCopies()
  5179. {
  5180. return copies;
  5181. }
  5182. IFile *open()
  5183. {
  5184. StringBuffer locations;
  5185. Owned<IException> exc;
  5186. ForEachItemIn(copy,copies) {
  5187. const RemoteFilename &rfn = copies.item(copy);
  5188. try {
  5189. OwnedIFile iFile = createIFile(rfn);
  5190. if (iFile->exists())
  5191. return iFile.getClear();
  5192. if (locations.length())
  5193. locations.append(", ");
  5194. rfn.getRemotePath(locations);
  5195. }
  5196. catch(IException *e) {
  5197. EXCLOG(e,"CReplicatedFile::open");
  5198. if (exc)
  5199. e->Release();
  5200. else
  5201. exc.setown(e);
  5202. }
  5203. }
  5204. if (exc.get())
  5205. throw exc.getClear();
  5206. throw MakeStringException(0, "%s: Failed to open part file at any of the following locations: ", locations.str());
  5207. }
  5208. };
  5209. IReplicatedFile *createReplicatedFile()
  5210. {
  5211. return new CReplicatedFile;
  5212. }
  5213. // ---------------------------------------------------------------------------------
  5214. class CSerialStreamBase : implements ISerialStream, public CInterface
  5215. {
  5216. private:
  5217. size32_t bufsize;
  5218. size32_t bufpos;
  5219. size32_t bufmax;
  5220. offset_t bufbase;
  5221. offset_t endpos; // -1 if not known
  5222. MemoryAttr ma;
  5223. byte *buf;
  5224. bool eoinput;
  5225. IFileSerialStreamCallback *tally;
  5226. inline size32_t doread(offset_t pos, size32_t max_size, void *ptr)
  5227. {
  5228. if (endpos!=(offset_t)-1) {
  5229. if (pos>=endpos)
  5230. return 0;
  5231. if (endpos-pos<max_size)
  5232. max_size = (size32_t)(endpos-pos);
  5233. }
  5234. size32_t size_read = rawread(pos, max_size, ptr);
  5235. if (tally)
  5236. tally->process(pos,size_read,ptr);
  5237. return size_read;
  5238. }
  5239. const void * dopeek(size32_t sz, size32_t &got) __attribute__((noinline))
  5240. {
  5241. for (;;)
  5242. {
  5243. size32_t left = bufmax-bufpos;
  5244. got = left;
  5245. if (left>=sz)
  5246. return buf+bufpos;
  5247. if (eoinput)
  5248. return left?(buf+bufpos):NULL;
  5249. size32_t reqsz = sz+bufsize; // NB not sz-left as want some slack
  5250. if (ma.length()<reqsz) {
  5251. MemoryAttr ma2;
  5252. void *nb = ma2.allocate(reqsz);
  5253. memcpy(nb,buf+bufpos,left);
  5254. ma.setOwn(reqsz,ma2.detach());
  5255. buf = (byte *)nb;
  5256. }
  5257. else
  5258. memmove(buf,buf+bufpos,left);
  5259. bufbase += bufpos;
  5260. size32_t rd = doread(bufbase+left,bufsize,buf+left);
  5261. if (!rd)
  5262. eoinput = true;
  5263. bufmax = rd+left;
  5264. bufpos = 0;
  5265. }
  5266. }
  5267. void getreadnext(size32_t len, void * ptr) __attribute__((noinline))
  5268. {
  5269. bufbase += bufmax;
  5270. bufpos = 0;
  5271. bufmax = 0;
  5272. size32_t rd = 0;
  5273. if (!eoinput) {
  5274. //If reading >= bufsize, read any complete blocks directly into the target
  5275. if (len>=bufsize) {
  5276. size32_t tord = (len/bufsize)*bufsize;
  5277. rd = doread(bufbase,tord,ptr);
  5278. bufbase += rd;
  5279. if (rd!=tord) {
  5280. eoinput = true;
  5281. PrintStackReport();
  5282. IERRLOG("CFileSerialStream::get read past end of stream.1 (%u,%u) %s",rd,tord,eoinput?"eoinput":"");
  5283. throw MakeStringException(-1,"CFileSerialStream::get read past end of stream");
  5284. }
  5285. len -= rd;
  5286. if (!len)
  5287. return;
  5288. ptr = (byte *)ptr+rd;
  5289. }
  5290. const void *p = dopeek(len,rd);
  5291. if (len<=rd) {
  5292. memcpy(ptr,p,len);
  5293. bufpos += len;
  5294. return;
  5295. }
  5296. }
  5297. PrintStackReport();
  5298. IERRLOG("CFileSerialStream::get read past end of stream.2 (%u,%u) %s",len,rd,eoinput?"eoinput":"");
  5299. throw MakeStringException(-1,"CFileSerialStream::get read past end of stream");
  5300. }
  5301. protected:
  5302. virtual size32_t rawread(offset_t pos, size32_t max_size, void *ptr) = 0;
  5303. public:
  5304. IMPLEMENT_IINTERFACE;
  5305. CSerialStreamBase(offset_t _offset, offset_t _len, size32_t _bufsize, IFileSerialStreamCallback *_tally)
  5306. {
  5307. tally = _tally;
  5308. bufsize = _bufsize;
  5309. if (bufsize==(size32_t)-1)
  5310. bufsize = DEFAULT_STREAM_BUFFER_SIZE;
  5311. if (bufsize<4096)
  5312. bufsize = 4096;
  5313. else
  5314. bufsize = ((bufsize+4095)/4096)*4096;
  5315. buf = (byte *)ma.allocate(bufsize+4096); // 4K initial slack
  5316. bufpos = 0;
  5317. bufmax = 0;
  5318. bufbase = _offset;
  5319. if (_len==(offset_t)-1)
  5320. endpos = (offset_t)-1;
  5321. else
  5322. endpos = _offset+_len;
  5323. eoinput = (_len==0);
  5324. }
  5325. virtual void reset(offset_t _offset, offset_t _len) override
  5326. {
  5327. bufpos = 0;
  5328. bufmax = 0;
  5329. bufbase = _offset;
  5330. if (_len==(offset_t)-1)
  5331. endpos = (offset_t)-1;
  5332. else
  5333. endpos = _offset+_len;
  5334. eoinput = (_len==0);
  5335. }
  5336. virtual const void *peek(size32_t sz,size32_t &got) override
  5337. {
  5338. return dopeek(sz, got);
  5339. }
  5340. virtual void get(size32_t len, void * ptr) override
  5341. {
  5342. size32_t cpy = bufmax-bufpos;
  5343. if (cpy>len)
  5344. cpy = len;
  5345. memcpy(ptr,(const byte *)buf+bufpos,cpy);
  5346. len -= cpy;
  5347. if (len==0) {
  5348. bufpos += cpy;
  5349. return;
  5350. }
  5351. return getreadnext(len, (byte *)ptr+cpy);
  5352. }
  5353. virtual bool eos() override
  5354. {
  5355. if (bufmax-bufpos)
  5356. return false;
  5357. size32_t rd;
  5358. return dopeek(1,rd)==NULL;
  5359. }
  5360. virtual void skip(size32_t len) override
  5361. {
  5362. size32_t left = bufmax-bufpos;
  5363. if (left>=len) {
  5364. bufpos += len;
  5365. return;
  5366. }
  5367. len -= left;
  5368. bufbase += bufmax;
  5369. bufpos = 0;
  5370. bufmax = 0;
  5371. if (!eoinput) {
  5372. while (len>=bufsize) {
  5373. size32_t rd;
  5374. if (tally) {
  5375. rd = doread(bufbase,bufsize,buf);
  5376. if (rd!=bufsize) {
  5377. eoinput = true;
  5378. throw MakeStringException(-1,"CFileSerialStream::skip read past end of stream");
  5379. }
  5380. }
  5381. else {
  5382. rd = (len/bufsize)*bufsize;
  5383. //rd=doskip(bufbase,bufsize,buf); to cope with reading from sockets etc?
  5384. }
  5385. bufbase += rd;
  5386. len -= bufsize;
  5387. }
  5388. if (len==0)
  5389. return;
  5390. size32_t got;
  5391. dopeek(len,got);
  5392. if (len<=got) {
  5393. bufpos += got;
  5394. return;
  5395. }
  5396. }
  5397. throw MakeStringException(-1,"CFileSerialStream::skip read past end of stream");
  5398. }
  5399. virtual offset_t tell() const override
  5400. {
  5401. return bufbase+bufpos;
  5402. }
  5403. };
  5404. class CFileSerialStream: public CSerialStreamBase
  5405. {
  5406. Linked<IFileIO> fileio;
  5407. virtual size32_t rawread(offset_t pos, size32_t max_size, void *ptr)
  5408. {
  5409. return fileio->read(pos,max_size,ptr);
  5410. }
  5411. public:
  5412. CFileSerialStream(IFileIO *_fileio,offset_t _offset, offset_t _len, size32_t _bufsize, IFileSerialStreamCallback *_tally)
  5413. : CSerialStreamBase(_offset, _len, _bufsize, _tally), fileio(_fileio)
  5414. {
  5415. }
  5416. };
  5417. ISerialStream *createFileSerialStream(IFileIO *fileio,offset_t ofs, offset_t flen, size32_t bufsize,IFileSerialStreamCallback *callback)
  5418. {
  5419. if (!fileio)
  5420. return NULL;
  5421. return new CFileSerialStream(fileio,ofs,flen,bufsize,callback);
  5422. }
  5423. class CIoSerialStream: public CSerialStreamBase
  5424. {
  5425. Linked<IFileIOStream> io;
  5426. offset_t lastpos;
  5427. virtual size32_t rawread(offset_t pos, size32_t max_size, void *ptr)
  5428. {
  5429. if (lastpos!=pos)
  5430. throw MakeStringException(-1,"CIoSerialStream: non-sequential read (%" I64F "d,%" I64F "d)",lastpos,pos);
  5431. size32_t rd = io->read(max_size,ptr);
  5432. lastpos = pos+rd;
  5433. return rd;
  5434. }
  5435. public:
  5436. CIoSerialStream(IFileIOStream * _io,offset_t _offset, size32_t _bufsize, IFileSerialStreamCallback *_tally)
  5437. : CSerialStreamBase(_offset, (offset_t)-1, _bufsize, _tally), io(_io)
  5438. {
  5439. lastpos = _offset;
  5440. }
  5441. };
  5442. ISerialStream *createFileSerialStream(IFileIOStream *io,size32_t bufsize,IFileSerialStreamCallback *callback)
  5443. {
  5444. if (!io)
  5445. return NULL;
  5446. return new CIoSerialStream(io,0,bufsize,callback);
  5447. }
  5448. class CSocketSerialStream: public CSerialStreamBase
  5449. {
  5450. Linked<ISocket> socket;
  5451. unsigned timeout;
  5452. offset_t lastpos;
  5453. virtual size32_t rawread(offset_t pos, size32_t max_size, void *ptr)
  5454. {
  5455. if (lastpos!=pos)
  5456. throw MakeStringException(-1,"CSocketSerialStream: non-sequential read (%" I64F "d,%" I64F "d)",lastpos,pos);
  5457. size32_t size_read;
  5458. socket->readtms(ptr, 0, max_size, size_read, timeout);
  5459. lastpos = pos+size_read;
  5460. return size_read;
  5461. }
  5462. public:
  5463. CSocketSerialStream(ISocket * _socket, unsigned _timeout, offset_t _offset, size32_t _bufsize, IFileSerialStreamCallback *_tally)
  5464. : CSerialStreamBase(_offset, (offset_t)-1, _bufsize, _tally), socket(_socket), timeout(_timeout)
  5465. {
  5466. lastpos = _offset;
  5467. }
  5468. };
  5469. ISerialStream *createSocketSerialStream(ISocket * socket, unsigned timeoutms, size32_t bufsize, IFileSerialStreamCallback *callback)
  5470. {
  5471. if (!socket)
  5472. return NULL;
  5473. return new CSocketSerialStream(socket,timeoutms,0,bufsize,callback);
  5474. }
  5475. class CSimpleReadSerialStream: public CSerialStreamBase
  5476. {
  5477. Linked<ISimpleReadStream> input;
  5478. offset_t lastpos;
  5479. virtual size32_t rawread(offset_t pos, size32_t max_size, void *ptr)
  5480. {
  5481. if (lastpos!=pos)
  5482. throw MakeStringException(-1,"CSimpleReadSerialStream: non-sequential read (%" I64F "d,%" I64F "d)",lastpos,pos);
  5483. size32_t rd = input->read(max_size, ptr);
  5484. lastpos += rd;
  5485. return rd;
  5486. }
  5487. public:
  5488. CSimpleReadSerialStream(ISimpleReadStream * _input, offset_t _offset, size32_t _bufsize, IFileSerialStreamCallback *_tally)
  5489. : CSerialStreamBase(_offset, (offset_t)-1, _bufsize, _tally), input(_input)
  5490. {
  5491. lastpos = _offset;
  5492. }
  5493. void reset(offset_t _ofs, offset_t _len)
  5494. {
  5495. // assume knows what doing
  5496. lastpos = _ofs;
  5497. CSerialStreamBase::reset(_ofs,_len);
  5498. }
  5499. };
  5500. ISerialStream *createSimpleSerialStream(ISimpleReadStream * input, size32_t bufsize, IFileSerialStreamCallback *callback)
  5501. {
  5502. if (!input)
  5503. return NULL;
  5504. return new CSimpleReadSerialStream(input,0,bufsize,callback);
  5505. }
  5506. class CMemoryMappedSerialStream: implements ISerialStream, public CInterface
  5507. {
  5508. Linked<IMemoryMappedFile> mmfile;
  5509. const byte *mmbase;
  5510. memsize_t mmsize;
  5511. memsize_t mmofs;
  5512. bool eoinput;
  5513. IFileSerialStreamCallback *tally;
  5514. public:
  5515. IMPLEMENT_IINTERFACE;
  5516. CMemoryMappedSerialStream(IMemoryMappedFile *_mmfile, offset_t ofs, offset_t flen, IFileSerialStreamCallback *_tally)
  5517. : mmfile(_mmfile)
  5518. {
  5519. tally = _tally;
  5520. offset_t fs = mmfile->fileSize();
  5521. if ((memsize_t)fs!=fs)
  5522. throw MakeStringException(-1,"CMemoryMappedSerialStream file too big to be mapped");
  5523. if ((flen!=(offset_t)-1)&&(fs>flen))
  5524. fs = flen;
  5525. mmsize = (memsize_t)fs;
  5526. mmofs = (memsize_t)((ofs<fs)?ofs:fs);
  5527. mmbase = (const byte *)mmfile->base();
  5528. eoinput = false;
  5529. }
  5530. virtual void reset(offset_t _ofs, offset_t _len) override
  5531. {
  5532. offset_t fs = mmfile->fileSize();
  5533. if ((_len!=(offset_t)-1)&&(fs>_len))
  5534. fs = _len;
  5535. mmsize = (memsize_t)fs;
  5536. mmofs = (memsize_t)((_ofs<fs)?_ofs:fs);
  5537. mmsize = (memsize_t)fs;
  5538. eoinput = false;
  5539. }
  5540. CMemoryMappedSerialStream(const void *buf, memsize_t len, IFileSerialStreamCallback *_tally)
  5541. {
  5542. tally = _tally;
  5543. mmsize = len;
  5544. mmofs = 0;
  5545. mmbase = (const byte *)buf;
  5546. eoinput = false;
  5547. }
  5548. virtual const void *peek(size32_t sz,size32_t &got) override
  5549. {
  5550. memsize_t left = mmsize-mmofs;
  5551. if (sz>left)
  5552. sz = (size32_t)left;
  5553. else if (left>=UINT_MAX)
  5554. got = UINT_MAX-1;
  5555. else
  5556. got = (size32_t)left;
  5557. return mmbase+mmofs;
  5558. }
  5559. virtual void get(size32_t len, void * ptr) override
  5560. {
  5561. memsize_t left = mmsize-mmofs;
  5562. if (len>left) {
  5563. PrintStackReport();
  5564. IERRLOG("CFileSerialStream::get read past end of stream.3 (%u,%u)",(unsigned)len,(unsigned)left);
  5565. throw MakeStringException(-1,"CMemoryMappedSerialStream::get read past end of stream (%u,%u)",(unsigned)len,(unsigned)left);
  5566. }
  5567. if (tally)
  5568. tally->process(mmofs,len,mmbase+mmofs);
  5569. memcpy(ptr,mmbase+mmofs,len);
  5570. mmofs += len;
  5571. }
  5572. virtual bool eos() override
  5573. {
  5574. return (mmsize<=mmofs);
  5575. }
  5576. virtual void skip(size32_t len) override
  5577. {
  5578. memsize_t left = mmsize-mmofs;
  5579. if (len>left)
  5580. throw MakeStringException(-1,"CMemoryMappedSerialStream::skip read past end of stream (%u,%u)",(unsigned)len,(unsigned)left);
  5581. if (tally)
  5582. tally->process(mmofs,len,mmbase+mmofs);
  5583. mmofs += len;
  5584. }
  5585. virtual offset_t tell() const override
  5586. {
  5587. return mmofs;
  5588. }
  5589. };
  5590. ISerialStream *createFileSerialStream(IMemoryMappedFile *mmfile, offset_t ofs, offset_t flen, IFileSerialStreamCallback *callback)
  5591. {
  5592. return new CMemoryMappedSerialStream(mmfile,ofs,flen,callback);
  5593. }
  5594. ISerialStream *createMemorySerialStream(const void *buffer, memsize_t len, IFileSerialStreamCallback *callback)
  5595. {
  5596. return new CMemoryMappedSerialStream(buffer,len,callback);
  5597. }
  5598. class CMemoryBufferSerialStream: implements ISerialStream, public CInterface
  5599. {
  5600. MemoryBuffer & buffer;
  5601. IFileSerialStreamCallback *tally;
  5602. public:
  5603. IMPLEMENT_IINTERFACE;
  5604. CMemoryBufferSerialStream(MemoryBuffer & _buffer, IFileSerialStreamCallback * _tally)
  5605. : buffer(_buffer), tally(_tally)
  5606. {
  5607. }
  5608. virtual const void *peek(size32_t sz,size32_t &got) override
  5609. {
  5610. got = buffer.remaining();
  5611. return buffer.readDirect(0);
  5612. }
  5613. virtual void get(size32_t len, void * ptr) override
  5614. {
  5615. if (len>buffer.remaining()) {
  5616. IERRLOG("CMemoryBufferSerialStream::get read past end of stream.4(%u,%u)",(unsigned)len,(unsigned)buffer.remaining());
  5617. throw MakeStringException(-1,"CMemoryBufferSerialStream::get read past end of stream (%u,%u)",(unsigned)len,(unsigned)buffer.remaining());
  5618. }
  5619. const void * data = buffer.readDirect(len);
  5620. if (tally)
  5621. tally->process(buffer.getPos()-len,len,data);
  5622. memcpy(ptr,data,len);
  5623. }
  5624. virtual bool eos() override
  5625. {
  5626. return buffer.remaining() == 0;
  5627. }
  5628. virtual void skip(size32_t len) override
  5629. {
  5630. if (len>buffer.remaining())
  5631. throw MakeStringException(-1,"CMemoryBufferSerialStream::skip read past end of stream (%u,%u)",(unsigned)len,(unsigned)buffer.remaining());
  5632. const void * data = buffer.readDirect(len);
  5633. if (tally)
  5634. tally->process(buffer.getPos()-len,len,data);
  5635. }
  5636. virtual offset_t tell() const override
  5637. {
  5638. return buffer.getPos();
  5639. }
  5640. virtual void reset(offset_t _offset,offset_t _len) override
  5641. {
  5642. size32_t ofs = (size32_t)_offset;
  5643. assertex(ofs==_offset);
  5644. assertex((_len==(offset_t)-1)||(_len>=buffer.length())); // don't support len on memory buffer
  5645. buffer.reset(ofs);
  5646. }
  5647. };
  5648. ISerialStream *createMemoryBufferSerialStream(MemoryBuffer & buffer, IFileSerialStreamCallback *callback)
  5649. {
  5650. return new CMemoryBufferSerialStream(buffer,callback);
  5651. }
  5652. // Memory Mapped Files
  5653. #define MEMORYMAP_PAGESIZE (0x1000) // could be different but won't ever be!
  5654. class CMemoryMappedFile: implements IMemoryMappedFile, public CInterface
  5655. {
  5656. byte *ptr; // base
  5657. offset_t ofs;
  5658. offset_t realofs; // rounded down to page size
  5659. offset_t filesize;
  5660. memsize_t size;
  5661. bool writeaccess;
  5662. memsize_t windowsize;
  5663. HANDLE hfile;
  5664. #ifdef _WIN32
  5665. static size32_t pagesize;
  5666. HANDLE hmap;
  5667. #endif
  5668. Linked<IFile> file;
  5669. inline offset_t pageround(offset_t o)
  5670. {
  5671. #ifdef _WIN32
  5672. return o-(o%pagesize);
  5673. #else
  5674. return o-(o%MEMORYMAP_PAGESIZE);
  5675. #endif
  5676. }
  5677. inline void * realptr()
  5678. {
  5679. return ptr?(ptr-(ofs-realofs)):NULL;
  5680. }
  5681. inline memsize_t realsize()
  5682. {
  5683. return (memsize_t)(size+(ofs-realofs));
  5684. }
  5685. public:
  5686. IMPLEMENT_IINTERFACE;
  5687. CMemoryMappedFile(HANDLE _hfile, offset_t _filesize, offset_t _ofs, memsize_t _size, bool _writeaccess)
  5688. {
  5689. hfile = _hfile;
  5690. #ifdef _WIN32
  5691. if (pagesize==0) {
  5692. SYSTEM_INFO sysinfo;
  5693. GetSystemInfo(&sysinfo);
  5694. pagesize = sysinfo.dwAllocationGranularity;
  5695. }
  5696. hmap = NULLFILE;
  5697. #endif
  5698. ptr = NULL;
  5699. filesize = _filesize;
  5700. windowsize = _size; // first open size assumed to be window size
  5701. reinit(_ofs, _size, _writeaccess);
  5702. }
  5703. ~CMemoryMappedFile()
  5704. {
  5705. #ifdef _WIN32
  5706. if (hmap!=NULLFILE)
  5707. CloseHandle(hmap);
  5708. CloseHandle(hfile);
  5709. #else
  5710. close(hfile);
  5711. #endif
  5712. #if defined(__linux__)
  5713. if (ptr)
  5714. {
  5715. munmap(realptr(),realsize());
  5716. ptr = NULL;
  5717. }
  5718. #endif
  5719. }
  5720. byte *base() { return ptr; }
  5721. offset_t offset() { return ofs; }
  5722. virtual memsize_t length() { return size; }
  5723. virtual offset_t fileSize() { return filesize; }
  5724. virtual int compareWithin(const void *p)
  5725. {
  5726. if (p<ptr)
  5727. return -1;
  5728. if (p>=size+ptr)
  5729. return 1;
  5730. return 0;
  5731. }
  5732. bool writeAccess() { return writeaccess; }
  5733. void flush()
  5734. {
  5735. if (ptr) {
  5736. #ifdef _WIN32
  5737. FlushViewOfFile(realptr(),0);
  5738. #elif defined(__linux__)
  5739. msync(realptr(),realsize(),MS_SYNC);
  5740. #else
  5741. UNIMPLEMENTED;
  5742. #endif
  5743. }
  5744. }
  5745. byte *nextPtr(const void *p,offset_t skip, memsize_t req, memsize_t &got)
  5746. {
  5747. // for scanning in sequence
  5748. if (p==NULL)
  5749. p = ptr;
  5750. else if ((p<ptr)||(p>ptr+size))
  5751. throw MakeStringException(-1,"CMemoryMappedFile::nextPtr - outside map");
  5752. memsize_t d = (byte *)p-ptr;
  5753. offset_t o = ofs+d+skip;
  5754. if (o>=filesize) {
  5755. got = 0;
  5756. return NULL;
  5757. }
  5758. offset_t left = filesize-o;
  5759. if (left<req)
  5760. req = (memsize_t)left;
  5761. if (o+req-ofs>size) {
  5762. reinit(o,windowsize,writeaccess);
  5763. assertex(o==ofs);
  5764. got = windowsize;
  5765. if (left<got)
  5766. got = (memsize_t)left;
  5767. return ptr;
  5768. }
  5769. got = (memsize_t)(size+o-ofs);
  5770. if (left<got)
  5771. got = (memsize_t)left;
  5772. return (byte *)p+skip;
  5773. }
  5774. virtual void reinit(offset_t _ofs, memsize_t _size, bool _writeaccess)
  5775. {
  5776. writeaccess = _writeaccess;
  5777. if (ptr) {
  5778. #ifdef _WIN32
  5779. // no need to unmap view
  5780. if (hmap != INVALID_HANDLE_VALUE) {
  5781. CloseHandle(hmap);
  5782. hmap = INVALID_HANDLE_VALUE;
  5783. }
  5784. #elif defined(__linux__)
  5785. munmap(realptr(),realsize());
  5786. // error checking TBD
  5787. #else
  5788. UNIMPLEMENTED;
  5789. #endif
  5790. ptr = NULL;
  5791. }
  5792. if (_ofs>filesize)
  5793. ofs = filesize;
  5794. else
  5795. ofs = _ofs;
  5796. realofs = pageround(ofs);
  5797. if (_size==(memsize_t)-1) {
  5798. size = (memsize_t)(filesize-_ofs);
  5799. if (size!=(filesize-_ofs))
  5800. throw MakeStringException(-1,"CMemoryMappedFile::reinit file too big");
  5801. }
  5802. else
  5803. size = _size;
  5804. memsize_t mapsz = realsize();
  5805. if (filesize-realofs<mapsz)
  5806. mapsz = (memsize_t)(filesize-realofs);
  5807. #ifdef _WIN32
  5808. LARGE_INTEGER li;
  5809. if (hmap == INVALID_HANDLE_VALUE) {
  5810. hmap = CreateFileMapping(hfile,NULL,writeaccess?PAGE_READWRITE:PAGE_READONLY,0, 0, NULL);
  5811. if (!hmap) {
  5812. DWORD err = GetLastError();
  5813. throw makeOsException(err,"CMemoryMappedFile::reinit");
  5814. }
  5815. }
  5816. li.QuadPart = realofs;
  5817. ptr = (byte *) MapViewOfFile(hmap, writeaccess?(FILE_MAP_READ|FILE_MAP_WRITE):FILE_MAP_READ, li.HighPart, li.LowPart, mapsz);
  5818. if (!ptr) {
  5819. DWORD err = GetLastError();
  5820. throw makeOsException(err,"CMemoryMappedFile::reinit");
  5821. }
  5822. #elif defined (__linux__)
  5823. ptr = (byte *) mmap(NULL, mapsz, writeaccess?(PROT_READ|PROT_WRITE):PROT_READ, MAP_SHARED|MAP_NORESERVE, hfile, realofs);
  5824. if (ptr == MAP_FAILED)
  5825. throw makeOsException(errno, "CMemoryMappedFile::reinit");
  5826. #else
  5827. UNIMPLEMENTED;
  5828. #endif
  5829. if (ptr)
  5830. ptr += (ofs-realofs);
  5831. }
  5832. };
  5833. #ifdef _WIN32
  5834. size32_t CMemoryMappedFile::pagesize=0;
  5835. #endif
  5836. // TBD MADV_SEQUENTIAL & MADV_WILLNEED?
  5837. IMemoryMappedFile *CFile::openMemoryMapped(offset_t ofs, memsize_t len, bool write)
  5838. {
  5839. HANDLE hfile = openHandle(write?IFOcreaterw:IFOread, IFSHread, false);
  5840. if (hfile == NULLFILE)
  5841. return NULL;
  5842. return new CMemoryMappedFile(hfile,size(),ofs,len,write);
  5843. }
  5844. bool isSpecialPath(const char *path)
  5845. {
  5846. // used for remote queries
  5847. if (!path)
  5848. return false;
  5849. if (isPathSepChar(path[0])&&(path[0]==path[1])) {
  5850. path += 2;
  5851. for (;;) {
  5852. if (*path=='/')
  5853. return (path[1]=='>');
  5854. if (!*path||(*path=='\\'))
  5855. return false;
  5856. path++;
  5857. }
  5858. }
  5859. return (path&&(*path=='/')&&(path[1]=='>'));
  5860. }
  5861. size32_t SendFile(ISocket *target, IFileIO *fileio,offset_t start,size32_t len)
  5862. {
  5863. assertex(target);
  5864. assertex(fileio);
  5865. offset_t fsz = fileio->size();
  5866. if (start>=fsz)
  5867. return 0;
  5868. if (start+len>fsz)
  5869. len = (size32_t)(fsz-start);
  5870. if (!len)
  5871. return 0;
  5872. CFileIO *cfile = QUERYINTERFACE(fileio,CFileIO);
  5873. if (cfile) {
  5874. HANDLE fh = cfile->queryHandle();
  5875. if ((fh!=(HANDLE)0)&&(fh!=(HANDLE)-1)) {
  5876. unsigned sh = target->OShandle();
  5877. if ((sh!=(unsigned)0)&&(sh!=(unsigned)-1)) {
  5878. #ifdef _WIN32
  5879. // MORE - should there be something here?
  5880. #elif defined(__linux__)
  5881. // TransmitFile not in std DLLs so don't bother with
  5882. off_t ofs = start;
  5883. ssize_t sent = ::sendfile(sh,fh,&ofs,len);
  5884. if (sent!=(ssize_t)-1)
  5885. return (size32_t)sent;
  5886. int err = errno;
  5887. if ((err!=EINVAL)&&(err!=ENOSYS))
  5888. throw makeOsException(err, "sendfile");
  5889. #else
  5890. UNIMPLEMENTED;
  5891. #endif
  5892. }
  5893. }
  5894. }
  5895. #ifdef _DEBUG
  5896. #ifndef _WIN32
  5897. IWARNLOG("SendFile falling back");
  5898. #endif
  5899. #endif
  5900. // fallback
  5901. MemoryAttr ma;
  5902. void *buf = ma.allocate(len);
  5903. size32_t rd = fileio->read(start,len,buf);
  5904. target->write(buf,rd);
  5905. return rd;
  5906. }
  5907. void asyncClose(IFileIO *io)
  5908. {
  5909. if (!io)
  5910. return;
  5911. static CriticalSection ADsect;
  5912. CriticalBlock block(ADsect);
  5913. static Owned<IWorkQueueThread> adwp = createWorkQueueThread();
  5914. class cWQI: public CInterface,implements IWorkQueueItem
  5915. {
  5916. Owned<IFileIO> io;
  5917. public:
  5918. IMPLEMENT_IINTERFACE;
  5919. cWQI(IFileIO *_io)
  5920. : io(_io)
  5921. {
  5922. }
  5923. void execute()
  5924. {
  5925. io.clear();
  5926. }
  5927. };
  5928. adwp->post(new cWQI(io));
  5929. };
  5930. int stdIoHandle(const char *path)
  5931. {
  5932. if (strcmp(path,"stdin:")==0)
  5933. return 0;
  5934. if (strcmp(path,"stdout:")==0)
  5935. return 1;
  5936. if (strcmp(path,"stderr:")==0)
  5937. return 2;
  5938. return -1;
  5939. }
  5940. extern jlib_decl bool containsFileWildcard(const char * path)
  5941. {
  5942. if (!path)
  5943. return false;
  5944. return strchr(path, '*') || strchr(path, '?');
  5945. }
  5946. extern jlib_decl bool isDirectory(const char * path)
  5947. {
  5948. Owned<IFile> file = createIFile(path);
  5949. return file->isDirectory()==fileBool::foundYes;
  5950. }
  5951. // IFileIOCache
  5952. class CLazyFileIOCache;
  5953. class CCachedFileIO: implements IFileIO, public CInterface
  5954. {
  5955. CLazyFileIOCache &owner;
  5956. RemoteFilename filename;
  5957. CriticalSection &sect;
  5958. CRuntimeStatisticCollection fileStats;
  5959. IFOmode mode;
  5960. void writeNotSupported(const char *s)
  5961. {
  5962. StringBuffer tmp;
  5963. filename.getRemotePath(tmp);
  5964. throw MakeStringException(-1, "CCachedFileIO(%s) %s not supported", tmp.str(), s);
  5965. }
  5966. public:
  5967. unsigned accesst;
  5968. Owned<IFileIO> cachedio;
  5969. CCachedFileIO(CLazyFileIOCache &_owner, CriticalSection &_sect, RemoteFilename &_filename, IFOmode _mode)
  5970. : owner(_owner), sect(_sect), fileStats(diskLocalStatistics)
  5971. {
  5972. filename.set(_filename);
  5973. mode = _mode;
  5974. accesst = 0;
  5975. }
  5976. virtual void Link(void) const { CInterface::Link(); } \
  5977. virtual bool Release(void) const;
  5978. unsigned __int64 getStatistic(StatisticKind kind)
  5979. {
  5980. CriticalBlock block(sect);
  5981. unsigned __int64 openValue = cachedio ? cachedio->getStatistic(kind) : 0;
  5982. return openValue + fileStats.getStatisticValue(kind);
  5983. }
  5984. IFileIO *open();
  5985. size32_t read(offset_t pos, size32_t len, void * data)
  5986. {
  5987. CriticalBlock block(sect);
  5988. Owned<IFileIO> io = open();
  5989. return io->read(pos,len,data);
  5990. }
  5991. offset_t size()
  5992. {
  5993. CriticalBlock block(sect);
  5994. Owned<IFileIO> io = open();
  5995. return io->size();
  5996. }
  5997. size32_t write(offset_t pos, size32_t len, const void * data)
  5998. {
  5999. CriticalBlock block(sect);
  6000. Owned<IFileIO> io = open();
  6001. return io->write(pos,len,data);
  6002. }
  6003. virtual void flush()
  6004. {
  6005. CriticalBlock block(sect);
  6006. if (cachedio)
  6007. cachedio->flush();
  6008. }
  6009. virtual void close()
  6010. {
  6011. CriticalBlock block(sect);
  6012. if (cachedio)
  6013. forceClose();
  6014. }
  6015. offset_t appendFile(IFile *file,offset_t pos,offset_t len)
  6016. {
  6017. CriticalBlock block(sect);
  6018. Owned<IFileIO> io = open();
  6019. return io->appendFile(file,pos,len);
  6020. }
  6021. void setSize(offset_t size)
  6022. {
  6023. CriticalBlock block(sect);
  6024. Owned<IFileIO> io = open();
  6025. io->setSize(size);
  6026. }
  6027. void forceClose()
  6028. {
  6029. cachedio->close();
  6030. mergeStats(fileStats, cachedio);
  6031. cachedio.clear();
  6032. }
  6033. };
  6034. class CLazyFileIOCache: implements IFileIOCache, public CInterface
  6035. {
  6036. CriticalSection sect;
  6037. unsigned max;
  6038. IPointerArrayOf<CCachedFileIO> cache;
  6039. public:
  6040. IMPLEMENT_IINTERFACE;
  6041. CLazyFileIOCache(unsigned _max)
  6042. {
  6043. max = _max;
  6044. }
  6045. CCachedFileIO *addFile( RemoteFilename &filename, IFOmode mode )
  6046. {
  6047. // check exists
  6048. unsigned i = cache.ordinality();
  6049. ForEachItemIn(i2,cache) {
  6050. if (!cache.item(i2)) {
  6051. i = i2;
  6052. break;
  6053. }
  6054. }
  6055. Linked<CCachedFileIO> ret = new CCachedFileIO(*this,sect,filename,mode);
  6056. if (i<cache.ordinality())
  6057. cache.replace(ret,i);
  6058. else
  6059. cache.append(ret);
  6060. return ret.getClear();
  6061. }
  6062. void checkCache(unsigned wanted=1)
  6063. {
  6064. // called in sect
  6065. for (;;) {
  6066. CCachedFileIO *oldest = NULL;
  6067. unsigned oldestt = 0;
  6068. unsigned t = msTick();
  6069. unsigned n = wanted;
  6070. ForEachItemIn(i1,cache) {
  6071. CCachedFileIO *cio = cache.item(i1);
  6072. if (cio&&cio->cachedio.get()) {
  6073. if (t-cio->accesst>=oldestt) {
  6074. oldest = cio;
  6075. oldestt = t-cio->accesst;
  6076. }
  6077. n++;
  6078. }
  6079. }
  6080. if (n<max)
  6081. break;
  6082. if (!oldest)
  6083. break;
  6084. oldest->forceClose();
  6085. //If previously had max ios then we now have space.
  6086. if (n == max)
  6087. break;
  6088. }
  6089. }
  6090. const CCachedFileIO *removeFile(const CCachedFileIO *io)
  6091. {
  6092. CriticalBlock block(sect);
  6093. ForEachItemIn(idx, cache)
  6094. {
  6095. if (io == cache.item(idx))
  6096. {
  6097. cache.replace(NULL, idx, true);
  6098. break;
  6099. }
  6100. }
  6101. return io;
  6102. }
  6103. };
  6104. bool CCachedFileIO::Release(void) const
  6105. {
  6106. if (CInterface::Release())
  6107. return true;
  6108. if (!CInterface::IsShared())
  6109. return owner.removeFile(this)->Release();
  6110. return false;
  6111. }
  6112. IFileIO *CCachedFileIO::open()
  6113. {
  6114. // called in sect
  6115. if (!cachedio) {
  6116. owner.checkCache();
  6117. Owned<IFile> inFile = createIFile(filename);
  6118. cachedio.setown(inFile->open(mode));
  6119. if (!cachedio.get()) {
  6120. StringBuffer tmp;
  6121. filename.getRemotePath(tmp);
  6122. throw MakeStringException(-1, "CCachedFileIO::open(%d) '%s' failed", (int)mode, tmp.str());
  6123. }
  6124. }
  6125. accesst = msTick();
  6126. return cachedio.getLink();
  6127. }
  6128. IFileIOCache* createFileIOCache(unsigned max)
  6129. {
  6130. return new CLazyFileIOCache(max);
  6131. }
  6132. extern jlib_decl IFile * createSentinelTarget()
  6133. {
  6134. const char * sentinelFilename = getenv("SENTINEL");
  6135. if (sentinelFilename)
  6136. return createIFile(sentinelFilename);
  6137. else
  6138. return NULL;
  6139. }
  6140. extern jlib_decl void removeSentinelFile(IFile * sentinelFile)
  6141. {
  6142. if (sentinelFile)
  6143. {
  6144. if(sentinelFile->exists() && sentinelFile->isDirectory()!=fileBool::foundYes)
  6145. {
  6146. DBGLOG("Removing sentinel file %s", sentinelFile->queryFilename());
  6147. try
  6148. {
  6149. sentinelFile->remove();
  6150. }
  6151. catch(IException *E)
  6152. {
  6153. StringBuffer s;
  6154. EXCLOG(E, s.appendf("Failed to remove sentinel file %s", sentinelFile->queryFilename()).str());
  6155. E->Release();
  6156. throw makeOsException(errno, "removeSentinelFile - file cannot be removed.");
  6157. }
  6158. }
  6159. }
  6160. }
  6161. extern jlib_decl void writeSentinelFile(IFile * sentinelFile)
  6162. {
  6163. if ( sentinelFile )
  6164. {
  6165. DBGLOG("Creating sentinel file %s for rerun from script", sentinelFile->queryFilename());
  6166. try
  6167. {
  6168. Owned<IFileIO> sentinel = sentinelFile->open(IFOcreate);
  6169. sentinel->write(0, 5, "rerun");
  6170. }
  6171. catch(IException *E)
  6172. {
  6173. StringBuffer s;
  6174. EXCLOG(E, s.appendf("Failed to create sentinel file %s for rerun from script", sentinelFile->queryFilename()).str());
  6175. E->Release();
  6176. throw makeOsException(errno, "writeSentinelFile - file not created.");
  6177. }
  6178. }
  6179. }
  6180. jlib_decl StringBuffer & appendCurrentDirectory(StringBuffer & target, bool blankIfFails)
  6181. {
  6182. char temp[_MAX_PATH+1];
  6183. if (!getcwd(temp,sizeof(temp)))
  6184. {
  6185. if (blankIfFails)
  6186. return target;
  6187. throw MakeStringException(JLIBERR_InternalError, "getcwd failed (%d)", errno);
  6188. }
  6189. return target.append(temp);
  6190. }
  6191. void removeFileTraceIfFail(const char * filename)
  6192. {
  6193. if (remove(filename) != 0)
  6194. DBGLOG("Could not remove file '%s'", filename);
  6195. }
  6196. timestamp_type getTimeStamp(IFile * file)
  6197. {
  6198. CDateTime modified;
  6199. file->getTime(nullptr, &modified, nullptr);
  6200. return modified.getTimeStamp();
  6201. }
  6202. class CSortedDirectoryIterator : public CSimpleInterfaceOf<IDirectoryIterator>
  6203. {
  6204. CIArrayOf<CDirectoryEntry> sortedFiles;
  6205. CDirectoryEntry *curDirectoryEntry = nullptr;
  6206. unsigned sortedFileCount = 0;
  6207. unsigned sortedFileIndex = 0;
  6208. Owned<IFile> cur;
  6209. bool curIsDir = false;
  6210. public:
  6211. CSortedDirectoryIterator(IDirectoryIterator &itr, SortDirectoryMode mode, bool rev, bool includedirs)
  6212. {
  6213. sortDirectory(sortedFiles, itr, mode, rev, includedirs);
  6214. sortedFileCount = sortedFiles.length();
  6215. }
  6216. //IIteratorOf
  6217. virtual bool first() override
  6218. {
  6219. sortedFileIndex = 0;
  6220. return next();
  6221. }
  6222. virtual bool next() override
  6223. {
  6224. if (sortedFileIndex >= sortedFileCount)
  6225. {
  6226. cur.clear();
  6227. curDirectoryEntry = nullptr;
  6228. return false;
  6229. }
  6230. curDirectoryEntry = &sortedFiles.item(sortedFileIndex);
  6231. cur.setown(createIFile(curDirectoryEntry->file->queryFilename()));
  6232. curIsDir = curDirectoryEntry->isdir;
  6233. sortedFileIndex++;
  6234. return true;
  6235. }
  6236. virtual bool isValid() override { return cur != nullptr; }
  6237. virtual IFile &query() override { return *cur; }
  6238. //IDirectoryIterator
  6239. virtual bool isDir() override { return curIsDir; }
  6240. virtual StringBuffer &getName(StringBuffer &buf) override
  6241. {
  6242. if (curDirectoryEntry)
  6243. return buf.set(curDirectoryEntry->name.get());
  6244. return buf;
  6245. }
  6246. virtual __int64 getFileSize() override
  6247. {
  6248. return curDirectoryEntry ? curDirectoryEntry->size : -1;
  6249. }
  6250. virtual bool getModifiedTime(CDateTime &ret) override
  6251. {
  6252. if (!curDirectoryEntry)
  6253. return false;
  6254. ret = curDirectoryEntry->modifiedTime;
  6255. return true;
  6256. }
  6257. };
  6258. IDirectoryIterator *getSortedDirectoryIterator(IFile *directory, SortDirectoryMode mode, bool rev, const char *mask, bool sub, bool includedirs)
  6259. {
  6260. if (!directory || directory->isDirectory()!=fileBool::foundYes)
  6261. throw MakeStringException(-1, "Invalid IFile input in getSortedDirectoryIterator()");
  6262. Owned<IDirectoryIterator> files = directory->directoryFiles(mask, sub, includedirs);
  6263. if (SD_nosort == mode)
  6264. return files;
  6265. return new CSortedDirectoryIterator(*files, mode, rev, includedirs);
  6266. }
  6267. IDirectoryIterator *getSortedDirectoryIterator(const char *dirName, SortDirectoryMode mode, bool rev, const char *mask, bool sub, bool includedirs)
  6268. {
  6269. if (isEmptyString(dirName))
  6270. throw MakeStringException(-1, "Invalid dirName input in getSortedDirectoryIterator()");
  6271. Owned<IFile> dir = createIFile(dirName);
  6272. return getSortedDirectoryIterator(dir, mode, rev, mask, sub, includedirs);
  6273. }
  6274. //--------------------------------------------------------------------------------------------------------------------
  6275. unsigned __int64 FileIOStats::getStatistic(StatisticKind kind)
  6276. {
  6277. switch (kind)
  6278. {
  6279. case StCycleDiskReadIOCycles:
  6280. return ioReadCycles.load();
  6281. case StCycleDiskWriteIOCycles:
  6282. return ioWriteCycles.load();
  6283. case StTimeDiskReadIO:
  6284. return cycle_to_nanosec(ioReadCycles.load());
  6285. case StTimeDiskWriteIO:
  6286. return cycle_to_nanosec(ioWriteCycles.load());
  6287. case StSizeDiskRead:
  6288. return ioReadBytes.load();
  6289. case StSizeDiskWrite:
  6290. return ioWriteBytes.load();
  6291. case StNumDiskReads:
  6292. return ioReads.load();
  6293. case StNumDiskWrites:
  6294. return ioWrites.load();
  6295. }
  6296. return 0;
  6297. }
  6298. void FileIOStats::trace()
  6299. {
  6300. if (ioReads)
  6301. printf("Reads: %u Bytes: %u TimeMs: %u\n", (unsigned)ioReads, (unsigned)ioReadBytes, (unsigned)cycle_to_millisec(ioReadCycles));
  6302. if (ioWrites)
  6303. printf("Writes: %u Bytes: %u TimeMs: %u\n", (unsigned)ioWrites, (unsigned)ioWriteBytes, (unsigned)cycle_to_millisec(ioWriteCycles));
  6304. }
  6305. //--------------------------------------------------------------------------------------------------------------------
  6306. static constexpr FileSystemProperties linuxFileSystemProperties {true, true, true, true, 0x10000}; // 64K
  6307. static constexpr FileSystemProperties defaultUrlFileSystemProperties{false, false, false, false, 0x400000}; // 4Mb
  6308. //This implementation should eventually make use of the file hook.
  6309. const FileSystemProperties & queryFileSystemProperties(const char * filename)
  6310. {
  6311. if (isUrl(filename))
  6312. return defaultUrlFileSystemProperties;
  6313. else
  6314. return linuxFileSystemProperties;
  6315. }