jfile.cpp 186 KB

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