Terminal.cpp 189 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139
  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. Result.Download = Result.General | cpaNoClearArchive |
  3062. cpaNoIgnorePermErrors |
  3063. // May be already set in General flags, but it's unconditional here
  3064. cpaNoRights | cpaNoRemoveCtrlZ | cpaNoRemoveBOM;
  3065. Result.Upload = Result.General | cpaNoPreserveReadOnly |
  3066. FLAGMASK(!IsCapable[fcPreservingTimestampUpload], cpaNoPreserveTime);
  3067. return Result;
  3068. }
  3069. //---------------------------------------------------------------------------
  3070. bool __fastcall TTerminal::IsRecycledFile(UnicodeString FileName)
  3071. {
  3072. bool Result = !SessionData->RecycleBinPath.IsEmpty();
  3073. if (Result)
  3074. {
  3075. UnicodeString Path = UnixExtractFilePath(FileName);
  3076. if (Path.IsEmpty())
  3077. {
  3078. Path = CurrentDirectory;
  3079. }
  3080. Result = UnixSamePath(Path, SessionData->RecycleBinPath);
  3081. }
  3082. return Result;
  3083. }
  3084. //---------------------------------------------------------------------------
  3085. void __fastcall TTerminal::RecycleFile(UnicodeString FileName,
  3086. const TRemoteFile * File)
  3087. {
  3088. if (FileName.IsEmpty())
  3089. {
  3090. DebugAssert(File != NULL);
  3091. FileName = File->FileName;
  3092. }
  3093. if (!IsRecycledFile(FileName))
  3094. {
  3095. LogEvent(FORMAT(L"Moving file \"%s\" to remote recycle bin '%s'.",
  3096. (FileName, SessionData->RecycleBinPath)));
  3097. TMoveFileParams Params;
  3098. Params.Target = SessionData->RecycleBinPath;
  3099. Params.FileMask = FORMAT(L"*-%s.*", (FormatDateTime(L"yyyymmdd-hhnnss", Now())));
  3100. MoveFile(FileName, File, &Params);
  3101. }
  3102. }
  3103. //---------------------------------------------------------------------------
  3104. bool __fastcall TTerminal::TryStartOperationWithFile(
  3105. const UnicodeString & FileName, TFileOperation Operation1, TFileOperation Operation2)
  3106. {
  3107. bool Result = true;
  3108. if ((OperationProgress != NULL) &&
  3109. ((OperationProgress->Operation == Operation1) ||
  3110. ((Operation2 != foNone) && (OperationProgress->Operation == Operation2))))
  3111. {
  3112. if (OperationProgress->Cancel != csContinue)
  3113. {
  3114. Result = false;
  3115. }
  3116. else
  3117. {
  3118. OperationProgress->SetFile(FileName);
  3119. }
  3120. }
  3121. return Result;
  3122. }
  3123. //---------------------------------------------------------------------------
  3124. void __fastcall TTerminal::StartOperationWithFile(
  3125. const UnicodeString & FileName, TFileOperation Operation1, TFileOperation Operation2)
  3126. {
  3127. if (!TryStartOperationWithFile(FileName, Operation1, Operation2))
  3128. {
  3129. Abort();
  3130. }
  3131. }
  3132. //---------------------------------------------------------------------------
  3133. void __fastcall TTerminal::DeleteFile(UnicodeString FileName,
  3134. const TRemoteFile * File, void * AParams)
  3135. {
  3136. if (FileName.IsEmpty() && File)
  3137. {
  3138. FileName = File->FileName;
  3139. }
  3140. StartOperationWithFile(FileName, foDelete);
  3141. int Params = (AParams != NULL) ? *((int*)AParams) : 0;
  3142. bool Recycle =
  3143. FLAGCLEAR(Params, dfForceDelete) &&
  3144. (SessionData->DeleteToRecycleBin != FLAGSET(Params, dfAlternative)) &&
  3145. !SessionData->RecycleBinPath.IsEmpty();
  3146. if (Recycle && !IsRecycledFile(FileName))
  3147. {
  3148. RecycleFile(FileName, File);
  3149. }
  3150. else
  3151. {
  3152. LogEvent(FORMAT(L"Deleting file \"%s\".", (FileName)));
  3153. FileModified(File, FileName, true);
  3154. DoDeleteFile(FileName, File, Params);
  3155. ReactOnCommand(fsDeleteFile);
  3156. }
  3157. }
  3158. //---------------------------------------------------------------------------
  3159. void __fastcall TTerminal::DoDeleteFile(const UnicodeString FileName,
  3160. const TRemoteFile * File, int Params)
  3161. {
  3162. TRetryOperationLoop RetryLoop(this);
  3163. do
  3164. {
  3165. TRmSessionAction Action(ActionLog, AbsolutePath(FileName, true));
  3166. try
  3167. {
  3168. DebugAssert(FFileSystem);
  3169. // 'File' parameter: SFTPFileSystem needs to know if file is file or directory
  3170. FFileSystem->DeleteFile(FileName, File, Params, Action);
  3171. }
  3172. catch(Exception & E)
  3173. {
  3174. RetryLoop.Error(E, Action, FMTLOAD(DELETE_FILE_ERROR, (FileName)));
  3175. }
  3176. }
  3177. while (RetryLoop.Retry());
  3178. }
  3179. //---------------------------------------------------------------------------
  3180. bool __fastcall TTerminal::DeleteFiles(TStrings * FilesToDelete, int Params)
  3181. {
  3182. // TODO: avoid resolving symlinks while reading subdirectories.
  3183. // Resolving does not work anyway for relative symlinks in subdirectories
  3184. // (at least for SFTP).
  3185. return ProcessFiles(FilesToDelete, foDelete, DeleteFile, &Params);
  3186. }
  3187. //---------------------------------------------------------------------------
  3188. void __fastcall TTerminal::DeleteLocalFile(UnicodeString FileName,
  3189. const TRemoteFile * /*File*/, void * Params)
  3190. {
  3191. StartOperationWithFile(FileName, foDelete);
  3192. if (OnDeleteLocalFile == NULL)
  3193. {
  3194. RecursiveDeleteFileChecked(FileName, false);
  3195. }
  3196. else
  3197. {
  3198. OnDeleteLocalFile(FileName, FLAGSET(*((int*)Params), dfAlternative));
  3199. }
  3200. }
  3201. //---------------------------------------------------------------------------
  3202. bool __fastcall TTerminal::DeleteLocalFiles(TStrings * FileList, int Params)
  3203. {
  3204. return ProcessFiles(FileList, foDelete, DeleteLocalFile, &Params, osLocal);
  3205. }
  3206. //---------------------------------------------------------------------------
  3207. void __fastcall TTerminal::CustomCommandOnFile(UnicodeString FileName,
  3208. const TRemoteFile * File, void * AParams)
  3209. {
  3210. TCustomCommandParams * Params = ((TCustomCommandParams *)AParams);
  3211. if (FileName.IsEmpty() && File)
  3212. {
  3213. FileName = File->FileName;
  3214. }
  3215. StartOperationWithFile(FileName, foCustomCommand);
  3216. LogEvent(FORMAT(L"Executing custom command \"%s\" (%d) on file \"%s\".",
  3217. (Params->Command, Params->Params, FileName)));
  3218. FileModified(File, FileName);
  3219. DoCustomCommandOnFile(FileName, File, Params->Command, Params->Params,
  3220. Params->OutputEvent);
  3221. ReactOnCommand(fsAnyCommand);
  3222. }
  3223. //---------------------------------------------------------------------------
  3224. void __fastcall TTerminal::DoCustomCommandOnFile(UnicodeString FileName,
  3225. const TRemoteFile * File, UnicodeString Command, int Params,
  3226. TCaptureOutputEvent OutputEvent)
  3227. {
  3228. TRetryOperationLoop RetryLoop(this);
  3229. do
  3230. {
  3231. try
  3232. {
  3233. if (IsCapable[fcAnyCommand])
  3234. {
  3235. DebugAssert(FFileSystem);
  3236. DebugAssert(fcShellAnyCommand);
  3237. FFileSystem->CustomCommandOnFile(FileName, File, Command, Params, OutputEvent);
  3238. }
  3239. else
  3240. {
  3241. DebugAssert(CommandSessionOpened);
  3242. DebugAssert(FCommandSession->FSProtocol == cfsSCP);
  3243. LogEvent(L"Executing custom command on command session.");
  3244. if (FCommandSession->CurrentDirectory != CurrentDirectory)
  3245. {
  3246. FCommandSession->CurrentDirectory = CurrentDirectory;
  3247. // We are likely in transaction, so ReadCurrentDirectory won't get called
  3248. // until transaction ends. But we need to know CurrentDirectory to
  3249. // expand !/ pattern.
  3250. // Doing this only, when current directory of the main and secondary shell differs,
  3251. // what would be the case before the first file in transaction.
  3252. // Otherwise we would be reading pwd before every time as the
  3253. // CustomCommandOnFile on its own sets FReadCurrentDirectoryPending
  3254. if (FCommandSession->FReadCurrentDirectoryPending)
  3255. {
  3256. FCommandSession->ReadCurrentDirectory();
  3257. }
  3258. }
  3259. FCommandSession->FFileSystem->CustomCommandOnFile(FileName, File, Command,
  3260. Params, OutputEvent);
  3261. }
  3262. }
  3263. catch(Exception & E)
  3264. {
  3265. RetryLoop.Error(E, FMTLOAD(CUSTOM_COMMAND_ERROR, (Command, FileName)));
  3266. }
  3267. }
  3268. while (RetryLoop.Retry());
  3269. }
  3270. //---------------------------------------------------------------------------
  3271. void __fastcall TTerminal::CustomCommandOnFiles(UnicodeString Command,
  3272. int Params, TStrings * Files, TCaptureOutputEvent OutputEvent)
  3273. {
  3274. if (!TRemoteCustomCommand().IsFileListCommand(Command))
  3275. {
  3276. TCustomCommandParams AParams;
  3277. AParams.Command = Command;
  3278. AParams.Params = Params;
  3279. AParams.OutputEvent = OutputEvent;
  3280. ProcessFiles(Files, foCustomCommand, CustomCommandOnFile, &AParams);
  3281. }
  3282. else
  3283. {
  3284. UnicodeString FileList;
  3285. for (int i = 0; i < Files->Count; i++)
  3286. {
  3287. TRemoteFile * File = static_cast<TRemoteFile *>(Files->Objects[i]);
  3288. bool Dir = File->IsDirectory && !File->IsSymLink;
  3289. if (!Dir || FLAGSET(Params, ccApplyToDirectories))
  3290. {
  3291. if (!FileList.IsEmpty())
  3292. {
  3293. FileList += L" ";
  3294. }
  3295. FileList += L"\"" + ShellDelimitStr(Files->Strings[i], L'"') + L"\"";
  3296. }
  3297. }
  3298. TCustomCommandData Data(this);
  3299. UnicodeString Cmd =
  3300. TRemoteCustomCommand(Data, CurrentDirectory, L"", FileList).
  3301. Complete(Command, true);
  3302. DoAnyCommand(Cmd, OutputEvent, NULL);
  3303. }
  3304. }
  3305. //---------------------------------------------------------------------------
  3306. void __fastcall TTerminal::ChangeFileProperties(UnicodeString FileName,
  3307. const TRemoteFile * File, /*const TRemoteProperties*/ void * Properties)
  3308. {
  3309. TRemoteProperties * RProperties = (TRemoteProperties *)Properties;
  3310. DebugAssert(RProperties && !RProperties->Valid.Empty());
  3311. if (FileName.IsEmpty() && File)
  3312. {
  3313. FileName = File->FileName;
  3314. }
  3315. StartOperationWithFile(FileName, foSetProperties);
  3316. if (Log->Logging)
  3317. {
  3318. LogEvent(FORMAT(L"Changing properties of \"%s\" (%s)",
  3319. (FileName, BooleanToEngStr(RProperties->Recursive))));
  3320. if (RProperties->Valid.Contains(vpRights))
  3321. {
  3322. LogEvent(FORMAT(L" - mode: \"%s\"", (RProperties->Rights.ModeStr)));
  3323. }
  3324. if (RProperties->Valid.Contains(vpGroup))
  3325. {
  3326. LogEvent(FORMAT(L" - group: %s", (RProperties->Group.LogText)));
  3327. }
  3328. if (RProperties->Valid.Contains(vpOwner))
  3329. {
  3330. LogEvent(FORMAT(L" - owner: %s", (RProperties->Owner.LogText)));
  3331. }
  3332. if (RProperties->Valid.Contains(vpModification))
  3333. {
  3334. LogEvent(FORMAT(L" - modification: \"%s\"",
  3335. (FormatDateTime(L"dddddd tt",
  3336. UnixToDateTime(RProperties->Modification, SessionData->DSTMode)))));
  3337. }
  3338. if (RProperties->Valid.Contains(vpLastAccess))
  3339. {
  3340. LogEvent(FORMAT(L" - last access: \"%s\"",
  3341. (FormatDateTime(L"dddddd tt",
  3342. UnixToDateTime(RProperties->LastAccess, SessionData->DSTMode)))));
  3343. }
  3344. }
  3345. FileModified(File, FileName);
  3346. DoChangeFileProperties(FileName, File, RProperties);
  3347. ReactOnCommand(fsChangeProperties);
  3348. }
  3349. //---------------------------------------------------------------------------
  3350. void __fastcall TTerminal::DoChangeFileProperties(const UnicodeString FileName,
  3351. const TRemoteFile * File, const TRemoteProperties * Properties)
  3352. {
  3353. TRetryOperationLoop RetryLoop(this);
  3354. do
  3355. {
  3356. TChmodSessionAction Action(ActionLog, AbsolutePath(FileName, true));
  3357. try
  3358. {
  3359. DebugAssert(FFileSystem);
  3360. FFileSystem->ChangeFileProperties(FileName, File, Properties, Action);
  3361. }
  3362. catch(Exception & E)
  3363. {
  3364. RetryLoop.Error(E, Action, FMTLOAD(CHANGE_PROPERTIES_ERROR, (FileName)));
  3365. }
  3366. }
  3367. while (RetryLoop.Retry());
  3368. }
  3369. //---------------------------------------------------------------------------
  3370. void __fastcall TTerminal::ChangeFilesProperties(TStrings * FileList,
  3371. const TRemoteProperties * Properties)
  3372. {
  3373. AnnounceFileListOperation();
  3374. ProcessFiles(FileList, foSetProperties, ChangeFileProperties, (void *)Properties);
  3375. }
  3376. //---------------------------------------------------------------------------
  3377. bool __fastcall TTerminal::LoadFilesProperties(TStrings * FileList)
  3378. {
  3379. // see comment in TSFTPFileSystem::IsCapable
  3380. bool Result =
  3381. IsCapable[fcLoadingAdditionalProperties] &&
  3382. FFileSystem->LoadFilesProperties(FileList);
  3383. if (Result && SessionData->CacheDirectories &&
  3384. (FileList->Count > 0) &&
  3385. (dynamic_cast<TRemoteFile *>(FileList->Objects[0])->Directory == FFiles))
  3386. {
  3387. AddCachedFileList(FFiles);
  3388. }
  3389. return Result;
  3390. }
  3391. //---------------------------------------------------------------------------
  3392. void __fastcall TTerminal::CalculateFileSize(UnicodeString FileName,
  3393. const TRemoteFile * File, /*TCalculateSizeParams*/ void * Param)
  3394. {
  3395. DebugAssert(Param);
  3396. DebugAssert(File);
  3397. TCalculateSizeParams * AParams = static_cast<TCalculateSizeParams*>(Param);
  3398. if (FileName.IsEmpty())
  3399. {
  3400. FileName = File->FileName;
  3401. }
  3402. if (!TryStartOperationWithFile(FileName, foCalculateSize))
  3403. {
  3404. AParams->Result = false;
  3405. Abort();
  3406. }
  3407. bool AllowTransfer = (AParams->CopyParam == NULL);
  3408. if (!AllowTransfer)
  3409. {
  3410. TFileMasks::TParams MaskParams;
  3411. MaskParams.Size = File->Size;
  3412. MaskParams.Modification = File->Modification;
  3413. UnicodeString BaseFileName =
  3414. GetBaseFileName(UnixExcludeTrailingBackslash(File->FullFileName));
  3415. AllowTransfer = AParams->CopyParam->AllowTransfer(
  3416. BaseFileName, osRemote, File->IsDirectory, MaskParams);
  3417. }
  3418. if (AllowTransfer)
  3419. {
  3420. if (File->IsDirectory)
  3421. {
  3422. if (!File->IsSymLink)
  3423. {
  3424. if (!AParams->AllowDirs)
  3425. {
  3426. AParams->Result = false;
  3427. }
  3428. else
  3429. {
  3430. LogEvent(FORMAT(L"Getting size of directory \"%s\"", (FileName)));
  3431. // pass in full path so we get it back in file list for AllowTransfer() exclusion
  3432. DoCalculateDirectorySize(File->FullFileName, File, AParams);
  3433. }
  3434. }
  3435. if (AParams->Stats != NULL)
  3436. {
  3437. AParams->Stats->Directories++;
  3438. }
  3439. }
  3440. else
  3441. {
  3442. AParams->Size += File->Size;
  3443. if (AParams->Stats != NULL)
  3444. {
  3445. AParams->Stats->Files++;
  3446. }
  3447. }
  3448. if ((AParams->Stats != NULL) && File->IsSymLink)
  3449. {
  3450. AParams->Stats->SymLinks++;
  3451. }
  3452. }
  3453. }
  3454. //---------------------------------------------------------------------------
  3455. void __fastcall TTerminal::DoCalculateDirectorySize(const UnicodeString FileName,
  3456. const TRemoteFile * /*File*/, TCalculateSizeParams * Params)
  3457. {
  3458. TRetryOperationLoop RetryLoop(this);
  3459. do
  3460. {
  3461. try
  3462. {
  3463. ProcessDirectory(FileName, CalculateFileSize, Params);
  3464. }
  3465. catch(Exception & E)
  3466. {
  3467. if (!Active || ((Params->Params & csIgnoreErrors) == 0))
  3468. {
  3469. RetryLoop.Error(E, FMTLOAD(CALCULATE_SIZE_ERROR, (FileName)));
  3470. }
  3471. }
  3472. }
  3473. while (RetryLoop.Retry());
  3474. }
  3475. //---------------------------------------------------------------------------
  3476. bool __fastcall TTerminal::CalculateFilesSize(TStrings * FileList,
  3477. __int64 & Size, int Params, const TCopyParamType * CopyParam,
  3478. bool AllowDirs, TCalculateSizeStats * Stats)
  3479. {
  3480. // With FTP protocol, we may use DSIZ command from
  3481. // draft-peterson-streamlined-ftp-command-extensions-10
  3482. // Implemented by Serv-U FTP.
  3483. TValueRestorer<bool> UseBusyCursorRestorer(FUseBusyCursor);
  3484. FUseBusyCursor = false;
  3485. TCalculateSizeParams Param;
  3486. Param.Size = 0;
  3487. Param.Params = Params;
  3488. Param.CopyParam = CopyParam;
  3489. Param.Stats = Stats;
  3490. Param.AllowDirs = AllowDirs;
  3491. Param.Result = true;
  3492. ProcessFiles(FileList, foCalculateSize, CalculateFileSize, &Param);
  3493. Size = Param.Size;
  3494. return Param.Result;
  3495. }
  3496. //---------------------------------------------------------------------------
  3497. void __fastcall TTerminal::CalculateFilesChecksum(const UnicodeString & Alg,
  3498. TStrings * FileList, TStrings * Checksums,
  3499. TCalculatedChecksumEvent OnCalculatedChecksum)
  3500. {
  3501. FFileSystem->CalculateFilesChecksum(Alg, FileList, Checksums, OnCalculatedChecksum);
  3502. }
  3503. //---------------------------------------------------------------------------
  3504. void __fastcall TTerminal::RenameFile(const UnicodeString FileName,
  3505. const UnicodeString NewName)
  3506. {
  3507. LogEvent(FORMAT(L"Renaming file \"%s\" to \"%s\".", (FileName, NewName)));
  3508. DoRenameFile(FileName, NewName, false);
  3509. ReactOnCommand(fsRenameFile);
  3510. }
  3511. //---------------------------------------------------------------------------
  3512. void __fastcall TTerminal::RenameFile(const TRemoteFile * File,
  3513. const UnicodeString NewName, bool CheckExistence)
  3514. {
  3515. DebugAssert(File && File->Directory == FFiles);
  3516. bool Proceed = true;
  3517. // if filename doesn't contain path, we check for existence of file
  3518. if ((File->FileName != NewName) && CheckExistence &&
  3519. Configuration->ConfirmOverwriting &&
  3520. UnixSamePath(CurrentDirectory, FFiles->Directory))
  3521. {
  3522. TRemoteFile * DuplicateFile = FFiles->FindFile(NewName);
  3523. if (DuplicateFile)
  3524. {
  3525. UnicodeString QuestionFmt;
  3526. if (DuplicateFile->IsDirectory)
  3527. {
  3528. QuestionFmt = LoadStr(DIRECTORY_OVERWRITE);
  3529. }
  3530. else
  3531. {
  3532. QuestionFmt = LoadStr(FILE_OVERWRITE);
  3533. }
  3534. TQueryParams Params(qpNeverAskAgainCheck);
  3535. UnicodeString Question = MainInstructions(FORMAT(QuestionFmt, (NewName)));
  3536. unsigned int Result = QueryUser(Question, NULL,
  3537. qaYes | qaNo, &Params);
  3538. if (Result == qaNeverAskAgain)
  3539. {
  3540. Proceed = true;
  3541. Configuration->ConfirmOverwriting = false;
  3542. }
  3543. else
  3544. {
  3545. Proceed = (Result == qaYes);
  3546. }
  3547. }
  3548. }
  3549. if (Proceed)
  3550. {
  3551. FileModified(File, File->FileName);
  3552. RenameFile(File->FileName, NewName);
  3553. }
  3554. }
  3555. //---------------------------------------------------------------------------
  3556. void __fastcall TTerminal::DoRenameFile(const UnicodeString FileName,
  3557. const UnicodeString NewName, bool Move)
  3558. {
  3559. TRetryOperationLoop RetryLoop(this);
  3560. do
  3561. {
  3562. TMvSessionAction Action(ActionLog, AbsolutePath(FileName, true), AbsolutePath(NewName, true));
  3563. try
  3564. {
  3565. DebugAssert(FFileSystem);
  3566. FFileSystem->RenameFile(FileName, NewName);
  3567. }
  3568. catch(Exception & E)
  3569. {
  3570. UnicodeString Message = FMTLOAD(Move ? MOVE_FILE_ERROR : RENAME_FILE_ERROR, (FileName, NewName));
  3571. RetryLoop.Error(E, Action, Message);
  3572. }
  3573. }
  3574. while (RetryLoop.Retry());
  3575. }
  3576. //---------------------------------------------------------------------------
  3577. void __fastcall TTerminal::MoveFile(const UnicodeString FileName,
  3578. const TRemoteFile * File, /*const TMoveFileParams*/ void * Param)
  3579. {
  3580. StartOperationWithFile(FileName, foRemoteMove, foDelete);
  3581. DebugAssert(Param != NULL);
  3582. const TMoveFileParams & Params = *static_cast<const TMoveFileParams*>(Param);
  3583. UnicodeString NewName = UnixIncludeTrailingBackslash(Params.Target) +
  3584. MaskFileName(UnixExtractFileName(FileName), Params.FileMask);
  3585. LogEvent(FORMAT(L"Moving file \"%s\" to \"%s\".", (FileName, NewName)));
  3586. FileModified(File, FileName);
  3587. DoRenameFile(FileName, NewName, true);
  3588. ReactOnCommand(fsMoveFile);
  3589. }
  3590. //---------------------------------------------------------------------------
  3591. bool __fastcall TTerminal::MoveFiles(TStrings * FileList, const UnicodeString Target,
  3592. const UnicodeString FileMask)
  3593. {
  3594. TMoveFileParams Params;
  3595. Params.Target = Target;
  3596. Params.FileMask = FileMask;
  3597. DirectoryModified(Target, true);
  3598. bool Result;
  3599. BeginTransaction();
  3600. try
  3601. {
  3602. Result = ProcessFiles(FileList, foRemoteMove, MoveFile, &Params);
  3603. }
  3604. __finally
  3605. {
  3606. if (Active)
  3607. {
  3608. UnicodeString WithTrailing = UnixIncludeTrailingBackslash(CurrentDirectory);
  3609. bool PossiblyMoved = false;
  3610. // check if we was moving current directory.
  3611. // this is just optimization to avoid checking existence of current
  3612. // directory after each move operation.
  3613. for (int Index = 0; !PossiblyMoved && (Index < FileList->Count); Index++)
  3614. {
  3615. const TRemoteFile * File =
  3616. dynamic_cast<const TRemoteFile *>(FileList->Objects[Index]);
  3617. // File can be NULL, and filename may not be full path,
  3618. // but currently this is the only way we can move (at least in GUI)
  3619. // current directory
  3620. if ((File != NULL) &&
  3621. File->IsDirectory &&
  3622. ((CurrentDirectory.SubString(1, FileList->Strings[Index].Length()) == FileList->Strings[Index]) &&
  3623. ((FileList->Strings[Index].Length() == CurrentDirectory.Length()) ||
  3624. (CurrentDirectory[FileList->Strings[Index].Length() + 1] == L'/'))))
  3625. {
  3626. PossiblyMoved = true;
  3627. }
  3628. }
  3629. if (PossiblyMoved && !FileExists(CurrentDirectory))
  3630. {
  3631. UnicodeString NearestExisting = CurrentDirectory;
  3632. do
  3633. {
  3634. NearestExisting = UnixExtractFileDir(NearestExisting);
  3635. }
  3636. while (!IsUnixRootPath(NearestExisting) && !FileExists(NearestExisting));
  3637. ChangeDirectory(NearestExisting);
  3638. }
  3639. }
  3640. EndTransaction();
  3641. }
  3642. return Result;
  3643. }
  3644. //---------------------------------------------------------------------------
  3645. void __fastcall TTerminal::DoCopyFile(const UnicodeString FileName,
  3646. const UnicodeString NewName)
  3647. {
  3648. TRetryOperationLoop RetryLoop(this);
  3649. do
  3650. {
  3651. try
  3652. {
  3653. DebugAssert(FFileSystem);
  3654. if (IsCapable[fcRemoteCopy])
  3655. {
  3656. FFileSystem->CopyFile(FileName, NewName);
  3657. }
  3658. else
  3659. {
  3660. DebugAssert(CommandSessionOpened);
  3661. DebugAssert(FCommandSession->FSProtocol == cfsSCP);
  3662. LogEvent(L"Copying file on command session.");
  3663. FCommandSession->CurrentDirectory = CurrentDirectory;
  3664. FCommandSession->FFileSystem->CopyFile(FileName, NewName);
  3665. }
  3666. }
  3667. catch(Exception & E)
  3668. {
  3669. RetryLoop.Error(E, FMTLOAD(COPY_FILE_ERROR, (FileName, NewName)));
  3670. }
  3671. }
  3672. while (RetryLoop.Retry());
  3673. }
  3674. //---------------------------------------------------------------------------
  3675. void __fastcall TTerminal::CopyFile(const UnicodeString FileName,
  3676. const TRemoteFile * /*File*/, /*const TMoveFileParams*/ void * Param)
  3677. {
  3678. StartOperationWithFile(FileName, foRemoteCopy);
  3679. DebugAssert(Param != NULL);
  3680. const TMoveFileParams & Params = *static_cast<const TMoveFileParams*>(Param);
  3681. UnicodeString NewName = UnixIncludeTrailingBackslash(Params.Target) +
  3682. MaskFileName(UnixExtractFileName(FileName), Params.FileMask);
  3683. LogEvent(FORMAT(L"Copying file \"%s\" to \"%s\".", (FileName, NewName)));
  3684. DoCopyFile(FileName, NewName);
  3685. ReactOnCommand(fsCopyFile);
  3686. }
  3687. //---------------------------------------------------------------------------
  3688. bool __fastcall TTerminal::CopyFiles(TStrings * FileList, const UnicodeString Target,
  3689. const UnicodeString FileMask)
  3690. {
  3691. TMoveFileParams Params;
  3692. Params.Target = Target;
  3693. Params.FileMask = FileMask;
  3694. DirectoryModified(Target, true);
  3695. return ProcessFiles(FileList, foRemoteCopy, CopyFile, &Params);
  3696. }
  3697. //---------------------------------------------------------------------------
  3698. void __fastcall TTerminal::CreateDirectory(const UnicodeString DirName,
  3699. const TRemoteProperties * Properties)
  3700. {
  3701. DebugAssert(FFileSystem);
  3702. EnsureNonExistence(DirName);
  3703. FileModified(NULL, DirName);
  3704. LogEvent(FORMAT(L"Creating directory \"%s\".", (DirName)));
  3705. DoCreateDirectory(DirName);
  3706. if ((Properties != NULL) && !Properties->Valid.Empty())
  3707. {
  3708. DoChangeFileProperties(DirName, NULL, Properties);
  3709. }
  3710. ReactOnCommand(fsCreateDirectory);
  3711. }
  3712. //---------------------------------------------------------------------------
  3713. void __fastcall TTerminal::DoCreateDirectory(const UnicodeString DirName)
  3714. {
  3715. TRetryOperationLoop RetryLoop(this);
  3716. do
  3717. {
  3718. TMkdirSessionAction Action(ActionLog, AbsolutePath(DirName, true));
  3719. try
  3720. {
  3721. DebugAssert(FFileSystem);
  3722. FFileSystem->CreateDirectory(DirName);
  3723. }
  3724. catch(Exception & E)
  3725. {
  3726. RetryLoop.Error(E, Action, FMTLOAD(CREATE_DIR_ERROR, (DirName)));
  3727. }
  3728. }
  3729. while (RetryLoop.Retry());
  3730. }
  3731. //---------------------------------------------------------------------------
  3732. void __fastcall TTerminal::CreateLink(const UnicodeString FileName,
  3733. const UnicodeString PointTo, bool Symbolic)
  3734. {
  3735. DebugAssert(FFileSystem);
  3736. EnsureNonExistence(FileName);
  3737. if (SessionData->CacheDirectories)
  3738. {
  3739. DirectoryModified(CurrentDirectory, false);
  3740. }
  3741. LogEvent(FORMAT(L"Creating link \"%s\" to \"%s\" (symbolic: %s).",
  3742. (FileName, PointTo, BooleanToEngStr(Symbolic))));
  3743. DoCreateLink(FileName, PointTo, Symbolic);
  3744. ReactOnCommand(fsCreateDirectory);
  3745. }
  3746. //---------------------------------------------------------------------------
  3747. void __fastcall TTerminal::DoCreateLink(const UnicodeString FileName,
  3748. const UnicodeString PointTo, bool Symbolic)
  3749. {
  3750. TRetryOperationLoop RetryLoop(this);
  3751. do
  3752. {
  3753. try
  3754. {
  3755. DebugAssert(FFileSystem);
  3756. FFileSystem->CreateLink(FileName, PointTo, Symbolic);
  3757. }
  3758. catch(Exception & E)
  3759. {
  3760. RetryLoop.Error(E, FMTLOAD(CREATE_LINK_ERROR, (FileName)));
  3761. }
  3762. }
  3763. while (RetryLoop.Retry());
  3764. }
  3765. //---------------------------------------------------------------------------
  3766. void __fastcall TTerminal::HomeDirectory()
  3767. {
  3768. DebugAssert(FFileSystem);
  3769. try
  3770. {
  3771. LogEvent(L"Changing directory to home directory.");
  3772. FFileSystem->HomeDirectory();
  3773. ReactOnCommand(fsHomeDirectory);
  3774. }
  3775. catch (Exception &E)
  3776. {
  3777. CommandError(&E, LoadStr(CHANGE_HOMEDIR_ERROR));
  3778. }
  3779. }
  3780. //---------------------------------------------------------------------------
  3781. void __fastcall TTerminal::ChangeDirectory(const UnicodeString Directory)
  3782. {
  3783. DebugAssert(FFileSystem);
  3784. try
  3785. {
  3786. UnicodeString CachedDirectory;
  3787. DebugAssert(!SessionData->CacheDirectoryChanges || (FDirectoryChangesCache != NULL));
  3788. // never use directory change cache during startup, this ensures, we never
  3789. // end-up initially in non-existing directory
  3790. if ((Status == ssOpened) &&
  3791. SessionData->CacheDirectoryChanges &&
  3792. FDirectoryChangesCache->GetDirectoryChange(PeekCurrentDirectory(),
  3793. Directory, CachedDirectory))
  3794. {
  3795. LogEvent(FORMAT(L"Cached directory change via \"%s\" to \"%s\".",
  3796. (Directory, CachedDirectory)));
  3797. FFileSystem->CachedChangeDirectory(CachedDirectory);
  3798. }
  3799. else
  3800. {
  3801. LogEvent(FORMAT(L"Changing directory to \"%s\".", (Directory)));
  3802. FFileSystem->ChangeDirectory(Directory);
  3803. }
  3804. FLastDirectoryChange = Directory;
  3805. ReactOnCommand(fsChangeDirectory);
  3806. }
  3807. catch (Exception &E)
  3808. {
  3809. CommandError(&E, FMTLOAD(CHANGE_DIR_ERROR, (Directory)));
  3810. }
  3811. }
  3812. //---------------------------------------------------------------------------
  3813. void __fastcall TTerminal::LookupUsersGroups()
  3814. {
  3815. if (!FUsersGroupsLookedup && (SessionData->LookupUserGroups != asOff) &&
  3816. IsCapable[fcUserGroupListing])
  3817. {
  3818. DebugAssert(FFileSystem);
  3819. try
  3820. {
  3821. FUsersGroupsLookedup = true;
  3822. LogEvent(L"Looking up groups and users.");
  3823. FFileSystem->LookupUsersGroups();
  3824. ReactOnCommand(fsLookupUsersGroups);
  3825. if (Log->Logging)
  3826. {
  3827. FGroups.Log(this, L"groups");
  3828. FMembership.Log(this, L"membership");
  3829. FUsers.Log(this, L"users");
  3830. }
  3831. }
  3832. catch (Exception &E)
  3833. {
  3834. if (!Active || (SessionData->LookupUserGroups == asOn))
  3835. {
  3836. CommandError(&E, LoadStr(LOOKUP_GROUPS_ERROR));
  3837. }
  3838. }
  3839. }
  3840. }
  3841. //---------------------------------------------------------------------------
  3842. bool __fastcall TTerminal::AllowedAnyCommand(const UnicodeString Command)
  3843. {
  3844. return !Command.Trim().IsEmpty();
  3845. }
  3846. //---------------------------------------------------------------------------
  3847. bool __fastcall TTerminal::GetCommandSessionOpened()
  3848. {
  3849. // consider secondary terminal open in "ready" state only
  3850. // so we never do keepalives on it until it is completely initialized
  3851. return (FCommandSession != NULL) &&
  3852. (FCommandSession->Status == ssOpened);
  3853. }
  3854. //---------------------------------------------------------------------------
  3855. TTerminal * __fastcall TTerminal::GetCommandSession()
  3856. {
  3857. if ((FCommandSession != NULL) && !FCommandSession->Active)
  3858. {
  3859. SAFE_DESTROY(FCommandSession);
  3860. }
  3861. if (FCommandSession == NULL)
  3862. {
  3863. // transaction cannot be started yet to allow proper matching transaction
  3864. // levels between main and command session
  3865. DebugAssert(FInTransaction == 0);
  3866. try
  3867. {
  3868. FCommandSession = new TSecondaryTerminal(this, SessionData,
  3869. Configuration, L"Shell");
  3870. FCommandSession->AutoReadDirectory = false;
  3871. TSessionData * CommandSessionData = FCommandSession->FSessionData;
  3872. CommandSessionData->RemoteDirectory = CurrentDirectory;
  3873. CommandSessionData->FSProtocol = fsSCPonly;
  3874. CommandSessionData->ClearAliases = false;
  3875. CommandSessionData->UnsetNationalVars = false;
  3876. CommandSessionData->LookupUserGroups = asOff;
  3877. FCommandSession->FExceptionOnFail = FExceptionOnFail;
  3878. FCommandSession->OnQueryUser = OnQueryUser;
  3879. FCommandSession->OnPromptUser = OnPromptUser;
  3880. FCommandSession->OnShowExtendedException = OnShowExtendedException;
  3881. FCommandSession->OnProgress = OnProgress;
  3882. FCommandSession->OnFinished = OnFinished;
  3883. FCommandSession->OnInformation = OnInformation;
  3884. FCommandSession->OnClose = CommandSessionClose;
  3885. // do not copy OnDisplayBanner to avoid it being displayed
  3886. }
  3887. catch(...)
  3888. {
  3889. SAFE_DESTROY(FCommandSession);
  3890. throw;
  3891. }
  3892. }
  3893. return FCommandSession;
  3894. }
  3895. //---------------------------------------------------------------------------
  3896. void __fastcall TTerminal::CommandSessionClose(TObject * /*Sender*/)
  3897. {
  3898. // Keep the states in sync.
  3899. // This is particularly to invoke ours OnClose,
  3900. // So that it is triggered before Reopen is called
  3901. Close();
  3902. }
  3903. //---------------------------------------------------------------------------
  3904. void __fastcall TTerminal::AnyCommand(const UnicodeString Command,
  3905. TCaptureOutputEvent OutputEvent)
  3906. {
  3907. class TOutputProxy
  3908. {
  3909. public:
  3910. __fastcall TOutputProxy(TCallSessionAction & Action, TCaptureOutputEvent OutputEvent) :
  3911. FAction(Action),
  3912. FOutputEvent(OutputEvent)
  3913. {
  3914. }
  3915. void __fastcall Output(const UnicodeString & Str, TCaptureOutputType OutputType)
  3916. {
  3917. switch (OutputType)
  3918. {
  3919. case cotOutput:
  3920. FAction.AddOutput(Str, false);
  3921. break;
  3922. case cotError:
  3923. FAction.AddOutput(Str, true);
  3924. break;
  3925. case cotExitCode:
  3926. FAction.ExitCode(StrToInt(Str));
  3927. break;
  3928. }
  3929. if (FOutputEvent != NULL)
  3930. {
  3931. FOutputEvent(Str, OutputType);
  3932. }
  3933. }
  3934. private:
  3935. TCallSessionAction & FAction;
  3936. TCaptureOutputEvent FOutputEvent;
  3937. };
  3938. TCallSessionAction Action(ActionLog, Command, CurrentDirectory);
  3939. TOutputProxy ProxyOutputEvent(Action, OutputEvent);
  3940. DoAnyCommand(Command, ProxyOutputEvent.Output, &Action);
  3941. }
  3942. //---------------------------------------------------------------------------
  3943. void __fastcall TTerminal::DoAnyCommand(const UnicodeString Command,
  3944. TCaptureOutputEvent OutputEvent, TCallSessionAction * Action)
  3945. {
  3946. DebugAssert(FFileSystem);
  3947. try
  3948. {
  3949. DirectoryModified(CurrentDirectory, false);
  3950. if (IsCapable[fcAnyCommand])
  3951. {
  3952. LogEvent(L"Executing user defined command.");
  3953. FFileSystem->AnyCommand(Command, OutputEvent);
  3954. }
  3955. else
  3956. {
  3957. DebugAssert(CommandSessionOpened);
  3958. DebugAssert(FCommandSession->FSProtocol == cfsSCP);
  3959. LogEvent(L"Executing user defined command on command session.");
  3960. FCommandSession->CurrentDirectory = CurrentDirectory;
  3961. FCommandSession->FFileSystem->AnyCommand(Command, OutputEvent);
  3962. FCommandSession->FFileSystem->ReadCurrentDirectory();
  3963. // synchronize pwd (by purpose we lose transaction optimization here)
  3964. ChangeDirectory(FCommandSession->CurrentDirectory);
  3965. }
  3966. ReactOnCommand(fsAnyCommand);
  3967. }
  3968. catch (Exception &E)
  3969. {
  3970. if (Action != NULL)
  3971. {
  3972. RollbackAction(*Action, NULL, &E);
  3973. }
  3974. if (ExceptionOnFail || (E.InheritsFrom(__classid(EFatal)))) throw;
  3975. else HandleExtendedException(&E);
  3976. }
  3977. }
  3978. //---------------------------------------------------------------------------
  3979. bool __fastcall TTerminal::DoCreateLocalFile(const UnicodeString FileName,
  3980. TFileOperationProgressType * OperationProgress, HANDLE * AHandle,
  3981. bool NoConfirmation)
  3982. {
  3983. bool Result = true;
  3984. bool Done;
  3985. unsigned int CreateAttr = FILE_ATTRIBUTE_NORMAL;
  3986. do
  3987. {
  3988. *AHandle = CreateFile(ApiPath(FileName).c_str(), GENERIC_WRITE, FILE_SHARE_READ,
  3989. NULL, CREATE_ALWAYS, CreateAttr, 0);
  3990. Done = (*AHandle != INVALID_HANDLE_VALUE);
  3991. if (!Done)
  3992. {
  3993. // save the error, otherwise it gets overwritten by call to FileExists
  3994. int LastError = GetLastError();
  3995. int FileAttr;
  3996. if (::FileExists(ApiPath(FileName)) &&
  3997. (((FileAttr = FileGetAttrFix(ApiPath(FileName))) & (faReadOnly | faHidden)) != 0))
  3998. {
  3999. if (FLAGSET(FileAttr, faReadOnly))
  4000. {
  4001. if (OperationProgress->BatchOverwrite == boNone)
  4002. {
  4003. Result = false;
  4004. }
  4005. else if ((OperationProgress->BatchOverwrite != boAll) && !NoConfirmation)
  4006. {
  4007. unsigned int Answer;
  4008. {
  4009. TSuspendFileOperationProgress Suspend(OperationProgress);
  4010. Answer = QueryUser(
  4011. MainInstructions(FMTLOAD(READ_ONLY_OVERWRITE, (FileName))), NULL,
  4012. qaYes | qaNo | qaCancel | qaYesToAll | qaNoToAll, 0);
  4013. }
  4014. switch (Answer) {
  4015. case qaYesToAll: OperationProgress->BatchOverwrite = boAll; break;
  4016. case qaCancel: OperationProgress->Cancel = csCancel; // continue on next case
  4017. case qaNoToAll: OperationProgress->BatchOverwrite = boNone;
  4018. case qaNo: Result = false; break;
  4019. }
  4020. }
  4021. }
  4022. else
  4023. {
  4024. DebugAssert(FLAGSET(FileAttr, faHidden));
  4025. Result = true;
  4026. }
  4027. if (Result)
  4028. {
  4029. CreateAttr |=
  4030. FLAGMASK(FLAGSET(FileAttr, faHidden), FILE_ATTRIBUTE_HIDDEN) |
  4031. FLAGMASK(FLAGSET(FileAttr, faReadOnly), FILE_ATTRIBUTE_READONLY);
  4032. FILE_OPERATION_LOOP_BEGIN
  4033. {
  4034. if (FileSetAttr(ApiPath(FileName), FileAttr & ~(faReadOnly | faHidden)) != 0)
  4035. {
  4036. RaiseLastOSError();
  4037. }
  4038. }
  4039. FILE_OPERATION_LOOP_END(FMTLOAD(CANT_SET_ATTRS, (FileName)));
  4040. }
  4041. else
  4042. {
  4043. Done = true;
  4044. }
  4045. }
  4046. else
  4047. {
  4048. RaiseLastOSError(LastError);
  4049. }
  4050. }
  4051. }
  4052. while (!Done);
  4053. return Result;
  4054. }
  4055. //---------------------------------------------------------------------------
  4056. bool __fastcall TTerminal::CreateLocalFile(const UnicodeString FileName,
  4057. TFileOperationProgressType * OperationProgress, HANDLE * AHandle,
  4058. bool NoConfirmation)
  4059. {
  4060. DebugAssert(AHandle);
  4061. bool Result = true;
  4062. FILE_OPERATION_LOOP_BEGIN
  4063. {
  4064. Result = DoCreateLocalFile(FileName, OperationProgress, AHandle, NoConfirmation);
  4065. }
  4066. FILE_OPERATION_LOOP_END(FMTLOAD(CREATE_FILE_ERROR, (FileName)));
  4067. return Result;
  4068. }
  4069. //---------------------------------------------------------------------------
  4070. void __fastcall TTerminal::OpenLocalFile(const UnicodeString FileName,
  4071. unsigned int Access, int * AAttrs, HANDLE * AHandle, __int64 * ACTime,
  4072. __int64 * AMTime, __int64 * AATime, __int64 * ASize,
  4073. bool TryWriteReadOnly)
  4074. {
  4075. int Attrs = 0;
  4076. HANDLE Handle = 0;
  4077. FILE_OPERATION_LOOP_BEGIN
  4078. {
  4079. UnicodeString FileNameApi = ApiPath(FileName);
  4080. Attrs = FileGetAttrFix(FileNameApi);
  4081. if (Attrs < 0)
  4082. {
  4083. RaiseLastOSError();
  4084. }
  4085. }
  4086. FILE_OPERATION_LOOP_END(FMTLOAD(FILE_NOT_EXISTS, (FileName)));
  4087. if (FLAGCLEAR(Attrs, faDirectory) || (AHandle == NULL))
  4088. {
  4089. bool NoHandle = false;
  4090. if (!TryWriteReadOnly && (Access == GENERIC_WRITE) &&
  4091. ((Attrs & faReadOnly) != 0))
  4092. {
  4093. Access = GENERIC_READ;
  4094. NoHandle = true;
  4095. }
  4096. FILE_OPERATION_LOOP_BEGIN
  4097. {
  4098. DWORD Flags = FLAGMASK(FLAGSET(Attrs, faDirectory), FILE_FLAG_BACKUP_SEMANTICS);
  4099. Handle = CreateFile(ApiPath(FileName).c_str(), Access,
  4100. Access == GENERIC_READ ? FILE_SHARE_READ | FILE_SHARE_WRITE : FILE_SHARE_READ,
  4101. NULL, OPEN_EXISTING, Flags, 0);
  4102. if (Handle == INVALID_HANDLE_VALUE)
  4103. {
  4104. Handle = 0;
  4105. RaiseLastOSError();
  4106. }
  4107. }
  4108. FILE_OPERATION_LOOP_END(FMTLOAD(OPENFILE_ERROR, (FileName)));
  4109. try
  4110. {
  4111. if (AATime || AMTime || ACTime)
  4112. {
  4113. FILETIME ATime;
  4114. FILETIME MTime;
  4115. FILETIME CTime;
  4116. // Get last file access and modification time
  4117. FILE_OPERATION_LOOP_BEGIN
  4118. {
  4119. THROWOSIFFALSE(GetFileTime(Handle, &CTime, &ATime, &MTime));
  4120. }
  4121. FILE_OPERATION_LOOP_END(FMTLOAD(CANT_GET_ATTRS, (FileName)));
  4122. if (ACTime)
  4123. {
  4124. *ACTime = ConvertTimestampToUnixSafe(CTime, SessionData->DSTMode);
  4125. }
  4126. if (AATime)
  4127. {
  4128. *AATime = ConvertTimestampToUnixSafe(ATime, SessionData->DSTMode);
  4129. }
  4130. if (AMTime)
  4131. {
  4132. *AMTime = ConvertTimestampToUnix(MTime, SessionData->DSTMode);
  4133. }
  4134. }
  4135. if (ASize)
  4136. {
  4137. // Get file size
  4138. FILE_OPERATION_LOOP_BEGIN
  4139. {
  4140. unsigned long LSize;
  4141. unsigned long HSize;
  4142. LSize = GetFileSize(Handle, &HSize);
  4143. if ((LSize == 0xFFFFFFFF) && (GetLastError() != NO_ERROR)) RaiseLastOSError();
  4144. *ASize = (__int64(HSize) << 32) + LSize;
  4145. }
  4146. FILE_OPERATION_LOOP_END(FMTLOAD(CANT_GET_ATTRS, (FileName)));
  4147. }
  4148. if ((AHandle == NULL) || NoHandle)
  4149. {
  4150. CloseHandle(Handle);
  4151. Handle = NULL;
  4152. }
  4153. }
  4154. catch(...)
  4155. {
  4156. CloseHandle(Handle);
  4157. throw;
  4158. }
  4159. }
  4160. if (AAttrs) *AAttrs = Attrs;
  4161. if (AHandle) *AHandle = Handle;
  4162. }
  4163. //---------------------------------------------------------------------------
  4164. bool __fastcall TTerminal::AllowLocalFileTransfer(UnicodeString FileName,
  4165. const TCopyParamType * CopyParam, TFileOperationProgressType * OperationProgress)
  4166. {
  4167. bool Result = true;
  4168. // optimization
  4169. if (Log->Logging || !CopyParam->AllowAnyTransfer())
  4170. {
  4171. WIN32_FIND_DATA FindData;
  4172. HANDLE Handle;
  4173. FILE_OPERATION_LOOP_BEGIN
  4174. {
  4175. Handle = FindFirstFile(ApiPath(ExcludeTrailingBackslash(FileName)).c_str(), &FindData);
  4176. if (Handle == INVALID_HANDLE_VALUE)
  4177. {
  4178. RaiseLastOSError();
  4179. }
  4180. }
  4181. FILE_OPERATION_LOOP_END(FMTLOAD(FILE_NOT_EXISTS, (FileName)));
  4182. ::FindClose(Handle);
  4183. bool Directory = FLAGSET(FindData.dwFileAttributes, FILE_ATTRIBUTE_DIRECTORY);
  4184. TFileMasks::TParams Params;
  4185. // SearchRec.Size in C++B2010 is __int64,
  4186. // so we should be able to use it instead of FindData.nFileSize*
  4187. Params.Size =
  4188. (static_cast<__int64>(FindData.nFileSizeHigh) << 32) +
  4189. FindData.nFileSizeLow;
  4190. Params.Modification = FileTimeToDateTime(FindData.ftLastWriteTime);
  4191. UnicodeString BaseFileName = GetBaseFileName(FileName);
  4192. if (!CopyParam->AllowTransfer(BaseFileName, osLocal, Directory, Params))
  4193. {
  4194. LogEvent(FORMAT(L"File \"%s\" excluded from transfer", (FileName)));
  4195. Result = false;
  4196. }
  4197. else if (CopyParam->SkipTransfer(FileName, Directory))
  4198. {
  4199. OperationProgress->AddSkippedFileSize(Params.Size);
  4200. Result = false;
  4201. }
  4202. if (Result)
  4203. {
  4204. LogFileDetails(FileName, Params.Modification, Params.Size);
  4205. }
  4206. }
  4207. return Result;
  4208. }
  4209. //---------------------------------------------------------------------------
  4210. void __fastcall TTerminal::MakeLocalFileList(const UnicodeString FileName,
  4211. const TSearchRec Rec, void * Param)
  4212. {
  4213. TMakeLocalFileListParams & Params = *static_cast<TMakeLocalFileListParams*>(Param);
  4214. bool Directory = FLAGSET(Rec.Attr, faDirectory);
  4215. if (Directory && Params.Recursive)
  4216. {
  4217. ProcessLocalDirectory(FileName, MakeLocalFileList, &Params);
  4218. }
  4219. if (!Directory || Params.IncludeDirs)
  4220. {
  4221. Params.FileList->Add(FileName);
  4222. if (Params.FileTimes != NULL)
  4223. {
  4224. Params.FileTimes->push_back(const_cast<TSearchRec &>(Rec).TimeStamp);
  4225. }
  4226. }
  4227. }
  4228. //---------------------------------------------------------------------------
  4229. void __fastcall TTerminal::CalculateLocalFileSize(const UnicodeString FileName,
  4230. const TSearchRec Rec, /*TCalculateSizeParams*/ void * Params)
  4231. {
  4232. TCalculateSizeParams * AParams = static_cast<TCalculateSizeParams*>(Params);
  4233. bool Dir = FLAGSET(Rec.Attr, faDirectory);
  4234. bool AllowTransfer = (AParams->CopyParam == NULL);
  4235. // SearchRec.Size in C++B2010 is __int64,
  4236. // so we should be able to use it instead of FindData.nFileSize*
  4237. __int64 Size =
  4238. (static_cast<__int64>(Rec.FindData.nFileSizeHigh) << 32) +
  4239. Rec.FindData.nFileSizeLow;
  4240. if (!AllowTransfer)
  4241. {
  4242. TFileMasks::TParams MaskParams;
  4243. MaskParams.Size = Size;
  4244. MaskParams.Modification = FileTimeToDateTime(Rec.FindData.ftLastWriteTime);
  4245. UnicodeString BaseFileName = GetBaseFileName(FileName);
  4246. AllowTransfer = AParams->CopyParam->AllowTransfer(BaseFileName, osLocal, Dir, MaskParams);
  4247. }
  4248. if (AllowTransfer)
  4249. {
  4250. if (!Dir)
  4251. {
  4252. AParams->Size += Size;
  4253. }
  4254. else
  4255. {
  4256. ProcessLocalDirectory(FileName, CalculateLocalFileSize, Params);
  4257. }
  4258. }
  4259. StartOperationWithFile(FileName, foCalculateSize);
  4260. }
  4261. //---------------------------------------------------------------------------
  4262. bool __fastcall TTerminal::CalculateLocalFilesSize(TStrings * FileList,
  4263. __int64 & Size, const TCopyParamType * CopyParam, bool AllowDirs)
  4264. {
  4265. bool Result = true;
  4266. TFileOperationProgressType OperationProgress(&DoProgress, &DoFinished);
  4267. TOnceDoneOperation OnceDoneOperation = odoIdle;
  4268. OperationProgress.Start(foCalculateSize, osLocal, FileList->Count);
  4269. try
  4270. {
  4271. TCalculateSizeParams Params;
  4272. Params.Size = 0;
  4273. Params.Params = 0;
  4274. Params.CopyParam = CopyParam;
  4275. DebugAssert(!FOperationProgress);
  4276. FOperationProgress = &OperationProgress;
  4277. for (int Index = 0; Result && (Index < FileList->Count); Index++)
  4278. {
  4279. UnicodeString FileName = FileList->Strings[Index];
  4280. TSearchRec Rec;
  4281. if (FileSearchRec(FileName, Rec))
  4282. {
  4283. if (FLAGSET(Rec.Attr, faDirectory) && !AllowDirs)
  4284. {
  4285. Result = false;
  4286. }
  4287. else
  4288. {
  4289. CalculateLocalFileSize(FileName, Rec, &Params);
  4290. OperationProgress.Finish(FileName, true, OnceDoneOperation);
  4291. }
  4292. }
  4293. }
  4294. Size = Params.Size;
  4295. }
  4296. __finally
  4297. {
  4298. FOperationProgress = NULL;
  4299. OperationProgress.Stop();
  4300. }
  4301. if (OnceDoneOperation != odoIdle)
  4302. {
  4303. CloseOnCompletion(OnceDoneOperation);
  4304. }
  4305. return Result;
  4306. }
  4307. //---------------------------------------------------------------------------
  4308. struct TSynchronizeFileData
  4309. {
  4310. bool Modified;
  4311. bool New;
  4312. bool IsDirectory;
  4313. TSynchronizeChecklist::TItem::TFileInfo Info;
  4314. TSynchronizeChecklist::TItem::TFileInfo MatchingRemoteFile;
  4315. TRemoteFile * MatchingRemoteFileFile;
  4316. int MatchingRemoteFileImageIndex;
  4317. FILETIME LocalLastWriteTime;
  4318. };
  4319. //---------------------------------------------------------------------------
  4320. const int sfFirstLevel = 0x01;
  4321. struct TSynchronizeData
  4322. {
  4323. UnicodeString LocalDirectory;
  4324. UnicodeString RemoteDirectory;
  4325. TTerminal::TSynchronizeMode Mode;
  4326. int Params;
  4327. TSynchronizeDirectory OnSynchronizeDirectory;
  4328. TSynchronizeOptions * Options;
  4329. int Flags;
  4330. TStringList * LocalFileList;
  4331. const TCopyParamType * CopyParam;
  4332. TSynchronizeChecklist * Checklist;
  4333. };
  4334. //---------------------------------------------------------------------------
  4335. TSynchronizeChecklist * __fastcall TTerminal::SynchronizeCollect(const UnicodeString LocalDirectory,
  4336. const UnicodeString RemoteDirectory, TSynchronizeMode Mode,
  4337. const TCopyParamType * CopyParam, int Params,
  4338. TSynchronizeDirectory OnSynchronizeDirectory,
  4339. TSynchronizeOptions * Options)
  4340. {
  4341. TValueRestorer<bool> UseBusyCursorRestorer(FUseBusyCursor);
  4342. FUseBusyCursor = false;
  4343. TSynchronizeChecklist * Checklist = new TSynchronizeChecklist();
  4344. try
  4345. {
  4346. DoSynchronizeCollectDirectory(LocalDirectory, RemoteDirectory, Mode,
  4347. CopyParam, Params, OnSynchronizeDirectory, Options, sfFirstLevel,
  4348. Checklist);
  4349. Checklist->Sort();
  4350. }
  4351. catch(...)
  4352. {
  4353. delete Checklist;
  4354. throw;
  4355. }
  4356. return Checklist;
  4357. }
  4358. //---------------------------------------------------------------------------
  4359. static void __fastcall AddFlagName(UnicodeString & ParamsStr, int & Params, int Param, const UnicodeString & Name)
  4360. {
  4361. if (FLAGSET(Params, Param))
  4362. {
  4363. AddToList(ParamsStr, Name, ", ");
  4364. }
  4365. Params &= ~Param;
  4366. }
  4367. //---------------------------------------------------------------------------
  4368. UnicodeString __fastcall TTerminal::SynchronizeModeStr(TSynchronizeMode Mode)
  4369. {
  4370. UnicodeString ModeStr;
  4371. switch (Mode)
  4372. {
  4373. case smRemote:
  4374. ModeStr = L"Remote";
  4375. break;
  4376. case smLocal:
  4377. ModeStr = L"Local";
  4378. break;
  4379. case smBoth:
  4380. ModeStr = L"Both";
  4381. break;
  4382. default:
  4383. ModeStr = L"Unknown";
  4384. break;
  4385. }
  4386. return ModeStr;
  4387. }
  4388. //---------------------------------------------------------------------------
  4389. UnicodeString __fastcall TTerminal::SynchronizeParamsStr(int Params)
  4390. {
  4391. UnicodeString ParamsStr;
  4392. AddFlagName(ParamsStr, Params, spDelete, L"Delete");
  4393. AddFlagName(ParamsStr, Params, spNoConfirmation, L"NoConfirmation");
  4394. AddFlagName(ParamsStr, Params, spExistingOnly, L"ExistingOnly");
  4395. AddFlagName(ParamsStr, Params, spNoRecurse, L"NoRecurse");
  4396. AddFlagName(ParamsStr, Params, spUseCache, L"UseCache");
  4397. AddFlagName(ParamsStr, Params, spDelayProgress, L"DelayProgress");
  4398. AddFlagName(ParamsStr, Params, spPreviewChanges, L"*PreviewChanges"); // GUI only
  4399. AddFlagName(ParamsStr, Params, spSubDirs, L"SubDirs");
  4400. AddFlagName(ParamsStr, Params, spTimestamp, L"Timestamp");
  4401. AddFlagName(ParamsStr, Params, spNotByTime, L"NotByTime");
  4402. AddFlagName(ParamsStr, Params, spBySize, L"BySize");
  4403. AddFlagName(ParamsStr, Params, spSelectedOnly, L"*SelectedOnly"); // GUI only
  4404. AddFlagName(ParamsStr, Params, spMirror, L"Mirror");
  4405. if (Params > 0)
  4406. {
  4407. AddToList(ParamsStr, FORMAT(L"0x%x", (int(Params))), L", ");
  4408. }
  4409. return ParamsStr;
  4410. }
  4411. //---------------------------------------------------------------------------
  4412. void __fastcall TTerminal::DoSynchronizeCollectDirectory(const UnicodeString LocalDirectory,
  4413. const UnicodeString RemoteDirectory, TSynchronizeMode Mode,
  4414. const TCopyParamType * CopyParam, int Params,
  4415. TSynchronizeDirectory OnSynchronizeDirectory, TSynchronizeOptions * Options,
  4416. int Flags, TSynchronizeChecklist * Checklist)
  4417. {
  4418. TSynchronizeData Data;
  4419. Data.LocalDirectory = IncludeTrailingBackslash(LocalDirectory);
  4420. Data.RemoteDirectory = UnixIncludeTrailingBackslash(RemoteDirectory);
  4421. Data.Mode = Mode;
  4422. Data.Params = Params;
  4423. Data.OnSynchronizeDirectory = OnSynchronizeDirectory;
  4424. Data.LocalFileList = NULL;
  4425. Data.CopyParam = CopyParam;
  4426. Data.Options = Options;
  4427. Data.Flags = Flags;
  4428. Data.Checklist = Checklist;
  4429. LogEvent(FORMAT(L"Collecting synchronization list for local directory '%s' and remote directory '%s', "
  4430. "mode = %s, params = 0x%x (%s)", (LocalDirectory, RemoteDirectory,
  4431. SynchronizeModeStr(Mode), int(Params), SynchronizeParamsStr(Params))));
  4432. if (FLAGCLEAR(Params, spDelayProgress))
  4433. {
  4434. DoSynchronizeProgress(Data, true);
  4435. }
  4436. try
  4437. {
  4438. bool Found;
  4439. TSearchRecChecked SearchRec;
  4440. Data.LocalFileList = CreateSortedStringList();
  4441. FILE_OPERATION_LOOP_BEGIN
  4442. {
  4443. int FindAttrs = faReadOnly | faHidden | faSysFile | faDirectory | faArchive;
  4444. Found = (FindFirstChecked(Data.LocalDirectory + L"*.*", FindAttrs, SearchRec) == 0);
  4445. }
  4446. FILE_OPERATION_LOOP_END(FMTLOAD(LIST_DIR_ERROR, (LocalDirectory)));
  4447. if (Found)
  4448. {
  4449. try
  4450. {
  4451. UnicodeString FileName;
  4452. while (Found)
  4453. {
  4454. FileName = SearchRec.Name;
  4455. // add dirs for recursive mode or when we are interested in newly
  4456. // added subdirs
  4457. // SearchRec.Size in C++B2010 is __int64,
  4458. // so we should be able to use it instead of FindData.nFileSize*
  4459. __int64 Size =
  4460. (static_cast<__int64>(SearchRec.FindData.nFileSizeHigh) << 32) +
  4461. SearchRec.FindData.nFileSizeLow;
  4462. TDateTime Modification = FileTimeToDateTime(SearchRec.FindData.ftLastWriteTime);
  4463. TFileMasks::TParams MaskParams;
  4464. MaskParams.Size = Size;
  4465. MaskParams.Modification = Modification;
  4466. UnicodeString RemoteFileName =
  4467. ChangeFileName(CopyParam, FileName, osLocal, false);
  4468. UnicodeString FullLocalFileName = Data.LocalDirectory + FileName;
  4469. UnicodeString BaseFileName = GetBaseFileName(FullLocalFileName);
  4470. if ((FileName != L".") && (FileName != L"..") &&
  4471. CopyParam->AllowTransfer(BaseFileName, osLocal,
  4472. FLAGSET(SearchRec.Attr, faDirectory), MaskParams) &&
  4473. !FFileSystem->TemporaryTransferFile(FileName) &&
  4474. (FLAGCLEAR(Flags, sfFirstLevel) ||
  4475. (Options == NULL) ||
  4476. Options->MatchesFilter(FileName) ||
  4477. Options->MatchesFilter(RemoteFileName)))
  4478. {
  4479. TSynchronizeFileData * FileData = new TSynchronizeFileData;
  4480. FileData->IsDirectory = FLAGSET(SearchRec.Attr, faDirectory);
  4481. FileData->Info.FileName = FileName;
  4482. FileData->Info.Directory = Data.LocalDirectory;
  4483. FileData->Info.Modification = Modification;
  4484. FileData->Info.ModificationFmt = mfFull;
  4485. FileData->Info.Size = Size;
  4486. FileData->LocalLastWriteTime = SearchRec.FindData.ftLastWriteTime;
  4487. FileData->New = true;
  4488. FileData->Modified = false;
  4489. Data.LocalFileList->AddObject(FileName,
  4490. reinterpret_cast<TObject*>(FileData));
  4491. LogEvent(FORMAT(L"Local file %s included to synchronization",
  4492. (FormatFileDetailsForLog(FullLocalFileName, Modification, Size))));
  4493. }
  4494. else
  4495. {
  4496. LogEvent(FORMAT(L"Local file %s excluded from synchronization",
  4497. (FormatFileDetailsForLog(FullLocalFileName, Modification, Size))));
  4498. }
  4499. FILE_OPERATION_LOOP_BEGIN
  4500. {
  4501. Found = (FindNextChecked(SearchRec) == 0);
  4502. }
  4503. FILE_OPERATION_LOOP_END(FMTLOAD(LIST_DIR_ERROR, (LocalDirectory)));
  4504. }
  4505. }
  4506. __finally
  4507. {
  4508. FindClose(SearchRec);
  4509. }
  4510. // can we expect that ProcessDirectory would take so little time
  4511. // that we can postpone showing progress window until anything actually happens?
  4512. bool Cached = FLAGSET(Params, spUseCache) && SessionData->CacheDirectories &&
  4513. FDirectoryCache->HasFileList(RemoteDirectory);
  4514. if (!Cached && FLAGSET(Params, spDelayProgress))
  4515. {
  4516. DoSynchronizeProgress(Data, true);
  4517. }
  4518. ProcessDirectory(RemoteDirectory, SynchronizeCollectFile, &Data,
  4519. FLAGSET(Params, spUseCache));
  4520. TSynchronizeFileData * FileData;
  4521. for (int Index = 0; Index < Data.LocalFileList->Count; Index++)
  4522. {
  4523. FileData = reinterpret_cast<TSynchronizeFileData *>
  4524. (Data.LocalFileList->Objects[Index]);
  4525. // add local file either if we are going to upload it
  4526. // (i.e. if it is updated or we want to upload even new files)
  4527. // or if we are going to delete it (i.e. all "new"=obsolete files)
  4528. bool Modified = (FileData->Modified && ((Mode == smBoth) || (Mode == smRemote)));
  4529. bool New = (FileData->New &&
  4530. ((Mode == smLocal) ||
  4531. (((Mode == smBoth) || (Mode == smRemote)) && FLAGCLEAR(Params, spTimestamp))));
  4532. if (New)
  4533. {
  4534. LogEvent(FORMAT(L"Local file %s is new",
  4535. (FormatFileDetailsForLog(FileData->Info.Directory + FileData->Info.FileName,
  4536. FileData->Info.Modification, FileData->Info.Size))));
  4537. }
  4538. if (Modified || New)
  4539. {
  4540. TSynchronizeChecklist::TItem * ChecklistItem = new TSynchronizeChecklist::TItem();
  4541. try
  4542. {
  4543. ChecklistItem->IsDirectory = FileData->IsDirectory;
  4544. ChecklistItem->Local = FileData->Info;
  4545. ChecklistItem->FLocalLastWriteTime = FileData->LocalLastWriteTime;
  4546. if (Modified)
  4547. {
  4548. DebugAssert(!FileData->MatchingRemoteFile.Directory.IsEmpty());
  4549. ChecklistItem->Remote = FileData->MatchingRemoteFile;
  4550. ChecklistItem->ImageIndex = FileData->MatchingRemoteFileImageIndex;
  4551. ChecklistItem->RemoteFile = FileData->MatchingRemoteFileFile;
  4552. }
  4553. else
  4554. {
  4555. ChecklistItem->Remote.Directory = Data.RemoteDirectory;
  4556. }
  4557. if ((Mode == smBoth) || (Mode == smRemote))
  4558. {
  4559. ChecklistItem->Action =
  4560. (Modified ? TSynchronizeChecklist::saUploadUpdate : TSynchronizeChecklist::saUploadNew);
  4561. ChecklistItem->Checked =
  4562. (Modified || FLAGCLEAR(Params, spExistingOnly)) &&
  4563. (!ChecklistItem->IsDirectory || FLAGCLEAR(Params, spNoRecurse) ||
  4564. FLAGSET(Params, spSubDirs));
  4565. }
  4566. else if ((Mode == smLocal) && FLAGCLEAR(Params, spTimestamp))
  4567. {
  4568. ChecklistItem->Action = TSynchronizeChecklist::saDeleteLocal;
  4569. ChecklistItem->Checked =
  4570. FLAGSET(Params, spDelete) &&
  4571. (!ChecklistItem->IsDirectory || FLAGCLEAR(Params, spNoRecurse) ||
  4572. FLAGSET(Params, spSubDirs));
  4573. }
  4574. if (ChecklistItem->Action != TSynchronizeChecklist::saNone)
  4575. {
  4576. Data.Checklist->Add(ChecklistItem);
  4577. ChecklistItem = NULL;
  4578. }
  4579. }
  4580. __finally
  4581. {
  4582. delete ChecklistItem;
  4583. }
  4584. }
  4585. else
  4586. {
  4587. if (FileData->Modified)
  4588. {
  4589. delete FileData->MatchingRemoteFileFile;
  4590. }
  4591. }
  4592. }
  4593. }
  4594. }
  4595. __finally
  4596. {
  4597. if (Data.LocalFileList != NULL)
  4598. {
  4599. for (int Index = 0; Index < Data.LocalFileList->Count; Index++)
  4600. {
  4601. TSynchronizeFileData * FileData = reinterpret_cast<TSynchronizeFileData*>
  4602. (Data.LocalFileList->Objects[Index]);
  4603. delete FileData;
  4604. }
  4605. delete Data.LocalFileList;
  4606. }
  4607. }
  4608. }
  4609. //---------------------------------------------------------------------------
  4610. void __fastcall TTerminal::SynchronizeCollectFile(const UnicodeString FileName,
  4611. const TRemoteFile * File, /*TSynchronizeData*/ void * Param)
  4612. {
  4613. try
  4614. {
  4615. DoSynchronizeCollectFile(FileName, File, Param);
  4616. }
  4617. catch(EScpSkipFile & E)
  4618. {
  4619. TSuspendFileOperationProgress Suspend(OperationProgress);
  4620. if (!HandleException(&E))
  4621. {
  4622. throw;
  4623. }
  4624. }
  4625. }
  4626. //---------------------------------------------------------------------------
  4627. void __fastcall TTerminal::DoSynchronizeCollectFile(const UnicodeString FileName,
  4628. const TRemoteFile * File, /*TSynchronizeData*/ void * Param)
  4629. {
  4630. TSynchronizeData * Data = static_cast<TSynchronizeData *>(Param);
  4631. TFileMasks::TParams MaskParams;
  4632. MaskParams.Size = File->Size;
  4633. MaskParams.Modification = File->Modification;
  4634. UnicodeString LocalFileName =
  4635. ChangeFileName(Data->CopyParam, File->FileName, osRemote, false);
  4636. UnicodeString FullRemoteFileName =
  4637. UnixExcludeTrailingBackslash(File->FullFileName);
  4638. UnicodeString BaseFileName = GetBaseFileName(FullRemoteFileName);
  4639. if (Data->CopyParam->AllowTransfer(
  4640. BaseFileName, osRemote,
  4641. File->IsDirectory, MaskParams) &&
  4642. !FFileSystem->TemporaryTransferFile(File->FileName) &&
  4643. (FLAGCLEAR(Data->Flags, sfFirstLevel) ||
  4644. (Data->Options == NULL) ||
  4645. Data->Options->MatchesFilter(File->FileName) ||
  4646. Data->Options->MatchesFilter(LocalFileName)))
  4647. {
  4648. TSynchronizeChecklist::TItem * ChecklistItem = new TSynchronizeChecklist::TItem();
  4649. try
  4650. {
  4651. ChecklistItem->IsDirectory = File->IsDirectory;
  4652. ChecklistItem->ImageIndex = File->IconIndex;
  4653. ChecklistItem->Remote.FileName = File->FileName;
  4654. ChecklistItem->Remote.Directory = Data->RemoteDirectory;
  4655. ChecklistItem->Remote.Modification = File->Modification;
  4656. ChecklistItem->Remote.ModificationFmt = File->ModificationFmt;
  4657. ChecklistItem->Remote.Size = File->Size;
  4658. bool Modified = false;
  4659. bool New = false;
  4660. if (File->IsDirectory && File->IsSymLink)
  4661. {
  4662. LogEvent(FORMAT(L"Skipping symlink to directory \"%s\".", (File->FileName)));
  4663. }
  4664. else
  4665. {
  4666. int LocalIndex = Data->LocalFileList->IndexOf(LocalFileName);
  4667. New = (LocalIndex < 0);
  4668. if (!New)
  4669. {
  4670. TSynchronizeFileData * LocalData =
  4671. reinterpret_cast<TSynchronizeFileData *>(Data->LocalFileList->Objects[LocalIndex]);
  4672. LocalData->New = false;
  4673. if (File->IsDirectory != LocalData->IsDirectory)
  4674. {
  4675. LogEvent(FORMAT(L"%s is directory on one side, but file on the another",
  4676. (File->FileName)));
  4677. }
  4678. else if (!File->IsDirectory)
  4679. {
  4680. ChecklistItem->Local = LocalData->Info;
  4681. ChecklistItem->Local.Modification =
  4682. ReduceDateTimePrecision(ChecklistItem->Local.Modification, File->ModificationFmt);
  4683. bool LocalModified = false;
  4684. // for spTimestamp+spBySize require that the file sizes are the same
  4685. // before comparing file time
  4686. int TimeCompare;
  4687. if (FLAGCLEAR(Data->Params, spNotByTime) &&
  4688. (FLAGCLEAR(Data->Params, spTimestamp) ||
  4689. FLAGCLEAR(Data->Params, spBySize) ||
  4690. (ChecklistItem->Local.Size == ChecklistItem->Remote.Size)))
  4691. {
  4692. TimeCompare = CompareFileTime(ChecklistItem->Local.Modification,
  4693. ChecklistItem->Remote.Modification);
  4694. }
  4695. else
  4696. {
  4697. TimeCompare = 0;
  4698. }
  4699. if (TimeCompare < 0)
  4700. {
  4701. if ((FLAGCLEAR(Data->Params, spTimestamp) && FLAGCLEAR(Data->Params, spMirror)) ||
  4702. (Data->Mode == smBoth) || (Data->Mode == smLocal))
  4703. {
  4704. Modified = true;
  4705. }
  4706. else
  4707. {
  4708. LocalModified = true;
  4709. }
  4710. }
  4711. else if (TimeCompare > 0)
  4712. {
  4713. if ((FLAGCLEAR(Data->Params, spTimestamp) && FLAGCLEAR(Data->Params, spMirror)) ||
  4714. (Data->Mode == smBoth) || (Data->Mode == smRemote))
  4715. {
  4716. LocalModified = true;
  4717. }
  4718. else
  4719. {
  4720. Modified = true;
  4721. }
  4722. }
  4723. else if (FLAGSET(Data->Params, spBySize) &&
  4724. (ChecklistItem->Local.Size != ChecklistItem->Remote.Size) &&
  4725. FLAGCLEAR(Data->Params, spTimestamp))
  4726. {
  4727. Modified = true;
  4728. LocalModified = true;
  4729. }
  4730. if (LocalModified)
  4731. {
  4732. LocalData->Modified = true;
  4733. LocalData->MatchingRemoteFile = ChecklistItem->Remote;
  4734. LocalData->MatchingRemoteFileImageIndex = ChecklistItem->ImageIndex;
  4735. // we need this for custom commands over checklist only,
  4736. // not for sync itself
  4737. LocalData->MatchingRemoteFileFile = File->Duplicate();
  4738. LogEvent(FORMAT(L"Local file %s is modified comparing to remote file %s",
  4739. (FormatFileDetailsForLog(LocalData->Info.Directory + LocalData->Info.FileName,
  4740. LocalData->Info.Modification, LocalData->Info.Size),
  4741. FormatFileDetailsForLog(FullRemoteFileName,
  4742. File->Modification, File->Size))));
  4743. }
  4744. if (Modified)
  4745. {
  4746. LogEvent(FORMAT(L"Remote file %s is modified comparing to local file %s",
  4747. (FormatFileDetailsForLog(FullRemoteFileName, File->Modification, File->Size),
  4748. FormatFileDetailsForLog(LocalData->Info.Directory + LocalData->Info.FileName,
  4749. LocalData->Info.Modification, LocalData->Info.Size))));
  4750. }
  4751. }
  4752. else if (FLAGCLEAR(Data->Params, spNoRecurse))
  4753. {
  4754. DoSynchronizeCollectDirectory(
  4755. Data->LocalDirectory + LocalData->Info.FileName,
  4756. Data->RemoteDirectory + File->FileName,
  4757. Data->Mode, Data->CopyParam, Data->Params, Data->OnSynchronizeDirectory,
  4758. Data->Options, (Data->Flags & ~sfFirstLevel),
  4759. Data->Checklist);
  4760. }
  4761. }
  4762. else
  4763. {
  4764. ChecklistItem->Local.Directory = Data->LocalDirectory;
  4765. LogEvent(FORMAT(L"Remote file %s is new",
  4766. (FormatFileDetailsForLog(FullRemoteFileName, File->Modification, File->Size))));
  4767. }
  4768. }
  4769. if (New || Modified)
  4770. {
  4771. DebugAssert(!New || !Modified);
  4772. // download the file if it changed or is new and we want to have it locally
  4773. if ((Data->Mode == smBoth) || (Data->Mode == smLocal))
  4774. {
  4775. if (FLAGCLEAR(Data->Params, spTimestamp) || Modified)
  4776. {
  4777. ChecklistItem->Action =
  4778. (Modified ? TSynchronizeChecklist::saDownloadUpdate : TSynchronizeChecklist::saDownloadNew);
  4779. ChecklistItem->Checked =
  4780. (Modified || FLAGCLEAR(Data->Params, spExistingOnly)) &&
  4781. (!ChecklistItem->IsDirectory || FLAGCLEAR(Data->Params, spNoRecurse) ||
  4782. FLAGSET(Data->Params, spSubDirs));
  4783. }
  4784. }
  4785. else if ((Data->Mode == smRemote) && New)
  4786. {
  4787. if (FLAGCLEAR(Data->Params, spTimestamp))
  4788. {
  4789. ChecklistItem->Action = TSynchronizeChecklist::saDeleteRemote;
  4790. ChecklistItem->Checked =
  4791. FLAGSET(Data->Params, spDelete) &&
  4792. (!ChecklistItem->IsDirectory || FLAGCLEAR(Data->Params, spNoRecurse) ||
  4793. FLAGSET(Data->Params, spSubDirs));
  4794. }
  4795. }
  4796. if (ChecklistItem->Action != TSynchronizeChecklist::saNone)
  4797. {
  4798. ChecklistItem->RemoteFile = File->Duplicate();
  4799. Data->Checklist->Add(ChecklistItem);
  4800. ChecklistItem = NULL;
  4801. }
  4802. }
  4803. }
  4804. __finally
  4805. {
  4806. delete ChecklistItem;
  4807. }
  4808. }
  4809. else
  4810. {
  4811. LogEvent(FORMAT(L"Remote file %s excluded from synchronization",
  4812. (FormatFileDetailsForLog(FullRemoteFileName, File->Modification, File->Size))));
  4813. }
  4814. }
  4815. //---------------------------------------------------------------------------
  4816. void __fastcall TTerminal::SynchronizeApply(TSynchronizeChecklist * Checklist,
  4817. const UnicodeString LocalDirectory, const UnicodeString RemoteDirectory,
  4818. const TCopyParamType * CopyParam, int Params,
  4819. TSynchronizeDirectory OnSynchronizeDirectory)
  4820. {
  4821. TSynchronizeData Data;
  4822. Data.OnSynchronizeDirectory = OnSynchronizeDirectory;
  4823. int CopyParams =
  4824. FLAGMASK(FLAGSET(Params, spNoConfirmation), cpNoConfirmation);
  4825. TCopyParamType SyncCopyParam = *CopyParam;
  4826. // when synchronizing by time, we force preserving time,
  4827. // otherwise it does not make any sense
  4828. if (FLAGCLEAR(Params, spNotByTime))
  4829. {
  4830. SyncCopyParam.PreserveTime = true;
  4831. }
  4832. TStringList * DownloadList = new TStringList();
  4833. TStringList * DeleteRemoteList = new TStringList();
  4834. TStringList * UploadList = new TStringList();
  4835. TStringList * DeleteLocalList = new TStringList();
  4836. BeginTransaction();
  4837. try
  4838. {
  4839. int IIndex = 0;
  4840. while (IIndex < Checklist->Count)
  4841. {
  4842. const TSynchronizeChecklist::TItem * ChecklistItem;
  4843. DownloadList->Clear();
  4844. DeleteRemoteList->Clear();
  4845. UploadList->Clear();
  4846. DeleteLocalList->Clear();
  4847. ChecklistItem = Checklist->Item[IIndex];
  4848. UnicodeString CurrentLocalDirectory = ChecklistItem->Local.Directory;
  4849. UnicodeString CurrentRemoteDirectory = ChecklistItem->Remote.Directory;
  4850. LogEvent(FORMAT(L"Synchronizing local directory '%s' with remote directory '%s', "
  4851. "params = 0x%x (%s)", (CurrentLocalDirectory, CurrentRemoteDirectory,
  4852. int(Params), SynchronizeParamsStr(Params))));
  4853. int Count = 0;
  4854. while ((IIndex < Checklist->Count) &&
  4855. (Checklist->Item[IIndex]->Local.Directory == CurrentLocalDirectory) &&
  4856. (Checklist->Item[IIndex]->Remote.Directory == CurrentRemoteDirectory))
  4857. {
  4858. ChecklistItem = Checklist->Item[IIndex];
  4859. if (ChecklistItem->Checked)
  4860. {
  4861. Count++;
  4862. if (FLAGSET(Params, spTimestamp))
  4863. {
  4864. switch (ChecklistItem->Action)
  4865. {
  4866. case TSynchronizeChecklist::saDownloadUpdate:
  4867. DownloadList->AddObject(
  4868. UnixIncludeTrailingBackslash(ChecklistItem->Remote.Directory) +
  4869. ChecklistItem->Remote.FileName,
  4870. (TObject *)(ChecklistItem));
  4871. break;
  4872. case TSynchronizeChecklist::saUploadUpdate:
  4873. UploadList->AddObject(
  4874. IncludeTrailingBackslash(ChecklistItem->Local.Directory) +
  4875. ChecklistItem->Local.FileName,
  4876. (TObject *)(ChecklistItem));
  4877. break;
  4878. default:
  4879. DebugFail();
  4880. break;
  4881. }
  4882. }
  4883. else
  4884. {
  4885. switch (ChecklistItem->Action)
  4886. {
  4887. case TSynchronizeChecklist::saDownloadNew:
  4888. case TSynchronizeChecklist::saDownloadUpdate:
  4889. DownloadList->AddObject(
  4890. UnixIncludeTrailingBackslash(ChecklistItem->Remote.Directory) +
  4891. ChecklistItem->Remote.FileName,
  4892. ChecklistItem->RemoteFile);
  4893. break;
  4894. case TSynchronizeChecklist::saDeleteRemote:
  4895. DeleteRemoteList->AddObject(
  4896. UnixIncludeTrailingBackslash(ChecklistItem->Remote.Directory) +
  4897. ChecklistItem->Remote.FileName,
  4898. ChecklistItem->RemoteFile);
  4899. break;
  4900. case TSynchronizeChecklist::saUploadNew:
  4901. case TSynchronizeChecklist::saUploadUpdate:
  4902. UploadList->Add(
  4903. IncludeTrailingBackslash(ChecklistItem->Local.Directory) +
  4904. ChecklistItem->Local.FileName);
  4905. break;
  4906. case TSynchronizeChecklist::saDeleteLocal:
  4907. DeleteLocalList->Add(
  4908. IncludeTrailingBackslash(ChecklistItem->Local.Directory) +
  4909. ChecklistItem->Local.FileName);
  4910. break;
  4911. default:
  4912. DebugFail();
  4913. break;
  4914. }
  4915. }
  4916. }
  4917. IIndex++;
  4918. }
  4919. // prevent showing/updating of progress dialog if there's nothing to do
  4920. if (Count > 0)
  4921. {
  4922. Data.LocalDirectory = IncludeTrailingBackslash(CurrentLocalDirectory);
  4923. Data.RemoteDirectory = UnixIncludeTrailingBackslash(CurrentRemoteDirectory);
  4924. DoSynchronizeProgress(Data, false);
  4925. if (FLAGSET(Params, spTimestamp))
  4926. {
  4927. if (DownloadList->Count > 0)
  4928. {
  4929. ProcessFiles(DownloadList, foSetProperties,
  4930. SynchronizeLocalTimestamp, NULL, osLocal);
  4931. }
  4932. if (UploadList->Count > 0)
  4933. {
  4934. ProcessFiles(UploadList, foSetProperties,
  4935. SynchronizeRemoteTimestamp);
  4936. }
  4937. }
  4938. else
  4939. {
  4940. if ((DownloadList->Count > 0) &&
  4941. !CopyToLocal(DownloadList, Data.LocalDirectory, &SyncCopyParam, CopyParams))
  4942. {
  4943. Abort();
  4944. }
  4945. if ((DeleteRemoteList->Count > 0) &&
  4946. !DeleteFiles(DeleteRemoteList))
  4947. {
  4948. Abort();
  4949. }
  4950. if ((UploadList->Count > 0) &&
  4951. !CopyToRemote(UploadList, Data.RemoteDirectory, &SyncCopyParam, CopyParams))
  4952. {
  4953. Abort();
  4954. }
  4955. if ((DeleteLocalList->Count > 0) &&
  4956. !DeleteLocalFiles(DeleteLocalList))
  4957. {
  4958. Abort();
  4959. }
  4960. }
  4961. }
  4962. }
  4963. }
  4964. __finally
  4965. {
  4966. delete DownloadList;
  4967. delete DeleteRemoteList;
  4968. delete UploadList;
  4969. delete DeleteLocalList;
  4970. EndTransaction();
  4971. }
  4972. }
  4973. //---------------------------------------------------------------------------
  4974. void __fastcall TTerminal::DoSynchronizeProgress(const TSynchronizeData & Data,
  4975. bool Collect)
  4976. {
  4977. if (Data.OnSynchronizeDirectory != NULL)
  4978. {
  4979. bool Continue = true;
  4980. Data.OnSynchronizeDirectory(Data.LocalDirectory, Data.RemoteDirectory,
  4981. Continue, Collect);
  4982. if (!Continue)
  4983. {
  4984. Abort();
  4985. }
  4986. }
  4987. }
  4988. //---------------------------------------------------------------------------
  4989. void __fastcall TTerminal::SynchronizeLocalTimestamp(const UnicodeString /*FileName*/,
  4990. const TRemoteFile * File, void * /*Param*/)
  4991. {
  4992. const TSynchronizeChecklist::TItem * ChecklistItem =
  4993. reinterpret_cast<const TSynchronizeChecklist::TItem *>(File);
  4994. UnicodeString LocalFile =
  4995. IncludeTrailingBackslash(ChecklistItem->Local.Directory) +
  4996. ChecklistItem->Local.FileName;
  4997. FILE_OPERATION_LOOP_BEGIN
  4998. {
  4999. HANDLE Handle;
  5000. OpenLocalFile(LocalFile, GENERIC_WRITE, NULL, &Handle,
  5001. NULL, NULL, NULL, NULL);
  5002. FILETIME WrTime = DateTimeToFileTime(ChecklistItem->Remote.Modification,
  5003. SessionData->DSTMode);
  5004. bool Result = SetFileTime(Handle, NULL, NULL, &WrTime);
  5005. int Error = GetLastError();
  5006. CloseHandle(Handle);
  5007. if (!Result)
  5008. {
  5009. RaiseLastOSError(Error);
  5010. }
  5011. }
  5012. FILE_OPERATION_LOOP_END(FMTLOAD(CANT_SET_ATTRS, (LocalFile)));
  5013. }
  5014. //---------------------------------------------------------------------------
  5015. void __fastcall TTerminal::SynchronizeRemoteTimestamp(const UnicodeString /*FileName*/,
  5016. const TRemoteFile * File, void * /*Param*/)
  5017. {
  5018. const TSynchronizeChecklist::TItem * ChecklistItem =
  5019. reinterpret_cast<const TSynchronizeChecklist::TItem *>(File);
  5020. TRemoteProperties Properties;
  5021. Properties.Valid << vpModification;
  5022. Properties.Modification = ConvertTimestampToUnix(ChecklistItem->FLocalLastWriteTime,
  5023. SessionData->DSTMode);
  5024. ChangeFileProperties(
  5025. UnixIncludeTrailingBackslash(ChecklistItem->Remote.Directory) + ChecklistItem->Remote.FileName,
  5026. NULL, &Properties);
  5027. }
  5028. //---------------------------------------------------------------------------
  5029. void __fastcall TTerminal::FileFind(UnicodeString FileName,
  5030. const TRemoteFile * File, /*TFilesFindParams*/ void * Param)
  5031. {
  5032. // see DoFilesFind
  5033. FOnFindingFile = NULL;
  5034. DebugAssert(Param);
  5035. DebugAssert(File);
  5036. TFilesFindParams * AParams = static_cast<TFilesFindParams*>(Param);
  5037. if (!AParams->Cancel)
  5038. {
  5039. if (FileName.IsEmpty())
  5040. {
  5041. FileName = File->FileName;
  5042. }
  5043. TFileMasks::TParams MaskParams;
  5044. MaskParams.Size = File->Size;
  5045. MaskParams.Modification = File->Modification;
  5046. UnicodeString FullFileName = UnixExcludeTrailingBackslash(File->FullFileName);
  5047. bool ImplicitMatch;
  5048. // Do not use recursive include match
  5049. if (AParams->FileMask.Matches(FullFileName, false,
  5050. File->IsDirectory, &MaskParams, false, ImplicitMatch))
  5051. {
  5052. if (!ImplicitMatch)
  5053. {
  5054. AParams->OnFileFound(this, FileName, File, AParams->Cancel);
  5055. }
  5056. if (File->IsDirectory)
  5057. {
  5058. if (!AParams->LoopDetector.IsUnvisitedDirectory(File))
  5059. {
  5060. LogEvent(FORMAT(L"Already searched \"%s\" directory, link loop detected", (FullFileName)));
  5061. }
  5062. else
  5063. {
  5064. DoFilesFind(FullFileName, *AParams);
  5065. }
  5066. }
  5067. }
  5068. }
  5069. }
  5070. //---------------------------------------------------------------------------
  5071. void __fastcall TTerminal::DoFilesFind(UnicodeString Directory, TFilesFindParams & Params)
  5072. {
  5073. Params.OnFindingFile(this, Directory, Params.Cancel);
  5074. if (!Params.Cancel)
  5075. {
  5076. DebugAssert(FOnFindingFile == NULL);
  5077. // ideally we should set the handler only around actually reading
  5078. // of the directory listing, so we at least reset the handler in
  5079. // FileFind
  5080. FOnFindingFile = Params.OnFindingFile;
  5081. try
  5082. {
  5083. ProcessDirectory(Directory, FileFind, &Params, false, true);
  5084. }
  5085. __finally
  5086. {
  5087. FOnFindingFile = NULL;
  5088. }
  5089. }
  5090. }
  5091. //---------------------------------------------------------------------------
  5092. void __fastcall TTerminal::FilesFind(UnicodeString Directory, const TFileMasks & FileMask,
  5093. TFileFoundEvent OnFileFound, TFindingFileEvent OnFindingFile)
  5094. {
  5095. TFilesFindParams Params;
  5096. Params.FileMask = FileMask;
  5097. Params.OnFileFound = OnFileFound;
  5098. Params.OnFindingFile = OnFindingFile;
  5099. Params.Cancel = false;
  5100. Params.LoopDetector.RecordVisitedDirectory(Directory);
  5101. DoFilesFind(Directory, Params);
  5102. }
  5103. //---------------------------------------------------------------------------
  5104. void __fastcall TTerminal::SpaceAvailable(const UnicodeString Path,
  5105. TSpaceAvailable & ASpaceAvailable)
  5106. {
  5107. DebugAssert(IsCapable[fcCheckingSpaceAvailable]);
  5108. try
  5109. {
  5110. FFileSystem->SpaceAvailable(Path, ASpaceAvailable);
  5111. }
  5112. catch (Exception &E)
  5113. {
  5114. CommandError(&E, FMTLOAD(SPACE_AVAILABLE_ERROR, (Path)));
  5115. }
  5116. }
  5117. //---------------------------------------------------------------------------
  5118. void __fastcall TTerminal::LockFile(const UnicodeString FileName,
  5119. const TRemoteFile * File, void * /*Param*/)
  5120. {
  5121. StartOperationWithFile(FileName, foLock);
  5122. LogEvent(FORMAT(L"Locking file \"%s\".", (FileName)));
  5123. FileModified(File, FileName, true);
  5124. DoLockFile(FileName, File);
  5125. ReactOnCommand(fsLock);
  5126. }
  5127. //---------------------------------------------------------------------------
  5128. void __fastcall TTerminal::DoLockFile(const UnicodeString & FileName, const TRemoteFile * File)
  5129. {
  5130. TRetryOperationLoop RetryLoop(this);
  5131. do
  5132. {
  5133. try
  5134. {
  5135. FFileSystem->LockFile(FileName, File);
  5136. }
  5137. catch(Exception & E)
  5138. {
  5139. RetryLoop.Error(E, FMTLOAD(LOCK_FILE_ERROR, (FileName)));
  5140. }
  5141. }
  5142. while (RetryLoop.Retry());
  5143. }
  5144. //---------------------------------------------------------------------------
  5145. void __fastcall TTerminal::UnlockFile(const UnicodeString FileName,
  5146. const TRemoteFile * File, void * /*Param*/)
  5147. {
  5148. StartOperationWithFile(FileName, foUnlock);
  5149. LogEvent(FORMAT(L"Unlocking file \"%s\".", (FileName)));
  5150. FileModified(File, FileName, true);
  5151. DoUnlockFile(FileName, File);
  5152. ReactOnCommand(fsLock);
  5153. }
  5154. //---------------------------------------------------------------------------
  5155. void __fastcall TTerminal::DoUnlockFile(const UnicodeString & FileName, const TRemoteFile * File)
  5156. {
  5157. TRetryOperationLoop RetryLoop(this);
  5158. do
  5159. {
  5160. try
  5161. {
  5162. FFileSystem->UnlockFile(FileName, File);
  5163. }
  5164. catch(Exception & E)
  5165. {
  5166. RetryLoop.Error(E, FMTLOAD(UNLOCK_FILE_ERROR, (FileName)));
  5167. }
  5168. }
  5169. while (RetryLoop.Retry());
  5170. }
  5171. //---------------------------------------------------------------------------
  5172. void __fastcall TTerminal::LockFiles(TStrings * FileList)
  5173. {
  5174. BeginTransaction();
  5175. try
  5176. {
  5177. ProcessFiles(FileList, foLock, LockFile, NULL);
  5178. }
  5179. __finally
  5180. {
  5181. EndTransaction();
  5182. }
  5183. }
  5184. //---------------------------------------------------------------------------
  5185. void __fastcall TTerminal::UnlockFiles(TStrings * FileList)
  5186. {
  5187. BeginTransaction();
  5188. try
  5189. {
  5190. ProcessFiles(FileList, foUnlock, UnlockFile, NULL);
  5191. }
  5192. __finally
  5193. {
  5194. EndTransaction();
  5195. }
  5196. }
  5197. //---------------------------------------------------------------------------
  5198. const TSessionInfo & __fastcall TTerminal::GetSessionInfo()
  5199. {
  5200. return FFileSystem->GetSessionInfo();
  5201. }
  5202. //---------------------------------------------------------------------------
  5203. const TFileSystemInfo & __fastcall TTerminal::GetFileSystemInfo(bool Retrieve)
  5204. {
  5205. return FFileSystem->GetFileSystemInfo(Retrieve);
  5206. }
  5207. //---------------------------------------------------------------------
  5208. void __fastcall TTerminal::GetSupportedChecksumAlgs(TStrings * Algs)
  5209. {
  5210. FFileSystem->GetSupportedChecksumAlgs(Algs);
  5211. }
  5212. //---------------------------------------------------------------------
  5213. UnicodeString __fastcall TTerminal::GetPassword()
  5214. {
  5215. UnicodeString Result;
  5216. // FRememberedPassword is empty also when stored password was used
  5217. if (FRememberedPassword.IsEmpty())
  5218. {
  5219. Result = SessionData->Password;
  5220. }
  5221. else
  5222. {
  5223. Result = RememberedPassword;
  5224. }
  5225. return Result;
  5226. }
  5227. //---------------------------------------------------------------------
  5228. UnicodeString __fastcall TTerminal::GetRememberedPassword()
  5229. {
  5230. return DecryptPassword(FRememberedPassword);
  5231. }
  5232. //---------------------------------------------------------------------
  5233. UnicodeString __fastcall TTerminal::GetRememberedTunnelPassword()
  5234. {
  5235. return DecryptPassword(FRememberedTunnelPassword);
  5236. }
  5237. //---------------------------------------------------------------------
  5238. bool __fastcall TTerminal::GetStoredCredentialsTried()
  5239. {
  5240. bool Result;
  5241. if (FFileSystem != NULL)
  5242. {
  5243. Result = FFileSystem->GetStoredCredentialsTried();
  5244. }
  5245. else if (FSecureShell != NULL)
  5246. {
  5247. Result = FSecureShell->GetStoredCredentialsTried();
  5248. }
  5249. else
  5250. {
  5251. DebugAssert(FTunnelOpening);
  5252. Result = false;
  5253. }
  5254. return Result;
  5255. }
  5256. //---------------------------------------------------------------------------
  5257. bool __fastcall TTerminal::CopyToRemote(TStrings * FilesToCopy,
  5258. const UnicodeString TargetDir, const TCopyParamType * CopyParam, int Params)
  5259. {
  5260. DebugAssert(FFileSystem);
  5261. DebugAssert(FilesToCopy);
  5262. bool Result = false;
  5263. TOnceDoneOperation OnceDoneOperation = odoIdle;
  5264. try
  5265. {
  5266. __int64 Size;
  5267. // dirty trick: when moving, do not pass copy param to avoid exclude mask
  5268. bool CalculatedSize =
  5269. CalculateLocalFilesSize(
  5270. FilesToCopy, Size,
  5271. (FLAGCLEAR(Params, cpDelete) ? CopyParam : NULL),
  5272. CopyParam->CalculateSize);
  5273. TFileOperationProgressType OperationProgress(&DoProgress, &DoFinished);
  5274. OperationProgress.Start((Params & cpDelete ? foMove : foCopy), osLocal,
  5275. FilesToCopy->Count, Params & cpTemporary, TargetDir, CopyParam->CPSLimit);
  5276. FOperationProgress = &OperationProgress;
  5277. bool CollectingUsage = false;
  5278. try
  5279. {
  5280. if (CalculatedSize)
  5281. {
  5282. if (Configuration->Usage->Collect)
  5283. {
  5284. int CounterSize = TUsage::CalculateCounterSize(Size);
  5285. Configuration->Usage->Inc(L"Uploads");
  5286. Configuration->Usage->Inc(L"UploadedBytes", CounterSize);
  5287. Configuration->Usage->SetMax(L"MaxUploadSize", CounterSize);
  5288. CollectingUsage = true;
  5289. }
  5290. OperationProgress.SetTotalSize(Size);
  5291. }
  5292. UnicodeString UnlockedTargetDir = TranslateLockedPath(TargetDir, false);
  5293. BeginTransaction();
  5294. try
  5295. {
  5296. if (Log->Logging)
  5297. {
  5298. LogEvent(FORMAT(L"Copying %d files/directories to remote directory "
  5299. "\"%s\"", (FilesToCopy->Count, TargetDir)));
  5300. LogEvent(CopyParam->LogStr);
  5301. }
  5302. FFileSystem->CopyToRemote(FilesToCopy, UnlockedTargetDir,
  5303. CopyParam, Params, &OperationProgress, OnceDoneOperation);
  5304. }
  5305. __finally
  5306. {
  5307. if (Active)
  5308. {
  5309. ReactOnCommand(fsCopyToRemote);
  5310. }
  5311. EndTransaction();
  5312. }
  5313. if (OperationProgress.Cancel == csContinue)
  5314. {
  5315. Result = true;
  5316. }
  5317. }
  5318. __finally
  5319. {
  5320. if (CollectingUsage)
  5321. {
  5322. int CounterTime = TimeToSeconds(OperationProgress.TimeElapsed());
  5323. Configuration->Usage->Inc(L"UploadTime", CounterTime);
  5324. Configuration->Usage->SetMax(L"MaxUploadTime", CounterTime);
  5325. }
  5326. OperationProgress.Stop();
  5327. FOperationProgress = NULL;
  5328. }
  5329. }
  5330. catch (Exception &E)
  5331. {
  5332. CommandError(&E, MainInstructions(LoadStr(TOREMOTE_COPY_ERROR)));
  5333. OnceDoneOperation = odoIdle;
  5334. }
  5335. if (OnceDoneOperation != odoIdle)
  5336. {
  5337. CloseOnCompletion(OnceDoneOperation);
  5338. }
  5339. return Result;
  5340. }
  5341. //---------------------------------------------------------------------------
  5342. bool __fastcall TTerminal::CopyToLocal(TStrings * FilesToCopy,
  5343. const UnicodeString TargetDir, const TCopyParamType * CopyParam, int Params)
  5344. {
  5345. DebugAssert(FFileSystem);
  5346. // see scp.c: sink(), tolocal()
  5347. bool Result = false;
  5348. bool OwnsFileList = (FilesToCopy == NULL);
  5349. TOnceDoneOperation OnceDoneOperation = odoIdle;
  5350. try
  5351. {
  5352. if (OwnsFileList)
  5353. {
  5354. FilesToCopy = new TStringList();
  5355. FilesToCopy->Assign(Files->SelectedFiles);
  5356. }
  5357. BeginTransaction();
  5358. try
  5359. {
  5360. __int64 TotalSize;
  5361. bool TotalSizeKnown = false;
  5362. TFileOperationProgressType OperationProgress(&DoProgress, &DoFinished);
  5363. ExceptionOnFail = true;
  5364. try
  5365. {
  5366. // dirty trick: when moving, do not pass copy param to avoid exclude mask
  5367. if (CalculateFilesSize(
  5368. FilesToCopy, TotalSize, csIgnoreErrors,
  5369. (FLAGCLEAR(Params, cpDelete) ? CopyParam : NULL),
  5370. CopyParam->CalculateSize, NULL))
  5371. {
  5372. TotalSizeKnown = true;
  5373. }
  5374. }
  5375. __finally
  5376. {
  5377. ExceptionOnFail = false;
  5378. }
  5379. OperationProgress.Start((Params & cpDelete ? foMove : foCopy), osRemote,
  5380. FilesToCopy->Count, Params & cpTemporary, TargetDir, CopyParam->CPSLimit);
  5381. FOperationProgress = &OperationProgress;
  5382. bool CollectingUsage = false;
  5383. try
  5384. {
  5385. if (TotalSizeKnown)
  5386. {
  5387. if (Configuration->Usage->Collect)
  5388. {
  5389. int CounterTotalSize = TUsage::CalculateCounterSize(TotalSize);
  5390. Configuration->Usage->Inc(L"Downloads");
  5391. Configuration->Usage->Inc(L"DownloadedBytes", CounterTotalSize);
  5392. Configuration->Usage->SetMax(L"MaxDownloadSize", CounterTotalSize);
  5393. CollectingUsage = true;
  5394. }
  5395. OperationProgress.SetTotalSize(TotalSize);
  5396. }
  5397. try
  5398. {
  5399. try
  5400. {
  5401. if (Log->Logging)
  5402. {
  5403. LogEvent(FORMAT(L"Copying %d files/directories to local directory "
  5404. "\"%s\"", (FilesToCopy->Count, TargetDir)));
  5405. LogEvent(CopyParam->LogStr);
  5406. }
  5407. FFileSystem->CopyToLocal(FilesToCopy, TargetDir, CopyParam, Params,
  5408. &OperationProgress, OnceDoneOperation);
  5409. }
  5410. __finally
  5411. {
  5412. if (Active)
  5413. {
  5414. ReactOnCommand(fsCopyToLocal);
  5415. }
  5416. }
  5417. }
  5418. catch (Exception &E)
  5419. {
  5420. CommandError(&E, MainInstructions(LoadStr(TOLOCAL_COPY_ERROR)));
  5421. OnceDoneOperation = odoIdle;
  5422. }
  5423. if (OperationProgress.Cancel == csContinue)
  5424. {
  5425. Result = true;
  5426. }
  5427. }
  5428. __finally
  5429. {
  5430. if (CollectingUsage)
  5431. {
  5432. int CounterTime = TimeToSeconds(OperationProgress.TimeElapsed());
  5433. Configuration->Usage->Inc(L"DownloadTime", CounterTime);
  5434. Configuration->Usage->SetMax(L"MaxDownloadTime", CounterTime);
  5435. }
  5436. FOperationProgress = NULL;
  5437. OperationProgress.Stop();
  5438. }
  5439. }
  5440. __finally
  5441. {
  5442. // If session is still active (no fatal error) we reload directory
  5443. // by calling EndTransaction
  5444. EndTransaction();
  5445. }
  5446. }
  5447. __finally
  5448. {
  5449. if (OwnsFileList) delete FilesToCopy;
  5450. }
  5451. if (OnceDoneOperation != odoIdle)
  5452. {
  5453. CloseOnCompletion(OnceDoneOperation);
  5454. }
  5455. return Result;
  5456. }
  5457. //---------------------------------------------------------------------------
  5458. void __fastcall TTerminal::ReflectSettings()
  5459. {
  5460. DebugAssert(FLog != NULL);
  5461. FLog->ReflectSettings();
  5462. DebugAssert(FActionLog != NULL);
  5463. FActionLog->ReflectSettings();
  5464. // also FTunnelLog ?
  5465. }
  5466. //---------------------------------------------------------------------------
  5467. void __fastcall TTerminal::CollectUsage()
  5468. {
  5469. switch (SessionData->FSProtocol)
  5470. {
  5471. case fsSCPonly:
  5472. Configuration->Usage->Inc(L"OpenedSessionsSCP");
  5473. break;
  5474. case fsSFTP:
  5475. case fsSFTPonly:
  5476. Configuration->Usage->Inc(L"OpenedSessionsSFTP");
  5477. break;
  5478. case fsFTP:
  5479. if (SessionData->Ftps == ftpsNone)
  5480. {
  5481. Configuration->Usage->Inc(L"OpenedSessionsFTP");
  5482. }
  5483. else
  5484. {
  5485. Configuration->Usage->Inc(L"OpenedSessionsFTPS");
  5486. }
  5487. break;
  5488. case fsWebDAV:
  5489. if (SessionData->Ftps == ftpsNone)
  5490. {
  5491. Configuration->Usage->Inc(L"OpenedSessionsWebDAV");
  5492. }
  5493. else
  5494. {
  5495. Configuration->Usage->Inc(L"OpenedSessionsWebDAVS");
  5496. }
  5497. break;
  5498. }
  5499. if (Configuration->Logging && Configuration->LogToFile)
  5500. {
  5501. Configuration->Usage->Inc(L"OpenedSessionsLogToFile2");
  5502. }
  5503. if (Configuration->LogActions)
  5504. {
  5505. Configuration->Usage->Inc(L"OpenedSessionsXmlLog");
  5506. }
  5507. std::unique_ptr<TSessionData> FactoryDefaults(new TSessionData(L""));
  5508. if (!SessionData->IsSame(FactoryDefaults.get(), true))
  5509. {
  5510. Configuration->Usage->Inc(L"OpenedSessionsAdvanced");
  5511. }
  5512. if (SessionData->ProxyMethod != ::pmNone)
  5513. {
  5514. Configuration->Usage->Inc(L"OpenedSessionsProxy");
  5515. }
  5516. if (SessionData->FtpProxyLogonType > 0)
  5517. {
  5518. Configuration->Usage->Inc(L"OpenedSessionsFtpProxy");
  5519. }
  5520. FCollectFileSystemUsage = true;
  5521. }
  5522. //---------------------------------------------------------------------------
  5523. static UnicodeString __fastcall FormatCertificateData(const UnicodeString & Fingerprint, int Failures)
  5524. {
  5525. return FORMAT(L"%s;%2.2X", (Fingerprint, Failures));
  5526. }
  5527. //---------------------------------------------------------------------------
  5528. bool __fastcall TTerminal::VerifyCertificate(
  5529. const UnicodeString & CertificateStorageKey, const UnicodeString & SiteKey,
  5530. const UnicodeString & Fingerprint,
  5531. const UnicodeString & CertificateSubject, int Failures)
  5532. {
  5533. bool Result = false;
  5534. UnicodeString CertificateData = FormatCertificateData(Fingerprint, Failures);
  5535. std::unique_ptr<THierarchicalStorage> Storage(Configuration->CreateConfigStorage());
  5536. Storage->AccessMode = smRead;
  5537. if (Storage->OpenSubKey(CertificateStorageKey, false))
  5538. {
  5539. if (Storage->ValueExists(SiteKey))
  5540. {
  5541. UnicodeString CachedCertificateData = Storage->ReadString(SiteKey, L"");
  5542. if (CertificateData == CachedCertificateData)
  5543. {
  5544. LogEvent(FORMAT(L"Certificate for \"%s\" matches cached fingerprint and failures", (CertificateSubject)));
  5545. Result = true;
  5546. }
  5547. }
  5548. else if (Storage->ValueExists(Fingerprint))
  5549. {
  5550. LogEvent(FORMAT(L"Certificate for \"%s\" matches legacy cached fingerprint", (CertificateSubject)));
  5551. Result = true;
  5552. }
  5553. }
  5554. if (!Result)
  5555. {
  5556. UnicodeString Buf = SessionData->HostKey;
  5557. while (!Result && !Buf.IsEmpty())
  5558. {
  5559. UnicodeString ExpectedKey = CutToChar(Buf, L';', false);
  5560. if (ExpectedKey == L"*")
  5561. {
  5562. UnicodeString Message = LoadStr(ANY_CERTIFICATE);
  5563. Information(Message, true);
  5564. Log->Add(llException, Message);
  5565. Result = true;
  5566. }
  5567. else if (ExpectedKey == Fingerprint)
  5568. {
  5569. LogEvent(FORMAT(L"Certificate for \"%s\" matches configured fingerprint", (CertificateSubject)));
  5570. Result = true;
  5571. }
  5572. }
  5573. }
  5574. return Result;
  5575. }
  5576. //---------------------------------------------------------------------------
  5577. void __fastcall TTerminal::CacheCertificate(const UnicodeString & CertificateStorageKey,
  5578. const UnicodeString & SiteKey, const UnicodeString & Fingerprint, int Failures)
  5579. {
  5580. UnicodeString CertificateData = FormatCertificateData(Fingerprint, Failures);
  5581. std::unique_ptr<THierarchicalStorage> Storage(Configuration->CreateConfigStorage());
  5582. Storage->AccessMode = smReadWrite;
  5583. if (Storage->OpenSubKey(CertificateStorageKey, true))
  5584. {
  5585. Storage->WriteString(SiteKey, CertificateData);
  5586. }
  5587. }
  5588. //---------------------------------------------------------------------------
  5589. void __fastcall TTerminal::CollectTlsUsage(const UnicodeString & TlsVersionStr)
  5590. {
  5591. // see SSL_get_version() in OpenSSL ssl_lib.c
  5592. if (TlsVersionStr == L"TLSv1.2")
  5593. {
  5594. Configuration->Usage->Inc(L"OpenedSessionsTLS12");
  5595. }
  5596. else if (TlsVersionStr == L"TLSv1.1")
  5597. {
  5598. Configuration->Usage->Inc(L"OpenedSessionsTLS11");
  5599. }
  5600. else if (TlsVersionStr == L"TLSv1")
  5601. {
  5602. Configuration->Usage->Inc(L"OpenedSessionsTLS10");
  5603. }
  5604. else if (TlsVersionStr == L"SSLv3")
  5605. {
  5606. Configuration->Usage->Inc(L"OpenedSessionsSSL30");
  5607. }
  5608. else if (TlsVersionStr == L"SSLv2")
  5609. {
  5610. Configuration->Usage->Inc(L"OpenedSessionsSSL20");
  5611. }
  5612. else
  5613. {
  5614. DebugFail();
  5615. }
  5616. }
  5617. //---------------------------------------------------------------------------
  5618. bool __fastcall TTerminal::LoadTlsCertificate(X509 *& Certificate, EVP_PKEY *& PrivateKey)
  5619. {
  5620. bool Result = !SessionData->TlsCertificateFile.IsEmpty();
  5621. if (Result)
  5622. {
  5623. UnicodeString Passphrase = SessionData->Passphrase;
  5624. // Inspired by neon's ne_ssl_clicert_read
  5625. bool Retry;
  5626. do
  5627. {
  5628. Retry = false;
  5629. bool WrongPassphrase = false;
  5630. ParseCertificate(SessionData->TlsCertificateFile, Passphrase, Certificate, PrivateKey, WrongPassphrase);
  5631. if (WrongPassphrase)
  5632. {
  5633. if (Passphrase.IsEmpty())
  5634. {
  5635. LogEvent(L"Certificate is encrypted, need passphrase");
  5636. Information(LoadStr(CLIENT_CERTIFICATE_LOADING), false);
  5637. }
  5638. else
  5639. {
  5640. Information(LoadStr(CERTIFICATE_DECODE_ERROR_INFO), false);
  5641. }
  5642. Passphrase = L"";
  5643. if (PromptUser(
  5644. SessionData, pkPassphrase,
  5645. LoadStr(CERTIFICATE_PASSPHRASE_TITLE), L"",
  5646. LoadStr(CERTIFICATE_PASSPHRASE_PROMPT), false, 0, Passphrase))
  5647. {
  5648. Retry = true;
  5649. }
  5650. else
  5651. {
  5652. Result = false;
  5653. }
  5654. }
  5655. }
  5656. while (Retry);
  5657. }
  5658. return Result;
  5659. }
  5660. //---------------------------------------------------------------------------
  5661. UnicodeString __fastcall TTerminal::GetBaseFileName(UnicodeString FileName)
  5662. {
  5663. if (FSessionData->TrimVMSVersions)
  5664. {
  5665. int P = FileName.LastDelimiter(L";");
  5666. if (P > 0)
  5667. {
  5668. FileName.SetLength(P - 1);
  5669. }
  5670. }
  5671. return FileName;
  5672. }
  5673. //---------------------------------------------------------------------------
  5674. UnicodeString __fastcall TTerminal::ChangeFileName(const TCopyParamType * CopyParam,
  5675. UnicodeString FileName, TOperationSide Side, bool FirstLevel)
  5676. {
  5677. FileName = GetBaseFileName(FileName);
  5678. FileName = CopyParam->ChangeFileName(FileName, Side, FirstLevel);
  5679. return FileName;
  5680. }
  5681. //---------------------------------------------------------------------------
  5682. __fastcall TSecondaryTerminal::TSecondaryTerminal(TTerminal * MainTerminal,
  5683. TSessionData * ASessionData, TConfiguration * Configuration, const UnicodeString & Name) :
  5684. TTerminal(ASessionData, Configuration),
  5685. FMainTerminal(MainTerminal)
  5686. {
  5687. Log->Parent = FMainTerminal->Log;
  5688. Log->Name = Name;
  5689. ActionLog->Enabled = false;
  5690. SessionData->NonPersistant();
  5691. DebugAssert(FMainTerminal != NULL);
  5692. if (!FMainTerminal->UserName.IsEmpty())
  5693. {
  5694. SessionData->UserName = FMainTerminal->UserName;
  5695. }
  5696. }
  5697. //---------------------------------------------------------------------------
  5698. void __fastcall TSecondaryTerminal::UpdateFromMain()
  5699. {
  5700. if ((FFileSystem != NULL) && (FMainTerminal->FFileSystem != NULL))
  5701. {
  5702. FFileSystem->UpdateFromMain(FMainTerminal->FFileSystem);
  5703. }
  5704. }
  5705. //---------------------------------------------------------------------------
  5706. void __fastcall TSecondaryTerminal::DirectoryLoaded(TRemoteFileList * FileList)
  5707. {
  5708. FMainTerminal->DirectoryLoaded(FileList);
  5709. DebugAssert(FileList != NULL);
  5710. }
  5711. //---------------------------------------------------------------------------
  5712. void __fastcall TSecondaryTerminal::DirectoryModified(const UnicodeString Path,
  5713. bool SubDirs)
  5714. {
  5715. // clear cache of main terminal
  5716. FMainTerminal->DirectoryModified(Path, SubDirs);
  5717. }
  5718. //---------------------------------------------------------------------------
  5719. TTerminal * __fastcall TSecondaryTerminal::GetPasswordSource()
  5720. {
  5721. return FMainTerminal;
  5722. }
  5723. //---------------------------------------------------------------------------
  5724. __fastcall TTerminalList::TTerminalList(TConfiguration * AConfiguration) :
  5725. TObjectList()
  5726. {
  5727. DebugAssert(AConfiguration);
  5728. FConfiguration = AConfiguration;
  5729. }
  5730. //---------------------------------------------------------------------------
  5731. __fastcall TTerminalList::~TTerminalList()
  5732. {
  5733. DebugAssert(Count == 0);
  5734. }
  5735. //---------------------------------------------------------------------------
  5736. TTerminal * __fastcall TTerminalList::CreateTerminal(TSessionData * Data)
  5737. {
  5738. return new TTerminal(Data, FConfiguration);
  5739. }
  5740. //---------------------------------------------------------------------------
  5741. TTerminal * __fastcall TTerminalList::NewTerminal(TSessionData * Data)
  5742. {
  5743. TTerminal * Terminal = CreateTerminal(Data);
  5744. Add(Terminal);
  5745. return Terminal;
  5746. }
  5747. //---------------------------------------------------------------------------
  5748. void __fastcall TTerminalList::FreeTerminal(TTerminal * Terminal)
  5749. {
  5750. DebugAssert(IndexOf(Terminal) >= 0);
  5751. Remove(Terminal);
  5752. }
  5753. //---------------------------------------------------------------------------
  5754. void __fastcall TTerminalList::FreeAndNullTerminal(TTerminal * & Terminal)
  5755. {
  5756. TTerminal * T = Terminal;
  5757. Terminal = NULL;
  5758. FreeTerminal(T);
  5759. }
  5760. //---------------------------------------------------------------------------
  5761. TTerminal * __fastcall TTerminalList::GetTerminal(int Index)
  5762. {
  5763. return dynamic_cast<TTerminal *>(Items[Index]);
  5764. }
  5765. //---------------------------------------------------------------------------
  5766. void __fastcall TTerminalList::Idle()
  5767. {
  5768. TTerminal * Terminal;
  5769. for (int i = 0; i < Count; i++)
  5770. {
  5771. Terminal = Terminals[i];
  5772. if (Terminal->Status == ssOpened)
  5773. {
  5774. Terminal->Idle();
  5775. }
  5776. }
  5777. }
  5778. //---------------------------------------------------------------------------
  5779. void __fastcall TTerminalList::RecryptPasswords()
  5780. {
  5781. for (int Index = 0; Index < Count; Index++)
  5782. {
  5783. Terminals[Index]->RecryptPasswords();
  5784. }
  5785. }