Terminal.cpp 273 KB

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