Terminal.cpp 240 KB

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