jfile.cpp 178 KB

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