Terminal.cpp 217 KB

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