jfile.cpp 170 KB

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