jfile.cpp 172 KB

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