jfile.cpp 181 KB

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