1
0

Terminal.cpp 162 KB

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