Terminal.cpp 294 KB

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