jfile.cpp 169 KB

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