Terminal.cpp 240 KB

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