Terminal.cpp 292 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151
  1. //---------------------------------------------------------------------------
  2. #include <vcl.h>
  3. #pragma hdrstop
  4. #include "Terminal.h"
  5. #include <SysUtils.hpp>
  6. #include <FileCtrl.hpp>
  7. #include <StrUtils.hpp>
  8. #include <System.IOUtils.hpp>
  9. #include "Common.h"
  10. #include "PuttyTools.h"
  11. #include "FileBuffer.h"
  12. #include "Interface.h"
  13. #include "RemoteFiles.h"
  14. #include "SecureShell.h"
  15. #include "ScpFileSystem.h"
  16. #include "SftpFileSystem.h"
  17. #include "FtpFileSystem.h"
  18. #include "WebDAVFileSystem.h"
  19. #include "S3FileSystem.h"
  20. #include "TextsCore.h"
  21. #include "HelpCore.h"
  22. #include "CoreMain.h"
  23. #include "Queue.h"
  24. #include "Cryptography.h"
  25. #include "NeonIntf.h"
  26. #include <PuttyTools.h>
  27. #include <openssl/pkcs12.h>
  28. #include <openssl/err.h>
  29. #include <algorithm>
  30. #ifndef AUTO_WINSOCK
  31. #include <winsock2.h>
  32. #endif
  33. //---------------------------------------------------------------------------
  34. #pragma package(smart_init)
  35. //---------------------------------------------------------------------------
  36. #define FILE_OPERATION_LOOP_TERMINAL this
  37. //---------------------------------------------------------------------------
  38. //---------------------------------------------------------------------------
  39. class TLoopDetector
  40. {
  41. public:
  42. __fastcall TLoopDetector();
  43. void __fastcall RecordVisitedDirectory(const UnicodeString & Directory);
  44. bool __fastcall IsUnvisitedDirectory(const UnicodeString & Directory);
  45. private:
  46. std::unique_ptr<TStringList> FVisitedDirectories;
  47. };
  48. //---------------------------------------------------------------------------
  49. __fastcall TLoopDetector::TLoopDetector()
  50. {
  51. FVisitedDirectories.reset(CreateSortedStringList());
  52. }
  53. //---------------------------------------------------------------------------
  54. void __fastcall TLoopDetector::RecordVisitedDirectory(const UnicodeString & Directory)
  55. {
  56. UnicodeString VisitedDirectory = ExcludeTrailingBackslash(Directory);
  57. FVisitedDirectories->Add(VisitedDirectory);
  58. }
  59. //---------------------------------------------------------------------------
  60. bool __fastcall TLoopDetector::IsUnvisitedDirectory(const UnicodeString & Directory)
  61. {
  62. bool Result = (FVisitedDirectories->IndexOf(Directory) < 0);
  63. if (Result)
  64. {
  65. RecordVisitedDirectory(Directory);
  66. }
  67. return Result;
  68. }
  69. //---------------------------------------------------------------------------
  70. //---------------------------------------------------------------------------
  71. struct TMoveFileParams
  72. {
  73. UnicodeString Target;
  74. UnicodeString FileMask;
  75. bool DontOverwrite;
  76. };
  77. //---------------------------------------------------------------------------
  78. struct TFilesFindParams
  79. {
  80. TFileMasks FileMask;
  81. TFileFoundEvent OnFileFound;
  82. TFindingFileEvent OnFindingFile;
  83. bool Cancel;
  84. TLoopDetector LoopDetector;
  85. UnicodeString RealDirectory;
  86. };
  87. //---------------------------------------------------------------------------
  88. TCalculateSizeStats::TCalculateSizeStats()
  89. {
  90. memset(this, 0, sizeof(*this));
  91. }
  92. //---------------------------------------------------------------------------
  93. TCalculateSizeParams::TCalculateSizeParams()
  94. {
  95. memset(this, 0, sizeof(*this));
  96. Result = true;
  97. AllowDirs = true;
  98. }
  99. //---------------------------------------------------------------------------
  100. TSynchronizeOptions::TSynchronizeOptions()
  101. {
  102. memset(this, 0, sizeof(*this));
  103. }
  104. //---------------------------------------------------------------------------
  105. TSynchronizeOptions::~TSynchronizeOptions()
  106. {
  107. delete Filter;
  108. }
  109. //---------------------------------------------------------------------------
  110. bool __fastcall TSynchronizeOptions::MatchesFilter(const UnicodeString & FileName)
  111. {
  112. int FoundIndex;
  113. bool Result;
  114. if (Filter == NULL)
  115. {
  116. Result = true;
  117. }
  118. else
  119. {
  120. Result = Filter->Find(FileName, FoundIndex);
  121. }
  122. return Result;
  123. }
  124. //---------------------------------------------------------------------------
  125. TSpaceAvailable::TSpaceAvailable()
  126. {
  127. memset(this, 0, sizeof(*this));
  128. }
  129. //---------------------------------------------------------------------------
  130. TOverwriteFileParams::TOverwriteFileParams()
  131. {
  132. SourceSize = 0;
  133. DestSize = 0;
  134. SourcePrecision = mfFull;
  135. DestPrecision = mfFull;
  136. }
  137. //---------------------------------------------------------------------------
  138. //---------------------------------------------------------------------------
  139. class TTunnelThread : public TSimpleThread
  140. {
  141. public:
  142. __fastcall TTunnelThread(TSecureShell * SecureShell);
  143. virtual __fastcall ~TTunnelThread();
  144. virtual void __fastcall Terminate();
  145. protected:
  146. virtual void __fastcall Execute();
  147. private:
  148. TSecureShell * FSecureShell;
  149. bool FTerminated;
  150. };
  151. //---------------------------------------------------------------------------
  152. __fastcall TTunnelThread::TTunnelThread(TSecureShell * SecureShell) :
  153. FSecureShell(SecureShell),
  154. FTerminated(false)
  155. {
  156. Start();
  157. }
  158. //---------------------------------------------------------------------------
  159. __fastcall TTunnelThread::~TTunnelThread()
  160. {
  161. // close before the class's virtual functions (Terminate particularly) are lost
  162. Close();
  163. }
  164. //---------------------------------------------------------------------------
  165. void __fastcall TTunnelThread::Terminate()
  166. {
  167. FTerminated = true;
  168. }
  169. //---------------------------------------------------------------------------
  170. void __fastcall TTunnelThread::Execute()
  171. {
  172. try
  173. {
  174. while (!FTerminated)
  175. {
  176. FSecureShell->Idle(250);
  177. }
  178. }
  179. catch(...)
  180. {
  181. if (FSecureShell->Active)
  182. {
  183. FSecureShell->Close();
  184. }
  185. // do not pass exception out of thread's proc
  186. }
  187. }
  188. //---------------------------------------------------------------------------
  189. //---------------------------------------------------------------------------
  190. class TTunnelUI : public TSessionUI
  191. {
  192. public:
  193. __fastcall TTunnelUI(TTerminal * Terminal);
  194. virtual void __fastcall Information(const UnicodeString & Str, bool Status);
  195. virtual unsigned int __fastcall QueryUser(const UnicodeString Query,
  196. TStrings * MoreMessages, unsigned int Answers, const TQueryParams * Params,
  197. TQueryType QueryType);
  198. virtual unsigned int __fastcall QueryUserException(const UnicodeString Query,
  199. Exception * E, unsigned int Answers, const TQueryParams * Params,
  200. TQueryType QueryType);
  201. virtual bool __fastcall PromptUser(TSessionData * Data, TPromptKind Kind,
  202. UnicodeString Name, UnicodeString Instructions, TStrings * Prompts,
  203. TStrings * Results);
  204. virtual void __fastcall DisplayBanner(const UnicodeString & Banner);
  205. virtual void __fastcall FatalError(Exception * E, UnicodeString Msg, UnicodeString HelpContext);
  206. virtual void __fastcall HandleExtendedException(Exception * E);
  207. virtual void __fastcall Closed();
  208. virtual void __fastcall ProcessGUI();
  209. private:
  210. TTerminal * FTerminal;
  211. unsigned int FTerminalThread;
  212. };
  213. //---------------------------------------------------------------------------
  214. __fastcall TTunnelUI::TTunnelUI(TTerminal * Terminal)
  215. {
  216. FTerminal = Terminal;
  217. FTerminalThread = GetCurrentThreadId();
  218. }
  219. //---------------------------------------------------------------------------
  220. void __fastcall TTunnelUI::Information(const UnicodeString & Str, bool Status)
  221. {
  222. if (GetCurrentThreadId() == FTerminalThread)
  223. {
  224. FTerminal->Information(Str, Status);
  225. }
  226. }
  227. //---------------------------------------------------------------------------
  228. unsigned int __fastcall TTunnelUI::QueryUser(const UnicodeString Query,
  229. TStrings * MoreMessages, unsigned int Answers, const TQueryParams * Params,
  230. TQueryType QueryType)
  231. {
  232. unsigned int Result;
  233. if (GetCurrentThreadId() == FTerminalThread)
  234. {
  235. Result = FTerminal->QueryUser(Query, MoreMessages, Answers, Params, QueryType);
  236. }
  237. else
  238. {
  239. Result = AbortAnswer(Answers);
  240. }
  241. return Result;
  242. }
  243. //---------------------------------------------------------------------------
  244. unsigned int __fastcall TTunnelUI::QueryUserException(const UnicodeString Query,
  245. Exception * E, unsigned int Answers, const TQueryParams * Params,
  246. TQueryType QueryType)
  247. {
  248. unsigned int Result;
  249. if (GetCurrentThreadId() == FTerminalThread)
  250. {
  251. Result = FTerminal->QueryUserException(Query, E, Answers, Params, QueryType);
  252. }
  253. else
  254. {
  255. Result = AbortAnswer(Answers);
  256. }
  257. return Result;
  258. }
  259. //---------------------------------------------------------------------------
  260. bool __fastcall TTunnelUI::PromptUser(TSessionData * Data, TPromptKind Kind,
  261. UnicodeString Name, UnicodeString Instructions, TStrings * Prompts, TStrings * Results)
  262. {
  263. bool Result;
  264. if (GetCurrentThreadId() == FTerminalThread)
  265. {
  266. if (IsAuthenticationPrompt(Kind))
  267. {
  268. Instructions =
  269. FMTLOAD(TUNNEL_INSTRUCTION2, (Data->HostName)) +
  270. (Instructions.IsEmpty() ? L"" : L"\n") +
  271. Instructions;
  272. }
  273. Result = FTerminal->PromptUser(Data, Kind, Name, Instructions, Prompts, Results);
  274. }
  275. else
  276. {
  277. Result = false;
  278. }
  279. return Result;
  280. }
  281. //---------------------------------------------------------------------------
  282. void __fastcall TTunnelUI::DisplayBanner(const UnicodeString & Banner)
  283. {
  284. if (GetCurrentThreadId() == FTerminalThread)
  285. {
  286. FTerminal->DisplayBanner(Banner);
  287. }
  288. }
  289. //---------------------------------------------------------------------------
  290. void __fastcall TTunnelUI::FatalError(Exception * E, UnicodeString Msg, UnicodeString HelpKeyword)
  291. {
  292. throw ESshFatal(E, Msg, HelpKeyword);
  293. }
  294. //---------------------------------------------------------------------------
  295. void __fastcall TTunnelUI::HandleExtendedException(Exception * E)
  296. {
  297. if (GetCurrentThreadId() == FTerminalThread)
  298. {
  299. FTerminal->HandleExtendedException(E);
  300. }
  301. }
  302. //---------------------------------------------------------------------------
  303. void __fastcall TTunnelUI::Closed()
  304. {
  305. // noop
  306. }
  307. //---------------------------------------------------------------------------
  308. void __fastcall TTunnelUI::ProcessGUI()
  309. {
  310. // noop
  311. }
  312. //---------------------------------------------------------------------------
  313. //---------------------------------------------------------------------------
  314. class TCallbackGuard
  315. {
  316. public:
  317. inline __fastcall TCallbackGuard(TTerminal * FTerminal);
  318. inline __fastcall ~TCallbackGuard();
  319. void __fastcall FatalError(Exception * E, const UnicodeString & Msg, const UnicodeString & HelpKeyword);
  320. inline void __fastcall Verify();
  321. inline bool __fastcall Verify(Exception * E);
  322. void __fastcall Dismiss();
  323. private:
  324. ExtException * FFatalError;
  325. TTerminal * FTerminal;
  326. bool FGuarding;
  327. };
  328. //---------------------------------------------------------------------------
  329. __fastcall TCallbackGuard::TCallbackGuard(TTerminal * Terminal) :
  330. FTerminal(Terminal),
  331. FFatalError(NULL),
  332. FGuarding(FTerminal->FCallbackGuard == NULL)
  333. {
  334. if (FGuarding)
  335. {
  336. FTerminal->FCallbackGuard = this;
  337. }
  338. }
  339. //---------------------------------------------------------------------------
  340. __fastcall TCallbackGuard::~TCallbackGuard()
  341. {
  342. if (FGuarding)
  343. {
  344. DebugAssert((FTerminal->FCallbackGuard == this) || (FTerminal->FCallbackGuard == NULL));
  345. FTerminal->FCallbackGuard = NULL;
  346. }
  347. delete FFatalError;
  348. }
  349. //---------------------------------------------------------------------------
  350. void __fastcall TCallbackGuard::FatalError(Exception * E, const UnicodeString & Msg, const UnicodeString & HelpKeyword)
  351. {
  352. DebugAssert(FGuarding);
  353. // make sure we do not bother about getting back the silent abort exception
  354. // we issued ourselves. this may happen when there is an exception handler
  355. // that converts any exception to fatal one (such as in TTerminal::Open).
  356. if (dynamic_cast<ECallbackGuardAbort *>(E) == NULL)
  357. {
  358. delete FFatalError;
  359. FFatalError = new ExtException(E, Msg, HelpKeyword);
  360. }
  361. // silently abort what we are doing.
  362. // non-silent exception would be caught probably by default application
  363. // exception handler, which may not do an appropriate action
  364. // (particularly it will not resume broken transfer).
  365. throw ECallbackGuardAbort();
  366. }
  367. //---------------------------------------------------------------------------
  368. void __fastcall TCallbackGuard::Dismiss()
  369. {
  370. DebugAssert(FFatalError == NULL);
  371. FGuarding = false;
  372. }
  373. //---------------------------------------------------------------------------
  374. void __fastcall TCallbackGuard::Verify()
  375. {
  376. if (FGuarding)
  377. {
  378. FGuarding = false;
  379. DebugAssert(FTerminal->FCallbackGuard == this);
  380. FTerminal->FCallbackGuard = NULL;
  381. if (FFatalError != NULL)
  382. {
  383. throw ESshFatal(FFatalError, L"");
  384. }
  385. }
  386. }
  387. //---------------------------------------------------------------------------
  388. bool __fastcall TCallbackGuard::Verify(Exception * E)
  389. {
  390. bool Result =
  391. (dynamic_cast<ECallbackGuardAbort *>(E) != NULL);
  392. if (Result)
  393. {
  394. DebugAssert(FGuarding && (FFatalError != NULL));
  395. Verify();
  396. }
  397. return Result;
  398. }
  399. //---------------------------------------------------------------------------
  400. //---------------------------------------------------------------------------
  401. TRobustOperationLoop::TRobustOperationLoop(
  402. TTerminal * Terminal, TFileOperationProgressType * OperationProgress, bool * AnyTransfer, bool CanRetry) :
  403. FTerminal(Terminal),
  404. FOperationProgress(OperationProgress),
  405. FRetry(false),
  406. FAnyTransfer(AnyTransfer),
  407. FCanRetry(CanRetry)
  408. {
  409. if (FAnyTransfer != NULL)
  410. {
  411. FPrevAnyTransfer = *FAnyTransfer;
  412. *FAnyTransfer = false;
  413. FStart = Now();
  414. }
  415. }
  416. //---------------------------------------------------------------------------
  417. TRobustOperationLoop::~TRobustOperationLoop()
  418. {
  419. if (FAnyTransfer != NULL)
  420. {
  421. *FAnyTransfer = FPrevAnyTransfer;
  422. }
  423. }
  424. //---------------------------------------------------------------------------
  425. bool TRobustOperationLoop::TryReopen(Exception & E)
  426. {
  427. if (!FCanRetry)
  428. {
  429. FRetry = false;
  430. }
  431. else if (dynamic_cast<ESkipFile *>(&E) != NULL)
  432. {
  433. FRetry = false;
  434. }
  435. else if (FTerminal->Active)
  436. {
  437. FTerminal->LogEvent(1, L"Session is open, will not retry transfer");
  438. FRetry = false;
  439. }
  440. else
  441. {
  442. FRetry = true;
  443. if (FAnyTransfer != NULL)
  444. {
  445. // if there was any transfer, reset the global timestamp
  446. if (*FAnyTransfer)
  447. {
  448. FStart = Now();
  449. FPrevAnyTransfer = true;
  450. *FAnyTransfer = false;
  451. }
  452. else
  453. {
  454. FRetry = FTerminal->ContinueReopen(FStart);
  455. if (!FRetry)
  456. {
  457. FTerminal->LogEvent(L"Retry interval expired, will not retry transfer");
  458. }
  459. }
  460. }
  461. if (FRetry)
  462. {
  463. FRetry =
  464. FTerminal->QueryReopen(&E, ropNoReadDirectory, FOperationProgress);
  465. }
  466. }
  467. return FRetry;
  468. }
  469. //---------------------------------------------------------------------------
  470. bool TRobustOperationLoop::ShouldRetry()
  471. {
  472. return FRetry;
  473. }
  474. //---------------------------------------------------------------------------
  475. bool TRobustOperationLoop::Retry()
  476. {
  477. bool Result = FRetry;
  478. FRetry = false;
  479. return Result;
  480. }
  481. //---------------------------------------------------------------------------
  482. class TRetryOperationLoop
  483. {
  484. public:
  485. TRetryOperationLoop(TTerminal * Terminal);
  486. void Error(Exception & E);
  487. void Error(Exception & E, TSessionAction & Action);
  488. void Error(Exception & E, const UnicodeString & Message);
  489. void Error(Exception & E, TSessionAction & Action, const UnicodeString & Message);
  490. bool Retry();
  491. bool Succeeded();
  492. private:
  493. TTerminal * FTerminal;
  494. bool FRetry;
  495. bool FSucceeded;
  496. void DoError(Exception & E, TSessionAction * Action, const UnicodeString & Message);
  497. };
  498. //---------------------------------------------------------------------------
  499. TRetryOperationLoop::TRetryOperationLoop(TTerminal * Terminal)
  500. {
  501. FTerminal = Terminal;
  502. FRetry = false;
  503. FSucceeded = true;
  504. }
  505. //---------------------------------------------------------------------------
  506. void TRetryOperationLoop::DoError(Exception & E, TSessionAction * Action, const UnicodeString & Message)
  507. {
  508. FSucceeded = false;
  509. // Note that the action may already be canceled when RollbackAction is called
  510. unsigned int Result;
  511. try
  512. {
  513. Result = FTerminal->CommandError(&E, Message, qaRetry | qaSkip | qaAbort);
  514. }
  515. catch (Exception & E2)
  516. {
  517. if (Action != NULL)
  518. {
  519. FTerminal->RollbackAction(*Action, NULL, &E2);
  520. }
  521. throw;
  522. }
  523. switch (Result)
  524. {
  525. case qaRetry:
  526. FRetry = true;
  527. if (Action != NULL)
  528. {
  529. Action->Cancel();
  530. }
  531. break;
  532. case qaAbort:
  533. if (Action != NULL)
  534. {
  535. FTerminal->RollbackAction(*Action, NULL, &E);
  536. }
  537. Abort();
  538. break;
  539. case qaSkip:
  540. if (Action != NULL)
  541. {
  542. Action->Cancel();
  543. }
  544. break;
  545. default:
  546. DebugFail();
  547. break;
  548. }
  549. }
  550. //---------------------------------------------------------------------------
  551. void TRetryOperationLoop::Error(Exception & E)
  552. {
  553. DoError(E, NULL, UnicodeString());
  554. }
  555. //---------------------------------------------------------------------------
  556. void TRetryOperationLoop::Error(Exception & E, TSessionAction & Action)
  557. {
  558. DoError(E, &Action, UnicodeString());
  559. }
  560. //---------------------------------------------------------------------------
  561. void TRetryOperationLoop::Error(Exception & E, const UnicodeString & Message)
  562. {
  563. DoError(E, NULL, Message);
  564. }
  565. //---------------------------------------------------------------------------
  566. void TRetryOperationLoop::Error(Exception & E, TSessionAction & Action, const UnicodeString & Message)
  567. {
  568. DoError(E, &Action, Message);
  569. }
  570. //---------------------------------------------------------------------------
  571. bool TRetryOperationLoop::Retry()
  572. {
  573. bool Result = FRetry;
  574. FRetry = false;
  575. if (Result)
  576. {
  577. FSucceeded = true;
  578. }
  579. return Result;
  580. }
  581. //---------------------------------------------------------------------------
  582. bool TRetryOperationLoop::Succeeded()
  583. {
  584. return FSucceeded;
  585. }
  586. //---------------------------------------------------------------------------
  587. //---------------------------------------------------------------------------
  588. TCollectedFileList::TCollectedFileList()
  589. {
  590. }
  591. //---------------------------------------------------------------------------
  592. __fastcall TCollectedFileList::~TCollectedFileList()
  593. {
  594. for (size_t Index = 0; Index < FList.size(); Index++)
  595. {
  596. Deleting(Index);
  597. }
  598. }
  599. //---------------------------------------------------------------------------
  600. void TCollectedFileList::Deleting(int Index)
  601. {
  602. delete FList[Index].Object;
  603. }
  604. //---------------------------------------------------------------------------
  605. int TCollectedFileList::Add(const UnicodeString & FileName, TObject * Object, bool Dir)
  606. {
  607. TFileData Data;
  608. Data.FileName = FileName;
  609. Data.Object = Object;
  610. Data.Dir = Dir;
  611. Data.Recursed = true;
  612. Data.State = 0;
  613. FList.push_back(Data);
  614. return Count() - 1;
  615. }
  616. //---------------------------------------------------------------------------
  617. void TCollectedFileList::DidNotRecurse(int Index)
  618. {
  619. FList[Index].Recursed = false;
  620. }
  621. //---------------------------------------------------------------------------
  622. void TCollectedFileList::Delete(int Index)
  623. {
  624. Deleting(Index);
  625. FList.erase(FList.begin() + Index);
  626. }
  627. //---------------------------------------------------------------------------
  628. int TCollectedFileList::Count() const
  629. {
  630. return FList.size();
  631. }
  632. //---------------------------------------------------------------------------
  633. UnicodeString TCollectedFileList::GetFileName(int Index) const
  634. {
  635. return FList[Index].FileName;
  636. }
  637. //---------------------------------------------------------------------------
  638. TObject * TCollectedFileList::GetObject(int Index) const
  639. {
  640. return FList[Index].Object;
  641. }
  642. //---------------------------------------------------------------------------
  643. bool TCollectedFileList::IsDir(int Index) const
  644. {
  645. return FList[Index].Dir;
  646. }
  647. //---------------------------------------------------------------------------
  648. bool TCollectedFileList::IsRecursed(int Index) const
  649. {
  650. return FList[Index].Recursed;
  651. }
  652. //---------------------------------------------------------------------------
  653. int TCollectedFileList::GetState(int Index) const
  654. {
  655. return FList[Index].State;
  656. }
  657. //---------------------------------------------------------------------------
  658. void TCollectedFileList::SetState(int Index, int State)
  659. {
  660. FList[Index].State = State;
  661. }
  662. //---------------------------------------------------------------------------
  663. //---------------------------------------------------------------------------
  664. TParallelOperation::TParallelOperation(TOperationSide Side)
  665. {
  666. FCopyParam = NULL;
  667. FParams = 0;
  668. FProbablyEmpty = false;
  669. FClients = 0;
  670. FMainOperationProgress = NULL;
  671. DebugAssert((Side == osLocal) || (Side == osRemote));
  672. FSide = Side;
  673. FVersion = 0;
  674. }
  675. //---------------------------------------------------------------------------
  676. void TParallelOperation::Init(
  677. TStrings * AFileList, const UnicodeString & TargetDir, const TCopyParamType * CopyParam, int Params,
  678. TFileOperationProgressType * MainOperationProgress, const UnicodeString & MainName,
  679. __int64 ParallelFileSize)
  680. {
  681. DebugAssert(FFileList.get() == NULL);
  682. // More lists should really happen in scripting only, which does not support parallel transfers atm.
  683. // But in general the code should work with more lists anyway, it just was not tested for it.
  684. DebugAssert(AFileList->Count == 1);
  685. FFileList.reset(AFileList);
  686. FSection.reset(new TCriticalSection());
  687. FTargetDir = TargetDir;
  688. FCopyParam = CopyParam;
  689. FParams = Params;
  690. FMainOperationProgress = MainOperationProgress;
  691. FMainName = MainName;
  692. FListIndex = 0;
  693. FIndex = 0;
  694. FIsParallelFileTransfer = (ParallelFileSize >= 0);
  695. FParallelFileSize = ParallelFileSize;
  696. FParallelFileOffset = 0;
  697. FParallelFileCount = 0;
  698. FParallelFileMerging = false;
  699. FParallelFileMerged = 0;
  700. }
  701. //---------------------------------------------------------------------------
  702. TParallelOperation::~TParallelOperation()
  703. {
  704. WaitFor();
  705. }
  706. //---------------------------------------------------------------------------
  707. bool TParallelOperation::IsInitialized()
  708. {
  709. return (FMainOperationProgress != NULL);
  710. }
  711. //---------------------------------------------------------------------------
  712. bool TParallelOperation::ShouldAddClient()
  713. {
  714. bool Result;
  715. // TTransferQueueItem::ProgressUpdated() already checks IsInitialized() before calling this
  716. if (!IsInitialized())
  717. {
  718. Result = false;
  719. }
  720. else
  721. {
  722. TGuard Guard(FSection.get());
  723. Result = !FProbablyEmpty && (FMainOperationProgress->Cancel < csCancel);
  724. }
  725. return Result;
  726. }
  727. //---------------------------------------------------------------------------
  728. void TParallelOperation::AddClient()
  729. {
  730. TGuard Guard(FSection.get());
  731. FClients++;
  732. }
  733. //---------------------------------------------------------------------------
  734. void TParallelOperation::RemoveClient()
  735. {
  736. TGuard Guard(FSection.get());
  737. FClients--;
  738. }
  739. //---------------------------------------------------------------------------
  740. void TParallelOperation::WaitFor()
  741. {
  742. // Even initialized?
  743. // Won't be, when parallel transfers were not possible (like when preserving of directory timestamps is enabled)
  744. if (FSection.get() != NULL)
  745. {
  746. bool Done;
  747. do
  748. {
  749. {
  750. TGuard Guard(FSection.get());
  751. Done = (FClients == 0);
  752. }
  753. if (!Done)
  754. {
  755. // propagate the total progress incremented by the parallel operations
  756. FMainOperationProgress->Progress();
  757. Sleep(200);
  758. }
  759. }
  760. while (!Done);
  761. FProbablyEmpty = true;
  762. }
  763. else
  764. {
  765. DebugAssert(FClients == 0);
  766. }
  767. }
  768. //---------------------------------------------------------------------------
  769. void TParallelOperation::Done(
  770. const UnicodeString & FileName, bool Dir, bool Success, const UnicodeString & TargetDir,
  771. const TCopyParamType * CopyParam, TTerminal * Terminal)
  772. {
  773. if (Dir)
  774. {
  775. TGuard Guard(FSection.get());
  776. TDirectories::iterator DirectoryIterator = FDirectories.find(FileName);
  777. if (DebugAlwaysTrue(DirectoryIterator != FDirectories.end()))
  778. {
  779. if (Success)
  780. {
  781. DebugAssert(!DirectoryIterator->second.Exists);
  782. DirectoryIterator->second.Exists = true;
  783. }
  784. else
  785. {
  786. // This is actually not useful at the moment, as when creating directory fails and "Skip" is pressed,
  787. // the current code in CopyToRemote/CreateDirectory will behave as, if it succeded, so Success will be true here.
  788. FDirectories.erase(DirectoryIterator);
  789. if (FFileList->Count > FListIndex)
  790. {
  791. UnicodeString FileNameWithSlash;
  792. if (FSide == osLocal)
  793. {
  794. FileNameWithSlash = IncludeTrailingBackslash(FileName);
  795. }
  796. else
  797. {
  798. FileNameWithSlash = UnixIncludeTrailingBackslash(FileName);
  799. }
  800. // It can actually be a different list than the one the directory was taken from,
  801. // but that does not matter that much. It should not happen anyway, as more lists should be in scripting only.
  802. TCollectedFileList * Files = GetFileList(FListIndex);
  803. int Index = 0;
  804. while (Index < Files->Count())
  805. {
  806. if (StartsText(FileNameWithSlash, Files->GetFileName(Index)))
  807. {
  808. // We should add the file to "skip" counters in the OperationProgress,
  809. // but an interactive foreground transfer is not doing that either yet.
  810. Files->Delete(Index);
  811. // Force re-update
  812. FVersion++;
  813. if (Index < FIndex)
  814. {
  815. FIndex--;
  816. }
  817. }
  818. else
  819. {
  820. Index++;
  821. }
  822. }
  823. }
  824. }
  825. }
  826. }
  827. else
  828. {
  829. if (IsParallelFileTransfer)
  830. {
  831. TGuard Guard(FSection.get());
  832. try
  833. {
  834. if (Success && DebugAlwaysTrue(FSide == osRemote))
  835. {
  836. TParallelFileOffsets::const_iterator I = std::find(FParallelFileOffsets.begin(), FParallelFileOffsets.end(), CopyParam->PartOffset);
  837. if (DebugAlwaysTrue(I != FParallelFileOffsets.end()))
  838. {
  839. int Index = I - FParallelFileOffsets.begin();
  840. DebugAssert(!FParallelFileDones[Index]);
  841. FParallelFileDones[Index] = true;
  842. if (!FParallelFileMerging)
  843. {
  844. // Once we obtain "merging" semaphor, we won't leave until everything is merged
  845. TAutoFlag MergingFlag(FParallelFileMerging);
  846. try
  847. {
  848. UnicodeString TargetName = CombinePaths(TargetDir, FParallelFileTargetName);
  849. UnicodeString TargetNamePartial = TargetName + PartialExt;
  850. UnicodeString TargetNamePartialOnly = ExtractFileName(TargetNamePartial);
  851. while (true)
  852. {
  853. if ((FParallelFileMerged >= FParallelFileCount) || !FParallelFileDones[FParallelFileMerged])
  854. {
  855. break;
  856. }
  857. else
  858. {
  859. TUnguard Unguard(FSection.get());
  860. UnicodeString FileNameOnly = UnixExtractFileName(FileName);
  861. // Safe as write access to FParallelFileMerged is guarded by FParallelFileMerging
  862. int Index = FParallelFileMerged;
  863. UnicodeString TargetPartName = GetPartPrefix(CombinePaths(TargetDir, FileNameOnly)) + IntToStr(Index);
  864. if ((CopyParam->PartSize >= 0) && (Terminal->OperationProgress->TransferredSize != CopyParam->PartSize))
  865. {
  866. UnicodeString TransferredSizeStr = IntToStr(Terminal->OperationProgress->TransferredSize);
  867. UnicodeString PartSizeStr = IntToStr(CopyParam->PartSize);
  868. UnicodeString Message =
  869. FMTLOAD(INCONSISTENT_SIZE, (TargetPartName, TransferredSizeStr, PartSizeStr));
  870. Terminal->TerminalError(NULL, Message);
  871. }
  872. if (Index == 0)
  873. {
  874. Terminal->LogEvent(FORMAT(L"Renaming part %d of \"%s\" to \"%s\"...", (Index, FileNameOnly, TargetNamePartialOnly)));
  875. Terminal->DoRenameLocalFileForce(TargetPartName, TargetNamePartial);
  876. }
  877. else
  878. {
  879. {
  880. Terminal->LogEvent(FORMAT(L"Appending part %d of \"%s\" to \"%s\"...", (Index, FileNameOnly, TargetNamePartialOnly)));
  881. std::unique_ptr<THandleStream> SourceStream(TSafeHandleStream::CreateFromFile(TargetPartName, fmOpenRead | fmShareDenyWrite));
  882. std::unique_ptr<THandleStream> DestStream(TSafeHandleStream::CreateFromFile(TargetNamePartial, fmOpenWrite | fmShareDenyWrite));
  883. HANDLE DestHandle = reinterpret_cast<HANDLE>(DestStream->Handle);
  884. FILETIME WrTime;
  885. bool GotWrTime = GetFileTime(DestHandle, NULL, NULL, &WrTime);
  886. DestStream->Seek(0L, soEnd);
  887. DestStream->CopyFrom(SourceStream.get(), SourceStream->Size);
  888. if (GotWrTime)
  889. {
  890. SetFileTime(DestHandle, NULL, NULL, &WrTime);
  891. }
  892. }
  893. Terminal->DoDeleteLocalFile(TargetPartName);
  894. }
  895. FParallelFileMerged++;
  896. }
  897. }
  898. if ((FParallelFileMerged == FParallelFileCount) && (FParallelFileOffset == FParallelFileSize))
  899. {
  900. Terminal->LogEvent(FORMAT(L"Renaming completed \"%s\" to \"%s\"...", (TargetNamePartialOnly, FParallelFileTargetName)));
  901. Terminal->DoRenameLocalFileForce(TargetNamePartial, TargetName);
  902. }
  903. }
  904. catch (...)
  905. {
  906. Success = false;
  907. throw;
  908. }
  909. }
  910. }
  911. }
  912. }
  913. __finally
  914. {
  915. if (!Success)
  916. {
  917. // If any part fails, cancel whole transfer.
  918. // We should get here only after the user sees/acknowledges the failure.
  919. FMainOperationProgress->SetCancel(csCancel);
  920. }
  921. }
  922. }
  923. }
  924. }
  925. //---------------------------------------------------------------------------
  926. bool TParallelOperation::CheckEnd(TCollectedFileList * Files)
  927. {
  928. bool Result = (FIndex >= Files->Count());
  929. if (Result)
  930. {
  931. FListIndex++;
  932. FIndex = 0;
  933. }
  934. return Result;
  935. }
  936. //---------------------------------------------------------------------------
  937. bool TParallelOperation::GetOnlyFile(TStrings * FileList, UnicodeString & FileName, TObject *& Object)
  938. {
  939. bool Result = (FileList->Count == 1);
  940. if (Result)
  941. {
  942. TCollectedFileList * OnlyFileList = GetFileList(FileList, 0);
  943. Result = (OnlyFileList->Count() == 1) && !OnlyFileList->IsDir(0);
  944. if (Result)
  945. {
  946. FileName = OnlyFileList->GetFileName(0);
  947. Object = OnlyFileList->GetObject(0);
  948. }
  949. }
  950. return Result;
  951. }
  952. //---------------------------------------------------------------------------
  953. TCollectedFileList * TParallelOperation::GetFileList(TStrings * FileList, int Index)
  954. {
  955. return DebugNotNull(dynamic_cast<TCollectedFileList *>(FileList->Objects[Index]));
  956. }
  957. //---------------------------------------------------------------------------
  958. TCollectedFileList * TParallelOperation::GetFileList(int Index)
  959. {
  960. return GetFileList(FFileList.get(), Index);
  961. }
  962. //---------------------------------------------------------------------------
  963. UnicodeString TParallelOperation::GetPartPrefix(const UnicodeString & FileName)
  964. {
  965. return FORMAT(L"%s%s.", (FileName, PartialExt));
  966. }
  967. //---------------------------------------------------------------------------
  968. int TParallelOperation::GetNext(
  969. TTerminal * Terminal, UnicodeString & FileName, TObject *& Object, UnicodeString & TargetDir, bool & Dir,
  970. bool & Recursed, TCopyParamType *& CustomCopyParam)
  971. {
  972. TGuard Guard(FSection.get());
  973. int Result = 1;
  974. TCollectedFileList * Files;
  975. do
  976. {
  977. if (FFileList->Count > FListIndex)
  978. {
  979. Files = GetFileList(FListIndex);
  980. // can happen if the file was excluded by file mask
  981. if (CheckEnd(Files))
  982. {
  983. Files = NULL;
  984. }
  985. }
  986. else
  987. {
  988. Files = NULL;
  989. Result = -1;
  990. }
  991. }
  992. while ((Result == 1) && (Files == NULL));
  993. if (Files != NULL)
  994. {
  995. UnicodeString RootPath = FFileList->Strings[FListIndex];
  996. FileName = Files->GetFileName(FIndex);
  997. Object = Files->GetObject(FIndex);
  998. Dir = Files->IsDir(FIndex);
  999. Recursed = Files->IsRecursed(FIndex);
  1000. UnicodeString DirPath;
  1001. bool FirstLevel;
  1002. if (FSide == osLocal)
  1003. {
  1004. DirPath = ExtractFileDir(FileName);
  1005. FirstLevel = SamePaths(DirPath, RootPath);
  1006. }
  1007. else
  1008. {
  1009. DirPath = UnixExtractFileDir(FileName);
  1010. FirstLevel = UnixSamePath(DirPath, RootPath);
  1011. }
  1012. if (FirstLevel)
  1013. {
  1014. TargetDir = FTargetDir;
  1015. }
  1016. else
  1017. {
  1018. TDirectories::const_iterator DirectoryIterator = FDirectories.find(DirPath);
  1019. if (DebugAlwaysFalse(DirectoryIterator == FDirectories.end()))
  1020. {
  1021. throw EInvalidOperation(L"Parent path not known");
  1022. }
  1023. const TDirectoryData & DirectoryData = DirectoryIterator->second;
  1024. if (!DirectoryData.Exists)
  1025. {
  1026. Result = 0; // wait for parent directory to be created
  1027. }
  1028. else
  1029. {
  1030. TargetDir = DirectoryData.OppositePath;
  1031. }
  1032. }
  1033. if (!TargetDir.IsEmpty())
  1034. {
  1035. UnicodeString OnlyFileName;
  1036. if (Dir || IsParallelFileTransfer) // optimization
  1037. {
  1038. if (FSide == osLocal)
  1039. {
  1040. OnlyFileName = ExtractFileName(FileName);
  1041. }
  1042. else
  1043. {
  1044. OnlyFileName = UnixExtractFileName(FileName);
  1045. }
  1046. OnlyFileName = Terminal->ChangeFileName(FCopyParam, OnlyFileName, FSide, FirstLevel);
  1047. }
  1048. if (Dir)
  1049. {
  1050. DebugAssert(!OnlyFileName.IsEmpty());
  1051. TDirectoryData DirectoryData;
  1052. if (FSide == osLocal)
  1053. {
  1054. DirectoryData.OppositePath = UnixCombinePaths(TargetDir, OnlyFileName);
  1055. }
  1056. else
  1057. {
  1058. DirectoryData.OppositePath = CombinePaths(TargetDir, OnlyFileName);
  1059. }
  1060. DirectoryData.Exists = false;
  1061. FDirectories.insert(std::make_pair(FileName, DirectoryData));
  1062. }
  1063. bool Processed = true;
  1064. if (IsParallelFileTransfer)
  1065. {
  1066. CustomCopyParam = new TCopyParamType(*FCopyParam);
  1067. CustomCopyParam->PartOffset = FParallelFileOffset;
  1068. __int64 Remaining = FParallelFileSize - CustomCopyParam->PartOffset;
  1069. CustomCopyParam->PartSize = FParallelFileSize / Configuration->QueueTransfersLimit;
  1070. DebugAssert(!OnlyFileName.IsEmpty());
  1071. if (FParallelFileTargetName.IsEmpty())
  1072. {
  1073. FParallelFileTargetName = OnlyFileName;
  1074. }
  1075. DebugAssert(FParallelFileTargetName == OnlyFileName);
  1076. int Index = FParallelFileCount;
  1077. UnicodeString PartFileName = GetPartPrefix(OnlyFileName) + IntToStr(Index);
  1078. FParallelFileCount++;
  1079. FParallelFileOffsets.push_back(CustomCopyParam->PartOffset);
  1080. FParallelFileDones.push_back(false);
  1081. DebugAssert(FParallelFileOffsets.size() == static_cast<size_t>(FParallelFileCount));
  1082. CustomCopyParam->FileMask = DelimitFileNameMask(PartFileName);
  1083. if ((CustomCopyParam->PartSize >= Remaining) ||
  1084. (Remaining - CustomCopyParam->PartSize < CustomCopyParam->PartSize / 10))
  1085. {
  1086. CustomCopyParam->PartSize = -1; // Until the end
  1087. FParallelFileOffset = FParallelFileSize;
  1088. Terminal->LogEvent(FORMAT(L"Starting transfer of \"%s\" part %d from %s until the EOF", (OnlyFileName, Index, IntToStr(CustomCopyParam->PartOffset))));
  1089. }
  1090. else
  1091. {
  1092. Processed = false;
  1093. FParallelFileOffset += CustomCopyParam->PartSize;
  1094. Terminal->LogEvent(FORMAT(L"Starting transfer of \"%s\" part %d from %s, length %s", (OnlyFileName, Index, IntToStr(CustomCopyParam->PartOffset), IntToStr(CustomCopyParam->PartSize))));
  1095. }
  1096. }
  1097. if (Processed)
  1098. {
  1099. // The current implementation of UpdateFileList relies on this specific way of changing state
  1100. // (all files before FIndex one-by-one)
  1101. Files->SetState(FIndex, qfsProcessed);
  1102. FIndex++;
  1103. CheckEnd(Files);
  1104. }
  1105. }
  1106. }
  1107. FProbablyEmpty = (FFileList->Count == FListIndex);
  1108. return Result;
  1109. }
  1110. //---------------------------------------------------------------------------
  1111. bool TParallelOperation::UpdateFileList(TQueueFileList * UpdateFileList)
  1112. {
  1113. TGuard Guard(FSection.get());
  1114. bool Result =
  1115. (UpdateFileList->FLastParallelOperation != this) ||
  1116. (UpdateFileList->FLastParallelOperationVersion != FVersion);
  1117. DebugAssert(FFileList->Count == 1);
  1118. TCollectedFileList * Files = GetFileList(0);
  1119. if (!Result && (UpdateFileList->GetCount() != Files->Count()))
  1120. {
  1121. DebugAssert(false);
  1122. Result = true;
  1123. }
  1124. if (Result)
  1125. {
  1126. UpdateFileList->Clear();
  1127. for (int Index = 0; Index < Files->Count(); Index++)
  1128. {
  1129. UpdateFileList->Add(Files->GetFileName(Index), Files->GetState(Index));
  1130. }
  1131. }
  1132. else
  1133. {
  1134. int Index = ((FListIndex == 0) ? FIndex : Files->Count()) - 1;
  1135. while ((Index >= 0) && (UpdateFileList->GetState(Index) != Files->GetState(Index)))
  1136. {
  1137. UpdateFileList->SetState(Index, Files->GetState(Index));
  1138. Index--;
  1139. Result = true;
  1140. }
  1141. }
  1142. UpdateFileList->FLastParallelOperation = this;
  1143. UpdateFileList->FLastParallelOperationVersion = FVersion;
  1144. return Result;
  1145. }
  1146. //---------------------------------------------------------------------------
  1147. //---------------------------------------------------------------------------
  1148. __fastcall TTerminal::TTerminal(TSessionData * SessionData, TConfiguration * Configuration, TActionLog * ActionLog)
  1149. {
  1150. FConfiguration = Configuration;
  1151. FSessionData = new TSessionData(L"");
  1152. FSessionData->Assign(SessionData);
  1153. TDateTime Started = Now(); // use the same time for session and XML log
  1154. FLog = new TSessionLog(this, Started, FSessionData, Configuration);
  1155. if (ActionLog != NULL)
  1156. {
  1157. FActionLog = ActionLog;
  1158. FActionLogOwned = false;
  1159. }
  1160. else
  1161. {
  1162. FActionLog = new TActionLog(this, Started, FSessionData, Configuration);
  1163. FActionLogOwned = true;
  1164. }
  1165. FFiles = new TRemoteDirectory(this);
  1166. FExceptionOnFail = 0;
  1167. FInTransaction = 0;
  1168. FReadCurrentDirectoryPending = false;
  1169. FReadDirectoryPending = false;
  1170. FUsersGroupsLookedup = False;
  1171. FTunnelLocalPortNumber = 0;
  1172. FFileSystem = NULL;
  1173. FSecureShell = NULL;
  1174. FOnProgress = NULL;
  1175. FOnFinished = NULL;
  1176. FOnDeleteLocalFile = NULL;
  1177. FOnReadDirectoryProgress = NULL;
  1178. FOnQueryUser = NULL;
  1179. FOnPromptUser = NULL;
  1180. FOnDisplayBanner = NULL;
  1181. FOnShowExtendedException = NULL;
  1182. FOnInformation = NULL;
  1183. FOnCustomCommand = NULL;
  1184. FOnClose = NULL;
  1185. FOnFindingFile = NULL;
  1186. FOperationProgressPersistence = NULL;
  1187. FOperationProgressOnceDoneOperation = odoIdle;
  1188. FUseBusyCursor = True;
  1189. FDirectoryCache = new TRemoteDirectoryCache();
  1190. FDirectoryChangesCache = NULL;
  1191. FFSProtocol = cfsUnknown;
  1192. FCommandSession = NULL;
  1193. FAutoReadDirectory = true;
  1194. FReadingCurrentDirectory = false;
  1195. FStatus = ssClosed;
  1196. FOpening = 0;
  1197. FTunnelThread = NULL;
  1198. FTunnel = NULL;
  1199. FTunnelData = NULL;
  1200. FTunnelLog = NULL;
  1201. FTunnelUI = NULL;
  1202. FTunnelOpening = false;
  1203. FCallbackGuard = NULL;
  1204. FNesting = 0;
  1205. FRememberedPasswordKind = TPromptKind(-1);
  1206. FSecondaryTerminals = 0;
  1207. }
  1208. //---------------------------------------------------------------------------
  1209. __fastcall TTerminal::~TTerminal()
  1210. {
  1211. if (Active)
  1212. {
  1213. Close();
  1214. }
  1215. if (FCallbackGuard != NULL)
  1216. {
  1217. // see TTerminal::HandleExtendedException
  1218. FCallbackGuard->Dismiss();
  1219. }
  1220. DebugAssert(FTunnel == NULL);
  1221. SAFE_DESTROY(FCommandSession);
  1222. if (SessionData->CacheDirectoryChanges && SessionData->PreserveDirectoryChanges &&
  1223. (FDirectoryChangesCache != NULL))
  1224. {
  1225. Configuration->SaveDirectoryChangesCache(SessionData->SessionKey,
  1226. FDirectoryChangesCache);
  1227. }
  1228. SAFE_DESTROY_EX(TCustomFileSystem, FFileSystem);
  1229. SAFE_DESTROY_EX(TSessionLog, FLog);
  1230. if (FActionLogOwned)
  1231. {
  1232. SAFE_DESTROY_EX(TActionLog, FActionLog);
  1233. }
  1234. else
  1235. {
  1236. FActionLog = NULL;
  1237. }
  1238. delete FFiles;
  1239. delete FDirectoryCache;
  1240. delete FDirectoryChangesCache;
  1241. SAFE_DESTROY(FSessionData);
  1242. }
  1243. //---------------------------------------------------------------------------
  1244. void __fastcall TTerminal::Idle()
  1245. {
  1246. // Once we disconnect, do nothing, until reconnect handler
  1247. // "receives the information".
  1248. // Never go idle when called from within ::ProcessGUI() call
  1249. // as we may recurse for good, timeouting eventually.
  1250. if (Active && (FNesting == 0))
  1251. {
  1252. TAutoNestingCounter NestingCounter(FNesting);
  1253. if (Configuration->ActualLogProtocol >= 1)
  1254. {
  1255. LogEvent(L"Session upkeep");
  1256. }
  1257. DebugAssert(FFileSystem != NULL);
  1258. FFileSystem->Idle();
  1259. if (CommandSessionOpened)
  1260. {
  1261. try
  1262. {
  1263. FCommandSession->Idle();
  1264. }
  1265. catch(Exception & E)
  1266. {
  1267. // If the secondary session is dropped, ignore the error and let
  1268. // it be reconnected when needed.
  1269. // BTW, non-fatal error can hardly happen here, that's why
  1270. // it is displayed, because it can be useful to know.
  1271. if (FCommandSession->Active)
  1272. {
  1273. FCommandSession->HandleExtendedException(&E);
  1274. }
  1275. }
  1276. }
  1277. }
  1278. }
  1279. //---------------------------------------------------------------------
  1280. RawByteString __fastcall TTerminal::EncryptPassword(const UnicodeString & Password)
  1281. {
  1282. return Configuration->EncryptPassword(Password, SessionData->GetSessionPasswordEncryptionKey());
  1283. }
  1284. //---------------------------------------------------------------------
  1285. UnicodeString __fastcall TTerminal::DecryptPassword(const RawByteString & Password)
  1286. {
  1287. UnicodeString Result;
  1288. try
  1289. {
  1290. Result = Configuration->DecryptPassword(Password, SessionData->GetSessionPasswordEncryptionKey());
  1291. }
  1292. catch(EAbort &)
  1293. {
  1294. // silently ignore aborted prompts for master password and return empty password
  1295. }
  1296. return Result;
  1297. }
  1298. //---------------------------------------------------------------------------
  1299. void __fastcall TTerminal::RecryptPasswords()
  1300. {
  1301. FSessionData->RecryptPasswords();
  1302. FRememberedPassword = EncryptPassword(GetRememberedPassword());
  1303. FRememberedTunnelPassword = EncryptPassword(GetRememberedTunnelPassword());
  1304. }
  1305. //---------------------------------------------------------------------------
  1306. UnicodeString __fastcall TTerminal::ExpandFileName(UnicodeString Path,
  1307. const UnicodeString BasePath)
  1308. {
  1309. // replace this by AbsolutePath()
  1310. Path = UnixExcludeTrailingBackslash(Path);
  1311. if (!UnixIsAbsolutePath(Path) && !BasePath.IsEmpty())
  1312. {
  1313. // TODO: Handle more complicated cases like "../../xxx"
  1314. if (Path == PARENTDIRECTORY)
  1315. {
  1316. Path = UnixExcludeTrailingBackslash(UnixExtractFilePath(
  1317. UnixExcludeTrailingBackslash(BasePath)));
  1318. }
  1319. else
  1320. {
  1321. Path = UnixIncludeTrailingBackslash(BasePath) + Path;
  1322. }
  1323. }
  1324. return Path;
  1325. }
  1326. //---------------------------------------------------------------------------
  1327. bool __fastcall TTerminal::GetActive()
  1328. {
  1329. return (FFileSystem != NULL) && FFileSystem->GetActive();
  1330. }
  1331. //---------------------------------------------------------------------------
  1332. void __fastcall TTerminal::Close()
  1333. {
  1334. FFileSystem->Close();
  1335. // Cannot rely on CommandSessionOpened here as Status is set to ssClosed too late
  1336. if ((FCommandSession != NULL) && FCommandSession->Active)
  1337. {
  1338. // prevent recursion
  1339. FCommandSession->OnClose = NULL;
  1340. FCommandSession->Close();
  1341. }
  1342. }
  1343. //---------------------------------------------------------------------------
  1344. void __fastcall TTerminal::ResetConnection()
  1345. {
  1346. // used to be called from Reopen(), why?
  1347. FTunnelError = L"";
  1348. FRememberedPasswordTried = false;
  1349. FRememberedTunnelPasswordTried = false;
  1350. if (FDirectoryChangesCache != NULL)
  1351. {
  1352. delete FDirectoryChangesCache;
  1353. FDirectoryChangesCache = NULL;
  1354. }
  1355. FFiles->Directory = L"";
  1356. // note that we cannot clear contained files
  1357. // as they can still be referenced in the GUI atm
  1358. }
  1359. //---------------------------------------------------------------------------
  1360. void __fastcall TTerminal::FingerprintScan(UnicodeString & SHA256, UnicodeString & SHA1, UnicodeString & MD5)
  1361. {
  1362. SessionData->FingerprintScan = true;
  1363. try
  1364. {
  1365. Open();
  1366. // we should never get here
  1367. DebugFail();
  1368. Abort();
  1369. }
  1370. catch (...)
  1371. {
  1372. if (!FFingerprintScannedSHA256.IsEmpty() ||
  1373. !FFingerprintScannedSHA1.IsEmpty() ||
  1374. !FFingerprintScannedMD5.IsEmpty())
  1375. {
  1376. SHA256 = FFingerprintScannedSHA256;
  1377. SHA1 = FFingerprintScannedSHA1;
  1378. MD5 = FFingerprintScannedMD5;
  1379. }
  1380. else
  1381. {
  1382. throw;
  1383. }
  1384. }
  1385. }
  1386. //---------------------------------------------------------------------------
  1387. void __fastcall TTerminal::Open()
  1388. {
  1389. AnySession = true;
  1390. Configuration->Usage->Inc(L"SessionOpens");
  1391. TAutoNestingCounter OpeningCounter(FOpening);
  1392. ReflectSettings();
  1393. try
  1394. {
  1395. FEncryptKey = HexToBytes(FSessionData->EncryptKey);
  1396. if (IsEncryptingFiles())
  1397. {
  1398. ValidateEncryptKey(FEncryptKey);
  1399. }
  1400. DoInformation(L"", true, 1);
  1401. try
  1402. {
  1403. FRememberedPasswordUsed = false;
  1404. try
  1405. {
  1406. ResetConnection();
  1407. FStatus = ssOpening;
  1408. try
  1409. {
  1410. if (FFileSystem == NULL)
  1411. {
  1412. Log->AddSystemInfo();
  1413. DoInitializeLog();
  1414. Log->AddStartupInfo();
  1415. }
  1416. DebugAssert(FTunnel == NULL);
  1417. if (FSessionData->Tunnel)
  1418. {
  1419. DoInformation(LoadStr(OPEN_TUNNEL), true);
  1420. LogEvent(L"Opening tunnel.");
  1421. OpenTunnel();
  1422. Log->AddSeparator();
  1423. FSessionData->ConfigureTunnel(FTunnelLocalPortNumber);
  1424. DoInformation(LoadStr(USING_TUNNEL), false);
  1425. LogEvent(FORMAT(L"Connecting via tunnel interface %s:%d.",
  1426. (FSessionData->HostNameExpanded, FSessionData->PortNumber)));
  1427. }
  1428. else
  1429. {
  1430. DebugAssert(FTunnelLocalPortNumber == 0);
  1431. }
  1432. if (FFileSystem == NULL)
  1433. {
  1434. if (SessionData->FSProtocol == fsFTP)
  1435. {
  1436. FFSProtocol = cfsFTP;
  1437. FFileSystem = new TFTPFileSystem(this);
  1438. FFileSystem->Open();
  1439. Log->AddSeparator();
  1440. LogEvent(L"Using FTP protocol.");
  1441. }
  1442. else if (SessionData->FSProtocol == fsWebDAV)
  1443. {
  1444. FFSProtocol = cfsWebDAV;
  1445. FFileSystem = new TWebDAVFileSystem(this);
  1446. FFileSystem->Open();
  1447. Log->AddSeparator();
  1448. LogEvent(L"Using WebDAV protocol.");
  1449. }
  1450. else if (SessionData->FSProtocol == fsS3)
  1451. {
  1452. FFSProtocol = cfsS3;
  1453. FFileSystem = new TS3FileSystem(this);
  1454. FFileSystem->Open();
  1455. Log->AddSeparator();
  1456. LogEvent(L"Using S3 protocol.");
  1457. }
  1458. else
  1459. {
  1460. DebugAssert(FSecureShell == NULL);
  1461. try
  1462. {
  1463. FSecureShell = new TSecureShell(this, FSessionData, Log, Configuration);
  1464. try
  1465. {
  1466. // there will be only one channel in this session
  1467. FSecureShell->Simple = true;
  1468. FSecureShell->Open();
  1469. }
  1470. catch(Exception & E)
  1471. {
  1472. DebugAssert(!FSecureShell->Active);
  1473. if (SessionData->FingerprintScan)
  1474. {
  1475. FSecureShell->GetHostKeyFingerprint(FFingerprintScannedSHA256, FFingerprintScannedMD5);
  1476. FFingerprintScannedSHA1 = UnicodeString();
  1477. }
  1478. // Tunnel errors that happens only once we connect to the local port (server-side forwarding problems).
  1479. // Contrary to local side problems handled already in OpenTunnel.
  1480. if (!FSecureShell->Active && !FTunnelError.IsEmpty())
  1481. {
  1482. // the only case where we expect this to happen (first in GUI, the latter in scripting)
  1483. DebugAssert((E.Message == LoadStr(UNEXPECTED_CLOSE_ERROR)) || (E.Message == LoadStr(NET_TRANSL_CONN_ABORTED)) || (E.Message.Pos(LoadStr(NOT_CONNECTED)) > 0));
  1484. FatalError(&E, FMTLOAD(TUNNEL_ERROR, (FTunnelError)));
  1485. }
  1486. else
  1487. {
  1488. throw;
  1489. }
  1490. }
  1491. Log->AddSeparator();
  1492. if ((SessionData->FSProtocol == fsSCPonly) ||
  1493. (SessionData->FSProtocol == fsSFTP && FSecureShell->SshFallbackCmd()))
  1494. {
  1495. FFSProtocol = cfsSCP;
  1496. FFileSystem = new TSCPFileSystem(this, FSecureShell);
  1497. FSecureShell = NULL; // ownership passed
  1498. LogEvent(L"Using SCP protocol.");
  1499. }
  1500. else
  1501. {
  1502. FFSProtocol = cfsSFTP;
  1503. FFileSystem = new TSFTPFileSystem(this, FSecureShell);
  1504. FSecureShell = NULL; // ownership passed
  1505. LogEvent(L"Using SFTP protocol.");
  1506. }
  1507. }
  1508. __finally
  1509. {
  1510. delete FSecureShell;
  1511. FSecureShell = NULL;
  1512. }
  1513. }
  1514. }
  1515. else
  1516. {
  1517. FFileSystem->Open();
  1518. }
  1519. }
  1520. __finally
  1521. {
  1522. if (FSessionData->Tunnel)
  1523. {
  1524. FSessionData->RollbackTunnel();
  1525. }
  1526. }
  1527. if (SessionData->CacheDirectoryChanges)
  1528. {
  1529. DebugAssert(FDirectoryChangesCache == NULL);
  1530. FDirectoryChangesCache = new TRemoteDirectoryChangesCache(
  1531. Configuration->CacheDirectoryChangesMaxSize);
  1532. if (SessionData->PreserveDirectoryChanges)
  1533. {
  1534. Configuration->LoadDirectoryChangesCache(SessionData->SessionKey,
  1535. FDirectoryChangesCache);
  1536. }
  1537. }
  1538. DoStartup();
  1539. if (FCollectFileSystemUsage)
  1540. {
  1541. FFileSystem->CollectUsage();
  1542. FCollectFileSystemUsage = false;
  1543. }
  1544. DoInformation(LoadStr(STATUS_READY), true);
  1545. FStatus = ssOpened;
  1546. }
  1547. catch(...)
  1548. {
  1549. // rollback
  1550. if (FDirectoryChangesCache != NULL)
  1551. {
  1552. delete FDirectoryChangesCache;
  1553. FDirectoryChangesCache = NULL;
  1554. }
  1555. if (SessionData->FingerprintScan && (FFileSystem != NULL) &&
  1556. DebugAlwaysTrue(SessionData->Ftps != ftpsNone))
  1557. {
  1558. const TSessionInfo & SessionInfo = FFileSystem->GetSessionInfo();
  1559. FFingerprintScannedSHA256 = SessionInfo.CertificateFingerprintSHA256;
  1560. FFingerprintScannedSHA1 = SessionInfo.CertificateFingerprintSHA1;
  1561. FFingerprintScannedMD5 = UnicodeString();
  1562. }
  1563. if (FRememberedPasswordUsed)
  1564. {
  1565. // Particularly to prevent reusing a wrong client certificate passphrase
  1566. // in the next login attempt
  1567. FRememberedPassword = UnicodeString();
  1568. FRememberedPasswordKind = TPromptKind(-1);
  1569. FRememberedTunnelPassword = UnicodeString();
  1570. }
  1571. throw;
  1572. }
  1573. }
  1574. __finally
  1575. {
  1576. // This does not make it through, if terminal thread is abandoned,
  1577. // see also TTerminalManager::DoConnectTerminal
  1578. DoInformation(L"", true, 0);
  1579. }
  1580. }
  1581. catch(EFatal &)
  1582. {
  1583. throw;
  1584. }
  1585. catch(Exception & E)
  1586. {
  1587. // any exception while opening session is fatal
  1588. FatalError(&E, L"");
  1589. }
  1590. }
  1591. //---------------------------------------------------------------------------
  1592. bool __fastcall TTerminal::IsListenerFree(unsigned int PortNumber)
  1593. {
  1594. SOCKET Socket = socket(AF_INET, SOCK_STREAM, 0);
  1595. bool Result = (Socket != INVALID_SOCKET);
  1596. if (Result)
  1597. {
  1598. SOCKADDR_IN Address;
  1599. memset(&Address, 0, sizeof(Address));
  1600. Address.sin_family = AF_INET;
  1601. Address.sin_port = htons(static_cast<short>(PortNumber));
  1602. Address.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  1603. Result = (bind(Socket, reinterpret_cast<sockaddr *>(&Address), sizeof(Address)) == 0);
  1604. closesocket(Socket);
  1605. }
  1606. return Result;
  1607. }
  1608. //---------------------------------------------------------------------------
  1609. void __fastcall TTerminal::OpenTunnel()
  1610. {
  1611. DebugAssert(FTunnelData == NULL);
  1612. FTunnelLocalPortNumber = FSessionData->TunnelLocalPortNumber;
  1613. if (FTunnelLocalPortNumber == 0)
  1614. {
  1615. // Randomizing the port selection to reduce a chance of conflicts.
  1616. std::vector<int> Ports;
  1617. for (int Port = Configuration->TunnelLocalPortNumberLow; Port <= Configuration->TunnelLocalPortNumberHigh; Port++)
  1618. {
  1619. Ports.push_back(Port);
  1620. }
  1621. do
  1622. {
  1623. if (Ports.empty())
  1624. {
  1625. FatalError(NULL, FMTLOAD(TUNNEL_NO_FREE_PORT,
  1626. (Configuration->TunnelLocalPortNumberLow, Configuration->TunnelLocalPortNumberHigh)));
  1627. }
  1628. int Index = Random(Ports.size());
  1629. int Port = Ports[Index];
  1630. Ports.erase(&Ports.at(Index));
  1631. if (IsListenerFree(Port))
  1632. {
  1633. FTunnelLocalPortNumber = Port;
  1634. LogEvent(FORMAT(L"Autoselected tunnel local port number %d", (FTunnelLocalPortNumber)));
  1635. }
  1636. }
  1637. while (FTunnelLocalPortNumber == 0);
  1638. }
  1639. try
  1640. {
  1641. FTunnelData = FSessionData->CreateTunnelData(FTunnelLocalPortNumber);
  1642. // The Started argument is not used with Parent being set
  1643. FTunnelLog = new TSessionLog(this, TDateTime(), FTunnelData, Configuration);
  1644. FTunnelLog->SetParent(FLog, L"Tunnel");
  1645. FTunnelLog->ReflectSettings();
  1646. FTunnelUI = new TTunnelUI(this);
  1647. FTunnel = new TSecureShell(FTunnelUI, FTunnelData, FTunnelLog, Configuration);
  1648. FTunnelOpening = true;
  1649. try
  1650. {
  1651. FTunnel->Open();
  1652. }
  1653. __finally
  1654. {
  1655. FTunnelOpening = false;
  1656. }
  1657. // When forwarding fails due to a local problem (e.g. port in use), we get the error already here, so abort asap.
  1658. // If we won't abort, particularly in case of "port in use", we may not even detect the problem,
  1659. // as the connection to the port may succeed.
  1660. // Remote-side tunnel problems are handled in TTerminal::Open().
  1661. if (!FTunnel->LastTunnelError.IsEmpty())
  1662. {
  1663. // Throw and handle with any other theoretical forwarding errors that may cause tunnel connection close
  1664. // (probably cannot happen)
  1665. EXCEPTION;
  1666. }
  1667. FTunnelThread = new TTunnelThread(FTunnel);
  1668. }
  1669. catch (Exception & E)
  1670. {
  1671. LogEvent(L"Error opening tunnel.");
  1672. CloseTunnel();
  1673. if (!FTunnelError.IsEmpty())
  1674. {
  1675. FatalError(&E, FMTLOAD(TUNNEL_ERROR, (FTunnelError)));
  1676. }
  1677. else
  1678. {
  1679. throw;
  1680. }
  1681. }
  1682. }
  1683. //---------------------------------------------------------------------------
  1684. void __fastcall TTerminal::CloseTunnel()
  1685. {
  1686. SAFE_DESTROY_EX(TTunnelThread, FTunnelThread);
  1687. FTunnelError = FTunnel->LastTunnelError;
  1688. SAFE_DESTROY_EX(TSecureShell, FTunnel);
  1689. SAFE_DESTROY_EX(TTunnelUI, FTunnelUI);
  1690. SAFE_DESTROY_EX(TSessionLog, FTunnelLog);
  1691. SAFE_DESTROY(FTunnelData);
  1692. FTunnelLocalPortNumber = 0;
  1693. }
  1694. //---------------------------------------------------------------------------
  1695. void __fastcall TTerminal::Closed()
  1696. {
  1697. if (FTunnel != NULL)
  1698. {
  1699. CloseTunnel();
  1700. }
  1701. if (OnClose)
  1702. {
  1703. TCallbackGuard Guard(this);
  1704. try
  1705. {
  1706. OnClose(this);
  1707. Guard.Verify();
  1708. }
  1709. catch (Exception & E)
  1710. {
  1711. if (!Guard.Verify(&E))
  1712. {
  1713. throw;
  1714. }
  1715. }
  1716. }
  1717. FStatus = ssClosed;
  1718. }
  1719. //---------------------------------------------------------------------------
  1720. void __fastcall TTerminal::ProcessGUI()
  1721. {
  1722. // Do not process GUI here, as we are called directly from a GUI loop and may
  1723. // recurse for good.
  1724. // Alternatively we may check for (FOperationProgress == NULL)
  1725. if (FNesting == 0)
  1726. {
  1727. TAutoNestingCounter NestingCounter(FNesting);
  1728. ::ProcessGUI();
  1729. }
  1730. }
  1731. //---------------------------------------------------------------------------
  1732. void __fastcall TTerminal::Progress(TFileOperationProgressType * OperationProgress)
  1733. {
  1734. if (FNesting == 0)
  1735. {
  1736. TAutoNestingCounter NestingCounter(FNesting);
  1737. OperationProgress->Progress();
  1738. }
  1739. }
  1740. //---------------------------------------------------------------------------
  1741. void __fastcall TTerminal::Reopen(int Params)
  1742. {
  1743. TFSProtocol OrigFSProtocol = SessionData->FSProtocol;
  1744. UnicodeString PrevRemoteDirectory = SessionData->RemoteDirectory;
  1745. bool PrevReadCurrentDirectoryPending = FReadCurrentDirectoryPending;
  1746. bool PrevReadDirectoryPending = FReadDirectoryPending;
  1747. DebugAssert(!FSuspendTransaction);
  1748. bool PrevAutoReadDirectory = FAutoReadDirectory;
  1749. // here used to be a check for FExceptionOnFail being 0
  1750. // but it can happen, e.g. when we are downloading file to execute it.
  1751. // however I'm not sure why we mind having exception-on-fail enabled here
  1752. int PrevExceptionOnFail = FExceptionOnFail;
  1753. try
  1754. {
  1755. FReadCurrentDirectoryPending = false;
  1756. FReadDirectoryPending = false;
  1757. // Not sure why we are suspending the transaction in the first place,
  1758. // but definitely when set while connecting auto loaded workspace session, it causes loading the directory twice.
  1759. // (when reconnecting lost connection, it's usually prevented by cached directory)
  1760. // Preventing that by suspending transaction only when there is one.
  1761. FSuspendTransaction = (FInTransaction > 0);
  1762. FExceptionOnFail = 0;
  1763. // typically, we avoid reading directory, when there is operation ongoing,
  1764. // for file list which may reference files from current directory
  1765. if (FLAGSET(Params, ropNoReadDirectory))
  1766. {
  1767. AutoReadDirectory = false;
  1768. }
  1769. // only peek, we may not be connected at all atm,
  1770. // so make sure we do not try retrieving current directory from the server
  1771. // (particularly with FTP)
  1772. UnicodeString ACurrentDirectory = PeekCurrentDirectory();
  1773. if (!ACurrentDirectory.IsEmpty())
  1774. {
  1775. SessionData->RemoteDirectory = ACurrentDirectory;
  1776. }
  1777. if (SessionData->FSProtocol == fsSFTP)
  1778. {
  1779. SessionData->FSProtocol = (FFSProtocol == cfsSCP ? fsSCPonly : fsSFTPonly);
  1780. }
  1781. Open();
  1782. }
  1783. __finally
  1784. {
  1785. SessionData->RemoteDirectory = PrevRemoteDirectory;
  1786. SessionData->FSProtocol = OrigFSProtocol;
  1787. FAutoReadDirectory = PrevAutoReadDirectory;
  1788. FReadCurrentDirectoryPending = PrevReadCurrentDirectoryPending;
  1789. FReadDirectoryPending = PrevReadDirectoryPending;
  1790. FSuspendTransaction = false;
  1791. FExceptionOnFail = PrevExceptionOnFail;
  1792. }
  1793. }
  1794. //---------------------------------------------------------------------------
  1795. bool __fastcall TTerminal::PromptUser(TSessionData * Data, TPromptKind Kind,
  1796. UnicodeString Name, UnicodeString Instructions, UnicodeString Prompt, bool Echo, int MaxLen, UnicodeString & Result)
  1797. {
  1798. bool AResult;
  1799. TStrings * Prompts = new TStringList;
  1800. TStrings * Results = new TStringList;
  1801. try
  1802. {
  1803. Prompts->AddObject(Prompt, (TObject *)(FLAGMASK(Echo, pupEcho)));
  1804. Results->AddObject(Result, (TObject *)MaxLen);
  1805. AResult = PromptUser(Data, Kind, Name, Instructions, Prompts, Results);
  1806. Result = Results->Strings[0];
  1807. }
  1808. __finally
  1809. {
  1810. delete Prompts;
  1811. delete Results;
  1812. }
  1813. return AResult;
  1814. }
  1815. //---------------------------------------------------------------------------
  1816. bool __fastcall TTerminal::PromptUser(TSessionData * Data, TPromptKind Kind,
  1817. UnicodeString Name, UnicodeString Instructions, TStrings * Prompts, TStrings * Results)
  1818. {
  1819. // If PromptUser is overridden in descendant class, the overridden version
  1820. // is not called when accessed via TSessionIU interface.
  1821. // So this is workaround.
  1822. // Actually no longer needed as we do not override DoPromptUser
  1823. // anymore in TSecondaryTerminal.
  1824. return DoPromptUser(Data, Kind, Name, Instructions, Prompts, Results);
  1825. }
  1826. //---------------------------------------------------------------------------
  1827. TTerminal * __fastcall TTerminal::GetPrimaryTerminal()
  1828. {
  1829. return this;
  1830. }
  1831. //---------------------------------------------------------------------------
  1832. bool __fastcall TTerminal::DoPromptUser(TSessionData * /*Data*/, TPromptKind Kind,
  1833. UnicodeString Name, UnicodeString Instructions, TStrings * Prompts, TStrings * Results)
  1834. {
  1835. bool AResult = false;
  1836. bool PasswordOrPassphrasePrompt = IsPasswordOrPassphrasePrompt(Kind, Prompts);
  1837. if (PasswordOrPassphrasePrompt)
  1838. {
  1839. bool & PasswordTried =
  1840. FTunnelOpening ? FRememberedTunnelPasswordTried : FRememberedPasswordTried;
  1841. if (!PasswordTried)
  1842. {
  1843. // let's expect that the main session is already authenticated and its password
  1844. // is not written after, so no locking is necessary
  1845. // (no longer true, once the main session can be reconnected)
  1846. UnicodeString APassword;
  1847. if (FTunnelOpening)
  1848. {
  1849. APassword = PrimaryTerminal->GetRememberedTunnelPassword();
  1850. }
  1851. else
  1852. {
  1853. APassword = PrimaryTerminal->GetRememberedPassword();
  1854. }
  1855. FRememberedPasswordUsed = true;
  1856. Results->Strings[0] = APassword;
  1857. if (!Results->Strings[0].IsEmpty())
  1858. {
  1859. LogEvent(L"Using remembered password.");
  1860. AResult = true;
  1861. }
  1862. PasswordTried = true;
  1863. }
  1864. }
  1865. if (!AResult)
  1866. {
  1867. if (PasswordOrPassphrasePrompt && !Configuration->RememberPassword)
  1868. {
  1869. Prompts->Objects[0] = (TObject*)(int(Prompts->Objects[0]) | pupRemember);
  1870. }
  1871. if (OnPromptUser != NULL)
  1872. {
  1873. TCallbackGuard Guard(this);
  1874. try
  1875. {
  1876. OnPromptUser(this, Kind, Name, Instructions, Prompts, Results, AResult, NULL);
  1877. Guard.Verify();
  1878. }
  1879. catch (Exception & E)
  1880. {
  1881. if (!Guard.Verify(&E))
  1882. {
  1883. throw;
  1884. }
  1885. }
  1886. }
  1887. if (AResult && PasswordOrPassphrasePrompt &&
  1888. (Configuration->RememberPassword || FLAGSET(int(Prompts->Objects[0]), pupRemember)))
  1889. {
  1890. RawByteString EncryptedPassword = EncryptPassword(Results->Strings[0]);
  1891. if (FTunnelOpening)
  1892. {
  1893. PrimaryTerminal->FRememberedTunnelPassword = EncryptedPassword;
  1894. }
  1895. else
  1896. {
  1897. PrimaryTerminal->FRememberedPassword = EncryptedPassword;
  1898. PrimaryTerminal->FRememberedPasswordKind = Kind;
  1899. }
  1900. }
  1901. }
  1902. return AResult;
  1903. }
  1904. //---------------------------------------------------------------------------
  1905. unsigned int __fastcall TTerminal::QueryUser(const UnicodeString Query,
  1906. TStrings * MoreMessages, unsigned int Answers, const TQueryParams * Params,
  1907. TQueryType QueryType)
  1908. {
  1909. LogEvent(FORMAT(L"Asking user:\n%s (%s)", (Query, (MoreMessages ? MoreMessages->CommaText : UnicodeString() ))));
  1910. unsigned int Answer = AbortAnswer(Answers);
  1911. if (FOnQueryUser)
  1912. {
  1913. TCallbackGuard Guard(this);
  1914. try
  1915. {
  1916. FOnQueryUser(this, Query, MoreMessages, Answers, Params, Answer, QueryType, NULL);
  1917. Guard.Verify();
  1918. }
  1919. catch (Exception & E)
  1920. {
  1921. if (!Guard.Verify(&E))
  1922. {
  1923. throw;
  1924. }
  1925. }
  1926. }
  1927. UnicodeString Name;
  1928. if (Answer == qaNeverAskAgain)
  1929. {
  1930. Name = L"NeverAskAgain";
  1931. }
  1932. else
  1933. {
  1934. UnicodeString Caption;
  1935. AnswerNameAndCaption(Answer, Name, Caption);
  1936. }
  1937. LogEvent(FORMAT(L"Answer: %s", (Name)));
  1938. return Answer;
  1939. }
  1940. //---------------------------------------------------------------------------
  1941. unsigned int __fastcall TTerminal::QueryUserException(const UnicodeString Query,
  1942. Exception * E, unsigned int Answers, const TQueryParams * Params,
  1943. TQueryType QueryType)
  1944. {
  1945. unsigned int Result;
  1946. UnicodeString ExMessage;
  1947. if (DebugAlwaysTrue(ExceptionMessageFormatted(E, ExMessage) || !Query.IsEmpty()))
  1948. {
  1949. TStrings * MoreMessages = new TStringList();
  1950. try
  1951. {
  1952. if (!ExMessage.IsEmpty() && !Query.IsEmpty())
  1953. {
  1954. MoreMessages->Add(UnformatMessage(ExMessage));
  1955. }
  1956. ExtException * EE = dynamic_cast<ExtException*>(E);
  1957. if ((EE != NULL) && (EE->MoreMessages != NULL))
  1958. {
  1959. MoreMessages->AddStrings(EE->MoreMessages);
  1960. }
  1961. // We know MoreMessages not to be NULL here,
  1962. // AppendExceptionStackTraceAndForget should never return true
  1963. // (indicating it had to create the string list)
  1964. DebugAlwaysFalse(AppendExceptionStackTraceAndForget(MoreMessages));
  1965. TQueryParams HelpKeywordOverrideParams;
  1966. if (Params != NULL)
  1967. {
  1968. HelpKeywordOverrideParams.Assign(*Params);
  1969. }
  1970. HelpKeywordOverrideParams.HelpKeyword =
  1971. MergeHelpKeyword(HelpKeywordOverrideParams.HelpKeyword, GetExceptionHelpKeyword(E));
  1972. Result = QueryUser(!Query.IsEmpty() ? Query : ExMessage,
  1973. MoreMessages->Count ? MoreMessages : NULL,
  1974. Answers, &HelpKeywordOverrideParams, QueryType);
  1975. }
  1976. __finally
  1977. {
  1978. delete MoreMessages;
  1979. }
  1980. }
  1981. return Result;
  1982. }
  1983. //---------------------------------------------------------------------------
  1984. void __fastcall TTerminal::DisplayBanner(const UnicodeString & Banner)
  1985. {
  1986. if (OnDisplayBanner != NULL)
  1987. {
  1988. unsigned int OrigParams, Params;
  1989. if (Configuration->ForceBanners ||
  1990. Configuration->ShowBanner(SessionData->SessionKey, Banner, Params))
  1991. {
  1992. bool NeverShowAgain = false;
  1993. int Options =
  1994. FLAGMASK(Configuration->ForceBanners, boDisableNeverShowAgain);
  1995. OrigParams = Params;
  1996. TCallbackGuard Guard(this);
  1997. try
  1998. {
  1999. OnDisplayBanner(this, SessionData->SessionName, Banner, NeverShowAgain, Options, Params);
  2000. Guard.Verify();
  2001. }
  2002. catch (Exception & E)
  2003. {
  2004. if (!Guard.Verify(&E))
  2005. {
  2006. throw;
  2007. }
  2008. }
  2009. if (!Configuration->ForceBanners && NeverShowAgain)
  2010. {
  2011. Configuration->NeverShowBanner(SessionData->SessionKey, Banner);
  2012. }
  2013. if (OrigParams != Params)
  2014. {
  2015. Configuration->SetBannerParams(SessionData->SessionKey, Params);
  2016. }
  2017. }
  2018. }
  2019. }
  2020. //---------------------------------------------------------------------------
  2021. void __fastcall TTerminal::HandleExtendedException(Exception * E)
  2022. {
  2023. Log->AddException(E);
  2024. if (OnShowExtendedException != NULL)
  2025. {
  2026. TCallbackGuard Guard(this);
  2027. try
  2028. {
  2029. // the event handler may destroy 'this' ...
  2030. OnShowExtendedException(this, E, NULL);
  2031. // .. hence guard is dismissed from destructor, to make following call no-op
  2032. Guard.Verify();
  2033. }
  2034. catch (Exception & E)
  2035. {
  2036. if (!Guard.Verify(&E))
  2037. {
  2038. throw;
  2039. }
  2040. }
  2041. }
  2042. }
  2043. //---------------------------------------------------------------------------
  2044. void __fastcall TTerminal::ShowExtendedException(Exception * E)
  2045. {
  2046. Log->AddException(E);
  2047. if (OnShowExtendedException != NULL)
  2048. {
  2049. OnShowExtendedException(this, E, NULL);
  2050. }
  2051. }
  2052. //---------------------------------------------------------------------------
  2053. void __fastcall TTerminal::DoInformation(
  2054. const UnicodeString & Str, bool Status, int Phase, const UnicodeString & Additional)
  2055. {
  2056. if (OnInformation)
  2057. {
  2058. TCallbackGuard Guard(this);
  2059. try
  2060. {
  2061. OnInformation(this, Str, Status, Phase, Additional);
  2062. Guard.Verify();
  2063. }
  2064. catch (Exception & E)
  2065. {
  2066. if (!Guard.Verify(&E))
  2067. {
  2068. throw;
  2069. }
  2070. }
  2071. }
  2072. }
  2073. //---------------------------------------------------------------------------
  2074. void __fastcall TTerminal::Information(const UnicodeString & Str, bool Status)
  2075. {
  2076. DoInformation(Str, Status);
  2077. }
  2078. //---------------------------------------------------------------------------
  2079. void __fastcall TTerminal::DoProgress(TFileOperationProgressType & ProgressData)
  2080. {
  2081. if ((Configuration->ActualLogProtocol >= 1) &&
  2082. ProgressData.IsTransfer())
  2083. {
  2084. DWORD Now = GetTickCount();
  2085. if (Now - FLastProgressLogged >= 1000)
  2086. {
  2087. LogEvent(L"Transfer progress: " + ProgressData.GetLogStr(false));
  2088. FLastProgressLogged = Now;
  2089. }
  2090. }
  2091. if (ProgressData.TransferredSize > 0)
  2092. {
  2093. FFileTransferAny = true;
  2094. }
  2095. if (OnProgress != NULL)
  2096. {
  2097. TCallbackGuard Guard(this);
  2098. try
  2099. {
  2100. OnProgress(ProgressData);
  2101. Guard.Verify();
  2102. }
  2103. catch (Exception & E)
  2104. {
  2105. if (!Guard.Verify(&E))
  2106. {
  2107. throw;
  2108. }
  2109. }
  2110. }
  2111. }
  2112. //---------------------------------------------------------------------------
  2113. void __fastcall TTerminal::DoFinished(TFileOperation Operation, TOperationSide Side, bool Temp,
  2114. const UnicodeString & FileName, bool Success, TOnceDoneOperation & OnceDoneOperation)
  2115. {
  2116. if (OnFinished != NULL)
  2117. {
  2118. TCallbackGuard Guard(this);
  2119. try
  2120. {
  2121. OnFinished(Operation, Side, Temp, FileName, Success, OnceDoneOperation);
  2122. Guard.Verify();
  2123. }
  2124. catch (Exception & E)
  2125. {
  2126. if (!Guard.Verify(&E))
  2127. {
  2128. throw;
  2129. }
  2130. }
  2131. }
  2132. }
  2133. //---------------------------------------------------------------------------
  2134. void __fastcall TTerminal::SaveCapabilities(TFileSystemInfo & FileSystemInfo)
  2135. {
  2136. for (int Index = 0; Index < fcCount; Index++)
  2137. {
  2138. FileSystemInfo.IsCapable[Index] = IsCapable[(TFSCapability)Index];
  2139. }
  2140. }
  2141. //---------------------------------------------------------------------------
  2142. bool __fastcall TTerminal::GetIsCapable(TFSCapability Capability) const
  2143. {
  2144. if (DebugAlwaysTrue(FFileSystem != NULL))
  2145. {
  2146. switch (Capability)
  2147. {
  2148. case fcBackgroundTransfers:
  2149. return !IsEncryptingFiles();
  2150. default:
  2151. return FFileSystem->IsCapable(Capability);
  2152. }
  2153. }
  2154. else
  2155. {
  2156. return false;
  2157. }
  2158. }
  2159. //---------------------------------------------------------------------------
  2160. UnicodeString __fastcall TTerminal::AbsolutePath(UnicodeString Path, bool Local)
  2161. {
  2162. return FFileSystem->AbsolutePath(Path, Local);
  2163. }
  2164. //---------------------------------------------------------------------------
  2165. void __fastcall TTerminal::ReactOnCommand(int /*TFSCommand*/ Cmd)
  2166. {
  2167. bool ChangesDirectory = false;
  2168. bool ModifiesFiles = false;
  2169. switch ((TFSCommand)Cmd) {
  2170. case fsChangeDirectory:
  2171. case fsHomeDirectory:
  2172. ChangesDirectory = true;
  2173. break;
  2174. case fsCopyToRemote:
  2175. case fsDeleteFile:
  2176. case fsRenameFile:
  2177. case fsMoveFile:
  2178. case fsCopyFile:
  2179. case fsCreateDirectory:
  2180. case fsChangeMode:
  2181. case fsChangeGroup:
  2182. case fsChangeOwner:
  2183. case fsChangeProperties:
  2184. case fsLock:
  2185. ModifiesFiles = true;
  2186. break;
  2187. case fsAnyCommand:
  2188. ChangesDirectory = true;
  2189. ModifiesFiles = true;
  2190. break;
  2191. }
  2192. if (ChangesDirectory)
  2193. {
  2194. if (!InTransaction())
  2195. {
  2196. ReadCurrentDirectory();
  2197. if (AutoReadDirectory)
  2198. {
  2199. ReadDirectory(false);
  2200. }
  2201. }
  2202. else
  2203. {
  2204. FReadCurrentDirectoryPending = true;
  2205. if (AutoReadDirectory)
  2206. {
  2207. FReadDirectoryPending = true;
  2208. }
  2209. }
  2210. }
  2211. else if (ModifiesFiles && AutoReadDirectory && Configuration->AutoReadDirectoryAfterOp)
  2212. {
  2213. if (!InTransaction())
  2214. {
  2215. ReadDirectory(true);
  2216. }
  2217. else
  2218. {
  2219. FReadDirectoryPending = true;
  2220. }
  2221. }
  2222. }
  2223. //---------------------------------------------------------------------------
  2224. void __fastcall TTerminal::TerminalError(UnicodeString Msg)
  2225. {
  2226. TerminalError(NULL, Msg);
  2227. }
  2228. //---------------------------------------------------------------------------
  2229. void __fastcall TTerminal::TerminalError(
  2230. Exception * E, UnicodeString Msg, UnicodeString HelpKeyword)
  2231. {
  2232. throw ETerminal(E, Msg, HelpKeyword);
  2233. }
  2234. //---------------------------------------------------------------------------
  2235. bool __fastcall TTerminal::DoQueryReopen(Exception * E)
  2236. {
  2237. EFatal * Fatal = dynamic_cast<EFatal *>(E);
  2238. DebugAssert(Fatal != NULL);
  2239. bool Result;
  2240. if ((Fatal != NULL) && Fatal->ReopenQueried)
  2241. {
  2242. Result = false;
  2243. }
  2244. else
  2245. {
  2246. LogEvent(L"Connection was lost, asking what to do.");
  2247. TQueryParams Params(qpAllowContinueOnError);
  2248. Params.Timeout = Configuration->SessionReopenAuto;
  2249. Params.TimeoutAnswer = qaRetry;
  2250. Params.TimeoutResponse = Params.TimeoutAnswer;
  2251. TQueryButtonAlias Aliases[1];
  2252. Aliases[0].Button = qaRetry;
  2253. Aliases[0].Alias = LoadStr(RECONNECT_BUTTON);
  2254. Params.Aliases = Aliases;
  2255. Params.AliasesCount = LENOF(Aliases);
  2256. Result = (QueryUserException(L"", E, qaRetry | qaAbort, &Params, qtError) == qaRetry);
  2257. if (Fatal != NULL)
  2258. {
  2259. Fatal->ReopenQueried = true;
  2260. }
  2261. }
  2262. return Result;
  2263. }
  2264. //---------------------------------------------------------------------------
  2265. bool __fastcall TTerminal::ContinueReopen(TDateTime Start)
  2266. {
  2267. return
  2268. (Configuration->SessionReopenTimeout == 0) ||
  2269. (int(double(Now() - Start) * MSecsPerDay) < Configuration->SessionReopenTimeout);
  2270. }
  2271. //---------------------------------------------------------------------------
  2272. bool __fastcall TTerminal::QueryReopen(Exception * E, int Params,
  2273. TFileOperationProgressType * OperationProgress)
  2274. {
  2275. TSuspendFileOperationProgress Suspend(OperationProgress);
  2276. bool Result = DoQueryReopen(E);
  2277. if (Result)
  2278. {
  2279. TDateTime Start = Now();
  2280. do
  2281. {
  2282. try
  2283. {
  2284. Reopen(Params);
  2285. }
  2286. catch(Exception & E)
  2287. {
  2288. if (!Active)
  2289. {
  2290. Result =
  2291. ContinueReopen(Start) &&
  2292. DoQueryReopen(&E);
  2293. }
  2294. else
  2295. {
  2296. throw;
  2297. }
  2298. }
  2299. }
  2300. while (!Active && Result);
  2301. }
  2302. return Result;
  2303. }
  2304. //---------------------------------------------------------------------------
  2305. bool __fastcall TTerminal::FileOperationLoopQuery(Exception & E,
  2306. TFileOperationProgressType * OperationProgress, const UnicodeString Message,
  2307. unsigned int Flags, UnicodeString SpecialRetry, UnicodeString HelpKeyword)
  2308. {
  2309. bool Result = false;
  2310. Log->AddException(&E);
  2311. unsigned int Answer;
  2312. bool AllowSkip = FLAGSET(Flags, folAllowSkip);
  2313. bool SkipToAllPossible = AllowSkip && (OperationProgress != NULL);
  2314. if (SkipToAllPossible && OperationProgress->SkipToAll)
  2315. {
  2316. Answer = qaSkip;
  2317. }
  2318. else
  2319. {
  2320. int Answers = qaRetry | qaAbort |
  2321. FLAGMASK(AllowSkip, qaSkip) |
  2322. FLAGMASK(SkipToAllPossible, qaAll) |
  2323. FLAGMASK(!SpecialRetry.IsEmpty(), qaYes);
  2324. TQueryParams Params(qpAllowContinueOnError | FLAGMASK(!AllowSkip, qpFatalAbort));
  2325. Params.HelpKeyword = HelpKeyword;
  2326. TQueryButtonAlias Aliases[2];
  2327. int AliasCount = 0;
  2328. if (FLAGSET(Answers, qaAll))
  2329. {
  2330. Aliases[AliasCount].Button = qaAll;
  2331. Aliases[AliasCount].Alias = LoadStr(SKIP_ALL_BUTTON);
  2332. AliasCount++;
  2333. }
  2334. if (FLAGSET(Answers, qaYes))
  2335. {
  2336. Aliases[AliasCount].Button = qaYes;
  2337. Aliases[AliasCount].Alias = SpecialRetry;
  2338. AliasCount++;
  2339. }
  2340. if (AliasCount > 0)
  2341. {
  2342. Params.Aliases = Aliases;
  2343. Params.AliasesCount = AliasCount;
  2344. }
  2345. {
  2346. TSuspendFileOperationProgress Suspend(OperationProgress);
  2347. Answer = QueryUserException(Message, &E, Answers, &Params, qtError);
  2348. }
  2349. if (Answer == qaAll)
  2350. {
  2351. DebugAssert(OperationProgress != NULL);
  2352. OperationProgress->SetSkipToAll();
  2353. Answer = qaSkip;
  2354. }
  2355. if (Answer == qaYes)
  2356. {
  2357. Result = true;
  2358. Answer = qaRetry;
  2359. }
  2360. }
  2361. if (Answer != qaRetry)
  2362. {
  2363. if ((Answer == qaAbort) && (OperationProgress != NULL))
  2364. {
  2365. OperationProgress->SetCancel(csCancel);
  2366. }
  2367. if (AllowSkip)
  2368. {
  2369. throw ESkipFile(&E, Message);
  2370. }
  2371. else
  2372. {
  2373. // this can happen only during file transfer with SCP
  2374. throw ExtException(&E, Message);
  2375. }
  2376. }
  2377. return Result;
  2378. }
  2379. //---------------------------------------------------------------------------
  2380. void __fastcall TTerminal::FileOperationLoopEnd(Exception & E,
  2381. TFileOperationProgressType * OperationProgress, const UnicodeString & Message,
  2382. unsigned int Flags, const UnicodeString & SpecialRetry, const UnicodeString & HelpKeyword)
  2383. {
  2384. if ((dynamic_cast<EAbort *>(&E) != NULL) ||
  2385. (dynamic_cast<ESkipFile *>(&E) != NULL) ||
  2386. (dynamic_cast<ESkipFile *>(&E) != NULL))
  2387. {
  2388. RethrowException(&E);
  2389. }
  2390. else if (dynamic_cast<EFatal *>(&E) != NULL)
  2391. {
  2392. if (FLAGCLEAR(Flags, folRetryOnFatal))
  2393. {
  2394. RethrowException(&E);
  2395. }
  2396. else
  2397. {
  2398. DebugAssert(SpecialRetry.IsEmpty());
  2399. std::unique_ptr<Exception> E2(new EFatal(&E, Message, HelpKeyword));
  2400. if (!DoQueryReopen(E2.get()))
  2401. {
  2402. RethrowException(E2.get());
  2403. }
  2404. }
  2405. }
  2406. else
  2407. {
  2408. FileOperationLoopQuery(E, OperationProgress, Message, Flags, SpecialRetry, HelpKeyword);
  2409. }
  2410. }
  2411. //---------------------------------------------------------------------------
  2412. int __fastcall TTerminal::FileOperationLoop(TFileOperationEvent CallBackFunc,
  2413. TFileOperationProgressType * OperationProgress, unsigned int Flags,
  2414. const UnicodeString Message, void * Param1, void * Param2)
  2415. {
  2416. DebugAssert(CallBackFunc);
  2417. int Result;
  2418. FILE_OPERATION_LOOP_BEGIN
  2419. {
  2420. Result = CallBackFunc(Param1, Param2);
  2421. }
  2422. FILE_OPERATION_LOOP_END_EX(Message, Flags);
  2423. return Result;
  2424. }
  2425. //---------------------------------------------------------------------------
  2426. void __fastcall TTerminal::ClearCaches()
  2427. {
  2428. FDirectoryCache->Clear();
  2429. if (FDirectoryChangesCache != NULL)
  2430. {
  2431. FDirectoryChangesCache->Clear();
  2432. }
  2433. if (FCommandSession != NULL)
  2434. {
  2435. FCommandSession->ClearCaches();
  2436. }
  2437. FFileSystem->ClearCaches();
  2438. FEncryptedFileNames.clear();
  2439. FFoldersScannedForEncryptedFiles.clear();
  2440. }
  2441. //---------------------------------------------------------------------------
  2442. void __fastcall TTerminal::ClearCachedFileList(const UnicodeString Path,
  2443. bool SubDirs)
  2444. {
  2445. FDirectoryCache->ClearFileList(Path, SubDirs);
  2446. }
  2447. //---------------------------------------------------------------------------
  2448. void __fastcall TTerminal::AddCachedFileList(TRemoteFileList * FileList)
  2449. {
  2450. FDirectoryCache->AddFileList(FileList);
  2451. }
  2452. //---------------------------------------------------------------------------
  2453. TRemoteFileList * __fastcall TTerminal::DirectoryFileList(const UnicodeString Path, TDateTime Timestamp, bool CanLoad)
  2454. {
  2455. TRemoteFileList * Result = NULL;
  2456. if (UnixSamePath(FFiles->Directory, Path))
  2457. {
  2458. if (Timestamp < FFiles->Timestamp)
  2459. {
  2460. Result = new TRemoteFileList();
  2461. FFiles->DuplicateTo(Result);
  2462. }
  2463. }
  2464. else
  2465. {
  2466. if (FDirectoryCache->HasNewerFileList(Path, Timestamp))
  2467. {
  2468. Result = new TRemoteFileList();
  2469. DebugAlwaysTrue(FDirectoryCache->GetFileList(Path, Result));
  2470. }
  2471. // do not attempt to load file list if there is cached version,
  2472. // only absence of cached version indicates that we consider
  2473. // the directory content obsolete
  2474. else if (CanLoad && !FDirectoryCache->HasFileList(Path))
  2475. {
  2476. Result = new TRemoteFileList();
  2477. Result->Directory = Path;
  2478. try
  2479. {
  2480. ReadDirectory(Result);
  2481. }
  2482. catch(...)
  2483. {
  2484. SAFE_DESTROY(Result);
  2485. throw;
  2486. }
  2487. }
  2488. }
  2489. return Result;
  2490. }
  2491. //---------------------------------------------------------------------------
  2492. void __fastcall TTerminal::SetCurrentDirectory(UnicodeString value)
  2493. {
  2494. DebugAssert(FFileSystem);
  2495. if (value != FFileSystem->CurrentDirectory)
  2496. {
  2497. ChangeDirectory(value);
  2498. }
  2499. }
  2500. //---------------------------------------------------------------------------
  2501. UnicodeString __fastcall TTerminal::GetCurrentDirectory()
  2502. {
  2503. if (FFileSystem != NULL)
  2504. {
  2505. // there's occasional crash when assigning FFileSystem->CurrentDirectory
  2506. // to FCurrentDirectory, splitting the assignment to two statements
  2507. // to locate the crash more closely
  2508. UnicodeString CurrentDirectory = FFileSystem->CurrentDirectory;
  2509. FCurrentDirectory = CurrentDirectory;
  2510. if (FCurrentDirectory.IsEmpty())
  2511. {
  2512. ReadCurrentDirectory();
  2513. }
  2514. }
  2515. return FCurrentDirectory;
  2516. }
  2517. //---------------------------------------------------------------------------
  2518. UnicodeString __fastcall TTerminal::PeekCurrentDirectory()
  2519. {
  2520. if (FFileSystem)
  2521. {
  2522. FCurrentDirectory = FFileSystem->CurrentDirectory;
  2523. }
  2524. return FCurrentDirectory;
  2525. }
  2526. //---------------------------------------------------------------------------
  2527. const TRemoteTokenList * __fastcall TTerminal::GetGroups()
  2528. {
  2529. DebugAssert(FFileSystem);
  2530. LookupUsersGroups();
  2531. return &FGroups;
  2532. }
  2533. //---------------------------------------------------------------------------
  2534. const TRemoteTokenList * __fastcall TTerminal::GetUsers()
  2535. {
  2536. DebugAssert(FFileSystem);
  2537. LookupUsersGroups();
  2538. return &FUsers;
  2539. }
  2540. //---------------------------------------------------------------------------
  2541. const TRemoteTokenList * __fastcall TTerminal::GetMembership()
  2542. {
  2543. DebugAssert(FFileSystem);
  2544. LookupUsersGroups();
  2545. return &FMembership;
  2546. }
  2547. //---------------------------------------------------------------------------
  2548. UnicodeString __fastcall TTerminal::GetUserName() const
  2549. {
  2550. // in future might also be implemented to detect username similar to GetUserGroups
  2551. DebugAssert(FFileSystem != NULL);
  2552. UnicodeString Result = FFileSystem->GetUserName();
  2553. // Is empty also when stored username was used
  2554. if (Result.IsEmpty())
  2555. {
  2556. Result = SessionData->UserNameExpanded;
  2557. }
  2558. return Result;
  2559. }
  2560. //---------------------------------------------------------------------------
  2561. bool __fastcall TTerminal::GetAreCachesEmpty() const
  2562. {
  2563. return FDirectoryCache->IsEmpty &&
  2564. ((FDirectoryChangesCache == NULL) || FDirectoryChangesCache->IsEmpty);
  2565. }
  2566. //---------------------------------------------------------------------------
  2567. void __fastcall TTerminal::DoInitializeLog()
  2568. {
  2569. if (FOnInitializeLog)
  2570. {
  2571. TCallbackGuard Guard(this);
  2572. try
  2573. {
  2574. FOnInitializeLog(this);
  2575. Guard.Verify();
  2576. }
  2577. catch (Exception & E)
  2578. {
  2579. if (!Guard.Verify(&E))
  2580. {
  2581. throw;
  2582. }
  2583. }
  2584. }
  2585. }
  2586. //---------------------------------------------------------------------------
  2587. void __fastcall TTerminal::DoChangeDirectory()
  2588. {
  2589. if (FOnChangeDirectory)
  2590. {
  2591. TCallbackGuard Guard(this);
  2592. try
  2593. {
  2594. FOnChangeDirectory(this);
  2595. Guard.Verify();
  2596. }
  2597. catch (Exception & E)
  2598. {
  2599. if (!Guard.Verify(&E))
  2600. {
  2601. throw;
  2602. }
  2603. }
  2604. }
  2605. }
  2606. //---------------------------------------------------------------------------
  2607. void __fastcall TTerminal::DoReadDirectory(bool ReloadOnly)
  2608. {
  2609. if (FOnReadDirectory)
  2610. {
  2611. TCallbackGuard Guard(this);
  2612. try
  2613. {
  2614. FOnReadDirectory(this, ReloadOnly);
  2615. Guard.Verify();
  2616. }
  2617. catch (Exception & E)
  2618. {
  2619. if (!Guard.Verify(&E))
  2620. {
  2621. throw;
  2622. }
  2623. }
  2624. }
  2625. }
  2626. //---------------------------------------------------------------------------
  2627. void __fastcall TTerminal::DoStartReadDirectory()
  2628. {
  2629. if (FOnStartReadDirectory)
  2630. {
  2631. TCallbackGuard Guard(this);
  2632. try
  2633. {
  2634. FOnStartReadDirectory(this);
  2635. Guard.Verify();
  2636. }
  2637. catch (Exception & E)
  2638. {
  2639. if (!Guard.Verify(&E))
  2640. {
  2641. throw;
  2642. }
  2643. }
  2644. }
  2645. }
  2646. //---------------------------------------------------------------------------
  2647. void __fastcall TTerminal::DoReadDirectoryProgress(int Progress, int ResolvedLinks, bool & Cancel)
  2648. {
  2649. if (FReadingCurrentDirectory && (FOnReadDirectoryProgress != NULL))
  2650. {
  2651. TCallbackGuard Guard(this);
  2652. try
  2653. {
  2654. FOnReadDirectoryProgress(this, Progress, ResolvedLinks, Cancel);
  2655. Guard.Verify();
  2656. }
  2657. catch (Exception & E)
  2658. {
  2659. if (!Guard.Verify(&E))
  2660. {
  2661. throw;
  2662. }
  2663. }
  2664. }
  2665. if (FOnFindingFile != NULL)
  2666. {
  2667. TCallbackGuard Guard(this);
  2668. try
  2669. {
  2670. FOnFindingFile(this, L"", Cancel);
  2671. Guard.Verify();
  2672. }
  2673. catch (Exception & E)
  2674. {
  2675. if (!Guard.Verify(&E))
  2676. {
  2677. throw;
  2678. }
  2679. }
  2680. }
  2681. }
  2682. //---------------------------------------------------------------------------
  2683. bool __fastcall TTerminal::InTransaction()
  2684. {
  2685. return (FInTransaction > 0) && !FSuspendTransaction;
  2686. }
  2687. //---------------------------------------------------------------------------
  2688. void __fastcall TTerminal::BeginTransaction()
  2689. {
  2690. if (FInTransaction == 0)
  2691. {
  2692. FReadCurrentDirectoryPending = false;
  2693. FReadDirectoryPending = false;
  2694. }
  2695. FInTransaction++;
  2696. if (FCommandSession != NULL)
  2697. {
  2698. FCommandSession->BeginTransaction();
  2699. }
  2700. }
  2701. //---------------------------------------------------------------------------
  2702. void __fastcall TTerminal::EndTransaction()
  2703. {
  2704. DoEndTransaction(false);
  2705. }
  2706. //---------------------------------------------------------------------------
  2707. void __fastcall TTerminal::DoEndTransaction(bool Inform)
  2708. {
  2709. if (FInTransaction == 0)
  2710. TerminalError(L"Can't end transaction, not in transaction");
  2711. DebugAssert(FInTransaction > 0);
  2712. FInTransaction--;
  2713. // it connection was closed due to fatal error during transaction, do nothing
  2714. if (Active)
  2715. {
  2716. if (FInTransaction == 0)
  2717. {
  2718. try
  2719. {
  2720. if (FReadCurrentDirectoryPending)
  2721. {
  2722. ReadCurrentDirectory();
  2723. }
  2724. if (FReadDirectoryPending)
  2725. {
  2726. if (Inform)
  2727. {
  2728. DoInformation(LoadStr(STATUS_OPEN_DIRECTORY), true, -1, CurrentDirectory);
  2729. }
  2730. ReadDirectory(!FReadCurrentDirectoryPending);
  2731. }
  2732. }
  2733. __finally
  2734. {
  2735. FReadCurrentDirectoryPending = false;
  2736. FReadDirectoryPending = false;
  2737. }
  2738. }
  2739. }
  2740. if (FCommandSession != NULL)
  2741. {
  2742. FCommandSession->EndTransaction();
  2743. }
  2744. }
  2745. //---------------------------------------------------------------------------
  2746. void __fastcall TTerminal::SetExceptionOnFail(bool value)
  2747. {
  2748. if (value)
  2749. {
  2750. FExceptionOnFail++;
  2751. }
  2752. else
  2753. {
  2754. if (FExceptionOnFail == 0)
  2755. throw Exception(L"ExceptionOnFail is already zero.");
  2756. FExceptionOnFail--;
  2757. }
  2758. if (FCommandSession != NULL)
  2759. {
  2760. FCommandSession->FExceptionOnFail = FExceptionOnFail;
  2761. }
  2762. }
  2763. //---------------------------------------------------------------------------
  2764. bool __fastcall TTerminal::GetExceptionOnFail() const
  2765. {
  2766. return (bool)(FExceptionOnFail > 0);
  2767. }
  2768. //---------------------------------------------------------------------------
  2769. void __fastcall TTerminal::FatalAbort()
  2770. {
  2771. FatalError(NULL, "");
  2772. }
  2773. //---------------------------------------------------------------------------
  2774. void __fastcall TTerminal::FatalError(Exception * E, UnicodeString Msg, UnicodeString HelpKeyword)
  2775. {
  2776. bool SecureShellActive = (FSecureShell != NULL) && FSecureShell->Active;
  2777. if (Active || SecureShellActive)
  2778. {
  2779. // We log this instead of exception handler, because Close() would
  2780. // probably cause exception handler to loose pointer to TShellLog()
  2781. LogEvent(L"Attempt to close connection due to fatal exception:");
  2782. Log->Add(llException, Msg);
  2783. Log->AddException(E);
  2784. if (Active)
  2785. {
  2786. Close();
  2787. }
  2788. // this may happen if failure of authentication of SSH, owned by terminal yet
  2789. // (because the protocol was not decided yet), is detected by us (not by putty).
  2790. // e.g. not verified host key
  2791. if (SecureShellActive)
  2792. {
  2793. FSecureShell->Close();
  2794. }
  2795. }
  2796. if (FCallbackGuard != NULL)
  2797. {
  2798. FCallbackGuard->FatalError(E, Msg, HelpKeyword);
  2799. }
  2800. else
  2801. {
  2802. throw ESshFatal(E, Msg, HelpKeyword);
  2803. }
  2804. }
  2805. //---------------------------------------------------------------------------
  2806. void __fastcall TTerminal::CommandError(Exception * E, const UnicodeString Msg)
  2807. {
  2808. CommandError(E, Msg, 0);
  2809. }
  2810. //---------------------------------------------------------------------------
  2811. unsigned int __fastcall TTerminal::CommandError(Exception * E, const UnicodeString Msg,
  2812. unsigned int Answers, const UnicodeString HelpKeyword)
  2813. {
  2814. // may not be, particularly when TTerminal::Reopen is being called
  2815. // from within OnShowExtendedException handler
  2816. DebugAssert(FCallbackGuard == NULL);
  2817. unsigned int Result = 0;
  2818. if (E && E->InheritsFrom(__classid(EFatal)))
  2819. {
  2820. FatalError(E, Msg, HelpKeyword);
  2821. }
  2822. else if (E && E->InheritsFrom(__classid(EAbort)))
  2823. {
  2824. // resent EAbort exception
  2825. Abort();
  2826. }
  2827. else if (ExceptionOnFail)
  2828. {
  2829. throw ECommand(E, Msg, HelpKeyword);
  2830. }
  2831. else if (!Answers)
  2832. {
  2833. ECommand * ECmd = new ECommand(E, Msg, HelpKeyword);
  2834. try
  2835. {
  2836. HandleExtendedException(ECmd);
  2837. }
  2838. __finally
  2839. {
  2840. delete ECmd;
  2841. }
  2842. }
  2843. else
  2844. {
  2845. // small hack to enable "skip to all" for TRetryOperationLoop
  2846. bool CanSkip = FLAGSET(Answers, qaSkip) && (OperationProgress != NULL);
  2847. if (CanSkip && OperationProgress->SkipToAll)
  2848. {
  2849. Result = qaSkip;
  2850. }
  2851. else
  2852. {
  2853. TQueryParams Params(qpAllowContinueOnError, HelpKeyword);
  2854. TQueryButtonAlias Aliases[1];
  2855. if (CanSkip)
  2856. {
  2857. Aliases[0].Button = qaAll;
  2858. Aliases[0].Alias = LoadStr(SKIP_ALL_BUTTON);
  2859. Params.Aliases = Aliases;
  2860. Params.AliasesCount = LENOF(Aliases);
  2861. Answers |= qaAll;
  2862. }
  2863. Result = QueryUserException(Msg, E, Answers, &Params, qtError);
  2864. if (Result == qaAll)
  2865. {
  2866. DebugAssert(OperationProgress != NULL);
  2867. OperationProgress->SetSkipToAll();
  2868. Result = qaSkip;
  2869. }
  2870. }
  2871. }
  2872. return Result;
  2873. }
  2874. //---------------------------------------------------------------------------
  2875. bool __fastcall TTerminal::HandleException(Exception * E)
  2876. {
  2877. if (ExceptionOnFail)
  2878. {
  2879. return false;
  2880. }
  2881. else
  2882. {
  2883. Log->AddException(E);
  2884. return true;
  2885. }
  2886. }
  2887. //---------------------------------------------------------------------------
  2888. void __fastcall TTerminal::CloseOnCompletion(
  2889. TOnceDoneOperation Operation, const UnicodeString & Message,
  2890. const UnicodeString & TargetLocalPath, const UnicodeString & DestLocalFileName)
  2891. {
  2892. if (FOperationProgressPersistence != NULL)
  2893. {
  2894. DebugAssert(Message.IsEmpty());
  2895. FOperationProgressOnceDoneOperation = Operation;
  2896. }
  2897. else
  2898. {
  2899. Configuration->Usage->Inc(L"ClosesOnCompletion");
  2900. LogEvent(L"Closing session after completed operation (as requested by user)");
  2901. Close();
  2902. throw ESshTerminate(NULL,
  2903. MainInstructions(Message.IsEmpty() ? LoadStr(CLOSED_ON_COMPLETION) : Message),
  2904. Operation, TargetLocalPath, DestLocalFileName);
  2905. }
  2906. }
  2907. //---------------------------------------------------------------------------
  2908. TBatchOverwrite __fastcall TTerminal::EffectiveBatchOverwrite(
  2909. const UnicodeString & SourceFullFileName, const TCopyParamType * CopyParam, int Params, TFileOperationProgressType * OperationProgress, bool Special)
  2910. {
  2911. TBatchOverwrite Result;
  2912. if (Special &&
  2913. (FLAGSET(Params, cpResume) || CopyParam->ResumeTransfer(SourceFullFileName)) &&
  2914. (CopyParam->PartOffset < 0))
  2915. {
  2916. Result = boResume;
  2917. }
  2918. else if (FLAGSET(Params, cpAppend))
  2919. {
  2920. Result = boAppend;
  2921. }
  2922. else if (CopyParam->NewerOnly &&
  2923. (((OperationProgress->Side == osLocal) && IsCapable[fcNewerOnlyUpload]) ||
  2924. (OperationProgress->Side != osLocal)) &&
  2925. DebugAlwaysTrue(CopyParam->PartOffset < 0))
  2926. {
  2927. // no way to change batch overwrite mode when CopyParam->NewerOnly is on
  2928. Result = boOlder;
  2929. }
  2930. else if (FLAGSET(Params, cpNoConfirmation) || !Configuration->ConfirmOverwriting)
  2931. {
  2932. // no way to change batch overwrite mode when overwrite confirmations are off
  2933. DebugAssert(OperationProgress->BatchOverwrite == boNo);
  2934. Result = boAll;
  2935. }
  2936. else
  2937. {
  2938. Result = OperationProgress->BatchOverwrite;
  2939. if (!Special &&
  2940. ((Result == boOlder) || (Result == boAlternateResume) || (Result == boResume)))
  2941. {
  2942. Result = boNo;
  2943. }
  2944. }
  2945. return Result;
  2946. }
  2947. //---------------------------------------------------------------------------
  2948. bool __fastcall TTerminal::CheckRemoteFile(
  2949. const UnicodeString & FileName, const TCopyParamType * CopyParam, int Params, TFileOperationProgressType * OperationProgress)
  2950. {
  2951. bool Result;
  2952. OperationProgress->LockUserSelections();
  2953. try
  2954. {
  2955. Result = (EffectiveBatchOverwrite(FileName, CopyParam, Params, OperationProgress, true) != boAll);
  2956. }
  2957. __finally
  2958. {
  2959. OperationProgress->UnlockUserSelections();
  2960. }
  2961. return Result;
  2962. }
  2963. //---------------------------------------------------------------------------
  2964. unsigned int __fastcall TTerminal::ConfirmFileOverwrite(
  2965. const UnicodeString & SourceFullFileName, const UnicodeString & TargetFileName,
  2966. const TOverwriteFileParams * FileParams, unsigned int Answers, TQueryParams * QueryParams,
  2967. TOperationSide Side, const TCopyParamType * CopyParam, int Params, TFileOperationProgressType * OperationProgress,
  2968. UnicodeString Message)
  2969. {
  2970. unsigned int Result;
  2971. TBatchOverwrite BatchOverwrite;
  2972. bool CanAlternateResume =
  2973. (FileParams != NULL) &&
  2974. (FileParams->DestSize < FileParams->SourceSize) &&
  2975. !OperationProgress->AsciiTransfer;
  2976. OperationProgress->LockUserSelections();
  2977. try
  2978. {
  2979. // duplicated in TSFTPFileSystem::SFTPConfirmOverwrite
  2980. BatchOverwrite = EffectiveBatchOverwrite(SourceFullFileName, CopyParam, Params, OperationProgress, true);
  2981. bool Applicable = true;
  2982. switch (BatchOverwrite)
  2983. {
  2984. case boOlder:
  2985. Applicable = (FileParams != NULL);
  2986. break;
  2987. case boAlternateResume:
  2988. Applicable = CanAlternateResume;
  2989. break;
  2990. case boResume:
  2991. Applicable = CanAlternateResume;
  2992. break;
  2993. }
  2994. if (!Applicable)
  2995. {
  2996. TBatchOverwrite ABatchOverwrite = EffectiveBatchOverwrite(SourceFullFileName, CopyParam, Params, OperationProgress, false);
  2997. DebugAssert(BatchOverwrite != ABatchOverwrite);
  2998. BatchOverwrite = ABatchOverwrite;
  2999. }
  3000. if (BatchOverwrite != boNo)
  3001. {
  3002. LogEvent(1, FORMAT(L"Batch operation mode [%d] is effective", (int(BatchOverwrite))));
  3003. }
  3004. else
  3005. {
  3006. // particularly with parallel transfers, the overall operation can be already cancelled by other parallel operation
  3007. if (OperationProgress->Cancel > csContinue)
  3008. {
  3009. LogEvent(1, L"Transfer cancelled in parallel operation");
  3010. Result = qaCancel;
  3011. }
  3012. else
  3013. {
  3014. if (Message.IsEmpty())
  3015. {
  3016. // Side refers to destination side here
  3017. Message = FMTLOAD((Side == osLocal ? LOCAL_FILE_OVERWRITE2 :
  3018. REMOTE_FILE_OVERWRITE2), (TargetFileName, TargetFileName));
  3019. }
  3020. if (FileParams != NULL)
  3021. {
  3022. Message = FMTLOAD(FILE_OVERWRITE_DETAILS, (Message,
  3023. FormatSize(FileParams->SourceSize),
  3024. DefaultStr(UserModificationStr(FileParams->SourceTimestamp, FileParams->SourcePrecision), LoadStr(TIME_UNKNOWN)),
  3025. FormatSize(FileParams->DestSize),
  3026. DefaultStr(UserModificationStr(FileParams->DestTimestamp, FileParams->DestPrecision), LoadStr(TIME_UNKNOWN))));
  3027. }
  3028. if (DebugAlwaysTrue(QueryParams->HelpKeyword.IsEmpty()))
  3029. {
  3030. QueryParams->HelpKeyword = HELP_OVERWRITE;
  3031. }
  3032. Result = QueryUser(Message, NULL, Answers, QueryParams);
  3033. switch (Result)
  3034. {
  3035. case qaNeverAskAgain:
  3036. Configuration->ConfirmOverwriting = false;
  3037. Result = qaYes;
  3038. break;
  3039. case qaYesToAll:
  3040. BatchOverwrite = boAll;
  3041. break;
  3042. case qaAll:
  3043. BatchOverwrite = boOlder;
  3044. break;
  3045. case qaNoToAll:
  3046. BatchOverwrite = boNone;
  3047. break;
  3048. }
  3049. // we user has not selected another batch overwrite mode,
  3050. // keep the current one. note that we may get here even
  3051. // when batch overwrite was selected already, but it could not be applied
  3052. // to current transfer (see condition above)
  3053. if (BatchOverwrite != boNo)
  3054. {
  3055. OperationProgress->SetBatchOverwrite(BatchOverwrite);
  3056. }
  3057. }
  3058. }
  3059. }
  3060. __finally
  3061. {
  3062. OperationProgress->UnlockUserSelections();
  3063. }
  3064. if (BatchOverwrite != boNo)
  3065. {
  3066. switch (BatchOverwrite)
  3067. {
  3068. case boAll:
  3069. LogEvent(1, L"Overwriting all files");
  3070. Result = qaYes;
  3071. break;
  3072. case boNone:
  3073. LogEvent(1, L"Not overwriting any file");
  3074. Result = qaNo;
  3075. break;
  3076. case boOlder:
  3077. if (FileParams == NULL)
  3078. {
  3079. LogEvent(1, L"Not overwriting due to lack of file information");
  3080. Result = qaNo;
  3081. }
  3082. else
  3083. {
  3084. TModificationFmt Precision = LessDateTimePrecision(FileParams->SourcePrecision, FileParams->DestPrecision);
  3085. TDateTime ReducedSourceTimestamp =
  3086. ReduceDateTimePrecision(FileParams->SourceTimestamp, Precision);
  3087. TDateTime ReducedDestTimestamp =
  3088. ReduceDateTimePrecision(FileParams->DestTimestamp, Precision);
  3089. Result =
  3090. (CompareFileTime(ReducedSourceTimestamp, ReducedDestTimestamp) > 0) ?
  3091. qaYes : qaNo;
  3092. LogEvent(FORMAT(L"Source file timestamp is [%s], destination timestamp is [%s], will%s overwrite",
  3093. (StandardTimestamp(ReducedSourceTimestamp),
  3094. StandardTimestamp(ReducedDestTimestamp),
  3095. ((Result == qaYes) ? L"" : L" not"))));
  3096. }
  3097. break;
  3098. case boAlternateResume:
  3099. DebugAssert(CanAlternateResume);
  3100. LogEvent(1, L"Alternate resume mode");
  3101. Result = qaSkip; // ugh
  3102. break;
  3103. case boAppend:
  3104. LogEvent(1, L"Appending file");
  3105. Result = qaRetry;
  3106. break;
  3107. case boResume:
  3108. LogEvent(1, L"Resuming file transfer");
  3109. Result = qaRetry;
  3110. break;
  3111. }
  3112. }
  3113. return Result;
  3114. }
  3115. //---------------------------------------------------------------------------
  3116. void __fastcall TTerminal::FileModified(const TRemoteFile * File,
  3117. const UnicodeString FileName, bool ClearDirectoryChange)
  3118. {
  3119. UnicodeString ParentDirectory;
  3120. UnicodeString Directory;
  3121. if (SessionData->CacheDirectories || SessionData->CacheDirectoryChanges)
  3122. {
  3123. if ((File != NULL) && (File->Directory != NULL))
  3124. {
  3125. if (File->IsDirectory)
  3126. {
  3127. Directory = File->Directory->FullDirectory + File->FileName;
  3128. }
  3129. ParentDirectory = File->Directory->Directory;
  3130. }
  3131. else if (!FileName.IsEmpty())
  3132. {
  3133. ParentDirectory = UnixExtractFilePath(FileName);
  3134. if (ParentDirectory.IsEmpty())
  3135. {
  3136. ParentDirectory = CurrentDirectory;
  3137. }
  3138. // this case for scripting
  3139. if ((File != NULL) && File->IsDirectory)
  3140. {
  3141. Directory = UnixIncludeTrailingBackslash(ParentDirectory) +
  3142. UnixExtractFileName(File->FileName);
  3143. }
  3144. }
  3145. }
  3146. if (SessionData->CacheDirectories)
  3147. {
  3148. if (!Directory.IsEmpty())
  3149. {
  3150. DirectoryModified(Directory, true);
  3151. }
  3152. if (!ParentDirectory.IsEmpty())
  3153. {
  3154. DirectoryModified(ParentDirectory, false);
  3155. }
  3156. }
  3157. if (SessionData->CacheDirectoryChanges && ClearDirectoryChange)
  3158. {
  3159. if (!Directory.IsEmpty())
  3160. {
  3161. FDirectoryChangesCache->ClearDirectoryChange(Directory);
  3162. FDirectoryChangesCache->ClearDirectoryChangeTarget(Directory);
  3163. }
  3164. }
  3165. }
  3166. //---------------------------------------------------------------------------
  3167. void __fastcall TTerminal::DirectoryModified(const UnicodeString Path, bool SubDirs)
  3168. {
  3169. if (Path.IsEmpty())
  3170. {
  3171. ClearCachedFileList(CurrentDirectory, SubDirs);
  3172. }
  3173. else
  3174. {
  3175. ClearCachedFileList(Path, SubDirs);
  3176. }
  3177. }
  3178. //---------------------------------------------------------------------------
  3179. void __fastcall TTerminal::DirectoryLoaded(TRemoteFileList * FileList)
  3180. {
  3181. AddCachedFileList(FileList);
  3182. }
  3183. //---------------------------------------------------------------------------
  3184. void __fastcall TTerminal::ReloadDirectory()
  3185. {
  3186. if (SessionData->CacheDirectories)
  3187. {
  3188. DirectoryModified(CurrentDirectory, false);
  3189. }
  3190. if (SessionData->CacheDirectoryChanges)
  3191. {
  3192. DebugAssert(FDirectoryChangesCache != NULL);
  3193. FDirectoryChangesCache->ClearDirectoryChange(CurrentDirectory);
  3194. }
  3195. ReadCurrentDirectory();
  3196. FReadCurrentDirectoryPending = false;
  3197. ReadDirectory(true);
  3198. FReadDirectoryPending = false;
  3199. }
  3200. //---------------------------------------------------------------------------
  3201. void __fastcall TTerminal::RefreshDirectory()
  3202. {
  3203. if (!SessionData->CacheDirectories)
  3204. {
  3205. LogEvent(L"Not refreshing directory, caching is off.");
  3206. }
  3207. else if (FDirectoryCache->HasNewerFileList(CurrentDirectory, FFiles->Timestamp))
  3208. {
  3209. // Second parameter was added to allow (rather force) using the cache.
  3210. // Before, the directory was reloaded always, it seems useless,
  3211. // has it any reason?
  3212. ReadDirectory(true, true);
  3213. FReadDirectoryPending = false;
  3214. }
  3215. }
  3216. //---------------------------------------------------------------------------
  3217. void __fastcall TTerminal::EnsureNonExistence(const UnicodeString FileName)
  3218. {
  3219. // if filename doesn't contain path, we check for existence of file
  3220. if ((UnixExtractFileDir(FileName).IsEmpty()) &&
  3221. UnixSamePath(CurrentDirectory, FFiles->Directory))
  3222. {
  3223. TRemoteFile *File = FFiles->FindFile(FileName);
  3224. if (File)
  3225. {
  3226. if (File->IsDirectory) throw ECommand(NULL, FMTLOAD(RENAME_CREATE_DIR_EXISTS, (FileName)));
  3227. else throw ECommand(NULL, FMTLOAD(RENAME_CREATE_FILE_EXISTS, (FileName)));
  3228. }
  3229. }
  3230. }
  3231. //---------------------------------------------------------------------------
  3232. void __fastcall inline TTerminal::LogEvent(const UnicodeString & Str)
  3233. {
  3234. if (Log->Logging)
  3235. {
  3236. Log->Add(llMessage, Str);
  3237. }
  3238. }
  3239. //---------------------------------------------------------------------------
  3240. void __fastcall TTerminal::LogEvent(int Level, const UnicodeString & Str)
  3241. {
  3242. if (Log->Logging && (Configuration->ActualLogProtocol >= Level))
  3243. {
  3244. Log->Add(llMessage, Str);
  3245. }
  3246. }
  3247. //---------------------------------------------------------------------------
  3248. void __fastcall TTerminal::RollbackAction(TSessionAction & Action,
  3249. TFileOperationProgressType * OperationProgress, Exception * E)
  3250. {
  3251. // ESkipFile without "cancel" is file skip,
  3252. // and we do not want to record skipped actions.
  3253. // But ESkipFile with "cancel" is abort and we want to record that.
  3254. // Note that TScpFileSystem modifies the logic of RollbackAction little bit.
  3255. if ((dynamic_cast<ESkipFile *>(E) != NULL) &&
  3256. ((OperationProgress == NULL) ||
  3257. (OperationProgress->Cancel == csContinue)))
  3258. {
  3259. Action.Cancel();
  3260. }
  3261. else
  3262. {
  3263. Action.Rollback(E);
  3264. }
  3265. }
  3266. //---------------------------------------------------------------------------
  3267. void __fastcall TTerminal::DoStartup()
  3268. {
  3269. LogEvent(L"Doing startup conversation with host.");
  3270. BeginTransaction();
  3271. try
  3272. {
  3273. DoInformation(LoadStr(STATUS_STARTUP), true);
  3274. // Make sure that directory would be loaded at last
  3275. FReadCurrentDirectoryPending = true;
  3276. FReadDirectoryPending = AutoReadDirectory;
  3277. FFileSystem->DoStartup();
  3278. LookupUsersGroups();
  3279. if (!SessionData->RemoteDirectory.IsEmpty())
  3280. {
  3281. if (SessionData->UpdateDirectories)
  3282. {
  3283. ExceptionOnFail = true;
  3284. try
  3285. {
  3286. ChangeDirectory(SessionData->RemoteDirectory);
  3287. }
  3288. catch (...)
  3289. {
  3290. if (!Active || SessionData->RequireDirectories)
  3291. {
  3292. ExceptionOnFail = false;
  3293. throw;
  3294. }
  3295. else
  3296. {
  3297. LogEvent(L"Configured initial remote directory cannot be opened, staying in the home directory.");
  3298. }
  3299. }
  3300. ExceptionOnFail = false;
  3301. }
  3302. else
  3303. {
  3304. ChangeDirectory(SessionData->RemoteDirectory);
  3305. }
  3306. }
  3307. }
  3308. __finally
  3309. {
  3310. DoEndTransaction(true);
  3311. }
  3312. LogEvent(L"Startup conversation with host finished.");
  3313. }
  3314. //---------------------------------------------------------------------------
  3315. void __fastcall TTerminal::ReadCurrentDirectory()
  3316. {
  3317. DebugAssert(FFileSystem);
  3318. try
  3319. {
  3320. // reset flag in case we are called externally (like from console dialog)
  3321. FReadCurrentDirectoryPending = false;
  3322. LogEvent(L"Getting current directory name.");
  3323. UnicodeString OldDirectory = FFileSystem->CurrentDirectory;
  3324. FFileSystem->ReadCurrentDirectory();
  3325. ReactOnCommand(fsCurrentDirectory);
  3326. if (SessionData->CacheDirectoryChanges)
  3327. {
  3328. DebugAssert(FDirectoryChangesCache != NULL);
  3329. if (!CurrentDirectory.IsEmpty() && !FLastDirectoryChange.IsEmpty() && (CurrentDirectory != OldDirectory))
  3330. {
  3331. FDirectoryChangesCache->AddDirectoryChange(OldDirectory,
  3332. FLastDirectoryChange, CurrentDirectory);
  3333. }
  3334. // not to breake the cache, if the next directory change would not
  3335. // be initialized by ChangeDirectory(), which sets it
  3336. // (HomeDirectory() particularly)
  3337. FLastDirectoryChange = L"";
  3338. }
  3339. if (OldDirectory != FFileSystem->CurrentDirectory) DoChangeDirectory();
  3340. }
  3341. catch (Exception &E)
  3342. {
  3343. CommandError(&E, LoadStr(READ_CURRENT_DIR_ERROR));
  3344. }
  3345. }
  3346. //---------------------------------------------------------------------------
  3347. void __fastcall TTerminal::ReadDirectory(bool ReloadOnly, bool ForceCache)
  3348. {
  3349. bool LoadedFromCache = false;
  3350. if (SessionData->CacheDirectories && FDirectoryCache->HasFileList(CurrentDirectory))
  3351. {
  3352. if (ReloadOnly && !ForceCache)
  3353. {
  3354. LogEvent(L"Cached directory not reloaded.");
  3355. }
  3356. else
  3357. {
  3358. DoStartReadDirectory();
  3359. try
  3360. {
  3361. LoadedFromCache = FDirectoryCache->GetFileList(CurrentDirectory, FFiles);
  3362. }
  3363. __finally
  3364. {
  3365. DoReadDirectory(ReloadOnly);
  3366. }
  3367. if (LoadedFromCache)
  3368. {
  3369. LogEvent(L"Directory content loaded from cache.");
  3370. }
  3371. else
  3372. {
  3373. LogEvent(L"Cached Directory content has been removed.");
  3374. }
  3375. }
  3376. }
  3377. if (!LoadedFromCache)
  3378. {
  3379. DoStartReadDirectory();
  3380. FReadingCurrentDirectory = true;
  3381. bool Cancel = false; // dummy
  3382. DoReadDirectoryProgress(0, 0, Cancel);
  3383. try
  3384. {
  3385. TRemoteDirectory * Files = new TRemoteDirectory(this, FFiles);
  3386. try
  3387. {
  3388. Files->Directory = CurrentDirectory;
  3389. CustomReadDirectory(Files);
  3390. }
  3391. __finally
  3392. {
  3393. DoReadDirectoryProgress(-1, 0, Cancel);
  3394. FReadingCurrentDirectory = false;
  3395. TRemoteDirectory * OldFiles = FFiles;
  3396. FFiles = Files;
  3397. try
  3398. {
  3399. DoReadDirectory(ReloadOnly);
  3400. }
  3401. __finally
  3402. {
  3403. // delete only after loading new files to dir view,
  3404. // not to destroy the file objects that the view holds
  3405. // (can be issue in multi threaded environment, such as when the
  3406. // terminal is reconnecting in the terminal thread)
  3407. delete OldFiles;
  3408. }
  3409. if (Active)
  3410. {
  3411. if (SessionData->CacheDirectories)
  3412. {
  3413. DirectoryLoaded(FFiles);
  3414. }
  3415. }
  3416. }
  3417. }
  3418. catch (Exception &E)
  3419. {
  3420. CommandError(&E, FmtLoadStr(LIST_DIR_ERROR, ARRAYOFCONST((FFiles->Directory))));
  3421. }
  3422. }
  3423. }
  3424. //---------------------------------------------------------------------------
  3425. UnicodeString __fastcall TTerminal::GetRemoteFileInfo(TRemoteFile * File)
  3426. {
  3427. return
  3428. FORMAT(L"%s;%s;%d;%s;%d;%s;%s;%s;%d",
  3429. (File->FileName, File->Type, File->Size, StandardTimestamp(File->Modification), int(File->ModificationFmt),
  3430. File->Owner.LogText, File->Group.LogText, File->Rights->Text,
  3431. File->Attr));
  3432. }
  3433. //---------------------------------------------------------------------------
  3434. void __fastcall TTerminal::LogRemoteFile(TRemoteFile * File)
  3435. {
  3436. // optimization
  3437. if (Log->Logging)
  3438. {
  3439. LogEvent(GetRemoteFileInfo(File));
  3440. }
  3441. }
  3442. //---------------------------------------------------------------------------
  3443. UnicodeString __fastcall TTerminal::FormatFileDetailsForLog(
  3444. const UnicodeString & FileName, TDateTime Modification, __int64 Size, const TRemoteFile * LinkedFile)
  3445. {
  3446. UnicodeString Result;
  3447. // optimization
  3448. if (Log->Logging)
  3449. {
  3450. Result = FORMAT(L"'%s' [%s] [%s]", (FileName, (Modification != TDateTime() ? StandardTimestamp(Modification) : UnicodeString(L"n/a")), IntToStr(Size)));
  3451. if (LinkedFile != NULL)
  3452. {
  3453. LinkedFile = LinkedFile->Resolve(); // in case it's symlink to symlink
  3454. Result += FORMAT(L" - Link to: %s", (FormatFileDetailsForLog(LinkedFile->FileName, LinkedFile->Modification, LinkedFile->Size, NULL)));
  3455. }
  3456. }
  3457. return Result;
  3458. }
  3459. //---------------------------------------------------------------------------
  3460. void __fastcall TTerminal::LogFileDetails(const UnicodeString & FileName, TDateTime Modification, __int64 Size, const TRemoteFile * LinkedFile)
  3461. {
  3462. // optimization
  3463. if (Log->Logging)
  3464. {
  3465. LogEvent(FORMAT("File: %s", (FormatFileDetailsForLog(FileName, Modification, Size, LinkedFile))));
  3466. }
  3467. }
  3468. //---------------------------------------------------------------------------
  3469. void __fastcall TTerminal::LogFileDone(
  3470. TFileOperationProgressType * OperationProgress, const UnicodeString & DestFileName,
  3471. TTransferSessionAction & Action)
  3472. {
  3473. if (FDestFileName.IsEmpty())
  3474. {
  3475. FDestFileName = DestFileName;
  3476. }
  3477. else
  3478. {
  3479. FMultipleDestinationFiles = true;
  3480. }
  3481. __int64 Size = OperationProgress->TransferredSize;
  3482. // optimization
  3483. if (Log->Logging)
  3484. {
  3485. LogEvent(FORMAT("Transfer done: '%s' => '%s' [%s]", (OperationProgress->FullFileName, DestFileName, IntToStr(Size))));
  3486. }
  3487. Action.Size(Size);
  3488. }
  3489. //---------------------------------------------------------------------------
  3490. void __fastcall TTerminal::CustomReadDirectory(TRemoteFileList * FileList)
  3491. {
  3492. DebugAssert(FileList);
  3493. DebugAssert(FFileSystem);
  3494. // To match FTP upload/download, we also limit directory listing.
  3495. // For simplicity, we limit it unconditionally, for all protocols for any kind of errors.
  3496. bool FileTransferAny = false;
  3497. TRobustOperationLoop RobustLoop(this, OperationProgress, &FileTransferAny);
  3498. do
  3499. {
  3500. try
  3501. {
  3502. // Record even an attempt, to avoid listing a directory over and over again, when it is not readable actually
  3503. if (IsEncryptingFiles())
  3504. {
  3505. FFoldersScannedForEncryptedFiles.insert(FileList->Directory);
  3506. }
  3507. FFileSystem->ReadDirectory(FileList);
  3508. }
  3509. catch (Exception & E)
  3510. {
  3511. // Do not retry for initial listing of directory,
  3512. // we instead retry whole connection attempt,
  3513. // what would be done anyway (but Open is not ready for recursion).
  3514. if ((FOpening > 0) ||
  3515. !RobustLoop.TryReopen(E))
  3516. {
  3517. throw;
  3518. }
  3519. }
  3520. }
  3521. while (RobustLoop.Retry());
  3522. if (Log->Logging && (Configuration->ActualLogProtocol >= 0))
  3523. {
  3524. for (int Index = 0; Index < FileList->Count; Index++)
  3525. {
  3526. LogRemoteFile(FileList->Files[Index]);
  3527. }
  3528. }
  3529. ReactOnCommand(fsListDirectory);
  3530. }
  3531. //---------------------------------------------------------------------------
  3532. TRemoteFileList * __fastcall TTerminal::ReadDirectoryListing(UnicodeString Directory, const TFileMasks & Mask)
  3533. {
  3534. TRemoteFileList * FileList;
  3535. TRetryOperationLoop RetryLoop(this);
  3536. do
  3537. {
  3538. FileList = NULL;
  3539. TLsSessionAction Action(ActionLog, AbsolutePath(Directory, true));
  3540. try
  3541. {
  3542. FileList = DoReadDirectoryListing(Directory, false);
  3543. if (FileList != NULL)
  3544. {
  3545. int Index = 0;
  3546. while (Index < FileList->Count)
  3547. {
  3548. TRemoteFile * File = FileList->Files[Index];
  3549. TFileMasks::TParams Params;
  3550. Params.Size = File->Resolve()->Size;
  3551. Params.Modification = File->Modification;
  3552. if (!Mask.MatchesFileName(File->FileName, false, &Params))
  3553. {
  3554. FileList->Delete(Index);
  3555. }
  3556. else
  3557. {
  3558. Index++;
  3559. }
  3560. }
  3561. Action.FileList(FileList);
  3562. }
  3563. }
  3564. catch(Exception & E)
  3565. {
  3566. RetryLoop.Error(E, Action);
  3567. }
  3568. }
  3569. while (RetryLoop.Retry());
  3570. return FileList;
  3571. }
  3572. //---------------------------------------------------------------------------
  3573. TRemoteFile * __fastcall TTerminal::ReadFileListing(UnicodeString Path)
  3574. {
  3575. TRemoteFile * File;
  3576. TRetryOperationLoop RetryLoop(this);
  3577. do
  3578. {
  3579. File = NULL;
  3580. TStatSessionAction Action(ActionLog, AbsolutePath(Path, true));
  3581. try
  3582. {
  3583. // reset caches
  3584. AnnounceFileListOperation();
  3585. File = ReadFile(Path);
  3586. Action.File(File);
  3587. }
  3588. catch(Exception & E)
  3589. {
  3590. RetryLoop.Error(E, Action);
  3591. }
  3592. }
  3593. while (RetryLoop.Retry());
  3594. return File;
  3595. }
  3596. //---------------------------------------------------------------------------
  3597. TRemoteFileList * __fastcall TTerminal::CustomReadDirectoryListing(UnicodeString Directory, bool UseCache)
  3598. {
  3599. TRemoteFileList * FileList = NULL;
  3600. TRetryOperationLoop RetryLoop(this);
  3601. do
  3602. {
  3603. try
  3604. {
  3605. FileList = DoReadDirectoryListing(Directory, UseCache);
  3606. }
  3607. catch(Exception & E)
  3608. {
  3609. RetryLoop.Error(E);
  3610. }
  3611. }
  3612. while (RetryLoop.Retry());
  3613. return FileList;
  3614. }
  3615. //---------------------------------------------------------------------------
  3616. TRemoteFileList * __fastcall TTerminal::DoReadDirectoryListing(UnicodeString Directory, bool UseCache)
  3617. {
  3618. TRemoteFileList * FileList = new TRemoteFileList();
  3619. try
  3620. {
  3621. bool Cache = UseCache && SessionData->CacheDirectories;
  3622. bool LoadedFromCache = Cache && FDirectoryCache->HasFileList(Directory);
  3623. if (LoadedFromCache)
  3624. {
  3625. LoadedFromCache = FDirectoryCache->GetFileList(Directory, FileList);
  3626. }
  3627. if (!LoadedFromCache)
  3628. {
  3629. FileList->Directory = Directory;
  3630. ExceptionOnFail = true;
  3631. try
  3632. {
  3633. ReadDirectory(FileList);
  3634. }
  3635. __finally
  3636. {
  3637. ExceptionOnFail = false;
  3638. }
  3639. if (Cache)
  3640. {
  3641. AddCachedFileList(FileList);
  3642. }
  3643. }
  3644. }
  3645. catch(...)
  3646. {
  3647. delete FileList;
  3648. throw;
  3649. }
  3650. return FileList;
  3651. }
  3652. //---------------------------------------------------------------------------
  3653. bool __fastcall TTerminal::DeleteContentsIfDirectory(
  3654. const UnicodeString & FileName, const TRemoteFile * File, int Params, TRmSessionAction & Action)
  3655. {
  3656. bool Dir = (File != NULL) && File->IsDirectory && CanRecurseToDirectory(File);
  3657. if (Dir && FLAGCLEAR(Params, dfNoRecursive))
  3658. {
  3659. try
  3660. {
  3661. ProcessDirectory(FileName, DeleteFile, &Params);
  3662. }
  3663. catch(...)
  3664. {
  3665. Action.Cancel();
  3666. throw;
  3667. }
  3668. }
  3669. return Dir && !File->IsSymLink;
  3670. }
  3671. //---------------------------------------------------------------------------
  3672. void __fastcall TTerminal::ProcessDirectory(const UnicodeString DirName,
  3673. TProcessFileEvent CallBackFunc, void * Param, bool UseCache, bool IgnoreErrors)
  3674. {
  3675. TRemoteFileList * FileList = NULL;
  3676. if (IgnoreErrors)
  3677. {
  3678. ExceptionOnFail = true;
  3679. try
  3680. {
  3681. try
  3682. {
  3683. FileList = CustomReadDirectoryListing(DirName, UseCache);
  3684. }
  3685. catch(...)
  3686. {
  3687. if (!Active)
  3688. {
  3689. throw;
  3690. }
  3691. }
  3692. }
  3693. __finally
  3694. {
  3695. ExceptionOnFail = false;
  3696. }
  3697. }
  3698. else
  3699. {
  3700. FileList = CustomReadDirectoryListing(DirName, UseCache);
  3701. }
  3702. // skip if directory listing fails and user selects "skip"
  3703. if (FileList)
  3704. {
  3705. try
  3706. {
  3707. UnicodeString Directory = UnixIncludeTrailingBackslash(DirName);
  3708. TRemoteFile * File;
  3709. for (int Index = 0; Index < FileList->Count; Index++)
  3710. {
  3711. File = FileList->Files[Index];
  3712. if (IsRealFile(File->FileName))
  3713. {
  3714. CallBackFunc(Directory + File->FileName, File, Param);
  3715. // We should catch ESkipFile here as we do in ProcessFiles.
  3716. // Now we have to handle ESkipFile in every callback implementation.
  3717. }
  3718. }
  3719. }
  3720. __finally
  3721. {
  3722. delete FileList;
  3723. }
  3724. }
  3725. }
  3726. //---------------------------------------------------------------------------
  3727. void __fastcall TTerminal::ReadDirectory(TRemoteFileList * FileList)
  3728. {
  3729. try
  3730. {
  3731. CustomReadDirectory(FileList);
  3732. }
  3733. catch (Exception &E)
  3734. {
  3735. CommandError(&E, FmtLoadStr(LIST_DIR_ERROR, ARRAYOFCONST((FileList->Directory))));
  3736. }
  3737. }
  3738. //---------------------------------------------------------------------------
  3739. void __fastcall TTerminal::ReadSymlink(TRemoteFile * SymlinkFile,
  3740. TRemoteFile *& File)
  3741. {
  3742. DebugAssert(FFileSystem);
  3743. try
  3744. {
  3745. LogEvent(FORMAT(L"Reading symlink \"%s\".", (SymlinkFile->FileName)));
  3746. FFileSystem->ReadSymlink(SymlinkFile, File);
  3747. ReactOnCommand(fsReadSymlink);
  3748. }
  3749. catch (Exception &E)
  3750. {
  3751. CommandError(&E, FMTLOAD(READ_SYMLINK_ERROR, (SymlinkFile->FileName)));
  3752. }
  3753. }
  3754. //---------------------------------------------------------------------------
  3755. TRemoteFile * TTerminal::ReadFile(const UnicodeString & FileName)
  3756. {
  3757. DebugAssert(FFileSystem);
  3758. std::unique_ptr<TRemoteFile> File;
  3759. try
  3760. {
  3761. LogEvent(FORMAT(L"Listing file \"%s\".", (FileName)));
  3762. TRemoteFile * AFile = NULL;
  3763. FFileSystem->ReadFile(FileName, AFile);
  3764. File.reset(AFile);
  3765. ReactOnCommand(fsListFile);
  3766. LogRemoteFile(File.get());
  3767. }
  3768. catch (Exception &E)
  3769. {
  3770. File.reset(NULL);
  3771. CommandError(&E, FMTLOAD(CANT_GET_ATTRS, (FileName)));
  3772. }
  3773. return File.release();
  3774. }
  3775. //---------------------------------------------------------------------------
  3776. TRemoteFile * TTerminal::TryReadFile(const UnicodeString & FileName)
  3777. {
  3778. TRemoteFile * File;
  3779. try
  3780. {
  3781. ExceptionOnFail = true;
  3782. try
  3783. {
  3784. File = ReadFile(UnixExcludeTrailingBackslash(FileName));
  3785. }
  3786. __finally
  3787. {
  3788. ExceptionOnFail = false;
  3789. }
  3790. }
  3791. catch(...)
  3792. {
  3793. if (Active)
  3794. {
  3795. File = NULL;
  3796. }
  3797. else
  3798. {
  3799. throw;
  3800. }
  3801. }
  3802. return File;
  3803. }
  3804. //---------------------------------------------------------------------------
  3805. bool TTerminal::FileExists(const UnicodeString & FileName)
  3806. {
  3807. std::unique_ptr<TRemoteFile> File(TryReadFile(FileName));
  3808. return (File.get() != NULL);
  3809. }
  3810. //---------------------------------------------------------------------------
  3811. void __fastcall TTerminal::AnnounceFileListOperation()
  3812. {
  3813. FFileSystem->AnnounceFileListOperation();
  3814. }
  3815. //---------------------------------------------------------------------------
  3816. void __fastcall TTerminal::OperationFinish(
  3817. TFileOperationProgressType * Progress, const void * /*Item*/, const UnicodeString & FileName,
  3818. bool Success, TOnceDoneOperation & OnceDoneOperation)
  3819. {
  3820. Progress->Finish(FileName, Success, OnceDoneOperation);
  3821. }
  3822. //---------------------------------------------------------------------------
  3823. void __fastcall TTerminal::OperationStart(
  3824. TFileOperationProgressType & Progress, TFileOperation Operation, TOperationSide Side, int Count)
  3825. {
  3826. OperationStart(Progress, Operation, Side, Count, false, UnicodeString(), 0, odoIdle);
  3827. }
  3828. //---------------------------------------------------------------------------
  3829. void __fastcall TTerminal::OperationStart(
  3830. TFileOperationProgressType & Progress, TFileOperation Operation, TOperationSide Side, int Count,
  3831. bool Temp, const UnicodeString & Directory, unsigned long CPSLimit, TOnceDoneOperation OnceDoneOperation)
  3832. {
  3833. if (FOperationProgressPersistence != NULL)
  3834. {
  3835. Progress.Restore(*FOperationProgressPersistence);
  3836. }
  3837. Progress.Start(Operation, Side, Count, Temp, Directory, CPSLimit, OnceDoneOperation);
  3838. DebugAssert(FOperationProgress == NULL);
  3839. FOperationProgress = &Progress;
  3840. }
  3841. //---------------------------------------------------------------------------
  3842. void __fastcall TTerminal::OperationStop(TFileOperationProgressType & Progress)
  3843. {
  3844. DebugAssert(FOperationProgress == &Progress);
  3845. if (FOperationProgressPersistence != NULL)
  3846. {
  3847. Progress.Store(*FOperationProgressPersistence);
  3848. }
  3849. FOperationProgress = NULL;
  3850. Progress.Stop();
  3851. }
  3852. //---------------------------------------------------------------------------
  3853. bool __fastcall TTerminal::ProcessFiles(TStrings * FileList,
  3854. TFileOperation Operation, TProcessFileEvent ProcessFile, void * Param,
  3855. TOperationSide Side, bool Ex)
  3856. {
  3857. DebugAssert(FileList);
  3858. bool Result = false;
  3859. TOnceDoneOperation OnceDoneOperation = odoIdle;
  3860. try
  3861. {
  3862. TFileOperationProgressType Progress(&DoProgress, &DoFinished);
  3863. OperationStart(Progress, Operation, Side, FileList->Count);
  3864. try
  3865. {
  3866. if (Side == osRemote)
  3867. {
  3868. DebugAssert(FFileSystem != NULL);
  3869. BeginTransaction();
  3870. }
  3871. try
  3872. {
  3873. int Index = 0;
  3874. UnicodeString FileName;
  3875. bool Success;
  3876. while ((Index < FileList->Count) && (Progress.Cancel == csContinue))
  3877. {
  3878. FileName = FileList->Strings[Index];
  3879. TRemoteFile * File = reinterpret_cast<TRemoteFile *>(FileList->Objects[Index]);
  3880. try
  3881. {
  3882. try
  3883. {
  3884. Success = false;
  3885. if (!Ex)
  3886. {
  3887. ProcessFile(FileName, File, Param);
  3888. }
  3889. else
  3890. {
  3891. // not used anymore
  3892. TProcessFileEventEx ProcessFileEx = (TProcessFileEventEx)ProcessFile;
  3893. ProcessFileEx(FileName, File, Param, Index);
  3894. }
  3895. Success = true;
  3896. }
  3897. __finally
  3898. {
  3899. OperationFinish(&Progress, File, FileName, Success, OnceDoneOperation);
  3900. }
  3901. }
  3902. catch(ESkipFile & E)
  3903. {
  3904. TSuspendFileOperationProgress Suspend(OperationProgress);
  3905. if (!HandleException(&E))
  3906. {
  3907. throw;
  3908. }
  3909. }
  3910. Index++;
  3911. }
  3912. }
  3913. __finally
  3914. {
  3915. if (Side == osRemote)
  3916. {
  3917. EndTransaction();
  3918. }
  3919. }
  3920. if (Progress.Cancel == csContinue)
  3921. {
  3922. Result = true;
  3923. }
  3924. }
  3925. __finally
  3926. {
  3927. OperationStop(Progress);
  3928. }
  3929. }
  3930. catch (...)
  3931. {
  3932. OnceDoneOperation = odoIdle;
  3933. // this was missing here. was it by purpose?
  3934. // without it any error message is lost
  3935. throw;
  3936. }
  3937. if (OnceDoneOperation != odoIdle)
  3938. {
  3939. CloseOnCompletion(OnceDoneOperation);
  3940. }
  3941. return Result;
  3942. }
  3943. //---------------------------------------------------------------------------
  3944. // not used anymore
  3945. bool __fastcall TTerminal::ProcessFilesEx(TStrings * FileList, TFileOperation Operation,
  3946. TProcessFileEventEx ProcessFile, void * Param, TOperationSide Side)
  3947. {
  3948. return ProcessFiles(FileList, Operation, TProcessFileEvent(ProcessFile),
  3949. Param, Side, true);
  3950. }
  3951. //---------------------------------------------------------------------------
  3952. TStrings * __fastcall TTerminal::GetFixedPaths()
  3953. {
  3954. DebugAssert(FFileSystem != NULL);
  3955. return FFileSystem->GetFixedPaths();
  3956. }
  3957. //---------------------------------------------------------------------------
  3958. bool __fastcall TTerminal::GetResolvingSymlinks()
  3959. {
  3960. return SessionData->ResolveSymlinks && IsCapable[fcResolveSymlink];
  3961. }
  3962. //---------------------------------------------------------------------------
  3963. TUsableCopyParamAttrs __fastcall TTerminal::UsableCopyParamAttrs(int Params)
  3964. {
  3965. TUsableCopyParamAttrs Result;
  3966. Result.General =
  3967. FLAGMASK(!IsCapable[fcTextMode], cpaNoTransferMode) |
  3968. FLAGMASK(!IsCapable[fcModeChanging], cpaNoRights) |
  3969. FLAGMASK(!IsCapable[fcModeChanging], cpaNoPreserveReadOnly) |
  3970. FLAGMASK(FLAGSET(Params, cpDelete), cpaNoClearArchive) |
  3971. FLAGMASK(!IsCapable[fcIgnorePermErrors], cpaNoIgnorePermErrors) |
  3972. // the following three are never supported for download,
  3973. // so when they are not supported for upload too,
  3974. // set them in General flags, so that they do not get enabled on
  3975. // Synchronize dialog.
  3976. FLAGMASK(!IsCapable[fcModeChangingUpload], cpaNoRights) |
  3977. FLAGMASK(!IsCapable[fcRemoveCtrlZUpload], cpaNoRemoveCtrlZ) |
  3978. FLAGMASK(!IsCapable[fcRemoveBOMUpload], cpaNoRemoveBOM) |
  3979. FLAGMASK(!IsCapable[fcPreservingTimestampDirs], cpaNoPreserveTimeDirs) |
  3980. FLAGMASK(!IsCapable[fcResumeSupport], cpaNoResumeSupport) |
  3981. FLAGMASK(!IsEncryptingFiles(), cpaNoEncryptNewFiles);
  3982. Result.Download = Result.General | cpaNoClearArchive |
  3983. cpaNoIgnorePermErrors |
  3984. // May be already set in General flags, but it's unconditional here
  3985. cpaNoRights | cpaNoRemoveCtrlZ | cpaNoRemoveBOM | cpaNoEncryptNewFiles;
  3986. Result.Upload = Result.General | cpaNoPreserveReadOnly |
  3987. FLAGMASK(!IsCapable[fcPreservingTimestampUpload], cpaNoPreserveTime);
  3988. return Result;
  3989. }
  3990. //---------------------------------------------------------------------------
  3991. bool __fastcall TTerminal::IsRecycledFile(UnicodeString FileName)
  3992. {
  3993. bool Result = !SessionData->RecycleBinPath.IsEmpty();
  3994. if (Result)
  3995. {
  3996. UnicodeString Path = UnixExtractFilePath(FileName);
  3997. if (Path.IsEmpty())
  3998. {
  3999. Path = CurrentDirectory;
  4000. }
  4001. Result = UnixSamePath(Path, SessionData->RecycleBinPath);
  4002. }
  4003. return Result;
  4004. }
  4005. //---------------------------------------------------------------------------
  4006. bool __fastcall TTerminal::RecycleFile(const UnicodeString & AFileName, const TRemoteFile * File)
  4007. {
  4008. UnicodeString FileName = AFileName;
  4009. if (FileName.IsEmpty())
  4010. {
  4011. DebugAssert(File != NULL);
  4012. FileName = File->FileName;
  4013. }
  4014. bool Result;
  4015. if (IsRecycledFile(FileName))
  4016. {
  4017. Result = true;
  4018. }
  4019. else
  4020. {
  4021. LogEvent(FORMAT(L"Moving file \"%s\" to remote recycle bin '%s'.",
  4022. (FileName, SessionData->RecycleBinPath)));
  4023. TMoveFileParams Params;
  4024. Params.Target = SessionData->RecycleBinPath;
  4025. Params.FileMask = FORMAT(L"*-%s.*", (FormatDateTime(L"yyyymmdd-hhnnss", Now())));
  4026. Params.DontOverwrite = false;
  4027. Result = DoMoveFile(FileName, File, &Params);
  4028. if (Result && (OperationProgress != NULL) && (OperationProgress->Operation == foDelete))
  4029. {
  4030. OperationProgress->Succeeded();
  4031. }
  4032. }
  4033. return Result;
  4034. }
  4035. //---------------------------------------------------------------------------
  4036. bool __fastcall TTerminal::TryStartOperationWithFile(
  4037. const UnicodeString & FileName, TFileOperation Operation1, TFileOperation Operation2)
  4038. {
  4039. bool Result = true;
  4040. if ((OperationProgress != NULL) &&
  4041. ((OperationProgress->Operation == Operation1) ||
  4042. ((Operation2 != foNone) && (OperationProgress->Operation == Operation2))))
  4043. {
  4044. if (OperationProgress->Cancel != csContinue)
  4045. {
  4046. Result = false;
  4047. }
  4048. else
  4049. {
  4050. OperationProgress->SetFile(FileName);
  4051. }
  4052. }
  4053. return Result;
  4054. }
  4055. //---------------------------------------------------------------------------
  4056. void __fastcall TTerminal::StartOperationWithFile(
  4057. const UnicodeString & FileName, TFileOperation Operation1, TFileOperation Operation2)
  4058. {
  4059. if (!TryStartOperationWithFile(FileName, Operation1, Operation2))
  4060. {
  4061. Abort();
  4062. }
  4063. }
  4064. //---------------------------------------------------------------------------
  4065. void __fastcall TTerminal::DeleteFile(UnicodeString FileName,
  4066. const TRemoteFile * File, void * AParams)
  4067. {
  4068. if (FileName.IsEmpty() && File)
  4069. {
  4070. FileName = File->FileName;
  4071. }
  4072. StartOperationWithFile(FileName, foDelete);
  4073. int Params = (AParams != NULL) ? *((int*)AParams) : 0;
  4074. bool Recycle =
  4075. FLAGCLEAR(Params, dfForceDelete) &&
  4076. (SessionData->DeleteToRecycleBin != FLAGSET(Params, dfAlternative)) &&
  4077. !SessionData->RecycleBinPath.IsEmpty();
  4078. if (Recycle && !IsRecycledFile(FileName))
  4079. {
  4080. RecycleFile(FileName, File);
  4081. }
  4082. else
  4083. {
  4084. DoDeleteFile(FFileSystem, FileName, File, Params);
  4085. }
  4086. }
  4087. //---------------------------------------------------------------------------
  4088. void __fastcall TTerminal::DoDeleteFile(
  4089. TCustomFileSystem * FileSystem, const UnicodeString & FileName, const TRemoteFile * File, int Params)
  4090. {
  4091. LogEvent(FORMAT(L"Deleting file \"%s\".", (FileName)));
  4092. FileModified(File, FileName, true);
  4093. TRetryOperationLoop RetryLoop(this);
  4094. do
  4095. {
  4096. TRmSessionAction Action(ActionLog, AbsolutePath(FileName, true));
  4097. try
  4098. {
  4099. DebugAssert(FileSystem != NULL);
  4100. // 'File' parameter: SFTPFileSystem needs to know if file is file or directory
  4101. FileSystem->DeleteFile(FileName, File, Params, Action);
  4102. if ((OperationProgress != NULL) && (OperationProgress->Operation == foDelete))
  4103. {
  4104. OperationProgress->Succeeded();
  4105. }
  4106. }
  4107. catch(Exception & E)
  4108. {
  4109. RetryLoop.Error(E, Action, FMTLOAD(DELETE_FILE_ERROR, (FileName)));
  4110. }
  4111. }
  4112. while (RetryLoop.Retry());
  4113. // Forget if file was or was not encrypted and use user preferences, if we ever recreate it.
  4114. FEncryptedFileNames.erase(AbsolutePath(FileName, true));
  4115. ReactOnCommand(fsDeleteFile);
  4116. }
  4117. //---------------------------------------------------------------------------
  4118. bool __fastcall TTerminal::DeleteFiles(TStrings * FilesToDelete, int Params)
  4119. {
  4120. TValueRestorer<bool> UseBusyCursorRestorer(FUseBusyCursor, false);
  4121. // TODO: avoid resolving symlinks while reading subdirectories.
  4122. // Resolving does not work anyway for relative symlinks in subdirectories
  4123. // (at least for SFTP).
  4124. return ProcessFiles(FilesToDelete, foDelete, DeleteFile, &Params);
  4125. }
  4126. //---------------------------------------------------------------------------
  4127. void __fastcall TTerminal::DeleteLocalFile(UnicodeString FileName,
  4128. const TRemoteFile * /*File*/, void * Params)
  4129. {
  4130. StartOperationWithFile(FileName, foDelete);
  4131. int Deleted;
  4132. if (OnDeleteLocalFile == NULL)
  4133. {
  4134. Deleted = RecursiveDeleteFileChecked(FileName, false);
  4135. }
  4136. else
  4137. {
  4138. OnDeleteLocalFile(FileName, FLAGSET(*((int*)Params), dfAlternative), Deleted);
  4139. }
  4140. if (DebugAlwaysTrue((OperationProgress != NULL) && (OperationProgress->Operation == foDelete)))
  4141. {
  4142. OperationProgress->Succeeded(Deleted);
  4143. }
  4144. }
  4145. //---------------------------------------------------------------------------
  4146. bool __fastcall TTerminal::DeleteLocalFiles(TStrings * FileList, int Params)
  4147. {
  4148. return ProcessFiles(FileList, foDelete, DeleteLocalFile, &Params, osLocal);
  4149. }
  4150. //---------------------------------------------------------------------------
  4151. void __fastcall TTerminal::CustomCommandOnFile(UnicodeString FileName,
  4152. const TRemoteFile * File, void * AParams)
  4153. {
  4154. TCustomCommandParams * Params = ((TCustomCommandParams *)AParams);
  4155. if (FileName.IsEmpty() && File)
  4156. {
  4157. FileName = File->FileName;
  4158. }
  4159. StartOperationWithFile(FileName, foCustomCommand);
  4160. LogEvent(FORMAT(L"Executing custom command \"%s\" (%d) on file \"%s\".",
  4161. (Params->Command, Params->Params, FileName)));
  4162. FileModified(File, FileName);
  4163. DoCustomCommandOnFile(FileName, File, Params->Command, Params->Params,
  4164. Params->OutputEvent);
  4165. ReactOnCommand(fsAnyCommand);
  4166. }
  4167. //---------------------------------------------------------------------------
  4168. void TTerminal::PrepareCommandSession(bool NeedCurrentDirectory)
  4169. {
  4170. DebugAssert(CommandSessionOpened);
  4171. DebugAssert(FCommandSession->FSProtocol == cfsSCP);
  4172. LogEvent(L"Performing operation on command session.");
  4173. if (FCommandSession->CurrentDirectory != CurrentDirectory)
  4174. {
  4175. FCommandSession->CurrentDirectory = CurrentDirectory;
  4176. // We are likely in transaction, so ReadCurrentDirectory won't get called
  4177. // until transaction ends. But we need to know CurrentDirectory to
  4178. // expand !/ pattern when in CustomCommandOnFiles.
  4179. // Doing this only, when current directory of the main and secondary shell differs,
  4180. // what would be the case before the first file in transaction.
  4181. // Otherwise we would be reading pwd before every time as the
  4182. // CustomCommandOnFile on its own sets FReadCurrentDirectoryPending
  4183. if (NeedCurrentDirectory && FCommandSession->FReadCurrentDirectoryPending)
  4184. {
  4185. FCommandSession->ReadCurrentDirectory();
  4186. }
  4187. }
  4188. }
  4189. //---------------------------------------------------------------------------
  4190. TCustomFileSystem * TTerminal::GetFileSystemForCapability(TFSCapability Capability, bool NeedCurrentDirectory)
  4191. {
  4192. TCustomFileSystem * Result;
  4193. if (IsCapable[Capability])
  4194. {
  4195. DebugAssert(FFileSystem != NULL);
  4196. Result = FFileSystem;
  4197. }
  4198. else
  4199. {
  4200. PrepareCommandSession(NeedCurrentDirectory);
  4201. Result = FCommandSession->FFileSystem;
  4202. }
  4203. return Result;
  4204. }
  4205. //---------------------------------------------------------------------------
  4206. void __fastcall TTerminal::DoCustomCommandOnFile(UnicodeString FileName,
  4207. const TRemoteFile * File, UnicodeString Command, int Params,
  4208. TCaptureOutputEvent OutputEvent)
  4209. {
  4210. TRetryOperationLoop RetryLoop(this);
  4211. do
  4212. {
  4213. try
  4214. {
  4215. TCustomFileSystem * FileSystem = GetFileSystemForCapability(fcAnyCommand, true);
  4216. DebugAssert((FileSystem != FFileSystem) || IsCapable[fcShellAnyCommand]);
  4217. FileSystem->CustomCommandOnFile(FileName, File, Command, Params, OutputEvent);
  4218. }
  4219. catch(Exception & E)
  4220. {
  4221. RetryLoop.Error(E, FMTLOAD(CUSTOM_COMMAND_ERROR, (Command, FileName)));
  4222. }
  4223. }
  4224. while (RetryLoop.Retry());
  4225. }
  4226. //---------------------------------------------------------------------------
  4227. void __fastcall TTerminal::CustomCommandOnFiles(UnicodeString Command,
  4228. int Params, TStrings * Files, TCaptureOutputEvent OutputEvent)
  4229. {
  4230. if (!TRemoteCustomCommand().IsFileListCommand(Command))
  4231. {
  4232. TCustomCommandParams AParams;
  4233. AParams.Command = Command;
  4234. AParams.Params = Params;
  4235. AParams.OutputEvent = OutputEvent;
  4236. ProcessFiles(Files, foCustomCommand, CustomCommandOnFile, &AParams);
  4237. }
  4238. else
  4239. {
  4240. UnicodeString FileList;
  4241. for (int i = 0; i < Files->Count; i++)
  4242. {
  4243. TRemoteFile * File = static_cast<TRemoteFile *>(Files->Objects[i]);
  4244. bool Dir = File->IsDirectory && CanRecurseToDirectory(File);
  4245. if (!Dir || FLAGSET(Params, ccApplyToDirectories))
  4246. {
  4247. AddToShellFileListCommandLine(FileList, Files->Strings[i]);
  4248. }
  4249. }
  4250. TCustomCommandData Data(this);
  4251. UnicodeString Cmd =
  4252. TRemoteCustomCommand(Data, CurrentDirectory, L"", FileList).
  4253. Complete(Command, true);
  4254. if (!DoOnCustomCommand(Cmd))
  4255. {
  4256. DoAnyCommand(Cmd, OutputEvent, NULL);
  4257. }
  4258. }
  4259. }
  4260. //---------------------------------------------------------------------------
  4261. bool __fastcall TTerminal::DoOnCustomCommand(const UnicodeString & Command)
  4262. {
  4263. bool Result = false;
  4264. if (FOnCustomCommand != NULL)
  4265. {
  4266. FOnCustomCommand(this, Command, Result);
  4267. }
  4268. return Result;
  4269. }
  4270. //---------------------------------------------------------------------------
  4271. void __fastcall TTerminal::ChangeFileProperties(UnicodeString FileName,
  4272. const TRemoteFile * File, /*const TRemoteProperties*/ void * Properties)
  4273. {
  4274. TRemoteProperties * RProperties = (TRemoteProperties *)Properties;
  4275. DebugAssert(RProperties && !RProperties->Valid.Empty());
  4276. if (FileName.IsEmpty() && File)
  4277. {
  4278. FileName = File->FileName;
  4279. }
  4280. StartOperationWithFile(FileName, foSetProperties);
  4281. if (Log->Logging)
  4282. {
  4283. LogEvent(FORMAT(L"Changing properties of \"%s\" (%s)",
  4284. (FileName, BooleanToEngStr(RProperties->Recursive))));
  4285. if (RProperties->Valid.Contains(vpRights))
  4286. {
  4287. LogEvent(FORMAT(L" - mode: \"%s\"", (RProperties->Rights.ModeStr)));
  4288. }
  4289. if (RProperties->Valid.Contains(vpGroup))
  4290. {
  4291. LogEvent(FORMAT(L" - group: %s", (RProperties->Group.LogText)));
  4292. }
  4293. if (RProperties->Valid.Contains(vpOwner))
  4294. {
  4295. LogEvent(FORMAT(L" - owner: %s", (RProperties->Owner.LogText)));
  4296. }
  4297. if (RProperties->Valid.Contains(vpModification))
  4298. {
  4299. LogEvent(FORMAT(L" - modification: \"%s\"",
  4300. (FormatDateTime(L"dddddd tt",
  4301. UnixToDateTime(RProperties->Modification, SessionData->DSTMode)))));
  4302. }
  4303. if (RProperties->Valid.Contains(vpLastAccess))
  4304. {
  4305. LogEvent(FORMAT(L" - last access: \"%s\"",
  4306. (FormatDateTime(L"dddddd tt",
  4307. UnixToDateTime(RProperties->LastAccess, SessionData->DSTMode)))));
  4308. }
  4309. }
  4310. FileModified(File, FileName);
  4311. DoChangeFileProperties(FileName, File, RProperties);
  4312. ReactOnCommand(fsChangeProperties);
  4313. }
  4314. //---------------------------------------------------------------------------
  4315. void __fastcall TTerminal::DoChangeFileProperties(const UnicodeString FileName,
  4316. const TRemoteFile * File, const TRemoteProperties * Properties)
  4317. {
  4318. TRetryOperationLoop RetryLoop(this);
  4319. do
  4320. {
  4321. TChmodSessionAction Action(ActionLog, AbsolutePath(FileName, true));
  4322. try
  4323. {
  4324. DebugAssert(FFileSystem);
  4325. FFileSystem->ChangeFileProperties(FileName, File, Properties, Action);
  4326. }
  4327. catch(Exception & E)
  4328. {
  4329. RetryLoop.Error(E, Action, FMTLOAD(CHANGE_PROPERTIES_ERROR, (FileName)));
  4330. }
  4331. }
  4332. while (RetryLoop.Retry());
  4333. }
  4334. //---------------------------------------------------------------------------
  4335. void __fastcall TTerminal::ChangeFilesProperties(TStrings * FileList,
  4336. const TRemoteProperties * Properties)
  4337. {
  4338. TValueRestorer<bool> UseBusyCursorRestorer(FUseBusyCursor, false);
  4339. AnnounceFileListOperation();
  4340. ProcessFiles(FileList, foSetProperties, ChangeFileProperties, (void *)Properties);
  4341. }
  4342. //---------------------------------------------------------------------------
  4343. bool __fastcall TTerminal::LoadFilesProperties(TStrings * FileList)
  4344. {
  4345. TValueRestorer<bool> UseBusyCursorRestorer(FUseBusyCursor, false);
  4346. // see comment in TSFTPFileSystem::IsCapable
  4347. bool Result =
  4348. IsCapable[fcLoadingAdditionalProperties] &&
  4349. FFileSystem->LoadFilesProperties(FileList);
  4350. if (Result && SessionData->CacheDirectories &&
  4351. (FileList->Count > 0) &&
  4352. (dynamic_cast<TRemoteFile *>(FileList->Objects[0])->Directory == FFiles))
  4353. {
  4354. AddCachedFileList(FFiles);
  4355. }
  4356. return Result;
  4357. }
  4358. //---------------------------------------------------------------------------
  4359. void __fastcall TTerminal::DoCalculateFileSize(UnicodeString FileName,
  4360. const TRemoteFile * File, void * Param)
  4361. {
  4362. // This is called for top-level entries only
  4363. TCalculateSizeParams * AParams = static_cast<TCalculateSizeParams*>(Param);
  4364. if (AParams->Stats->FoundFiles != NULL)
  4365. {
  4366. UnicodeString DirPath = UnixExtractFilePath(UnixExcludeTrailingBackslash(File->FullFileName));
  4367. if ((DirPath != AParams->LastDirPath) ||
  4368. (AParams->Files == NULL))
  4369. {
  4370. AParams->Files = new TCollectedFileList();
  4371. AParams->LastDirPath = DirPath;
  4372. AParams->Stats->FoundFiles->AddObject(AParams->LastDirPath, AParams->Files);
  4373. }
  4374. }
  4375. __int64 PrevSize = AParams->Size;
  4376. CalculateFileSize(FileName, File, Param);
  4377. if (AParams->Stats->CalculatedSizes != NULL)
  4378. {
  4379. __int64 Size = AParams->Size - PrevSize;
  4380. AParams->Stats->CalculatedSizes->push_back(Size);
  4381. }
  4382. }
  4383. //---------------------------------------------------------------------------
  4384. void __fastcall TTerminal::CalculateFileSize(UnicodeString FileName,
  4385. const TRemoteFile * File, /*TCalculateSizeParams*/ void * Param)
  4386. {
  4387. DebugAssert(Param);
  4388. DebugAssert(File);
  4389. TCalculateSizeParams * AParams = static_cast<TCalculateSizeParams*>(Param);
  4390. if (FileName.IsEmpty())
  4391. {
  4392. FileName = File->FileName;
  4393. }
  4394. if (!TryStartOperationWithFile(FileName, foCalculateSize))
  4395. {
  4396. AParams->Result = false;
  4397. // Combined with csIgnoreErrors, this will not abort completely, but we get called again
  4398. // with next sibling of our parent directory (and we get again to this branch, throwing again)
  4399. Abort();
  4400. }
  4401. if ((AParams->CopyParam == NULL) ||
  4402. DoAllowRemoteFileTransfer(File, AParams->CopyParam, FLAGSET(AParams->Params, csDisallowTemporaryTransferFiles)))
  4403. {
  4404. int CollectionIndex = -1;
  4405. if (AParams->Files != NULL)
  4406. {
  4407. UnicodeString FullFileName = UnixExcludeTrailingBackslash(File->FullFileName);
  4408. CollectionIndex = AParams->Files->Add(FullFileName, File->Duplicate(), File->IsDirectory);
  4409. }
  4410. if (File->IsDirectory)
  4411. {
  4412. if (CanRecurseToDirectory(File))
  4413. {
  4414. if (!AParams->AllowDirs)
  4415. {
  4416. AParams->Result = false;
  4417. }
  4418. else if (FLAGSET(AParams->Params, csStopOnFirstFile) && (AParams->Stats->Files > 0))
  4419. {
  4420. // do not waste time recursing into a folder, if we already found some files
  4421. }
  4422. else
  4423. {
  4424. if (FLAGCLEAR(AParams->Params, csStopOnFirstFile))
  4425. {
  4426. LogEvent(FORMAT(L"Getting size of directory \"%s\"", (FileName)));
  4427. }
  4428. // pass in full path so we get it back in file list for AllowTransfer() exclusion
  4429. if (!DoCalculateDirectorySize(File->FullFileName, AParams))
  4430. {
  4431. if (CollectionIndex >= 0)
  4432. {
  4433. AParams->Files->DidNotRecurse(CollectionIndex);
  4434. }
  4435. }
  4436. }
  4437. }
  4438. AParams->Stats->Directories++;
  4439. }
  4440. else
  4441. {
  4442. AParams->Size += File->Resolve()->Size;
  4443. AParams->Stats->Files++;
  4444. }
  4445. if (File->IsSymLink)
  4446. {
  4447. AParams->Stats->SymLinks++;
  4448. }
  4449. }
  4450. }
  4451. //---------------------------------------------------------------------------
  4452. bool __fastcall TTerminal::DoCalculateDirectorySize(const UnicodeString & FileName, TCalculateSizeParams * Params)
  4453. {
  4454. bool Result = false;
  4455. if (FLAGSET(Params->Params, csStopOnFirstFile) && (Configuration->ActualLogProtocol >= 1))
  4456. {
  4457. LogEvent(FORMAT(L"Checking if remote directory \"%s\" is empty", (FileName)));
  4458. }
  4459. TRetryOperationLoop RetryLoop(this);
  4460. do
  4461. {
  4462. try
  4463. {
  4464. ProcessDirectory(FileName, CalculateFileSize, Params, Params->UseCache);
  4465. Result = true;
  4466. }
  4467. catch(Exception & E)
  4468. {
  4469. // We can probably replace the csIgnoreErrors with IgnoreErrors argument of the ProcessDirectory
  4470. if (!Active || ((Params->Params & csIgnoreErrors) == 0))
  4471. {
  4472. RetryLoop.Error(E, FMTLOAD(CALCULATE_SIZE_ERROR, (FileName)));
  4473. }
  4474. }
  4475. }
  4476. while (RetryLoop.Retry());
  4477. if (Configuration->ActualLogProtocol >= 1)
  4478. {
  4479. if (Params->Stats->Files == 0)
  4480. {
  4481. LogEvent(FORMAT(L"Remote directory \"%s\" is empty", (FileName)));
  4482. }
  4483. else
  4484. {
  4485. LogEvent(FORMAT(L"Remote directory \"%s\" is not empty", (FileName)));
  4486. }
  4487. }
  4488. return Result;
  4489. }
  4490. //---------------------------------------------------------------------------
  4491. bool TTerminal::CalculateFilesSize(TStrings * FileList, __int64 & Size, TCalculateSizeParams & Params)
  4492. {
  4493. // With FTP protocol, we may use DSIZ command from
  4494. // draft-peterson-streamlined-ftp-command-extensions-10
  4495. // Implemented by Serv-U FTP.
  4496. TValueRestorer<bool> UseBusyCursorRestorer(FUseBusyCursor, false);
  4497. ProcessFiles(FileList, foCalculateSize, DoCalculateFileSize, &Params);
  4498. Size = Params.Size;
  4499. if (Configuration->ActualLogProtocol >= 1)
  4500. {
  4501. LogEvent(FORMAT(L"Size of %d remote files/folders calculated as %s", (FileList->Count, IntToStr(Size))));
  4502. }
  4503. return Params.Result;
  4504. }
  4505. //---------------------------------------------------------------------------
  4506. void __fastcall TTerminal::CalculateSubFoldersChecksum(
  4507. const UnicodeString & Alg, TStrings * FileList, TCalculatedChecksumEvent OnCalculatedChecksum,
  4508. TFileOperationProgressType * OperationProgress, bool FirstLevel)
  4509. {
  4510. // recurse into subdirectories only if we have callback function
  4511. if (OnCalculatedChecksum != NULL)
  4512. {
  4513. int Index = 0;
  4514. TOnceDoneOperation OnceDoneOperation; // unused
  4515. while ((Index < FileList->Count) && !OperationProgress->Cancel)
  4516. {
  4517. UnicodeString FileName = FileList->Strings[Index];
  4518. TRemoteFile * File = DebugNotNull(dynamic_cast<TRemoteFile *>(FileList->Objects[Index]));
  4519. if (File->IsDirectory &&
  4520. CanRecurseToDirectory(File) &&
  4521. IsRealFile(File->FileName))
  4522. {
  4523. OperationProgress->SetFile(File->FileName);
  4524. std::unique_ptr<TRemoteFileList> SubFiles(CustomReadDirectoryListing(File->FullFileName, false));
  4525. if (SubFiles.get() != NULL)
  4526. {
  4527. std::unique_ptr<TStrings> SubFileList(new TStringList());
  4528. bool Success = false;
  4529. try
  4530. {
  4531. OperationProgress->SetFile(File->FileName);
  4532. for (int Index = 0; Index < SubFiles->Count; Index++)
  4533. {
  4534. TRemoteFile * SubFile = SubFiles->Files[Index];
  4535. UnicodeString SubFileName = UnixCombinePaths(FileName, SubFile->FileName);
  4536. SubFileList->AddObject(SubFileName, SubFile);
  4537. }
  4538. FFileSystem->CalculateFilesChecksum(Alg, SubFileList.get(), OnCalculatedChecksum, OperationProgress, false);
  4539. Success = true;
  4540. }
  4541. __finally
  4542. {
  4543. if (FirstLevel)
  4544. {
  4545. OperationProgress->Finish(File->FileName, Success, OnceDoneOperation);
  4546. }
  4547. }
  4548. }
  4549. }
  4550. Index++;
  4551. }
  4552. }
  4553. }
  4554. //---------------------------------------------------------------------------
  4555. void __fastcall TTerminal::CalculateFilesChecksum(
  4556. const UnicodeString & Alg, TStrings * FileList, TCalculatedChecksumEvent OnCalculatedChecksum)
  4557. {
  4558. TFileOperationProgressType Progress(&DoProgress, &DoFinished);
  4559. OperationStart(Progress, foCalculateChecksum, osRemote, FileList->Count);
  4560. try
  4561. {
  4562. TCustomFileSystem * FileSystem = GetFileSystemForCapability(fcCalculatingChecksum);
  4563. UnicodeString NormalizedAlg = FileSystem->CalculateFilesChecksumInitialize(Alg);
  4564. FileSystem->CalculateFilesChecksum(NormalizedAlg, FileList, OnCalculatedChecksum, &Progress, true);
  4565. }
  4566. __finally
  4567. {
  4568. OperationStop(Progress);
  4569. }
  4570. }
  4571. //---------------------------------------------------------------------------
  4572. void __fastcall TTerminal::RenameFile(const TRemoteFile * File, const UnicodeString & NewName)
  4573. {
  4574. // Already checked in TUnixDirView::InternalEdit
  4575. if (DebugAlwaysTrue(File->FileName != NewName))
  4576. {
  4577. FileModified(File, File->FileName);
  4578. LogEvent(FORMAT(L"Renaming file \"%s\" to \"%s\".", (File->FileName, NewName)));
  4579. if (DoRenameFile(File->FileName, File, NewName, false, false))
  4580. {
  4581. ReactOnCommand(fsRenameFile);
  4582. }
  4583. }
  4584. }
  4585. //---------------------------------------------------------------------------
  4586. bool TTerminal::DoRenameOrCopyFile(
  4587. bool Rename, const UnicodeString & FileName, const TRemoteFile * File, const UnicodeString & NewName,
  4588. bool Move, bool DontOverwrite, bool IsBatchOperation)
  4589. {
  4590. TBatchOverwrite BatchOverwrite = (IsBatchOperation ? OperationProgress->BatchOverwrite : boNo);
  4591. UnicodeString AbsoluteFileName = AbsolutePath(FileName, true);
  4592. UnicodeString AbsoluteNewName = AbsolutePath(NewName, true);
  4593. bool Result = true;
  4594. bool ExistenceKnown = false;
  4595. std::unique_ptr<TRemoteFile> DuplicateFile;
  4596. if (UnixSamePath(AbsoluteFileName, AbsoluteNewName))
  4597. {
  4598. LogEvent(FORMAT(L"Tartget \"%s\" is same as source \"%s\" - skipping.", (AbsoluteNewName, AbsoluteFileName)));
  4599. Result = false;
  4600. }
  4601. else if (BatchOverwrite == boNone)
  4602. {
  4603. DebugAssert(!DontOverwrite); // unsupported combination
  4604. Result = !FileExists(AbsoluteNewName);
  4605. ExistenceKnown = true;
  4606. }
  4607. else if (BatchOverwrite == boAll)
  4608. {
  4609. // noop
  4610. }
  4611. else if (DebugAlwaysTrue(BatchOverwrite == boNo) &&
  4612. Configuration->ConfirmOverwriting &&
  4613. !DontOverwrite)
  4614. {
  4615. DuplicateFile.reset(TryReadFile(AbsoluteNewName));
  4616. ExistenceKnown = true;
  4617. if (DuplicateFile.get() != NULL)
  4618. {
  4619. UnicodeString QuestionFmt;
  4620. TQueryType QueryType;
  4621. if (DuplicateFile->IsDirectory)
  4622. {
  4623. QuestionFmt = MainInstructions(LoadStr(DIRECTORY_OVERWRITE)) + LoadStr(DIRECTORY_OVERWRITE_WARNING);
  4624. QueryType = qtWarning;
  4625. }
  4626. else
  4627. {
  4628. QuestionFmt = MainInstructions(LoadStr(FILE_OVERWRITE));
  4629. QueryType = qtConfirmation;
  4630. }
  4631. TQueryParams Params(qpNeverAskAgainCheck);
  4632. UnicodeString Question = FORMAT(QuestionFmt, (NewName));
  4633. unsigned int Answers = qaYes | qaNo | FLAGMASK(OperationProgress != NULL, qaCancel) | FLAGMASK(IsBatchOperation, qaYesToAll | qaNoToAll);
  4634. unsigned int Answer = QueryUser(Question, NULL, Answers, &Params, QueryType);
  4635. switch (Answer)
  4636. {
  4637. case qaNeverAskAgain:
  4638. Configuration->ConfirmOverwriting = false;
  4639. Result = true;
  4640. break;
  4641. case qaYes:
  4642. Result = true;
  4643. break;
  4644. case qaNo:
  4645. Result = false;
  4646. break;
  4647. case qaYesToAll:
  4648. Result = true;
  4649. if (DebugAlwaysTrue(IsBatchOperation))
  4650. {
  4651. OperationProgress->SetBatchOverwrite(boAll);
  4652. }
  4653. break;
  4654. case qaNoToAll:
  4655. Result = false;
  4656. if (DebugAlwaysTrue(IsBatchOperation))
  4657. {
  4658. OperationProgress->SetBatchOverwrite(boNone);
  4659. }
  4660. break;
  4661. case qaCancel:
  4662. Result = false;
  4663. OperationProgress->SetCancel(csCancel);
  4664. break;
  4665. default:
  4666. Result = false;
  4667. DebugFail();
  4668. break;
  4669. }
  4670. }
  4671. }
  4672. if (Result)
  4673. {
  4674. // Prevent destroying TRemoteFile between delete and rename
  4675. BeginTransaction();
  4676. try
  4677. {
  4678. TCustomFileSystem * FileSystem;
  4679. if (!Rename)
  4680. {
  4681. if (IsCapable[fcSecondaryShell] &&
  4682. File->IsDirectory &&
  4683. (FCommandSession != NULL)) // Won't be in scripting, there we let it fail later
  4684. {
  4685. PrepareCommandSession();
  4686. FileSystem = FCommandSession->FFileSystem;
  4687. }
  4688. else
  4689. {
  4690. FileSystem = GetFileSystemForCapability(fcRemoteCopy);
  4691. }
  4692. }
  4693. else
  4694. {
  4695. FileSystem = FFileSystem;
  4696. }
  4697. if (!IsCapable[fcMoveOverExistingFile] && !DontOverwrite)
  4698. {
  4699. if (!ExistenceKnown)
  4700. {
  4701. DuplicateFile.reset(TryReadFile(AbsoluteNewName));
  4702. }
  4703. if (DuplicateFile.get() != NULL)
  4704. {
  4705. DoDeleteFile(FileSystem, AbsoluteNewName, DuplicateFile.get(), 0);
  4706. }
  4707. }
  4708. TRetryOperationLoop RetryLoop(this);
  4709. do
  4710. {
  4711. DebugAssert(FileSystem != NULL);
  4712. if (Rename)
  4713. {
  4714. TMvSessionAction Action(ActionLog, AbsoluteFileName, AbsoluteNewName);
  4715. try
  4716. {
  4717. FileSystem->RenameFile(FileName, File, NewName, !DontOverwrite);
  4718. }
  4719. catch (Exception & E)
  4720. {
  4721. UnicodeString Message = FMTLOAD(Move ? MOVE_FILE_ERROR : RENAME_FILE_ERROR, (FileName, NewName));
  4722. RetryLoop.Error(E, Action, Message);
  4723. }
  4724. }
  4725. else
  4726. {
  4727. TCpSessionAction Action(ActionLog, AbsoluteFileName, AbsoluteNewName);
  4728. try
  4729. {
  4730. FileSystem->CopyFile(FileName, File, NewName, !DontOverwrite);
  4731. }
  4732. catch (Exception & E)
  4733. {
  4734. RetryLoop.Error(E, Action, FMTLOAD(COPY_FILE_ERROR, (FileName, NewName)));
  4735. }
  4736. }
  4737. }
  4738. while (RetryLoop.Retry());
  4739. Result = RetryLoop.Succeeded();
  4740. }
  4741. __finally
  4742. {
  4743. EndTransaction();
  4744. }
  4745. }
  4746. return Result;
  4747. }
  4748. //---------------------------------------------------------------------------
  4749. bool __fastcall TTerminal::DoRenameFile(
  4750. const UnicodeString & FileName, const TRemoteFile * File, const UnicodeString & NewName, bool Move, bool DontOverwrite)
  4751. {
  4752. // Can be foDelete when recycling (and overwrite should not happen in this case)
  4753. bool IsBatchOperation = (OperationProgress != NULL) && (OperationProgress->Operation == foRemoteMove);
  4754. return DoRenameOrCopyFile(true, FileName, File, NewName, Move, DontOverwrite, IsBatchOperation);
  4755. }
  4756. //---------------------------------------------------------------------------
  4757. bool __fastcall TTerminal::DoMoveFile(const UnicodeString & FileName, const TRemoteFile * File, /*const TMoveFileParams*/ void * Param)
  4758. {
  4759. StartOperationWithFile(FileName, foRemoteMove, foDelete);
  4760. DebugAssert(Param != NULL);
  4761. const TMoveFileParams & Params = *static_cast<const TMoveFileParams*>(Param);
  4762. UnicodeString NewName = UnixIncludeTrailingBackslash(Params.Target) +
  4763. MaskFileName(UnixExtractFileName(FileName), Params.FileMask);
  4764. LogEvent(FORMAT(L"Moving file \"%s\" to \"%s\".", (FileName, NewName)));
  4765. FileModified(File, FileName);
  4766. bool Result = DoRenameFile(FileName, File, NewName, true, Params.DontOverwrite);
  4767. if (Result)
  4768. {
  4769. ReactOnCommand(fsMoveFile);
  4770. }
  4771. return Result;
  4772. }
  4773. //---------------------------------------------------------------------------
  4774. void __fastcall TTerminal::MoveFile(const UnicodeString FileName, const TRemoteFile * File, /*const TMoveFileParams*/ void * Param)
  4775. {
  4776. DoMoveFile(FileName, File, Param);
  4777. }
  4778. //---------------------------------------------------------------------------
  4779. bool __fastcall TTerminal::MoveFiles(
  4780. TStrings * FileList, const UnicodeString & Target, const UnicodeString & FileMask, bool DontOverwrite)
  4781. {
  4782. TMoveFileParams Params;
  4783. Params.Target = Target;
  4784. Params.FileMask = FileMask;
  4785. Params.DontOverwrite = DontOverwrite;
  4786. bool Result;
  4787. BeginTransaction();
  4788. try
  4789. {
  4790. Result = ProcessFiles(FileList, foRemoteMove, MoveFile, &Params);
  4791. }
  4792. __finally
  4793. {
  4794. if (Active)
  4795. {
  4796. // Only after the move, as with encryption, the folders can be read and cached before the move
  4797. // (when determining if the target exists and is encrypted)
  4798. DirectoryModified(Target, true);
  4799. UnicodeString WithTrailing = UnixIncludeTrailingBackslash(CurrentDirectory);
  4800. bool PossiblyMoved = false;
  4801. // check if we was moving current directory.
  4802. // this is just optimization to avoid checking existence of current
  4803. // directory after each move operation.
  4804. for (int Index = 0; !PossiblyMoved && (Index < FileList->Count); Index++)
  4805. {
  4806. const TRemoteFile * File =
  4807. dynamic_cast<const TRemoteFile *>(FileList->Objects[Index]);
  4808. // File can be NULL, and filename may not be full path,
  4809. // but currently this is the only way we can move (at least in GUI)
  4810. // current directory
  4811. if ((File != NULL) &&
  4812. File->IsDirectory &&
  4813. ((CurrentDirectory.SubString(1, FileList->Strings[Index].Length()) == FileList->Strings[Index]) &&
  4814. ((FileList->Strings[Index].Length() == CurrentDirectory.Length()) ||
  4815. (CurrentDirectory[FileList->Strings[Index].Length() + 1] == L'/'))))
  4816. {
  4817. PossiblyMoved = true;
  4818. }
  4819. }
  4820. if (PossiblyMoved && !FileExists(CurrentDirectory))
  4821. {
  4822. UnicodeString NearestExisting = CurrentDirectory;
  4823. do
  4824. {
  4825. NearestExisting = UnixExtractFileDir(NearestExisting);
  4826. }
  4827. while (!IsUnixRootPath(NearestExisting) && !FileExists(NearestExisting));
  4828. ChangeDirectory(NearestExisting);
  4829. }
  4830. }
  4831. EndTransaction();
  4832. }
  4833. return Result;
  4834. }
  4835. //---------------------------------------------------------------------------
  4836. void __fastcall TTerminal::DoCopyFile(
  4837. const UnicodeString & FileName, const TRemoteFile * File, const UnicodeString & NewName, bool DontOverwrite)
  4838. {
  4839. bool IsBatchOperation = DebugAlwaysTrue(OperationProgress != NULL);
  4840. bool Move = false; // not used
  4841. DoRenameOrCopyFile(false, FileName, File, NewName, Move, DontOverwrite, IsBatchOperation);
  4842. }
  4843. //---------------------------------------------------------------------------
  4844. void __fastcall TTerminal::CopyFile(const UnicodeString FileName,
  4845. const TRemoteFile * File, /*const TMoveFileParams*/ void * Param)
  4846. {
  4847. StartOperationWithFile(FileName, foRemoteCopy);
  4848. DebugAssert(Param != NULL);
  4849. const TMoveFileParams & Params = *static_cast<const TMoveFileParams*>(Param);
  4850. UnicodeString NewName = UnixIncludeTrailingBackslash(Params.Target) +
  4851. MaskFileName(UnixExtractFileName(FileName), Params.FileMask);
  4852. LogEvent(FORMAT(L"Copying file \"%s\" to \"%s\".", (FileName, NewName)));
  4853. DoCopyFile(FileName, File, NewName, Params.DontOverwrite);
  4854. ReactOnCommand(fsCopyFile);
  4855. }
  4856. //---------------------------------------------------------------------------
  4857. bool __fastcall TTerminal::CopyFiles(
  4858. TStrings * FileList, const UnicodeString & Target, const UnicodeString & FileMask, bool DontOverwrite)
  4859. {
  4860. TMoveFileParams Params;
  4861. Params.Target = Target;
  4862. Params.FileMask = FileMask;
  4863. Params.DontOverwrite = DontOverwrite;
  4864. DirectoryModified(Target, true);
  4865. return ProcessFiles(FileList, foRemoteCopy, CopyFile, &Params);
  4866. }
  4867. //---------------------------------------------------------------------------
  4868. void __fastcall TTerminal::CreateDirectory(const UnicodeString & DirName, const TRemoteProperties * Properties)
  4869. {
  4870. DebugAssert(FFileSystem);
  4871. DebugAssert(Properties != NULL);
  4872. EnsureNonExistence(DirName);
  4873. FileModified(NULL, DirName);
  4874. LogEvent(FORMAT(L"Creating directory \"%s\".", (DirName)));
  4875. bool Encrypt = Properties->Valid.Contains(vpEncrypt) && Properties->Encrypt;
  4876. DoCreateDirectory(DirName, Encrypt);
  4877. TValidProperties RemainingPropeties = Properties->Valid - (TValidProperties() << vpEncrypt);
  4878. if (!RemainingPropeties.Empty() &&
  4879. (IsCapable[fcModeChanging] || IsCapable[fcOwnerChanging] || IsCapable[fcGroupChanging]))
  4880. {
  4881. DoChangeFileProperties(DirName, NULL, Properties);
  4882. }
  4883. ReactOnCommand(fsCreateDirectory);
  4884. }
  4885. //---------------------------------------------------------------------------
  4886. void __fastcall TTerminal::DoCreateDirectory(const UnicodeString & DirName, bool Encrypt)
  4887. {
  4888. TRetryOperationLoop RetryLoop(this);
  4889. do
  4890. {
  4891. TMkdirSessionAction Action(ActionLog, AbsolutePath(DirName, true));
  4892. try
  4893. {
  4894. DebugAssert(FFileSystem);
  4895. FFileSystem->CreateDirectory(DirName, Encrypt);
  4896. }
  4897. catch(Exception & E)
  4898. {
  4899. RetryLoop.Error(E, Action, FMTLOAD(CREATE_DIR_ERROR, (DirName)));
  4900. }
  4901. }
  4902. while (RetryLoop.Retry());
  4903. }
  4904. //---------------------------------------------------------------------------
  4905. void __fastcall TTerminal::CreateLink(const UnicodeString FileName,
  4906. const UnicodeString PointTo, bool Symbolic)
  4907. {
  4908. DebugAssert(FFileSystem);
  4909. EnsureNonExistence(FileName);
  4910. if (SessionData->CacheDirectories)
  4911. {
  4912. DirectoryModified(CurrentDirectory, false);
  4913. }
  4914. LogEvent(FORMAT(L"Creating link \"%s\" to \"%s\" (symbolic: %s).",
  4915. (FileName, PointTo, BooleanToEngStr(Symbolic))));
  4916. DoCreateLink(FileName, PointTo, Symbolic);
  4917. ReactOnCommand(fsCreateDirectory);
  4918. }
  4919. //---------------------------------------------------------------------------
  4920. void __fastcall TTerminal::DoCreateLink(const UnicodeString FileName,
  4921. const UnicodeString PointTo, bool Symbolic)
  4922. {
  4923. TRetryOperationLoop RetryLoop(this);
  4924. do
  4925. {
  4926. try
  4927. {
  4928. DebugAssert(FFileSystem);
  4929. FFileSystem->CreateLink(FileName, PointTo, Symbolic);
  4930. }
  4931. catch(Exception & E)
  4932. {
  4933. RetryLoop.Error(E, FMTLOAD(CREATE_LINK_ERROR, (FileName)));
  4934. }
  4935. }
  4936. while (RetryLoop.Retry());
  4937. }
  4938. //---------------------------------------------------------------------------
  4939. void __fastcall TTerminal::HomeDirectory()
  4940. {
  4941. DebugAssert(FFileSystem);
  4942. try
  4943. {
  4944. LogEvent(L"Changing directory to home directory.");
  4945. FFileSystem->HomeDirectory();
  4946. ReactOnCommand(fsHomeDirectory);
  4947. }
  4948. catch (Exception &E)
  4949. {
  4950. CommandError(&E, LoadStr(CHANGE_HOMEDIR_ERROR));
  4951. }
  4952. }
  4953. //---------------------------------------------------------------------------
  4954. UnicodeString __fastcall TTerminal::GetHomeDirectory()
  4955. {
  4956. return FFileSystem->GetHomeDirectory();
  4957. }
  4958. //---------------------------------------------------------------------------
  4959. void __fastcall TTerminal::ChangeDirectory(const UnicodeString Directory)
  4960. {
  4961. DebugAssert(FFileSystem);
  4962. try
  4963. {
  4964. UnicodeString CachedDirectory;
  4965. DebugAssert(!SessionData->CacheDirectoryChanges || (FDirectoryChangesCache != NULL));
  4966. // never use directory change cache during startup, this ensures, we never
  4967. // end-up initially in non-existing directory
  4968. if ((Status == ssOpened) &&
  4969. SessionData->CacheDirectoryChanges &&
  4970. FDirectoryChangesCache->GetDirectoryChange(PeekCurrentDirectory(),
  4971. Directory, CachedDirectory))
  4972. {
  4973. LogEvent(FORMAT(L"Cached directory change via \"%s\" to \"%s\".",
  4974. (Directory, CachedDirectory)));
  4975. FFileSystem->CachedChangeDirectory(CachedDirectory);
  4976. }
  4977. else
  4978. {
  4979. LogEvent(FORMAT(L"Changing directory to \"%s\".", (Directory)));
  4980. FFileSystem->ChangeDirectory(Directory);
  4981. }
  4982. FLastDirectoryChange = Directory;
  4983. ReactOnCommand(fsChangeDirectory);
  4984. }
  4985. catch (Exception &E)
  4986. {
  4987. CommandError(&E, FMTLOAD(CHANGE_DIR_ERROR, (Directory)));
  4988. }
  4989. }
  4990. //---------------------------------------------------------------------------
  4991. void __fastcall TTerminal::LookupUsersGroups()
  4992. {
  4993. if (!FUsersGroupsLookedup && (SessionData->LookupUserGroups != asOff) &&
  4994. IsCapable[fcUserGroupListing])
  4995. {
  4996. DebugAssert(FFileSystem);
  4997. try
  4998. {
  4999. FUsersGroupsLookedup = true;
  5000. LogEvent(L"Looking up groups and users.");
  5001. FFileSystem->LookupUsersGroups();
  5002. ReactOnCommand(fsLookupUsersGroups);
  5003. if (Log->Logging)
  5004. {
  5005. FGroups.Log(this, L"groups");
  5006. FMembership.Log(this, L"membership");
  5007. FUsers.Log(this, L"users");
  5008. }
  5009. }
  5010. catch (Exception &E)
  5011. {
  5012. if (!Active || (SessionData->LookupUserGroups == asOn))
  5013. {
  5014. CommandError(&E, LoadStr(LOOKUP_GROUPS_ERROR));
  5015. }
  5016. }
  5017. }
  5018. }
  5019. //---------------------------------------------------------------------------
  5020. bool __fastcall TTerminal::AllowedAnyCommand(const UnicodeString Command)
  5021. {
  5022. return !Command.Trim().IsEmpty();
  5023. }
  5024. //---------------------------------------------------------------------------
  5025. bool __fastcall TTerminal::GetCommandSessionOpened()
  5026. {
  5027. // consider secondary terminal open in "ready" state only
  5028. // so we never do keepalives on it until it is completely initialized
  5029. return (FCommandSession != NULL) &&
  5030. (FCommandSession->Status == ssOpened);
  5031. }
  5032. //---------------------------------------------------------------------------
  5033. TTerminal * __fastcall TTerminal::CreateSecondarySession(const UnicodeString & Name, TSessionData * SessionData)
  5034. {
  5035. std::unique_ptr<TTerminal> Result(new TSecondaryTerminal(this, SessionData, Configuration, Name, ActionLog));
  5036. Result->AutoReadDirectory = false;
  5037. Result->FExceptionOnFail = FExceptionOnFail;
  5038. Result->OnQueryUser = OnQueryUser;
  5039. Result->OnPromptUser = OnPromptUser;
  5040. Result->OnShowExtendedException = OnShowExtendedException;
  5041. Result->OnProgress = OnProgress;
  5042. Result->OnFinished = OnFinished;
  5043. Result->OnInformation = OnInformation;
  5044. Result->OnCustomCommand = OnCustomCommand;
  5045. // do not copy OnDisplayBanner to avoid it being displayed
  5046. return Result.release();
  5047. }
  5048. //---------------------------------------------------------------------------
  5049. void __fastcall TTerminal::FillSessionDataForCode(TSessionData * Data)
  5050. {
  5051. const TSessionInfo & SessionInfo = GetSessionInfo();
  5052. if (!SessionInfo.HostKeyFingerprintSHA256.IsEmpty())
  5053. {
  5054. Data->HostKey = SessionInfo.HostKeyFingerprintSHA256;
  5055. }
  5056. else if (SessionInfo.CertificateVerifiedManually && DebugAlwaysTrue(!SessionInfo.CertificateFingerprintSHA256.IsEmpty()))
  5057. {
  5058. Data->HostKey = SessionInfo.CertificateFingerprintSHA256;
  5059. }
  5060. if (FTunnel != NULL)
  5061. {
  5062. const TSessionInfo & TunnelSessionInfo = FTunnel->GetSessionInfo();
  5063. if (DebugAlwaysTrue(!TunnelSessionInfo.HostKeyFingerprintSHA256.IsEmpty()))
  5064. {
  5065. Data->TunnelHostKey = TunnelSessionInfo.HostKeyFingerprintSHA256;
  5066. }
  5067. }
  5068. }
  5069. //---------------------------------------------------------------------------
  5070. void __fastcall TTerminal::UpdateSessionCredentials(TSessionData * Data)
  5071. {
  5072. // Only if it differs from the original session data?
  5073. // Because this way, we persist the username redundantly in workspace session linked to a stored site.
  5074. Data->UserName = UserName;
  5075. Data->Password = Password;
  5076. if (!FRememberedPassword.IsEmpty() && (FRememberedPasswordKind == pkPassphrase))
  5077. {
  5078. Data->Passphrase = GetRememberedPassword();
  5079. }
  5080. }
  5081. //---------------------------------------------------------------------------
  5082. TTerminal * __fastcall TTerminal::GetCommandSession()
  5083. {
  5084. if ((FCommandSession != NULL) && !FCommandSession->Active)
  5085. {
  5086. SAFE_DESTROY(FCommandSession);
  5087. }
  5088. if (FCommandSession == NULL)
  5089. {
  5090. // transaction cannot be started yet to allow proper matching transaction
  5091. // levels between main and command session
  5092. DebugAssert(FInTransaction == 0);
  5093. std::unique_ptr<TSessionData> CommandSessionData(SessionData->Clone());
  5094. CommandSessionData->RemoteDirectory = CurrentDirectory;
  5095. CommandSessionData->FSProtocol = fsSCPonly;
  5096. CommandSessionData->ClearAliases = false;
  5097. CommandSessionData->UnsetNationalVars = false;
  5098. CommandSessionData->LookupUserGroups = asOff;
  5099. FCommandSession = CreateSecondarySession(L"Shell", CommandSessionData.get());
  5100. FCommandSession->AutoReadDirectory = false;
  5101. FCommandSession->FExceptionOnFail = FExceptionOnFail;
  5102. FCommandSession->OnQueryUser = OnQueryUser;
  5103. FCommandSession->OnPromptUser = OnPromptUser;
  5104. FCommandSession->OnShowExtendedException = OnShowExtendedException;
  5105. FCommandSession->OnProgress = OnProgress;
  5106. FCommandSession->OnFinished = OnFinished;
  5107. FCommandSession->OnInformation = OnInformation;
  5108. FCommandSession->OnCustomCommand = OnCustomCommand;
  5109. // do not copy OnDisplayBanner to avoid it being displayed
  5110. }
  5111. return FCommandSession;
  5112. }
  5113. //---------------------------------------------------------------------------
  5114. void __fastcall TTerminal::AnyCommand(const UnicodeString Command,
  5115. TCaptureOutputEvent OutputEvent)
  5116. {
  5117. #pragma warn -inl
  5118. class TOutputProxy
  5119. {
  5120. public:
  5121. __fastcall TOutputProxy(TCallSessionAction & Action, TCaptureOutputEvent OutputEvent) :
  5122. FAction(Action),
  5123. FOutputEvent(OutputEvent)
  5124. {
  5125. }
  5126. void __fastcall Output(const UnicodeString & Str, TCaptureOutputType OutputType)
  5127. {
  5128. switch (OutputType)
  5129. {
  5130. case cotOutput:
  5131. FAction.AddOutput(Str, false);
  5132. break;
  5133. case cotError:
  5134. FAction.AddOutput(Str, true);
  5135. break;
  5136. case cotExitCode:
  5137. FAction.ExitCode(StrToInt(Str));
  5138. break;
  5139. }
  5140. if (FOutputEvent != NULL)
  5141. {
  5142. FOutputEvent(Str, OutputType);
  5143. }
  5144. }
  5145. private:
  5146. TCallSessionAction & FAction;
  5147. TCaptureOutputEvent FOutputEvent;
  5148. };
  5149. #pragma warn .inl
  5150. TCallSessionAction Action(ActionLog, Command, CurrentDirectory);
  5151. TOutputProxy ProxyOutputEvent(Action, OutputEvent);
  5152. DoAnyCommand(Command, ProxyOutputEvent.Output, &Action);
  5153. }
  5154. //---------------------------------------------------------------------------
  5155. void __fastcall TTerminal::DoAnyCommand(const UnicodeString Command,
  5156. TCaptureOutputEvent OutputEvent, TCallSessionAction * Action)
  5157. {
  5158. DebugAssert(FFileSystem);
  5159. try
  5160. {
  5161. DirectoryModified(CurrentDirectory, false);
  5162. LogEvent(L"Executing user defined command.");
  5163. TCustomFileSystem * FileSystem = GetFileSystemForCapability(fcAnyCommand);
  5164. FileSystem->AnyCommand(Command, OutputEvent);
  5165. if (CommandSessionOpened && (FileSystem == FCommandSession->FFileSystem))
  5166. {
  5167. FCommandSession->FFileSystem->ReadCurrentDirectory();
  5168. // synchronize pwd (by purpose we lose transaction optimization here)
  5169. ChangeDirectory(FCommandSession->CurrentDirectory);
  5170. }
  5171. ReactOnCommand(fsAnyCommand);
  5172. }
  5173. catch (Exception &E)
  5174. {
  5175. if (Action != NULL)
  5176. {
  5177. RollbackAction(*Action, NULL, &E);
  5178. }
  5179. if (ExceptionOnFail || (E.InheritsFrom(__classid(EFatal)))) throw;
  5180. else HandleExtendedException(&E);
  5181. }
  5182. }
  5183. //---------------------------------------------------------------------------
  5184. bool __fastcall TTerminal::DoCreateLocalFile(const UnicodeString FileName,
  5185. TFileOperationProgressType * OperationProgress, HANDLE * AHandle,
  5186. bool NoConfirmation)
  5187. {
  5188. bool Result = true;
  5189. bool Done;
  5190. unsigned int CreateAttr = FILE_ATTRIBUTE_NORMAL;
  5191. do
  5192. {
  5193. *AHandle = CreateFile(ApiPath(FileName).c_str(), GENERIC_WRITE, FILE_SHARE_READ,
  5194. NULL, CREATE_ALWAYS, CreateAttr, 0);
  5195. Done = (*AHandle != INVALID_HANDLE_VALUE);
  5196. if (!Done)
  5197. {
  5198. // save the error, otherwise it gets overwritten by call to FileExists
  5199. int LastError = GetLastError();
  5200. int FileAttr;
  5201. if (::FileExists(ApiPath(FileName)) &&
  5202. (((FileAttr = FileGetAttrFix(ApiPath(FileName))) & (faReadOnly | faHidden)) != 0))
  5203. {
  5204. if (FLAGSET(FileAttr, faReadOnly))
  5205. {
  5206. OperationProgress->LockUserSelections();
  5207. try
  5208. {
  5209. if (OperationProgress->BatchOverwrite == boNone)
  5210. {
  5211. Result = false;
  5212. }
  5213. else if ((OperationProgress->BatchOverwrite != boAll) && !NoConfirmation)
  5214. {
  5215. unsigned int Answer;
  5216. {
  5217. TSuspendFileOperationProgress Suspend(OperationProgress);
  5218. Answer = QueryUser(
  5219. MainInstructions(FMTLOAD(READ_ONLY_OVERWRITE, (FileName))), NULL,
  5220. qaYes | qaNo | qaCancel | qaYesToAll | qaNoToAll, 0);
  5221. }
  5222. switch (Answer) {
  5223. case qaYesToAll: OperationProgress->SetBatchOverwrite(boAll); break;
  5224. case qaCancel: OperationProgress->SetCancel(csCancel); // continue on next case
  5225. case qaNoToAll: OperationProgress->SetBatchOverwrite(boNone);
  5226. case qaNo: Result = false; break;
  5227. }
  5228. }
  5229. }
  5230. __finally
  5231. {
  5232. OperationProgress->UnlockUserSelections();
  5233. }
  5234. }
  5235. else
  5236. {
  5237. DebugAssert(FLAGSET(FileAttr, faHidden));
  5238. Result = true;
  5239. }
  5240. if (Result)
  5241. {
  5242. CreateAttr |=
  5243. FLAGMASK(FLAGSET(FileAttr, faHidden), FILE_ATTRIBUTE_HIDDEN) |
  5244. FLAGMASK(FLAGSET(FileAttr, faReadOnly), FILE_ATTRIBUTE_READONLY);
  5245. FILE_OPERATION_LOOP_BEGIN
  5246. {
  5247. if (FileSetAttr(ApiPath(FileName), FileAttr & ~(faReadOnly | faHidden)) != 0)
  5248. {
  5249. RaiseLastOSError();
  5250. }
  5251. }
  5252. FILE_OPERATION_LOOP_END(FMTLOAD(CANT_SET_ATTRS, (FileName)));
  5253. }
  5254. else
  5255. {
  5256. Done = true;
  5257. }
  5258. }
  5259. else
  5260. {
  5261. RaiseLastOSError(LastError);
  5262. }
  5263. }
  5264. }
  5265. while (!Done);
  5266. return Result;
  5267. }
  5268. //---------------------------------------------------------------------------
  5269. bool __fastcall TTerminal::CreateLocalFile(const UnicodeString FileName,
  5270. TFileOperationProgressType * OperationProgress, HANDLE * AHandle,
  5271. bool NoConfirmation)
  5272. {
  5273. DebugAssert(AHandle);
  5274. bool Result = true;
  5275. FILE_OPERATION_LOOP_BEGIN
  5276. {
  5277. Result = DoCreateLocalFile(FileName, OperationProgress, AHandle, NoConfirmation);
  5278. }
  5279. FILE_OPERATION_LOOP_END(FMTLOAD(CREATE_FILE_ERROR, (FileName)));
  5280. return Result;
  5281. }
  5282. //---------------------------------------------------------------------------
  5283. void __fastcall TTerminal::OpenLocalFile(const UnicodeString FileName,
  5284. unsigned int Access, int * AAttrs, HANDLE * AHandle, __int64 * ACTime,
  5285. __int64 * AMTime, __int64 * AATime, __int64 * ASize,
  5286. bool TryWriteReadOnly)
  5287. {
  5288. int Attrs = 0;
  5289. HANDLE Handle = 0;
  5290. FILE_OPERATION_LOOP_BEGIN
  5291. {
  5292. UnicodeString FileNameApi = ApiPath(FileName);
  5293. Attrs = FileGetAttrFix(FileNameApi);
  5294. if (Attrs < 0)
  5295. {
  5296. RaiseLastOSError();
  5297. }
  5298. }
  5299. FILE_OPERATION_LOOP_END(FMTLOAD(FILE_NOT_EXISTS, (FileName)));
  5300. if (FLAGCLEAR(Attrs, faDirectory) || (AHandle == NULL))
  5301. {
  5302. bool NoHandle = false;
  5303. if (!TryWriteReadOnly && (Access == GENERIC_WRITE) &&
  5304. ((Attrs & faReadOnly) != 0))
  5305. {
  5306. Access = GENERIC_READ;
  5307. NoHandle = true;
  5308. }
  5309. FILE_OPERATION_LOOP_BEGIN
  5310. {
  5311. DWORD Flags = FLAGMASK(FLAGSET(Attrs, faDirectory), FILE_FLAG_BACKUP_SEMANTICS);
  5312. Handle = CreateFile(ApiPath(FileName).c_str(), Access,
  5313. Access == GENERIC_READ ? FILE_SHARE_READ | FILE_SHARE_WRITE : FILE_SHARE_READ,
  5314. NULL, OPEN_EXISTING, Flags, 0);
  5315. if (Handle == INVALID_HANDLE_VALUE)
  5316. {
  5317. Handle = 0;
  5318. RaiseLastOSError();
  5319. }
  5320. }
  5321. FILE_OPERATION_LOOP_END(FMTLOAD(OPENFILE_ERROR, (FileName)));
  5322. try
  5323. {
  5324. if (AATime || AMTime || ACTime)
  5325. {
  5326. FILETIME ATime;
  5327. FILETIME MTime;
  5328. FILETIME CTime;
  5329. // Get last file access and modification time
  5330. FILE_OPERATION_LOOP_BEGIN
  5331. {
  5332. THROWOSIFFALSE(GetFileTime(Handle, &CTime, &ATime, &MTime));
  5333. }
  5334. FILE_OPERATION_LOOP_END(FMTLOAD(CANT_GET_ATTRS, (FileName)));
  5335. if (ACTime)
  5336. {
  5337. *ACTime = ConvertTimestampToUnixSafe(CTime, SessionData->DSTMode);
  5338. }
  5339. if (AATime)
  5340. {
  5341. *AATime = ConvertTimestampToUnixSafe(ATime, SessionData->DSTMode);
  5342. }
  5343. if (AMTime)
  5344. {
  5345. *AMTime = ConvertTimestampToUnix(MTime, SessionData->DSTMode);
  5346. }
  5347. }
  5348. if (ASize)
  5349. {
  5350. // Get file size
  5351. FILE_OPERATION_LOOP_BEGIN
  5352. {
  5353. unsigned long LSize;
  5354. unsigned long HSize;
  5355. LSize = GetFileSize(Handle, &HSize);
  5356. if ((LSize == 0xFFFFFFFF) && (GetLastError() != NO_ERROR)) RaiseLastOSError();
  5357. *ASize = (__int64(HSize) << 32) + LSize;
  5358. }
  5359. FILE_OPERATION_LOOP_END(FMTLOAD(CANT_GET_ATTRS, (FileName)));
  5360. }
  5361. if ((AHandle == NULL) || NoHandle)
  5362. {
  5363. CloseHandle(Handle);
  5364. Handle = NULL;
  5365. }
  5366. }
  5367. catch(...)
  5368. {
  5369. CloseHandle(Handle);
  5370. throw;
  5371. }
  5372. }
  5373. if (AAttrs) *AAttrs = Attrs;
  5374. if (AHandle) *AHandle = Handle;
  5375. }
  5376. //---------------------------------------------------------------------------
  5377. void __fastcall TTerminal::OpenLocalFile(
  5378. const UnicodeString & FileName, unsigned int Access, TLocalFileHandle & Handle, bool TryWriteReadOnly)
  5379. {
  5380. Handle.FileName = FileName;
  5381. OpenLocalFile(
  5382. FileName, Access, &Handle.Attrs, &Handle.Handle, NULL, &Handle.MTime, &Handle.ATime, &Handle.Size,
  5383. TryWriteReadOnly);
  5384. Handle.Modification = UnixToDateTime(Handle.MTime, SessionData->DSTMode);
  5385. Handle.Directory = FLAGSET(Handle.Attrs, faDirectory);
  5386. }
  5387. //---------------------------------------------------------------------------
  5388. bool __fastcall TTerminal::DoAllowLocalFileTransfer(
  5389. const UnicodeString & FileName, const TSearchRecSmart & SearchRec, const TCopyParamType * CopyParam, bool DisallowTemporaryTransferFiles)
  5390. {
  5391. TFileMasks::TParams Params;
  5392. Params.Size = SearchRec.Size;
  5393. Params.Modification = SearchRec.GetLastWriteTime();
  5394. UnicodeString BaseFileName = GetBaseFileName(FileName);
  5395. // Note that for synchronization, we do not need to check "TSynchronizeOptions::MatchesFilter" here as
  5396. // that is checked for top-level entries only and we are never top-level here.
  5397. return
  5398. CopyParam->AllowTransfer(BaseFileName, osLocal, SearchRec.IsDirectory(), Params, SearchRec.IsHidden()) &&
  5399. (!DisallowTemporaryTransferFiles || !FFileSystem->TemporaryTransferFile(FileName)) &&
  5400. (!SearchRec.IsDirectory() || !CopyParam->ExcludeEmptyDirectories ||
  5401. !IsEmptyLocalDirectory(FileName, CopyParam, DisallowTemporaryTransferFiles));
  5402. }
  5403. //---------------------------------------------------------------------------
  5404. bool __fastcall TTerminal::DoAllowRemoteFileTransfer(
  5405. const TRemoteFile * File, const TCopyParamType * CopyParam, bool DisallowTemporaryTransferFiles)
  5406. {
  5407. TFileMasks::TParams MaskParams;
  5408. MaskParams.Size = File->Resolve()->Size;
  5409. MaskParams.Modification = File->Modification;
  5410. UnicodeString FullRemoteFileName = UnixExcludeTrailingBackslash(File->FullFileName);
  5411. UnicodeString BaseFileName = GetBaseFileName(FullRemoteFileName);
  5412. return
  5413. CopyParam->AllowTransfer(BaseFileName, osRemote, File->IsDirectory, MaskParams, File->IsHidden) &&
  5414. (!DisallowTemporaryTransferFiles || !FFileSystem->TemporaryTransferFile(File->FileName)) &&
  5415. (!File->IsDirectory || !CopyParam->ExcludeEmptyDirectories ||
  5416. !IsEmptyRemoteDirectory(File, CopyParam, DisallowTemporaryTransferFiles));
  5417. }
  5418. //---------------------------------------------------------------------------
  5419. bool __fastcall TTerminal::AllowLocalFileTransfer(
  5420. const UnicodeString & FileName, const TSearchRecSmart * SearchRec,
  5421. const TCopyParamType * CopyParam, TFileOperationProgressType * OperationProgress)
  5422. {
  5423. bool Result = true;
  5424. // optimization (though in most uses of the method, the caller actually knows TSearchRec already, so it passes it here
  5425. if (Log->Logging || !CopyParam->AllowAnyTransfer())
  5426. {
  5427. TSearchRecSmart ASearchRec;
  5428. if (SearchRec == NULL)
  5429. {
  5430. if (CopyParam->OnTransferIn != NULL)
  5431. {
  5432. ASearchRec.Clear();
  5433. }
  5434. else
  5435. {
  5436. FILE_OPERATION_LOOP_BEGIN
  5437. {
  5438. if (!FileSearchRec(FileName, ASearchRec))
  5439. {
  5440. RaiseLastOSError();
  5441. }
  5442. }
  5443. FILE_OPERATION_LOOP_END(FMTLOAD(FILE_NOT_EXISTS, (FileName)));
  5444. }
  5445. SearchRec = &ASearchRec;
  5446. }
  5447. if (!DoAllowLocalFileTransfer(FileName, *SearchRec, CopyParam, false))
  5448. {
  5449. LogEvent(FORMAT(L"File \"%s\" excluded from transfer", (FileName)));
  5450. Result = false;
  5451. }
  5452. else if (CopyParam->SkipTransfer(FileName, SearchRec->IsDirectory()))
  5453. {
  5454. OperationProgress->AddSkippedFileSize(SearchRec->Size);
  5455. Result = false;
  5456. }
  5457. if (Result)
  5458. {
  5459. LogFileDetails(FileName, SearchRec->GetLastWriteTime(), SearchRec->Size);
  5460. }
  5461. }
  5462. return Result;
  5463. }
  5464. //---------------------------------------------------------------------------
  5465. void __fastcall TTerminal::MakeLocalFileList(
  5466. const UnicodeString & FileName, const TSearchRecSmart & Rec, void * Param)
  5467. {
  5468. TMakeLocalFileListParams & Params = *static_cast<TMakeLocalFileListParams*>(Param);
  5469. if (Rec.IsDirectory() && Params.Recursive)
  5470. {
  5471. ProcessLocalDirectory(FileName, MakeLocalFileList, &Params);
  5472. }
  5473. if (!Rec.IsDirectory() || Params.IncludeDirs)
  5474. {
  5475. Params.FileList->Add(FileName);
  5476. if (Params.FileTimes != NULL)
  5477. {
  5478. Params.FileTimes->push_back(const_cast<TSearchRecSmart &>(Rec).TimeStamp);
  5479. }
  5480. }
  5481. }
  5482. //---------------------------------------------------------------------------
  5483. void __fastcall TTerminal::CalculateLocalFileSize(
  5484. const UnicodeString & FileName, const TSearchRecSmart & Rec, /*TCalculateSizeParams*/ void * Params)
  5485. {
  5486. TCalculateSizeParams * AParams = static_cast<TCalculateSizeParams*>(Params);
  5487. if (!TryStartOperationWithFile(FileName, foCalculateSize))
  5488. {
  5489. AParams->Result = false;
  5490. }
  5491. else
  5492. {
  5493. try
  5494. {
  5495. if ((AParams->CopyParam == NULL) ||
  5496. DoAllowLocalFileTransfer(FileName, Rec, AParams->CopyParam, false))
  5497. {
  5498. int CollectionIndex = -1;
  5499. if (AParams->Files != NULL)
  5500. {
  5501. UnicodeString FullFileName = ::ExpandFileName(FileName);
  5502. CollectionIndex = AParams->Files->Add(FullFileName, NULL, Rec.IsDirectory());
  5503. }
  5504. if (!Rec.IsDirectory())
  5505. {
  5506. AParams->Size += Rec.Size;
  5507. }
  5508. else
  5509. {
  5510. try
  5511. {
  5512. ProcessLocalDirectory(FileName, CalculateLocalFileSize, Params);
  5513. }
  5514. catch (...)
  5515. {
  5516. if (CollectionIndex >= 0)
  5517. {
  5518. AParams->Files->DidNotRecurse(CollectionIndex);
  5519. }
  5520. }
  5521. }
  5522. }
  5523. }
  5524. catch (...)
  5525. {
  5526. // ignore
  5527. }
  5528. }
  5529. }
  5530. //---------------------------------------------------------------------------
  5531. bool __fastcall TTerminal::CalculateLocalFilesSize(TStrings * FileList,
  5532. __int64 & Size, const TCopyParamType * CopyParam, bool AllowDirs, TStrings * Files,
  5533. TCalculatedSizes * CalculatedSizes)
  5534. {
  5535. bool Result = false;
  5536. TFileOperationProgressType OperationProgress(&DoProgress, &DoFinished);
  5537. TOnceDoneOperation OnceDoneOperation = odoIdle;
  5538. OperationStart(OperationProgress, foCalculateSize, osLocal, FileList->Count);
  5539. try
  5540. {
  5541. TCalculateSizeParams Params;
  5542. Params.Size = 0;
  5543. Params.Params = 0;
  5544. Params.CopyParam = CopyParam;
  5545. Params.Files = NULL;
  5546. Params.Result = true;
  5547. UnicodeString LastDirPath;
  5548. for (int Index = 0; Params.Result && (Index < FileList->Count); Index++)
  5549. {
  5550. UnicodeString FileName = FileList->Strings[Index];
  5551. TSearchRecSmart Rec;
  5552. if (FileSearchRec(FileName, Rec))
  5553. {
  5554. if (Rec.IsDirectory() && !AllowDirs)
  5555. {
  5556. Params.Result = false;
  5557. }
  5558. else
  5559. {
  5560. if (Files != NULL)
  5561. {
  5562. UnicodeString FullFileName = ::ExpandFileName(FileName);
  5563. UnicodeString DirPath = ExtractFilePath(FullFileName);
  5564. if (DirPath != LastDirPath)
  5565. {
  5566. Params.Files = new TCollectedFileList();
  5567. LastDirPath = DirPath;
  5568. Files->AddObject(LastDirPath, Params.Files);
  5569. }
  5570. }
  5571. __int64 PrevSize = Params.Size;
  5572. CalculateLocalFileSize(FileName, Rec, &Params);
  5573. if (CalculatedSizes != NULL)
  5574. {
  5575. __int64 Size = Params.Size - PrevSize;
  5576. CalculatedSizes->push_back(Size);
  5577. }
  5578. OperationFinish(&OperationProgress, FileList->Objects[Index], FileName, true, OnceDoneOperation);
  5579. }
  5580. }
  5581. }
  5582. Size = Params.Size;
  5583. Result = Params.Result;
  5584. }
  5585. __finally
  5586. {
  5587. OperationStop(OperationProgress);
  5588. }
  5589. if (Configuration->ActualLogProtocol >= 1)
  5590. {
  5591. LogEvent(FORMAT(L"Size of %d local files/folders calculated as %s", (FileList->Count, IntToStr(Size))));
  5592. }
  5593. if (OnceDoneOperation != odoIdle)
  5594. {
  5595. CloseOnCompletion(OnceDoneOperation);
  5596. }
  5597. return Result;
  5598. }
  5599. //---------------------------------------------------------------------------
  5600. struct TSynchronizeFileData
  5601. {
  5602. bool Modified;
  5603. bool New;
  5604. bool IsDirectory;
  5605. TSynchronizeChecklist::TItem::TFileInfo Info;
  5606. TSynchronizeChecklist::TItem::TFileInfo MatchingRemoteFile;
  5607. TRemoteFile * MatchingRemoteFileFile;
  5608. int MatchingRemoteFileImageIndex;
  5609. FILETIME LocalLastWriteTime;
  5610. };
  5611. //---------------------------------------------------------------------------
  5612. const int sfFirstLevel = 0x01;
  5613. struct TSynchronizeData
  5614. {
  5615. UnicodeString LocalDirectory;
  5616. UnicodeString RemoteDirectory;
  5617. TTerminal::TSynchronizeMode Mode;
  5618. int Params;
  5619. TSynchronizeDirectory OnSynchronizeDirectory;
  5620. TSynchronizeOptions * Options;
  5621. int Flags;
  5622. TStringList * LocalFileList;
  5623. const TCopyParamType * CopyParam;
  5624. TSynchronizeChecklist * Checklist;
  5625. };
  5626. //---------------------------------------------------------------------------
  5627. TSynchronizeChecklist * __fastcall TTerminal::SynchronizeCollect(const UnicodeString LocalDirectory,
  5628. const UnicodeString RemoteDirectory, TSynchronizeMode Mode,
  5629. const TCopyParamType * CopyParam, int Params,
  5630. TSynchronizeDirectory OnSynchronizeDirectory,
  5631. TSynchronizeOptions * Options)
  5632. {
  5633. TValueRestorer<bool> UseBusyCursorRestorer(FUseBusyCursor, false);
  5634. TSynchronizeChecklist * Checklist = new TSynchronizeChecklist();
  5635. try
  5636. {
  5637. DoSynchronizeCollectDirectory(LocalDirectory, RemoteDirectory, Mode,
  5638. CopyParam, Params, OnSynchronizeDirectory, Options, sfFirstLevel,
  5639. Checklist);
  5640. Checklist->Sort();
  5641. }
  5642. catch(...)
  5643. {
  5644. delete Checklist;
  5645. throw;
  5646. }
  5647. return Checklist;
  5648. }
  5649. //---------------------------------------------------------------------------
  5650. static void __fastcall AddFlagName(UnicodeString & ParamsStr, int & Params, int Param, const UnicodeString & Name)
  5651. {
  5652. if (FLAGSET(Params, Param))
  5653. {
  5654. AddToList(ParamsStr, Name, ", ");
  5655. }
  5656. Params &= ~Param;
  5657. }
  5658. //---------------------------------------------------------------------------
  5659. UnicodeString __fastcall TTerminal::SynchronizeModeStr(TSynchronizeMode Mode)
  5660. {
  5661. UnicodeString ModeStr;
  5662. switch (Mode)
  5663. {
  5664. case smRemote:
  5665. ModeStr = L"Remote";
  5666. break;
  5667. case smLocal:
  5668. ModeStr = L"Local";
  5669. break;
  5670. case smBoth:
  5671. ModeStr = L"Both";
  5672. break;
  5673. default:
  5674. ModeStr = L"Unknown";
  5675. break;
  5676. }
  5677. return ModeStr;
  5678. }
  5679. //---------------------------------------------------------------------------
  5680. UnicodeString __fastcall TTerminal::SynchronizeParamsStr(int Params)
  5681. {
  5682. UnicodeString ParamsStr;
  5683. AddFlagName(ParamsStr, Params, spDelete, L"Delete");
  5684. AddFlagName(ParamsStr, Params, spNoConfirmation, L"NoConfirmation");
  5685. AddFlagName(ParamsStr, Params, spExistingOnly, L"ExistingOnly");
  5686. AddFlagName(ParamsStr, Params, spNoRecurse, L"NoRecurse");
  5687. AddFlagName(ParamsStr, Params, spUseCache, L"UseCache");
  5688. AddFlagName(ParamsStr, Params, spDelayProgress, L"DelayProgress");
  5689. AddFlagName(ParamsStr, Params, spPreviewChanges, L"*PreviewChanges"); // GUI only
  5690. AddFlagName(ParamsStr, Params, spSubDirs, L"SubDirs");
  5691. AddFlagName(ParamsStr, Params, spTimestamp, L"Timestamp");
  5692. AddFlagName(ParamsStr, Params, spNotByTime, L"NotByTime");
  5693. AddFlagName(ParamsStr, Params, spBySize, L"BySize");
  5694. AddFlagName(ParamsStr, Params, spByChecksum, L"ByChecksum");
  5695. AddFlagName(ParamsStr, Params, spCaseSensitive, L"CaseSensitive");
  5696. AddFlagName(ParamsStr, Params, spSelectedOnly, L"*SelectedOnly"); // GUI only
  5697. AddFlagName(ParamsStr, Params, spMirror, L"Mirror");
  5698. if (Params > 0)
  5699. {
  5700. AddToList(ParamsStr, FORMAT(L"0x%x", (int(Params))), L", ");
  5701. }
  5702. return ParamsStr;
  5703. }
  5704. //---------------------------------------------------------------------------
  5705. bool __fastcall TTerminal::LocalFindFirstLoop(const UnicodeString & Path, TSearchRecChecked & SearchRec)
  5706. {
  5707. bool Result;
  5708. FILE_OPERATION_LOOP_BEGIN
  5709. {
  5710. const int FindAttrs = faReadOnly | faHidden | faSysFile | faDirectory | faArchive;
  5711. Result = (FindFirstChecked(Path, FindAttrs, SearchRec) == 0);
  5712. }
  5713. FILE_OPERATION_LOOP_END(FMTLOAD(LIST_DIR_ERROR, (Path)));
  5714. return Result;
  5715. }
  5716. //---------------------------------------------------------------------------
  5717. bool __fastcall TTerminal::LocalFindNextLoop(TSearchRecChecked & SearchRec)
  5718. {
  5719. bool Result;
  5720. FILE_OPERATION_LOOP_BEGIN
  5721. {
  5722. Result = (FindNextChecked(SearchRec) == 0);
  5723. }
  5724. FILE_OPERATION_LOOP_END(FMTLOAD(LIST_DIR_ERROR, (SearchRec.Path)));
  5725. return Result;
  5726. }
  5727. //---------------------------------------------------------------------------
  5728. bool __fastcall TTerminal::IsEmptyLocalDirectory(
  5729. const UnicodeString & Path, const TCopyParamType * CopyParam, bool DisallowTemporaryTransferFiles)
  5730. {
  5731. UnicodeString Contents;
  5732. if (Configuration->ActualLogProtocol >= 1)
  5733. {
  5734. LogEvent(FORMAT(L"Checking if local directory \"%s\" is empty", (Path)));
  5735. }
  5736. TSearchRecOwned SearchRec;
  5737. if (LocalFindFirstLoop(IncludeTrailingBackslash(Path) + L"*.*", SearchRec))
  5738. {
  5739. do
  5740. {
  5741. UnicodeString FullLocalFileName = SearchRec.GetFilePath();
  5742. if (SearchRec.IsRealFile() &&
  5743. DoAllowLocalFileTransfer(FullLocalFileName, SearchRec, CopyParam, true))
  5744. {
  5745. if (!SearchRec.IsDirectory() ||
  5746. !IsEmptyLocalDirectory(FullLocalFileName, CopyParam, DisallowTemporaryTransferFiles))
  5747. {
  5748. Contents = SearchRec.Name;
  5749. }
  5750. }
  5751. }
  5752. while (Contents.IsEmpty() && LocalFindNextLoop(SearchRec));
  5753. }
  5754. if (Configuration->ActualLogProtocol >= 1)
  5755. {
  5756. if (Contents.IsEmpty())
  5757. {
  5758. LogEvent(FORMAT(L"Local directory \"%s\" is empty", (Path)));
  5759. }
  5760. else
  5761. {
  5762. LogEvent(FORMAT(L"Local directory \"%s\" is not empty, it contains \"%s\"", (Path, Contents)));
  5763. }
  5764. }
  5765. return Contents.IsEmpty();
  5766. }
  5767. //---------------------------------------------------------------------------
  5768. void __fastcall TTerminal::DoSynchronizeCollectDirectory(const UnicodeString LocalDirectory,
  5769. const UnicodeString RemoteDirectory, TSynchronizeMode Mode,
  5770. const TCopyParamType * CopyParam, int Params,
  5771. TSynchronizeDirectory OnSynchronizeDirectory, TSynchronizeOptions * Options,
  5772. int Flags, TSynchronizeChecklist * Checklist)
  5773. {
  5774. TSynchronizeData Data;
  5775. Data.LocalDirectory = IncludeTrailingBackslash(LocalDirectory);
  5776. Data.RemoteDirectory = UnixIncludeTrailingBackslash(RemoteDirectory);
  5777. Data.Mode = Mode;
  5778. Data.Params = Params;
  5779. Data.OnSynchronizeDirectory = OnSynchronizeDirectory;
  5780. Data.LocalFileList = NULL;
  5781. Data.CopyParam = CopyParam;
  5782. Data.Options = Options;
  5783. Data.Flags = Flags;
  5784. Data.Checklist = Checklist;
  5785. LogEvent(FORMAT(L"Collecting synchronization list for local directory '%s' and remote directory '%s', "
  5786. "mode = %s, params = 0x%x (%s), file mask = '%s'", (LocalDirectory, RemoteDirectory,
  5787. SynchronizeModeStr(Mode), int(Params), SynchronizeParamsStr(Params), CopyParam->IncludeFileMask.Masks)));
  5788. if (FLAGCLEAR(Params, spDelayProgress))
  5789. {
  5790. DoSynchronizeProgress(Data, true);
  5791. }
  5792. try
  5793. {
  5794. Data.LocalFileList = CreateSortedStringList(FLAGSET(Params, spCaseSensitive));
  5795. TSearchRecOwned SearchRec;
  5796. if (LocalFindFirstLoop(Data.LocalDirectory + L"*.*", SearchRec))
  5797. {
  5798. do
  5799. {
  5800. UnicodeString FileName = SearchRec.Name;
  5801. UnicodeString FullLocalFileName = SearchRec.GetFilePath();
  5802. UnicodeString RemoteFileName = ChangeFileName(CopyParam, FileName, osLocal, false);
  5803. if (SearchRec.IsRealFile() &&
  5804. DoAllowLocalFileTransfer(FullLocalFileName, SearchRec, CopyParam, true) &&
  5805. (FLAGCLEAR(Flags, sfFirstLevel) ||
  5806. (Options == NULL) ||
  5807. Options->MatchesFilter(FileName) ||
  5808. Options->MatchesFilter(RemoteFileName)))
  5809. {
  5810. TSynchronizeFileData * FileData = new TSynchronizeFileData;
  5811. FileData->IsDirectory = SearchRec.IsDirectory();
  5812. FileData->Info.FileName = FileName;
  5813. FileData->Info.Directory = Data.LocalDirectory;
  5814. FileData->Info.Modification = SearchRec.GetLastWriteTime();
  5815. FileData->Info.ModificationFmt = mfFull;
  5816. FileData->Info.Size = SearchRec.Size;
  5817. FileData->LocalLastWriteTime = SearchRec.FindData.ftLastWriteTime;
  5818. FileData->New = true;
  5819. FileData->Modified = false;
  5820. Data.LocalFileList->AddObject(FileName, reinterpret_cast<TObject*>(FileData));
  5821. LogEvent(0, FORMAT(L"Local file %s included to synchronization",
  5822. (FormatFileDetailsForLog(FullLocalFileName, SearchRec.GetLastWriteTime(), SearchRec.Size))));
  5823. }
  5824. else
  5825. {
  5826. LogEvent(0, FORMAT(L"Local file %s excluded from synchronization",
  5827. (FormatFileDetailsForLog(FullLocalFileName, SearchRec.GetLastWriteTime(), SearchRec.Size))));
  5828. }
  5829. }
  5830. while (LocalFindNextLoop(SearchRec));
  5831. SearchRec.Close();
  5832. // can we expect that ProcessDirectory would take so little time
  5833. // that we can postpone showing progress window until anything actually happens?
  5834. bool Cached = FLAGSET(Params, spUseCache) && SessionData->CacheDirectories &&
  5835. FDirectoryCache->HasFileList(RemoteDirectory);
  5836. if (!Cached && FLAGSET(Params, spDelayProgress))
  5837. {
  5838. DoSynchronizeProgress(Data, true);
  5839. }
  5840. ProcessDirectory(RemoteDirectory, SynchronizeCollectFile, &Data,
  5841. FLAGSET(Params, spUseCache));
  5842. TSynchronizeFileData * FileData;
  5843. for (int Index = 0; Index < Data.LocalFileList->Count; Index++)
  5844. {
  5845. FileData = reinterpret_cast<TSynchronizeFileData *>
  5846. (Data.LocalFileList->Objects[Index]);
  5847. // add local file either if we are going to upload it
  5848. // (i.e. if it is updated or we want to upload even new files)
  5849. // or if we are going to delete it (i.e. all "new"=obsolete files)
  5850. bool Modified = (FileData->Modified && ((Mode == smBoth) || (Mode == smRemote)));
  5851. bool New = (FileData->New &&
  5852. ((Mode == smLocal) ||
  5853. (((Mode == smBoth) || (Mode == smRemote)) && FLAGCLEAR(Params, spTimestamp))));
  5854. if (New)
  5855. {
  5856. LogEvent(FORMAT(L"Local file %s is new",
  5857. (FormatFileDetailsForLog(FileData->Info.Directory + FileData->Info.FileName,
  5858. FileData->Info.Modification, FileData->Info.Size))));
  5859. }
  5860. if (Modified || New)
  5861. {
  5862. TSynchronizeChecklist::TItem * ChecklistItem = new TSynchronizeChecklist::TItem();
  5863. try
  5864. {
  5865. ChecklistItem->IsDirectory = FileData->IsDirectory;
  5866. ChecklistItem->Local = FileData->Info;
  5867. ChecklistItem->FLocalLastWriteTime = FileData->LocalLastWriteTime;
  5868. if (Modified)
  5869. {
  5870. DebugAssert(!FileData->MatchingRemoteFile.Directory.IsEmpty());
  5871. ChecklistItem->Remote = FileData->MatchingRemoteFile;
  5872. ChecklistItem->ImageIndex = FileData->MatchingRemoteFileImageIndex;
  5873. ChecklistItem->RemoteFile = FileData->MatchingRemoteFileFile;
  5874. }
  5875. else
  5876. {
  5877. ChecklistItem->Remote.Directory = Data.RemoteDirectory;
  5878. }
  5879. if ((Mode == smBoth) || (Mode == smRemote))
  5880. {
  5881. ChecklistItem->Action =
  5882. (Modified ? TSynchronizeChecklist::saUploadUpdate : TSynchronizeChecklist::saUploadNew);
  5883. ChecklistItem->Checked =
  5884. (Modified || FLAGCLEAR(Params, spExistingOnly)) &&
  5885. (!ChecklistItem->IsDirectory || FLAGCLEAR(Params, spNoRecurse) ||
  5886. FLAGSET(Params, spSubDirs));
  5887. }
  5888. else if ((Mode == smLocal) && FLAGCLEAR(Params, spTimestamp))
  5889. {
  5890. ChecklistItem->Action = TSynchronizeChecklist::saDeleteLocal;
  5891. ChecklistItem->Checked =
  5892. FLAGSET(Params, spDelete) &&
  5893. (!ChecklistItem->IsDirectory || FLAGCLEAR(Params, spNoRecurse) ||
  5894. FLAGSET(Params, spSubDirs));
  5895. }
  5896. if (ChecklistItem->Action != TSynchronizeChecklist::saNone)
  5897. {
  5898. Data.Checklist->Add(ChecklistItem);
  5899. ChecklistItem = NULL;
  5900. }
  5901. }
  5902. __finally
  5903. {
  5904. delete ChecklistItem;
  5905. }
  5906. }
  5907. else
  5908. {
  5909. if (FileData->Modified)
  5910. {
  5911. delete FileData->MatchingRemoteFileFile;
  5912. }
  5913. }
  5914. }
  5915. }
  5916. }
  5917. __finally
  5918. {
  5919. if (Data.LocalFileList != NULL)
  5920. {
  5921. for (int Index = 0; Index < Data.LocalFileList->Count; Index++)
  5922. {
  5923. TSynchronizeFileData * FileData = reinterpret_cast<TSynchronizeFileData*>
  5924. (Data.LocalFileList->Objects[Index]);
  5925. delete FileData;
  5926. }
  5927. delete Data.LocalFileList;
  5928. }
  5929. }
  5930. }
  5931. //---------------------------------------------------------------------------
  5932. void __fastcall TTerminal::SynchronizeCollectFile(const UnicodeString FileName,
  5933. const TRemoteFile * File, /*TSynchronizeData*/ void * Param)
  5934. {
  5935. try
  5936. {
  5937. DoSynchronizeCollectFile(FileName, File, Param);
  5938. }
  5939. catch(ESkipFile & E)
  5940. {
  5941. TSuspendFileOperationProgress Suspend(OperationProgress);
  5942. if (!HandleException(&E))
  5943. {
  5944. throw;
  5945. }
  5946. }
  5947. }
  5948. //---------------------------------------------------------------------------
  5949. bool __fastcall TTerminal::IsEmptyRemoteDirectory(
  5950. const TRemoteFile * File, const TCopyParamType * ACopyParam, bool DisallowTemporaryTransferFiles)
  5951. {
  5952. TCalculateSizeStats Stats;
  5953. TCopyParamType CopyParam(*ACopyParam);
  5954. CopyParam.ExcludeEmptyDirectories = false; // to avoid endless recursion
  5955. TCalculateSizeParams Params;
  5956. Params.Params = csStopOnFirstFile | csIgnoreErrors | FLAGMASK(DisallowTemporaryTransferFiles, csDisallowTemporaryTransferFiles);
  5957. Params.CopyParam = &CopyParam;
  5958. Params.Stats = &Stats;
  5959. DoCalculateDirectorySize(UnixExcludeTrailingBackslash(File->FullFileName), &Params);
  5960. return Params.Result && (Stats.Files == 0);
  5961. }
  5962. //---------------------------------------------------------------------------
  5963. void __fastcall TTerminal::CollectCalculatedChecksum(
  5964. const UnicodeString & DebugUsedArg(FileName), const UnicodeString & DebugUsedArg(Alg), const UnicodeString & Hash)
  5965. {
  5966. DebugAssert(FCollectedCalculatedChecksum.IsEmpty());
  5967. FCollectedCalculatedChecksum = Hash;
  5968. }
  5969. //---------------------------------------------------------------------------
  5970. bool TTerminal::SameFileChecksum(const UnicodeString & LocalFileName, const TRemoteFile * File)
  5971. {
  5972. UnicodeString DefaultAlg = Sha256ChecksumAlg;
  5973. UnicodeString Algs =
  5974. DefaultStr(Configuration->SynchronizationChecksumAlgs, DefaultAlg + L"," + Sha1ChecksumAlg);
  5975. std::unique_ptr<TStrings> SupportedAlgs(CreateSortedStringList());
  5976. GetSupportedChecksumAlgs(SupportedAlgs.get());
  5977. UnicodeString Alg;
  5978. while (Alg.IsEmpty() && !Algs.IsEmpty())
  5979. {
  5980. UnicodeString A = CutToChar(Algs, L',', true);
  5981. if (SupportedAlgs->IndexOf(A) >= 0)
  5982. {
  5983. Alg = A;
  5984. }
  5985. }
  5986. if (Alg.IsEmpty())
  5987. {
  5988. Alg = DefaultAlg;
  5989. }
  5990. std::unique_ptr<TStrings> FileList(new TStringList());
  5991. FileList->AddObject(File->FullFileName, File);
  5992. DebugAssert(FCollectedCalculatedChecksum.IsEmpty());
  5993. FCollectedCalculatedChecksum = EmptyStr;
  5994. CalculateFilesChecksum(Alg, FileList.get(), CollectCalculatedChecksum);
  5995. UnicodeString RemoteChecksum = FCollectedCalculatedChecksum;
  5996. FCollectedCalculatedChecksum = EmptyStr;
  5997. UnicodeString LocalChecksum;
  5998. FILE_OPERATION_LOOP_BEGIN
  5999. {
  6000. std::unique_ptr<THandleStream> Stream(TSafeHandleStream::CreateFromFile(LocalFileName, fmOpenRead | fmShareDenyWrite));
  6001. LocalChecksum = CalculateFileChecksum(Stream.get(), Alg);
  6002. }
  6003. FILE_OPERATION_LOOP_END(FMTLOAD(CHECKSUM_ERROR, (LocalFileName)));
  6004. return SameText(RemoteChecksum, LocalChecksum);
  6005. }
  6006. //---------------------------------------------------------------------------
  6007. void __fastcall TTerminal::DoSynchronizeCollectFile(const UnicodeString FileName,
  6008. const TRemoteFile * File, /*TSynchronizeData*/ void * Param)
  6009. {
  6010. TSynchronizeData * Data = static_cast<TSynchronizeData *>(Param);
  6011. // Can be NULL in scripting
  6012. if (Data->Options != NULL)
  6013. {
  6014. Data->Options->Files++;
  6015. }
  6016. UnicodeString LocalFileName = ChangeFileName(Data->CopyParam, File->FileName, osRemote, false);
  6017. UnicodeString FullRemoteFileName = UnixExcludeTrailingBackslash(File->FullFileName);
  6018. if (DoAllowRemoteFileTransfer(File, Data->CopyParam, true) &&
  6019. (FLAGCLEAR(Data->Flags, sfFirstLevel) ||
  6020. (Data->Options == NULL) ||
  6021. Data->Options->MatchesFilter(File->FileName) ||
  6022. Data->Options->MatchesFilter(LocalFileName)))
  6023. {
  6024. TSynchronizeChecklist::TItem * ChecklistItem = new TSynchronizeChecklist::TItem();
  6025. try
  6026. {
  6027. ChecklistItem->IsDirectory = File->IsDirectory;
  6028. ChecklistItem->ImageIndex = File->IconIndex;
  6029. ChecklistItem->Remote.FileName = File->FileName;
  6030. ChecklistItem->Remote.Directory = Data->RemoteDirectory;
  6031. ChecklistItem->Remote.Modification = File->Modification;
  6032. ChecklistItem->Remote.ModificationFmt = File->ModificationFmt;
  6033. ChecklistItem->Remote.Size = File->Resolve()->Size;
  6034. bool Modified = false;
  6035. bool New = false;
  6036. if (File->IsDirectory && !CanRecurseToDirectory(File))
  6037. {
  6038. LogEvent(FORMAT(L"Skipping symlink to directory \"%s\".", (File->FileName)));
  6039. }
  6040. else
  6041. {
  6042. int LocalIndex = Data->LocalFileList->IndexOf(LocalFileName);
  6043. New = (LocalIndex < 0);
  6044. if (!New)
  6045. {
  6046. TSynchronizeFileData * LocalData =
  6047. reinterpret_cast<TSynchronizeFileData *>(Data->LocalFileList->Objects[LocalIndex]);
  6048. LocalData->New = false;
  6049. UnicodeString FullLocalFileName = LocalData->Info.Directory + LocalData->Info.FileName;
  6050. if (File->IsDirectory != LocalData->IsDirectory)
  6051. {
  6052. LogEvent(FORMAT(L"%s is directory on one side, but file on the another",
  6053. (File->FileName)));
  6054. }
  6055. else if (!File->IsDirectory)
  6056. {
  6057. ChecklistItem->Local = LocalData->Info;
  6058. ChecklistItem->Local.Modification =
  6059. ReduceDateTimePrecision(ChecklistItem->Local.Modification, File->ModificationFmt);
  6060. bool LocalModified = false;
  6061. // for spTimestamp+spBySize require that the file sizes are the same
  6062. // before comparing file time
  6063. int TimeCompare;
  6064. if (FLAGCLEAR(Data->Params, spNotByTime) &&
  6065. (FLAGCLEAR(Data->Params, spTimestamp) ||
  6066. FLAGCLEAR(Data->Params, spBySize) ||
  6067. (ChecklistItem->Local.Size == ChecklistItem->Remote.Size)))
  6068. {
  6069. TimeCompare = CompareFileTime(ChecklistItem->Local.Modification,
  6070. ChecklistItem->Remote.Modification);
  6071. }
  6072. else
  6073. {
  6074. TimeCompare = 0;
  6075. }
  6076. if (TimeCompare < 0)
  6077. {
  6078. if ((FLAGCLEAR(Data->Params, spTimestamp) && FLAGCLEAR(Data->Params, spMirror)) ||
  6079. (Data->Mode == smBoth) || (Data->Mode == smLocal))
  6080. {
  6081. Modified = true;
  6082. }
  6083. else
  6084. {
  6085. LocalModified = true;
  6086. }
  6087. }
  6088. else if (TimeCompare > 0)
  6089. {
  6090. if ((FLAGCLEAR(Data->Params, spTimestamp) && FLAGCLEAR(Data->Params, spMirror)) ||
  6091. (Data->Mode == smBoth) || (Data->Mode == smRemote))
  6092. {
  6093. LocalModified = true;
  6094. }
  6095. else
  6096. {
  6097. Modified = true;
  6098. }
  6099. }
  6100. else if (FLAGSET(Data->Params, spBySize) &&
  6101. (ChecklistItem->Local.Size != ChecklistItem->Remote.Size) &&
  6102. FLAGCLEAR(Data->Params, spTimestamp))
  6103. {
  6104. Modified = true;
  6105. LocalModified = true;
  6106. }
  6107. else if (FLAGSET(Data->Params, spByChecksum) &&
  6108. FLAGCLEAR(Data->Params, spTimestamp) &&
  6109. !SameFileChecksum(FullLocalFileName, File) &&
  6110. FLAGCLEAR(Data->Params, spTimestamp))
  6111. {
  6112. Modified = true;
  6113. LocalModified = true;
  6114. }
  6115. if (LocalModified)
  6116. {
  6117. LocalData->Modified = true;
  6118. LocalData->MatchingRemoteFile = ChecklistItem->Remote;
  6119. LocalData->MatchingRemoteFileImageIndex = ChecklistItem->ImageIndex;
  6120. // we need this for custom commands over checklist only,
  6121. // not for sync itself
  6122. LocalData->MatchingRemoteFileFile = File->Duplicate();
  6123. LogEvent(FORMAT(L"Local file %s is modified comparing to remote file %s",
  6124. (FormatFileDetailsForLog(FullLocalFileName, LocalData->Info.Modification, LocalData->Info.Size),
  6125. FormatFileDetailsForLog(FullRemoteFileName, File->Modification, File->Size, File->LinkedFile))));
  6126. }
  6127. if (Modified)
  6128. {
  6129. LogEvent(FORMAT(L"Remote file %s is modified comparing to local file %s",
  6130. (FormatFileDetailsForLog(FullRemoteFileName, File->Modification, File->Size, File->LinkedFile),
  6131. FormatFileDetailsForLog(FullLocalFileName, LocalData->Info.Modification, LocalData->Info.Size))));
  6132. }
  6133. }
  6134. else if (FLAGCLEAR(Data->Params, spNoRecurse))
  6135. {
  6136. DoSynchronizeCollectDirectory(
  6137. FullLocalFileName, FullRemoteFileName,
  6138. Data->Mode, Data->CopyParam, Data->Params, Data->OnSynchronizeDirectory,
  6139. Data->Options, (Data->Flags & ~sfFirstLevel),
  6140. Data->Checklist);
  6141. }
  6142. }
  6143. else
  6144. {
  6145. ChecklistItem->Local.Directory = Data->LocalDirectory;
  6146. LogEvent(FORMAT(L"Remote file %s is new",
  6147. (FormatFileDetailsForLog(FullRemoteFileName, File->Modification, File->Size, File->LinkedFile))));
  6148. }
  6149. }
  6150. if (New || Modified)
  6151. {
  6152. DebugAssert(!New || !Modified);
  6153. // download the file if it changed or is new and we want to have it locally
  6154. if ((Data->Mode == smBoth) || (Data->Mode == smLocal))
  6155. {
  6156. if (FLAGCLEAR(Data->Params, spTimestamp) || Modified)
  6157. {
  6158. ChecklistItem->Action =
  6159. (Modified ? TSynchronizeChecklist::saDownloadUpdate : TSynchronizeChecklist::saDownloadNew);
  6160. ChecklistItem->Checked =
  6161. (Modified || FLAGCLEAR(Data->Params, spExistingOnly)) &&
  6162. (!ChecklistItem->IsDirectory || FLAGCLEAR(Data->Params, spNoRecurse) ||
  6163. FLAGSET(Data->Params, spSubDirs));
  6164. }
  6165. }
  6166. else if ((Data->Mode == smRemote) && New)
  6167. {
  6168. if (FLAGCLEAR(Data->Params, spTimestamp))
  6169. {
  6170. ChecklistItem->Action = TSynchronizeChecklist::saDeleteRemote;
  6171. ChecklistItem->Checked =
  6172. FLAGSET(Data->Params, spDelete) &&
  6173. (!ChecklistItem->IsDirectory || FLAGCLEAR(Data->Params, spNoRecurse) ||
  6174. FLAGSET(Data->Params, spSubDirs));
  6175. }
  6176. }
  6177. if (ChecklistItem->Action != TSynchronizeChecklist::saNone)
  6178. {
  6179. ChecklistItem->RemoteFile = File->Duplicate();
  6180. Data->Checklist->Add(ChecklistItem);
  6181. ChecklistItem = NULL;
  6182. }
  6183. }
  6184. }
  6185. __finally
  6186. {
  6187. delete ChecklistItem;
  6188. }
  6189. }
  6190. else
  6191. {
  6192. LogEvent(0, FORMAT(L"Remote file %s excluded from synchronization",
  6193. (FormatFileDetailsForLog(FullRemoteFileName, File->Modification, File->Size, File->LinkedFile))));
  6194. }
  6195. }
  6196. //---------------------------------------------------------------------------
  6197. void __fastcall TTerminal::SynchronizeApply(
  6198. TSynchronizeChecklist * Checklist,
  6199. const TCopyParamType * CopyParam, int Params,
  6200. TSynchronizeDirectory OnSynchronizeDirectory, TProcessedSynchronizationChecklistItem OnProcessedItem,
  6201. TUpdatedSynchronizationChecklistItems OnUpdatedSynchronizationChecklistItems, void * Token,
  6202. TFileOperationStatistics * Statistics)
  6203. {
  6204. TSynchronizeData Data;
  6205. Data.OnSynchronizeDirectory = OnSynchronizeDirectory;
  6206. int CopyParams =
  6207. FLAGMASK(FLAGSET(Params, spNoConfirmation), cpNoConfirmation);
  6208. TCopyParamType SyncCopyParam = *CopyParam;
  6209. // when synchronizing by time, we force preserving time,
  6210. // otherwise it does not make any sense
  6211. if (FLAGCLEAR(Params, spNotByTime))
  6212. {
  6213. SyncCopyParam.PreserveTime = true;
  6214. }
  6215. if (SyncCopyParam.CalculateSize)
  6216. {
  6217. // If we fail to collect the sizes, do not try again during an actual transfer
  6218. SyncCopyParam.CalculateSize = false;
  6219. TSynchronizeChecklist::TItemList Items;
  6220. for (int Index = 0; Index < Checklist->Count; Index++)
  6221. {
  6222. const TSynchronizeChecklist::TItem * ChecklistItem = Checklist->Item[Index];
  6223. // TSynchronizeChecklistDialog relies on us not to update a size of an item that had size already
  6224. // See TSynchronizeChecklistDialog::UpdatedSynchronizationChecklistItems
  6225. if (ChecklistItem->Checked && !TSynchronizeChecklist::IsItemSizeIrrelevant(ChecklistItem->Action) &&
  6226. !ChecklistItem->HasSize() && DebugAlwaysTrue(ChecklistItem->IsDirectory))
  6227. {
  6228. Items.push_back(ChecklistItem);
  6229. }
  6230. }
  6231. SynchronizeChecklistCalculateSize(Checklist, Items, &SyncCopyParam);
  6232. if (OnUpdatedSynchronizationChecklistItems != NULL)
  6233. {
  6234. OnUpdatedSynchronizationChecklistItems(Items);
  6235. }
  6236. }
  6237. BeginTransaction();
  6238. TValueRestorer<TFileOperationProgressType::TPersistence *> OperationProgressPersistenceRestorer(FOperationProgressPersistence);
  6239. TValueRestorer<TOnceDoneOperation> OperationProgressOnceDoneOperationRestorer(FOperationProgressOnceDoneOperation);
  6240. TFileOperationProgressType::TPersistence OperationProgressPersistence;
  6241. OperationProgressPersistence.Statistics = Statistics;
  6242. FOperationProgressPersistence = &OperationProgressPersistence;
  6243. try
  6244. {
  6245. int Index = 0;
  6246. while (Index < Checklist->Count)
  6247. {
  6248. const TSynchronizeChecklist::TItem * ChecklistItem = Checklist->Item[Index];
  6249. if (ChecklistItem->Checked)
  6250. {
  6251. if (!SamePaths(Data.LocalDirectory, ChecklistItem->Local.Directory) ||
  6252. !UnixSamePath(Data.RemoteDirectory, ChecklistItem->Remote.Directory))
  6253. {
  6254. Data.LocalDirectory = IncludeTrailingBackslash(ChecklistItem->Local.Directory);
  6255. Data.RemoteDirectory = UnixIncludeTrailingBackslash(ChecklistItem->Remote.Directory);
  6256. LogEvent(
  6257. FORMAT(L"Synchronizing local directory '%s' with remote directory '%s', params = 0x%x (%s)",
  6258. (Data.LocalDirectory, Data.RemoteDirectory, int(Params), SynchronizeParamsStr(Params))));
  6259. DoSynchronizeProgress(Data, false);
  6260. }
  6261. std::unique_ptr<TStringList> FileList(new TStringList());
  6262. UnicodeString LocalPath = IncludeTrailingBackslash(ChecklistItem->Local.Directory) + ChecklistItem->Local.FileName;
  6263. UnicodeString RemotePath = UnixIncludeTrailingBackslash(ChecklistItem->Remote.Directory) + ChecklistItem->Remote.FileName;
  6264. bool Result = true;
  6265. if (FLAGSET(Params, spTimestamp))
  6266. {
  6267. // used by SynchronizeLocalTimestamp and SynchronizeRemoteTimestamp
  6268. TObject * ChecklistItemToken = const_cast<TObject *>(reinterpret_cast<const TObject *>(ChecklistItem));
  6269. switch (ChecklistItem->Action)
  6270. {
  6271. case TSynchronizeChecklist::saDownloadUpdate:
  6272. FileList->AddObject(RemotePath, ChecklistItemToken);
  6273. ProcessFiles(FileList.get(), foSetProperties, SynchronizeLocalTimestamp, NULL, osLocal);
  6274. break;
  6275. case TSynchronizeChecklist::saUploadUpdate:
  6276. FileList->AddObject(LocalPath, ChecklistItemToken);
  6277. ProcessFiles(FileList.get(), foSetProperties, SynchronizeRemoteTimestamp);
  6278. break;
  6279. default:
  6280. DebugFail();
  6281. Result = false;
  6282. break;
  6283. }
  6284. }
  6285. else
  6286. {
  6287. TCopyParamType ItemCopyParam = SyncCopyParam;
  6288. ItemCopyParam.Size = ChecklistItem->HasSize() ? ChecklistItem->GetSize() : -1;
  6289. switch (ChecklistItem->Action)
  6290. {
  6291. case TSynchronizeChecklist::saDownloadNew:
  6292. case TSynchronizeChecklist::saDownloadUpdate:
  6293. FileList->AddObject(RemotePath, ChecklistItem->RemoteFile);
  6294. Result = CopyToLocal(FileList.get(), Data.LocalDirectory, &ItemCopyParam, CopyParams, NULL);
  6295. break;
  6296. case TSynchronizeChecklist::saDeleteRemote:
  6297. FileList->AddObject(RemotePath, ChecklistItem->RemoteFile);
  6298. Result = DeleteFiles(FileList.get());
  6299. break;
  6300. case TSynchronizeChecklist::saUploadNew:
  6301. case TSynchronizeChecklist::saUploadUpdate:
  6302. FileList->Add(LocalPath);
  6303. Result = CopyToRemote(FileList.get(), Data.RemoteDirectory, &ItemCopyParam, CopyParams, NULL);
  6304. break;
  6305. case TSynchronizeChecklist::saDeleteLocal:
  6306. FileList->Add(LocalPath);
  6307. Result = DeleteLocalFiles(FileList.get());
  6308. break;
  6309. default:
  6310. DebugFail();
  6311. Result = false;
  6312. break;
  6313. }
  6314. }
  6315. if (!Result)
  6316. {
  6317. Abort();
  6318. }
  6319. if (OnProcessedItem != NULL)
  6320. {
  6321. OnProcessedItem(Token, ChecklistItem);
  6322. }
  6323. }
  6324. Index++;
  6325. }
  6326. }
  6327. __finally
  6328. {
  6329. EndTransaction();
  6330. }
  6331. if (FOperationProgressOnceDoneOperation != odoIdle)
  6332. {
  6333. // Otherwise CloseOnCompletion would have no effect
  6334. OperationProgressPersistenceRestorer.Release();
  6335. CloseOnCompletion(FOperationProgressOnceDoneOperation);
  6336. }
  6337. }
  6338. //---------------------------------------------------------------------------
  6339. void __fastcall TTerminal::SynchronizeChecklistCalculateSize(
  6340. TSynchronizeChecklist * Checklist, const TSynchronizeChecklist::TItemList & Items,
  6341. const TCopyParamType * CopyParam)
  6342. {
  6343. std::unique_ptr<TStrings> RemoteFileList(new TStringList());
  6344. std::unique_ptr<TStrings> LocalFileList(new TStringList());
  6345. for (size_t Index = 0; Index < Items.size(); Index++)
  6346. {
  6347. const TSynchronizeChecklist::TItem * ChecklistItem = Items[Index];
  6348. if (ChecklistItem->IsDirectory)
  6349. {
  6350. if (ChecklistItem->IsRemoteOnly())
  6351. {
  6352. RemoteFileList->AddObject(ChecklistItem->RemoteFile->FullFileName, ChecklistItem->RemoteFile);
  6353. }
  6354. else if (ChecklistItem->IsLocalOnly())
  6355. {
  6356. LocalFileList->Add(IncludeTrailingBackslash(ChecklistItem->Local.Directory) + ChecklistItem->Local.FileName);
  6357. }
  6358. else
  6359. {
  6360. // "update" actions are not relevant for directories
  6361. DebugFail();
  6362. }
  6363. }
  6364. }
  6365. TCalculatedSizes RemoteCalculatedSizes;
  6366. TCalculatedSizes LocalCalculatedSizes;
  6367. try
  6368. {
  6369. bool Result = true;
  6370. if (LocalFileList->Count > 0)
  6371. {
  6372. __int64 LocalSize = 0;
  6373. Result = CalculateLocalFilesSize(LocalFileList.get(), LocalSize, CopyParam, true, NULL, &LocalCalculatedSizes);
  6374. }
  6375. if (Result && (RemoteFileList->Count > 0))
  6376. {
  6377. __int64 RemoteSize = 0;
  6378. TCalculateSizeStats RemoteStats;
  6379. RemoteStats.CalculatedSizes = &RemoteCalculatedSizes;
  6380. TCalculateSizeParams Params;
  6381. Params.CopyParam = CopyParam;
  6382. Params.Stats = &RemoteStats;
  6383. CalculateFilesSize(RemoteFileList.get(), RemoteSize, Params);
  6384. }
  6385. }
  6386. __finally
  6387. {
  6388. size_t LocalIndex = 0;
  6389. size_t RemoteIndex = 0;
  6390. for (size_t Index = 0; Index < Items.size(); Index++)
  6391. {
  6392. const TSynchronizeChecklist::TItem * ChecklistItem = Items[Index];
  6393. if (ChecklistItem->IsDirectory)
  6394. {
  6395. __int64 Size = -1;
  6396. if (ChecklistItem->IsRemoteOnly())
  6397. {
  6398. if (RemoteIndex < RemoteCalculatedSizes.size())
  6399. {
  6400. Size = RemoteCalculatedSizes[RemoteIndex];
  6401. }
  6402. RemoteIndex++;
  6403. }
  6404. else if (ChecklistItem->IsLocalOnly())
  6405. {
  6406. if (LocalIndex < LocalCalculatedSizes.size())
  6407. {
  6408. Size = LocalCalculatedSizes[LocalIndex];
  6409. }
  6410. LocalIndex++;
  6411. }
  6412. else
  6413. {
  6414. // "update" actions are not relevant for directories
  6415. DebugFail();
  6416. }
  6417. if (Size >= 0)
  6418. {
  6419. Checklist->UpdateDirectorySize(ChecklistItem, Size);
  6420. }
  6421. }
  6422. }
  6423. DebugAssert(RemoteIndex >= RemoteCalculatedSizes.size());
  6424. DebugAssert(LocalIndex >= LocalCalculatedSizes.size());
  6425. }
  6426. }
  6427. //---------------------------------------------------------------------------
  6428. void __fastcall TTerminal::DoSynchronizeProgress(const TSynchronizeData & Data,
  6429. bool Collect)
  6430. {
  6431. if (Data.OnSynchronizeDirectory != NULL)
  6432. {
  6433. bool Continue = true;
  6434. Data.OnSynchronizeDirectory(
  6435. Data.LocalDirectory, Data.RemoteDirectory, Continue, Collect, Data.Options);
  6436. if (!Continue)
  6437. {
  6438. Abort();
  6439. }
  6440. }
  6441. }
  6442. //---------------------------------------------------------------------------
  6443. void __fastcall TTerminal::SynchronizeLocalTimestamp(const UnicodeString /*FileName*/,
  6444. const TRemoteFile * File, void * /*Param*/)
  6445. {
  6446. const TSynchronizeChecklist::TItem * ChecklistItem =
  6447. reinterpret_cast<const TSynchronizeChecklist::TItem *>(File);
  6448. UnicodeString LocalFile =
  6449. IncludeTrailingBackslash(ChecklistItem->Local.Directory) +
  6450. ChecklistItem->Local.FileName;
  6451. FILE_OPERATION_LOOP_BEGIN
  6452. {
  6453. HANDLE Handle;
  6454. OpenLocalFile(LocalFile, GENERIC_WRITE, NULL, &Handle,
  6455. NULL, NULL, NULL, NULL);
  6456. FILETIME WrTime = DateTimeToFileTime(ChecklistItem->Remote.Modification,
  6457. SessionData->DSTMode);
  6458. bool Result = SetFileTime(Handle, NULL, NULL, &WrTime);
  6459. int Error = GetLastError();
  6460. CloseHandle(Handle);
  6461. if (!Result)
  6462. {
  6463. RaiseLastOSError(Error);
  6464. }
  6465. }
  6466. FILE_OPERATION_LOOP_END(FMTLOAD(CANT_SET_ATTRS, (LocalFile)));
  6467. }
  6468. //---------------------------------------------------------------------------
  6469. void __fastcall TTerminal::SynchronizeRemoteTimestamp(const UnicodeString /*FileName*/,
  6470. const TRemoteFile * File, void * /*Param*/)
  6471. {
  6472. const TSynchronizeChecklist::TItem * ChecklistItem =
  6473. reinterpret_cast<const TSynchronizeChecklist::TItem *>(File);
  6474. TRemoteProperties Properties;
  6475. Properties.Valid << vpModification;
  6476. Properties.Modification = ConvertTimestampToUnix(ChecklistItem->FLocalLastWriteTime,
  6477. SessionData->DSTMode);
  6478. ChangeFileProperties(
  6479. UnixIncludeTrailingBackslash(ChecklistItem->Remote.Directory) + ChecklistItem->Remote.FileName,
  6480. NULL, &Properties);
  6481. }
  6482. //---------------------------------------------------------------------------
  6483. void __fastcall TTerminal::FileFind(UnicodeString FileName,
  6484. const TRemoteFile * File, /*TFilesFindParams*/ void * Param)
  6485. {
  6486. // see DoFilesFind
  6487. FOnFindingFile = NULL;
  6488. DebugAssert(Param);
  6489. DebugAssert(File);
  6490. TFilesFindParams * AParams = static_cast<TFilesFindParams*>(Param);
  6491. if (!AParams->Cancel)
  6492. {
  6493. if (FileName.IsEmpty())
  6494. {
  6495. FileName = File->FileName;
  6496. }
  6497. TFileMasks::TParams MaskParams;
  6498. MaskParams.Size = File->Resolve()->Size;
  6499. MaskParams.Modification = File->Modification;
  6500. UnicodeString FullFileName = UnixExcludeTrailingBackslash(File->FullFileName);
  6501. bool ImplicitMatch;
  6502. // Do not use recursive include match
  6503. if (AParams->FileMask.Matches(FullFileName, false,
  6504. File->IsDirectory, &MaskParams, false, ImplicitMatch))
  6505. {
  6506. if (!ImplicitMatch)
  6507. {
  6508. AParams->OnFileFound(this, FileName, File, AParams->Cancel);
  6509. }
  6510. if (File->IsDirectory)
  6511. {
  6512. UnicodeString RealDirectory;
  6513. if (!File->IsSymLink || File->LinkTo.IsEmpty())
  6514. {
  6515. RealDirectory = UnixIncludeTrailingBackslash(AParams->RealDirectory) + File->FileName;
  6516. }
  6517. else
  6518. {
  6519. RealDirectory = ::AbsolutePath(AParams->RealDirectory, File->LinkTo);
  6520. }
  6521. if (!AParams->LoopDetector.IsUnvisitedDirectory(RealDirectory))
  6522. {
  6523. LogEvent(FORMAT(L"Already searched \"%s\" directory (real path \"%s\"), link loop detected", (FullFileName, RealDirectory)));
  6524. }
  6525. else
  6526. {
  6527. DoFilesFind(FullFileName, *AParams, RealDirectory);
  6528. }
  6529. }
  6530. }
  6531. }
  6532. }
  6533. //---------------------------------------------------------------------------
  6534. void __fastcall TTerminal::DoFilesFind(UnicodeString Directory, TFilesFindParams & Params, UnicodeString RealDirectory)
  6535. {
  6536. LogEvent(FORMAT(L"Searching directory \"%s\" (real path \"%s\")", (Directory, RealDirectory)));
  6537. Params.OnFindingFile(this, Directory, Params.Cancel);
  6538. if (!Params.Cancel)
  6539. {
  6540. DebugAssert(FOnFindingFile == NULL);
  6541. // ideally we should set the handler only around actually reading
  6542. // of the directory listing, so we at least reset the handler in
  6543. // FileFind
  6544. FOnFindingFile = Params.OnFindingFile;
  6545. UnicodeString PrevRealDirectory = Params.RealDirectory;
  6546. try
  6547. {
  6548. Params.RealDirectory = RealDirectory;
  6549. ProcessDirectory(Directory, FileFind, &Params, false, true);
  6550. }
  6551. __finally
  6552. {
  6553. Params.RealDirectory = PrevRealDirectory;
  6554. FOnFindingFile = NULL;
  6555. }
  6556. }
  6557. }
  6558. //---------------------------------------------------------------------------
  6559. void __fastcall TTerminal::FilesFind(UnicodeString Directory, const TFileMasks & FileMask,
  6560. TFileFoundEvent OnFileFound, TFindingFileEvent OnFindingFile)
  6561. {
  6562. TFilesFindParams Params;
  6563. Params.FileMask = FileMask;
  6564. Params.FileMask.NoImplicitMatchWithDirExcludeMask = true;
  6565. Params.FileMask.AllDirsAreImplicitlyIncluded = true;
  6566. Params.OnFileFound = OnFileFound;
  6567. Params.OnFindingFile = OnFindingFile;
  6568. Params.Cancel = false;
  6569. Params.LoopDetector.RecordVisitedDirectory(Directory);
  6570. DoFilesFind(Directory, Params, Directory);
  6571. }
  6572. //---------------------------------------------------------------------------
  6573. void __fastcall TTerminal::SpaceAvailable(const UnicodeString Path,
  6574. TSpaceAvailable & ASpaceAvailable)
  6575. {
  6576. DebugAssert(IsCapable[fcCheckingSpaceAvailable]);
  6577. try
  6578. {
  6579. FFileSystem->SpaceAvailable(Path, ASpaceAvailable);
  6580. }
  6581. catch (Exception &E)
  6582. {
  6583. CommandError(&E, FMTLOAD(SPACE_AVAILABLE_ERROR, (Path)));
  6584. }
  6585. }
  6586. //---------------------------------------------------------------------------
  6587. void __fastcall TTerminal::LockFile(const UnicodeString FileName,
  6588. const TRemoteFile * File, void * /*Param*/)
  6589. {
  6590. StartOperationWithFile(FileName, foLock);
  6591. LogEvent(FORMAT(L"Locking file \"%s\".", (FileName)));
  6592. FileModified(File, FileName, true);
  6593. DoLockFile(FileName, File);
  6594. ReactOnCommand(fsLock);
  6595. }
  6596. //---------------------------------------------------------------------------
  6597. void __fastcall TTerminal::DoLockFile(const UnicodeString & FileName, const TRemoteFile * File)
  6598. {
  6599. TRetryOperationLoop RetryLoop(this);
  6600. do
  6601. {
  6602. try
  6603. {
  6604. FFileSystem->LockFile(FileName, File);
  6605. }
  6606. catch(Exception & E)
  6607. {
  6608. RetryLoop.Error(E, FMTLOAD(LOCK_FILE_ERROR, (FileName)));
  6609. }
  6610. }
  6611. while (RetryLoop.Retry());
  6612. }
  6613. //---------------------------------------------------------------------------
  6614. void __fastcall TTerminal::UnlockFile(const UnicodeString FileName,
  6615. const TRemoteFile * File, void * /*Param*/)
  6616. {
  6617. StartOperationWithFile(FileName, foUnlock);
  6618. LogEvent(FORMAT(L"Unlocking file \"%s\".", (FileName)));
  6619. FileModified(File, FileName, true);
  6620. DoUnlockFile(FileName, File);
  6621. ReactOnCommand(fsLock);
  6622. }
  6623. //---------------------------------------------------------------------------
  6624. void __fastcall TTerminal::DoUnlockFile(const UnicodeString & FileName, const TRemoteFile * File)
  6625. {
  6626. TRetryOperationLoop RetryLoop(this);
  6627. do
  6628. {
  6629. try
  6630. {
  6631. FFileSystem->UnlockFile(FileName, File);
  6632. }
  6633. catch(Exception & E)
  6634. {
  6635. RetryLoop.Error(E, FMTLOAD(UNLOCK_FILE_ERROR, (FileName)));
  6636. }
  6637. }
  6638. while (RetryLoop.Retry());
  6639. }
  6640. //---------------------------------------------------------------------------
  6641. void __fastcall TTerminal::LockFiles(TStrings * FileList)
  6642. {
  6643. BeginTransaction();
  6644. try
  6645. {
  6646. ProcessFiles(FileList, foLock, LockFile, NULL);
  6647. }
  6648. __finally
  6649. {
  6650. EndTransaction();
  6651. }
  6652. }
  6653. //---------------------------------------------------------------------------
  6654. void __fastcall TTerminal::UnlockFiles(TStrings * FileList)
  6655. {
  6656. BeginTransaction();
  6657. try
  6658. {
  6659. ProcessFiles(FileList, foUnlock, UnlockFile, NULL);
  6660. }
  6661. __finally
  6662. {
  6663. EndTransaction();
  6664. }
  6665. }
  6666. //---------------------------------------------------------------------------
  6667. const TSessionInfo & __fastcall TTerminal::GetSessionInfo()
  6668. {
  6669. return FFileSystem->GetSessionInfo();
  6670. }
  6671. //---------------------------------------------------------------------------
  6672. const TFileSystemInfo & __fastcall TTerminal::GetFileSystemInfo(bool Retrieve)
  6673. {
  6674. return FFileSystem->GetFileSystemInfo(Retrieve);
  6675. }
  6676. //---------------------------------------------------------------------
  6677. TStrings * TTerminal::GetShellChecksumAlgDefs()
  6678. {
  6679. if (FShellChecksumAlgDefs.get() == NULL)
  6680. {
  6681. UnicodeString ChecksumCommandsDef = Configuration->ChecksumCommands;
  6682. if (ChecksumCommandsDef.IsEmpty())
  6683. {
  6684. UnicodeString Delimiter(L",");
  6685. AddToList(ChecksumCommandsDef, Sha512ChecksumAlg + L"=sha512sum", Delimiter);
  6686. AddToList(ChecksumCommandsDef, Sha384ChecksumAlg + L"=sha384sum", Delimiter);
  6687. AddToList(ChecksumCommandsDef, Sha256ChecksumAlg + L"=sha256sum", Delimiter);
  6688. AddToList(ChecksumCommandsDef, Sha224ChecksumAlg + L"=sha224sum", Delimiter);
  6689. AddToList(ChecksumCommandsDef, Sha1ChecksumAlg + L"=sha1sum", Delimiter);
  6690. AddToList(ChecksumCommandsDef, Md5ChecksumAlg + L"=md5sums", Delimiter);
  6691. }
  6692. FShellChecksumAlgDefs.reset(CommaTextToStringList(ChecksumCommandsDef));
  6693. }
  6694. return FShellChecksumAlgDefs.get();
  6695. }
  6696. //---------------------------------------------------------------------
  6697. void TTerminal::GetShellChecksumAlgs(TStrings * Algs)
  6698. {
  6699. TStrings * AlgDefs = GetShellChecksumAlgDefs();
  6700. for (int Index = 0; Index < AlgDefs->Count; Index++)
  6701. {
  6702. Algs->Add(AlgDefs->Names[Index]);
  6703. }
  6704. }
  6705. //---------------------------------------------------------------------
  6706. void __fastcall TTerminal::GetSupportedChecksumAlgs(TStrings * Algs)
  6707. {
  6708. if (!IsCapable[fcCalculatingChecksum] && IsCapable[fcSecondaryShell])
  6709. {
  6710. // Both return the same anyway
  6711. if (CommandSessionOpened)
  6712. {
  6713. FCommandSession->GetSupportedChecksumAlgs(Algs);
  6714. }
  6715. else
  6716. {
  6717. GetShellChecksumAlgs(Algs);
  6718. }
  6719. }
  6720. else
  6721. {
  6722. FFileSystem->GetSupportedChecksumAlgs(Algs);
  6723. }
  6724. }
  6725. //---------------------------------------------------------------------
  6726. UnicodeString __fastcall TTerminal::GetPassword()
  6727. {
  6728. UnicodeString Result;
  6729. // FRememberedPassword is empty also when stored password was used
  6730. if (FRememberedPassword.IsEmpty())
  6731. {
  6732. Result = SessionData->Password;
  6733. }
  6734. else if (FRememberedPasswordKind != pkPassphrase)
  6735. {
  6736. Result = GetRememberedPassword();
  6737. }
  6738. return Result;
  6739. }
  6740. //---------------------------------------------------------------------
  6741. UnicodeString __fastcall TTerminal::GetRememberedPassword()
  6742. {
  6743. return DecryptPassword(FRememberedPassword);
  6744. }
  6745. //---------------------------------------------------------------------
  6746. UnicodeString __fastcall TTerminal::GetRememberedTunnelPassword()
  6747. {
  6748. return DecryptPassword(FRememberedTunnelPassword);
  6749. }
  6750. //---------------------------------------------------------------------
  6751. bool __fastcall TTerminal::GetStoredCredentialsTried()
  6752. {
  6753. bool Result;
  6754. if (FFileSystem != NULL)
  6755. {
  6756. Result = FFileSystem->GetStoredCredentialsTried();
  6757. }
  6758. else if (FSecureShell != NULL)
  6759. {
  6760. Result = FSecureShell->GetStoredCredentialsTried();
  6761. }
  6762. else
  6763. {
  6764. DebugAssert(FTunnelOpening);
  6765. Result = false;
  6766. }
  6767. return Result;
  6768. }
  6769. //---------------------------------------------------------------------------
  6770. int __fastcall TTerminal::CopyToParallel(TParallelOperation * ParallelOperation, TFileOperationProgressType * OperationProgress)
  6771. {
  6772. UnicodeString FileName;
  6773. TObject * Object;
  6774. UnicodeString TargetDir;
  6775. bool Dir;
  6776. bool Recursed;
  6777. TCopyParamType * CustomCopyParam = NULL;
  6778. int Result = ParallelOperation->GetNext(this, FileName, Object, TargetDir, Dir, Recursed, CustomCopyParam);
  6779. std::unique_ptr<TCopyParamType> CustomCopyParamOwner(CustomCopyParam);
  6780. if (Result > 0)
  6781. {
  6782. std::unique_ptr<TStrings> FilesToCopy(new TStringList());
  6783. FilesToCopy->AddObject(FileName, Object);
  6784. // OnceDoneOperation is not supported
  6785. TOnceDoneOperation OnceDoneOperation = odoIdle;
  6786. int Params = ParallelOperation->Params;
  6787. // If we failed to recurse the directory when enumerating, recurse now (typically only to show the recursion error)
  6788. if (Dir && Recursed)
  6789. {
  6790. Params = Params | cpNoRecurse;
  6791. }
  6792. int Prev = OperationProgress->FilesFinishedSuccessfully;
  6793. DebugAssert((FOperationProgress == OperationProgress) || (FOperationProgress == NULL));
  6794. TFileOperationProgressType * PrevOperationProgress = FOperationProgress;
  6795. const TCopyParamType * CopyParam = (CustomCopyParam != NULL) ? CustomCopyParam : ParallelOperation->CopyParam;
  6796. try
  6797. {
  6798. FOperationProgress = OperationProgress;
  6799. if (ParallelOperation->Side == osLocal)
  6800. {
  6801. FFileSystem->CopyToRemote(
  6802. FilesToCopy.get(), TargetDir, CopyParam, Params, OperationProgress, OnceDoneOperation);
  6803. }
  6804. else if (DebugAlwaysTrue(ParallelOperation->Side == osRemote))
  6805. {
  6806. FFileSystem->CopyToLocal(
  6807. FilesToCopy.get(), TargetDir, CopyParam, Params, OperationProgress, OnceDoneOperation);
  6808. }
  6809. }
  6810. __finally
  6811. {
  6812. bool Success = (Prev < OperationProgress->FilesFinishedSuccessfully);
  6813. ParallelOperation->Done(FileName, Dir, Success, TargetDir, CopyParam, this);
  6814. // Not to fail an assertion in OperationStop when called from CopyToRemote or CopyToLocal,
  6815. // when FOperationProgress is already OperationProgress.
  6816. FOperationProgress = PrevOperationProgress;
  6817. }
  6818. }
  6819. return Result;
  6820. }
  6821. //---------------------------------------------------------------------------
  6822. bool __fastcall TTerminal::CanParallel(
  6823. const TCopyParamType * CopyParam, int Params, TParallelOperation * ParallelOperation)
  6824. {
  6825. return
  6826. (ParallelOperation != NULL) &&
  6827. FFileSystem->IsCapable(fcParallelTransfers) &&
  6828. // parallel transfer is not implemented for operations needed to be done on a folder
  6829. // after all its files are processed
  6830. FLAGCLEAR(Params, cpDelete) &&
  6831. (!CopyParam->PreserveTime || !CopyParam->PreserveTimeDirs);
  6832. }
  6833. //---------------------------------------------------------------------------
  6834. void __fastcall TTerminal::CopyParallel(TParallelOperation * ParallelOperation, TFileOperationProgressType * OperationProgress)
  6835. {
  6836. try
  6837. {
  6838. bool Continue = true;
  6839. do
  6840. {
  6841. int GotNext = CopyToParallel(ParallelOperation, OperationProgress);
  6842. if (GotNext < 0)
  6843. {
  6844. Continue = false;
  6845. }
  6846. else if (GotNext == 0)
  6847. {
  6848. Sleep(100);
  6849. }
  6850. }
  6851. while (Continue && !OperationProgress->Cancel);
  6852. }
  6853. __finally
  6854. {
  6855. OperationProgress->SetDone();
  6856. ParallelOperation->WaitFor();
  6857. }
  6858. }
  6859. //---------------------------------------------------------------------------
  6860. void __fastcall TTerminal::LogParallelTransfer(TParallelOperation * ParallelOperation)
  6861. {
  6862. LogEvent(
  6863. FORMAT("Adding a parallel transfer to the transfer started on the connection \"%s\"",
  6864. (ParallelOperation->MainName)));
  6865. }
  6866. //---------------------------------------------------------------------------
  6867. void __fastcall TTerminal::LogTotalTransferDetails(
  6868. const UnicodeString TargetDir, const TCopyParamType * CopyParam,
  6869. TFileOperationProgressType * OperationProgress, bool Parallel, TStrings * Files)
  6870. {
  6871. if (Log->Logging)
  6872. {
  6873. UnicodeString TargetSide = ((OperationProgress->Side == osLocal) ? L"remote" : L"local");
  6874. UnicodeString S =
  6875. FORMAT(
  6876. L"Copying %d files/directories to %s directory \"%s\"",
  6877. (OperationProgress->Count, TargetSide, TargetDir));
  6878. if (Parallel && DebugAlwaysTrue(Files != NULL))
  6879. {
  6880. int Count = 0;
  6881. for (int Index = 0; Index < Files->Count; Index++)
  6882. {
  6883. TCollectedFileList * FileList = dynamic_cast<TCollectedFileList *>(Files->Objects[Index]);
  6884. Count += FileList->Count();
  6885. }
  6886. S += FORMAT(L" - in parallel, with %d total files", (Count));
  6887. }
  6888. if (OperationProgress->TotalSizeSet)
  6889. {
  6890. S += FORMAT(L" - total size: %s", (FormatSize(OperationProgress->TotalSize)));
  6891. }
  6892. LogEvent(S);
  6893. LogEvent(0, CopyParam->LogStr);
  6894. }
  6895. }
  6896. //---------------------------------------------------------------------------
  6897. void __fastcall TTerminal::LogTotalTransferDone(TFileOperationProgressType * OperationProgress)
  6898. {
  6899. LogEvent(L"Copying finished: " + OperationProgress->GetLogStr(true));
  6900. }
  6901. //---------------------------------------------------------------------------
  6902. bool __fastcall TTerminal::CopyToRemote(
  6903. TStrings * FilesToCopy, const UnicodeString & TargetDir, const TCopyParamType * CopyParam, int Params,
  6904. TParallelOperation * ParallelOperation)
  6905. {
  6906. DebugAssert(FFileSystem);
  6907. DebugAssert(FilesToCopy);
  6908. bool Result = false;
  6909. TOnceDoneOperation OnceDoneOperation = odoIdle;
  6910. if ((CopyParam->OnTransferIn != NULL) && !FFileSystem->IsCapable(fcTransferIn))
  6911. {
  6912. NotSupported();
  6913. }
  6914. try
  6915. {
  6916. __int64 Size;
  6917. std::unique_ptr<TStringList> Files;
  6918. bool ACanParallel =
  6919. CanParallel(CopyParam, Params, ParallelOperation) &&
  6920. !CopyParam->ClearArchive;
  6921. if (ACanParallel)
  6922. {
  6923. Files.reset(new TStringList());
  6924. Files->OwnsObjects = true;
  6925. }
  6926. bool CalculatedSize;
  6927. if ((CopyParam->Size >= 0) &&
  6928. DebugAlwaysTrue(!ACanParallel)) // Size is set for sync only and we never use parallel transfer for sync
  6929. {
  6930. Size = CopyParam->Size;
  6931. CalculatedSize = true;
  6932. }
  6933. else
  6934. {
  6935. bool CalculateSize = ACanParallel || CopyParam->CalculateSize;
  6936. CalculatedSize = CalculateLocalFilesSize(FilesToCopy, Size, CopyParam, CalculateSize, Files.get(), NULL);
  6937. }
  6938. FLastProgressLogged = GetTickCount();
  6939. TFileOperationProgressType OperationProgress(&DoProgress, &DoFinished);
  6940. OperationStart(
  6941. OperationProgress, (Params & cpDelete ? foMove : foCopy), osLocal,
  6942. FilesToCopy->Count, Params & cpTemporary, TargetDir, CopyParam->CPSLimit, CopyParam->OnceDoneOperation);
  6943. bool CollectingUsage = false;
  6944. try
  6945. {
  6946. if (CalculatedSize)
  6947. {
  6948. if (Configuration->Usage->Collect)
  6949. {
  6950. int CounterSize = TUsage::CalculateCounterSize(Size);
  6951. Configuration->Usage->Inc(L"Uploads");
  6952. Configuration->Usage->Inc(L"UploadedBytes", CounterSize);
  6953. Configuration->Usage->SetMax(L"MaxUploadSize", CounterSize);
  6954. CollectingUsage = true;
  6955. }
  6956. OperationProgress.SetTotalSize(Size);
  6957. }
  6958. BeginTransaction();
  6959. try
  6960. {
  6961. bool Parallel = ACanParallel && CalculatedSize;
  6962. LogTotalTransferDetails(TargetDir, CopyParam, &OperationProgress, Parallel, Files.get());
  6963. if (Parallel)
  6964. {
  6965. // OnceDoneOperation is not supported
  6966. ParallelOperation->Init(Files.release(), TargetDir, CopyParam, Params, &OperationProgress, Log->Name, -1);
  6967. CopyParallel(ParallelOperation, &OperationProgress);
  6968. }
  6969. else
  6970. {
  6971. FFileSystem->CopyToRemote(
  6972. FilesToCopy, TargetDir, CopyParam, Params, &OperationProgress, OnceDoneOperation);
  6973. }
  6974. LogTotalTransferDone(&OperationProgress);
  6975. }
  6976. __finally
  6977. {
  6978. if (Active)
  6979. {
  6980. ReactOnCommand(fsCopyToRemote);
  6981. }
  6982. EndTransaction();
  6983. }
  6984. if (OperationProgress.Cancel == csContinue)
  6985. {
  6986. Result = true;
  6987. }
  6988. }
  6989. __finally
  6990. {
  6991. if (CollectingUsage)
  6992. {
  6993. int CounterTime = TimeToSeconds(OperationProgress.TimeElapsed());
  6994. Configuration->Usage->Inc(L"UploadTime", CounterTime);
  6995. Configuration->Usage->SetMax(L"MaxUploadTime", CounterTime);
  6996. }
  6997. OperationStop(OperationProgress);
  6998. }
  6999. }
  7000. catch (Exception &E)
  7001. {
  7002. CommandError(&E, MainInstructions(LoadStr(TOREMOTE_COPY_ERROR)));
  7003. OnceDoneOperation = odoIdle;
  7004. }
  7005. if (OnceDoneOperation != odoIdle)
  7006. {
  7007. CloseOnCompletion(OnceDoneOperation);
  7008. }
  7009. return Result;
  7010. }
  7011. //---------------------------------------------------------------------------
  7012. void __fastcall TTerminal::DoCopyToRemote(
  7013. TStrings * FilesToCopy, const UnicodeString & ATargetDir, const TCopyParamType * CopyParam, int Params,
  7014. TFileOperationProgressType * OperationProgress, unsigned int Flags, TOnceDoneOperation & OnceDoneOperation)
  7015. {
  7016. DebugAssert((FilesToCopy != NULL) && (OperationProgress != NULL));
  7017. FFileSystem->TransferOnDirectory(ATargetDir, CopyParam, Params);
  7018. // Must be local resolving, as this is outside of robust loop
  7019. UnicodeString TargetDir = AbsolutePath(ATargetDir, true);
  7020. UnicodeString FullTargetDir = UnixIncludeTrailingBackslash(TargetDir);
  7021. int Index = 0;
  7022. while ((Index < FilesToCopy->Count) && !OperationProgress->Cancel)
  7023. {
  7024. bool Success = false;
  7025. UnicodeString FileName = FilesToCopy->Strings[Index];
  7026. TSearchRecSmart * SearchRec = NULL;
  7027. if (FilesToCopy->Objects[Index] != NULL)
  7028. {
  7029. TLocalFile * LocalFile = dynamic_cast<TLocalFile *>(FilesToCopy->Objects[Index]);
  7030. SearchRec = &LocalFile->SearchRec;
  7031. }
  7032. try
  7033. {
  7034. try
  7035. {
  7036. if (SessionData->CacheDirectories)
  7037. {
  7038. DirectoryModified(TargetDir, false);
  7039. if (DirectoryExists(ApiPath(FileName)))
  7040. {
  7041. UnicodeString FileNameOnly = ExtractFileName(FileName);
  7042. DirectoryModified(FullTargetDir + FileNameOnly, true);
  7043. }
  7044. }
  7045. SourceRobust(FileName, SearchRec, FullTargetDir, CopyParam, Params, OperationProgress, Flags | tfFirstLevel);
  7046. Success = true;
  7047. }
  7048. catch (ESkipFile & E)
  7049. {
  7050. TSuspendFileOperationProgress Suspend(OperationProgress);
  7051. if (!HandleException(&E))
  7052. {
  7053. throw;
  7054. }
  7055. }
  7056. }
  7057. __finally
  7058. {
  7059. OperationFinish(OperationProgress, FilesToCopy->Objects[Index], FileName, Success, OnceDoneOperation);
  7060. }
  7061. Index++;
  7062. }
  7063. }
  7064. //---------------------------------------------------------------------------
  7065. void __fastcall TTerminal::SourceRobust(
  7066. const UnicodeString & FileName, const TSearchRecSmart * SearchRec,
  7067. const UnicodeString & TargetDir, const TCopyParamType * CopyParam, int Params,
  7068. TFileOperationProgressType * OperationProgress, unsigned int Flags)
  7069. {
  7070. TUploadSessionAction Action(ActionLog);
  7071. bool * AFileTransferAny = FLAGSET(Flags, tfUseFileTransferAny) ? &FFileTransferAny : NULL;
  7072. bool CanRetry = (CopyParam->OnTransferIn == NULL);
  7073. TRobustOperationLoop RobustLoop(this, OperationProgress, AFileTransferAny, CanRetry);
  7074. do
  7075. {
  7076. bool ChildError = false;
  7077. try
  7078. {
  7079. Source(FileName, SearchRec, TargetDir, CopyParam, Params, OperationProgress, Flags, Action, ChildError);
  7080. }
  7081. catch (Exception & E)
  7082. {
  7083. if (!RobustLoop.TryReopen(E))
  7084. {
  7085. if (!ChildError)
  7086. {
  7087. RollbackAction(Action, OperationProgress, &E);
  7088. }
  7089. throw;
  7090. }
  7091. }
  7092. if (RobustLoop.ShouldRetry())
  7093. {
  7094. OperationProgress->RollbackTransfer();
  7095. Action.Restart();
  7096. // prevent overwrite and resume confirmations (should not be set for directories!)
  7097. Params |= cpNoConfirmation;
  7098. // enable resume even if we are uploading into new directory
  7099. Flags &= ~tfNewDirectory;
  7100. Flags |= tfAutoResume;
  7101. }
  7102. }
  7103. while (RobustLoop.Retry());
  7104. }
  7105. //---------------------------------------------------------------------------
  7106. bool __fastcall TTerminal::CreateTargetDirectory(
  7107. const UnicodeString & DirectoryPath, int Attrs, const TCopyParamType * CopyParam)
  7108. {
  7109. std::unique_ptr<TRemoteFile> File(TryReadFile(DirectoryPath));
  7110. bool DoCreate =
  7111. (File.get() == NULL) ||
  7112. !File->IsDirectory; // just try to create and make it fail
  7113. File.reset(NULL);
  7114. if (DoCreate)
  7115. {
  7116. TRemoteProperties Properties;
  7117. // Do not even try with FTP, as while theoretically it supports setting permissions of created folders and it will try,
  7118. // it most likely fail as most FTP servers do not support SITE CHMOD.
  7119. if (CopyParam->PreserveRights && IsCapable[fcModeChangingUpload])
  7120. {
  7121. Properties.Valid = Properties.Valid << vpRights;
  7122. Properties.Rights = CopyParam->RemoteFileRights(Attrs);
  7123. }
  7124. Properties.Valid = Properties.Valid << vpEncrypt;
  7125. Properties.Encrypt = CopyParam->EncryptNewFiles;
  7126. CreateDirectory(DirectoryPath, &Properties);
  7127. }
  7128. return DoCreate;
  7129. }
  7130. //---------------------------------------------------------------------------
  7131. void __fastcall TTerminal::DirectorySource(
  7132. const UnicodeString & DirectoryName, const UnicodeString & TargetDir, const UnicodeString & DestDirectoryName,
  7133. int Attrs, const TCopyParamType * CopyParam, int Params,
  7134. TFileOperationProgressType * OperationProgress, unsigned int Flags)
  7135. {
  7136. FFileSystem->TransferOnDirectory(TargetDir, CopyParam, Params);
  7137. UnicodeString DestFullName = TargetDir + DestDirectoryName;
  7138. OperationProgress->SetFile(DirectoryName);
  7139. bool PostCreateDir = FLAGCLEAR(Flags, tfPreCreateDir);
  7140. // WebDAV, SFTP and S3
  7141. if (!PostCreateDir)
  7142. {
  7143. // This is originally a code for WebDAV, SFTP used a slightly different logic,
  7144. // but functionally it should be very similar.
  7145. if (CreateTargetDirectory(DestFullName, Attrs, CopyParam))
  7146. {
  7147. Flags |= tfNewDirectory;
  7148. }
  7149. }
  7150. bool DoRecurse = FLAGCLEAR(Params, cpNoRecurse);
  7151. if (DoRecurse)
  7152. {
  7153. TSearchRecOwned SearchRec;
  7154. bool FindOK = LocalFindFirstLoop(DirectoryName + L"*.*", SearchRec);
  7155. while (FindOK && !OperationProgress->Cancel)
  7156. {
  7157. UnicodeString FileName = SearchRec.GetFilePath();
  7158. try
  7159. {
  7160. if (SearchRec.IsRealFile())
  7161. {
  7162. // Not sure if we need the trailing slash here, but we cannot use it in CreateTargetDirectory.
  7163. // At least FTP cannot handle it, when setting the new directory permissions.
  7164. UnicodeString ATargetDir = UnixIncludeTrailingBackslash(DestFullName);
  7165. SourceRobust(FileName, &SearchRec, ATargetDir, CopyParam, Params, OperationProgress, (Flags & ~(tfFirstLevel | tfAutoResume)));
  7166. // FTP: if any file got uploaded (i.e. there were any file in the directory and at least one was not skipped),
  7167. // do not try to create the directory, as it should be already created by FZAPI during upload
  7168. PostCreateDir = false;
  7169. }
  7170. }
  7171. catch (ESkipFile &E)
  7172. {
  7173. // If ESkipFile occurs, just log it and continue with next file
  7174. TSuspendFileOperationProgress Suspend(OperationProgress);
  7175. // here a message to user was displayed, which was not appropriate
  7176. // when user refused to overwrite the file in subdirectory.
  7177. // hopefully it won't be missing in other situations.
  7178. if (!HandleException(&E))
  7179. {
  7180. throw;
  7181. }
  7182. }
  7183. FindOK = LocalFindNextLoop(SearchRec);
  7184. }
  7185. SearchRec.Close();
  7186. }
  7187. // FTP
  7188. if (PostCreateDir)
  7189. {
  7190. CreateTargetDirectory(DestFullName, Attrs, CopyParam);
  7191. }
  7192. // Parallel transfers (cpNoRecurse) won't be allowed if any of these are set anyway (see CanParallel).
  7193. // Exception is ClearArchive, which is does not prevent parallel transfer, but is silently ignored for directories.
  7194. if (DoRecurse && !OperationProgress->Cancel)
  7195. {
  7196. // TODO : Delete also read-only directories.
  7197. // TODO : Show error message on failure.
  7198. if (IsCapable[fcPreservingTimestampDirs] && CopyParam->PreserveTime && CopyParam->PreserveTimeDirs)
  7199. {
  7200. TRemoteProperties Properties;
  7201. Properties.Valid << vpModification;
  7202. OpenLocalFile(
  7203. ExcludeTrailingBackslash(DirectoryName), GENERIC_READ, NULL, NULL, NULL,
  7204. &Properties.Modification, &Properties.LastAccess, NULL);
  7205. ChangeFileProperties(DestFullName, NULL, &Properties);
  7206. }
  7207. if (FLAGSET(Params, cpDelete))
  7208. {
  7209. DebugAssert(FLAGCLEAR(Params, cpNoRecurse));
  7210. RemoveDir(ApiPath(DirectoryName));
  7211. }
  7212. else if (CopyParam->ClearArchive && FLAGSET(Attrs, faArchive))
  7213. {
  7214. FILE_OPERATION_LOOP_BEGIN
  7215. {
  7216. THROWOSIFFALSE(FileSetAttr(ApiPath(DirectoryName), Attrs & ~faArchive) == 0);
  7217. }
  7218. FILE_OPERATION_LOOP_END(FMTLOAD(CANT_SET_ATTRS, (DirectoryName)));
  7219. }
  7220. }
  7221. }
  7222. //---------------------------------------------------------------------------
  7223. bool TTerminal::UseAsciiTransfer(
  7224. const UnicodeString & BaseFileName, TOperationSide Side, const TCopyParamType * CopyParam,
  7225. const TFileMasks::TParams & MaskParams)
  7226. {
  7227. return
  7228. IsCapable[fcTextMode] &&
  7229. CopyParam->UseAsciiTransfer(BaseFileName, Side, MaskParams) &&
  7230. // Used either before PartSize is set (to check that file is to be transferred in binary mode, hence allows parallel file transfer),
  7231. // or later during parallel transfer (which never happens for ascii mode).
  7232. DebugAlwaysTrue(CopyParam->PartSize < 0);
  7233. }
  7234. //---------------------------------------------------------------------------
  7235. void __fastcall TTerminal::SelectTransferMode(
  7236. const UnicodeString & BaseFileName, TOperationSide Side, const TCopyParamType * CopyParam,
  7237. const TFileMasks::TParams & MaskParams)
  7238. {
  7239. bool AsciiTransfer = UseAsciiTransfer(BaseFileName, Side, CopyParam, MaskParams);
  7240. OperationProgress->SetAsciiTransfer(AsciiTransfer);
  7241. UnicodeString ModeName = (OperationProgress->AsciiTransfer ? L"Ascii" : L"Binary");
  7242. LogEvent(0, FORMAT(L"%s transfer mode selected.", (ModeName)));
  7243. }
  7244. //---------------------------------------------------------------------------
  7245. void __fastcall TTerminal::SelectSourceTransferMode(const TLocalFileHandle & Handle, const TCopyParamType * CopyParam)
  7246. {
  7247. // Will we use ASCII or BINARY file transfer?
  7248. TFileMasks::TParams MaskParams;
  7249. MaskParams.Size = Handle.Size;
  7250. MaskParams.Modification = Handle.Modification;
  7251. UnicodeString BaseFileName = GetBaseFileName(Handle.FileName);
  7252. SelectTransferMode(BaseFileName, osLocal, CopyParam, MaskParams);
  7253. }
  7254. //---------------------------------------------------------------------------
  7255. void TTerminal::DoDeleteLocalFile(const UnicodeString & FileName)
  7256. {
  7257. FILE_OPERATION_LOOP_BEGIN
  7258. {
  7259. DeleteFileChecked(FileName);
  7260. }
  7261. FILE_OPERATION_LOOP_END(FMTLOAD(DELETE_LOCAL_FILE_ERROR, (FileName)));
  7262. }
  7263. //---------------------------------------------------------------------------
  7264. void TTerminal::DoRenameLocalFileForce(const UnicodeString & OldName, const UnicodeString & NewName)
  7265. {
  7266. if (::FileExists(ApiPath(NewName)))
  7267. {
  7268. DoDeleteLocalFile(NewName);
  7269. }
  7270. FILE_OPERATION_LOOP_BEGIN
  7271. {
  7272. THROWOSIFFALSE(Sysutils::RenameFile(ApiPath(OldName), ApiPath(NewName)));
  7273. }
  7274. FILE_OPERATION_LOOP_END(FMTLOAD(RENAME_FILE_ERROR, (OldName, NewName)));
  7275. }
  7276. //---------------------------------------------------------------------------
  7277. void __fastcall TTerminal::UpdateSource(const TLocalFileHandle & Handle, const TCopyParamType * CopyParam, int Params)
  7278. {
  7279. // TODO: Delete also read-only files.
  7280. if (FLAGSET(Params, cpDelete))
  7281. {
  7282. if (!Handle.Directory)
  7283. {
  7284. LogEvent(FORMAT(L"Deleting successfully uploaded source file \"%s\".", (Handle.FileName)));
  7285. DoDeleteLocalFile(Handle.FileName);
  7286. }
  7287. }
  7288. else if (CopyParam->ClearArchive && FLAGSET(Handle.Attrs, faArchive))
  7289. {
  7290. FILE_OPERATION_LOOP_BEGIN
  7291. {
  7292. THROWOSIFFALSE(FileSetAttr(ApiPath(Handle.FileName), (Handle.Attrs & ~faArchive)) == 0);
  7293. }
  7294. FILE_OPERATION_LOOP_END(FMTLOAD(CANT_SET_ATTRS, (Handle.FileName)));
  7295. }
  7296. }
  7297. //---------------------------------------------------------------------------
  7298. void __fastcall TTerminal::Source(
  7299. const UnicodeString & FileName, const TSearchRecSmart * SearchRec,
  7300. const UnicodeString & TargetDir, const TCopyParamType * CopyParam, int Params,
  7301. TFileOperationProgressType * OperationProgress, unsigned int Flags, TUploadSessionAction & Action, bool & ChildError)
  7302. {
  7303. UnicodeString ActionFileName = FileName;
  7304. if (CopyParam->OnTransferIn == NULL)
  7305. {
  7306. ActionFileName = ExpandUNCFileName(ActionFileName);
  7307. }
  7308. Action.FileName(ActionFileName);
  7309. OperationProgress->SetFile(FileName, false);
  7310. if (!AllowLocalFileTransfer(FileName, SearchRec, CopyParam, OperationProgress))
  7311. {
  7312. throw ESkipFile();
  7313. }
  7314. TLocalFileHandle Handle;
  7315. if (CopyParam->OnTransferIn == NULL)
  7316. {
  7317. OpenLocalFile(FileName, GENERIC_READ, Handle);
  7318. }
  7319. else
  7320. {
  7321. Handle.FileName = FileName;
  7322. }
  7323. OperationProgress->SetFileInProgress();
  7324. UnicodeString DestFileName =
  7325. ChangeFileName(CopyParam, ExtractFileName(FileName), osLocal, FLAGSET(Flags, tfFirstLevel));
  7326. if (Handle.Directory)
  7327. {
  7328. Action.Cancel();
  7329. DirectorySource(
  7330. IncludeTrailingBackslash(FileName), TargetDir, DestFileName, Handle.Attrs,
  7331. CopyParam, Params, OperationProgress, Flags);
  7332. }
  7333. else
  7334. {
  7335. if (CopyParam->OnTransferIn != NULL)
  7336. {
  7337. LogEvent(FORMAT(L"Streaming \"%s\" to remote directory started.", (FileName)));
  7338. }
  7339. else
  7340. {
  7341. LogEvent(FORMAT(L"Copying \"%s\" to remote directory started.", (FileName)));
  7342. OperationProgress->SetLocalSize(Handle.Size);
  7343. // Suppose same data size to transfer as to read
  7344. // (not true with ASCII transfer)
  7345. OperationProgress->SetTransferSize(OperationProgress->LocalSize);
  7346. }
  7347. if (IsCapable[fcTextMode])
  7348. {
  7349. SelectSourceTransferMode(Handle, CopyParam);
  7350. }
  7351. FFileSystem->Source(
  7352. Handle, TargetDir, DestFileName, CopyParam, Params, OperationProgress, Flags, Action, ChildError);
  7353. LogFileDone(OperationProgress, AbsolutePath(TargetDir + DestFileName, true), Action);
  7354. OperationProgress->Succeeded();
  7355. }
  7356. Handle.Release();
  7357. UpdateSource(Handle, CopyParam, Params);
  7358. }
  7359. //---------------------------------------------------------------------------
  7360. void TTerminal::CheckParallelFileTransfer(
  7361. const UnicodeString & TargetDir, TStringList * Files, const TCopyParamType * CopyParam, int Params,
  7362. UnicodeString & ParallelFileName, __int64 & ParallelFileSize, TFileOperationProgressType * OperationProgress)
  7363. {
  7364. if ((Configuration->ParallelTransferThreshold > 0) &&
  7365. FFileSystem->IsCapable(fcParallelFileTransfers))
  7366. {
  7367. TObject * ParallelObject = NULL;
  7368. if (TParallelOperation::GetOnlyFile(Files, ParallelFileName, ParallelObject))
  7369. {
  7370. TRemoteFile * File = static_cast<TRemoteFile *>(ParallelObject);
  7371. const TRemoteFile * UltimateFile = File->Resolve();
  7372. if ((UltimateFile == File) && // not tested with symlinks
  7373. (UltimateFile->Size >= static_cast<__int64>(Configuration->ParallelTransferThreshold) * 1024))
  7374. {
  7375. UnicodeString BaseFileName = GetBaseFileName(ParallelFileName);
  7376. TFileMasks::TParams MaskParams;
  7377. MaskParams.Size = UltimateFile->Size;
  7378. MaskParams.Modification = File->Modification;
  7379. if (!UseAsciiTransfer(BaseFileName, osRemote, CopyParam, MaskParams))
  7380. {
  7381. ParallelFileSize = UltimateFile->Size;
  7382. UnicodeString TargetFileName = CopyParam->ChangeFileName(UnixExtractFileName(ParallelFileName), osRemote, true);
  7383. UnicodeString DestFullName = CombinePaths(TargetDir, TargetFileName);
  7384. if (::FileExists(ApiPath(DestFullName)))
  7385. {
  7386. TSuspendFileOperationProgress Suspend(OperationProgress);
  7387. TOverwriteFileParams FileParams;
  7388. __int64 MTime;
  7389. OpenLocalFile(DestFullName, GENERIC_READ, NULL, NULL, NULL, &MTime, NULL, &FileParams.DestSize, false);
  7390. FileParams.SourceSize = ParallelFileSize;
  7391. FileParams.SourceTimestamp = UltimateFile->Modification;
  7392. FileParams.SourcePrecision = UltimateFile->ModificationFmt;
  7393. FileParams.DestTimestamp = UnixToDateTime(MTime, SessionData->DSTMode);
  7394. int Answers = qaYes | qaNo | qaCancel;
  7395. TQueryParams QueryParams(qpNeverAskAgainCheck);
  7396. unsigned int Answer =
  7397. ConfirmFileOverwrite(
  7398. ParallelFileName, TargetFileName, &FileParams, Answers, &QueryParams, osRemote,
  7399. CopyParam, Params, OperationProgress, EmptyStr);
  7400. switch (Answer)
  7401. {
  7402. case qaCancel:
  7403. case qaNo:
  7404. OperationProgress->SetCancelAtLeast(csCancel);
  7405. break;
  7406. }
  7407. }
  7408. }
  7409. }
  7410. }
  7411. }
  7412. }
  7413. //---------------------------------------------------------------------------
  7414. bool __fastcall TTerminal::CopyToLocal(
  7415. TStrings * FilesToCopy, const UnicodeString & TargetDir, const TCopyParamType * CopyParam, int Params,
  7416. TParallelOperation * ParallelOperation)
  7417. {
  7418. DebugAssert(FFileSystem);
  7419. // see scp.c: sink(), tolocal()
  7420. bool Result = false;
  7421. DebugAssert(FilesToCopy != NULL);
  7422. TOnceDoneOperation OnceDoneOperation = odoIdle;
  7423. if ((CopyParam->OnTransferOut != NULL) && !FFileSystem->IsCapable(fcTransferOut))
  7424. {
  7425. NotSupported();
  7426. }
  7427. FDestFileName = L"";
  7428. FMultipleDestinationFiles = false;
  7429. BeginTransaction();
  7430. try
  7431. {
  7432. __int64 TotalSize;
  7433. bool TotalSizeKnown = false;
  7434. FLastProgressLogged = GetTickCount();
  7435. TFileOperationProgressType OperationProgress(&DoProgress, &DoFinished);
  7436. std::unique_ptr<TStringList> Files;
  7437. bool ACanParallel =
  7438. CanParallel(CopyParam, Params, ParallelOperation) &&
  7439. DebugAlwaysTrue(CopyParam->OnTransferOut == NULL);
  7440. if (ACanParallel)
  7441. {
  7442. Files.reset(new TStringList());
  7443. Files->OwnsObjects = true;
  7444. }
  7445. if ((CopyParam->Size >= 0) &&
  7446. DebugAlwaysTrue(!ACanParallel)) // Size is set for sync only and we never use parallel transfer for sync
  7447. {
  7448. TotalSize = CopyParam->Size;
  7449. TotalSizeKnown = true;
  7450. }
  7451. else
  7452. {
  7453. ExceptionOnFail = true;
  7454. try
  7455. {
  7456. TCalculateSizeStats Stats;
  7457. Stats.FoundFiles = Files.get();
  7458. TCalculateSizeParams Params;
  7459. Params.Params = csIgnoreErrors;
  7460. Params.CopyParam = CopyParam;
  7461. Params.AllowDirs = ACanParallel || CopyParam->CalculateSize;
  7462. Params.Stats = &Stats;
  7463. if (CalculateFilesSize(FilesToCopy, TotalSize, Params))
  7464. {
  7465. TotalSizeKnown = true;
  7466. }
  7467. }
  7468. __finally
  7469. {
  7470. ExceptionOnFail = false;
  7471. }
  7472. }
  7473. OperationStart(OperationProgress, (Params & cpDelete ? foMove : foCopy), osRemote,
  7474. FilesToCopy->Count, Params & cpTemporary, TargetDir, CopyParam->CPSLimit, CopyParam->OnceDoneOperation);
  7475. bool CollectingUsage = false;
  7476. try
  7477. {
  7478. if (TotalSizeKnown)
  7479. {
  7480. if (Configuration->Usage->Collect)
  7481. {
  7482. int CounterTotalSize = TUsage::CalculateCounterSize(TotalSize);
  7483. Configuration->Usage->Inc(L"Downloads");
  7484. Configuration->Usage->Inc(L"DownloadedBytes", CounterTotalSize);
  7485. Configuration->Usage->SetMax(L"MaxDownloadSize", CounterTotalSize);
  7486. CollectingUsage = true;
  7487. }
  7488. OperationProgress.SetTotalSize(TotalSize);
  7489. }
  7490. try
  7491. {
  7492. try
  7493. {
  7494. bool Parallel = ACanParallel && TotalSizeKnown;
  7495. LogTotalTransferDetails(TargetDir, CopyParam, &OperationProgress, Parallel, Files.get());
  7496. if (Parallel)
  7497. {
  7498. UnicodeString ParallelFileName;
  7499. __int64 ParallelFileSize = -1;
  7500. CheckParallelFileTransfer(TargetDir, Files.get(), CopyParam, Params, ParallelFileName, ParallelFileSize, &OperationProgress);
  7501. if (OperationProgress.Cancel == csContinue)
  7502. {
  7503. if (ParallelFileSize >= 0)
  7504. {
  7505. DebugAssert(ParallelFileSize == TotalSize);
  7506. Params |= cpNoConfirmation;
  7507. }
  7508. // OnceDoneOperation is not supported
  7509. ParallelOperation->Init(
  7510. Files.release(), TargetDir, CopyParam, Params, &OperationProgress, Log->Name, ParallelFileSize);
  7511. UnicodeString ParallelFilePrefix;
  7512. CopyParallel(ParallelOperation, &OperationProgress);
  7513. }
  7514. }
  7515. else
  7516. {
  7517. FFileSystem->CopyToLocal(FilesToCopy, TargetDir, CopyParam, Params,
  7518. &OperationProgress, OnceDoneOperation);
  7519. }
  7520. LogTotalTransferDone(&OperationProgress);
  7521. }
  7522. __finally
  7523. {
  7524. if (Active)
  7525. {
  7526. ReactOnCommand(fsCopyToLocal);
  7527. }
  7528. }
  7529. }
  7530. catch (Exception &E)
  7531. {
  7532. CommandError(&E, MainInstructions(LoadStr(TOLOCAL_COPY_ERROR)));
  7533. OnceDoneOperation = odoIdle;
  7534. }
  7535. if (OperationProgress.Cancel == csContinue)
  7536. {
  7537. Result = true;
  7538. }
  7539. }
  7540. __finally
  7541. {
  7542. if (CollectingUsage)
  7543. {
  7544. int CounterTime = TimeToSeconds(OperationProgress.TimeElapsed());
  7545. Configuration->Usage->Inc(L"DownloadTime", CounterTime);
  7546. Configuration->Usage->SetMax(L"MaxDownloadTime", CounterTime);
  7547. }
  7548. OperationStop(OperationProgress);
  7549. }
  7550. Files.reset(NULL);
  7551. }
  7552. __finally
  7553. {
  7554. // If session is still active (no fatal error) we reload directory
  7555. // by calling EndTransaction
  7556. EndTransaction();
  7557. }
  7558. if (OnceDoneOperation != odoIdle)
  7559. {
  7560. UnicodeString DestFileName;
  7561. if (!FMultipleDestinationFiles)
  7562. {
  7563. DestFileName = FDestFileName;
  7564. }
  7565. CloseOnCompletion(OnceDoneOperation, UnicodeString(), TargetDir, DestFileName);
  7566. }
  7567. return Result;
  7568. }
  7569. //---------------------------------------------------------------------------
  7570. void __fastcall TTerminal::DoCopyToLocal(
  7571. TStrings * FilesToCopy, const UnicodeString & TargetDir, const TCopyParamType * CopyParam, int Params,
  7572. TFileOperationProgressType * OperationProgress, unsigned int Flags, TOnceDoneOperation & OnceDoneOperation)
  7573. {
  7574. DebugAssert((FilesToCopy != NULL) && (OperationProgress != NULL));
  7575. UnicodeString FullTargetDir = IncludeTrailingBackslash(TargetDir);
  7576. int Index = 0;
  7577. while ((Index < FilesToCopy->Count) && !OperationProgress->Cancel)
  7578. {
  7579. bool Success = false;
  7580. UnicodeString FileName = FilesToCopy->Strings[Index];
  7581. const TRemoteFile * File = dynamic_cast<const TRemoteFile *>(FilesToCopy->Objects[Index]);
  7582. try
  7583. {
  7584. try
  7585. {
  7586. UnicodeString AbsoluteFileName = AbsolutePath(FileName, true);
  7587. SinkRobust(AbsoluteFileName, File, FullTargetDir, CopyParam, Params, OperationProgress, Flags | tfFirstLevel);
  7588. Success = true;
  7589. }
  7590. catch (ESkipFile & E)
  7591. {
  7592. TSuspendFileOperationProgress Suspend(OperationProgress);
  7593. if (!HandleException(&E))
  7594. {
  7595. throw;
  7596. }
  7597. }
  7598. }
  7599. __finally
  7600. {
  7601. OperationFinish(OperationProgress, File, FileName, Success, OnceDoneOperation);
  7602. }
  7603. Index++;
  7604. }
  7605. }
  7606. //---------------------------------------------------------------------------
  7607. void __fastcall TTerminal::SinkRobust(
  7608. const UnicodeString & FileName, const TRemoteFile * File, const UnicodeString & TargetDir,
  7609. const TCopyParamType * CopyParam, int Params, TFileOperationProgressType * OperationProgress, unsigned int Flags)
  7610. {
  7611. TDownloadSessionAction Action(ActionLog);
  7612. try
  7613. {
  7614. bool * AFileTransferAny = FLAGSET(Flags, tfUseFileTransferAny) ? &FFileTransferAny : NULL;
  7615. bool CanRetry = (CopyParam->OnTransferOut == NULL);
  7616. TRobustOperationLoop RobustLoop(this, OperationProgress, AFileTransferAny, CanRetry);
  7617. bool Sunk = false;
  7618. do
  7619. {
  7620. try
  7621. {
  7622. // If connection is lost while deleting the file, so not retry download on the next round.
  7623. // The file may not exist anymore and the download attempt might overwrite the (only) local copy.
  7624. if (!Sunk)
  7625. {
  7626. Sink(FileName, File, TargetDir, CopyParam, Params, OperationProgress, Flags, Action);
  7627. Sunk = true;
  7628. }
  7629. if (FLAGSET(Params, cpDelete))
  7630. {
  7631. DebugAssert(FLAGCLEAR(Params, cpNoRecurse));
  7632. // If file is directory, do not delete it recursively, because it should be
  7633. // empty already. If not, it should not be deleted (some files were
  7634. // skipped or some new files were copied to it, while we were downloading)
  7635. int Params = dfNoRecursive;
  7636. DeleteFile(FileName, File, &Params);
  7637. }
  7638. }
  7639. catch (Exception & E)
  7640. {
  7641. if (!RobustLoop.TryReopen(E))
  7642. {
  7643. if (!Sunk)
  7644. {
  7645. RollbackAction(Action, OperationProgress, &E);
  7646. }
  7647. throw;
  7648. }
  7649. }
  7650. if (RobustLoop.ShouldRetry())
  7651. {
  7652. OperationProgress->RollbackTransfer();
  7653. Action.Restart();
  7654. DebugAssert(File != NULL);
  7655. if (!File->IsDirectory)
  7656. {
  7657. // prevent overwrite and resume confirmations
  7658. Params |= cpNoConfirmation;
  7659. Flags |= tfAutoResume;
  7660. }
  7661. }
  7662. }
  7663. while (RobustLoop.Retry());
  7664. }
  7665. __finally
  7666. {
  7667. // Once we issue <download> we must terminate the data stream
  7668. if (Action.IsValid() && (CopyParam->OnTransferOut != NULL) && DebugAlwaysTrue(IsCapable[fcTransferOut]))
  7669. {
  7670. CopyParam->OnTransferOut(this, NULL, 0);
  7671. }
  7672. }
  7673. }
  7674. //---------------------------------------------------------------------------
  7675. struct TSinkFileParams
  7676. {
  7677. UnicodeString TargetDir;
  7678. const TCopyParamType * CopyParam;
  7679. int Params;
  7680. TFileOperationProgressType * OperationProgress;
  7681. bool Skipped;
  7682. unsigned int Flags;
  7683. };
  7684. //---------------------------------------------------------------------------
  7685. void __fastcall TTerminal::Sink(
  7686. const UnicodeString & FileName, const TRemoteFile * File, const UnicodeString & TargetDir,
  7687. const TCopyParamType * CopyParam, int Params, TFileOperationProgressType * OperationProgress, unsigned int Flags,
  7688. TDownloadSessionAction & Action)
  7689. {
  7690. Action.FileName(FileName);
  7691. DebugAssert(File);
  7692. if (!DoAllowRemoteFileTransfer(File, CopyParam, false))
  7693. {
  7694. LogEvent(FORMAT(L"File \"%s\" excluded from transfer", (FileName)));
  7695. throw ESkipFile();
  7696. }
  7697. if (CopyParam->SkipTransfer(FileName, File->IsDirectory))
  7698. {
  7699. OperationProgress->AddSkippedFileSize(File->Resolve()->Size);
  7700. throw ESkipFile();
  7701. }
  7702. LogFileDetails(FileName, File->Modification, File->Size, File->LinkedFile);
  7703. OperationProgress->SetFile(FileName);
  7704. UnicodeString OnlyFileName = UnixExtractFileName(FileName);
  7705. UnicodeString DestFileName = ChangeFileName(CopyParam, OnlyFileName, osRemote, FLAGSET(Flags, tfFirstLevel));
  7706. UnicodeString DestFullName = TargetDir + DestFileName;
  7707. if (File->IsDirectory)
  7708. {
  7709. Action.Cancel();
  7710. if (CanRecurseToDirectory(File))
  7711. {
  7712. FILE_OPERATION_LOOP_BEGIN
  7713. {
  7714. int Attrs = FileGetAttrFix(ApiPath(DestFullName));
  7715. if (FLAGCLEAR(Attrs, faDirectory))
  7716. {
  7717. EXCEPTION;
  7718. }
  7719. }
  7720. FILE_OPERATION_LOOP_END(FMTLOAD(NOT_DIRECTORY_ERROR, (DestFullName)));
  7721. FILE_OPERATION_LOOP_BEGIN
  7722. {
  7723. THROWOSIFFALSE(ForceDirectories(ApiPath(DestFullName)));
  7724. }
  7725. FILE_OPERATION_LOOP_END(FMTLOAD(CREATE_DIR_ERROR, (DestFullName)));
  7726. if (FLAGCLEAR(Params, cpNoRecurse))
  7727. {
  7728. TSinkFileParams SinkFileParams;
  7729. SinkFileParams.TargetDir = IncludeTrailingBackslash(DestFullName);
  7730. SinkFileParams.CopyParam = CopyParam;
  7731. SinkFileParams.Params = Params;
  7732. SinkFileParams.OperationProgress = OperationProgress;
  7733. SinkFileParams.Skipped = false;
  7734. SinkFileParams.Flags = Flags & ~(tfFirstLevel | tfAutoResume);
  7735. ProcessDirectory(FileName, SinkFile, &SinkFileParams);
  7736. FFileSystem->DirectorySunk(DestFullName, File, CopyParam);
  7737. // Do not delete directory if some of its files were skipped.
  7738. // Throw "skip file" for the directory to avoid attempt to deletion
  7739. // of any parent directory
  7740. if (FLAGSET(Params, cpDelete) && SinkFileParams.Skipped)
  7741. {
  7742. throw ESkipFile();
  7743. }
  7744. }
  7745. }
  7746. else
  7747. {
  7748. LogEvent(FORMAT(L"Skipping symlink to directory \"%s\".", (FileName)));
  7749. }
  7750. }
  7751. else
  7752. {
  7753. if (CopyParam->OnTransferOut != NULL)
  7754. {
  7755. LogEvent(FORMAT(L"Streaming \"%s\" to local machine started.", (FileName)));
  7756. }
  7757. else
  7758. {
  7759. LogEvent(FORMAT(L"Copying \"%s\" to local directory started.", (FileName)));
  7760. }
  7761. // Will we use ASCII or BINARY file transfer?
  7762. UnicodeString BaseFileName = GetBaseFileName(FileName);
  7763. const TRemoteFile * UltimateFile = File->Resolve();
  7764. TFileMasks::TParams MaskParams;
  7765. MaskParams.Size = UltimateFile->Size;
  7766. MaskParams.Modification = File->Modification;
  7767. SelectTransferMode(BaseFileName, osRemote, CopyParam, MaskParams);
  7768. // Suppose same data size to transfer as to write
  7769. // (not true with ASCII transfer)
  7770. __int64 TransferSize = (CopyParam->PartSize >= 0) ? CopyParam->PartSize : (UltimateFile->Size - std::max(0LL, CopyParam->PartOffset));
  7771. OperationProgress->SetLocalSize(TransferSize);
  7772. if (IsFileEncrypted(FileName))
  7773. {
  7774. TransferSize += TEncryption::GetOverhead();
  7775. }
  7776. OperationProgress->SetTransferSize(TransferSize);
  7777. int Attrs;
  7778. UnicodeString LogFileName;
  7779. if (CopyParam->OnTransferOut != NULL)
  7780. {
  7781. Attrs = -1;
  7782. LogFileName = L"-";
  7783. }
  7784. else
  7785. {
  7786. FILE_OPERATION_LOOP_BEGIN
  7787. {
  7788. Attrs = FileGetAttrFix(ApiPath(DestFullName));
  7789. if ((Attrs >= 0) && FLAGSET(Attrs, faDirectory))
  7790. {
  7791. EXCEPTION;
  7792. }
  7793. }
  7794. FILE_OPERATION_LOOP_END(FMTLOAD(NOT_FILE_ERROR, (DestFullName)));
  7795. LogFileName = ExpandUNCFileName(DestFullName);
  7796. }
  7797. FFileSystem->Sink(
  7798. FileName, File, TargetDir, DestFileName, Attrs, CopyParam, Params, OperationProgress, Flags, Action);
  7799. LogFileDone(OperationProgress, LogFileName, Action);
  7800. OperationProgress->Succeeded();
  7801. }
  7802. }
  7803. //---------------------------------------------------------------------------
  7804. void __fastcall TTerminal::UpdateTargetAttrs(
  7805. const UnicodeString & DestFullName, const TRemoteFile * File, const TCopyParamType * CopyParam, int Attrs)
  7806. {
  7807. if (Attrs == -1)
  7808. {
  7809. Attrs = faArchive;
  7810. }
  7811. int NewAttrs = CopyParam->LocalFileAttrs(*File->Rights);
  7812. if ((NewAttrs & Attrs) != NewAttrs)
  7813. {
  7814. FILE_OPERATION_LOOP_BEGIN
  7815. {
  7816. THROWOSIFFALSE(FileSetAttr(ApiPath(DestFullName), Attrs | NewAttrs) == 0);
  7817. }
  7818. FILE_OPERATION_LOOP_END(FMTLOAD(CANT_SET_ATTRS, (DestFullName)));
  7819. }
  7820. }
  7821. //---------------------------------------------------------------------------
  7822. void __fastcall TTerminal::UpdateTargetTime(
  7823. HANDLE Handle, TDateTime Modification, TModificationFmt ModificationFmt, TDSTMode DSTMode)
  7824. {
  7825. if (ModificationFmt == mfNone)
  7826. {
  7827. LogEvent(L"Timestamp not known");
  7828. }
  7829. else
  7830. {
  7831. LogEvent(FORMAT(L"Preserving timestamp [%s]", (StandardTimestamp(Modification))));
  7832. FILETIME WrTime = DateTimeToFileTime(Modification, DSTMode);
  7833. if (!SetFileTime(Handle, NULL, NULL, &WrTime))
  7834. {
  7835. int Error = GetLastError();
  7836. LogEvent(FORMAT(L"Preserving timestamp failed, ignoring: %s", (SysErrorMessageForError(Error))));
  7837. }
  7838. }
  7839. }
  7840. //---------------------------------------------------------------------------
  7841. void __fastcall TTerminal::SinkFile(UnicodeString FileName, const TRemoteFile * File, void * Param)
  7842. {
  7843. TSinkFileParams * Params = static_cast<TSinkFileParams *>(Param);
  7844. DebugAssert(Params->OperationProgress != NULL);
  7845. try
  7846. {
  7847. SinkRobust(FileName, File, Params->TargetDir, Params->CopyParam,
  7848. Params->Params, Params->OperationProgress, Params->Flags);
  7849. }
  7850. catch (ESkipFile & E)
  7851. {
  7852. Params->Skipped = true;
  7853. {
  7854. TSuspendFileOperationProgress Suspend(Params->OperationProgress);
  7855. if (!HandleException(&E))
  7856. {
  7857. throw;
  7858. }
  7859. }
  7860. if (Params->OperationProgress->Cancel)
  7861. {
  7862. Abort();
  7863. }
  7864. }
  7865. }
  7866. //---------------------------------------------------------------------------
  7867. void __fastcall TTerminal::ReflectSettings()
  7868. {
  7869. DebugAssert(FLog != NULL);
  7870. FLog->ReflectSettings();
  7871. if (FActionLogOwned)
  7872. {
  7873. DebugAssert(FActionLog != NULL);
  7874. FActionLog->ReflectSettings();
  7875. }
  7876. // also FTunnelLog ?
  7877. }
  7878. //---------------------------------------------------------------------------
  7879. void __fastcall TTerminal::CollectUsage()
  7880. {
  7881. switch (SessionData->FSProtocol)
  7882. {
  7883. case fsSCPonly:
  7884. Configuration->Usage->Inc(L"OpenedSessionsSCP");
  7885. break;
  7886. case fsSFTP:
  7887. case fsSFTPonly:
  7888. Configuration->Usage->Inc(L"OpenedSessionsSFTP");
  7889. break;
  7890. case fsFTP:
  7891. if (SessionData->Ftps == ftpsNone)
  7892. {
  7893. Configuration->Usage->Inc(L"OpenedSessionsFTP");
  7894. }
  7895. else
  7896. {
  7897. Configuration->Usage->Inc(L"OpenedSessionsFTPS");
  7898. }
  7899. break;
  7900. case fsWebDAV:
  7901. if (SessionData->Ftps == ftpsNone)
  7902. {
  7903. Configuration->Usage->Inc(L"OpenedSessionsWebDAV");
  7904. }
  7905. else
  7906. {
  7907. Configuration->Usage->Inc(L"OpenedSessionsWebDAVS");
  7908. }
  7909. break;
  7910. case fsS3:
  7911. Configuration->Usage->Inc(L"OpenedSessionsS3");
  7912. break;
  7913. }
  7914. if (Configuration->Logging && Configuration->LogToFile)
  7915. {
  7916. Configuration->Usage->Inc(L"OpenedSessionsLogToFile2");
  7917. }
  7918. if (Configuration->LogActions)
  7919. {
  7920. Configuration->Usage->Inc(L"OpenedSessionsXmlLog");
  7921. }
  7922. std::unique_ptr<TSessionData> FactoryDefaults(new TSessionData(L""));
  7923. if (!SessionData->IsSame(FactoryDefaults.get(), true))
  7924. {
  7925. Configuration->Usage->Inc(L"OpenedSessionsAdvanced");
  7926. }
  7927. if (SessionData->ProxyMethod != ::pmNone)
  7928. {
  7929. Configuration->Usage->Inc(L"OpenedSessionsProxy");
  7930. }
  7931. if (SessionData->FtpProxyLogonType > 0)
  7932. {
  7933. Configuration->Usage->Inc(L"OpenedSessionsFtpProxy");
  7934. }
  7935. if (IsEncryptingFiles())
  7936. {
  7937. Configuration->Usage->Inc(L"OpenedSessionsEncrypted");
  7938. }
  7939. if (SessionData->SendBuf == 0)
  7940. {
  7941. Configuration->Usage->Inc(L"OpenedSessionsNoSendBuf");
  7942. }
  7943. FCollectFileSystemUsage = true;
  7944. }
  7945. //---------------------------------------------------------------------------
  7946. static UnicodeString __fastcall FormatCertificateData(const UnicodeString & Fingerprint, int Failures)
  7947. {
  7948. return FORMAT(L"%s;%2.2X", (Fingerprint, Failures));
  7949. }
  7950. //---------------------------------------------------------------------------
  7951. bool __fastcall TTerminal::VerifyCertificate(
  7952. const UnicodeString & CertificateStorageKey, const UnicodeString & SiteKey,
  7953. const UnicodeString & FingerprintSHA1, const UnicodeString & FingerprintSHA256,
  7954. const UnicodeString & CertificateSubject, int Failures)
  7955. {
  7956. bool Result = false;
  7957. UnicodeString CertificateDataSHA1 = FormatCertificateData(FingerprintSHA1, Failures);
  7958. UnicodeString CertificateDataSHA256 = FormatCertificateData(FingerprintSHA256, Failures);
  7959. std::unique_ptr<THierarchicalStorage> Storage(Configuration->CreateConfigStorage());
  7960. Storage->AccessMode = smRead;
  7961. if (Storage->OpenSubKey(CertificateStorageKey, false))
  7962. {
  7963. if (Storage->ValueExists(SiteKey))
  7964. {
  7965. UnicodeString CachedCertificateData = Storage->ReadString(SiteKey, L"");
  7966. if (SameChecksum(CertificateDataSHA1, CachedCertificateData, false) ||
  7967. SameChecksum(CertificateDataSHA256, CachedCertificateData, false))
  7968. {
  7969. LogEvent(FORMAT(L"Certificate for \"%s\" matches cached fingerprint and failures", (CertificateSubject)));
  7970. Result = true;
  7971. }
  7972. }
  7973. else if (Storage->ValueExists(FingerprintSHA1) || Storage->ValueExists(FingerprintSHA256))
  7974. {
  7975. LogEvent(FORMAT(L"Certificate for \"%s\" matches legacy cached fingerprint", (CertificateSubject)));
  7976. Result = true;
  7977. }
  7978. }
  7979. if (!Result)
  7980. {
  7981. UnicodeString Buf = SessionData->HostKey;
  7982. while (!Result && !Buf.IsEmpty())
  7983. {
  7984. UnicodeString ExpectedKey = CutToChar(Buf, L';', false);
  7985. if (ExpectedKey == L"*")
  7986. {
  7987. UnicodeString Message = LoadStr(ANY_CERTIFICATE);
  7988. Information(Message, true);
  7989. Log->Add(llException, Message);
  7990. Result = true;
  7991. }
  7992. else if (SameChecksum(ExpectedKey, FingerprintSHA1, false) ||
  7993. SameChecksum(ExpectedKey, FingerprintSHA256, false))
  7994. {
  7995. LogEvent(FORMAT(L"Certificate for \"%s\" matches configured fingerprint", (CertificateSubject)));
  7996. Result = true;
  7997. }
  7998. }
  7999. }
  8000. return Result;
  8001. }
  8002. //---------------------------------------------------------------------------
  8003. bool __fastcall TTerminal::ConfirmCertificate(
  8004. TSessionInfo & SessionInfo, int Failures, const UnicodeString & CertificateStorageKey, bool CanRemember)
  8005. {
  8006. TClipboardHandler ClipboardHandler;
  8007. ClipboardHandler.Text =
  8008. FORMAT(L"SHA-256: %s\nSHA-1: %s", (SessionInfo.CertificateFingerprintSHA256, SessionInfo.CertificateFingerprintSHA1));
  8009. TQueryButtonAlias Aliases[1];
  8010. Aliases[0].Button = qaRetry;
  8011. Aliases[0].Alias = LoadStr(COPY_KEY_BUTTON);
  8012. Aliases[0].ActionAlias = LoadStr(COPY_CERTIFICATE_ACTION);
  8013. Aliases[0].OnSubmit = &ClipboardHandler.Copy;
  8014. TQueryParams Params(qpWaitInBatch);
  8015. Params.HelpKeyword = HELP_VERIFY_CERTIFICATE;
  8016. Params.NoBatchAnswers = qaYes | qaRetry;
  8017. Params.Aliases = Aliases;
  8018. Params.AliasesCount = LENOF(Aliases);
  8019. unsigned int Answer =
  8020. QueryUser(
  8021. FMTLOAD(VERIFY_CERT_PROMPT3, (SessionInfo.Certificate)),
  8022. NULL, qaYes | qaNo | qaCancel | qaRetry, &Params, qtWarning);
  8023. bool Result;
  8024. switch (Answer)
  8025. {
  8026. case qaYes:
  8027. CacheCertificate(
  8028. CertificateStorageKey, SessionData->SiteKey,
  8029. SessionInfo.CertificateFingerprintSHA1, SessionInfo.CertificateFingerprintSHA256, Failures);
  8030. Result = true;
  8031. break;
  8032. case qaNo:
  8033. Result = true;
  8034. break;
  8035. case qaCancel:
  8036. Configuration->Usage->Inc(L"HostNotVerified");
  8037. Result = false;
  8038. break;
  8039. default:
  8040. DebugFail();
  8041. Result = false;
  8042. break;
  8043. }
  8044. // Cache only if the certificate was accepted manually
  8045. if (Result && CanRemember)
  8046. {
  8047. Configuration->RememberLastFingerprint(
  8048. SessionData->SiteKey, TlsFingerprintType, SessionInfo.CertificateFingerprintSHA256);
  8049. }
  8050. return Result;
  8051. }
  8052. //---------------------------------------------------------------------------
  8053. void __fastcall TTerminal::CacheCertificate(
  8054. const UnicodeString & CertificateStorageKey, const UnicodeString & SiteKey,
  8055. const UnicodeString & DebugUsedArg(FingerprintSHA1), const UnicodeString & FingerprintSHA256, int Failures)
  8056. {
  8057. UnicodeString CertificateData = FormatCertificateData(FingerprintSHA256, Failures);
  8058. std::unique_ptr<THierarchicalStorage> Storage(Configuration->CreateConfigStorage());
  8059. Storage->AccessMode = smReadWrite;
  8060. if (Storage->OpenSubKey(CertificateStorageKey, true))
  8061. {
  8062. Storage->WriteString(SiteKey, CertificateData);
  8063. }
  8064. }
  8065. //---------------------------------------------------------------------------
  8066. // Shared implementation for WebDAV and S3
  8067. bool TTerminal::VerifyOrConfirmHttpCertificate(
  8068. const UnicodeString & AHostName, int APortNumber, const TNeonCertificateData & AData, bool CanRemember,
  8069. TSessionInfo & SessionInfo)
  8070. {
  8071. TNeonCertificateData Data = AData;
  8072. SessionInfo.CertificateFingerprintSHA1 = Data.FingerprintSHA1;
  8073. SessionInfo.CertificateFingerprintSHA256 = Data.FingerprintSHA256;
  8074. bool Result;
  8075. if (SessionData->FingerprintScan)
  8076. {
  8077. Result = false;
  8078. }
  8079. else
  8080. {
  8081. LogEvent(0, CertificateVerificationMessage(Data));
  8082. UnicodeString WindowsValidatedMessage;
  8083. // Side effect is that NE_SSL_UNTRUSTED is removed from Failure, before we call VerifyCertificate,
  8084. // as it compares failures against a cached failures that do not include NE_SSL_UNTRUSTED
  8085. // (if the certificate is trusted by Windows certificate store).
  8086. // But we will log that result only if we actually use it for the decision.
  8087. bool WindowsValidated = NeonWindowsValidateCertificateWithMessage(Data, WindowsValidatedMessage);
  8088. UnicodeString SiteKey = TSessionData::FormatSiteKey(AHostName, APortNumber);
  8089. Result =
  8090. VerifyCertificate(
  8091. HttpsCertificateStorageKey, SiteKey, Data.FingerprintSHA1, Data.FingerprintSHA256, Data.Subject, Data.Failures);
  8092. if (Result)
  8093. {
  8094. SessionInfo.CertificateVerifiedManually = true;
  8095. }
  8096. else
  8097. {
  8098. Result = WindowsValidated;
  8099. LogEvent(0, WindowsValidatedMessage);
  8100. }
  8101. SessionInfo.Certificate = CertificateSummary(Data, AHostName);
  8102. if (!Result)
  8103. {
  8104. if (ConfirmCertificate(SessionInfo, Data.Failures, HttpsCertificateStorageKey, CanRemember))
  8105. {
  8106. Result = true;
  8107. SessionInfo.CertificateVerifiedManually = true;
  8108. }
  8109. }
  8110. }
  8111. return Result;
  8112. }
  8113. //---------------------------------------------------------------------------
  8114. void __fastcall TTerminal::CollectTlsUsage(const UnicodeString & TlsVersionStr)
  8115. {
  8116. // see SSL_get_version() in OpenSSL ssl_lib.c
  8117. if (TlsVersionStr == L"TLSv1.3")
  8118. {
  8119. Configuration->Usage->Inc(L"OpenedSessionsTLS13");
  8120. }
  8121. else if (TlsVersionStr == L"TLSv1.2")
  8122. {
  8123. Configuration->Usage->Inc(L"OpenedSessionsTLS12");
  8124. }
  8125. else if (TlsVersionStr == L"TLSv1.1")
  8126. {
  8127. Configuration->Usage->Inc(L"OpenedSessionsTLS11");
  8128. }
  8129. else if (TlsVersionStr == L"TLSv1")
  8130. {
  8131. Configuration->Usage->Inc(L"OpenedSessionsTLS10");
  8132. }
  8133. else if (TlsVersionStr == L"SSLv3")
  8134. {
  8135. Configuration->Usage->Inc(L"OpenedSessionsSSL30");
  8136. }
  8137. else if (TlsVersionStr == L"SSLv2")
  8138. {
  8139. Configuration->Usage->Inc(L"OpenedSessionsSSL20");
  8140. }
  8141. else
  8142. {
  8143. DebugFail();
  8144. }
  8145. }
  8146. //---------------------------------------------------------------------------
  8147. bool __fastcall TTerminal::LoadTlsCertificate(X509 *& Certificate, EVP_PKEY *& PrivateKey)
  8148. {
  8149. bool Result = !SessionData->TlsCertificateFile.IsEmpty();
  8150. if (Result)
  8151. {
  8152. UnicodeString Passphrase = SessionData->Passphrase;
  8153. // Inspired by neon's ne_ssl_clicert_read
  8154. bool Retry;
  8155. do
  8156. {
  8157. Retry = false;
  8158. bool WrongPassphrase;
  8159. ParseCertificate(SessionData->TlsCertificateFile, Passphrase, Certificate, PrivateKey, WrongPassphrase);
  8160. if (WrongPassphrase)
  8161. {
  8162. if (Passphrase.IsEmpty())
  8163. {
  8164. LogEvent(L"Certificate is encrypted, need passphrase");
  8165. Information(LoadStr(CLIENT_CERTIFICATE_LOADING), false);
  8166. }
  8167. else
  8168. {
  8169. Information(LoadStr(CERTIFICATE_DECODE_ERROR_INFO), false);
  8170. }
  8171. Passphrase = L"";
  8172. if (PromptUser(
  8173. SessionData, pkPassphrase,
  8174. LoadStr(CERTIFICATE_PASSPHRASE_TITLE), L"",
  8175. LoadStr(CERTIFICATE_PASSPHRASE_PROMPT), false, 0, Passphrase))
  8176. {
  8177. Retry = true;
  8178. }
  8179. else
  8180. {
  8181. Result = false;
  8182. }
  8183. }
  8184. }
  8185. while (Retry);
  8186. }
  8187. return Result;
  8188. }
  8189. //---------------------------------------------------------------------------
  8190. UnicodeString __fastcall TTerminal::GetBaseFileName(UnicodeString FileName)
  8191. {
  8192. if (FSessionData->TrimVMSVersions)
  8193. {
  8194. int P = FileName.LastDelimiter(L";");
  8195. if (P > 0)
  8196. {
  8197. FileName.SetLength(P - 1);
  8198. }
  8199. }
  8200. return FileName;
  8201. }
  8202. //---------------------------------------------------------------------------
  8203. UnicodeString __fastcall TTerminal::ChangeFileName(const TCopyParamType * CopyParam,
  8204. UnicodeString FileName, TOperationSide Side, bool FirstLevel)
  8205. {
  8206. FileName = GetBaseFileName(FileName);
  8207. FileName = CopyParam->ChangeFileName(FileName, Side, FirstLevel);
  8208. return FileName;
  8209. }
  8210. //---------------------------------------------------------------------------
  8211. bool __fastcall TTerminal::CanRecurseToDirectory(const TRemoteFile * File)
  8212. {
  8213. return !File->IsSymLink || FSessionData->FollowDirectorySymlinks;
  8214. }
  8215. //---------------------------------------------------------------------------
  8216. TTerminal::TEncryptedFileNames::const_iterator __fastcall TTerminal::GetEncryptedFileName(const UnicodeString & Path)
  8217. {
  8218. UnicodeString FileDir = UnixExtractFileDir(Path);
  8219. // If we haven't been in this folder yet, read it to collect mapping to encrypted file names.
  8220. if (FFoldersScannedForEncryptedFiles.find(FileDir) == FFoldersScannedForEncryptedFiles.end())
  8221. {
  8222. try
  8223. {
  8224. delete DoReadDirectoryListing(FileDir, true);
  8225. }
  8226. catch (Exception & E)
  8227. {
  8228. if (!Active)
  8229. {
  8230. throw;
  8231. }
  8232. if (FEncryptedFileNames.find(Path) == FEncryptedFileNames.end())
  8233. {
  8234. FEncryptedFileNames.insert(std::make_pair(Path, UnixExtractFileName(Path)));
  8235. LogEvent(2, FORMAT(L"Name of file '%s' assumed not to be encrypted", (Path)));
  8236. }
  8237. }
  8238. FFoldersScannedForEncryptedFiles.insert(FileDir);
  8239. }
  8240. TEncryptedFileNames::const_iterator Result = FEncryptedFileNames.find(Path);
  8241. return Result;
  8242. }
  8243. //---------------------------------------------------------------------------
  8244. bool __fastcall TTerminal::IsFileEncrypted(const UnicodeString & Path, bool EncryptNewFiles)
  8245. {
  8246. // can be optimized
  8247. bool Result = (EncryptFileName(Path, EncryptNewFiles) != Path);
  8248. return Result;
  8249. }
  8250. //---------------------------------------------------------------------------
  8251. UnicodeString __fastcall TTerminal::EncryptFileName(const UnicodeString & Path, bool EncryptNewFiles)
  8252. {
  8253. UnicodeString Result = Path;
  8254. if (IsEncryptingFiles() && !IsUnixRootPath(Path))
  8255. {
  8256. UnicodeString FileName = UnixExtractFileName(Path);
  8257. UnicodeString FileDir = UnixExtractFileDir(Path);
  8258. if (!FileName.IsEmpty() && IsRealFile(FileName))
  8259. {
  8260. TEncryptedFileNames::const_iterator I = GetEncryptedFileName(Path);
  8261. if (I != FEncryptedFileNames.end())
  8262. {
  8263. FileName = I->second;
  8264. }
  8265. else if (EncryptNewFiles)
  8266. {
  8267. TEncryption Encryption(FEncryptKey);
  8268. FileName = Encryption.EncryptFileName(FileName);
  8269. FEncryptedFileNames.insert(std::make_pair(Path, FileName));
  8270. LogEvent(2, FORMAT(L"Name of file '%s' encrypted as '%s'", (Path, FileName)));
  8271. }
  8272. }
  8273. FileDir = EncryptFileName(FileDir, EncryptNewFiles);
  8274. Result = UnixCombinePaths(FileDir, FileName);
  8275. }
  8276. return Result;
  8277. }
  8278. //---------------------------------------------------------------------------
  8279. UnicodeString __fastcall TTerminal::DecryptFileName(const UnicodeString & Path, bool DecryptFullPath, bool DontCache)
  8280. {
  8281. UnicodeString Result = Path;
  8282. if (IsEncryptingFiles() && !IsUnixRootPath(Path))
  8283. {
  8284. UnicodeString FileName = UnixExtractFileName(Path);
  8285. UnicodeString FileNameEncrypted = FileName;
  8286. bool Encrypted = TEncryption::IsEncryptedFileName(FileName);
  8287. if (Encrypted)
  8288. {
  8289. TEncryption Encryption(FEncryptKey);
  8290. FileName = Encryption.DecryptFileName(FileName);
  8291. }
  8292. if (Encrypted || DecryptFullPath) // DecryptFullPath is just an optimization
  8293. {
  8294. UnicodeString FileDir = UnixExtractFileDir(Path);
  8295. FileDir = DecryptFileName(FileDir, DecryptFullPath, DontCache);
  8296. Result = UnixCombinePaths(FileDir, FileName);
  8297. }
  8298. TEncryptedFileNames::iterator Iter = FEncryptedFileNames.find(Result);
  8299. bool NotCached = (Iter == FEncryptedFileNames.end());
  8300. if (!DontCache && (Encrypted || NotCached))
  8301. {
  8302. if (Encrypted && (NotCached || (Iter->second != FileNameEncrypted)))
  8303. {
  8304. LogEvent(2, FORMAT(L"Name of file '%s' decrypted from '%s'", (Result, FileNameEncrypted)));
  8305. }
  8306. // This may overwrite another variant of encryption
  8307. FEncryptedFileNames[Result] = FileNameEncrypted;
  8308. }
  8309. }
  8310. return Result;
  8311. }
  8312. //---------------------------------------------------------------------------
  8313. TRemoteFile * TTerminal::CheckRights(const UnicodeString & EntryType, const UnicodeString & FileName, bool & WrongRights)
  8314. {
  8315. std::unique_ptr<TRemoteFile> File;
  8316. try
  8317. {
  8318. LogEvent(FORMAT(L"Checking %s \"%s\"...", (LowerCase(EntryType), FileName)));
  8319. File.reset(ReadFile(FileName));
  8320. int ForbiddenRights = TRights::rfGroupWrite | TRights::rfOtherWrite;
  8321. if ((File->Rights->Number & ForbiddenRights) != 0)
  8322. {
  8323. LogEvent(FORMAT(L"%s \"%s\" exists, but has incorrect permissions %s.", (EntryType, FileName, File->Rights->Octal)));
  8324. WrongRights = true;
  8325. }
  8326. else
  8327. {
  8328. LogEvent(FORMAT(L"%s \"%s\" exists and has correct permissions %s.", (EntryType, FileName, File->Rights->Octal)));
  8329. }
  8330. }
  8331. catch (Exception & E)
  8332. {
  8333. }
  8334. return File.release();
  8335. }
  8336. //---------------------------------------------------------------------------
  8337. UnicodeString TTerminal::UploadPublicKey(const UnicodeString & FileName)
  8338. {
  8339. UnicodeString Result;
  8340. UnicodeString TemporaryDir;
  8341. bool PrevAutoReadDirectory = AutoReadDirectory;
  8342. bool PrevExceptionOnFail = ExceptionOnFail;
  8343. UnicodeString AuthorizedKeysFilePath = FORMAT(L"%s/%s", (OpensshFolderName, OpensshAuthorizedKeysFileName));
  8344. try
  8345. {
  8346. AutoReadDirectory = false;
  8347. ExceptionOnFail = true;
  8348. Log->AddSeparator();
  8349. UnicodeString Comment;
  8350. bool UnusedHasCertificate;
  8351. UnicodeString Line = GetPublicKeyLine(FileName, Comment, UnusedHasCertificate);
  8352. LogEvent(FORMAT(L"Adding public key line to \"%s\" file:\n%s", (AuthorizedKeysFilePath, Line)));
  8353. UnicodeString SshFolderAbsolutePath = UnixIncludeTrailingBackslash(GetHomeDirectory()) + OpensshFolderName;
  8354. bool WrongRights = false;
  8355. std::unique_ptr<TRemoteFile> SshFolderFile(CheckRights(L"Folder", SshFolderAbsolutePath, WrongRights));
  8356. if (SshFolderFile.get() == NULL)
  8357. {
  8358. TRights SshFolderRights;
  8359. SshFolderRights.Number = TRights::rfUserRead | TRights::rfUserWrite | TRights::rfUserExec;
  8360. TRemoteProperties SshFolderProperties;
  8361. SshFolderProperties.Rights = SshFolderRights;
  8362. SshFolderProperties.Valid = TValidProperties() << vpRights;
  8363. LogEvent(FORMAT(L"Trying to create \"%s\" folder with permissions %s...", (OpensshFolderName, SshFolderRights.Octal)));
  8364. CreateDirectory(SshFolderAbsolutePath, &SshFolderProperties);
  8365. }
  8366. TemporaryDir = ExcludeTrailingBackslash(Configuration->TemporaryDir());
  8367. if (!ForceDirectories(ApiPath(TemporaryDir)))
  8368. {
  8369. throw EOSExtException(FMTLOAD(CREATE_TEMP_DIR_ERROR, (TemporaryDir)));
  8370. }
  8371. UnicodeString TemporaryAuthorizedKeysFile = IncludeTrailingBackslash(TemporaryDir) + OpensshAuthorizedKeysFileName;
  8372. UnicodeString AuthorizedKeysFileAbsolutePath = UnixIncludeTrailingBackslash(SshFolderAbsolutePath) + OpensshAuthorizedKeysFileName;
  8373. bool Updated = true;
  8374. TCopyParamType CopyParam; // Use factory defaults
  8375. CopyParam.ResumeSupport = rsOff; // not to break the permissions
  8376. CopyParam.PreserveTime = false; // not needed
  8377. UnicodeString AuthorizedKeys;
  8378. std::unique_ptr<TRemoteFile> AuthorizedKeysFileFile(CheckRights(L"File", AuthorizedKeysFileAbsolutePath, WrongRights));
  8379. if (AuthorizedKeysFileFile.get() != NULL)
  8380. {
  8381. AuthorizedKeysFileFile->FullFileName = AuthorizedKeysFileAbsolutePath;
  8382. std::unique_ptr<TStrings> Files(new TStringList());
  8383. Files->AddObject(AuthorizedKeysFileAbsolutePath, AuthorizedKeysFileFile.get());
  8384. LogEvent(FORMAT(L"Downloading current \"%s\" file...", (OpensshAuthorizedKeysFileName)));
  8385. CopyToLocal(Files.get(), TemporaryDir, &CopyParam, cpNoConfirmation, NULL);
  8386. // Overload with Encoding parameter work incorrectly, when used on a file without BOM
  8387. AuthorizedKeys = TFile::ReadAllText(TemporaryAuthorizedKeysFile);
  8388. std::unique_ptr<TStrings> AuthorizedKeysLines(TextToStringList(AuthorizedKeys));
  8389. int P = Line.Pos(L" ");
  8390. if (DebugAlwaysTrue(P > 0))
  8391. {
  8392. P = PosEx(L" ", Line, P + 1);
  8393. }
  8394. UnicodeString Prefix = Line.SubString(1, P); // including the space
  8395. for (int Index = 0; Index < AuthorizedKeysLines->Count; Index++)
  8396. {
  8397. if (StartsStr(Prefix, AuthorizedKeysLines->Strings[Index]))
  8398. {
  8399. LogEvent(FORMAT(L"\"%s\" file already contains public key line:\n%s", (OpensshAuthorizedKeysFileName, AuthorizedKeysLines->Strings[Index])));
  8400. Updated = false;
  8401. }
  8402. }
  8403. if (Updated)
  8404. {
  8405. LogEvent(FORMAT(L"\"%s\" file does not contain the public key line yet.", (OpensshAuthorizedKeysFileName)));
  8406. if (!EndsStr(L"\n", AuthorizedKeys))
  8407. {
  8408. LogEvent(FORMAT(L"Adding missing trailing new line to \"%s\" file...", (OpensshAuthorizedKeysFileName)));
  8409. AuthorizedKeys += L"\n";
  8410. }
  8411. }
  8412. }
  8413. else
  8414. {
  8415. LogEvent(FORMAT(L"Creating new \"%s\" file...", (OpensshAuthorizedKeysFileName)));
  8416. CopyParam.PreserveRights = true;
  8417. CopyParam.Rights.Number = TRights::rfUserRead | TRights::rfUserWrite;
  8418. }
  8419. if (Updated)
  8420. {
  8421. AuthorizedKeys += Line + L"\n";
  8422. // Overload without Encoding parameter uses TEncoding::UTF8, but does not write BOM, what we want
  8423. TFile::WriteAllText(TemporaryAuthorizedKeysFile, AuthorizedKeys);
  8424. std::unique_ptr<TStrings> Files(new TStringList());
  8425. Files->Add(TemporaryAuthorizedKeysFile);
  8426. LogEvent(FORMAT(L"Uploading updated \"%s\" file...", (OpensshAuthorizedKeysFileName)));
  8427. CopyToRemote(Files.get(), SshFolderAbsolutePath, &CopyParam, cpNoConfirmation, NULL);
  8428. }
  8429. Result = FMTLOAD(PUBLIC_KEY_UPLOADED, (Comment));
  8430. if (WrongRights)
  8431. {
  8432. Result += L"\n\n" + FMTLOAD(PUBLIC_KEY_PERMISSIONS, (AuthorizedKeysFilePath));
  8433. }
  8434. }
  8435. __finally
  8436. {
  8437. AutoReadDirectory = PrevAutoReadDirectory;
  8438. ExceptionOnFail = PrevExceptionOnFail;
  8439. if (!TemporaryDir.IsEmpty())
  8440. {
  8441. RecursiveDeleteFile(ExcludeTrailingBackslash(TemporaryDir));
  8442. }
  8443. }
  8444. return Result;
  8445. }
  8446. //---------------------------------------------------------------------------
  8447. bool TTerminal::IsValidFile(TRemoteFile * File)
  8448. {
  8449. return
  8450. !File->FileName.IsEmpty() &&
  8451. (IsUnixRootPath(File->FileName) || UnixExtractFileDir(File->FileName).IsEmpty());
  8452. }
  8453. //---------------------------------------------------------------------------
  8454. TStrings * TTerminal::ProcessFeatures(TStrings * Features)
  8455. {
  8456. return ::ProcessFeatures(Features, SessionData->ProtocolFeatures.Trim());
  8457. }
  8458. //---------------------------------------------------------------------------
  8459. //---------------------------------------------------------------------------
  8460. __fastcall TSecondaryTerminal::TSecondaryTerminal(
  8461. TTerminal * MainTerminal, TSessionData * ASessionData, TConfiguration * Configuration,
  8462. const UnicodeString & Name, TActionLog * ActionLog) :
  8463. TTerminal(ASessionData, Configuration, ActionLog),
  8464. FMainTerminal(MainTerminal)
  8465. {
  8466. Log->SetParent(FMainTerminal->Log, Name);
  8467. SessionData->NonPersistant();
  8468. DebugAssert(FMainTerminal != NULL);
  8469. FMainTerminal->FSecondaryTerminals++;
  8470. if (SessionData->TunnelLocalPortNumber != 0)
  8471. {
  8472. SessionData->TunnelLocalPortNumber = SessionData->TunnelLocalPortNumber + FMainTerminal->FSecondaryTerminals;
  8473. }
  8474. if (!FMainTerminal->UserName.IsEmpty())
  8475. {
  8476. SessionData->UserName = FMainTerminal->UserName;
  8477. }
  8478. }
  8479. //---------------------------------------------------------------------------
  8480. void __fastcall TSecondaryTerminal::UpdateFromMain()
  8481. {
  8482. if ((FFileSystem != NULL) && (FMainTerminal->FFileSystem != NULL))
  8483. {
  8484. FFileSystem->UpdateFromMain(FMainTerminal->FFileSystem);
  8485. }
  8486. }
  8487. //---------------------------------------------------------------------------
  8488. void __fastcall TSecondaryTerminal::DirectoryLoaded(TRemoteFileList * FileList)
  8489. {
  8490. FMainTerminal->DirectoryLoaded(FileList);
  8491. DebugAssert(FileList != NULL);
  8492. }
  8493. //---------------------------------------------------------------------------
  8494. void __fastcall TSecondaryTerminal::DirectoryModified(const UnicodeString Path,
  8495. bool SubDirs)
  8496. {
  8497. // clear cache of main terminal
  8498. FMainTerminal->DirectoryModified(Path, SubDirs);
  8499. }
  8500. //---------------------------------------------------------------------------
  8501. TTerminal * __fastcall TSecondaryTerminal::GetPrimaryTerminal()
  8502. {
  8503. return FMainTerminal;
  8504. }
  8505. //---------------------------------------------------------------------------
  8506. __fastcall TTerminalList::TTerminalList(TConfiguration * AConfiguration) :
  8507. TObjectList()
  8508. {
  8509. DebugAssert(AConfiguration);
  8510. FConfiguration = AConfiguration;
  8511. }
  8512. //---------------------------------------------------------------------------
  8513. __fastcall TTerminalList::~TTerminalList()
  8514. {
  8515. DebugAssert(Count == 0);
  8516. }
  8517. //---------------------------------------------------------------------------
  8518. TTerminal * __fastcall TTerminalList::CreateTerminal(TSessionData * Data)
  8519. {
  8520. return new TTerminal(Data, FConfiguration);
  8521. }
  8522. //---------------------------------------------------------------------------
  8523. TTerminal * __fastcall TTerminalList::NewTerminal(TSessionData * Data)
  8524. {
  8525. TTerminal * Terminal = CreateTerminal(Data);
  8526. Add(Terminal);
  8527. return Terminal;
  8528. }
  8529. //---------------------------------------------------------------------------
  8530. void __fastcall TTerminalList::FreeTerminal(TTerminal * Terminal)
  8531. {
  8532. DebugAssert(IndexOf(Terminal) >= 0);
  8533. Remove(Terminal);
  8534. }
  8535. //---------------------------------------------------------------------------
  8536. void __fastcall TTerminalList::FreeAndNullTerminal(TTerminal * & Terminal)
  8537. {
  8538. TTerminal * T = Terminal;
  8539. Terminal = NULL;
  8540. FreeTerminal(T);
  8541. }
  8542. //---------------------------------------------------------------------------
  8543. TTerminal * __fastcall TTerminalList::GetTerminal(int Index)
  8544. {
  8545. return dynamic_cast<TTerminal *>(Items[Index]);
  8546. }
  8547. //---------------------------------------------------------------------------
  8548. void __fastcall TTerminalList::RecryptPasswords()
  8549. {
  8550. for (int Index = 0; Index < Count; Index++)
  8551. {
  8552. Terminals[Index]->RecryptPasswords();
  8553. }
  8554. }
  8555. //---------------------------------------------------------------------------
  8556. //---------------------------------------------------------------------------
  8557. TLocalFileHandle::TLocalFileHandle()
  8558. {
  8559. Handle = 0;
  8560. Attrs = 0;
  8561. MTime = 0;
  8562. ATime = 0;
  8563. Size = 0;
  8564. Directory = false;
  8565. }
  8566. //---------------------------------------------------------------------------
  8567. TLocalFileHandle::~TLocalFileHandle()
  8568. {
  8569. Release();
  8570. }
  8571. //---------------------------------------------------------------------------
  8572. void TLocalFileHandle::Release()
  8573. {
  8574. if (Handle != 0)
  8575. {
  8576. Close();
  8577. }
  8578. }
  8579. //---------------------------------------------------------------------------
  8580. void TLocalFileHandle::Dismiss()
  8581. {
  8582. if (DebugAlwaysTrue(Handle != 0))
  8583. {
  8584. Handle = 0;
  8585. }
  8586. }
  8587. //---------------------------------------------------------------------------
  8588. void TLocalFileHandle::Close()
  8589. {
  8590. if (DebugAlwaysTrue(Handle != 0))
  8591. {
  8592. CloseHandle(Handle);
  8593. Dismiss();
  8594. }
  8595. }