Terminal.cpp 255 KB

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