1
0

Terminal.cpp 189 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154
  1. //---------------------------------------------------------------------------
  2. #include <vcl.h>
  3. #pragma hdrstop
  4. #include "Terminal.h"
  5. #include <SysUtils.hpp>
  6. #include <FileCtrl.hpp>
  7. #include "Common.h"
  8. #include "PuttyTools.h"
  9. #include "FileBuffer.h"
  10. #include "Interface.h"
  11. #include "RemoteFiles.h"
  12. #include "SecureShell.h"
  13. #include "ScpFileSystem.h"
  14. #include "SftpFileSystem.h"
  15. #ifndef NO_FILEZILLA
  16. #include "FtpFileSystem.h"
  17. #endif
  18. #include "WebDAVFileSystem.h"
  19. #include "TextsCore.h"
  20. #include "HelpCore.h"
  21. #include "CoreMain.h"
  22. #include "Queue.h"
  23. #include <openssl/pkcs12.h>
  24. #include <openssl/err.h>
  25. #ifndef AUTO_WINSOCK
  26. #include <winsock2.h>
  27. #endif
  28. //---------------------------------------------------------------------------
  29. #pragma package(smart_init)
  30. //---------------------------------------------------------------------------
  31. #define FILE_OPERATION_LOOP_TERMINAL this
  32. //---------------------------------------------------------------------------
  33. //---------------------------------------------------------------------------
  34. class TLoopDetector
  35. {
  36. public:
  37. __fastcall TLoopDetector();
  38. void __fastcall RecordVisitedDirectory(const UnicodeString & Directory);
  39. bool __fastcall IsUnvisitedDirectory(const TRemoteFile * File);
  40. private:
  41. std::unique_ptr<TStringList> FVisitedDirectories;
  42. };
  43. //---------------------------------------------------------------------------
  44. __fastcall TLoopDetector::TLoopDetector()
  45. {
  46. FVisitedDirectories.reset(CreateSortedStringList());
  47. }
  48. //---------------------------------------------------------------------------
  49. void __fastcall TLoopDetector::RecordVisitedDirectory(const UnicodeString & Directory)
  50. {
  51. UnicodeString VisitedDirectory = ExcludeTrailingBackslash(Directory);
  52. FVisitedDirectories->Add(VisitedDirectory);
  53. }
  54. //---------------------------------------------------------------------------
  55. bool __fastcall TLoopDetector::IsUnvisitedDirectory(const TRemoteFile * File)
  56. {
  57. DebugAssert(File->IsDirectory);
  58. UnicodeString Directory = UnixExcludeTrailingBackslash(File->FullFileName);
  59. bool Result = (FVisitedDirectories->IndexOf(Directory) < 0);
  60. if (Result)
  61. {
  62. if (File->IsSymLink)
  63. {
  64. UnicodeString BaseDirectory = UnixExtractFileDir(Directory);
  65. UnicodeString SymlinkDirectory =
  66. UnixExcludeTrailingBackslash(AbsolutePath(BaseDirectory, File->LinkTo));
  67. Result = (FVisitedDirectories->IndexOf(SymlinkDirectory) < 0);
  68. }
  69. }
  70. if (Result)
  71. {
  72. RecordVisitedDirectory(Directory);
  73. }
  74. return Result;
  75. }
  76. //---------------------------------------------------------------------------
  77. //---------------------------------------------------------------------------
  78. struct TMoveFileParams
  79. {
  80. UnicodeString Target;
  81. UnicodeString FileMask;
  82. };
  83. //---------------------------------------------------------------------------
  84. struct TFilesFindParams
  85. {
  86. TFileMasks FileMask;
  87. TFileFoundEvent OnFileFound;
  88. TFindingFileEvent OnFindingFile;
  89. bool Cancel;
  90. TLoopDetector LoopDetector;
  91. };
  92. //---------------------------------------------------------------------------
  93. TCalculateSizeStats::TCalculateSizeStats()
  94. {
  95. memset(this, 0, sizeof(*this));
  96. }
  97. //---------------------------------------------------------------------------
  98. TSynchronizeOptions::TSynchronizeOptions()
  99. {
  100. memset(this, 0, sizeof(*this));
  101. }
  102. //---------------------------------------------------------------------------
  103. TSynchronizeOptions::~TSynchronizeOptions()
  104. {
  105. delete Filter;
  106. }
  107. //---------------------------------------------------------------------------
  108. bool __fastcall TSynchronizeOptions::MatchesFilter(const UnicodeString & FileName)
  109. {
  110. int FoundIndex;
  111. bool Result;
  112. if (Filter == NULL)
  113. {
  114. Result = true;
  115. }
  116. else
  117. {
  118. Result = Filter->Find(FileName, FoundIndex);
  119. }
  120. return Result;
  121. }
  122. //---------------------------------------------------------------------------
  123. TSpaceAvailable::TSpaceAvailable()
  124. {
  125. memset(this, 0, sizeof(*this));
  126. }
  127. //---------------------------------------------------------------------------
  128. TOverwriteFileParams::TOverwriteFileParams()
  129. {
  130. SourceSize = 0;
  131. DestSize = 0;
  132. SourcePrecision = mfFull;
  133. DestPrecision = mfFull;
  134. }
  135. //---------------------------------------------------------------------------
  136. //---------------------------------------------------------------------------
  137. TSynchronizeChecklist::TItem::TItem() :
  138. Action(saNone), IsDirectory(false), RemoteFile(NULL), Checked(true), ImageIndex(-1)
  139. {
  140. Local.ModificationFmt = mfFull;
  141. Local.Modification = 0;
  142. Local.Size = 0;
  143. Remote.ModificationFmt = mfFull;
  144. Remote.Modification = 0;
  145. Remote.Size = 0;
  146. }
  147. //---------------------------------------------------------------------------
  148. TSynchronizeChecklist::TItem::~TItem()
  149. {
  150. delete RemoteFile;
  151. }
  152. //---------------------------------------------------------------------------
  153. const UnicodeString& TSynchronizeChecklist::TItem::GetFileName() const
  154. {
  155. if (!Remote.FileName.IsEmpty())
  156. {
  157. return Remote.FileName;
  158. }
  159. else
  160. {
  161. DebugAssert(!Local.FileName.IsEmpty());
  162. return Local.FileName;
  163. }
  164. }
  165. //---------------------------------------------------------------------------
  166. //---------------------------------------------------------------------------
  167. TSynchronizeChecklist::TSynchronizeChecklist() :
  168. FList(new TList())
  169. {
  170. }
  171. //---------------------------------------------------------------------------
  172. TSynchronizeChecklist::~TSynchronizeChecklist()
  173. {
  174. for (int Index = 0; Index < FList->Count; Index++)
  175. {
  176. delete static_cast<TItem *>(FList->Items[Index]);
  177. }
  178. delete FList;
  179. }
  180. //---------------------------------------------------------------------------
  181. void TSynchronizeChecklist::Add(TItem * Item)
  182. {
  183. FList->Add(Item);
  184. }
  185. //---------------------------------------------------------------------------
  186. int __fastcall TSynchronizeChecklist::Compare(void * AItem1, void * AItem2)
  187. {
  188. TItem * Item1 = static_cast<TItem *>(AItem1);
  189. TItem * Item2 = static_cast<TItem *>(AItem2);
  190. int Result;
  191. if (!Item1->Local.Directory.IsEmpty())
  192. {
  193. Result = AnsiCompareText(Item1->Local.Directory, Item2->Local.Directory);
  194. }
  195. else
  196. {
  197. DebugAssert(!Item1->Remote.Directory.IsEmpty());
  198. Result = AnsiCompareText(Item1->Remote.Directory, Item2->Remote.Directory);
  199. }
  200. if (Result == 0)
  201. {
  202. Result = AnsiCompareText(Item1->GetFileName(), Item2->GetFileName());
  203. }
  204. return Result;
  205. }
  206. //---------------------------------------------------------------------------
  207. void TSynchronizeChecklist::Sort()
  208. {
  209. FList->Sort(Compare);
  210. }
  211. //---------------------------------------------------------------------------
  212. int TSynchronizeChecklist::GetCount() const
  213. {
  214. return FList->Count;
  215. }
  216. //---------------------------------------------------------------------------
  217. const TSynchronizeChecklist::TItem * TSynchronizeChecklist::GetItem(int Index) const
  218. {
  219. return static_cast<TItem *>(FList->Items[Index]);
  220. }
  221. //---------------------------------------------------------------------------
  222. void __fastcall TSynchronizeChecklist::Update(const TItem * Item, bool Check, TAction Action)
  223. {
  224. // TSynchronizeChecklist owns non-const items so it can manipulate them freely,
  225. // const_cast here is just an optimization
  226. TItem * MutableItem = const_cast<TItem *>(Item);
  227. DebugAssert(FList->IndexOf(MutableItem) >= 0);
  228. MutableItem->Checked = Check;
  229. MutableItem->Action = Action;
  230. }
  231. //---------------------------------------------------------------------------
  232. TSynchronizeChecklist::TAction __fastcall TSynchronizeChecklist::Reverse(TSynchronizeChecklist::TAction Action)
  233. {
  234. switch (Action)
  235. {
  236. case saUploadNew:
  237. return saDeleteLocal;
  238. case saDownloadNew:
  239. return saDeleteRemote;
  240. case saUploadUpdate:
  241. return saDownloadUpdate;
  242. case saDownloadUpdate:
  243. return saUploadUpdate;
  244. case saDeleteRemote:
  245. return saDownloadNew;
  246. case saDeleteLocal:
  247. return saUploadNew;
  248. default:
  249. case saNone:
  250. DebugFail();
  251. return saNone;
  252. }
  253. }
  254. //---------------------------------------------------------------------------
  255. //---------------------------------------------------------------------------
  256. class TTunnelThread : public TSimpleThread
  257. {
  258. public:
  259. __fastcall TTunnelThread(TSecureShell * SecureShell);
  260. virtual __fastcall ~TTunnelThread();
  261. virtual void __fastcall Terminate();
  262. protected:
  263. virtual void __fastcall Execute();
  264. private:
  265. TSecureShell * FSecureShell;
  266. bool FTerminated;
  267. };
  268. //---------------------------------------------------------------------------
  269. __fastcall TTunnelThread::TTunnelThread(TSecureShell * SecureShell) :
  270. FSecureShell(SecureShell),
  271. FTerminated(false)
  272. {
  273. Start();
  274. }
  275. //---------------------------------------------------------------------------
  276. __fastcall TTunnelThread::~TTunnelThread()
  277. {
  278. // close before the class's virtual functions (Terminate particularly) are lost
  279. Close();
  280. }
  281. //---------------------------------------------------------------------------
  282. void __fastcall TTunnelThread::Terminate()
  283. {
  284. FTerminated = true;
  285. }
  286. //---------------------------------------------------------------------------
  287. void __fastcall TTunnelThread::Execute()
  288. {
  289. try
  290. {
  291. while (!FTerminated)
  292. {
  293. FSecureShell->Idle(250);
  294. }
  295. }
  296. catch(...)
  297. {
  298. if (FSecureShell->Active)
  299. {
  300. FSecureShell->Close();
  301. }
  302. // do not pass exception out of thread's proc
  303. }
  304. }
  305. //---------------------------------------------------------------------------
  306. //---------------------------------------------------------------------------
  307. class TTunnelUI : public TSessionUI
  308. {
  309. public:
  310. __fastcall TTunnelUI(TTerminal * Terminal);
  311. virtual void __fastcall Information(const UnicodeString & Str, bool Status);
  312. virtual unsigned int __fastcall QueryUser(const UnicodeString Query,
  313. TStrings * MoreMessages, unsigned int Answers, const TQueryParams * Params,
  314. TQueryType QueryType);
  315. virtual unsigned int __fastcall QueryUserException(const UnicodeString Query,
  316. Exception * E, unsigned int Answers, const TQueryParams * Params,
  317. TQueryType QueryType);
  318. virtual bool __fastcall PromptUser(TSessionData * Data, TPromptKind Kind,
  319. UnicodeString Name, UnicodeString Instructions, TStrings * Prompts,
  320. TStrings * Results);
  321. virtual void __fastcall DisplayBanner(const UnicodeString & Banner);
  322. virtual void __fastcall FatalError(Exception * E, UnicodeString Msg, UnicodeString HelpContext);
  323. virtual void __fastcall HandleExtendedException(Exception * E);
  324. virtual void __fastcall Closed();
  325. virtual void __fastcall ProcessGUI();
  326. private:
  327. TTerminal * FTerminal;
  328. unsigned int FTerminalThread;
  329. };
  330. //---------------------------------------------------------------------------
  331. __fastcall TTunnelUI::TTunnelUI(TTerminal * Terminal)
  332. {
  333. FTerminal = Terminal;
  334. FTerminalThread = GetCurrentThreadId();
  335. }
  336. //---------------------------------------------------------------------------
  337. void __fastcall TTunnelUI::Information(const UnicodeString & Str, bool Status)
  338. {
  339. if (GetCurrentThreadId() == FTerminalThread)
  340. {
  341. FTerminal->Information(Str, Status);
  342. }
  343. }
  344. //---------------------------------------------------------------------------
  345. unsigned int __fastcall TTunnelUI::QueryUser(const UnicodeString Query,
  346. TStrings * MoreMessages, unsigned int Answers, const TQueryParams * Params,
  347. TQueryType QueryType)
  348. {
  349. unsigned int Result;
  350. if (GetCurrentThreadId() == FTerminalThread)
  351. {
  352. Result = FTerminal->QueryUser(Query, MoreMessages, Answers, Params, QueryType);
  353. }
  354. else
  355. {
  356. Result = AbortAnswer(Answers);
  357. }
  358. return Result;
  359. }
  360. //---------------------------------------------------------------------------
  361. unsigned int __fastcall TTunnelUI::QueryUserException(const UnicodeString Query,
  362. Exception * E, unsigned int Answers, const TQueryParams * Params,
  363. TQueryType QueryType)
  364. {
  365. unsigned int Result;
  366. if (GetCurrentThreadId() == FTerminalThread)
  367. {
  368. Result = FTerminal->QueryUserException(Query, E, Answers, Params, QueryType);
  369. }
  370. else
  371. {
  372. Result = AbortAnswer(Answers);
  373. }
  374. return Result;
  375. }
  376. //---------------------------------------------------------------------------
  377. bool __fastcall TTunnelUI::PromptUser(TSessionData * Data, TPromptKind Kind,
  378. UnicodeString Name, UnicodeString Instructions, TStrings * Prompts, TStrings * Results)
  379. {
  380. bool Result;
  381. if (GetCurrentThreadId() == FTerminalThread)
  382. {
  383. if (IsAuthenticationPrompt(Kind))
  384. {
  385. Instructions = LoadStr(TUNNEL_INSTRUCTION) +
  386. (Instructions.IsEmpty() ? L"" : L"\n") +
  387. Instructions;
  388. }
  389. Result = FTerminal->PromptUser(Data, Kind, Name, Instructions, Prompts, Results);
  390. }
  391. else
  392. {
  393. Result = false;
  394. }
  395. return Result;
  396. }
  397. //---------------------------------------------------------------------------
  398. void __fastcall TTunnelUI::DisplayBanner(const UnicodeString & Banner)
  399. {
  400. if (GetCurrentThreadId() == FTerminalThread)
  401. {
  402. FTerminal->DisplayBanner(Banner);
  403. }
  404. }
  405. //---------------------------------------------------------------------------
  406. void __fastcall TTunnelUI::FatalError(Exception * E, UnicodeString Msg, UnicodeString HelpKeyword)
  407. {
  408. throw ESshFatal(E, Msg, HelpKeyword);
  409. }
  410. //---------------------------------------------------------------------------
  411. void __fastcall TTunnelUI::HandleExtendedException(Exception * E)
  412. {
  413. if (GetCurrentThreadId() == FTerminalThread)
  414. {
  415. FTerminal->HandleExtendedException(E);
  416. }
  417. }
  418. //---------------------------------------------------------------------------
  419. void __fastcall TTunnelUI::Closed()
  420. {
  421. // noop
  422. }
  423. //---------------------------------------------------------------------------
  424. void __fastcall TTunnelUI::ProcessGUI()
  425. {
  426. // noop
  427. }
  428. //---------------------------------------------------------------------------
  429. //---------------------------------------------------------------------------
  430. class TCallbackGuard
  431. {
  432. public:
  433. inline __fastcall TCallbackGuard(TTerminal * FTerminal);
  434. inline __fastcall ~TCallbackGuard();
  435. void __fastcall FatalError(Exception * E, const UnicodeString & Msg, const UnicodeString & HelpKeyword);
  436. inline void __fastcall Verify();
  437. void __fastcall Dismiss();
  438. private:
  439. ExtException * FFatalError;
  440. TTerminal * FTerminal;
  441. bool FGuarding;
  442. };
  443. //---------------------------------------------------------------------------
  444. __fastcall TCallbackGuard::TCallbackGuard(TTerminal * Terminal) :
  445. FTerminal(Terminal),
  446. FFatalError(NULL),
  447. FGuarding(FTerminal->FCallbackGuard == NULL)
  448. {
  449. if (FGuarding)
  450. {
  451. FTerminal->FCallbackGuard = this;
  452. }
  453. }
  454. //---------------------------------------------------------------------------
  455. __fastcall TCallbackGuard::~TCallbackGuard()
  456. {
  457. if (FGuarding)
  458. {
  459. DebugAssert((FTerminal->FCallbackGuard == this) || (FTerminal->FCallbackGuard == NULL));
  460. FTerminal->FCallbackGuard = NULL;
  461. }
  462. delete FFatalError;
  463. }
  464. //---------------------------------------------------------------------------
  465. void __fastcall TCallbackGuard::FatalError(Exception * E, const UnicodeString & Msg, const UnicodeString & HelpKeyword)
  466. {
  467. DebugAssert(FGuarding);
  468. // make sure we do not bother about getting back the silent abort exception
  469. // we issued ourselves. this may happen when there is an exception handler
  470. // that converts any exception to fatal one (such as in TTerminal::Open).
  471. if (dynamic_cast<ECallbackGuardAbort *>(E) == NULL)
  472. {
  473. delete FFatalError;
  474. FFatalError = new ExtException(E, Msg, HelpKeyword);
  475. }
  476. // silently abort what we are doing.
  477. // non-silent exception would be caught probably by default application
  478. // exception handler, which may not do an appropriate action
  479. // (particularly it will not resume broken transfer).
  480. throw ECallbackGuardAbort();
  481. }
  482. //---------------------------------------------------------------------------
  483. void __fastcall TCallbackGuard::Dismiss()
  484. {
  485. DebugAssert(FFatalError == NULL);
  486. FGuarding = false;
  487. }
  488. //---------------------------------------------------------------------------
  489. void __fastcall TCallbackGuard::Verify()
  490. {
  491. if (FGuarding)
  492. {
  493. FGuarding = false;
  494. DebugAssert(FTerminal->FCallbackGuard == this);
  495. FTerminal->FCallbackGuard = NULL;
  496. if (FFatalError != NULL)
  497. {
  498. throw ESshFatal(FFatalError, L"");
  499. }
  500. }
  501. }
  502. //---------------------------------------------------------------------------
  503. //---------------------------------------------------------------------------
  504. TRobustOperationLoop::TRobustOperationLoop(TTerminal * Terminal, TFileOperationProgressType * OperationProgress) :
  505. FTerminal(Terminal),
  506. FOperationProgress(OperationProgress),
  507. FRetry(false)
  508. {
  509. }
  510. //---------------------------------------------------------------------------
  511. bool TRobustOperationLoop::TryReopen(Exception & E)
  512. {
  513. FRetry =
  514. !FTerminal->Active &&
  515. FTerminal->QueryReopen(&E, ropNoReadDirectory, FOperationProgress);
  516. return FRetry;
  517. }
  518. //---------------------------------------------------------------------------
  519. bool TRobustOperationLoop::ShouldRetry()
  520. {
  521. return FRetry;
  522. }
  523. //---------------------------------------------------------------------------
  524. bool TRobustOperationLoop::Retry()
  525. {
  526. bool Result = FRetry;
  527. FRetry = false;
  528. return Result;
  529. }
  530. //---------------------------------------------------------------------------
  531. class TRetryOperationLoop
  532. {
  533. public:
  534. TRetryOperationLoop(TTerminal * Terminal);
  535. void Error(Exception & E);
  536. void Error(Exception & E, TSessionAction & Action);
  537. void Error(Exception & E, const UnicodeString & Message);
  538. void Error(Exception & E, TSessionAction & Action, const UnicodeString & Message);
  539. bool Retry();
  540. private:
  541. TTerminal * FTerminal;
  542. bool FRetry;
  543. void DoError(Exception & E, TSessionAction * Action, const UnicodeString & Message);
  544. };
  545. //---------------------------------------------------------------------------
  546. TRetryOperationLoop::TRetryOperationLoop(TTerminal * Terminal)
  547. {
  548. FTerminal = Terminal;
  549. FRetry = false;
  550. }
  551. //---------------------------------------------------------------------------
  552. void TRetryOperationLoop::DoError(Exception & E, TSessionAction * Action, const UnicodeString & Message)
  553. {
  554. // Note that the action may already be canceled when RollbackAction is called
  555. unsigned int Result;
  556. try
  557. {
  558. Result = FTerminal->CommandError(&E, Message, qaRetry | qaSkip | qaAbort);
  559. }
  560. catch (Exception & E2)
  561. {
  562. if (Action != NULL)
  563. {
  564. FTerminal->RollbackAction(*Action, NULL, &E2);
  565. }
  566. throw;
  567. }
  568. switch (Result)
  569. {
  570. case qaRetry:
  571. FRetry = true;
  572. if (Action != NULL)
  573. {
  574. Action->Cancel();
  575. }
  576. break;
  577. case qaAbort:
  578. if (Action != NULL)
  579. {
  580. FTerminal->RollbackAction(*Action, NULL, &E);
  581. }
  582. Abort();
  583. break;
  584. case qaSkip:
  585. if (Action != NULL)
  586. {
  587. Action->Cancel();
  588. }
  589. break;
  590. default:
  591. DebugFail();
  592. break;
  593. }
  594. }
  595. //---------------------------------------------------------------------------
  596. void TRetryOperationLoop::Error(Exception & E)
  597. {
  598. DoError(E, NULL, UnicodeString());
  599. }
  600. //---------------------------------------------------------------------------
  601. void TRetryOperationLoop::Error(Exception & E, TSessionAction & Action)
  602. {
  603. DoError(E, &Action, UnicodeString());
  604. }
  605. //---------------------------------------------------------------------------
  606. void TRetryOperationLoop::Error(Exception & E, const UnicodeString & Message)
  607. {
  608. DoError(E, NULL, Message);
  609. }
  610. //---------------------------------------------------------------------------
  611. void TRetryOperationLoop::Error(Exception & E, TSessionAction & Action, const UnicodeString & Message)
  612. {
  613. DoError(E, &Action, Message);
  614. }
  615. //---------------------------------------------------------------------------
  616. bool TRetryOperationLoop::Retry()
  617. {
  618. bool Result = FRetry;
  619. FRetry = false;
  620. return Result;
  621. }
  622. //---------------------------------------------------------------------------
  623. //---------------------------------------------------------------------------
  624. __fastcall TTerminal::TTerminal(TSessionData * SessionData,
  625. TConfiguration * Configuration)
  626. {
  627. FConfiguration = Configuration;
  628. FSessionData = new TSessionData(L"");
  629. FSessionData->Assign(SessionData);
  630. FLog = new TSessionLog(this, FSessionData, Configuration);
  631. FActionLog = new TActionLog(this, FSessionData, Configuration);
  632. FFiles = new TRemoteDirectory(this);
  633. FExceptionOnFail = 0;
  634. FInTransaction = 0;
  635. FReadCurrentDirectoryPending = false;
  636. FReadDirectoryPending = false;
  637. FUsersGroupsLookedup = False;
  638. FTunnelLocalPortNumber = 0;
  639. FFileSystem = NULL;
  640. FSecureShell = NULL;
  641. FOnProgress = NULL;
  642. FOnFinished = NULL;
  643. FOnDeleteLocalFile = NULL;
  644. FOnReadDirectoryProgress = NULL;
  645. FOnQueryUser = NULL;
  646. FOnPromptUser = NULL;
  647. FOnDisplayBanner = NULL;
  648. FOnShowExtendedException = NULL;
  649. FOnInformation = NULL;
  650. FOnClose = NULL;
  651. FOnFindingFile = NULL;
  652. FUseBusyCursor = True;
  653. FLockDirectory = L"";
  654. FDirectoryCache = new TRemoteDirectoryCache();
  655. FDirectoryChangesCache = NULL;
  656. FFSProtocol = cfsUnknown;
  657. FCommandSession = NULL;
  658. FAutoReadDirectory = true;
  659. FReadingCurrentDirectory = false;
  660. FStatus = ssClosed;
  661. FOpening = 0;
  662. FTunnelThread = NULL;
  663. FTunnel = NULL;
  664. FTunnelData = NULL;
  665. FTunnelLog = NULL;
  666. FTunnelUI = NULL;
  667. FTunnelOpening = false;
  668. FCallbackGuard = NULL;
  669. FNesting = 0;
  670. }
  671. //---------------------------------------------------------------------------
  672. __fastcall TTerminal::~TTerminal()
  673. {
  674. if (Active)
  675. {
  676. Close();
  677. }
  678. if (FCallbackGuard != NULL)
  679. {
  680. // see TTerminal::HandleExtendedException
  681. FCallbackGuard->Dismiss();
  682. }
  683. DebugAssert(FTunnel == NULL);
  684. SAFE_DESTROY(FCommandSession);
  685. if (SessionData->CacheDirectoryChanges && SessionData->PreserveDirectoryChanges &&
  686. (FDirectoryChangesCache != NULL))
  687. {
  688. Configuration->SaveDirectoryChangesCache(SessionData->SessionKey,
  689. FDirectoryChangesCache);
  690. }
  691. SAFE_DESTROY_EX(TCustomFileSystem, FFileSystem);
  692. SAFE_DESTROY_EX(TSessionLog, FLog);
  693. SAFE_DESTROY_EX(TActionLog, FActionLog);
  694. delete FFiles;
  695. delete FDirectoryCache;
  696. delete FDirectoryChangesCache;
  697. SAFE_DESTROY(FSessionData);
  698. }
  699. //---------------------------------------------------------------------------
  700. void __fastcall TTerminal::Idle()
  701. {
  702. // Once we disconnect, do nothing, until reconnect handler
  703. // "receives the information".
  704. // Never go idle when called from within ::ProcessGUI() call
  705. // as we may recurse for good, timeouting eventually.
  706. if (Active && (FNesting == 0))
  707. {
  708. TAutoNestingCounter NestingCounter(FNesting);
  709. if (Configuration->ActualLogProtocol >= 1)
  710. {
  711. LogEvent(L"Session upkeep");
  712. }
  713. DebugAssert(FFileSystem != NULL);
  714. FFileSystem->Idle();
  715. if (CommandSessionOpened)
  716. {
  717. try
  718. {
  719. FCommandSession->Idle();
  720. }
  721. catch(Exception & E)
  722. {
  723. // If the secondary session is dropped, ignore the error and let
  724. // it be reconnected when needed.
  725. // BTW, non-fatal error can hardly happen here, that's why
  726. // it is displayed, because it can be useful to know.
  727. if (FCommandSession->Active)
  728. {
  729. FCommandSession->HandleExtendedException(&E);
  730. }
  731. }
  732. }
  733. }
  734. }
  735. //---------------------------------------------------------------------
  736. RawByteString __fastcall TTerminal::EncryptPassword(const UnicodeString & Password)
  737. {
  738. return Configuration->EncryptPassword(Password, SessionData->SessionName);
  739. }
  740. //---------------------------------------------------------------------
  741. UnicodeString __fastcall TTerminal::DecryptPassword(const RawByteString & Password)
  742. {
  743. UnicodeString Result;
  744. try
  745. {
  746. Result = Configuration->DecryptPassword(Password, SessionData->SessionName);
  747. }
  748. catch(EAbort &)
  749. {
  750. // silently ignore aborted prompts for master password and return empty password
  751. }
  752. return Result;
  753. }
  754. //---------------------------------------------------------------------------
  755. void __fastcall TTerminal::RecryptPasswords()
  756. {
  757. FSessionData->RecryptPasswords();
  758. FRememberedPassword = EncryptPassword(DecryptPassword(FRememberedPassword));
  759. FRememberedTunnelPassword = EncryptPassword(DecryptPassword(FRememberedTunnelPassword));
  760. }
  761. //---------------------------------------------------------------------------
  762. UnicodeString __fastcall TTerminal::ExpandFileName(UnicodeString Path,
  763. const UnicodeString BasePath)
  764. {
  765. // replace this by AbsolutePath()
  766. Path = UnixExcludeTrailingBackslash(Path);
  767. if (!UnixIsAbsolutePath(Path) && !BasePath.IsEmpty())
  768. {
  769. // TODO: Handle more complicated cases like "../../xxx"
  770. if (Path == L"..")
  771. {
  772. Path = UnixExcludeTrailingBackslash(UnixExtractFilePath(
  773. UnixExcludeTrailingBackslash(BasePath)));
  774. }
  775. else
  776. {
  777. Path = UnixIncludeTrailingBackslash(BasePath) + Path;
  778. }
  779. }
  780. return Path;
  781. }
  782. //---------------------------------------------------------------------------
  783. bool __fastcall TTerminal::GetActive()
  784. {
  785. return (FFileSystem != NULL) && FFileSystem->GetActive();
  786. }
  787. //---------------------------------------------------------------------------
  788. void __fastcall TTerminal::Close()
  789. {
  790. FFileSystem->Close();
  791. // Cannot rely on CommandSessionOpened here as Status is set to ssClosed
  792. // only after the OnClose is called
  793. if ((FCommandSession != NULL) && FCommandSession->Active)
  794. {
  795. // prevent recursion
  796. FCommandSession->OnClose = NULL;
  797. FCommandSession->Close();
  798. }
  799. }
  800. //---------------------------------------------------------------------------
  801. void __fastcall TTerminal::ResetConnection()
  802. {
  803. // used to be called from Reopen(), why?
  804. FTunnelError = L"";
  805. FRememberedPasswordTried = false;
  806. // Particularly to prevent reusing a wrong client certificate passphrase
  807. // from a previous login attempt
  808. FRememberedPassword = UnicodeString();
  809. FRememberedTunnelPasswordTried = false;
  810. FRememberedTunnelPassword = UnicodeString();
  811. if (FDirectoryChangesCache != NULL)
  812. {
  813. delete FDirectoryChangesCache;
  814. FDirectoryChangesCache = NULL;
  815. }
  816. FFiles->Directory = L"";
  817. // note that we cannot clear contained files
  818. // as they can still be referenced in the GUI atm
  819. }
  820. //---------------------------------------------------------------------------
  821. UnicodeString __fastcall TTerminal::FingerprintScan()
  822. {
  823. SessionData->FingerprintScan = true;
  824. try
  825. {
  826. Open();
  827. // we should never get here
  828. Abort();
  829. }
  830. catch (...)
  831. {
  832. if (!FFingerprintScanned.IsEmpty())
  833. {
  834. return FFingerprintScanned;
  835. }
  836. throw;
  837. }
  838. DebugFail();
  839. return UnicodeString();
  840. }
  841. //---------------------------------------------------------------------------
  842. void __fastcall TTerminal::Open()
  843. {
  844. TAutoNestingCounter OpeningCounter(FOpening);
  845. ReflectSettings();
  846. try
  847. {
  848. DoInformation(L"", true, 1);
  849. try
  850. {
  851. try
  852. {
  853. ResetConnection();
  854. FStatus = ssOpening;
  855. try
  856. {
  857. if (FFileSystem == NULL)
  858. {
  859. Log->AddSystemInfo();
  860. DoInitializeLog();
  861. Log->AddStartupInfo();
  862. }
  863. DebugAssert(FTunnel == NULL);
  864. if (FSessionData->Tunnel)
  865. {
  866. DoInformation(LoadStr(OPEN_TUNNEL), true);
  867. LogEvent(L"Opening tunnel.");
  868. OpenTunnel();
  869. Log->AddSeparator();
  870. FSessionData->ConfigureTunnel(FTunnelLocalPortNumber);
  871. DoInformation(LoadStr(USING_TUNNEL), false);
  872. LogEvent(FORMAT(L"Connecting via tunnel interface %s:%d.",
  873. (FSessionData->HostNameExpanded, FSessionData->PortNumber)));
  874. }
  875. else
  876. {
  877. DebugAssert(FTunnelLocalPortNumber == 0);
  878. }
  879. if (FFileSystem == NULL)
  880. {
  881. if (SessionData->FSProtocol == fsFTP)
  882. {
  883. #ifdef NO_FILEZILLA
  884. LogEvent(L"FTP protocol is not supported by this build.");
  885. FatalError(NULL, LoadStr(FTP_UNSUPPORTED));
  886. #else
  887. FFSProtocol = cfsFTP;
  888. FFileSystem = new TFTPFileSystem(this);
  889. FFileSystem->Open();
  890. Log->AddSeparator();
  891. LogEvent(L"Using FTP protocol.");
  892. #endif
  893. }
  894. else if (SessionData->FSProtocol == fsWebDAV)
  895. {
  896. FFSProtocol = cfsWebDAV;
  897. FFileSystem = new TWebDAVFileSystem(this);
  898. FFileSystem->Open();
  899. Log->AddSeparator();
  900. LogEvent(L"Using WebDAV protocol.");
  901. }
  902. else
  903. {
  904. DebugAssert(FSecureShell == NULL);
  905. try
  906. {
  907. FSecureShell = new TSecureShell(this, FSessionData, Log, Configuration);
  908. try
  909. {
  910. // there will be only one channel in this session
  911. FSecureShell->Simple = true;
  912. FSecureShell->Open();
  913. }
  914. catch(Exception & E)
  915. {
  916. DebugAssert(!FSecureShell->Active);
  917. if (SessionData->FingerprintScan)
  918. {
  919. FFingerprintScanned = FSecureShell->GetHostKeyFingerprint();
  920. }
  921. if (!FSecureShell->Active && !FTunnelError.IsEmpty())
  922. {
  923. // the only case where we expect this to happen
  924. DebugAssert(E.Message == LoadStr(UNEXPECTED_CLOSE_ERROR));
  925. FatalError(&E, FMTLOAD(TUNNEL_ERROR, (FTunnelError)));
  926. }
  927. else
  928. {
  929. throw;
  930. }
  931. }
  932. Log->AddSeparator();
  933. if ((SessionData->FSProtocol == fsSCPonly) ||
  934. (SessionData->FSProtocol == fsSFTP && FSecureShell->SshFallbackCmd()))
  935. {
  936. FFSProtocol = cfsSCP;
  937. FFileSystem = new TSCPFileSystem(this, FSecureShell);
  938. FSecureShell = NULL; // ownership passed
  939. LogEvent(L"Using SCP protocol.");
  940. }
  941. else
  942. {
  943. FFSProtocol = cfsSFTP;
  944. FFileSystem = new TSFTPFileSystem(this, FSecureShell);
  945. FSecureShell = NULL; // ownership passed
  946. LogEvent(L"Using SFTP protocol.");
  947. }
  948. }
  949. __finally
  950. {
  951. delete FSecureShell;
  952. FSecureShell = NULL;
  953. }
  954. }
  955. }
  956. else
  957. {
  958. FFileSystem->Open();
  959. }
  960. }
  961. __finally
  962. {
  963. if (FSessionData->Tunnel)
  964. {
  965. FSessionData->RollbackTunnel();
  966. }
  967. }
  968. if (SessionData->CacheDirectoryChanges)
  969. {
  970. DebugAssert(FDirectoryChangesCache == NULL);
  971. FDirectoryChangesCache = new TRemoteDirectoryChangesCache(
  972. Configuration->CacheDirectoryChangesMaxSize);
  973. if (SessionData->PreserveDirectoryChanges)
  974. {
  975. Configuration->LoadDirectoryChangesCache(SessionData->SessionKey,
  976. FDirectoryChangesCache);
  977. }
  978. }
  979. DoStartup();
  980. if (FCollectFileSystemUsage)
  981. {
  982. FFileSystem->CollectUsage();
  983. FCollectFileSystemUsage = false;
  984. }
  985. DoInformation(LoadStr(STATUS_READY), true);
  986. FStatus = ssOpened;
  987. }
  988. catch(...)
  989. {
  990. // rollback
  991. if (FDirectoryChangesCache != NULL)
  992. {
  993. delete FDirectoryChangesCache;
  994. FDirectoryChangesCache = NULL;
  995. }
  996. if (SessionData->FingerprintScan && (FFileSystem != NULL) &&
  997. DebugAlwaysTrue(SessionData->Ftps != ftpsNone))
  998. {
  999. FFingerprintScanned = FFileSystem->GetSessionInfo().CertificateFingerprint;
  1000. }
  1001. throw;
  1002. }
  1003. }
  1004. __finally
  1005. {
  1006. DoInformation(L"", true, 0);
  1007. }
  1008. }
  1009. catch(EFatal &)
  1010. {
  1011. throw;
  1012. }
  1013. catch(Exception & E)
  1014. {
  1015. // any exception while opening session is fatal
  1016. FatalError(&E, L"");
  1017. }
  1018. }
  1019. //---------------------------------------------------------------------------
  1020. bool __fastcall TTerminal::IsListenerFree(unsigned int PortNumber)
  1021. {
  1022. SOCKET Socket = socket(AF_INET, SOCK_STREAM, 0);
  1023. bool Result = (Socket != INVALID_SOCKET);
  1024. if (Result)
  1025. {
  1026. SOCKADDR_IN Address;
  1027. memset(&Address, 0, sizeof(Address));
  1028. Address.sin_family = AF_INET;
  1029. Address.sin_port = htons(static_cast<short>(PortNumber));
  1030. Address.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  1031. Result = (bind(Socket, reinterpret_cast<sockaddr *>(&Address), sizeof(Address)) == 0);
  1032. closesocket(Socket);
  1033. }
  1034. return Result;
  1035. }
  1036. //---------------------------------------------------------------------------
  1037. void __fastcall TTerminal::OpenTunnel()
  1038. {
  1039. DebugAssert(FTunnelData == NULL);
  1040. FTunnelLocalPortNumber = FSessionData->TunnelLocalPortNumber;
  1041. if (FTunnelLocalPortNumber == 0)
  1042. {
  1043. FTunnelLocalPortNumber = Configuration->TunnelLocalPortNumberLow;
  1044. while (!IsListenerFree(FTunnelLocalPortNumber))
  1045. {
  1046. FTunnelLocalPortNumber++;
  1047. if (FTunnelLocalPortNumber > Configuration->TunnelLocalPortNumberHigh)
  1048. {
  1049. FTunnelLocalPortNumber = 0;
  1050. FatalError(NULL, FMTLOAD(TUNNEL_NO_FREE_PORT,
  1051. (Configuration->TunnelLocalPortNumberLow, Configuration->TunnelLocalPortNumberHigh)));
  1052. }
  1053. }
  1054. LogEvent(FORMAT(L"Autoselected tunnel local port number %d", (FTunnelLocalPortNumber)));
  1055. }
  1056. try
  1057. {
  1058. FTunnelData = new TSessionData(L"");
  1059. FTunnelData->Assign(StoredSessions->DefaultSettings);
  1060. FTunnelData->Name = FMTLOAD(TUNNEL_SESSION_NAME, (FSessionData->SessionName));
  1061. FTunnelData->Tunnel = false;
  1062. FTunnelData->HostName = FSessionData->TunnelHostName;
  1063. FTunnelData->PortNumber = FSessionData->TunnelPortNumber;
  1064. FTunnelData->UserName = FSessionData->TunnelUserName;
  1065. FTunnelData->Password = FSessionData->TunnelPassword;
  1066. FTunnelData->PublicKeyFile = FSessionData->TunnelPublicKeyFile;
  1067. FTunnelData->TunnelPortFwd = FORMAT(L"L%d\t%s:%d",
  1068. (FTunnelLocalPortNumber, FSessionData->HostNameExpanded, FSessionData->PortNumber));
  1069. FTunnelData->HostKey = FSessionData->TunnelHostKey;
  1070. FTunnelData->ProxyMethod = FSessionData->ProxyMethod;
  1071. FTunnelData->ProxyHost = FSessionData->ProxyHost;
  1072. FTunnelData->ProxyPort = FSessionData->ProxyPort;
  1073. FTunnelData->ProxyUsername = FSessionData->ProxyUsername;
  1074. FTunnelData->ProxyPassword = FSessionData->ProxyPassword;
  1075. FTunnelData->ProxyTelnetCommand = FSessionData->ProxyTelnetCommand;
  1076. FTunnelData->ProxyLocalCommand = FSessionData->ProxyLocalCommand;
  1077. FTunnelData->ProxyDNS = FSessionData->ProxyDNS;
  1078. FTunnelData->ProxyLocalhost = FSessionData->ProxyLocalhost;
  1079. FTunnelLog = new TSessionLog(this, FTunnelData, Configuration);
  1080. FTunnelLog->Parent = FLog;
  1081. FTunnelLog->Name = L"Tunnel";
  1082. FTunnelLog->ReflectSettings();
  1083. FTunnelUI = new TTunnelUI(this);
  1084. FTunnel = new TSecureShell(FTunnelUI, FTunnelData, FTunnelLog, Configuration);
  1085. FTunnelOpening = true;
  1086. try
  1087. {
  1088. FTunnel->Open();
  1089. }
  1090. __finally
  1091. {
  1092. FTunnelOpening = false;
  1093. }
  1094. FTunnelThread = new TTunnelThread(FTunnel);
  1095. }
  1096. catch(...)
  1097. {
  1098. CloseTunnel();
  1099. throw;
  1100. }
  1101. }
  1102. //---------------------------------------------------------------------------
  1103. void __fastcall TTerminal::CloseTunnel()
  1104. {
  1105. SAFE_DESTROY_EX(TTunnelThread, FTunnelThread);
  1106. FTunnelError = FTunnel->LastTunnelError;
  1107. SAFE_DESTROY_EX(TSecureShell, FTunnel);
  1108. SAFE_DESTROY_EX(TTunnelUI, FTunnelUI);
  1109. SAFE_DESTROY_EX(TSessionLog, FTunnelLog);
  1110. SAFE_DESTROY(FTunnelData);
  1111. FTunnelLocalPortNumber = 0;
  1112. }
  1113. //---------------------------------------------------------------------------
  1114. void __fastcall TTerminal::Closed()
  1115. {
  1116. if (FTunnel != NULL)
  1117. {
  1118. CloseTunnel();
  1119. }
  1120. if (OnClose)
  1121. {
  1122. TCallbackGuard Guard(this);
  1123. OnClose(this);
  1124. Guard.Verify();
  1125. }
  1126. FStatus = ssClosed;
  1127. }
  1128. //---------------------------------------------------------------------------
  1129. void __fastcall TTerminal::ProcessGUI()
  1130. {
  1131. // Do not process GUI here, as we are called directly from a GUI loop and may
  1132. // recurse for good.
  1133. // Alternatively we may check for (FOperationProgress == NULL)
  1134. if (FNesting == 0)
  1135. {
  1136. TAutoNestingCounter NestingCounter(FNesting);
  1137. ::ProcessGUI();
  1138. }
  1139. }
  1140. //---------------------------------------------------------------------------
  1141. void __fastcall TTerminal::Progress(TFileOperationProgressType * OperationProgress)
  1142. {
  1143. if (FNesting == 0)
  1144. {
  1145. TAutoNestingCounter NestingCounter(FNesting);
  1146. OperationProgress->Progress();
  1147. }
  1148. }
  1149. //---------------------------------------------------------------------------
  1150. void __fastcall TTerminal::Reopen(int Params)
  1151. {
  1152. TFSProtocol OrigFSProtocol = SessionData->FSProtocol;
  1153. UnicodeString PrevRemoteDirectory = SessionData->RemoteDirectory;
  1154. bool PrevReadCurrentDirectoryPending = FReadCurrentDirectoryPending;
  1155. bool PrevReadDirectoryPending = FReadDirectoryPending;
  1156. DebugAssert(!FSuspendTransaction);
  1157. bool PrevAutoReadDirectory = FAutoReadDirectory;
  1158. // here used to be a check for FExceptionOnFail being 0
  1159. // but it can happen, e.g. when we are downloading file to execute it.
  1160. // however I'm not sure why we mind having excaption-on-fail enabled here
  1161. int PrevExceptionOnFail = FExceptionOnFail;
  1162. try
  1163. {
  1164. FReadCurrentDirectoryPending = false;
  1165. FReadDirectoryPending = false;
  1166. FSuspendTransaction = true;
  1167. FExceptionOnFail = 0;
  1168. // typically, we avoid reading directory, when there is operation ongoing,
  1169. // for file list which may reference files from current directory
  1170. if (FLAGSET(Params, ropNoReadDirectory))
  1171. {
  1172. AutoReadDirectory = false;
  1173. }
  1174. // only peek, we may not be connected at all atm,
  1175. // so make sure we do not try retrieving current directory from the server
  1176. // (particularly with FTP)
  1177. UnicodeString ACurrentDirectory = PeekCurrentDirectory();
  1178. if (!ACurrentDirectory.IsEmpty())
  1179. {
  1180. SessionData->RemoteDirectory = ACurrentDirectory;
  1181. }
  1182. if (SessionData->FSProtocol == fsSFTP)
  1183. {
  1184. SessionData->FSProtocol = (FFSProtocol == cfsSCP ? fsSCPonly : fsSFTPonly);
  1185. }
  1186. // Could be active before, if fatal error occured in the secondary terminal.
  1187. // But now, since we handle the secondary terminal's OnClose,
  1188. // by closing outselves, it should not happen anymore.
  1189. if (DebugAlwaysFalse(Active))
  1190. {
  1191. Close();
  1192. }
  1193. Open();
  1194. }
  1195. __finally
  1196. {
  1197. SessionData->RemoteDirectory = PrevRemoteDirectory;
  1198. SessionData->FSProtocol = OrigFSProtocol;
  1199. FAutoReadDirectory = PrevAutoReadDirectory;
  1200. FReadCurrentDirectoryPending = PrevReadCurrentDirectoryPending;
  1201. FReadDirectoryPending = PrevReadDirectoryPending;
  1202. FSuspendTransaction = false;
  1203. FExceptionOnFail = PrevExceptionOnFail;
  1204. }
  1205. }
  1206. //---------------------------------------------------------------------------
  1207. bool __fastcall TTerminal::PromptUser(TSessionData * Data, TPromptKind Kind,
  1208. UnicodeString Name, UnicodeString Instructions, UnicodeString Prompt, bool Echo, int MaxLen, UnicodeString & Result)
  1209. {
  1210. bool AResult;
  1211. TStrings * Prompts = new TStringList;
  1212. TStrings * Results = new TStringList;
  1213. try
  1214. {
  1215. Prompts->AddObject(Prompt, (TObject *)(FLAGMASK(Echo, pupEcho)));
  1216. Results->AddObject(Result, (TObject *)MaxLen);
  1217. AResult = PromptUser(Data, Kind, Name, Instructions, Prompts, Results);
  1218. Result = Results->Strings[0];
  1219. }
  1220. __finally
  1221. {
  1222. delete Prompts;
  1223. delete Results;
  1224. }
  1225. return AResult;
  1226. }
  1227. //---------------------------------------------------------------------------
  1228. bool __fastcall TTerminal::PromptUser(TSessionData * Data, TPromptKind Kind,
  1229. UnicodeString Name, UnicodeString Instructions, TStrings * Prompts, TStrings * Results)
  1230. {
  1231. // If PromptUser is overridden in descendant class, the overridden version
  1232. // is not called when accessed via TSessionIU interface.
  1233. // So this is workaround.
  1234. // Actually no longer needed as we do not uverride DoPromptUser
  1235. // anymore in TSecondaryTerminal.
  1236. return DoPromptUser(Data, Kind, Name, Instructions, Prompts, Results);
  1237. }
  1238. //---------------------------------------------------------------------------
  1239. TTerminal * __fastcall TTerminal::GetPasswordSource()
  1240. {
  1241. return this;
  1242. }
  1243. //---------------------------------------------------------------------------
  1244. bool __fastcall TTerminal::DoPromptUser(TSessionData * /*Data*/, TPromptKind Kind,
  1245. UnicodeString Name, UnicodeString Instructions, TStrings * Prompts, TStrings * Results)
  1246. {
  1247. bool AResult = false;
  1248. bool PasswordOrPassphrasePrompt = IsPasswordOrPassphrasePrompt(Kind, Prompts);
  1249. if (PasswordOrPassphrasePrompt)
  1250. {
  1251. bool & PasswordTried =
  1252. FTunnelOpening ? FRememberedTunnelPasswordTried : FRememberedPasswordTried;
  1253. if (!PasswordTried)
  1254. {
  1255. // let's expect that the main session is already authenticated and its password
  1256. // is not written after, so no locking is necessary
  1257. // (no longer true, once the main session can be reconnected)
  1258. UnicodeString APassword;
  1259. if (FTunnelOpening)
  1260. {
  1261. APassword = GetPasswordSource()->RememberedTunnelPassword;
  1262. }
  1263. else
  1264. {
  1265. APassword = GetPasswordSource()->RememberedPassword;
  1266. }
  1267. Results->Strings[0] = APassword;
  1268. if (!Results->Strings[0].IsEmpty())
  1269. {
  1270. LogEvent(L"Using remembered password.");
  1271. AResult = true;
  1272. }
  1273. PasswordTried = true;
  1274. }
  1275. }
  1276. if (!AResult)
  1277. {
  1278. if (PasswordOrPassphrasePrompt && !Configuration->RememberPassword)
  1279. {
  1280. Prompts->Objects[0] = (TObject*)(int(Prompts->Objects[0]) | pupRemember);
  1281. }
  1282. if (OnPromptUser != NULL)
  1283. {
  1284. TCallbackGuard Guard(this);
  1285. OnPromptUser(this, Kind, Name, Instructions, Prompts, Results, AResult, NULL);
  1286. Guard.Verify();
  1287. }
  1288. if (AResult && PasswordOrPassphrasePrompt &&
  1289. (Configuration->RememberPassword || FLAGSET(int(Prompts->Objects[0]), pupRemember)))
  1290. {
  1291. RawByteString EncryptedPassword = EncryptPassword(Results->Strings[0]);
  1292. if (FTunnelOpening)
  1293. {
  1294. GetPasswordSource()->FRememberedTunnelPassword = EncryptedPassword;
  1295. }
  1296. else
  1297. {
  1298. GetPasswordSource()->FRememberedPassword = EncryptedPassword;
  1299. }
  1300. }
  1301. }
  1302. return AResult;
  1303. }
  1304. //---------------------------------------------------------------------------
  1305. unsigned int __fastcall TTerminal::QueryUser(const UnicodeString Query,
  1306. TStrings * MoreMessages, unsigned int Answers, const TQueryParams * Params,
  1307. TQueryType QueryType)
  1308. {
  1309. LogEvent(FORMAT(L"Asking user:\n%s (%s)", (Query, (MoreMessages ? MoreMessages->CommaText : UnicodeString() ))));
  1310. unsigned int Answer = AbortAnswer(Answers);
  1311. if (FOnQueryUser)
  1312. {
  1313. TCallbackGuard Guard(this);
  1314. FOnQueryUser(this, Query, MoreMessages, Answers, Params, Answer, QueryType, NULL);
  1315. Guard.Verify();
  1316. }
  1317. return Answer;
  1318. }
  1319. //---------------------------------------------------------------------------
  1320. unsigned int __fastcall TTerminal::QueryUserException(const UnicodeString Query,
  1321. Exception * E, unsigned int Answers, const TQueryParams * Params,
  1322. TQueryType QueryType)
  1323. {
  1324. unsigned int Result;
  1325. UnicodeString ExMessage;
  1326. if (DebugAlwaysTrue(ExceptionMessage(E, ExMessage) || !Query.IsEmpty()))
  1327. {
  1328. TStrings * MoreMessages = new TStringList();
  1329. try
  1330. {
  1331. if (!ExMessage.IsEmpty() && !Query.IsEmpty())
  1332. {
  1333. MoreMessages->Add(UnformatMessage(ExMessage));
  1334. }
  1335. ExtException * EE = dynamic_cast<ExtException*>(E);
  1336. if ((EE != NULL) && (EE->MoreMessages != NULL))
  1337. {
  1338. MoreMessages->AddStrings(EE->MoreMessages);
  1339. }
  1340. // We know MoreMessages not to be NULL here,
  1341. // AppendExceptionStackTraceAndForget should never return true
  1342. // (indicating it had to create the string list)
  1343. DebugAlwaysFalse(AppendExceptionStackTraceAndForget(MoreMessages));
  1344. TQueryParams HelpKeywordOverrideParams;
  1345. if (Params != NULL)
  1346. {
  1347. HelpKeywordOverrideParams.Assign(*Params);
  1348. }
  1349. HelpKeywordOverrideParams.HelpKeyword =
  1350. MergeHelpKeyword(HelpKeywordOverrideParams.HelpKeyword, GetExceptionHelpKeyword(E));
  1351. Result = QueryUser(!Query.IsEmpty() ? Query : ExMessage,
  1352. MoreMessages->Count ? MoreMessages : NULL,
  1353. Answers, &HelpKeywordOverrideParams, QueryType);
  1354. }
  1355. __finally
  1356. {
  1357. delete MoreMessages;
  1358. }
  1359. }
  1360. return Result;
  1361. }
  1362. //---------------------------------------------------------------------------
  1363. void __fastcall TTerminal::DisplayBanner(const UnicodeString & Banner)
  1364. {
  1365. if (OnDisplayBanner != NULL)
  1366. {
  1367. if (Configuration->ForceBanners ||
  1368. Configuration->ShowBanner(SessionData->SessionKey, Banner))
  1369. {
  1370. bool NeverShowAgain = false;
  1371. int Options =
  1372. FLAGMASK(Configuration->ForceBanners, boDisableNeverShowAgain);
  1373. TCallbackGuard Guard(this);
  1374. OnDisplayBanner(this, SessionData->SessionName, Banner,
  1375. NeverShowAgain, Options);
  1376. Guard.Verify();
  1377. if (!Configuration->ForceBanners && NeverShowAgain)
  1378. {
  1379. Configuration->NeverShowBanner(SessionData->SessionKey, Banner);
  1380. }
  1381. }
  1382. }
  1383. }
  1384. //---------------------------------------------------------------------------
  1385. void __fastcall TTerminal::HandleExtendedException(Exception * E)
  1386. {
  1387. Log->AddException(E);
  1388. if (OnShowExtendedException != NULL)
  1389. {
  1390. TCallbackGuard Guard(this);
  1391. // the event handler may destroy 'this' ...
  1392. OnShowExtendedException(this, E, NULL);
  1393. // .. hence guard is dismissed from destructor, to make following call no-op
  1394. Guard.Verify();
  1395. }
  1396. }
  1397. //---------------------------------------------------------------------------
  1398. void __fastcall TTerminal::ShowExtendedException(Exception * E)
  1399. {
  1400. Log->AddException(E);
  1401. if (OnShowExtendedException != NULL)
  1402. {
  1403. OnShowExtendedException(this, E, NULL);
  1404. }
  1405. }
  1406. //---------------------------------------------------------------------------
  1407. void __fastcall TTerminal::DoInformation(const UnicodeString & Str, bool Status,
  1408. int Phase)
  1409. {
  1410. if (OnInformation)
  1411. {
  1412. TCallbackGuard Guard(this);
  1413. OnInformation(this, Str, Status, Phase);
  1414. Guard.Verify();
  1415. }
  1416. }
  1417. //---------------------------------------------------------------------------
  1418. void __fastcall TTerminal::Information(const UnicodeString & Str, bool Status)
  1419. {
  1420. DoInformation(Str, Status);
  1421. }
  1422. //---------------------------------------------------------------------------
  1423. void __fastcall TTerminal::DoProgress(TFileOperationProgressType & ProgressData)
  1424. {
  1425. if (OnProgress != NULL)
  1426. {
  1427. TCallbackGuard Guard(this);
  1428. OnProgress(ProgressData);
  1429. Guard.Verify();
  1430. }
  1431. }
  1432. //---------------------------------------------------------------------------
  1433. void __fastcall TTerminal::DoFinished(TFileOperation Operation, TOperationSide Side, bool Temp,
  1434. const UnicodeString & FileName, bool Success, TOnceDoneOperation & OnceDoneOperation)
  1435. {
  1436. if (OnFinished != NULL)
  1437. {
  1438. TCallbackGuard Guard(this);
  1439. OnFinished(Operation, Side, Temp, FileName, Success, OnceDoneOperation);
  1440. Guard.Verify();
  1441. }
  1442. }
  1443. //---------------------------------------------------------------------------
  1444. void __fastcall TTerminal::SaveCapabilities(TFileSystemInfo & FileSystemInfo)
  1445. {
  1446. for (int Index = 0; Index < fcCount; Index++)
  1447. {
  1448. FileSystemInfo.IsCapable[Index] = IsCapable[(TFSCapability)Index];
  1449. }
  1450. }
  1451. //---------------------------------------------------------------------------
  1452. bool __fastcall TTerminal::GetIsCapable(TFSCapability Capability) const
  1453. {
  1454. DebugAssert(FFileSystem);
  1455. return FFileSystem->IsCapable(Capability);
  1456. }
  1457. //---------------------------------------------------------------------------
  1458. UnicodeString __fastcall TTerminal::AbsolutePath(UnicodeString Path, bool Local)
  1459. {
  1460. return FFileSystem->AbsolutePath(Path, Local);
  1461. }
  1462. //---------------------------------------------------------------------------
  1463. void __fastcall TTerminal::ReactOnCommand(int /*TFSCommand*/ Cmd)
  1464. {
  1465. bool ChangesDirectory = false;
  1466. bool ModifiesFiles = false;
  1467. switch ((TFSCommand)Cmd) {
  1468. case fsChangeDirectory:
  1469. case fsHomeDirectory:
  1470. ChangesDirectory = true;
  1471. break;
  1472. case fsCopyToRemote:
  1473. case fsDeleteFile:
  1474. case fsRenameFile:
  1475. case fsMoveFile:
  1476. case fsCopyFile:
  1477. case fsCreateDirectory:
  1478. case fsChangeMode:
  1479. case fsChangeGroup:
  1480. case fsChangeOwner:
  1481. case fsChangeProperties:
  1482. case fsLock:
  1483. ModifiesFiles = true;
  1484. break;
  1485. case fsAnyCommand:
  1486. ChangesDirectory = true;
  1487. ModifiesFiles = true;
  1488. break;
  1489. }
  1490. if (ChangesDirectory)
  1491. {
  1492. if (!InTransaction())
  1493. {
  1494. ReadCurrentDirectory();
  1495. if (AutoReadDirectory)
  1496. {
  1497. ReadDirectory(false);
  1498. }
  1499. }
  1500. else
  1501. {
  1502. FReadCurrentDirectoryPending = true;
  1503. if (AutoReadDirectory)
  1504. {
  1505. FReadDirectoryPending = true;
  1506. }
  1507. }
  1508. }
  1509. else if (ModifiesFiles && AutoReadDirectory && Configuration->AutoReadDirectoryAfterOp)
  1510. {
  1511. if (!InTransaction())
  1512. {
  1513. ReadDirectory(true);
  1514. }
  1515. else
  1516. {
  1517. FReadDirectoryPending = true;
  1518. }
  1519. }
  1520. }
  1521. //---------------------------------------------------------------------------
  1522. void __fastcall TTerminal::TerminalError(UnicodeString Msg)
  1523. {
  1524. TerminalError(NULL, Msg);
  1525. }
  1526. //---------------------------------------------------------------------------
  1527. void __fastcall TTerminal::TerminalError(
  1528. Exception * E, UnicodeString Msg, UnicodeString HelpKeyword)
  1529. {
  1530. throw ETerminal(E, Msg, HelpKeyword);
  1531. }
  1532. //---------------------------------------------------------------------------
  1533. bool __fastcall TTerminal::DoQueryReopen(Exception * E)
  1534. {
  1535. EFatal * Fatal = dynamic_cast<EFatal *>(E);
  1536. DebugAssert(Fatal != NULL);
  1537. bool Result;
  1538. if ((Fatal != NULL) && Fatal->ReopenQueried)
  1539. {
  1540. Result = false;
  1541. }
  1542. else
  1543. {
  1544. LogEvent(L"Connection was lost, asking what to do.");
  1545. TQueryParams Params(qpAllowContinueOnError);
  1546. Params.Timeout = Configuration->SessionReopenAuto;
  1547. Params.TimeoutAnswer = qaRetry;
  1548. TQueryButtonAlias Aliases[1];
  1549. Aliases[0].Button = qaRetry;
  1550. Aliases[0].Alias = LoadStr(RECONNECT_BUTTON);
  1551. Params.Aliases = Aliases;
  1552. Params.AliasesCount = LENOF(Aliases);
  1553. Result = (QueryUserException(L"", E, qaRetry | qaAbort, &Params, qtError) == qaRetry);
  1554. if (Fatal != NULL)
  1555. {
  1556. Fatal->ReopenQueried = true;
  1557. }
  1558. }
  1559. return Result;
  1560. }
  1561. //---------------------------------------------------------------------------
  1562. bool __fastcall TTerminal::QueryReopen(Exception * E, int Params,
  1563. TFileOperationProgressType * OperationProgress)
  1564. {
  1565. TSuspendFileOperationProgress Suspend(OperationProgress);
  1566. bool Result = DoQueryReopen(E);
  1567. if (Result)
  1568. {
  1569. TDateTime Start = Now();
  1570. do
  1571. {
  1572. try
  1573. {
  1574. Reopen(Params);
  1575. }
  1576. catch(Exception & E)
  1577. {
  1578. if (!Active)
  1579. {
  1580. Result =
  1581. ((Configuration->SessionReopenTimeout == 0) ||
  1582. (int(double(Now() - Start) * MSecsPerDay) < Configuration->SessionReopenTimeout)) &&
  1583. DoQueryReopen(&E);
  1584. }
  1585. else
  1586. {
  1587. throw;
  1588. }
  1589. }
  1590. }
  1591. while (!Active && Result);
  1592. }
  1593. return Result;
  1594. }
  1595. //---------------------------------------------------------------------------
  1596. bool __fastcall TTerminal::FileOperationLoopQuery(Exception & E,
  1597. TFileOperationProgressType * OperationProgress, const UnicodeString Message,
  1598. bool AllowSkip, UnicodeString SpecialRetry, UnicodeString HelpKeyword)
  1599. {
  1600. bool Result = false;
  1601. Log->AddException(&E);
  1602. unsigned int Answer;
  1603. bool SkipToAllPossible = AllowSkip && (OperationProgress != NULL);
  1604. if (SkipToAllPossible && OperationProgress->SkipToAll)
  1605. {
  1606. Answer = qaSkip;
  1607. }
  1608. else
  1609. {
  1610. int Answers = qaRetry | qaAbort |
  1611. FLAGMASK(AllowSkip, qaSkip) |
  1612. FLAGMASK(SkipToAllPossible, qaAll) |
  1613. FLAGMASK(!SpecialRetry.IsEmpty(), qaYes);
  1614. TQueryParams Params(qpAllowContinueOnError | FLAGMASK(!AllowSkip, qpFatalAbort));
  1615. Params.HelpKeyword = HelpKeyword;
  1616. TQueryButtonAlias Aliases[2];
  1617. int AliasCount = 0;
  1618. if (FLAGSET(Answers, qaAll))
  1619. {
  1620. Aliases[AliasCount].Button = qaAll;
  1621. Aliases[AliasCount].Alias = LoadStr(SKIP_ALL_BUTTON);
  1622. AliasCount++;
  1623. }
  1624. if (FLAGSET(Answers, qaYes))
  1625. {
  1626. Aliases[AliasCount].Button = qaYes;
  1627. Aliases[AliasCount].Alias = SpecialRetry;
  1628. AliasCount++;
  1629. }
  1630. if (AliasCount > 0)
  1631. {
  1632. Params.Aliases = Aliases;
  1633. Params.AliasesCount = AliasCount;
  1634. }
  1635. {
  1636. TSuspendFileOperationProgress Suspend(OperationProgress);
  1637. Answer = QueryUserException(Message, &E, Answers, &Params, qtError);
  1638. }
  1639. if (Answer == qaAll)
  1640. {
  1641. DebugAssert(OperationProgress != NULL);
  1642. OperationProgress->SkipToAll = true;
  1643. Answer = qaSkip;
  1644. }
  1645. if (Answer == qaYes)
  1646. {
  1647. Result = true;
  1648. Answer = qaRetry;
  1649. }
  1650. }
  1651. if (Answer != qaRetry)
  1652. {
  1653. if ((Answer == qaAbort) && (OperationProgress != NULL))
  1654. {
  1655. OperationProgress->Cancel = csCancel;
  1656. }
  1657. if (AllowSkip)
  1658. {
  1659. THROW_SKIP_FILE(&E, Message);
  1660. }
  1661. else
  1662. {
  1663. // this can happen only during file transfer with SCP
  1664. throw ExtException(&E, Message);
  1665. }
  1666. }
  1667. return Result;
  1668. }
  1669. //---------------------------------------------------------------------------
  1670. int __fastcall TTerminal::FileOperationLoop(TFileOperationEvent CallBackFunc,
  1671. TFileOperationProgressType * OperationProgress, bool AllowSkip,
  1672. const UnicodeString Message, void * Param1, void * Param2)
  1673. {
  1674. DebugAssert(CallBackFunc);
  1675. int Result;
  1676. FILE_OPERATION_LOOP_BEGIN
  1677. {
  1678. Result = CallBackFunc(Param1, Param2);
  1679. }
  1680. FILE_OPERATION_LOOP_END_EX(Message, AllowSkip);
  1681. return Result;
  1682. }
  1683. //---------------------------------------------------------------------------
  1684. UnicodeString __fastcall TTerminal::TranslateLockedPath(UnicodeString Path, bool Lock)
  1685. {
  1686. if (SessionData->LockInHome && !Path.IsEmpty() && (Path[1] == L'/'))
  1687. {
  1688. if (Lock)
  1689. {
  1690. if (Path.SubString(1, FLockDirectory.Length()) == FLockDirectory)
  1691. {
  1692. Path.Delete(1, FLockDirectory.Length());
  1693. if (Path.IsEmpty()) Path = L"/";
  1694. }
  1695. }
  1696. else
  1697. {
  1698. Path = UnixExcludeTrailingBackslash(FLockDirectory + Path);
  1699. }
  1700. }
  1701. return Path;
  1702. }
  1703. //---------------------------------------------------------------------------
  1704. void __fastcall TTerminal::ClearCaches()
  1705. {
  1706. FDirectoryCache->Clear();
  1707. if (FDirectoryChangesCache != NULL)
  1708. {
  1709. FDirectoryChangesCache->Clear();
  1710. }
  1711. if (FCommandSession != NULL)
  1712. {
  1713. FCommandSession->ClearCaches();
  1714. }
  1715. }
  1716. //---------------------------------------------------------------------------
  1717. void __fastcall TTerminal::ClearCachedFileList(const UnicodeString Path,
  1718. bool SubDirs)
  1719. {
  1720. FDirectoryCache->ClearFileList(Path, SubDirs);
  1721. }
  1722. //---------------------------------------------------------------------------
  1723. void __fastcall TTerminal::AddCachedFileList(TRemoteFileList * FileList)
  1724. {
  1725. FDirectoryCache->AddFileList(FileList);
  1726. }
  1727. //---------------------------------------------------------------------------
  1728. bool __fastcall TTerminal::DirectoryFileList(const UnicodeString Path,
  1729. TRemoteFileList *& FileList, bool CanLoad)
  1730. {
  1731. bool Result = false;
  1732. if (UnixSamePath(FFiles->Directory, Path))
  1733. {
  1734. Result = (FileList == NULL) || (FileList->Timestamp < FFiles->Timestamp);
  1735. if (Result)
  1736. {
  1737. if (FileList == NULL)
  1738. {
  1739. FileList = new TRemoteFileList();
  1740. }
  1741. FFiles->DuplicateTo(FileList);
  1742. }
  1743. }
  1744. else
  1745. {
  1746. if (((FileList == NULL) && FDirectoryCache->HasFileList(Path)) ||
  1747. ((FileList != NULL) && FDirectoryCache->HasNewerFileList(Path, FileList->Timestamp)))
  1748. {
  1749. bool Created = (FileList == NULL);
  1750. if (Created)
  1751. {
  1752. FileList = new TRemoteFileList();
  1753. }
  1754. Result = FDirectoryCache->GetFileList(Path, FileList);
  1755. if (!Result && Created)
  1756. {
  1757. SAFE_DESTROY(FileList);
  1758. }
  1759. }
  1760. // do not attempt to load file list if there is cached version,
  1761. // only absence of cached version indicates that we consider
  1762. // the directory content obsolete
  1763. else if (CanLoad && !FDirectoryCache->HasFileList(Path))
  1764. {
  1765. bool Created = (FileList == NULL);
  1766. if (Created)
  1767. {
  1768. FileList = new TRemoteFileList();
  1769. }
  1770. FileList->Directory = Path;
  1771. try
  1772. {
  1773. ReadDirectory(FileList);
  1774. Result = true;
  1775. }
  1776. catch(...)
  1777. {
  1778. if (Created)
  1779. {
  1780. SAFE_DESTROY(FileList);
  1781. }
  1782. throw;
  1783. }
  1784. }
  1785. }
  1786. return Result;
  1787. }
  1788. //---------------------------------------------------------------------------
  1789. void __fastcall TTerminal::SetCurrentDirectory(UnicodeString value)
  1790. {
  1791. DebugAssert(FFileSystem);
  1792. value = TranslateLockedPath(value, false);
  1793. if (value != FFileSystem->CurrentDirectory)
  1794. {
  1795. ChangeDirectory(value);
  1796. }
  1797. }
  1798. //---------------------------------------------------------------------------
  1799. UnicodeString __fastcall TTerminal::GetCurrentDirectory()
  1800. {
  1801. if (FFileSystem != NULL)
  1802. {
  1803. // there's occasional crash when assigning FFileSystem->CurrentDirectory
  1804. // to FCurrentDirectory, splitting the assignment to two statemets
  1805. // to locate the crash more closely
  1806. UnicodeString CurrentDirectory = FFileSystem->CurrentDirectory;
  1807. FCurrentDirectory = CurrentDirectory;
  1808. if (FCurrentDirectory.IsEmpty())
  1809. {
  1810. ReadCurrentDirectory();
  1811. }
  1812. }
  1813. UnicodeString Result = TranslateLockedPath(FCurrentDirectory, true);
  1814. return Result;
  1815. }
  1816. //---------------------------------------------------------------------------
  1817. UnicodeString __fastcall TTerminal::PeekCurrentDirectory()
  1818. {
  1819. if (FFileSystem)
  1820. {
  1821. FCurrentDirectory = FFileSystem->CurrentDirectory;
  1822. }
  1823. UnicodeString Result = TranslateLockedPath(FCurrentDirectory, true);
  1824. return Result;
  1825. }
  1826. //---------------------------------------------------------------------------
  1827. const TRemoteTokenList * __fastcall TTerminal::GetGroups()
  1828. {
  1829. DebugAssert(FFileSystem);
  1830. LookupUsersGroups();
  1831. return &FGroups;
  1832. }
  1833. //---------------------------------------------------------------------------
  1834. const TRemoteTokenList * __fastcall TTerminal::GetUsers()
  1835. {
  1836. DebugAssert(FFileSystem);
  1837. LookupUsersGroups();
  1838. return &FUsers;
  1839. }
  1840. //---------------------------------------------------------------------------
  1841. const TRemoteTokenList * __fastcall TTerminal::GetMembership()
  1842. {
  1843. DebugAssert(FFileSystem);
  1844. LookupUsersGroups();
  1845. return &FMembership;
  1846. }
  1847. //---------------------------------------------------------------------------
  1848. UnicodeString __fastcall TTerminal::GetUserName() const
  1849. {
  1850. // in future might also be implemented to detect username similar to GetUserGroups
  1851. DebugAssert(FFileSystem != NULL);
  1852. UnicodeString Result = FFileSystem->GetUserName();
  1853. // Is empty also when stored username was used
  1854. if (Result.IsEmpty())
  1855. {
  1856. Result = SessionData->UserNameExpanded;
  1857. }
  1858. return Result;
  1859. }
  1860. //---------------------------------------------------------------------------
  1861. bool __fastcall TTerminal::GetAreCachesEmpty() const
  1862. {
  1863. return FDirectoryCache->IsEmpty &&
  1864. ((FDirectoryChangesCache == NULL) || FDirectoryChangesCache->IsEmpty);
  1865. }
  1866. //---------------------------------------------------------------------------
  1867. void __fastcall TTerminal::DoInitializeLog()
  1868. {
  1869. if (FOnInitializeLog)
  1870. {
  1871. TCallbackGuard Guard(this);
  1872. FOnInitializeLog(this);
  1873. Guard.Verify();
  1874. }
  1875. }
  1876. //---------------------------------------------------------------------------
  1877. void __fastcall TTerminal::DoChangeDirectory()
  1878. {
  1879. if (FOnChangeDirectory)
  1880. {
  1881. TCallbackGuard Guard(this);
  1882. FOnChangeDirectory(this);
  1883. Guard.Verify();
  1884. }
  1885. }
  1886. //---------------------------------------------------------------------------
  1887. void __fastcall TTerminal::DoReadDirectory(bool ReloadOnly)
  1888. {
  1889. if (FOnReadDirectory)
  1890. {
  1891. TCallbackGuard Guard(this);
  1892. FOnReadDirectory(this, ReloadOnly);
  1893. Guard.Verify();
  1894. }
  1895. }
  1896. //---------------------------------------------------------------------------
  1897. void __fastcall TTerminal::DoStartReadDirectory()
  1898. {
  1899. if (FOnStartReadDirectory)
  1900. {
  1901. TCallbackGuard Guard(this);
  1902. FOnStartReadDirectory(this);
  1903. Guard.Verify();
  1904. }
  1905. }
  1906. //---------------------------------------------------------------------------
  1907. void __fastcall TTerminal::DoReadDirectoryProgress(int Progress, int ResolvedLinks, bool & Cancel)
  1908. {
  1909. if (FReadingCurrentDirectory && (FOnReadDirectoryProgress != NULL))
  1910. {
  1911. TCallbackGuard Guard(this);
  1912. FOnReadDirectoryProgress(this, Progress, ResolvedLinks, Cancel);
  1913. Guard.Verify();
  1914. }
  1915. if (FOnFindingFile != NULL)
  1916. {
  1917. TCallbackGuard Guard(this);
  1918. FOnFindingFile(this, L"", Cancel);
  1919. Guard.Verify();
  1920. }
  1921. }
  1922. //---------------------------------------------------------------------------
  1923. bool __fastcall TTerminal::InTransaction()
  1924. {
  1925. return (FInTransaction > 0) && !FSuspendTransaction;
  1926. }
  1927. //---------------------------------------------------------------------------
  1928. void __fastcall TTerminal::BeginTransaction()
  1929. {
  1930. if (FInTransaction == 0)
  1931. {
  1932. FReadCurrentDirectoryPending = false;
  1933. FReadDirectoryPending = false;
  1934. }
  1935. FInTransaction++;
  1936. if (FCommandSession != NULL)
  1937. {
  1938. FCommandSession->BeginTransaction();
  1939. }
  1940. }
  1941. //---------------------------------------------------------------------------
  1942. void __fastcall TTerminal::EndTransaction()
  1943. {
  1944. DoEndTransaction(false);
  1945. }
  1946. //---------------------------------------------------------------------------
  1947. void __fastcall TTerminal::DoEndTransaction(bool Inform)
  1948. {
  1949. if (FInTransaction == 0)
  1950. TerminalError(L"Can't end transaction, not in transaction");
  1951. DebugAssert(FInTransaction > 0);
  1952. FInTransaction--;
  1953. // it connection was closed due to fatal error during transaction, do nothing
  1954. if (Active)
  1955. {
  1956. if (FInTransaction == 0)
  1957. {
  1958. try
  1959. {
  1960. if (FReadCurrentDirectoryPending)
  1961. {
  1962. ReadCurrentDirectory();
  1963. }
  1964. if (FReadDirectoryPending)
  1965. {
  1966. if (Inform)
  1967. {
  1968. DoInformation(LoadStr(STATUS_OPEN_DIRECTORY), true);
  1969. }
  1970. ReadDirectory(!FReadCurrentDirectoryPending);
  1971. }
  1972. }
  1973. __finally
  1974. {
  1975. FReadCurrentDirectoryPending = false;
  1976. FReadDirectoryPending = false;
  1977. }
  1978. }
  1979. }
  1980. if (FCommandSession != NULL)
  1981. {
  1982. FCommandSession->EndTransaction();
  1983. }
  1984. }
  1985. //---------------------------------------------------------------------------
  1986. void __fastcall TTerminal::SetExceptionOnFail(bool value)
  1987. {
  1988. if (value)
  1989. {
  1990. FExceptionOnFail++;
  1991. }
  1992. else
  1993. {
  1994. if (FExceptionOnFail == 0)
  1995. throw Exception(L"ExceptionOnFail is already zero.");
  1996. FExceptionOnFail--;
  1997. }
  1998. if (FCommandSession != NULL)
  1999. {
  2000. FCommandSession->FExceptionOnFail = FExceptionOnFail;
  2001. }
  2002. }
  2003. //---------------------------------------------------------------------------
  2004. bool __fastcall TTerminal::GetExceptionOnFail() const
  2005. {
  2006. return (bool)(FExceptionOnFail > 0);
  2007. }
  2008. //---------------------------------------------------------------------------
  2009. void __fastcall TTerminal::FatalAbort()
  2010. {
  2011. FatalError(NULL, "");
  2012. }
  2013. //---------------------------------------------------------------------------
  2014. void __fastcall TTerminal::FatalError(Exception * E, UnicodeString Msg, UnicodeString HelpKeyword)
  2015. {
  2016. bool SecureShellActive = (FSecureShell != NULL) && FSecureShell->Active;
  2017. if (Active || SecureShellActive)
  2018. {
  2019. // We log this instead of exception handler, because Close() would
  2020. // probably cause exception handler to loose pointer to TShellLog()
  2021. LogEvent(L"Attempt to close connection due to fatal exception:");
  2022. Log->Add(llException, Msg);
  2023. Log->AddException(E);
  2024. if (Active)
  2025. {
  2026. Close();
  2027. }
  2028. // this may happen if failure of authentication of SSH, owned by terminal yet
  2029. // (because the protocol was not decided yet), is detected by us (not by putty).
  2030. // e.g. not verified host key
  2031. if (SecureShellActive)
  2032. {
  2033. FSecureShell->Close();
  2034. }
  2035. }
  2036. if (FCallbackGuard != NULL)
  2037. {
  2038. FCallbackGuard->FatalError(E, Msg, HelpKeyword);
  2039. }
  2040. else
  2041. {
  2042. throw ESshFatal(E, Msg, HelpKeyword);
  2043. }
  2044. }
  2045. //---------------------------------------------------------------------------
  2046. void __fastcall TTerminal::CommandError(Exception * E, const UnicodeString Msg)
  2047. {
  2048. CommandError(E, Msg, 0);
  2049. }
  2050. //---------------------------------------------------------------------------
  2051. unsigned int __fastcall TTerminal::CommandError(Exception * E, const UnicodeString Msg,
  2052. unsigned int Answers, const UnicodeString HelpKeyword)
  2053. {
  2054. // may not be, particularly when TTerminal::Reopen is being called
  2055. // from within OnShowExtendedException handler
  2056. DebugAssert(FCallbackGuard == NULL);
  2057. unsigned int Result = 0;
  2058. if (E && E->InheritsFrom(__classid(EFatal)))
  2059. {
  2060. FatalError(E, Msg, HelpKeyword);
  2061. }
  2062. else if (E && E->InheritsFrom(__classid(EAbort)))
  2063. {
  2064. // resent EAbort exception
  2065. Abort();
  2066. }
  2067. else if (ExceptionOnFail)
  2068. {
  2069. throw ECommand(E, Msg, HelpKeyword);
  2070. }
  2071. else if (!Answers)
  2072. {
  2073. ECommand * ECmd = new ECommand(E, Msg, HelpKeyword);
  2074. try
  2075. {
  2076. HandleExtendedException(ECmd);
  2077. }
  2078. __finally
  2079. {
  2080. delete ECmd;
  2081. }
  2082. }
  2083. else
  2084. {
  2085. // small hack to enable "skip to all" for TRetryOperationLoop
  2086. bool CanSkip = FLAGSET(Answers, qaSkip) && (OperationProgress != NULL);
  2087. if (CanSkip && OperationProgress->SkipToAll)
  2088. {
  2089. Result = qaSkip;
  2090. }
  2091. else
  2092. {
  2093. TQueryParams Params(qpAllowContinueOnError, HelpKeyword);
  2094. TQueryButtonAlias Aliases[1];
  2095. if (CanSkip)
  2096. {
  2097. Aliases[0].Button = qaAll;
  2098. Aliases[0].Alias = LoadStr(SKIP_ALL_BUTTON);
  2099. Params.Aliases = Aliases;
  2100. Params.AliasesCount = LENOF(Aliases);
  2101. Answers |= qaAll;
  2102. }
  2103. Result = QueryUserException(Msg, E, Answers, &Params, qtError);
  2104. if (Result == qaAll)
  2105. {
  2106. DebugAssert(OperationProgress != NULL);
  2107. OperationProgress->SkipToAll = true;
  2108. Result = qaSkip;
  2109. }
  2110. }
  2111. }
  2112. return Result;
  2113. }
  2114. //---------------------------------------------------------------------------
  2115. bool __fastcall TTerminal::HandleException(Exception * E)
  2116. {
  2117. if (ExceptionOnFail)
  2118. {
  2119. return false;
  2120. }
  2121. else
  2122. {
  2123. Log->AddException(E);
  2124. return true;
  2125. }
  2126. }
  2127. //---------------------------------------------------------------------------
  2128. void __fastcall TTerminal::CloseOnCompletion(TOnceDoneOperation Operation, const UnicodeString Message)
  2129. {
  2130. Configuration->Usage->Inc(L"ClosesOnCompletion");
  2131. LogEvent(L"Closing session after completed operation (as requested by user)");
  2132. Close();
  2133. throw ESshTerminate(NULL,
  2134. Message.IsEmpty() ? UnicodeString(LoadStr(CLOSED_ON_COMPLETION)) : Message,
  2135. Operation);
  2136. }
  2137. //---------------------------------------------------------------------------
  2138. TBatchOverwrite __fastcall TTerminal::EffectiveBatchOverwrite(
  2139. const UnicodeString & SourceFullFileName, const TCopyParamType * CopyParam, int Params, TFileOperationProgressType * OperationProgress, bool Special)
  2140. {
  2141. TBatchOverwrite Result;
  2142. if (Special &&
  2143. (FLAGSET(Params, cpResume) || CopyParam->ResumeTransfer(SourceFullFileName)))
  2144. {
  2145. Result = boResume;
  2146. }
  2147. else if (FLAGSET(Params, cpAppend))
  2148. {
  2149. Result = boAppend;
  2150. }
  2151. else if (CopyParam->NewerOnly &&
  2152. (((OperationProgress->Side == osLocal) && IsCapable[fcNewerOnlyUpload]) ||
  2153. (OperationProgress->Side != osLocal)))
  2154. {
  2155. // no way to change batch overwrite mode when CopyParam->NewerOnly is on
  2156. Result = boOlder;
  2157. }
  2158. else if (FLAGSET(Params, cpNoConfirmation) || !Configuration->ConfirmOverwriting)
  2159. {
  2160. // no way to change batch overwrite mode when overwrite confirmations are off
  2161. DebugAssert(OperationProgress->BatchOverwrite == boNo);
  2162. Result = boAll;
  2163. }
  2164. else
  2165. {
  2166. Result = OperationProgress->BatchOverwrite;
  2167. if (!Special &&
  2168. ((Result == boOlder) || (Result == boAlternateResume) || (Result == boResume)))
  2169. {
  2170. Result = boNo;
  2171. }
  2172. }
  2173. return Result;
  2174. }
  2175. //---------------------------------------------------------------------------
  2176. bool __fastcall TTerminal::CheckRemoteFile(
  2177. const UnicodeString & FileName, const TCopyParamType * CopyParam, int Params, TFileOperationProgressType * OperationProgress)
  2178. {
  2179. return (EffectiveBatchOverwrite(FileName, CopyParam, Params, OperationProgress, true) != boAll);
  2180. }
  2181. //---------------------------------------------------------------------------
  2182. unsigned int __fastcall TTerminal::ConfirmFileOverwrite(
  2183. const UnicodeString & SourceFullFileName, const UnicodeString & TargetFileName,
  2184. const TOverwriteFileParams * FileParams, unsigned int Answers, TQueryParams * QueryParams,
  2185. TOperationSide Side, const TCopyParamType * CopyParam, int Params, TFileOperationProgressType * OperationProgress,
  2186. UnicodeString Message)
  2187. {
  2188. unsigned int Result;
  2189. // duplicated in TSFTPFileSystem::SFTPConfirmOverwrite
  2190. bool CanAlternateResume =
  2191. (FileParams != NULL) &&
  2192. (FileParams->DestSize < FileParams->SourceSize) &&
  2193. !OperationProgress->AsciiTransfer;
  2194. TBatchOverwrite BatchOverwrite = EffectiveBatchOverwrite(SourceFullFileName, CopyParam, Params, OperationProgress, true);
  2195. bool Applicable = true;
  2196. switch (BatchOverwrite)
  2197. {
  2198. case boOlder:
  2199. Applicable = (FileParams != NULL);
  2200. break;
  2201. case boAlternateResume:
  2202. Applicable = CanAlternateResume;
  2203. break;
  2204. case boResume:
  2205. Applicable = CanAlternateResume;
  2206. break;
  2207. }
  2208. if (!Applicable)
  2209. {
  2210. TBatchOverwrite ABatchOverwrite = EffectiveBatchOverwrite(SourceFullFileName, CopyParam, Params, OperationProgress, false);
  2211. DebugAssert(BatchOverwrite != ABatchOverwrite);
  2212. BatchOverwrite = ABatchOverwrite;
  2213. }
  2214. if (BatchOverwrite == boNo)
  2215. {
  2216. if (Message.IsEmpty())
  2217. {
  2218. // Side refers to destination side here
  2219. Message = FMTLOAD((Side == osLocal ? LOCAL_FILE_OVERWRITE2 :
  2220. REMOTE_FILE_OVERWRITE2), (TargetFileName, TargetFileName));
  2221. }
  2222. if (FileParams != NULL)
  2223. {
  2224. Message = FMTLOAD(FILE_OVERWRITE_DETAILS, (Message,
  2225. FormatSize(FileParams->SourceSize),
  2226. UserModificationStr(FileParams->SourceTimestamp, FileParams->SourcePrecision),
  2227. FormatSize(FileParams->DestSize),
  2228. UserModificationStr(FileParams->DestTimestamp, FileParams->DestPrecision)));
  2229. }
  2230. if (DebugAlwaysTrue(QueryParams->HelpKeyword.IsEmpty()))
  2231. {
  2232. QueryParams->HelpKeyword = HELP_OVERWRITE;
  2233. }
  2234. Result = QueryUser(Message, NULL, Answers, QueryParams);
  2235. switch (Result)
  2236. {
  2237. case qaNeverAskAgain:
  2238. Configuration->ConfirmOverwriting = false;
  2239. Result = qaYes;
  2240. break;
  2241. case qaYesToAll:
  2242. BatchOverwrite = boAll;
  2243. break;
  2244. case qaAll:
  2245. BatchOverwrite = boOlder;
  2246. break;
  2247. case qaNoToAll:
  2248. BatchOverwrite = boNone;
  2249. break;
  2250. }
  2251. // we user has not selected another batch overwrite mode,
  2252. // keep the current one. note that we may get here even
  2253. // when batch overwrite was selected already, but it could not be applied
  2254. // to current transfer (see condition above)
  2255. if (BatchOverwrite != boNo)
  2256. {
  2257. OperationProgress->BatchOverwrite = BatchOverwrite;
  2258. }
  2259. }
  2260. if (BatchOverwrite != boNo)
  2261. {
  2262. switch (BatchOverwrite)
  2263. {
  2264. case boAll:
  2265. Result = qaYes;
  2266. break;
  2267. case boNone:
  2268. Result = qaNo;
  2269. break;
  2270. case boOlder:
  2271. if (FileParams == NULL)
  2272. {
  2273. Result = qaNo;
  2274. }
  2275. else
  2276. {
  2277. TModificationFmt Precision = LessDateTimePrecision(FileParams->SourcePrecision, FileParams->DestPrecision);
  2278. TDateTime ReducedSourceTimestamp =
  2279. ReduceDateTimePrecision(FileParams->SourceTimestamp, Precision);
  2280. TDateTime ReducedDestTimestamp =
  2281. ReduceDateTimePrecision(FileParams->DestTimestamp, Precision);
  2282. Result =
  2283. (CompareFileTime(ReducedSourceTimestamp, ReducedDestTimestamp) > 0) ?
  2284. qaYes : qaNo;
  2285. LogEvent(FORMAT(L"Source file timestamp is [%s], destination timestamp is [%s], will%s overwrite",
  2286. (StandardTimestamp(ReducedSourceTimestamp),
  2287. StandardTimestamp(ReducedDestTimestamp),
  2288. ((Result == qaYes) ? L"" : L" not"))));
  2289. }
  2290. break;
  2291. case boAlternateResume:
  2292. DebugAssert(CanAlternateResume);
  2293. Result = qaSkip; // ugh
  2294. break;
  2295. case boAppend:
  2296. Result = qaRetry;
  2297. break;
  2298. case boResume:
  2299. Result = qaRetry;
  2300. break;
  2301. }
  2302. }
  2303. return Result;
  2304. }
  2305. //---------------------------------------------------------------------------
  2306. void __fastcall TTerminal::FileModified(const TRemoteFile * File,
  2307. const UnicodeString FileName, bool ClearDirectoryChange)
  2308. {
  2309. UnicodeString ParentDirectory;
  2310. UnicodeString Directory;
  2311. if (SessionData->CacheDirectories || SessionData->CacheDirectoryChanges)
  2312. {
  2313. if ((File != NULL) && (File->Directory != NULL))
  2314. {
  2315. if (File->IsDirectory)
  2316. {
  2317. Directory = File->Directory->FullDirectory + File->FileName;
  2318. }
  2319. ParentDirectory = File->Directory->Directory;
  2320. }
  2321. else if (!FileName.IsEmpty())
  2322. {
  2323. ParentDirectory = UnixExtractFilePath(FileName);
  2324. if (ParentDirectory.IsEmpty())
  2325. {
  2326. ParentDirectory = CurrentDirectory;
  2327. }
  2328. // this case for scripting
  2329. if ((File != NULL) && File->IsDirectory)
  2330. {
  2331. Directory = UnixIncludeTrailingBackslash(ParentDirectory) +
  2332. UnixExtractFileName(File->FileName);
  2333. }
  2334. }
  2335. }
  2336. if (SessionData->CacheDirectories)
  2337. {
  2338. if (!Directory.IsEmpty())
  2339. {
  2340. DirectoryModified(Directory, true);
  2341. }
  2342. if (!ParentDirectory.IsEmpty())
  2343. {
  2344. DirectoryModified(ParentDirectory, false);
  2345. }
  2346. }
  2347. if (SessionData->CacheDirectoryChanges && ClearDirectoryChange)
  2348. {
  2349. if (!Directory.IsEmpty())
  2350. {
  2351. FDirectoryChangesCache->ClearDirectoryChange(Directory);
  2352. FDirectoryChangesCache->ClearDirectoryChangeTarget(Directory);
  2353. }
  2354. }
  2355. }
  2356. //---------------------------------------------------------------------------
  2357. void __fastcall TTerminal::DirectoryModified(const UnicodeString Path, bool SubDirs)
  2358. {
  2359. if (Path.IsEmpty())
  2360. {
  2361. ClearCachedFileList(CurrentDirectory, SubDirs);
  2362. }
  2363. else
  2364. {
  2365. ClearCachedFileList(Path, SubDirs);
  2366. }
  2367. }
  2368. //---------------------------------------------------------------------------
  2369. void __fastcall TTerminal::DirectoryLoaded(TRemoteFileList * FileList)
  2370. {
  2371. AddCachedFileList(FileList);
  2372. }
  2373. //---------------------------------------------------------------------------
  2374. void __fastcall TTerminal::ReloadDirectory()
  2375. {
  2376. if (SessionData->CacheDirectories)
  2377. {
  2378. DirectoryModified(CurrentDirectory, false);
  2379. }
  2380. if (SessionData->CacheDirectoryChanges)
  2381. {
  2382. DebugAssert(FDirectoryChangesCache != NULL);
  2383. FDirectoryChangesCache->ClearDirectoryChange(CurrentDirectory);
  2384. }
  2385. ReadCurrentDirectory();
  2386. FReadCurrentDirectoryPending = false;
  2387. ReadDirectory(true);
  2388. FReadDirectoryPending = false;
  2389. }
  2390. //---------------------------------------------------------------------------
  2391. void __fastcall TTerminal::RefreshDirectory()
  2392. {
  2393. if (!SessionData->CacheDirectories)
  2394. {
  2395. LogEvent(L"Not refreshing directory, caching is off.");
  2396. }
  2397. else if (FDirectoryCache->HasNewerFileList(CurrentDirectory, FFiles->Timestamp))
  2398. {
  2399. // Second parameter was added to allow (rather force) using the cache.
  2400. // Before, the directory was reloaded always, it seems useless,
  2401. // has it any reason?
  2402. ReadDirectory(true, true);
  2403. FReadDirectoryPending = false;
  2404. }
  2405. }
  2406. //---------------------------------------------------------------------------
  2407. void __fastcall TTerminal::EnsureNonExistence(const UnicodeString FileName)
  2408. {
  2409. // if filename doesn't contain path, we check for existence of file
  2410. if ((UnixExtractFileDir(FileName).IsEmpty()) &&
  2411. UnixSamePath(CurrentDirectory, FFiles->Directory))
  2412. {
  2413. TRemoteFile *File = FFiles->FindFile(FileName);
  2414. if (File)
  2415. {
  2416. if (File->IsDirectory) throw ECommand(NULL, FMTLOAD(RENAME_CREATE_DIR_EXISTS, (FileName)));
  2417. else throw ECommand(NULL, FMTLOAD(RENAME_CREATE_FILE_EXISTS, (FileName)));
  2418. }
  2419. }
  2420. }
  2421. //---------------------------------------------------------------------------
  2422. void __fastcall inline TTerminal::LogEvent(const UnicodeString & Str)
  2423. {
  2424. if (Log->Logging)
  2425. {
  2426. Log->Add(llMessage, Str);
  2427. }
  2428. }
  2429. //---------------------------------------------------------------------------
  2430. void __fastcall TTerminal::RollbackAction(TSessionAction & Action,
  2431. TFileOperationProgressType * OperationProgress, Exception * E)
  2432. {
  2433. // EScpSkipFile without "cancel" is file skip,
  2434. // and we do not want to record skipped actions.
  2435. // But EScpSkipFile with "cancel" is abort and we want to record that.
  2436. // Note that TSCPFileSystem modifies the logic of RollbackAction little bit.
  2437. if ((dynamic_cast<EScpSkipFile *>(E) != NULL) &&
  2438. ((OperationProgress == NULL) ||
  2439. (OperationProgress->Cancel == csContinue)))
  2440. {
  2441. Action.Cancel();
  2442. }
  2443. else
  2444. {
  2445. Action.Rollback(E);
  2446. }
  2447. }
  2448. //---------------------------------------------------------------------------
  2449. void __fastcall TTerminal::DoStartup()
  2450. {
  2451. LogEvent(L"Doing startup conversation with host.");
  2452. BeginTransaction();
  2453. try
  2454. {
  2455. DoInformation(LoadStr(STATUS_STARTUP), true);
  2456. // Make sure that directory would be loaded at last
  2457. FReadCurrentDirectoryPending = true;
  2458. FReadDirectoryPending = AutoReadDirectory;
  2459. FFileSystem->DoStartup();
  2460. LookupUsersGroups();
  2461. if (!SessionData->RemoteDirectory.IsEmpty())
  2462. {
  2463. ChangeDirectory(SessionData->RemoteDirectory);
  2464. }
  2465. }
  2466. __finally
  2467. {
  2468. DoEndTransaction(true);
  2469. }
  2470. LogEvent(L"Startup conversation with host finished.");
  2471. }
  2472. //---------------------------------------------------------------------------
  2473. void __fastcall TTerminal::ReadCurrentDirectory()
  2474. {
  2475. DebugAssert(FFileSystem);
  2476. try
  2477. {
  2478. // reset flag is case we are called externally (like from console dialog)
  2479. FReadCurrentDirectoryPending = false;
  2480. LogEvent(L"Getting current directory name.");
  2481. UnicodeString OldDirectory = FFileSystem->CurrentDirectory;
  2482. FFileSystem->ReadCurrentDirectory();
  2483. ReactOnCommand(fsCurrentDirectory);
  2484. if (SessionData->CacheDirectoryChanges)
  2485. {
  2486. DebugAssert(FDirectoryChangesCache != NULL);
  2487. if (!CurrentDirectory.IsEmpty() && !FLastDirectoryChange.IsEmpty() && (CurrentDirectory != OldDirectory))
  2488. {
  2489. FDirectoryChangesCache->AddDirectoryChange(OldDirectory,
  2490. FLastDirectoryChange, CurrentDirectory);
  2491. }
  2492. // not to broke the cache, if the next directory change would not
  2493. // be initialized by ChangeDirectory(), which sets it
  2494. // (HomeDirectory() particularly)
  2495. FLastDirectoryChange = L"";
  2496. }
  2497. if (OldDirectory.IsEmpty())
  2498. {
  2499. FLockDirectory = (SessionData->LockInHome ?
  2500. FFileSystem->CurrentDirectory : UnicodeString(L""));
  2501. }
  2502. if (OldDirectory != FFileSystem->CurrentDirectory) DoChangeDirectory();
  2503. }
  2504. catch (Exception &E)
  2505. {
  2506. CommandError(&E, LoadStr(READ_CURRENT_DIR_ERROR));
  2507. }
  2508. }
  2509. //---------------------------------------------------------------------------
  2510. void __fastcall TTerminal::ReadDirectory(bool ReloadOnly, bool ForceCache)
  2511. {
  2512. bool LoadedFromCache = false;
  2513. if (SessionData->CacheDirectories && FDirectoryCache->HasFileList(CurrentDirectory))
  2514. {
  2515. if (ReloadOnly && !ForceCache)
  2516. {
  2517. LogEvent(L"Cached directory not reloaded.");
  2518. }
  2519. else
  2520. {
  2521. DoStartReadDirectory();
  2522. try
  2523. {
  2524. LoadedFromCache = FDirectoryCache->GetFileList(CurrentDirectory, FFiles);
  2525. }
  2526. __finally
  2527. {
  2528. DoReadDirectory(ReloadOnly);
  2529. }
  2530. if (LoadedFromCache)
  2531. {
  2532. LogEvent(L"Directory content loaded from cache.");
  2533. }
  2534. else
  2535. {
  2536. LogEvent(L"Cached Directory content has been removed.");
  2537. }
  2538. }
  2539. }
  2540. if (!LoadedFromCache)
  2541. {
  2542. DoStartReadDirectory();
  2543. FReadingCurrentDirectory = true;
  2544. bool Cancel = false; // dummy
  2545. DoReadDirectoryProgress(0, 0, Cancel);
  2546. try
  2547. {
  2548. TRemoteDirectory * Files = new TRemoteDirectory(this, FFiles);
  2549. try
  2550. {
  2551. Files->Directory = CurrentDirectory;
  2552. CustomReadDirectory(Files);
  2553. }
  2554. __finally
  2555. {
  2556. DoReadDirectoryProgress(-1, 0, Cancel);
  2557. FReadingCurrentDirectory = false;
  2558. TRemoteDirectory * OldFiles = FFiles;
  2559. FFiles = Files;
  2560. try
  2561. {
  2562. DoReadDirectory(ReloadOnly);
  2563. }
  2564. __finally
  2565. {
  2566. // delete only after loading new files to dir view,
  2567. // not to destroy the file objects that the view holds
  2568. // (can be issue in multi threaded environment, such as when the
  2569. // terminal is reconnecting in the terminal thread)
  2570. delete OldFiles;
  2571. }
  2572. if (Active)
  2573. {
  2574. if (SessionData->CacheDirectories)
  2575. {
  2576. DirectoryLoaded(FFiles);
  2577. }
  2578. }
  2579. }
  2580. }
  2581. catch (Exception &E)
  2582. {
  2583. CommandError(&E, FmtLoadStr(LIST_DIR_ERROR, ARRAYOFCONST((FFiles->Directory))));
  2584. }
  2585. }
  2586. }
  2587. //---------------------------------------------------------------------------
  2588. void __fastcall TTerminal::LogRemoteFile(TRemoteFile * File)
  2589. {
  2590. // optimization
  2591. if (Log->Logging)
  2592. {
  2593. LogEvent(FORMAT(L"%s;%s;%d;%s;%d;%s;%s;%s;%d",
  2594. (File->FileName, File->Type, File->Size, StandardTimestamp(File->Modification), int(File->ModificationFmt),
  2595. File->Owner.LogText, File->Group.LogText, File->Rights->Text,
  2596. File->Attr)));
  2597. }
  2598. }
  2599. //---------------------------------------------------------------------------
  2600. UnicodeString __fastcall TTerminal::FormatFileDetailsForLog(const UnicodeString & FileName, TDateTime Modification, __int64 Size)
  2601. {
  2602. UnicodeString Result;
  2603. // optimization
  2604. if (Log->Logging)
  2605. {
  2606. Result = FORMAT(L"'%s' [%s] [%s]", (FileName, (Modification != TDateTime() ? StandardTimestamp(Modification) : UnicodeString(L"n/a")), IntToStr(Size)));
  2607. }
  2608. return Result;
  2609. }
  2610. //---------------------------------------------------------------------------
  2611. void __fastcall TTerminal::LogFileDetails(const UnicodeString & FileName, TDateTime Modification, __int64 Size)
  2612. {
  2613. // optimization
  2614. if (Log->Logging)
  2615. {
  2616. LogEvent(FORMAT("File: %s", (FormatFileDetailsForLog(FileName, Modification, Size))));
  2617. }
  2618. }
  2619. //---------------------------------------------------------------------------
  2620. void __fastcall TTerminal::LogFileDone(TFileOperationProgressType * OperationProgress)
  2621. {
  2622. // optimization
  2623. if (Log->Logging)
  2624. {
  2625. LogEvent(FORMAT("Transfer done: '%s' [%s]", (OperationProgress->FullFileName, IntToStr(OperationProgress->TransferedSize))));
  2626. }
  2627. }
  2628. //---------------------------------------------------------------------------
  2629. void __fastcall TTerminal::CustomReadDirectory(TRemoteFileList * FileList)
  2630. {
  2631. DebugAssert(FileList);
  2632. DebugAssert(FFileSystem);
  2633. TRobustOperationLoop RobustLoop(this, OperationProgress);
  2634. do
  2635. {
  2636. try
  2637. {
  2638. FFileSystem->ReadDirectory(FileList);
  2639. }
  2640. catch (Exception & E)
  2641. {
  2642. // Do not retry for initial listing of directory,
  2643. // we instead retry whole connection attempt,
  2644. // what would be done anyway (but Open is not ready for recursion).
  2645. if ((FOpening > 0) ||
  2646. !RobustLoop.TryReopen(E))
  2647. {
  2648. throw;
  2649. }
  2650. }
  2651. }
  2652. while (RobustLoop.Retry());
  2653. if (Log->Logging)
  2654. {
  2655. for (int Index = 0; Index < FileList->Count; Index++)
  2656. {
  2657. LogRemoteFile(FileList->Files[Index]);
  2658. }
  2659. }
  2660. ReactOnCommand(fsListDirectory);
  2661. }
  2662. //---------------------------------------------------------------------------
  2663. TRemoteFileList * __fastcall TTerminal::ReadDirectoryListing(UnicodeString Directory, const TFileMasks & Mask)
  2664. {
  2665. TRemoteFileList * FileList;
  2666. TRetryOperationLoop RetryLoop(this);
  2667. do
  2668. {
  2669. FileList = NULL;
  2670. TLsSessionAction Action(ActionLog, AbsolutePath(Directory, true));
  2671. try
  2672. {
  2673. FileList = DoReadDirectoryListing(Directory, false);
  2674. if (FileList != NULL)
  2675. {
  2676. int Index = 0;
  2677. while (Index < FileList->Count)
  2678. {
  2679. TRemoteFile * File = FileList->Files[Index];
  2680. TFileMasks::TParams Params;
  2681. Params.Size = File->Size;
  2682. Params.Modification = File->Modification;
  2683. // Have to use UnicodeString(), instead of L"", as with that
  2684. // overload with (UnicodeString, bool, bool, TParams*) wins
  2685. if (!Mask.Matches(File->FileName, false, UnicodeString(), &Params))
  2686. {
  2687. FileList->Delete(Index);
  2688. }
  2689. else
  2690. {
  2691. Index++;
  2692. }
  2693. }
  2694. Action.FileList(FileList);
  2695. }
  2696. }
  2697. catch(Exception & E)
  2698. {
  2699. RetryLoop.Error(E, Action);
  2700. }
  2701. }
  2702. while (RetryLoop.Retry());
  2703. return FileList;
  2704. }
  2705. //---------------------------------------------------------------------------
  2706. TRemoteFile * __fastcall TTerminal::ReadFileListing(UnicodeString Path)
  2707. {
  2708. TRemoteFile * File;
  2709. TRetryOperationLoop RetryLoop(this);
  2710. do
  2711. {
  2712. File = NULL;
  2713. TStatSessionAction Action(ActionLog, AbsolutePath(Path, true));
  2714. try
  2715. {
  2716. // reset caches
  2717. AnnounceFileListOperation();
  2718. ReadFile(Path, File);
  2719. Action.File(File);
  2720. }
  2721. catch(Exception & E)
  2722. {
  2723. RetryLoop.Error(E, Action);
  2724. }
  2725. }
  2726. while (RetryLoop.Retry());
  2727. return File;
  2728. }
  2729. //---------------------------------------------------------------------------
  2730. TRemoteFileList * __fastcall TTerminal::CustomReadDirectoryListing(UnicodeString Directory, bool UseCache)
  2731. {
  2732. TRemoteFileList * FileList = NULL;
  2733. TRetryOperationLoop RetryLoop(this);
  2734. do
  2735. {
  2736. try
  2737. {
  2738. FileList = DoReadDirectoryListing(Directory, UseCache);
  2739. }
  2740. catch(Exception & E)
  2741. {
  2742. RetryLoop.Error(E);
  2743. }
  2744. }
  2745. while (RetryLoop.Retry());
  2746. return FileList;
  2747. }
  2748. //---------------------------------------------------------------------------
  2749. TRemoteFileList * __fastcall TTerminal::DoReadDirectoryListing(UnicodeString Directory, bool UseCache)
  2750. {
  2751. TRemoteFileList * FileList = new TRemoteFileList();
  2752. try
  2753. {
  2754. bool Cache = UseCache && SessionData->CacheDirectories;
  2755. bool LoadedFromCache = Cache && FDirectoryCache->HasFileList(Directory);
  2756. if (LoadedFromCache)
  2757. {
  2758. LoadedFromCache = FDirectoryCache->GetFileList(Directory, FileList);
  2759. }
  2760. if (!LoadedFromCache)
  2761. {
  2762. FileList->Directory = Directory;
  2763. ExceptionOnFail = true;
  2764. try
  2765. {
  2766. ReadDirectory(FileList);
  2767. }
  2768. __finally
  2769. {
  2770. ExceptionOnFail = false;
  2771. }
  2772. if (Cache)
  2773. {
  2774. AddCachedFileList(FileList);
  2775. }
  2776. }
  2777. }
  2778. catch(...)
  2779. {
  2780. delete FileList;
  2781. throw;
  2782. }
  2783. return FileList;
  2784. }
  2785. //---------------------------------------------------------------------------
  2786. void __fastcall TTerminal::ProcessDirectory(const UnicodeString DirName,
  2787. TProcessFileEvent CallBackFunc, void * Param, bool UseCache, bool IgnoreErrors)
  2788. {
  2789. TRemoteFileList * FileList = NULL;
  2790. if (IgnoreErrors)
  2791. {
  2792. ExceptionOnFail = true;
  2793. try
  2794. {
  2795. try
  2796. {
  2797. FileList = CustomReadDirectoryListing(DirName, UseCache);
  2798. }
  2799. catch(...)
  2800. {
  2801. if (!Active)
  2802. {
  2803. throw;
  2804. }
  2805. }
  2806. }
  2807. __finally
  2808. {
  2809. ExceptionOnFail = false;
  2810. }
  2811. }
  2812. else
  2813. {
  2814. FileList = CustomReadDirectoryListing(DirName, UseCache);
  2815. }
  2816. // skip if directory listing fails and user selects "skip"
  2817. if (FileList)
  2818. {
  2819. try
  2820. {
  2821. UnicodeString Directory = UnixIncludeTrailingBackslash(DirName);
  2822. TRemoteFile * File;
  2823. for (int Index = 0; Index < FileList->Count; Index++)
  2824. {
  2825. File = FileList->Files[Index];
  2826. if (!File->IsParentDirectory && !File->IsThisDirectory)
  2827. {
  2828. CallBackFunc(Directory + File->FileName, File, Param);
  2829. // We should catch EScpSkipFile here as we do in ProcessFiles.
  2830. // Now we have to handle EScpSkipFile in every callback implementation.
  2831. }
  2832. }
  2833. }
  2834. __finally
  2835. {
  2836. delete FileList;
  2837. }
  2838. }
  2839. }
  2840. //---------------------------------------------------------------------------
  2841. void __fastcall TTerminal::ReadDirectory(TRemoteFileList * FileList)
  2842. {
  2843. try
  2844. {
  2845. CustomReadDirectory(FileList);
  2846. }
  2847. catch (Exception &E)
  2848. {
  2849. CommandError(&E, FmtLoadStr(LIST_DIR_ERROR, ARRAYOFCONST((FileList->Directory))));
  2850. }
  2851. }
  2852. //---------------------------------------------------------------------------
  2853. void __fastcall TTerminal::ReadSymlink(TRemoteFile * SymlinkFile,
  2854. TRemoteFile *& File)
  2855. {
  2856. DebugAssert(FFileSystem);
  2857. try
  2858. {
  2859. LogEvent(FORMAT(L"Reading symlink \"%s\".", (SymlinkFile->FileName)));
  2860. FFileSystem->ReadSymlink(SymlinkFile, File);
  2861. ReactOnCommand(fsReadSymlink);
  2862. }
  2863. catch (Exception &E)
  2864. {
  2865. CommandError(&E, FMTLOAD(READ_SYMLINK_ERROR, (SymlinkFile->FileName)));
  2866. }
  2867. }
  2868. //---------------------------------------------------------------------------
  2869. void __fastcall TTerminal::ReadFile(const UnicodeString FileName,
  2870. TRemoteFile *& File)
  2871. {
  2872. DebugAssert(FFileSystem);
  2873. File = NULL;
  2874. try
  2875. {
  2876. LogEvent(FORMAT(L"Listing file \"%s\".", (FileName)));
  2877. FFileSystem->ReadFile(FileName, File);
  2878. ReactOnCommand(fsListFile);
  2879. LogRemoteFile(File);
  2880. }
  2881. catch (Exception &E)
  2882. {
  2883. if (File) delete File;
  2884. File = NULL;
  2885. CommandError(&E, FMTLOAD(CANT_GET_ATTRS, (FileName)));
  2886. }
  2887. }
  2888. //---------------------------------------------------------------------------
  2889. bool __fastcall TTerminal::FileExists(const UnicodeString FileName, TRemoteFile ** AFile)
  2890. {
  2891. bool Result;
  2892. TRemoteFile * File = NULL;
  2893. try
  2894. {
  2895. ExceptionOnFail = true;
  2896. try
  2897. {
  2898. ReadFile(UnixExcludeTrailingBackslash(FileName), File);
  2899. }
  2900. __finally
  2901. {
  2902. ExceptionOnFail = false;
  2903. }
  2904. if (AFile != NULL)
  2905. {
  2906. *AFile = File;
  2907. }
  2908. else
  2909. {
  2910. delete File;
  2911. }
  2912. Result = true;
  2913. }
  2914. catch(...)
  2915. {
  2916. if (Active)
  2917. {
  2918. Result = false;
  2919. }
  2920. else
  2921. {
  2922. throw;
  2923. }
  2924. }
  2925. return Result;
  2926. }
  2927. //---------------------------------------------------------------------------
  2928. void __fastcall TTerminal::AnnounceFileListOperation()
  2929. {
  2930. FFileSystem->AnnounceFileListOperation();
  2931. }
  2932. //---------------------------------------------------------------------------
  2933. bool __fastcall TTerminal::ProcessFiles(TStrings * FileList,
  2934. TFileOperation Operation, TProcessFileEvent ProcessFile, void * Param,
  2935. TOperationSide Side, bool Ex)
  2936. {
  2937. DebugAssert(FFileSystem);
  2938. DebugAssert(FileList);
  2939. bool Result = false;
  2940. TOnceDoneOperation OnceDoneOperation = odoIdle;
  2941. try
  2942. {
  2943. TFileOperationProgressType Progress(&DoProgress, &DoFinished);
  2944. Progress.Start(Operation, Side, FileList->Count);
  2945. FOperationProgress = &Progress;
  2946. try
  2947. {
  2948. if (Side == osRemote)
  2949. {
  2950. BeginTransaction();
  2951. }
  2952. try
  2953. {
  2954. int Index = 0;
  2955. UnicodeString FileName;
  2956. bool Success;
  2957. while ((Index < FileList->Count) && (Progress.Cancel == csContinue))
  2958. {
  2959. FileName = FileList->Strings[Index];
  2960. try
  2961. {
  2962. try
  2963. {
  2964. Success = false;
  2965. if (!Ex)
  2966. {
  2967. ProcessFile(FileName, (TRemoteFile *)FileList->Objects[Index], Param);
  2968. }
  2969. else
  2970. {
  2971. // not used anymore
  2972. TProcessFileEventEx ProcessFileEx = (TProcessFileEventEx)ProcessFile;
  2973. ProcessFileEx(FileName, (TRemoteFile *)FileList->Objects[Index], Param, Index);
  2974. }
  2975. Success = true;
  2976. }
  2977. __finally
  2978. {
  2979. Progress.Finish(FileName, Success, OnceDoneOperation);
  2980. }
  2981. }
  2982. catch(EScpSkipFile & E)
  2983. {
  2984. TSuspendFileOperationProgress Suspend(OperationProgress);
  2985. if (!HandleException(&E))
  2986. {
  2987. throw;
  2988. }
  2989. }
  2990. Index++;
  2991. }
  2992. }
  2993. __finally
  2994. {
  2995. if (Side == osRemote)
  2996. {
  2997. EndTransaction();
  2998. }
  2999. }
  3000. if (Progress.Cancel == csContinue)
  3001. {
  3002. Result = true;
  3003. }
  3004. }
  3005. __finally
  3006. {
  3007. FOperationProgress = NULL;
  3008. Progress.Stop();
  3009. }
  3010. }
  3011. catch (...)
  3012. {
  3013. OnceDoneOperation = odoIdle;
  3014. // this was missing here. was it by purpose?
  3015. // without it any error message is lost
  3016. throw;
  3017. }
  3018. if (OnceDoneOperation != odoIdle)
  3019. {
  3020. CloseOnCompletion(OnceDoneOperation);
  3021. }
  3022. return Result;
  3023. }
  3024. //---------------------------------------------------------------------------
  3025. // not used anymore
  3026. bool __fastcall TTerminal::ProcessFilesEx(TStrings * FileList, TFileOperation Operation,
  3027. TProcessFileEventEx ProcessFile, void * Param, TOperationSide Side)
  3028. {
  3029. return ProcessFiles(FileList, Operation, TProcessFileEvent(ProcessFile),
  3030. Param, Side, true);
  3031. }
  3032. //---------------------------------------------------------------------------
  3033. TStrings * __fastcall TTerminal::GetFixedPaths()
  3034. {
  3035. DebugAssert(FFileSystem != NULL);
  3036. return FFileSystem->GetFixedPaths();
  3037. }
  3038. //---------------------------------------------------------------------------
  3039. bool __fastcall TTerminal::GetResolvingSymlinks()
  3040. {
  3041. return SessionData->ResolveSymlinks && IsCapable[fcResolveSymlink];
  3042. }
  3043. //---------------------------------------------------------------------------
  3044. TUsableCopyParamAttrs __fastcall TTerminal::UsableCopyParamAttrs(int Params)
  3045. {
  3046. TUsableCopyParamAttrs Result;
  3047. Result.General =
  3048. FLAGMASK(!IsCapable[fcTextMode], cpaNoTransferMode) |
  3049. FLAGMASK(!IsCapable[fcModeChanging], cpaNoRights) |
  3050. FLAGMASK(!IsCapable[fcModeChanging], cpaNoPreserveReadOnly) |
  3051. FLAGMASK(FLAGSET(Params, cpDelete), cpaNoClearArchive) |
  3052. FLAGMASK(!IsCapable[fcIgnorePermErrors], cpaNoIgnorePermErrors) |
  3053. // the following three are never supported for download,
  3054. // so when they are not suppored for upload too,
  3055. // set them in General flags, so that they do not get enabled on
  3056. // Synchronize dialog.
  3057. FLAGMASK(!IsCapable[fcModeChangingUpload], cpaNoRights) |
  3058. FLAGMASK(!IsCapable[fcRemoveCtrlZUpload], cpaNoRemoveCtrlZ) |
  3059. FLAGMASK(!IsCapable[fcRemoveBOMUpload], cpaNoRemoveBOM) |
  3060. FLAGMASK(!IsCapable[fcPreservingTimestampDirs], cpaNoPreserveTimeDirs) |
  3061. FLAGMASK(!IsCapable[fcResumeSupport], cpaNoResumeSupport);
  3062. Result.Download = Result.General | cpaNoClearArchive |
  3063. cpaNoIgnorePermErrors |
  3064. // May be already set in General flags, but it's unconditional here
  3065. cpaNoRights | cpaNoRemoveCtrlZ | cpaNoRemoveBOM;
  3066. Result.Upload = Result.General | cpaNoPreserveReadOnly |
  3067. FLAGMASK(!IsCapable[fcPreservingTimestampUpload], cpaNoPreserveTime);
  3068. return Result;
  3069. }
  3070. //---------------------------------------------------------------------------
  3071. bool __fastcall TTerminal::IsRecycledFile(UnicodeString FileName)
  3072. {
  3073. bool Result = !SessionData->RecycleBinPath.IsEmpty();
  3074. if (Result)
  3075. {
  3076. UnicodeString Path = UnixExtractFilePath(FileName);
  3077. if (Path.IsEmpty())
  3078. {
  3079. Path = CurrentDirectory;
  3080. }
  3081. Result = UnixSamePath(Path, SessionData->RecycleBinPath);
  3082. }
  3083. return Result;
  3084. }
  3085. //---------------------------------------------------------------------------
  3086. void __fastcall TTerminal::RecycleFile(UnicodeString FileName,
  3087. const TRemoteFile * File)
  3088. {
  3089. if (FileName.IsEmpty())
  3090. {
  3091. DebugAssert(File != NULL);
  3092. FileName = File->FileName;
  3093. }
  3094. if (!IsRecycledFile(FileName))
  3095. {
  3096. LogEvent(FORMAT(L"Moving file \"%s\" to remote recycle bin '%s'.",
  3097. (FileName, SessionData->RecycleBinPath)));
  3098. TMoveFileParams Params;
  3099. Params.Target = SessionData->RecycleBinPath;
  3100. Params.FileMask = FORMAT(L"*-%s.*", (FormatDateTime(L"yyyymmdd-hhnnss", Now())));
  3101. MoveFile(FileName, File, &Params);
  3102. }
  3103. }
  3104. //---------------------------------------------------------------------------
  3105. bool __fastcall TTerminal::TryStartOperationWithFile(
  3106. const UnicodeString & FileName, TFileOperation Operation1, TFileOperation Operation2)
  3107. {
  3108. bool Result = true;
  3109. if ((OperationProgress != NULL) &&
  3110. ((OperationProgress->Operation == Operation1) ||
  3111. ((Operation2 != foNone) && (OperationProgress->Operation == Operation2))))
  3112. {
  3113. if (OperationProgress->Cancel != csContinue)
  3114. {
  3115. Result = false;
  3116. }
  3117. else
  3118. {
  3119. OperationProgress->SetFile(FileName);
  3120. }
  3121. }
  3122. return Result;
  3123. }
  3124. //---------------------------------------------------------------------------
  3125. void __fastcall TTerminal::StartOperationWithFile(
  3126. const UnicodeString & FileName, TFileOperation Operation1, TFileOperation Operation2)
  3127. {
  3128. if (!TryStartOperationWithFile(FileName, Operation1, Operation2))
  3129. {
  3130. Abort();
  3131. }
  3132. }
  3133. //---------------------------------------------------------------------------
  3134. void __fastcall TTerminal::DeleteFile(UnicodeString FileName,
  3135. const TRemoteFile * File, void * AParams)
  3136. {
  3137. if (FileName.IsEmpty() && File)
  3138. {
  3139. FileName = File->FileName;
  3140. }
  3141. StartOperationWithFile(FileName, foDelete);
  3142. int Params = (AParams != NULL) ? *((int*)AParams) : 0;
  3143. bool Recycle =
  3144. FLAGCLEAR(Params, dfForceDelete) &&
  3145. (SessionData->DeleteToRecycleBin != FLAGSET(Params, dfAlternative)) &&
  3146. !SessionData->RecycleBinPath.IsEmpty();
  3147. if (Recycle && !IsRecycledFile(FileName))
  3148. {
  3149. RecycleFile(FileName, File);
  3150. }
  3151. else
  3152. {
  3153. LogEvent(FORMAT(L"Deleting file \"%s\".", (FileName)));
  3154. FileModified(File, FileName, true);
  3155. DoDeleteFile(FileName, File, Params);
  3156. ReactOnCommand(fsDeleteFile);
  3157. }
  3158. }
  3159. //---------------------------------------------------------------------------
  3160. void __fastcall TTerminal::DoDeleteFile(const UnicodeString FileName,
  3161. const TRemoteFile * File, int Params)
  3162. {
  3163. TRetryOperationLoop RetryLoop(this);
  3164. do
  3165. {
  3166. TRmSessionAction Action(ActionLog, AbsolutePath(FileName, true));
  3167. try
  3168. {
  3169. DebugAssert(FFileSystem);
  3170. // 'File' parameter: SFTPFileSystem needs to know if file is file or directory
  3171. FFileSystem->DeleteFile(FileName, File, Params, Action);
  3172. }
  3173. catch(Exception & E)
  3174. {
  3175. RetryLoop.Error(E, Action, FMTLOAD(DELETE_FILE_ERROR, (FileName)));
  3176. }
  3177. }
  3178. while (RetryLoop.Retry());
  3179. }
  3180. //---------------------------------------------------------------------------
  3181. bool __fastcall TTerminal::DeleteFiles(TStrings * FilesToDelete, int Params)
  3182. {
  3183. TValueRestorer<bool> UseBusyCursorRestorer(FUseBusyCursor);
  3184. FUseBusyCursor = false;
  3185. // TODO: avoid resolving symlinks while reading subdirectories.
  3186. // Resolving does not work anyway for relative symlinks in subdirectories
  3187. // (at least for SFTP).
  3188. return ProcessFiles(FilesToDelete, foDelete, DeleteFile, &Params);
  3189. }
  3190. //---------------------------------------------------------------------------
  3191. void __fastcall TTerminal::DeleteLocalFile(UnicodeString FileName,
  3192. const TRemoteFile * /*File*/, void * Params)
  3193. {
  3194. StartOperationWithFile(FileName, foDelete);
  3195. if (OnDeleteLocalFile == NULL)
  3196. {
  3197. RecursiveDeleteFileChecked(FileName, false);
  3198. }
  3199. else
  3200. {
  3201. OnDeleteLocalFile(FileName, FLAGSET(*((int*)Params), dfAlternative));
  3202. }
  3203. }
  3204. //---------------------------------------------------------------------------
  3205. bool __fastcall TTerminal::DeleteLocalFiles(TStrings * FileList, int Params)
  3206. {
  3207. return ProcessFiles(FileList, foDelete, DeleteLocalFile, &Params, osLocal);
  3208. }
  3209. //---------------------------------------------------------------------------
  3210. void __fastcall TTerminal::CustomCommandOnFile(UnicodeString FileName,
  3211. const TRemoteFile * File, void * AParams)
  3212. {
  3213. TCustomCommandParams * Params = ((TCustomCommandParams *)AParams);
  3214. if (FileName.IsEmpty() && File)
  3215. {
  3216. FileName = File->FileName;
  3217. }
  3218. StartOperationWithFile(FileName, foCustomCommand);
  3219. LogEvent(FORMAT(L"Executing custom command \"%s\" (%d) on file \"%s\".",
  3220. (Params->Command, Params->Params, FileName)));
  3221. FileModified(File, FileName);
  3222. DoCustomCommandOnFile(FileName, File, Params->Command, Params->Params,
  3223. Params->OutputEvent);
  3224. ReactOnCommand(fsAnyCommand);
  3225. }
  3226. //---------------------------------------------------------------------------
  3227. void __fastcall TTerminal::DoCustomCommandOnFile(UnicodeString FileName,
  3228. const TRemoteFile * File, UnicodeString Command, int Params,
  3229. TCaptureOutputEvent OutputEvent)
  3230. {
  3231. TRetryOperationLoop RetryLoop(this);
  3232. do
  3233. {
  3234. try
  3235. {
  3236. if (IsCapable[fcAnyCommand])
  3237. {
  3238. DebugAssert(FFileSystem);
  3239. DebugAssert(fcShellAnyCommand);
  3240. FFileSystem->CustomCommandOnFile(FileName, File, Command, Params, OutputEvent);
  3241. }
  3242. else
  3243. {
  3244. DebugAssert(CommandSessionOpened);
  3245. DebugAssert(FCommandSession->FSProtocol == cfsSCP);
  3246. LogEvent(L"Executing custom command on command session.");
  3247. if (FCommandSession->CurrentDirectory != CurrentDirectory)
  3248. {
  3249. FCommandSession->CurrentDirectory = CurrentDirectory;
  3250. // We are likely in transaction, so ReadCurrentDirectory won't get called
  3251. // until transaction ends. But we need to know CurrentDirectory to
  3252. // expand !/ pattern.
  3253. // Doing this only, when current directory of the main and secondary shell differs,
  3254. // what would be the case before the first file in transaction.
  3255. // Otherwise we would be reading pwd before every time as the
  3256. // CustomCommandOnFile on its own sets FReadCurrentDirectoryPending
  3257. if (FCommandSession->FReadCurrentDirectoryPending)
  3258. {
  3259. FCommandSession->ReadCurrentDirectory();
  3260. }
  3261. }
  3262. FCommandSession->FFileSystem->CustomCommandOnFile(FileName, File, Command,
  3263. Params, OutputEvent);
  3264. }
  3265. }
  3266. catch(Exception & E)
  3267. {
  3268. RetryLoop.Error(E, FMTLOAD(CUSTOM_COMMAND_ERROR, (Command, FileName)));
  3269. }
  3270. }
  3271. while (RetryLoop.Retry());
  3272. }
  3273. //---------------------------------------------------------------------------
  3274. void __fastcall TTerminal::CustomCommandOnFiles(UnicodeString Command,
  3275. int Params, TStrings * Files, TCaptureOutputEvent OutputEvent)
  3276. {
  3277. if (!TRemoteCustomCommand().IsFileListCommand(Command))
  3278. {
  3279. TCustomCommandParams AParams;
  3280. AParams.Command = Command;
  3281. AParams.Params = Params;
  3282. AParams.OutputEvent = OutputEvent;
  3283. ProcessFiles(Files, foCustomCommand, CustomCommandOnFile, &AParams);
  3284. }
  3285. else
  3286. {
  3287. UnicodeString FileList;
  3288. for (int i = 0; i < Files->Count; i++)
  3289. {
  3290. TRemoteFile * File = static_cast<TRemoteFile *>(Files->Objects[i]);
  3291. bool Dir = File->IsDirectory && CanRecurseToDirectory(File);
  3292. if (!Dir || FLAGSET(Params, ccApplyToDirectories))
  3293. {
  3294. if (!FileList.IsEmpty())
  3295. {
  3296. FileList += L" ";
  3297. }
  3298. FileList += L"\"" + ShellDelimitStr(Files->Strings[i], L'"') + L"\"";
  3299. }
  3300. }
  3301. TCustomCommandData Data(this);
  3302. UnicodeString Cmd =
  3303. TRemoteCustomCommand(Data, CurrentDirectory, L"", FileList).
  3304. Complete(Command, true);
  3305. DoAnyCommand(Cmd, OutputEvent, NULL);
  3306. }
  3307. }
  3308. //---------------------------------------------------------------------------
  3309. void __fastcall TTerminal::ChangeFileProperties(UnicodeString FileName,
  3310. const TRemoteFile * File, /*const TRemoteProperties*/ void * Properties)
  3311. {
  3312. TRemoteProperties * RProperties = (TRemoteProperties *)Properties;
  3313. DebugAssert(RProperties && !RProperties->Valid.Empty());
  3314. if (FileName.IsEmpty() && File)
  3315. {
  3316. FileName = File->FileName;
  3317. }
  3318. StartOperationWithFile(FileName, foSetProperties);
  3319. if (Log->Logging)
  3320. {
  3321. LogEvent(FORMAT(L"Changing properties of \"%s\" (%s)",
  3322. (FileName, BooleanToEngStr(RProperties->Recursive))));
  3323. if (RProperties->Valid.Contains(vpRights))
  3324. {
  3325. LogEvent(FORMAT(L" - mode: \"%s\"", (RProperties->Rights.ModeStr)));
  3326. }
  3327. if (RProperties->Valid.Contains(vpGroup))
  3328. {
  3329. LogEvent(FORMAT(L" - group: %s", (RProperties->Group.LogText)));
  3330. }
  3331. if (RProperties->Valid.Contains(vpOwner))
  3332. {
  3333. LogEvent(FORMAT(L" - owner: %s", (RProperties->Owner.LogText)));
  3334. }
  3335. if (RProperties->Valid.Contains(vpModification))
  3336. {
  3337. LogEvent(FORMAT(L" - modification: \"%s\"",
  3338. (FormatDateTime(L"dddddd tt",
  3339. UnixToDateTime(RProperties->Modification, SessionData->DSTMode)))));
  3340. }
  3341. if (RProperties->Valid.Contains(vpLastAccess))
  3342. {
  3343. LogEvent(FORMAT(L" - last access: \"%s\"",
  3344. (FormatDateTime(L"dddddd tt",
  3345. UnixToDateTime(RProperties->LastAccess, SessionData->DSTMode)))));
  3346. }
  3347. }
  3348. FileModified(File, FileName);
  3349. DoChangeFileProperties(FileName, File, RProperties);
  3350. ReactOnCommand(fsChangeProperties);
  3351. }
  3352. //---------------------------------------------------------------------------
  3353. void __fastcall TTerminal::DoChangeFileProperties(const UnicodeString FileName,
  3354. const TRemoteFile * File, const TRemoteProperties * Properties)
  3355. {
  3356. TRetryOperationLoop RetryLoop(this);
  3357. do
  3358. {
  3359. TChmodSessionAction Action(ActionLog, AbsolutePath(FileName, true));
  3360. try
  3361. {
  3362. DebugAssert(FFileSystem);
  3363. FFileSystem->ChangeFileProperties(FileName, File, Properties, Action);
  3364. }
  3365. catch(Exception & E)
  3366. {
  3367. RetryLoop.Error(E, Action, FMTLOAD(CHANGE_PROPERTIES_ERROR, (FileName)));
  3368. }
  3369. }
  3370. while (RetryLoop.Retry());
  3371. }
  3372. //---------------------------------------------------------------------------
  3373. void __fastcall TTerminal::ChangeFilesProperties(TStrings * FileList,
  3374. const TRemoteProperties * Properties)
  3375. {
  3376. TValueRestorer<bool> UseBusyCursorRestorer(FUseBusyCursor);
  3377. FUseBusyCursor = false;
  3378. AnnounceFileListOperation();
  3379. ProcessFiles(FileList, foSetProperties, ChangeFileProperties, (void *)Properties);
  3380. }
  3381. //---------------------------------------------------------------------------
  3382. bool __fastcall TTerminal::LoadFilesProperties(TStrings * FileList)
  3383. {
  3384. // see comment in TSFTPFileSystem::IsCapable
  3385. bool Result =
  3386. IsCapable[fcLoadingAdditionalProperties] &&
  3387. FFileSystem->LoadFilesProperties(FileList);
  3388. if (Result && SessionData->CacheDirectories &&
  3389. (FileList->Count > 0) &&
  3390. (dynamic_cast<TRemoteFile *>(FileList->Objects[0])->Directory == FFiles))
  3391. {
  3392. AddCachedFileList(FFiles);
  3393. }
  3394. return Result;
  3395. }
  3396. //---------------------------------------------------------------------------
  3397. void __fastcall TTerminal::CalculateFileSize(UnicodeString FileName,
  3398. const TRemoteFile * File, /*TCalculateSizeParams*/ void * Param)
  3399. {
  3400. DebugAssert(Param);
  3401. DebugAssert(File);
  3402. TCalculateSizeParams * AParams = static_cast<TCalculateSizeParams*>(Param);
  3403. if (FileName.IsEmpty())
  3404. {
  3405. FileName = File->FileName;
  3406. }
  3407. if (!TryStartOperationWithFile(FileName, foCalculateSize))
  3408. {
  3409. AParams->Result = false;
  3410. Abort();
  3411. }
  3412. bool AllowTransfer = (AParams->CopyParam == NULL);
  3413. if (!AllowTransfer)
  3414. {
  3415. TFileMasks::TParams MaskParams;
  3416. MaskParams.Size = File->Size;
  3417. MaskParams.Modification = File->Modification;
  3418. UnicodeString BaseFileName =
  3419. GetBaseFileName(UnixExcludeTrailingBackslash(File->FullFileName));
  3420. AllowTransfer = AParams->CopyParam->AllowTransfer(
  3421. BaseFileName, osRemote, File->IsDirectory, MaskParams);
  3422. }
  3423. if (AllowTransfer)
  3424. {
  3425. if (File->IsDirectory)
  3426. {
  3427. if (CanRecurseToDirectory(File))
  3428. {
  3429. if (!AParams->AllowDirs)
  3430. {
  3431. AParams->Result = false;
  3432. }
  3433. else
  3434. {
  3435. LogEvent(FORMAT(L"Getting size of directory \"%s\"", (FileName)));
  3436. // pass in full path so we get it back in file list for AllowTransfer() exclusion
  3437. DoCalculateDirectorySize(File->FullFileName, File, AParams);
  3438. }
  3439. }
  3440. if (AParams->Stats != NULL)
  3441. {
  3442. AParams->Stats->Directories++;
  3443. }
  3444. }
  3445. else
  3446. {
  3447. AParams->Size += File->Size;
  3448. if (AParams->Stats != NULL)
  3449. {
  3450. AParams->Stats->Files++;
  3451. }
  3452. }
  3453. if ((AParams->Stats != NULL) && File->IsSymLink)
  3454. {
  3455. AParams->Stats->SymLinks++;
  3456. }
  3457. }
  3458. }
  3459. //---------------------------------------------------------------------------
  3460. void __fastcall TTerminal::DoCalculateDirectorySize(const UnicodeString FileName,
  3461. const TRemoteFile * /*File*/, TCalculateSizeParams * Params)
  3462. {
  3463. TRetryOperationLoop RetryLoop(this);
  3464. do
  3465. {
  3466. try
  3467. {
  3468. ProcessDirectory(FileName, CalculateFileSize, Params);
  3469. }
  3470. catch(Exception & E)
  3471. {
  3472. if (!Active || ((Params->Params & csIgnoreErrors) == 0))
  3473. {
  3474. RetryLoop.Error(E, FMTLOAD(CALCULATE_SIZE_ERROR, (FileName)));
  3475. }
  3476. }
  3477. }
  3478. while (RetryLoop.Retry());
  3479. }
  3480. //---------------------------------------------------------------------------
  3481. bool __fastcall TTerminal::CalculateFilesSize(TStrings * FileList,
  3482. __int64 & Size, int Params, const TCopyParamType * CopyParam,
  3483. bool AllowDirs, TCalculateSizeStats * Stats)
  3484. {
  3485. // With FTP protocol, we may use DSIZ command from
  3486. // draft-peterson-streamlined-ftp-command-extensions-10
  3487. // Implemented by Serv-U FTP.
  3488. TValueRestorer<bool> UseBusyCursorRestorer(FUseBusyCursor);
  3489. FUseBusyCursor = false;
  3490. TCalculateSizeParams Param;
  3491. Param.Size = 0;
  3492. Param.Params = Params;
  3493. Param.CopyParam = CopyParam;
  3494. Param.Stats = Stats;
  3495. Param.AllowDirs = AllowDirs;
  3496. Param.Result = true;
  3497. ProcessFiles(FileList, foCalculateSize, CalculateFileSize, &Param);
  3498. Size = Param.Size;
  3499. return Param.Result;
  3500. }
  3501. //---------------------------------------------------------------------------
  3502. void __fastcall TTerminal::CalculateFilesChecksum(const UnicodeString & Alg,
  3503. TStrings * FileList, TStrings * Checksums,
  3504. TCalculatedChecksumEvent OnCalculatedChecksum)
  3505. {
  3506. FFileSystem->CalculateFilesChecksum(Alg, FileList, Checksums, OnCalculatedChecksum);
  3507. }
  3508. //---------------------------------------------------------------------------
  3509. void __fastcall TTerminal::RenameFile(const UnicodeString FileName,
  3510. const UnicodeString NewName)
  3511. {
  3512. LogEvent(FORMAT(L"Renaming file \"%s\" to \"%s\".", (FileName, NewName)));
  3513. DoRenameFile(FileName, NewName, false);
  3514. ReactOnCommand(fsRenameFile);
  3515. }
  3516. //---------------------------------------------------------------------------
  3517. void __fastcall TTerminal::RenameFile(const TRemoteFile * File,
  3518. const UnicodeString NewName, bool CheckExistence)
  3519. {
  3520. DebugAssert(File && File->Directory == FFiles);
  3521. bool Proceed = true;
  3522. // if filename doesn't contain path, we check for existence of file
  3523. if ((File->FileName != NewName) && CheckExistence &&
  3524. Configuration->ConfirmOverwriting &&
  3525. UnixSamePath(CurrentDirectory, FFiles->Directory))
  3526. {
  3527. TRemoteFile * DuplicateFile = FFiles->FindFile(NewName);
  3528. if (DuplicateFile)
  3529. {
  3530. UnicodeString QuestionFmt;
  3531. if (DuplicateFile->IsDirectory)
  3532. {
  3533. QuestionFmt = LoadStr(DIRECTORY_OVERWRITE);
  3534. }
  3535. else
  3536. {
  3537. QuestionFmt = LoadStr(FILE_OVERWRITE);
  3538. }
  3539. TQueryParams Params(qpNeverAskAgainCheck);
  3540. UnicodeString Question = MainInstructions(FORMAT(QuestionFmt, (NewName)));
  3541. unsigned int Result = QueryUser(Question, NULL,
  3542. qaYes | qaNo, &Params);
  3543. if (Result == qaNeverAskAgain)
  3544. {
  3545. Proceed = true;
  3546. Configuration->ConfirmOverwriting = false;
  3547. }
  3548. else
  3549. {
  3550. Proceed = (Result == qaYes);
  3551. }
  3552. }
  3553. }
  3554. if (Proceed)
  3555. {
  3556. FileModified(File, File->FileName);
  3557. RenameFile(File->FileName, NewName);
  3558. }
  3559. }
  3560. //---------------------------------------------------------------------------
  3561. void __fastcall TTerminal::DoRenameFile(const UnicodeString FileName,
  3562. const UnicodeString NewName, bool Move)
  3563. {
  3564. TRetryOperationLoop RetryLoop(this);
  3565. do
  3566. {
  3567. TMvSessionAction Action(ActionLog, AbsolutePath(FileName, true), AbsolutePath(NewName, true));
  3568. try
  3569. {
  3570. DebugAssert(FFileSystem);
  3571. FFileSystem->RenameFile(FileName, NewName);
  3572. }
  3573. catch(Exception & E)
  3574. {
  3575. UnicodeString Message = FMTLOAD(Move ? MOVE_FILE_ERROR : RENAME_FILE_ERROR, (FileName, NewName));
  3576. RetryLoop.Error(E, Action, Message);
  3577. }
  3578. }
  3579. while (RetryLoop.Retry());
  3580. }
  3581. //---------------------------------------------------------------------------
  3582. void __fastcall TTerminal::MoveFile(const UnicodeString FileName,
  3583. const TRemoteFile * File, /*const TMoveFileParams*/ void * Param)
  3584. {
  3585. StartOperationWithFile(FileName, foRemoteMove, foDelete);
  3586. DebugAssert(Param != NULL);
  3587. const TMoveFileParams & Params = *static_cast<const TMoveFileParams*>(Param);
  3588. UnicodeString NewName = UnixIncludeTrailingBackslash(Params.Target) +
  3589. MaskFileName(UnixExtractFileName(FileName), Params.FileMask);
  3590. LogEvent(FORMAT(L"Moving file \"%s\" to \"%s\".", (FileName, NewName)));
  3591. FileModified(File, FileName);
  3592. DoRenameFile(FileName, NewName, true);
  3593. ReactOnCommand(fsMoveFile);
  3594. }
  3595. //---------------------------------------------------------------------------
  3596. bool __fastcall TTerminal::MoveFiles(TStrings * FileList, const UnicodeString Target,
  3597. const UnicodeString FileMask)
  3598. {
  3599. TMoveFileParams Params;
  3600. Params.Target = Target;
  3601. Params.FileMask = FileMask;
  3602. DirectoryModified(Target, true);
  3603. bool Result;
  3604. BeginTransaction();
  3605. try
  3606. {
  3607. Result = ProcessFiles(FileList, foRemoteMove, MoveFile, &Params);
  3608. }
  3609. __finally
  3610. {
  3611. if (Active)
  3612. {
  3613. UnicodeString WithTrailing = UnixIncludeTrailingBackslash(CurrentDirectory);
  3614. bool PossiblyMoved = false;
  3615. // check if we was moving current directory.
  3616. // this is just optimization to avoid checking existence of current
  3617. // directory after each move operation.
  3618. for (int Index = 0; !PossiblyMoved && (Index < FileList->Count); Index++)
  3619. {
  3620. const TRemoteFile * File =
  3621. dynamic_cast<const TRemoteFile *>(FileList->Objects[Index]);
  3622. // File can be NULL, and filename may not be full path,
  3623. // but currently this is the only way we can move (at least in GUI)
  3624. // current directory
  3625. if ((File != NULL) &&
  3626. File->IsDirectory &&
  3627. ((CurrentDirectory.SubString(1, FileList->Strings[Index].Length()) == FileList->Strings[Index]) &&
  3628. ((FileList->Strings[Index].Length() == CurrentDirectory.Length()) ||
  3629. (CurrentDirectory[FileList->Strings[Index].Length() + 1] == L'/'))))
  3630. {
  3631. PossiblyMoved = true;
  3632. }
  3633. }
  3634. if (PossiblyMoved && !FileExists(CurrentDirectory))
  3635. {
  3636. UnicodeString NearestExisting = CurrentDirectory;
  3637. do
  3638. {
  3639. NearestExisting = UnixExtractFileDir(NearestExisting);
  3640. }
  3641. while (!IsUnixRootPath(NearestExisting) && !FileExists(NearestExisting));
  3642. ChangeDirectory(NearestExisting);
  3643. }
  3644. }
  3645. EndTransaction();
  3646. }
  3647. return Result;
  3648. }
  3649. //---------------------------------------------------------------------------
  3650. void __fastcall TTerminal::DoCopyFile(const UnicodeString FileName,
  3651. const UnicodeString NewName)
  3652. {
  3653. TRetryOperationLoop RetryLoop(this);
  3654. do
  3655. {
  3656. try
  3657. {
  3658. DebugAssert(FFileSystem);
  3659. if (IsCapable[fcRemoteCopy])
  3660. {
  3661. FFileSystem->CopyFile(FileName, NewName);
  3662. }
  3663. else
  3664. {
  3665. DebugAssert(CommandSessionOpened);
  3666. DebugAssert(FCommandSession->FSProtocol == cfsSCP);
  3667. LogEvent(L"Copying file on command session.");
  3668. FCommandSession->CurrentDirectory = CurrentDirectory;
  3669. FCommandSession->FFileSystem->CopyFile(FileName, NewName);
  3670. }
  3671. }
  3672. catch(Exception & E)
  3673. {
  3674. RetryLoop.Error(E, FMTLOAD(COPY_FILE_ERROR, (FileName, NewName)));
  3675. }
  3676. }
  3677. while (RetryLoop.Retry());
  3678. }
  3679. //---------------------------------------------------------------------------
  3680. void __fastcall TTerminal::CopyFile(const UnicodeString FileName,
  3681. const TRemoteFile * /*File*/, /*const TMoveFileParams*/ void * Param)
  3682. {
  3683. StartOperationWithFile(FileName, foRemoteCopy);
  3684. DebugAssert(Param != NULL);
  3685. const TMoveFileParams & Params = *static_cast<const TMoveFileParams*>(Param);
  3686. UnicodeString NewName = UnixIncludeTrailingBackslash(Params.Target) +
  3687. MaskFileName(UnixExtractFileName(FileName), Params.FileMask);
  3688. LogEvent(FORMAT(L"Copying file \"%s\" to \"%s\".", (FileName, NewName)));
  3689. DoCopyFile(FileName, NewName);
  3690. ReactOnCommand(fsCopyFile);
  3691. }
  3692. //---------------------------------------------------------------------------
  3693. bool __fastcall TTerminal::CopyFiles(TStrings * FileList, const UnicodeString Target,
  3694. const UnicodeString FileMask)
  3695. {
  3696. TMoveFileParams Params;
  3697. Params.Target = Target;
  3698. Params.FileMask = FileMask;
  3699. DirectoryModified(Target, true);
  3700. return ProcessFiles(FileList, foRemoteCopy, CopyFile, &Params);
  3701. }
  3702. //---------------------------------------------------------------------------
  3703. void __fastcall TTerminal::CreateDirectory(const UnicodeString DirName,
  3704. const TRemoteProperties * Properties)
  3705. {
  3706. DebugAssert(FFileSystem);
  3707. EnsureNonExistence(DirName);
  3708. FileModified(NULL, DirName);
  3709. LogEvent(FORMAT(L"Creating directory \"%s\".", (DirName)));
  3710. DoCreateDirectory(DirName);
  3711. if ((Properties != NULL) && !Properties->Valid.Empty())
  3712. {
  3713. DoChangeFileProperties(DirName, NULL, Properties);
  3714. }
  3715. ReactOnCommand(fsCreateDirectory);
  3716. }
  3717. //---------------------------------------------------------------------------
  3718. void __fastcall TTerminal::DoCreateDirectory(const UnicodeString DirName)
  3719. {
  3720. TRetryOperationLoop RetryLoop(this);
  3721. do
  3722. {
  3723. TMkdirSessionAction Action(ActionLog, AbsolutePath(DirName, true));
  3724. try
  3725. {
  3726. DebugAssert(FFileSystem);
  3727. FFileSystem->CreateDirectory(DirName);
  3728. }
  3729. catch(Exception & E)
  3730. {
  3731. RetryLoop.Error(E, Action, FMTLOAD(CREATE_DIR_ERROR, (DirName)));
  3732. }
  3733. }
  3734. while (RetryLoop.Retry());
  3735. }
  3736. //---------------------------------------------------------------------------
  3737. void __fastcall TTerminal::CreateLink(const UnicodeString FileName,
  3738. const UnicodeString PointTo, bool Symbolic)
  3739. {
  3740. DebugAssert(FFileSystem);
  3741. EnsureNonExistence(FileName);
  3742. if (SessionData->CacheDirectories)
  3743. {
  3744. DirectoryModified(CurrentDirectory, false);
  3745. }
  3746. LogEvent(FORMAT(L"Creating link \"%s\" to \"%s\" (symbolic: %s).",
  3747. (FileName, PointTo, BooleanToEngStr(Symbolic))));
  3748. DoCreateLink(FileName, PointTo, Symbolic);
  3749. ReactOnCommand(fsCreateDirectory);
  3750. }
  3751. //---------------------------------------------------------------------------
  3752. void __fastcall TTerminal::DoCreateLink(const UnicodeString FileName,
  3753. const UnicodeString PointTo, bool Symbolic)
  3754. {
  3755. TRetryOperationLoop RetryLoop(this);
  3756. do
  3757. {
  3758. try
  3759. {
  3760. DebugAssert(FFileSystem);
  3761. FFileSystem->CreateLink(FileName, PointTo, Symbolic);
  3762. }
  3763. catch(Exception & E)
  3764. {
  3765. RetryLoop.Error(E, FMTLOAD(CREATE_LINK_ERROR, (FileName)));
  3766. }
  3767. }
  3768. while (RetryLoop.Retry());
  3769. }
  3770. //---------------------------------------------------------------------------
  3771. void __fastcall TTerminal::HomeDirectory()
  3772. {
  3773. DebugAssert(FFileSystem);
  3774. try
  3775. {
  3776. LogEvent(L"Changing directory to home directory.");
  3777. FFileSystem->HomeDirectory();
  3778. ReactOnCommand(fsHomeDirectory);
  3779. }
  3780. catch (Exception &E)
  3781. {
  3782. CommandError(&E, LoadStr(CHANGE_HOMEDIR_ERROR));
  3783. }
  3784. }
  3785. //---------------------------------------------------------------------------
  3786. void __fastcall TTerminal::ChangeDirectory(const UnicodeString Directory)
  3787. {
  3788. DebugAssert(FFileSystem);
  3789. try
  3790. {
  3791. UnicodeString CachedDirectory;
  3792. DebugAssert(!SessionData->CacheDirectoryChanges || (FDirectoryChangesCache != NULL));
  3793. // never use directory change cache during startup, this ensures, we never
  3794. // end-up initially in non-existing directory
  3795. if ((Status == ssOpened) &&
  3796. SessionData->CacheDirectoryChanges &&
  3797. FDirectoryChangesCache->GetDirectoryChange(PeekCurrentDirectory(),
  3798. Directory, CachedDirectory))
  3799. {
  3800. LogEvent(FORMAT(L"Cached directory change via \"%s\" to \"%s\".",
  3801. (Directory, CachedDirectory)));
  3802. FFileSystem->CachedChangeDirectory(CachedDirectory);
  3803. }
  3804. else
  3805. {
  3806. LogEvent(FORMAT(L"Changing directory to \"%s\".", (Directory)));
  3807. FFileSystem->ChangeDirectory(Directory);
  3808. }
  3809. FLastDirectoryChange = Directory;
  3810. ReactOnCommand(fsChangeDirectory);
  3811. }
  3812. catch (Exception &E)
  3813. {
  3814. CommandError(&E, FMTLOAD(CHANGE_DIR_ERROR, (Directory)));
  3815. }
  3816. }
  3817. //---------------------------------------------------------------------------
  3818. void __fastcall TTerminal::LookupUsersGroups()
  3819. {
  3820. if (!FUsersGroupsLookedup && (SessionData->LookupUserGroups != asOff) &&
  3821. IsCapable[fcUserGroupListing])
  3822. {
  3823. DebugAssert(FFileSystem);
  3824. try
  3825. {
  3826. FUsersGroupsLookedup = true;
  3827. LogEvent(L"Looking up groups and users.");
  3828. FFileSystem->LookupUsersGroups();
  3829. ReactOnCommand(fsLookupUsersGroups);
  3830. if (Log->Logging)
  3831. {
  3832. FGroups.Log(this, L"groups");
  3833. FMembership.Log(this, L"membership");
  3834. FUsers.Log(this, L"users");
  3835. }
  3836. }
  3837. catch (Exception &E)
  3838. {
  3839. if (!Active || (SessionData->LookupUserGroups == asOn))
  3840. {
  3841. CommandError(&E, LoadStr(LOOKUP_GROUPS_ERROR));
  3842. }
  3843. }
  3844. }
  3845. }
  3846. //---------------------------------------------------------------------------
  3847. bool __fastcall TTerminal::AllowedAnyCommand(const UnicodeString Command)
  3848. {
  3849. return !Command.Trim().IsEmpty();
  3850. }
  3851. //---------------------------------------------------------------------------
  3852. bool __fastcall TTerminal::GetCommandSessionOpened()
  3853. {
  3854. // consider secondary terminal open in "ready" state only
  3855. // so we never do keepalives on it until it is completely initialized
  3856. return (FCommandSession != NULL) &&
  3857. (FCommandSession->Status == ssOpened);
  3858. }
  3859. //---------------------------------------------------------------------------
  3860. TTerminal * __fastcall TTerminal::GetCommandSession()
  3861. {
  3862. if ((FCommandSession != NULL) && !FCommandSession->Active)
  3863. {
  3864. SAFE_DESTROY(FCommandSession);
  3865. }
  3866. if (FCommandSession == NULL)
  3867. {
  3868. // transaction cannot be started yet to allow proper matching transaction
  3869. // levels between main and command session
  3870. DebugAssert(FInTransaction == 0);
  3871. try
  3872. {
  3873. FCommandSession = new TSecondaryTerminal(this, SessionData,
  3874. Configuration, L"Shell");
  3875. FCommandSession->AutoReadDirectory = false;
  3876. TSessionData * CommandSessionData = FCommandSession->FSessionData;
  3877. CommandSessionData->RemoteDirectory = CurrentDirectory;
  3878. CommandSessionData->FSProtocol = fsSCPonly;
  3879. CommandSessionData->ClearAliases = false;
  3880. CommandSessionData->UnsetNationalVars = false;
  3881. CommandSessionData->LookupUserGroups = asOff;
  3882. FCommandSession->FExceptionOnFail = FExceptionOnFail;
  3883. FCommandSession->OnQueryUser = OnQueryUser;
  3884. FCommandSession->OnPromptUser = OnPromptUser;
  3885. FCommandSession->OnShowExtendedException = OnShowExtendedException;
  3886. FCommandSession->OnProgress = OnProgress;
  3887. FCommandSession->OnFinished = OnFinished;
  3888. FCommandSession->OnInformation = OnInformation;
  3889. FCommandSession->OnClose = CommandSessionClose;
  3890. // do not copy OnDisplayBanner to avoid it being displayed
  3891. }
  3892. catch(...)
  3893. {
  3894. SAFE_DESTROY(FCommandSession);
  3895. throw;
  3896. }
  3897. }
  3898. return FCommandSession;
  3899. }
  3900. //---------------------------------------------------------------------------
  3901. void __fastcall TTerminal::CommandSessionClose(TObject * /*Sender*/)
  3902. {
  3903. // Keep the states in sync.
  3904. // This is particularly to invoke ours OnClose,
  3905. // So that it is triggered before Reopen is called
  3906. Close();
  3907. }
  3908. //---------------------------------------------------------------------------
  3909. void __fastcall TTerminal::AnyCommand(const UnicodeString Command,
  3910. TCaptureOutputEvent OutputEvent)
  3911. {
  3912. #pragma warn -inl
  3913. class TOutputProxy
  3914. {
  3915. public:
  3916. __fastcall TOutputProxy(TCallSessionAction & Action, TCaptureOutputEvent OutputEvent) :
  3917. FAction(Action),
  3918. FOutputEvent(OutputEvent)
  3919. {
  3920. }
  3921. void __fastcall Output(const UnicodeString & Str, TCaptureOutputType OutputType)
  3922. {
  3923. switch (OutputType)
  3924. {
  3925. case cotOutput:
  3926. FAction.AddOutput(Str, false);
  3927. break;
  3928. case cotError:
  3929. FAction.AddOutput(Str, true);
  3930. break;
  3931. case cotExitCode:
  3932. FAction.ExitCode(StrToInt(Str));
  3933. break;
  3934. }
  3935. if (FOutputEvent != NULL)
  3936. {
  3937. FOutputEvent(Str, OutputType);
  3938. }
  3939. }
  3940. private:
  3941. TCallSessionAction & FAction;
  3942. TCaptureOutputEvent FOutputEvent;
  3943. };
  3944. #pragma warn .inl
  3945. TCallSessionAction Action(ActionLog, Command, CurrentDirectory);
  3946. TOutputProxy ProxyOutputEvent(Action, OutputEvent);
  3947. DoAnyCommand(Command, ProxyOutputEvent.Output, &Action);
  3948. }
  3949. //---------------------------------------------------------------------------
  3950. void __fastcall TTerminal::DoAnyCommand(const UnicodeString Command,
  3951. TCaptureOutputEvent OutputEvent, TCallSessionAction * Action)
  3952. {
  3953. DebugAssert(FFileSystem);
  3954. try
  3955. {
  3956. DirectoryModified(CurrentDirectory, false);
  3957. if (IsCapable[fcAnyCommand])
  3958. {
  3959. LogEvent(L"Executing user defined command.");
  3960. FFileSystem->AnyCommand(Command, OutputEvent);
  3961. }
  3962. else
  3963. {
  3964. DebugAssert(CommandSessionOpened);
  3965. DebugAssert(FCommandSession->FSProtocol == cfsSCP);
  3966. LogEvent(L"Executing user defined command on command session.");
  3967. FCommandSession->CurrentDirectory = CurrentDirectory;
  3968. FCommandSession->FFileSystem->AnyCommand(Command, OutputEvent);
  3969. FCommandSession->FFileSystem->ReadCurrentDirectory();
  3970. // synchronize pwd (by purpose we lose transaction optimization here)
  3971. ChangeDirectory(FCommandSession->CurrentDirectory);
  3972. }
  3973. ReactOnCommand(fsAnyCommand);
  3974. }
  3975. catch (Exception &E)
  3976. {
  3977. if (Action != NULL)
  3978. {
  3979. RollbackAction(*Action, NULL, &E);
  3980. }
  3981. if (ExceptionOnFail || (E.InheritsFrom(__classid(EFatal)))) throw;
  3982. else HandleExtendedException(&E);
  3983. }
  3984. }
  3985. //---------------------------------------------------------------------------
  3986. bool __fastcall TTerminal::DoCreateLocalFile(const UnicodeString FileName,
  3987. TFileOperationProgressType * OperationProgress, HANDLE * AHandle,
  3988. bool NoConfirmation)
  3989. {
  3990. bool Result = true;
  3991. bool Done;
  3992. unsigned int CreateAttr = FILE_ATTRIBUTE_NORMAL;
  3993. do
  3994. {
  3995. *AHandle = CreateFile(ApiPath(FileName).c_str(), GENERIC_WRITE, FILE_SHARE_READ,
  3996. NULL, CREATE_ALWAYS, CreateAttr, 0);
  3997. Done = (*AHandle != INVALID_HANDLE_VALUE);
  3998. if (!Done)
  3999. {
  4000. // save the error, otherwise it gets overwritten by call to FileExists
  4001. int LastError = GetLastError();
  4002. int FileAttr;
  4003. if (::FileExists(ApiPath(FileName)) &&
  4004. (((FileAttr = FileGetAttrFix(ApiPath(FileName))) & (faReadOnly | faHidden)) != 0))
  4005. {
  4006. if (FLAGSET(FileAttr, faReadOnly))
  4007. {
  4008. if (OperationProgress->BatchOverwrite == boNone)
  4009. {
  4010. Result = false;
  4011. }
  4012. else if ((OperationProgress->BatchOverwrite != boAll) && !NoConfirmation)
  4013. {
  4014. unsigned int Answer;
  4015. {
  4016. TSuspendFileOperationProgress Suspend(OperationProgress);
  4017. Answer = QueryUser(
  4018. MainInstructions(FMTLOAD(READ_ONLY_OVERWRITE, (FileName))), NULL,
  4019. qaYes | qaNo | qaCancel | qaYesToAll | qaNoToAll, 0);
  4020. }
  4021. switch (Answer) {
  4022. case qaYesToAll: OperationProgress->BatchOverwrite = boAll; break;
  4023. case qaCancel: OperationProgress->Cancel = csCancel; // continue on next case
  4024. case qaNoToAll: OperationProgress->BatchOverwrite = boNone;
  4025. case qaNo: Result = false; break;
  4026. }
  4027. }
  4028. }
  4029. else
  4030. {
  4031. DebugAssert(FLAGSET(FileAttr, faHidden));
  4032. Result = true;
  4033. }
  4034. if (Result)
  4035. {
  4036. CreateAttr |=
  4037. FLAGMASK(FLAGSET(FileAttr, faHidden), FILE_ATTRIBUTE_HIDDEN) |
  4038. FLAGMASK(FLAGSET(FileAttr, faReadOnly), FILE_ATTRIBUTE_READONLY);
  4039. FILE_OPERATION_LOOP_BEGIN
  4040. {
  4041. if (FileSetAttr(ApiPath(FileName), FileAttr & ~(faReadOnly | faHidden)) != 0)
  4042. {
  4043. RaiseLastOSError();
  4044. }
  4045. }
  4046. FILE_OPERATION_LOOP_END(FMTLOAD(CANT_SET_ATTRS, (FileName)));
  4047. }
  4048. else
  4049. {
  4050. Done = true;
  4051. }
  4052. }
  4053. else
  4054. {
  4055. RaiseLastOSError(LastError);
  4056. }
  4057. }
  4058. }
  4059. while (!Done);
  4060. return Result;
  4061. }
  4062. //---------------------------------------------------------------------------
  4063. bool __fastcall TTerminal::CreateLocalFile(const UnicodeString FileName,
  4064. TFileOperationProgressType * OperationProgress, HANDLE * AHandle,
  4065. bool NoConfirmation)
  4066. {
  4067. DebugAssert(AHandle);
  4068. bool Result = true;
  4069. FILE_OPERATION_LOOP_BEGIN
  4070. {
  4071. Result = DoCreateLocalFile(FileName, OperationProgress, AHandle, NoConfirmation);
  4072. }
  4073. FILE_OPERATION_LOOP_END(FMTLOAD(CREATE_FILE_ERROR, (FileName)));
  4074. return Result;
  4075. }
  4076. //---------------------------------------------------------------------------
  4077. void __fastcall TTerminal::OpenLocalFile(const UnicodeString FileName,
  4078. unsigned int Access, int * AAttrs, HANDLE * AHandle, __int64 * ACTime,
  4079. __int64 * AMTime, __int64 * AATime, __int64 * ASize,
  4080. bool TryWriteReadOnly)
  4081. {
  4082. int Attrs = 0;
  4083. HANDLE Handle = 0;
  4084. FILE_OPERATION_LOOP_BEGIN
  4085. {
  4086. UnicodeString FileNameApi = ApiPath(FileName);
  4087. Attrs = FileGetAttrFix(FileNameApi);
  4088. if (Attrs < 0)
  4089. {
  4090. RaiseLastOSError();
  4091. }
  4092. }
  4093. FILE_OPERATION_LOOP_END(FMTLOAD(FILE_NOT_EXISTS, (FileName)));
  4094. if (FLAGCLEAR(Attrs, faDirectory) || (AHandle == NULL))
  4095. {
  4096. bool NoHandle = false;
  4097. if (!TryWriteReadOnly && (Access == GENERIC_WRITE) &&
  4098. ((Attrs & faReadOnly) != 0))
  4099. {
  4100. Access = GENERIC_READ;
  4101. NoHandle = true;
  4102. }
  4103. FILE_OPERATION_LOOP_BEGIN
  4104. {
  4105. DWORD Flags = FLAGMASK(FLAGSET(Attrs, faDirectory), FILE_FLAG_BACKUP_SEMANTICS);
  4106. Handle = CreateFile(ApiPath(FileName).c_str(), Access,
  4107. Access == GENERIC_READ ? FILE_SHARE_READ | FILE_SHARE_WRITE : FILE_SHARE_READ,
  4108. NULL, OPEN_EXISTING, Flags, 0);
  4109. if (Handle == INVALID_HANDLE_VALUE)
  4110. {
  4111. Handle = 0;
  4112. RaiseLastOSError();
  4113. }
  4114. }
  4115. FILE_OPERATION_LOOP_END(FMTLOAD(OPENFILE_ERROR, (FileName)));
  4116. try
  4117. {
  4118. if (AATime || AMTime || ACTime)
  4119. {
  4120. FILETIME ATime;
  4121. FILETIME MTime;
  4122. FILETIME CTime;
  4123. // Get last file access and modification time
  4124. FILE_OPERATION_LOOP_BEGIN
  4125. {
  4126. THROWOSIFFALSE(GetFileTime(Handle, &CTime, &ATime, &MTime));
  4127. }
  4128. FILE_OPERATION_LOOP_END(FMTLOAD(CANT_GET_ATTRS, (FileName)));
  4129. if (ACTime)
  4130. {
  4131. *ACTime = ConvertTimestampToUnixSafe(CTime, SessionData->DSTMode);
  4132. }
  4133. if (AATime)
  4134. {
  4135. *AATime = ConvertTimestampToUnixSafe(ATime, SessionData->DSTMode);
  4136. }
  4137. if (AMTime)
  4138. {
  4139. *AMTime = ConvertTimestampToUnix(MTime, SessionData->DSTMode);
  4140. }
  4141. }
  4142. if (ASize)
  4143. {
  4144. // Get file size
  4145. FILE_OPERATION_LOOP_BEGIN
  4146. {
  4147. unsigned long LSize;
  4148. unsigned long HSize;
  4149. LSize = GetFileSize(Handle, &HSize);
  4150. if ((LSize == 0xFFFFFFFF) && (GetLastError() != NO_ERROR)) RaiseLastOSError();
  4151. *ASize = (__int64(HSize) << 32) + LSize;
  4152. }
  4153. FILE_OPERATION_LOOP_END(FMTLOAD(CANT_GET_ATTRS, (FileName)));
  4154. }
  4155. if ((AHandle == NULL) || NoHandle)
  4156. {
  4157. CloseHandle(Handle);
  4158. Handle = NULL;
  4159. }
  4160. }
  4161. catch(...)
  4162. {
  4163. CloseHandle(Handle);
  4164. throw;
  4165. }
  4166. }
  4167. if (AAttrs) *AAttrs = Attrs;
  4168. if (AHandle) *AHandle = Handle;
  4169. }
  4170. //---------------------------------------------------------------------------
  4171. bool __fastcall TTerminal::AllowLocalFileTransfer(UnicodeString FileName,
  4172. const TCopyParamType * CopyParam, TFileOperationProgressType * OperationProgress)
  4173. {
  4174. bool Result = true;
  4175. // optimization
  4176. if (Log->Logging || !CopyParam->AllowAnyTransfer())
  4177. {
  4178. WIN32_FIND_DATA FindData;
  4179. HANDLE Handle;
  4180. FILE_OPERATION_LOOP_BEGIN
  4181. {
  4182. Handle = FindFirstFile(ApiPath(ExcludeTrailingBackslash(FileName)).c_str(), &FindData);
  4183. if (Handle == INVALID_HANDLE_VALUE)
  4184. {
  4185. RaiseLastOSError();
  4186. }
  4187. }
  4188. FILE_OPERATION_LOOP_END(FMTLOAD(FILE_NOT_EXISTS, (FileName)));
  4189. ::FindClose(Handle);
  4190. bool Directory = FLAGSET(FindData.dwFileAttributes, FILE_ATTRIBUTE_DIRECTORY);
  4191. TFileMasks::TParams Params;
  4192. // SearchRec.Size in C++B2010 is __int64,
  4193. // so we should be able to use it instead of FindData.nFileSize*
  4194. Params.Size =
  4195. (static_cast<__int64>(FindData.nFileSizeHigh) << 32) +
  4196. FindData.nFileSizeLow;
  4197. Params.Modification = FileTimeToDateTime(FindData.ftLastWriteTime);
  4198. UnicodeString BaseFileName = GetBaseFileName(FileName);
  4199. if (!CopyParam->AllowTransfer(BaseFileName, osLocal, Directory, Params))
  4200. {
  4201. LogEvent(FORMAT(L"File \"%s\" excluded from transfer", (FileName)));
  4202. Result = false;
  4203. }
  4204. else if (CopyParam->SkipTransfer(FileName, Directory))
  4205. {
  4206. OperationProgress->AddSkippedFileSize(Params.Size);
  4207. Result = false;
  4208. }
  4209. if (Result)
  4210. {
  4211. LogFileDetails(FileName, Params.Modification, Params.Size);
  4212. }
  4213. }
  4214. return Result;
  4215. }
  4216. //---------------------------------------------------------------------------
  4217. void __fastcall TTerminal::MakeLocalFileList(const UnicodeString FileName,
  4218. const TSearchRec Rec, void * Param)
  4219. {
  4220. TMakeLocalFileListParams & Params = *static_cast<TMakeLocalFileListParams*>(Param);
  4221. bool Directory = FLAGSET(Rec.Attr, faDirectory);
  4222. if (Directory && Params.Recursive)
  4223. {
  4224. ProcessLocalDirectory(FileName, MakeLocalFileList, &Params);
  4225. }
  4226. if (!Directory || Params.IncludeDirs)
  4227. {
  4228. Params.FileList->Add(FileName);
  4229. if (Params.FileTimes != NULL)
  4230. {
  4231. Params.FileTimes->push_back(const_cast<TSearchRec &>(Rec).TimeStamp);
  4232. }
  4233. }
  4234. }
  4235. //---------------------------------------------------------------------------
  4236. void __fastcall TTerminal::CalculateLocalFileSize(const UnicodeString FileName,
  4237. const TSearchRec Rec, /*TCalculateSizeParams*/ void * Params)
  4238. {
  4239. TCalculateSizeParams * AParams = static_cast<TCalculateSizeParams*>(Params);
  4240. bool Dir = FLAGSET(Rec.Attr, faDirectory);
  4241. bool AllowTransfer = (AParams->CopyParam == NULL);
  4242. // SearchRec.Size in C++B2010 is __int64,
  4243. // so we should be able to use it instead of FindData.nFileSize*
  4244. __int64 Size =
  4245. (static_cast<__int64>(Rec.FindData.nFileSizeHigh) << 32) +
  4246. Rec.FindData.nFileSizeLow;
  4247. if (!AllowTransfer)
  4248. {
  4249. TFileMasks::TParams MaskParams;
  4250. MaskParams.Size = Size;
  4251. MaskParams.Modification = FileTimeToDateTime(Rec.FindData.ftLastWriteTime);
  4252. UnicodeString BaseFileName = GetBaseFileName(FileName);
  4253. AllowTransfer = AParams->CopyParam->AllowTransfer(BaseFileName, osLocal, Dir, MaskParams);
  4254. }
  4255. if (AllowTransfer)
  4256. {
  4257. if (!Dir)
  4258. {
  4259. AParams->Size += Size;
  4260. }
  4261. else
  4262. {
  4263. ProcessLocalDirectory(FileName, CalculateLocalFileSize, Params);
  4264. }
  4265. }
  4266. StartOperationWithFile(FileName, foCalculateSize);
  4267. }
  4268. //---------------------------------------------------------------------------
  4269. bool __fastcall TTerminal::CalculateLocalFilesSize(TStrings * FileList,
  4270. __int64 & Size, const TCopyParamType * CopyParam, bool AllowDirs)
  4271. {
  4272. bool Result = true;
  4273. TFileOperationProgressType OperationProgress(&DoProgress, &DoFinished);
  4274. TOnceDoneOperation OnceDoneOperation = odoIdle;
  4275. OperationProgress.Start(foCalculateSize, osLocal, FileList->Count);
  4276. try
  4277. {
  4278. TCalculateSizeParams Params;
  4279. Params.Size = 0;
  4280. Params.Params = 0;
  4281. Params.CopyParam = CopyParam;
  4282. DebugAssert(!FOperationProgress);
  4283. FOperationProgress = &OperationProgress;
  4284. for (int Index = 0; Result && (Index < FileList->Count); Index++)
  4285. {
  4286. UnicodeString FileName = FileList->Strings[Index];
  4287. TSearchRec Rec;
  4288. if (FileSearchRec(FileName, Rec))
  4289. {
  4290. if (FLAGSET(Rec.Attr, faDirectory) && !AllowDirs)
  4291. {
  4292. Result = false;
  4293. }
  4294. else
  4295. {
  4296. CalculateLocalFileSize(FileName, Rec, &Params);
  4297. OperationProgress.Finish(FileName, true, OnceDoneOperation);
  4298. }
  4299. }
  4300. }
  4301. Size = Params.Size;
  4302. }
  4303. __finally
  4304. {
  4305. FOperationProgress = NULL;
  4306. OperationProgress.Stop();
  4307. }
  4308. if (OnceDoneOperation != odoIdle)
  4309. {
  4310. CloseOnCompletion(OnceDoneOperation);
  4311. }
  4312. return Result;
  4313. }
  4314. //---------------------------------------------------------------------------
  4315. struct TSynchronizeFileData
  4316. {
  4317. bool Modified;
  4318. bool New;
  4319. bool IsDirectory;
  4320. TSynchronizeChecklist::TItem::TFileInfo Info;
  4321. TSynchronizeChecklist::TItem::TFileInfo MatchingRemoteFile;
  4322. TRemoteFile * MatchingRemoteFileFile;
  4323. int MatchingRemoteFileImageIndex;
  4324. FILETIME LocalLastWriteTime;
  4325. };
  4326. //---------------------------------------------------------------------------
  4327. const int sfFirstLevel = 0x01;
  4328. struct TSynchronizeData
  4329. {
  4330. UnicodeString LocalDirectory;
  4331. UnicodeString RemoteDirectory;
  4332. TTerminal::TSynchronizeMode Mode;
  4333. int Params;
  4334. TSynchronizeDirectory OnSynchronizeDirectory;
  4335. TSynchronizeOptions * Options;
  4336. int Flags;
  4337. TStringList * LocalFileList;
  4338. const TCopyParamType * CopyParam;
  4339. TSynchronizeChecklist * Checklist;
  4340. };
  4341. //---------------------------------------------------------------------------
  4342. TSynchronizeChecklist * __fastcall TTerminal::SynchronizeCollect(const UnicodeString LocalDirectory,
  4343. const UnicodeString RemoteDirectory, TSynchronizeMode Mode,
  4344. const TCopyParamType * CopyParam, int Params,
  4345. TSynchronizeDirectory OnSynchronizeDirectory,
  4346. TSynchronizeOptions * Options)
  4347. {
  4348. TValueRestorer<bool> UseBusyCursorRestorer(FUseBusyCursor);
  4349. FUseBusyCursor = false;
  4350. TSynchronizeChecklist * Checklist = new TSynchronizeChecklist();
  4351. try
  4352. {
  4353. DoSynchronizeCollectDirectory(LocalDirectory, RemoteDirectory, Mode,
  4354. CopyParam, Params, OnSynchronizeDirectory, Options, sfFirstLevel,
  4355. Checklist);
  4356. Checklist->Sort();
  4357. }
  4358. catch(...)
  4359. {
  4360. delete Checklist;
  4361. throw;
  4362. }
  4363. return Checklist;
  4364. }
  4365. //---------------------------------------------------------------------------
  4366. static void __fastcall AddFlagName(UnicodeString & ParamsStr, int & Params, int Param, const UnicodeString & Name)
  4367. {
  4368. if (FLAGSET(Params, Param))
  4369. {
  4370. AddToList(ParamsStr, Name, ", ");
  4371. }
  4372. Params &= ~Param;
  4373. }
  4374. //---------------------------------------------------------------------------
  4375. UnicodeString __fastcall TTerminal::SynchronizeModeStr(TSynchronizeMode Mode)
  4376. {
  4377. UnicodeString ModeStr;
  4378. switch (Mode)
  4379. {
  4380. case smRemote:
  4381. ModeStr = L"Remote";
  4382. break;
  4383. case smLocal:
  4384. ModeStr = L"Local";
  4385. break;
  4386. case smBoth:
  4387. ModeStr = L"Both";
  4388. break;
  4389. default:
  4390. ModeStr = L"Unknown";
  4391. break;
  4392. }
  4393. return ModeStr;
  4394. }
  4395. //---------------------------------------------------------------------------
  4396. UnicodeString __fastcall TTerminal::SynchronizeParamsStr(int Params)
  4397. {
  4398. UnicodeString ParamsStr;
  4399. AddFlagName(ParamsStr, Params, spDelete, L"Delete");
  4400. AddFlagName(ParamsStr, Params, spNoConfirmation, L"NoConfirmation");
  4401. AddFlagName(ParamsStr, Params, spExistingOnly, L"ExistingOnly");
  4402. AddFlagName(ParamsStr, Params, spNoRecurse, L"NoRecurse");
  4403. AddFlagName(ParamsStr, Params, spUseCache, L"UseCache");
  4404. AddFlagName(ParamsStr, Params, spDelayProgress, L"DelayProgress");
  4405. AddFlagName(ParamsStr, Params, spPreviewChanges, L"*PreviewChanges"); // GUI only
  4406. AddFlagName(ParamsStr, Params, spSubDirs, L"SubDirs");
  4407. AddFlagName(ParamsStr, Params, spTimestamp, L"Timestamp");
  4408. AddFlagName(ParamsStr, Params, spNotByTime, L"NotByTime");
  4409. AddFlagName(ParamsStr, Params, spBySize, L"BySize");
  4410. AddFlagName(ParamsStr, Params, spSelectedOnly, L"*SelectedOnly"); // GUI only
  4411. AddFlagName(ParamsStr, Params, spMirror, L"Mirror");
  4412. if (Params > 0)
  4413. {
  4414. AddToList(ParamsStr, FORMAT(L"0x%x", (int(Params))), L", ");
  4415. }
  4416. return ParamsStr;
  4417. }
  4418. //---------------------------------------------------------------------------
  4419. void __fastcall TTerminal::DoSynchronizeCollectDirectory(const UnicodeString LocalDirectory,
  4420. const UnicodeString RemoteDirectory, TSynchronizeMode Mode,
  4421. const TCopyParamType * CopyParam, int Params,
  4422. TSynchronizeDirectory OnSynchronizeDirectory, TSynchronizeOptions * Options,
  4423. int Flags, TSynchronizeChecklist * Checklist)
  4424. {
  4425. TSynchronizeData Data;
  4426. Data.LocalDirectory = IncludeTrailingBackslash(LocalDirectory);
  4427. Data.RemoteDirectory = UnixIncludeTrailingBackslash(RemoteDirectory);
  4428. Data.Mode = Mode;
  4429. Data.Params = Params;
  4430. Data.OnSynchronizeDirectory = OnSynchronizeDirectory;
  4431. Data.LocalFileList = NULL;
  4432. Data.CopyParam = CopyParam;
  4433. Data.Options = Options;
  4434. Data.Flags = Flags;
  4435. Data.Checklist = Checklist;
  4436. LogEvent(FORMAT(L"Collecting synchronization list for local directory '%s' and remote directory '%s', "
  4437. "mode = %s, params = 0x%x (%s)", (LocalDirectory, RemoteDirectory,
  4438. SynchronizeModeStr(Mode), int(Params), SynchronizeParamsStr(Params))));
  4439. if (FLAGCLEAR(Params, spDelayProgress))
  4440. {
  4441. DoSynchronizeProgress(Data, true);
  4442. }
  4443. try
  4444. {
  4445. bool Found;
  4446. TSearchRecChecked SearchRec;
  4447. Data.LocalFileList = CreateSortedStringList();
  4448. FILE_OPERATION_LOOP_BEGIN
  4449. {
  4450. int FindAttrs = faReadOnly | faHidden | faSysFile | faDirectory | faArchive;
  4451. Found = (FindFirstChecked(Data.LocalDirectory + L"*.*", FindAttrs, SearchRec) == 0);
  4452. }
  4453. FILE_OPERATION_LOOP_END(FMTLOAD(LIST_DIR_ERROR, (LocalDirectory)));
  4454. if (Found)
  4455. {
  4456. try
  4457. {
  4458. UnicodeString FileName;
  4459. while (Found)
  4460. {
  4461. FileName = SearchRec.Name;
  4462. // add dirs for recursive mode or when we are interested in newly
  4463. // added subdirs
  4464. // SearchRec.Size in C++B2010 is __int64,
  4465. // so we should be able to use it instead of FindData.nFileSize*
  4466. __int64 Size =
  4467. (static_cast<__int64>(SearchRec.FindData.nFileSizeHigh) << 32) +
  4468. SearchRec.FindData.nFileSizeLow;
  4469. TDateTime Modification = FileTimeToDateTime(SearchRec.FindData.ftLastWriteTime);
  4470. TFileMasks::TParams MaskParams;
  4471. MaskParams.Size = Size;
  4472. MaskParams.Modification = Modification;
  4473. UnicodeString RemoteFileName =
  4474. ChangeFileName(CopyParam, FileName, osLocal, false);
  4475. UnicodeString FullLocalFileName = Data.LocalDirectory + FileName;
  4476. UnicodeString BaseFileName = GetBaseFileName(FullLocalFileName);
  4477. if ((FileName != L".") && (FileName != L"..") &&
  4478. CopyParam->AllowTransfer(BaseFileName, osLocal,
  4479. FLAGSET(SearchRec.Attr, faDirectory), MaskParams) &&
  4480. !FFileSystem->TemporaryTransferFile(FileName) &&
  4481. (FLAGCLEAR(Flags, sfFirstLevel) ||
  4482. (Options == NULL) ||
  4483. Options->MatchesFilter(FileName) ||
  4484. Options->MatchesFilter(RemoteFileName)))
  4485. {
  4486. TSynchronizeFileData * FileData = new TSynchronizeFileData;
  4487. FileData->IsDirectory = FLAGSET(SearchRec.Attr, faDirectory);
  4488. FileData->Info.FileName = FileName;
  4489. FileData->Info.Directory = Data.LocalDirectory;
  4490. FileData->Info.Modification = Modification;
  4491. FileData->Info.ModificationFmt = mfFull;
  4492. FileData->Info.Size = Size;
  4493. FileData->LocalLastWriteTime = SearchRec.FindData.ftLastWriteTime;
  4494. FileData->New = true;
  4495. FileData->Modified = false;
  4496. Data.LocalFileList->AddObject(FileName,
  4497. reinterpret_cast<TObject*>(FileData));
  4498. LogEvent(FORMAT(L"Local file %s included to synchronization",
  4499. (FormatFileDetailsForLog(FullLocalFileName, Modification, Size))));
  4500. }
  4501. else
  4502. {
  4503. LogEvent(FORMAT(L"Local file %s excluded from synchronization",
  4504. (FormatFileDetailsForLog(FullLocalFileName, Modification, Size))));
  4505. }
  4506. FILE_OPERATION_LOOP_BEGIN
  4507. {
  4508. Found = (FindNextChecked(SearchRec) == 0);
  4509. }
  4510. FILE_OPERATION_LOOP_END(FMTLOAD(LIST_DIR_ERROR, (LocalDirectory)));
  4511. }
  4512. }
  4513. __finally
  4514. {
  4515. FindClose(SearchRec);
  4516. }
  4517. // can we expect that ProcessDirectory would take so little time
  4518. // that we can postpone showing progress window until anything actually happens?
  4519. bool Cached = FLAGSET(Params, spUseCache) && SessionData->CacheDirectories &&
  4520. FDirectoryCache->HasFileList(RemoteDirectory);
  4521. if (!Cached && FLAGSET(Params, spDelayProgress))
  4522. {
  4523. DoSynchronizeProgress(Data, true);
  4524. }
  4525. ProcessDirectory(RemoteDirectory, SynchronizeCollectFile, &Data,
  4526. FLAGSET(Params, spUseCache));
  4527. TSynchronizeFileData * FileData;
  4528. for (int Index = 0; Index < Data.LocalFileList->Count; Index++)
  4529. {
  4530. FileData = reinterpret_cast<TSynchronizeFileData *>
  4531. (Data.LocalFileList->Objects[Index]);
  4532. // add local file either if we are going to upload it
  4533. // (i.e. if it is updated or we want to upload even new files)
  4534. // or if we are going to delete it (i.e. all "new"=obsolete files)
  4535. bool Modified = (FileData->Modified && ((Mode == smBoth) || (Mode == smRemote)));
  4536. bool New = (FileData->New &&
  4537. ((Mode == smLocal) ||
  4538. (((Mode == smBoth) || (Mode == smRemote)) && FLAGCLEAR(Params, spTimestamp))));
  4539. if (New)
  4540. {
  4541. LogEvent(FORMAT(L"Local file %s is new",
  4542. (FormatFileDetailsForLog(FileData->Info.Directory + FileData->Info.FileName,
  4543. FileData->Info.Modification, FileData->Info.Size))));
  4544. }
  4545. if (Modified || New)
  4546. {
  4547. TSynchronizeChecklist::TItem * ChecklistItem = new TSynchronizeChecklist::TItem();
  4548. try
  4549. {
  4550. ChecklistItem->IsDirectory = FileData->IsDirectory;
  4551. ChecklistItem->Local = FileData->Info;
  4552. ChecklistItem->FLocalLastWriteTime = FileData->LocalLastWriteTime;
  4553. if (Modified)
  4554. {
  4555. DebugAssert(!FileData->MatchingRemoteFile.Directory.IsEmpty());
  4556. ChecklistItem->Remote = FileData->MatchingRemoteFile;
  4557. ChecklistItem->ImageIndex = FileData->MatchingRemoteFileImageIndex;
  4558. ChecklistItem->RemoteFile = FileData->MatchingRemoteFileFile;
  4559. }
  4560. else
  4561. {
  4562. ChecklistItem->Remote.Directory = Data.RemoteDirectory;
  4563. }
  4564. if ((Mode == smBoth) || (Mode == smRemote))
  4565. {
  4566. ChecklistItem->Action =
  4567. (Modified ? TSynchronizeChecklist::saUploadUpdate : TSynchronizeChecklist::saUploadNew);
  4568. ChecklistItem->Checked =
  4569. (Modified || FLAGCLEAR(Params, spExistingOnly)) &&
  4570. (!ChecklistItem->IsDirectory || FLAGCLEAR(Params, spNoRecurse) ||
  4571. FLAGSET(Params, spSubDirs));
  4572. }
  4573. else if ((Mode == smLocal) && FLAGCLEAR(Params, spTimestamp))
  4574. {
  4575. ChecklistItem->Action = TSynchronizeChecklist::saDeleteLocal;
  4576. ChecklistItem->Checked =
  4577. FLAGSET(Params, spDelete) &&
  4578. (!ChecklistItem->IsDirectory || FLAGCLEAR(Params, spNoRecurse) ||
  4579. FLAGSET(Params, spSubDirs));
  4580. }
  4581. if (ChecklistItem->Action != TSynchronizeChecklist::saNone)
  4582. {
  4583. Data.Checklist->Add(ChecklistItem);
  4584. ChecklistItem = NULL;
  4585. }
  4586. }
  4587. __finally
  4588. {
  4589. delete ChecklistItem;
  4590. }
  4591. }
  4592. else
  4593. {
  4594. if (FileData->Modified)
  4595. {
  4596. delete FileData->MatchingRemoteFileFile;
  4597. }
  4598. }
  4599. }
  4600. }
  4601. }
  4602. __finally
  4603. {
  4604. if (Data.LocalFileList != NULL)
  4605. {
  4606. for (int Index = 0; Index < Data.LocalFileList->Count; Index++)
  4607. {
  4608. TSynchronizeFileData * FileData = reinterpret_cast<TSynchronizeFileData*>
  4609. (Data.LocalFileList->Objects[Index]);
  4610. delete FileData;
  4611. }
  4612. delete Data.LocalFileList;
  4613. }
  4614. }
  4615. }
  4616. //---------------------------------------------------------------------------
  4617. void __fastcall TTerminal::SynchronizeCollectFile(const UnicodeString FileName,
  4618. const TRemoteFile * File, /*TSynchronizeData*/ void * Param)
  4619. {
  4620. try
  4621. {
  4622. DoSynchronizeCollectFile(FileName, File, Param);
  4623. }
  4624. catch(EScpSkipFile & E)
  4625. {
  4626. TSuspendFileOperationProgress Suspend(OperationProgress);
  4627. if (!HandleException(&E))
  4628. {
  4629. throw;
  4630. }
  4631. }
  4632. }
  4633. //---------------------------------------------------------------------------
  4634. void __fastcall TTerminal::DoSynchronizeCollectFile(const UnicodeString FileName,
  4635. const TRemoteFile * File, /*TSynchronizeData*/ void * Param)
  4636. {
  4637. TSynchronizeData * Data = static_cast<TSynchronizeData *>(Param);
  4638. TFileMasks::TParams MaskParams;
  4639. MaskParams.Size = File->Size;
  4640. MaskParams.Modification = File->Modification;
  4641. UnicodeString LocalFileName =
  4642. ChangeFileName(Data->CopyParam, File->FileName, osRemote, false);
  4643. UnicodeString FullRemoteFileName =
  4644. UnixExcludeTrailingBackslash(File->FullFileName);
  4645. UnicodeString BaseFileName = GetBaseFileName(FullRemoteFileName);
  4646. if (Data->CopyParam->AllowTransfer(
  4647. BaseFileName, osRemote,
  4648. File->IsDirectory, MaskParams) &&
  4649. !FFileSystem->TemporaryTransferFile(File->FileName) &&
  4650. (FLAGCLEAR(Data->Flags, sfFirstLevel) ||
  4651. (Data->Options == NULL) ||
  4652. Data->Options->MatchesFilter(File->FileName) ||
  4653. Data->Options->MatchesFilter(LocalFileName)))
  4654. {
  4655. TSynchronizeChecklist::TItem * ChecklistItem = new TSynchronizeChecklist::TItem();
  4656. try
  4657. {
  4658. ChecklistItem->IsDirectory = File->IsDirectory;
  4659. ChecklistItem->ImageIndex = File->IconIndex;
  4660. ChecklistItem->Remote.FileName = File->FileName;
  4661. ChecklistItem->Remote.Directory = Data->RemoteDirectory;
  4662. ChecklistItem->Remote.Modification = File->Modification;
  4663. ChecklistItem->Remote.ModificationFmt = File->ModificationFmt;
  4664. ChecklistItem->Remote.Size = File->Size;
  4665. bool Modified = false;
  4666. bool New = false;
  4667. if (File->IsDirectory && !CanRecurseToDirectory(File))
  4668. {
  4669. LogEvent(FORMAT(L"Skipping symlink to directory \"%s\".", (File->FileName)));
  4670. }
  4671. else
  4672. {
  4673. int LocalIndex = Data->LocalFileList->IndexOf(LocalFileName);
  4674. New = (LocalIndex < 0);
  4675. if (!New)
  4676. {
  4677. TSynchronizeFileData * LocalData =
  4678. reinterpret_cast<TSynchronizeFileData *>(Data->LocalFileList->Objects[LocalIndex]);
  4679. LocalData->New = false;
  4680. if (File->IsDirectory != LocalData->IsDirectory)
  4681. {
  4682. LogEvent(FORMAT(L"%s is directory on one side, but file on the another",
  4683. (File->FileName)));
  4684. }
  4685. else if (!File->IsDirectory)
  4686. {
  4687. ChecklistItem->Local = LocalData->Info;
  4688. ChecklistItem->Local.Modification =
  4689. ReduceDateTimePrecision(ChecklistItem->Local.Modification, File->ModificationFmt);
  4690. bool LocalModified = false;
  4691. // for spTimestamp+spBySize require that the file sizes are the same
  4692. // before comparing file time
  4693. int TimeCompare;
  4694. if (FLAGCLEAR(Data->Params, spNotByTime) &&
  4695. (FLAGCLEAR(Data->Params, spTimestamp) ||
  4696. FLAGCLEAR(Data->Params, spBySize) ||
  4697. (ChecklistItem->Local.Size == ChecklistItem->Remote.Size)))
  4698. {
  4699. TimeCompare = CompareFileTime(ChecklistItem->Local.Modification,
  4700. ChecklistItem->Remote.Modification);
  4701. }
  4702. else
  4703. {
  4704. TimeCompare = 0;
  4705. }
  4706. if (TimeCompare < 0)
  4707. {
  4708. if ((FLAGCLEAR(Data->Params, spTimestamp) && FLAGCLEAR(Data->Params, spMirror)) ||
  4709. (Data->Mode == smBoth) || (Data->Mode == smLocal))
  4710. {
  4711. Modified = true;
  4712. }
  4713. else
  4714. {
  4715. LocalModified = true;
  4716. }
  4717. }
  4718. else if (TimeCompare > 0)
  4719. {
  4720. if ((FLAGCLEAR(Data->Params, spTimestamp) && FLAGCLEAR(Data->Params, spMirror)) ||
  4721. (Data->Mode == smBoth) || (Data->Mode == smRemote))
  4722. {
  4723. LocalModified = true;
  4724. }
  4725. else
  4726. {
  4727. Modified = true;
  4728. }
  4729. }
  4730. else if (FLAGSET(Data->Params, spBySize) &&
  4731. (ChecklistItem->Local.Size != ChecklistItem->Remote.Size) &&
  4732. FLAGCLEAR(Data->Params, spTimestamp))
  4733. {
  4734. Modified = true;
  4735. LocalModified = true;
  4736. }
  4737. if (LocalModified)
  4738. {
  4739. LocalData->Modified = true;
  4740. LocalData->MatchingRemoteFile = ChecklistItem->Remote;
  4741. LocalData->MatchingRemoteFileImageIndex = ChecklistItem->ImageIndex;
  4742. // we need this for custom commands over checklist only,
  4743. // not for sync itself
  4744. LocalData->MatchingRemoteFileFile = File->Duplicate();
  4745. LogEvent(FORMAT(L"Local file %s is modified comparing to remote file %s",
  4746. (FormatFileDetailsForLog(LocalData->Info.Directory + LocalData->Info.FileName,
  4747. LocalData->Info.Modification, LocalData->Info.Size),
  4748. FormatFileDetailsForLog(FullRemoteFileName,
  4749. File->Modification, File->Size))));
  4750. }
  4751. if (Modified)
  4752. {
  4753. LogEvent(FORMAT(L"Remote file %s is modified comparing to local file %s",
  4754. (FormatFileDetailsForLog(FullRemoteFileName, File->Modification, File->Size),
  4755. FormatFileDetailsForLog(LocalData->Info.Directory + LocalData->Info.FileName,
  4756. LocalData->Info.Modification, LocalData->Info.Size))));
  4757. }
  4758. }
  4759. else if (FLAGCLEAR(Data->Params, spNoRecurse))
  4760. {
  4761. DoSynchronizeCollectDirectory(
  4762. Data->LocalDirectory + LocalData->Info.FileName,
  4763. Data->RemoteDirectory + File->FileName,
  4764. Data->Mode, Data->CopyParam, Data->Params, Data->OnSynchronizeDirectory,
  4765. Data->Options, (Data->Flags & ~sfFirstLevel),
  4766. Data->Checklist);
  4767. }
  4768. }
  4769. else
  4770. {
  4771. ChecklistItem->Local.Directory = Data->LocalDirectory;
  4772. LogEvent(FORMAT(L"Remote file %s is new",
  4773. (FormatFileDetailsForLog(FullRemoteFileName, File->Modification, File->Size))));
  4774. }
  4775. }
  4776. if (New || Modified)
  4777. {
  4778. DebugAssert(!New || !Modified);
  4779. // download the file if it changed or is new and we want to have it locally
  4780. if ((Data->Mode == smBoth) || (Data->Mode == smLocal))
  4781. {
  4782. if (FLAGCLEAR(Data->Params, spTimestamp) || Modified)
  4783. {
  4784. ChecklistItem->Action =
  4785. (Modified ? TSynchronizeChecklist::saDownloadUpdate : TSynchronizeChecklist::saDownloadNew);
  4786. ChecklistItem->Checked =
  4787. (Modified || FLAGCLEAR(Data->Params, spExistingOnly)) &&
  4788. (!ChecklistItem->IsDirectory || FLAGCLEAR(Data->Params, spNoRecurse) ||
  4789. FLAGSET(Data->Params, spSubDirs));
  4790. }
  4791. }
  4792. else if ((Data->Mode == smRemote) && New)
  4793. {
  4794. if (FLAGCLEAR(Data->Params, spTimestamp))
  4795. {
  4796. ChecklistItem->Action = TSynchronizeChecklist::saDeleteRemote;
  4797. ChecklistItem->Checked =
  4798. FLAGSET(Data->Params, spDelete) &&
  4799. (!ChecklistItem->IsDirectory || FLAGCLEAR(Data->Params, spNoRecurse) ||
  4800. FLAGSET(Data->Params, spSubDirs));
  4801. }
  4802. }
  4803. if (ChecklistItem->Action != TSynchronizeChecklist::saNone)
  4804. {
  4805. ChecklistItem->RemoteFile = File->Duplicate();
  4806. Data->Checklist->Add(ChecklistItem);
  4807. ChecklistItem = NULL;
  4808. }
  4809. }
  4810. }
  4811. __finally
  4812. {
  4813. delete ChecklistItem;
  4814. }
  4815. }
  4816. else
  4817. {
  4818. LogEvent(FORMAT(L"Remote file %s excluded from synchronization",
  4819. (FormatFileDetailsForLog(FullRemoteFileName, File->Modification, File->Size))));
  4820. }
  4821. }
  4822. //---------------------------------------------------------------------------
  4823. void __fastcall TTerminal::SynchronizeApply(TSynchronizeChecklist * Checklist,
  4824. const UnicodeString LocalDirectory, const UnicodeString RemoteDirectory,
  4825. const TCopyParamType * CopyParam, int Params,
  4826. TSynchronizeDirectory OnSynchronizeDirectory)
  4827. {
  4828. TSynchronizeData Data;
  4829. Data.OnSynchronizeDirectory = OnSynchronizeDirectory;
  4830. int CopyParams =
  4831. FLAGMASK(FLAGSET(Params, spNoConfirmation), cpNoConfirmation);
  4832. TCopyParamType SyncCopyParam = *CopyParam;
  4833. // when synchronizing by time, we force preserving time,
  4834. // otherwise it does not make any sense
  4835. if (FLAGCLEAR(Params, spNotByTime))
  4836. {
  4837. SyncCopyParam.PreserveTime = true;
  4838. }
  4839. TStringList * DownloadList = new TStringList();
  4840. TStringList * DeleteRemoteList = new TStringList();
  4841. TStringList * UploadList = new TStringList();
  4842. TStringList * DeleteLocalList = new TStringList();
  4843. BeginTransaction();
  4844. try
  4845. {
  4846. int IIndex = 0;
  4847. while (IIndex < Checklist->Count)
  4848. {
  4849. const TSynchronizeChecklist::TItem * ChecklistItem;
  4850. DownloadList->Clear();
  4851. DeleteRemoteList->Clear();
  4852. UploadList->Clear();
  4853. DeleteLocalList->Clear();
  4854. ChecklistItem = Checklist->Item[IIndex];
  4855. UnicodeString CurrentLocalDirectory = ChecklistItem->Local.Directory;
  4856. UnicodeString CurrentRemoteDirectory = ChecklistItem->Remote.Directory;
  4857. LogEvent(FORMAT(L"Synchronizing local directory '%s' with remote directory '%s', "
  4858. "params = 0x%x (%s)", (CurrentLocalDirectory, CurrentRemoteDirectory,
  4859. int(Params), SynchronizeParamsStr(Params))));
  4860. int Count = 0;
  4861. while ((IIndex < Checklist->Count) &&
  4862. (Checklist->Item[IIndex]->Local.Directory == CurrentLocalDirectory) &&
  4863. (Checklist->Item[IIndex]->Remote.Directory == CurrentRemoteDirectory))
  4864. {
  4865. ChecklistItem = Checklist->Item[IIndex];
  4866. if (ChecklistItem->Checked)
  4867. {
  4868. Count++;
  4869. if (FLAGSET(Params, spTimestamp))
  4870. {
  4871. switch (ChecklistItem->Action)
  4872. {
  4873. case TSynchronizeChecklist::saDownloadUpdate:
  4874. DownloadList->AddObject(
  4875. UnixIncludeTrailingBackslash(ChecklistItem->Remote.Directory) +
  4876. ChecklistItem->Remote.FileName,
  4877. (TObject *)(ChecklistItem));
  4878. break;
  4879. case TSynchronizeChecklist::saUploadUpdate:
  4880. UploadList->AddObject(
  4881. IncludeTrailingBackslash(ChecklistItem->Local.Directory) +
  4882. ChecklistItem->Local.FileName,
  4883. (TObject *)(ChecklistItem));
  4884. break;
  4885. default:
  4886. DebugFail();
  4887. break;
  4888. }
  4889. }
  4890. else
  4891. {
  4892. switch (ChecklistItem->Action)
  4893. {
  4894. case TSynchronizeChecklist::saDownloadNew:
  4895. case TSynchronizeChecklist::saDownloadUpdate:
  4896. DownloadList->AddObject(
  4897. UnixIncludeTrailingBackslash(ChecklistItem->Remote.Directory) +
  4898. ChecklistItem->Remote.FileName,
  4899. ChecklistItem->RemoteFile);
  4900. break;
  4901. case TSynchronizeChecklist::saDeleteRemote:
  4902. DeleteRemoteList->AddObject(
  4903. UnixIncludeTrailingBackslash(ChecklistItem->Remote.Directory) +
  4904. ChecklistItem->Remote.FileName,
  4905. ChecklistItem->RemoteFile);
  4906. break;
  4907. case TSynchronizeChecklist::saUploadNew:
  4908. case TSynchronizeChecklist::saUploadUpdate:
  4909. UploadList->Add(
  4910. IncludeTrailingBackslash(ChecklistItem->Local.Directory) +
  4911. ChecklistItem->Local.FileName);
  4912. break;
  4913. case TSynchronizeChecklist::saDeleteLocal:
  4914. DeleteLocalList->Add(
  4915. IncludeTrailingBackslash(ChecklistItem->Local.Directory) +
  4916. ChecklistItem->Local.FileName);
  4917. break;
  4918. default:
  4919. DebugFail();
  4920. break;
  4921. }
  4922. }
  4923. }
  4924. IIndex++;
  4925. }
  4926. // prevent showing/updating of progress dialog if there's nothing to do
  4927. if (Count > 0)
  4928. {
  4929. Data.LocalDirectory = IncludeTrailingBackslash(CurrentLocalDirectory);
  4930. Data.RemoteDirectory = UnixIncludeTrailingBackslash(CurrentRemoteDirectory);
  4931. DoSynchronizeProgress(Data, false);
  4932. if (FLAGSET(Params, spTimestamp))
  4933. {
  4934. if (DownloadList->Count > 0)
  4935. {
  4936. ProcessFiles(DownloadList, foSetProperties,
  4937. SynchronizeLocalTimestamp, NULL, osLocal);
  4938. }
  4939. if (UploadList->Count > 0)
  4940. {
  4941. ProcessFiles(UploadList, foSetProperties,
  4942. SynchronizeRemoteTimestamp);
  4943. }
  4944. }
  4945. else
  4946. {
  4947. if ((DownloadList->Count > 0) &&
  4948. !CopyToLocal(DownloadList, Data.LocalDirectory, &SyncCopyParam, CopyParams))
  4949. {
  4950. Abort();
  4951. }
  4952. if ((DeleteRemoteList->Count > 0) &&
  4953. !DeleteFiles(DeleteRemoteList))
  4954. {
  4955. Abort();
  4956. }
  4957. if ((UploadList->Count > 0) &&
  4958. !CopyToRemote(UploadList, Data.RemoteDirectory, &SyncCopyParam, CopyParams))
  4959. {
  4960. Abort();
  4961. }
  4962. if ((DeleteLocalList->Count > 0) &&
  4963. !DeleteLocalFiles(DeleteLocalList))
  4964. {
  4965. Abort();
  4966. }
  4967. }
  4968. }
  4969. }
  4970. }
  4971. __finally
  4972. {
  4973. delete DownloadList;
  4974. delete DeleteRemoteList;
  4975. delete UploadList;
  4976. delete DeleteLocalList;
  4977. EndTransaction();
  4978. }
  4979. }
  4980. //---------------------------------------------------------------------------
  4981. void __fastcall TTerminal::DoSynchronizeProgress(const TSynchronizeData & Data,
  4982. bool Collect)
  4983. {
  4984. if (Data.OnSynchronizeDirectory != NULL)
  4985. {
  4986. bool Continue = true;
  4987. Data.OnSynchronizeDirectory(Data.LocalDirectory, Data.RemoteDirectory,
  4988. Continue, Collect);
  4989. if (!Continue)
  4990. {
  4991. Abort();
  4992. }
  4993. }
  4994. }
  4995. //---------------------------------------------------------------------------
  4996. void __fastcall TTerminal::SynchronizeLocalTimestamp(const UnicodeString /*FileName*/,
  4997. const TRemoteFile * File, void * /*Param*/)
  4998. {
  4999. const TSynchronizeChecklist::TItem * ChecklistItem =
  5000. reinterpret_cast<const TSynchronizeChecklist::TItem *>(File);
  5001. UnicodeString LocalFile =
  5002. IncludeTrailingBackslash(ChecklistItem->Local.Directory) +
  5003. ChecklistItem->Local.FileName;
  5004. FILE_OPERATION_LOOP_BEGIN
  5005. {
  5006. HANDLE Handle;
  5007. OpenLocalFile(LocalFile, GENERIC_WRITE, NULL, &Handle,
  5008. NULL, NULL, NULL, NULL);
  5009. FILETIME WrTime = DateTimeToFileTime(ChecklistItem->Remote.Modification,
  5010. SessionData->DSTMode);
  5011. bool Result = SetFileTime(Handle, NULL, NULL, &WrTime);
  5012. int Error = GetLastError();
  5013. CloseHandle(Handle);
  5014. if (!Result)
  5015. {
  5016. RaiseLastOSError(Error);
  5017. }
  5018. }
  5019. FILE_OPERATION_LOOP_END(FMTLOAD(CANT_SET_ATTRS, (LocalFile)));
  5020. }
  5021. //---------------------------------------------------------------------------
  5022. void __fastcall TTerminal::SynchronizeRemoteTimestamp(const UnicodeString /*FileName*/,
  5023. const TRemoteFile * File, void * /*Param*/)
  5024. {
  5025. const TSynchronizeChecklist::TItem * ChecklistItem =
  5026. reinterpret_cast<const TSynchronizeChecklist::TItem *>(File);
  5027. TRemoteProperties Properties;
  5028. Properties.Valid << vpModification;
  5029. Properties.Modification = ConvertTimestampToUnix(ChecklistItem->FLocalLastWriteTime,
  5030. SessionData->DSTMode);
  5031. ChangeFileProperties(
  5032. UnixIncludeTrailingBackslash(ChecklistItem->Remote.Directory) + ChecklistItem->Remote.FileName,
  5033. NULL, &Properties);
  5034. }
  5035. //---------------------------------------------------------------------------
  5036. void __fastcall TTerminal::FileFind(UnicodeString FileName,
  5037. const TRemoteFile * File, /*TFilesFindParams*/ void * Param)
  5038. {
  5039. // see DoFilesFind
  5040. FOnFindingFile = NULL;
  5041. DebugAssert(Param);
  5042. DebugAssert(File);
  5043. TFilesFindParams * AParams = static_cast<TFilesFindParams*>(Param);
  5044. if (!AParams->Cancel)
  5045. {
  5046. if (FileName.IsEmpty())
  5047. {
  5048. FileName = File->FileName;
  5049. }
  5050. TFileMasks::TParams MaskParams;
  5051. MaskParams.Size = File->Size;
  5052. MaskParams.Modification = File->Modification;
  5053. UnicodeString FullFileName = UnixExcludeTrailingBackslash(File->FullFileName);
  5054. bool ImplicitMatch;
  5055. // Do not use recursive include match
  5056. if (AParams->FileMask.Matches(FullFileName, false,
  5057. File->IsDirectory, &MaskParams, false, ImplicitMatch))
  5058. {
  5059. if (!ImplicitMatch)
  5060. {
  5061. AParams->OnFileFound(this, FileName, File, AParams->Cancel);
  5062. }
  5063. if (File->IsDirectory)
  5064. {
  5065. if (!AParams->LoopDetector.IsUnvisitedDirectory(File))
  5066. {
  5067. LogEvent(FORMAT(L"Already searched \"%s\" directory, link loop detected", (FullFileName)));
  5068. }
  5069. else
  5070. {
  5071. DoFilesFind(FullFileName, *AParams);
  5072. }
  5073. }
  5074. }
  5075. }
  5076. }
  5077. //---------------------------------------------------------------------------
  5078. void __fastcall TTerminal::DoFilesFind(UnicodeString Directory, TFilesFindParams & Params)
  5079. {
  5080. Params.OnFindingFile(this, Directory, Params.Cancel);
  5081. if (!Params.Cancel)
  5082. {
  5083. DebugAssert(FOnFindingFile == NULL);
  5084. // ideally we should set the handler only around actually reading
  5085. // of the directory listing, so we at least reset the handler in
  5086. // FileFind
  5087. FOnFindingFile = Params.OnFindingFile;
  5088. try
  5089. {
  5090. ProcessDirectory(Directory, FileFind, &Params, false, true);
  5091. }
  5092. __finally
  5093. {
  5094. FOnFindingFile = NULL;
  5095. }
  5096. }
  5097. }
  5098. //---------------------------------------------------------------------------
  5099. void __fastcall TTerminal::FilesFind(UnicodeString Directory, const TFileMasks & FileMask,
  5100. TFileFoundEvent OnFileFound, TFindingFileEvent OnFindingFile)
  5101. {
  5102. TFilesFindParams Params;
  5103. Params.FileMask = FileMask;
  5104. Params.OnFileFound = OnFileFound;
  5105. Params.OnFindingFile = OnFindingFile;
  5106. Params.Cancel = false;
  5107. Params.LoopDetector.RecordVisitedDirectory(Directory);
  5108. DoFilesFind(Directory, Params);
  5109. }
  5110. //---------------------------------------------------------------------------
  5111. void __fastcall TTerminal::SpaceAvailable(const UnicodeString Path,
  5112. TSpaceAvailable & ASpaceAvailable)
  5113. {
  5114. DebugAssert(IsCapable[fcCheckingSpaceAvailable]);
  5115. try
  5116. {
  5117. FFileSystem->SpaceAvailable(Path, ASpaceAvailable);
  5118. }
  5119. catch (Exception &E)
  5120. {
  5121. CommandError(&E, FMTLOAD(SPACE_AVAILABLE_ERROR, (Path)));
  5122. }
  5123. }
  5124. //---------------------------------------------------------------------------
  5125. void __fastcall TTerminal::LockFile(const UnicodeString FileName,
  5126. const TRemoteFile * File, void * /*Param*/)
  5127. {
  5128. StartOperationWithFile(FileName, foLock);
  5129. LogEvent(FORMAT(L"Locking file \"%s\".", (FileName)));
  5130. FileModified(File, FileName, true);
  5131. DoLockFile(FileName, File);
  5132. ReactOnCommand(fsLock);
  5133. }
  5134. //---------------------------------------------------------------------------
  5135. void __fastcall TTerminal::DoLockFile(const UnicodeString & FileName, const TRemoteFile * File)
  5136. {
  5137. TRetryOperationLoop RetryLoop(this);
  5138. do
  5139. {
  5140. try
  5141. {
  5142. FFileSystem->LockFile(FileName, File);
  5143. }
  5144. catch(Exception & E)
  5145. {
  5146. RetryLoop.Error(E, FMTLOAD(LOCK_FILE_ERROR, (FileName)));
  5147. }
  5148. }
  5149. while (RetryLoop.Retry());
  5150. }
  5151. //---------------------------------------------------------------------------
  5152. void __fastcall TTerminal::UnlockFile(const UnicodeString FileName,
  5153. const TRemoteFile * File, void * /*Param*/)
  5154. {
  5155. StartOperationWithFile(FileName, foUnlock);
  5156. LogEvent(FORMAT(L"Unlocking file \"%s\".", (FileName)));
  5157. FileModified(File, FileName, true);
  5158. DoUnlockFile(FileName, File);
  5159. ReactOnCommand(fsLock);
  5160. }
  5161. //---------------------------------------------------------------------------
  5162. void __fastcall TTerminal::DoUnlockFile(const UnicodeString & FileName, const TRemoteFile * File)
  5163. {
  5164. TRetryOperationLoop RetryLoop(this);
  5165. do
  5166. {
  5167. try
  5168. {
  5169. FFileSystem->UnlockFile(FileName, File);
  5170. }
  5171. catch(Exception & E)
  5172. {
  5173. RetryLoop.Error(E, FMTLOAD(UNLOCK_FILE_ERROR, (FileName)));
  5174. }
  5175. }
  5176. while (RetryLoop.Retry());
  5177. }
  5178. //---------------------------------------------------------------------------
  5179. void __fastcall TTerminal::LockFiles(TStrings * FileList)
  5180. {
  5181. BeginTransaction();
  5182. try
  5183. {
  5184. ProcessFiles(FileList, foLock, LockFile, NULL);
  5185. }
  5186. __finally
  5187. {
  5188. EndTransaction();
  5189. }
  5190. }
  5191. //---------------------------------------------------------------------------
  5192. void __fastcall TTerminal::UnlockFiles(TStrings * FileList)
  5193. {
  5194. BeginTransaction();
  5195. try
  5196. {
  5197. ProcessFiles(FileList, foUnlock, UnlockFile, NULL);
  5198. }
  5199. __finally
  5200. {
  5201. EndTransaction();
  5202. }
  5203. }
  5204. //---------------------------------------------------------------------------
  5205. const TSessionInfo & __fastcall TTerminal::GetSessionInfo()
  5206. {
  5207. return FFileSystem->GetSessionInfo();
  5208. }
  5209. //---------------------------------------------------------------------------
  5210. const TFileSystemInfo & __fastcall TTerminal::GetFileSystemInfo(bool Retrieve)
  5211. {
  5212. return FFileSystem->GetFileSystemInfo(Retrieve);
  5213. }
  5214. //---------------------------------------------------------------------
  5215. void __fastcall TTerminal::GetSupportedChecksumAlgs(TStrings * Algs)
  5216. {
  5217. FFileSystem->GetSupportedChecksumAlgs(Algs);
  5218. }
  5219. //---------------------------------------------------------------------
  5220. UnicodeString __fastcall TTerminal::GetPassword()
  5221. {
  5222. UnicodeString Result;
  5223. // FRememberedPassword is empty also when stored password was used
  5224. if (FRememberedPassword.IsEmpty())
  5225. {
  5226. Result = SessionData->Password;
  5227. }
  5228. else
  5229. {
  5230. Result = RememberedPassword;
  5231. }
  5232. return Result;
  5233. }
  5234. //---------------------------------------------------------------------
  5235. UnicodeString __fastcall TTerminal::GetRememberedPassword()
  5236. {
  5237. return DecryptPassword(FRememberedPassword);
  5238. }
  5239. //---------------------------------------------------------------------
  5240. UnicodeString __fastcall TTerminal::GetRememberedTunnelPassword()
  5241. {
  5242. return DecryptPassword(FRememberedTunnelPassword);
  5243. }
  5244. //---------------------------------------------------------------------
  5245. bool __fastcall TTerminal::GetStoredCredentialsTried()
  5246. {
  5247. bool Result;
  5248. if (FFileSystem != NULL)
  5249. {
  5250. Result = FFileSystem->GetStoredCredentialsTried();
  5251. }
  5252. else if (FSecureShell != NULL)
  5253. {
  5254. Result = FSecureShell->GetStoredCredentialsTried();
  5255. }
  5256. else
  5257. {
  5258. DebugAssert(FTunnelOpening);
  5259. Result = false;
  5260. }
  5261. return Result;
  5262. }
  5263. //---------------------------------------------------------------------------
  5264. bool __fastcall TTerminal::CopyToRemote(TStrings * FilesToCopy,
  5265. const UnicodeString TargetDir, const TCopyParamType * CopyParam, int Params)
  5266. {
  5267. DebugAssert(FFileSystem);
  5268. DebugAssert(FilesToCopy);
  5269. bool Result = false;
  5270. TOnceDoneOperation OnceDoneOperation = odoIdle;
  5271. try
  5272. {
  5273. __int64 Size;
  5274. // dirty trick: when moving, do not pass copy param to avoid exclude mask
  5275. bool CalculatedSize =
  5276. CalculateLocalFilesSize(
  5277. FilesToCopy, Size,
  5278. (FLAGCLEAR(Params, cpDelete) ? CopyParam : NULL),
  5279. CopyParam->CalculateSize);
  5280. TFileOperationProgressType OperationProgress(&DoProgress, &DoFinished);
  5281. OperationProgress.Start((Params & cpDelete ? foMove : foCopy), osLocal,
  5282. FilesToCopy->Count, Params & cpTemporary, TargetDir, CopyParam->CPSLimit);
  5283. FOperationProgress = &OperationProgress;
  5284. bool CollectingUsage = false;
  5285. try
  5286. {
  5287. if (CalculatedSize)
  5288. {
  5289. if (Configuration->Usage->Collect)
  5290. {
  5291. int CounterSize = TUsage::CalculateCounterSize(Size);
  5292. Configuration->Usage->Inc(L"Uploads");
  5293. Configuration->Usage->Inc(L"UploadedBytes", CounterSize);
  5294. Configuration->Usage->SetMax(L"MaxUploadSize", CounterSize);
  5295. CollectingUsage = true;
  5296. }
  5297. OperationProgress.SetTotalSize(Size);
  5298. }
  5299. UnicodeString UnlockedTargetDir = TranslateLockedPath(TargetDir, false);
  5300. BeginTransaction();
  5301. try
  5302. {
  5303. if (Log->Logging)
  5304. {
  5305. LogEvent(FORMAT(L"Copying %d files/directories to remote directory "
  5306. "\"%s\"", (FilesToCopy->Count, TargetDir)));
  5307. LogEvent(CopyParam->LogStr);
  5308. }
  5309. FFileSystem->CopyToRemote(FilesToCopy, UnlockedTargetDir,
  5310. CopyParam, Params, &OperationProgress, OnceDoneOperation);
  5311. }
  5312. __finally
  5313. {
  5314. if (Active)
  5315. {
  5316. ReactOnCommand(fsCopyToRemote);
  5317. }
  5318. EndTransaction();
  5319. }
  5320. if (OperationProgress.Cancel == csContinue)
  5321. {
  5322. Result = true;
  5323. }
  5324. }
  5325. __finally
  5326. {
  5327. if (CollectingUsage)
  5328. {
  5329. int CounterTime = TimeToSeconds(OperationProgress.TimeElapsed());
  5330. Configuration->Usage->Inc(L"UploadTime", CounterTime);
  5331. Configuration->Usage->SetMax(L"MaxUploadTime", CounterTime);
  5332. }
  5333. OperationProgress.Stop();
  5334. FOperationProgress = NULL;
  5335. }
  5336. }
  5337. catch (Exception &E)
  5338. {
  5339. CommandError(&E, MainInstructions(LoadStr(TOREMOTE_COPY_ERROR)));
  5340. OnceDoneOperation = odoIdle;
  5341. }
  5342. if (OnceDoneOperation != odoIdle)
  5343. {
  5344. CloseOnCompletion(OnceDoneOperation);
  5345. }
  5346. return Result;
  5347. }
  5348. //---------------------------------------------------------------------------
  5349. bool __fastcall TTerminal::CopyToLocal(TStrings * FilesToCopy,
  5350. const UnicodeString TargetDir, const TCopyParamType * CopyParam, int Params)
  5351. {
  5352. DebugAssert(FFileSystem);
  5353. // see scp.c: sink(), tolocal()
  5354. bool Result = false;
  5355. bool OwnsFileList = (FilesToCopy == NULL);
  5356. TOnceDoneOperation OnceDoneOperation = odoIdle;
  5357. try
  5358. {
  5359. if (OwnsFileList)
  5360. {
  5361. FilesToCopy = new TStringList();
  5362. FilesToCopy->Assign(Files->SelectedFiles);
  5363. }
  5364. BeginTransaction();
  5365. try
  5366. {
  5367. __int64 TotalSize;
  5368. bool TotalSizeKnown = false;
  5369. TFileOperationProgressType OperationProgress(&DoProgress, &DoFinished);
  5370. ExceptionOnFail = true;
  5371. try
  5372. {
  5373. // dirty trick: when moving, do not pass copy param to avoid exclude mask
  5374. if (CalculateFilesSize(
  5375. FilesToCopy, TotalSize, csIgnoreErrors,
  5376. (FLAGCLEAR(Params, cpDelete) ? CopyParam : NULL),
  5377. CopyParam->CalculateSize, NULL))
  5378. {
  5379. TotalSizeKnown = true;
  5380. }
  5381. }
  5382. __finally
  5383. {
  5384. ExceptionOnFail = false;
  5385. }
  5386. OperationProgress.Start((Params & cpDelete ? foMove : foCopy), osRemote,
  5387. FilesToCopy->Count, Params & cpTemporary, TargetDir, CopyParam->CPSLimit);
  5388. FOperationProgress = &OperationProgress;
  5389. bool CollectingUsage = false;
  5390. try
  5391. {
  5392. if (TotalSizeKnown)
  5393. {
  5394. if (Configuration->Usage->Collect)
  5395. {
  5396. int CounterTotalSize = TUsage::CalculateCounterSize(TotalSize);
  5397. Configuration->Usage->Inc(L"Downloads");
  5398. Configuration->Usage->Inc(L"DownloadedBytes", CounterTotalSize);
  5399. Configuration->Usage->SetMax(L"MaxDownloadSize", CounterTotalSize);
  5400. CollectingUsage = true;
  5401. }
  5402. OperationProgress.SetTotalSize(TotalSize);
  5403. }
  5404. try
  5405. {
  5406. try
  5407. {
  5408. if (Log->Logging)
  5409. {
  5410. LogEvent(FORMAT(L"Copying %d files/directories to local directory "
  5411. "\"%s\"", (FilesToCopy->Count, TargetDir)));
  5412. LogEvent(CopyParam->LogStr);
  5413. }
  5414. FFileSystem->CopyToLocal(FilesToCopy, TargetDir, CopyParam, Params,
  5415. &OperationProgress, OnceDoneOperation);
  5416. }
  5417. __finally
  5418. {
  5419. if (Active)
  5420. {
  5421. ReactOnCommand(fsCopyToLocal);
  5422. }
  5423. }
  5424. }
  5425. catch (Exception &E)
  5426. {
  5427. CommandError(&E, MainInstructions(LoadStr(TOLOCAL_COPY_ERROR)));
  5428. OnceDoneOperation = odoIdle;
  5429. }
  5430. if (OperationProgress.Cancel == csContinue)
  5431. {
  5432. Result = true;
  5433. }
  5434. }
  5435. __finally
  5436. {
  5437. if (CollectingUsage)
  5438. {
  5439. int CounterTime = TimeToSeconds(OperationProgress.TimeElapsed());
  5440. Configuration->Usage->Inc(L"DownloadTime", CounterTime);
  5441. Configuration->Usage->SetMax(L"MaxDownloadTime", CounterTime);
  5442. }
  5443. FOperationProgress = NULL;
  5444. OperationProgress.Stop();
  5445. }
  5446. }
  5447. __finally
  5448. {
  5449. // If session is still active (no fatal error) we reload directory
  5450. // by calling EndTransaction
  5451. EndTransaction();
  5452. }
  5453. }
  5454. __finally
  5455. {
  5456. if (OwnsFileList) delete FilesToCopy;
  5457. }
  5458. if (OnceDoneOperation != odoIdle)
  5459. {
  5460. CloseOnCompletion(OnceDoneOperation);
  5461. }
  5462. return Result;
  5463. }
  5464. //---------------------------------------------------------------------------
  5465. void __fastcall TTerminal::ReflectSettings()
  5466. {
  5467. DebugAssert(FLog != NULL);
  5468. FLog->ReflectSettings();
  5469. DebugAssert(FActionLog != NULL);
  5470. FActionLog->ReflectSettings();
  5471. // also FTunnelLog ?
  5472. }
  5473. //---------------------------------------------------------------------------
  5474. void __fastcall TTerminal::CollectUsage()
  5475. {
  5476. switch (SessionData->FSProtocol)
  5477. {
  5478. case fsSCPonly:
  5479. Configuration->Usage->Inc(L"OpenedSessionsSCP");
  5480. break;
  5481. case fsSFTP:
  5482. case fsSFTPonly:
  5483. Configuration->Usage->Inc(L"OpenedSessionsSFTP");
  5484. break;
  5485. case fsFTP:
  5486. if (SessionData->Ftps == ftpsNone)
  5487. {
  5488. Configuration->Usage->Inc(L"OpenedSessionsFTP");
  5489. }
  5490. else
  5491. {
  5492. Configuration->Usage->Inc(L"OpenedSessionsFTPS");
  5493. }
  5494. break;
  5495. case fsWebDAV:
  5496. if (SessionData->Ftps == ftpsNone)
  5497. {
  5498. Configuration->Usage->Inc(L"OpenedSessionsWebDAV");
  5499. }
  5500. else
  5501. {
  5502. Configuration->Usage->Inc(L"OpenedSessionsWebDAVS");
  5503. }
  5504. break;
  5505. }
  5506. if (Configuration->Logging && Configuration->LogToFile)
  5507. {
  5508. Configuration->Usage->Inc(L"OpenedSessionsLogToFile2");
  5509. }
  5510. if (Configuration->LogActions)
  5511. {
  5512. Configuration->Usage->Inc(L"OpenedSessionsXmlLog");
  5513. }
  5514. std::unique_ptr<TSessionData> FactoryDefaults(new TSessionData(L""));
  5515. if (!SessionData->IsSame(FactoryDefaults.get(), true))
  5516. {
  5517. Configuration->Usage->Inc(L"OpenedSessionsAdvanced");
  5518. }
  5519. if (SessionData->ProxyMethod != ::pmNone)
  5520. {
  5521. Configuration->Usage->Inc(L"OpenedSessionsProxy");
  5522. }
  5523. if (SessionData->FtpProxyLogonType > 0)
  5524. {
  5525. Configuration->Usage->Inc(L"OpenedSessionsFtpProxy");
  5526. }
  5527. FCollectFileSystemUsage = true;
  5528. }
  5529. //---------------------------------------------------------------------------
  5530. static UnicodeString __fastcall FormatCertificateData(const UnicodeString & Fingerprint, int Failures)
  5531. {
  5532. return FORMAT(L"%s;%2.2X", (Fingerprint, Failures));
  5533. }
  5534. //---------------------------------------------------------------------------
  5535. bool __fastcall TTerminal::VerifyCertificate(
  5536. const UnicodeString & CertificateStorageKey, const UnicodeString & SiteKey,
  5537. const UnicodeString & Fingerprint,
  5538. const UnicodeString & CertificateSubject, int Failures)
  5539. {
  5540. bool Result = false;
  5541. UnicodeString CertificateData = FormatCertificateData(Fingerprint, Failures);
  5542. std::unique_ptr<THierarchicalStorage> Storage(Configuration->CreateConfigStorage());
  5543. Storage->AccessMode = smRead;
  5544. if (Storage->OpenSubKey(CertificateStorageKey, false))
  5545. {
  5546. if (Storage->ValueExists(SiteKey))
  5547. {
  5548. UnicodeString CachedCertificateData = Storage->ReadString(SiteKey, L"");
  5549. if (CertificateData == CachedCertificateData)
  5550. {
  5551. LogEvent(FORMAT(L"Certificate for \"%s\" matches cached fingerprint and failures", (CertificateSubject)));
  5552. Result = true;
  5553. }
  5554. }
  5555. else if (Storage->ValueExists(Fingerprint))
  5556. {
  5557. LogEvent(FORMAT(L"Certificate for \"%s\" matches legacy cached fingerprint", (CertificateSubject)));
  5558. Result = true;
  5559. }
  5560. }
  5561. if (!Result)
  5562. {
  5563. UnicodeString Buf = SessionData->HostKey;
  5564. while (!Result && !Buf.IsEmpty())
  5565. {
  5566. UnicodeString ExpectedKey = CutToChar(Buf, L';', false);
  5567. if (ExpectedKey == L"*")
  5568. {
  5569. UnicodeString Message = LoadStr(ANY_CERTIFICATE);
  5570. Information(Message, true);
  5571. Log->Add(llException, Message);
  5572. Result = true;
  5573. }
  5574. else if (ExpectedKey == Fingerprint)
  5575. {
  5576. LogEvent(FORMAT(L"Certificate for \"%s\" matches configured fingerprint", (CertificateSubject)));
  5577. Result = true;
  5578. }
  5579. }
  5580. }
  5581. return Result;
  5582. }
  5583. //---------------------------------------------------------------------------
  5584. void __fastcall TTerminal::CacheCertificate(const UnicodeString & CertificateStorageKey,
  5585. const UnicodeString & SiteKey, const UnicodeString & Fingerprint, int Failures)
  5586. {
  5587. UnicodeString CertificateData = FormatCertificateData(Fingerprint, Failures);
  5588. std::unique_ptr<THierarchicalStorage> Storage(Configuration->CreateConfigStorage());
  5589. Storage->AccessMode = smReadWrite;
  5590. if (Storage->OpenSubKey(CertificateStorageKey, true))
  5591. {
  5592. Storage->WriteString(SiteKey, CertificateData);
  5593. }
  5594. }
  5595. //---------------------------------------------------------------------------
  5596. void __fastcall TTerminal::CollectTlsUsage(const UnicodeString & TlsVersionStr)
  5597. {
  5598. // see SSL_get_version() in OpenSSL ssl_lib.c
  5599. if (TlsVersionStr == L"TLSv1.2")
  5600. {
  5601. Configuration->Usage->Inc(L"OpenedSessionsTLS12");
  5602. }
  5603. else if (TlsVersionStr == L"TLSv1.1")
  5604. {
  5605. Configuration->Usage->Inc(L"OpenedSessionsTLS11");
  5606. }
  5607. else if (TlsVersionStr == L"TLSv1")
  5608. {
  5609. Configuration->Usage->Inc(L"OpenedSessionsTLS10");
  5610. }
  5611. else if (TlsVersionStr == L"SSLv3")
  5612. {
  5613. Configuration->Usage->Inc(L"OpenedSessionsSSL30");
  5614. }
  5615. else if (TlsVersionStr == L"SSLv2")
  5616. {
  5617. Configuration->Usage->Inc(L"OpenedSessionsSSL20");
  5618. }
  5619. else
  5620. {
  5621. DebugFail();
  5622. }
  5623. }
  5624. //---------------------------------------------------------------------------
  5625. bool __fastcall TTerminal::LoadTlsCertificate(X509 *& Certificate, EVP_PKEY *& PrivateKey)
  5626. {
  5627. bool Result = !SessionData->TlsCertificateFile.IsEmpty();
  5628. if (Result)
  5629. {
  5630. UnicodeString Passphrase = SessionData->Passphrase;
  5631. // Inspired by neon's ne_ssl_clicert_read
  5632. bool Retry;
  5633. do
  5634. {
  5635. Retry = false;
  5636. bool WrongPassphrase = false;
  5637. ParseCertificate(SessionData->TlsCertificateFile, Passphrase, Certificate, PrivateKey, WrongPassphrase);
  5638. if (WrongPassphrase)
  5639. {
  5640. if (Passphrase.IsEmpty())
  5641. {
  5642. LogEvent(L"Certificate is encrypted, need passphrase");
  5643. Information(LoadStr(CLIENT_CERTIFICATE_LOADING), false);
  5644. }
  5645. else
  5646. {
  5647. Information(LoadStr(CERTIFICATE_DECODE_ERROR_INFO), false);
  5648. }
  5649. Passphrase = L"";
  5650. if (PromptUser(
  5651. SessionData, pkPassphrase,
  5652. LoadStr(CERTIFICATE_PASSPHRASE_TITLE), L"",
  5653. LoadStr(CERTIFICATE_PASSPHRASE_PROMPT), false, 0, Passphrase))
  5654. {
  5655. Retry = true;
  5656. }
  5657. else
  5658. {
  5659. Result = false;
  5660. }
  5661. }
  5662. }
  5663. while (Retry);
  5664. }
  5665. return Result;
  5666. }
  5667. //---------------------------------------------------------------------------
  5668. UnicodeString __fastcall TTerminal::GetBaseFileName(UnicodeString FileName)
  5669. {
  5670. if (FSessionData->TrimVMSVersions)
  5671. {
  5672. int P = FileName.LastDelimiter(L";");
  5673. if (P > 0)
  5674. {
  5675. FileName.SetLength(P - 1);
  5676. }
  5677. }
  5678. return FileName;
  5679. }
  5680. //---------------------------------------------------------------------------
  5681. UnicodeString __fastcall TTerminal::ChangeFileName(const TCopyParamType * CopyParam,
  5682. UnicodeString FileName, TOperationSide Side, bool FirstLevel)
  5683. {
  5684. FileName = GetBaseFileName(FileName);
  5685. FileName = CopyParam->ChangeFileName(FileName, Side, FirstLevel);
  5686. return FileName;
  5687. }
  5688. //---------------------------------------------------------------------------
  5689. bool __fastcall TTerminal::CanRecurseToDirectory(const TRemoteFile * File)
  5690. {
  5691. return !File->IsSymLink || FSessionData->FollowDirectorySymlinks;
  5692. }
  5693. //---------------------------------------------------------------------------
  5694. //---------------------------------------------------------------------------
  5695. __fastcall TSecondaryTerminal::TSecondaryTerminal(TTerminal * MainTerminal,
  5696. TSessionData * ASessionData, TConfiguration * Configuration, const UnicodeString & Name) :
  5697. TTerminal(ASessionData, Configuration),
  5698. FMainTerminal(MainTerminal)
  5699. {
  5700. Log->Parent = FMainTerminal->Log;
  5701. Log->Name = Name;
  5702. ActionLog->Enabled = false;
  5703. SessionData->NonPersistant();
  5704. DebugAssert(FMainTerminal != NULL);
  5705. if (!FMainTerminal->UserName.IsEmpty())
  5706. {
  5707. SessionData->UserName = FMainTerminal->UserName;
  5708. }
  5709. }
  5710. //---------------------------------------------------------------------------
  5711. void __fastcall TSecondaryTerminal::UpdateFromMain()
  5712. {
  5713. if ((FFileSystem != NULL) && (FMainTerminal->FFileSystem != NULL))
  5714. {
  5715. FFileSystem->UpdateFromMain(FMainTerminal->FFileSystem);
  5716. }
  5717. }
  5718. //---------------------------------------------------------------------------
  5719. void __fastcall TSecondaryTerminal::DirectoryLoaded(TRemoteFileList * FileList)
  5720. {
  5721. FMainTerminal->DirectoryLoaded(FileList);
  5722. DebugAssert(FileList != NULL);
  5723. }
  5724. //---------------------------------------------------------------------------
  5725. void __fastcall TSecondaryTerminal::DirectoryModified(const UnicodeString Path,
  5726. bool SubDirs)
  5727. {
  5728. // clear cache of main terminal
  5729. FMainTerminal->DirectoryModified(Path, SubDirs);
  5730. }
  5731. //---------------------------------------------------------------------------
  5732. TTerminal * __fastcall TSecondaryTerminal::GetPasswordSource()
  5733. {
  5734. return FMainTerminal;
  5735. }
  5736. //---------------------------------------------------------------------------
  5737. __fastcall TTerminalList::TTerminalList(TConfiguration * AConfiguration) :
  5738. TObjectList()
  5739. {
  5740. DebugAssert(AConfiguration);
  5741. FConfiguration = AConfiguration;
  5742. }
  5743. //---------------------------------------------------------------------------
  5744. __fastcall TTerminalList::~TTerminalList()
  5745. {
  5746. DebugAssert(Count == 0);
  5747. }
  5748. //---------------------------------------------------------------------------
  5749. TTerminal * __fastcall TTerminalList::CreateTerminal(TSessionData * Data)
  5750. {
  5751. return new TTerminal(Data, FConfiguration);
  5752. }
  5753. //---------------------------------------------------------------------------
  5754. TTerminal * __fastcall TTerminalList::NewTerminal(TSessionData * Data)
  5755. {
  5756. TTerminal * Terminal = CreateTerminal(Data);
  5757. Add(Terminal);
  5758. return Terminal;
  5759. }
  5760. //---------------------------------------------------------------------------
  5761. void __fastcall TTerminalList::FreeTerminal(TTerminal * Terminal)
  5762. {
  5763. DebugAssert(IndexOf(Terminal) >= 0);
  5764. Remove(Terminal);
  5765. }
  5766. //---------------------------------------------------------------------------
  5767. void __fastcall TTerminalList::FreeAndNullTerminal(TTerminal * & Terminal)
  5768. {
  5769. TTerminal * T = Terminal;
  5770. Terminal = NULL;
  5771. FreeTerminal(T);
  5772. }
  5773. //---------------------------------------------------------------------------
  5774. TTerminal * __fastcall TTerminalList::GetTerminal(int Index)
  5775. {
  5776. return dynamic_cast<TTerminal *>(Items[Index]);
  5777. }
  5778. //---------------------------------------------------------------------------
  5779. void __fastcall TTerminalList::Idle()
  5780. {
  5781. TTerminal * Terminal;
  5782. for (int i = 0; i < Count; i++)
  5783. {
  5784. Terminal = Terminals[i];
  5785. if (Terminal->Status == ssOpened)
  5786. {
  5787. Terminal->Idle();
  5788. }
  5789. }
  5790. }
  5791. //---------------------------------------------------------------------------
  5792. void __fastcall TTerminalList::RecryptPasswords()
  5793. {
  5794. for (int Index = 0; Index < Count; Index++)
  5795. {
  5796. Terminals[Index]->RecryptPasswords();
  5797. }
  5798. }