jfile.cpp 178 KB

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