Terminal.cpp 124 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141
  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 "Exceptions.h"
  10. #include "FileBuffer.h"
  11. #include "Interface.h"
  12. #include "RemoteFiles.h"
  13. #include "SecureShell.h"
  14. #include "ScpFileSystem.h"
  15. #include "SftpFileSystem.h"
  16. #ifndef NO_FILEZILLA
  17. #include "FtpFileSystem.h"
  18. #endif
  19. #include "TextsCore.h"
  20. #include "HelpCore.h"
  21. #include "Security.h"
  22. #include "CoreMain.h"
  23. #include "Queue.h"
  24. //---------------------------------------------------------------------------
  25. #pragma package(smart_init)
  26. //---------------------------------------------------------------------------
  27. #define SSH_ERROR(x) throw ESsh(NULL, x)
  28. #define SSH_FATAL_ERROR_EXT(E, x) throw ESshFatal(E, x)
  29. #define SSH_FATAL_ERROR(x) SSH_FATAL_ERROR_EXT(NULL, x)
  30. //---------------------------------------------------------------------------
  31. #define COMMAND_ERROR_ARI(MESSAGE, REPEAT) \
  32. { \
  33. int Result = CommandError(&E, MESSAGE, qaRetry | qaSkip | qaAbort); \
  34. switch (Result) { \
  35. case qaRetry: { REPEAT; } break; \
  36. case qaAbort: Abort(); \
  37. } \
  38. }
  39. #define FILE_OPERATION_LOOP_EX(ALLOW_SKIP, MESSAGE, OPERATION) \
  40. FILE_OPERATION_LOOP_CUSTOM(this, ALLOW_SKIP, MESSAGE, OPERATION)
  41. //---------------------------------------------------------------------------
  42. struct TMoveFileParams
  43. {
  44. AnsiString Target;
  45. AnsiString FileMask;
  46. };
  47. //---------------------------------------------------------------------------
  48. TCalculateSizeStats::TCalculateSizeStats()
  49. {
  50. memset(this, 0, sizeof(*this));
  51. }
  52. //---------------------------------------------------------------------------
  53. TSynchronizeOptions::TSynchronizeOptions()
  54. {
  55. memset(this, 0, sizeof(*this));
  56. }
  57. //---------------------------------------------------------------------------
  58. TSynchronizeOptions::~TSynchronizeOptions()
  59. {
  60. delete Filter;
  61. }
  62. //---------------------------------------------------------------------------
  63. TSpaceAvailable::TSpaceAvailable()
  64. {
  65. memset(this, 0, sizeof(*this));
  66. }
  67. //---------------------------------------------------------------------------
  68. TOverwriteFileParams::TOverwriteFileParams()
  69. {
  70. SourceSize = 0;
  71. DestSize = 0;
  72. SourcePrecision = mfFull;
  73. DestPrecision = mfFull;
  74. }
  75. //---------------------------------------------------------------------------
  76. //---------------------------------------------------------------------------
  77. TSynchronizeChecklist::TItem::TItem() :
  78. Action(saNone), IsDirectory(false), FRemoteFile(NULL), Checked(true), ImageIndex(-1)
  79. {
  80. Local.ModificationFmt = mfFull;
  81. Local.Modification = 0;
  82. Local.Size = 0;
  83. Remote.ModificationFmt = mfFull;
  84. Remote.Modification = 0;
  85. Remote.Size = 0;
  86. }
  87. //---------------------------------------------------------------------------
  88. TSynchronizeChecklist::TItem::~TItem()
  89. {
  90. delete FRemoteFile;
  91. }
  92. //---------------------------------------------------------------------------
  93. //---------------------------------------------------------------------------
  94. TSynchronizeChecklist::TSynchronizeChecklist() :
  95. FList(new TList())
  96. {
  97. }
  98. //---------------------------------------------------------------------------
  99. TSynchronizeChecklist::~TSynchronizeChecklist()
  100. {
  101. for (int Index = 0; Index < FList->Count; Index++)
  102. {
  103. delete static_cast<TItem *>(FList->Items[Index]);
  104. }
  105. delete FList;
  106. }
  107. //---------------------------------------------------------------------------
  108. void TSynchronizeChecklist::Add(TItem * Item)
  109. {
  110. FList->Add(Item);
  111. }
  112. //---------------------------------------------------------------------------
  113. int __fastcall TSynchronizeChecklist::Compare(void * AItem1, void * AItem2)
  114. {
  115. TItem * Item1 = static_cast<TItem *>(AItem1);
  116. TItem * Item2 = static_cast<TItem *>(AItem2);
  117. int Result;
  118. if (!Item1->Local.Directory.IsEmpty())
  119. {
  120. Result = CompareText(Item1->Local.Directory, Item2->Local.Directory);
  121. }
  122. else
  123. {
  124. assert(!Item1->Remote.Directory.IsEmpty());
  125. Result = CompareText(Item1->Remote.Directory, Item2->Remote.Directory);
  126. }
  127. if (Result == 0)
  128. {
  129. Result = CompareText(Item1->FileName, Item2->FileName);
  130. }
  131. return Result;
  132. }
  133. //---------------------------------------------------------------------------
  134. void TSynchronizeChecklist::Sort()
  135. {
  136. FList->Sort(Compare);
  137. }
  138. //---------------------------------------------------------------------------
  139. int TSynchronizeChecklist::GetCount() const
  140. {
  141. return FList->Count;
  142. }
  143. //---------------------------------------------------------------------------
  144. const TSynchronizeChecklist::TItem * TSynchronizeChecklist::GetItem(int Index) const
  145. {
  146. return static_cast<TItem *>(FList->Items[Index]);
  147. }
  148. //---------------------------------------------------------------------------
  149. //---------------------------------------------------------------------------
  150. class TTunnelThread : public TSimpleThread
  151. {
  152. public:
  153. __fastcall TTunnelThread(TSecureShell * SecureShell);
  154. virtual __fastcall ~TTunnelThread();
  155. virtual void __fastcall Terminate();
  156. protected:
  157. virtual void __fastcall Execute();
  158. private:
  159. TSecureShell * FSecureShell;
  160. bool FTerminated;
  161. };
  162. //---------------------------------------------------------------------------
  163. __fastcall TTunnelThread::TTunnelThread(TSecureShell * SecureShell) :
  164. FSecureShell(SecureShell),
  165. FTerminated(false)
  166. {
  167. Start();
  168. }
  169. //---------------------------------------------------------------------------
  170. __fastcall TTunnelThread::~TTunnelThread()
  171. {
  172. // close before the class's virtual functions (Terminate particularly) are lost
  173. Close();
  174. }
  175. //---------------------------------------------------------------------------
  176. void __fastcall TTunnelThread::Terminate()
  177. {
  178. FTerminated = true;
  179. }
  180. //---------------------------------------------------------------------------
  181. void __fastcall TTunnelThread::Execute()
  182. {
  183. try
  184. {
  185. while (!FTerminated)
  186. {
  187. FSecureShell->Idle(250);
  188. }
  189. }
  190. catch(...)
  191. {
  192. if (FSecureShell->Active)
  193. {
  194. FSecureShell->Close();
  195. }
  196. throw;
  197. }
  198. }
  199. //---------------------------------------------------------------------------
  200. //---------------------------------------------------------------------------
  201. class TTunnelUI : public TSessionUI
  202. {
  203. public:
  204. __fastcall TTunnelUI(TTerminal * Terminal);
  205. virtual void __fastcall Information(const AnsiString & Str, bool Status);
  206. virtual int __fastcall QueryUser(const AnsiString Query,
  207. TStrings * MoreMessages, int Answers, const TQueryParams * Params,
  208. TQueryType QueryType);
  209. virtual int __fastcall QueryUserException(const AnsiString Query,
  210. Exception * E, int Answers, const TQueryParams * Params,
  211. TQueryType QueryType);
  212. virtual bool __fastcall PromptUser(TSessionData * Data, AnsiString Prompt,
  213. TPromptKind Kind, AnsiString & Response);
  214. virtual void __fastcall DisplayBanner(const AnsiString & Banner);
  215. virtual void __fastcall ShowExtendedException(Exception * E);
  216. virtual void __fastcall Closed();
  217. private:
  218. TTerminal * FTerminal;
  219. unsigned int FTerminalThread;
  220. };
  221. //---------------------------------------------------------------------------
  222. __fastcall TTunnelUI::TTunnelUI(TTerminal * Terminal)
  223. {
  224. FTerminal = Terminal;
  225. FTerminalThread = GetCurrentThreadId();
  226. }
  227. //---------------------------------------------------------------------------
  228. void __fastcall TTunnelUI::Information(const AnsiString & Str, bool Status)
  229. {
  230. if (GetCurrentThreadId() == FTerminalThread)
  231. {
  232. FTerminal->Information(Str, Status);
  233. }
  234. }
  235. //---------------------------------------------------------------------------
  236. int __fastcall TTunnelUI::QueryUser(const AnsiString Query,
  237. TStrings * MoreMessages, int Answers, const TQueryParams * Params,
  238. TQueryType QueryType)
  239. {
  240. int Result;
  241. if (GetCurrentThreadId() == FTerminalThread)
  242. {
  243. Result = FTerminal->QueryUser(Query, MoreMessages, Answers, Params, QueryType);
  244. }
  245. else
  246. {
  247. Result = AbortAnswer(Answers);
  248. }
  249. return Result;
  250. }
  251. //---------------------------------------------------------------------------
  252. int __fastcall TTunnelUI::QueryUserException(const AnsiString Query,
  253. Exception * E, int Answers, const TQueryParams * Params,
  254. TQueryType QueryType)
  255. {
  256. int Result;
  257. if (GetCurrentThreadId() == FTerminalThread)
  258. {
  259. Result = FTerminal->QueryUserException(Query, E, Answers, Params, QueryType);
  260. }
  261. else
  262. {
  263. Result = AbortAnswer(Answers);
  264. }
  265. return Result;
  266. }
  267. //---------------------------------------------------------------------------
  268. bool __fastcall TTunnelUI::PromptUser(TSessionData * Data, AnsiString Prompt,
  269. TPromptKind Kind, AnsiString & Response)
  270. {
  271. bool Result;
  272. if (GetCurrentThreadId() == FTerminalThread)
  273. {
  274. Result = FTerminal->PromptUser(Data, Prompt, Kind, Response);
  275. }
  276. else
  277. {
  278. Result = false;
  279. }
  280. return Result;
  281. }
  282. //---------------------------------------------------------------------------
  283. void __fastcall TTunnelUI::DisplayBanner(const AnsiString & Banner)
  284. {
  285. if (GetCurrentThreadId() == FTerminalThread)
  286. {
  287. FTerminal->DisplayBanner(Banner);
  288. }
  289. }
  290. //---------------------------------------------------------------------------
  291. void __fastcall TTunnelUI::ShowExtendedException(Exception * E)
  292. {
  293. if (GetCurrentThreadId() == FTerminalThread)
  294. {
  295. FTerminal->ShowExtendedException(E);
  296. }
  297. }
  298. //---------------------------------------------------------------------------
  299. void __fastcall TTunnelUI::Closed()
  300. {
  301. // noop
  302. }
  303. //---------------------------------------------------------------------------
  304. //---------------------------------------------------------------------------
  305. __fastcall TTerminal::TTerminal(TSessionData * SessionData,
  306. TConfiguration * Configuration)
  307. {
  308. FConfiguration = Configuration;
  309. FSessionData = new TSessionData("");
  310. FSessionData->Assign(SessionData);
  311. FLog = new TSessionLog(this, FSessionData, Configuration);
  312. FFiles = new TRemoteDirectory(this);
  313. FExceptionOnFail = 0;
  314. FInTransaction = 0;
  315. FReadCurrentDirectoryPending = false;
  316. FReadDirectoryPending = false;
  317. FUsersGroupsLookedup = False;
  318. FTunnelLocalPortNumber = 0;
  319. FGroups = new TUsersGroupsList();
  320. FUsers = new TUsersGroupsList();
  321. FFileSystem = NULL;
  322. FSecureShell = NULL;
  323. FOnProgress = NULL;
  324. FOnFinished = NULL;
  325. FOnDeleteLocalFile = NULL;
  326. FOnReadDirectoryProgress = NULL;
  327. FOnQueryUser = NULL;
  328. FOnPromptUser = NULL;
  329. FOnDisplayBanner = NULL;
  330. FOnShowExtendedException = NULL;
  331. FOnInformation = NULL;
  332. FOnClose = NULL;
  333. FUseBusyCursor = True;
  334. FLockDirectory = "";
  335. FDirectoryCache = new TRemoteDirectoryCache();
  336. FDirectoryChangesCache = NULL;
  337. FFSProtocol = cfsUnknown;
  338. FCommandSession = NULL;
  339. FAutoReadDirectory = true;
  340. FReadingCurrentDirectory = false;
  341. FStatus = ssClosed;
  342. FTunnelThread = NULL;
  343. FTunnel = NULL;
  344. FTunnelData = NULL;
  345. FTunnelLog = NULL;
  346. FTunnelUI = NULL;
  347. }
  348. //---------------------------------------------------------------------------
  349. __fastcall TTerminal::~TTerminal()
  350. {
  351. if (Active)
  352. {
  353. Close();
  354. }
  355. assert(FTunnel == NULL);
  356. SAFE_DESTROY(FCommandSession);
  357. if (SessionData->CacheDirectoryChanges && SessionData->PreserveDirectoryChanges &&
  358. (FDirectoryChangesCache != NULL))
  359. {
  360. Configuration->SaveDirectoryChangesCache(SessionData->SessionKey,
  361. FDirectoryChangesCache);
  362. }
  363. SAFE_DESTROY_EX(TCustomFileSystem, FFileSystem);
  364. SAFE_DESTROY_EX(TSessionLog, FLog);
  365. delete FFiles;
  366. delete FGroups;
  367. delete FUsers;
  368. delete FDirectoryCache;
  369. delete FDirectoryChangesCache;
  370. SAFE_DESTROY(FSessionData);
  371. }
  372. //---------------------------------------------------------------------------
  373. void __fastcall TTerminal::Idle()
  374. {
  375. if (Configuration->LogProtocol >= 1)
  376. {
  377. LogEvent("Session upkeep");
  378. }
  379. assert(FFileSystem != NULL);
  380. FFileSystem->Idle();
  381. if (CommandSessionOpened)
  382. {
  383. try
  384. {
  385. FCommandSession->Idle();
  386. }
  387. catch(Exception & E)
  388. {
  389. // If the secondary session is dropped, ignore the error and let
  390. // it be reconnected when needed.
  391. // BTW, non-fatal error can hardly happen here, that's why
  392. // it is displayed, because it can be useful to know.
  393. if (FCommandSession->Active)
  394. {
  395. FCommandSession->ShowExtendedException(&E);
  396. }
  397. }
  398. }
  399. }
  400. //---------------------------------------------------------------------------
  401. bool __fastcall TTerminal::IsAbsolutePath(const AnsiString Path)
  402. {
  403. return !Path.IsEmpty() && Path[1] == '/';
  404. }
  405. //---------------------------------------------------------------------------
  406. AnsiString __fastcall TTerminal::ExpandFileName(AnsiString Path,
  407. const AnsiString BasePath)
  408. {
  409. Path = UnixExcludeTrailingBackslash(Path);
  410. if (!IsAbsolutePath(Path) && !BasePath.IsEmpty())
  411. {
  412. // TODO: Handle more complicated cases like "../../xxx"
  413. if (Path == "..")
  414. {
  415. Path = UnixExcludeTrailingBackslash(UnixExtractFilePath(
  416. UnixExcludeTrailingBackslash(BasePath)));
  417. }
  418. else
  419. {
  420. Path = UnixIncludeTrailingBackslash(BasePath) + Path;
  421. }
  422. }
  423. return Path;
  424. }
  425. //---------------------------------------------------------------------------
  426. bool __fastcall TTerminal::GetActive()
  427. {
  428. return (FFileSystem != NULL) && FFileSystem->GetActive();
  429. }
  430. //---------------------------------------------------------------------------
  431. void __fastcall TTerminal::Close()
  432. {
  433. FFileSystem->Close();
  434. if (CommandSessionOpened)
  435. {
  436. FCommandSession->Close();
  437. }
  438. }
  439. //---------------------------------------------------------------------------
  440. void __fastcall TTerminal::ResetConnection()
  441. {
  442. FAnyInformation = false;
  443. // used to be called from Reopen(), why?
  444. FTunnelError = "";
  445. if (FDirectoryChangesCache != NULL)
  446. {
  447. delete FDirectoryChangesCache;
  448. FDirectoryChangesCache = NULL;
  449. }
  450. }
  451. //---------------------------------------------------------------------------
  452. void __fastcall TTerminal::Open()
  453. {
  454. try
  455. {
  456. try
  457. {
  458. ResetConnection();
  459. FStatus = ssOpening;
  460. try
  461. {
  462. if (FFileSystem == NULL)
  463. {
  464. Log->AddStartupInfo();
  465. }
  466. assert(FTunnel == NULL);
  467. if (FSessionData->Tunnel)
  468. {
  469. DoInformation(LoadStr(OPEN_TUNNEL), true);
  470. LogEvent("Opening tunnel.");
  471. OpenTunnel();
  472. Log->AddSeparator();
  473. FSessionData->ConfigureTunnel(FTunnelLocalPortNumber);
  474. DoInformation(LoadStr(USING_TUNNEL), false);
  475. LogEvent(FORMAT("Connecting via tunnel interface %s:%d.",
  476. (FSessionData->HostName, FSessionData->PortNumber)));
  477. }
  478. else
  479. {
  480. FTunnelLocalPortNumber = 0;
  481. }
  482. if (FFileSystem == NULL)
  483. {
  484. if (SessionData->FSProtocol == fsFTP)
  485. {
  486. #ifdef NO_FILEZILLA
  487. LogEvent("FTP protocol is not supported by this build.");
  488. FatalError(NULL, LoadStr(FTP_UNSUPPORTED));
  489. #else
  490. FFSProtocol = cfsFTP;
  491. FFileSystem = new TFTPFileSystem(this);
  492. FFileSystem->Open();
  493. Log->AddSeparator();
  494. LogEvent("Using FTP protocol.");
  495. #endif
  496. }
  497. else
  498. {
  499. assert(FSecureShell == NULL);
  500. try
  501. {
  502. FSecureShell = new TSecureShell(this, FSessionData, Log, Configuration);
  503. try
  504. {
  505. FSecureShell->Open();
  506. }
  507. catch(Exception & E)
  508. {
  509. assert(!FSecureShell->Active);
  510. if (!FSecureShell->Active && !FTunnelError.IsEmpty())
  511. {
  512. // the only case where we expect this to happen
  513. assert(E.Message == LoadStr(UNEXPECTED_CLOSE_ERROR));
  514. FatalError(&E, FMTLOAD(TUNNEL_ERROR, (FTunnelError)));
  515. }
  516. else
  517. {
  518. throw;
  519. }
  520. }
  521. Log->AddSeparator();
  522. if ((SessionData->FSProtocol == fsSCPonly) ||
  523. (SessionData->FSProtocol == fsSFTP && FSecureShell->SshFallbackCmd()))
  524. {
  525. FFSProtocol = cfsSCP;
  526. FFileSystem = new TSCPFileSystem(this, FSecureShell);
  527. FSecureShell = NULL; // ownership passed
  528. LogEvent("Using SCP protocol.");
  529. }
  530. else
  531. {
  532. FFSProtocol = cfsSFTP;
  533. FFileSystem = new TSFTPFileSystem(this, FSecureShell);
  534. FSecureShell = NULL; // ownership passed
  535. LogEvent("Using SFTP protocol.");
  536. }
  537. }
  538. __finally
  539. {
  540. delete FSecureShell;
  541. FSecureShell = NULL;
  542. }
  543. }
  544. }
  545. else
  546. {
  547. FFileSystem->Open();
  548. }
  549. }
  550. __finally
  551. {
  552. if (FSessionData->Tunnel)
  553. {
  554. FSessionData->RollbackTunnel();
  555. }
  556. }
  557. if (SessionData->CacheDirectoryChanges)
  558. {
  559. assert(FDirectoryChangesCache == NULL);
  560. FDirectoryChangesCache = new TRemoteDirectoryChangesCache();
  561. if (SessionData->PreserveDirectoryChanges)
  562. {
  563. Configuration->LoadDirectoryChangesCache(SessionData->SessionKey,
  564. FDirectoryChangesCache);
  565. }
  566. }
  567. DoStartup();
  568. DoInformation(LoadStr(STATUS_READY), true);
  569. FStatus = ssOpened;
  570. }
  571. catch(...)
  572. {
  573. // rollback
  574. if (FDirectoryChangesCache != NULL)
  575. {
  576. delete FDirectoryChangesCache;
  577. FDirectoryChangesCache = NULL;
  578. }
  579. throw;
  580. }
  581. }
  582. __finally
  583. {
  584. // Prevent calling Information with active=false unless there was at least
  585. // one call with active=true
  586. if (FAnyInformation)
  587. {
  588. DoInformation("", true, false);
  589. }
  590. }
  591. }
  592. //---------------------------------------------------------------------------
  593. void __fastcall TTerminal::OpenTunnel()
  594. {
  595. assert(FTunnelData == NULL);
  596. try
  597. {
  598. FTunnelLocalPortNumber = FSessionData->TunnelLocalPortNumber;
  599. if (FTunnelLocalPortNumber == 0)
  600. {
  601. FTunnelLocalPortNumber = Configuration->TunnelLocalPortNumberLow;
  602. while (!IsListenerFree(FTunnelLocalPortNumber))
  603. {
  604. FTunnelLocalPortNumber++;
  605. if (FTunnelLocalPortNumber > Configuration->TunnelLocalPortNumberHigh)
  606. {
  607. FatalError(NULL, FMTLOAD(TUNNEL_NO_FREE_PORT,
  608. (Configuration->TunnelLocalPortNumberLow, Configuration->TunnelLocalPortNumberHigh)));
  609. }
  610. }
  611. LogEvent(FORMAT("Autoselected tunnel local port number %d", (FTunnelLocalPortNumber)));
  612. }
  613. FTunnelData = new TSessionData("");
  614. FTunnelData->Assign(StoredSessions->DefaultSettings);
  615. FTunnelData->Name = FMTLOAD(TUNNEL_SESSION_NAME, (FSessionData->SessionName));
  616. FTunnelData->Tunnel = false;
  617. FTunnelData->HostName = FSessionData->TunnelHostName;
  618. FTunnelData->PortNumber = FSessionData->TunnelPortNumber;
  619. FTunnelData->UserName = FSessionData->TunnelUserName;
  620. FTunnelData->Password = FSessionData->TunnelPassword;
  621. FTunnelData->PublicKeyFile = FSessionData->TunnelPublicKeyFile;
  622. FTunnelData->TunnelPortFwd = FORMAT("L%d\t%s:%d",
  623. (FTunnelLocalPortNumber, FSessionData->HostName, FSessionData->PortNumber));
  624. FTunnelData->ProxyMethod = FSessionData->ProxyMethod;
  625. FTunnelData->ProxyHost = FSessionData->ProxyHost;
  626. FTunnelData->ProxyPort = FSessionData->ProxyPort;
  627. FTunnelData->ProxyUsername = FSessionData->ProxyUsername;
  628. FTunnelData->ProxyPassword = FSessionData->ProxyPassword;
  629. FTunnelData->ProxyTelnetCommand = FSessionData->ProxyTelnetCommand;
  630. FTunnelData->ProxyDNS = FSessionData->ProxyDNS;
  631. FTunnelData->ProxyLocalhost = FSessionData->ProxyLocalhost;
  632. FTunnelLog = new TSessionLog(this, FTunnelData, Configuration);
  633. FTunnelLog->Parent = FLog;
  634. FTunnelLog->Name = "Tunnel";
  635. FTunnelUI = new TTunnelUI(this);
  636. FTunnel = new TSecureShell(FTunnelUI, FTunnelData, FTunnelLog, Configuration);
  637. FTunnel->Open();
  638. FTunnelThread = new TTunnelThread(FTunnel);
  639. }
  640. catch(...)
  641. {
  642. CloseTunnel();
  643. throw;
  644. }
  645. }
  646. //---------------------------------------------------------------------------
  647. void __fastcall TTerminal::CloseTunnel()
  648. {
  649. SAFE_DESTROY_EX(TTunnelThread, FTunnelThread);
  650. FTunnelError = FTunnel->LastTunnelError;
  651. SAFE_DESTROY_EX(TSecureShell, FTunnel);
  652. SAFE_DESTROY_EX(TTunnelUI, FTunnelUI);
  653. SAFE_DESTROY_EX(TSessionLog, FTunnelLog);
  654. SAFE_DESTROY(FTunnelData);
  655. }
  656. //---------------------------------------------------------------------------
  657. void __fastcall TTerminal::Closed()
  658. {
  659. if (FTunnel != NULL)
  660. {
  661. CloseTunnel();
  662. }
  663. if (OnClose)
  664. {
  665. OnClose(this);
  666. }
  667. FStatus = ssClosed;
  668. }
  669. //---------------------------------------------------------------------------
  670. void __fastcall TTerminal::Reopen(int Params)
  671. {
  672. assert(FExceptionOnFail == 0);
  673. TFSProtocol OrigFSProtocol = SessionData->FSProtocol;
  674. AnsiString PrevRemoteDirectory = SessionData->RemoteDirectory;
  675. bool PrevReadCurrentDirectoryPending = FReadCurrentDirectoryPending;
  676. bool PrevReadDirectoryPending = FReadDirectoryPending;
  677. int PrevInTransaction = FInTransaction;
  678. bool PrevAutoReadDirectory = FAutoReadDirectory;
  679. try
  680. {
  681. FReadCurrentDirectoryPending = false;
  682. FReadDirectoryPending = false;
  683. FInTransaction = 0;
  684. // typically, we avoid reading directory, when there is operation ongoing,
  685. // for file list which may reference files from current directory
  686. if (FLAGSET(Params, ropNoReadDirectory))
  687. {
  688. AutoReadDirectory = false;
  689. }
  690. SessionData->RemoteDirectory = CurrentDirectory;
  691. if (SessionData->FSProtocol == fsSFTP)
  692. {
  693. SessionData->FSProtocol = (FFSProtocol == cfsSCP ? fsSCPonly : fsSFTPonly);
  694. }
  695. if (Active)
  696. {
  697. Close();
  698. }
  699. Open();
  700. }
  701. __finally
  702. {
  703. SessionData->RemoteDirectory = PrevRemoteDirectory;
  704. SessionData->FSProtocol = OrigFSProtocol;
  705. FAutoReadDirectory = PrevAutoReadDirectory;
  706. FReadCurrentDirectoryPending = PrevReadCurrentDirectoryPending;
  707. FReadDirectoryPending = PrevReadDirectoryPending;
  708. FInTransaction = PrevInTransaction;
  709. }
  710. }
  711. //---------------------------------------------------------------------------
  712. bool __fastcall TTerminal::PromptUser(TSessionData * Data, AnsiString Prompt,
  713. TPromptKind Kind, AnsiString & Response)
  714. {
  715. // If PromptUser is overriden in descendant class, the overriden version
  716. // is not called when accessed via TSessionIU interface.
  717. // So this is workaround.
  718. return DoPromptUser(Data, Prompt, Kind, Response);
  719. }
  720. //---------------------------------------------------------------------------
  721. bool __fastcall TTerminal::DoPromptUser(TSessionData * /*Data*/, AnsiString Prompt,
  722. TPromptKind Kind, AnsiString & Response)
  723. {
  724. bool Result = false;
  725. if (OnPromptUser != NULL)
  726. {
  727. OnPromptUser(this, Prompt, Kind, Response, Result, NULL);
  728. }
  729. if ((Configuration->RememberPassword) &&
  730. ((Kind == pkPassword) || (Kind == pkPassphrase) || (Kind == pkServerPrompt)))
  731. {
  732. FPassword = EncryptPassword(Response, SessionData->SessionName);
  733. }
  734. return Result;
  735. }
  736. //---------------------------------------------------------------------------
  737. int __fastcall TTerminal::QueryUser(const AnsiString Query,
  738. TStrings * MoreMessages, int Answers, const TQueryParams * Params,
  739. TQueryType QueryType)
  740. {
  741. LogEvent(FORMAT("Asking user:\n%s (%s)", (Query, (MoreMessages ? MoreMessages->CommaText : AnsiString() ))));
  742. int Answer = AbortAnswer(Answers);
  743. if (FOnQueryUser)
  744. {
  745. FOnQueryUser(this, Query, MoreMessages, Answers, Params, Answer, QueryType, NULL);
  746. }
  747. return Answer;
  748. }
  749. //---------------------------------------------------------------------------
  750. int __fastcall TTerminal::QueryUserException(const AnsiString Query,
  751. Exception * E, int Answers, const TQueryParams * Params,
  752. TQueryType QueryType)
  753. {
  754. int Result;
  755. TStrings * MoreMessages = new TStringList();
  756. try
  757. {
  758. if (!E->Message.IsEmpty() && !Query.IsEmpty())
  759. {
  760. MoreMessages->Add(E->Message);
  761. }
  762. ExtException * EE = dynamic_cast<ExtException*>(E);
  763. if ((EE != NULL) && (EE->MoreMessages != NULL))
  764. {
  765. MoreMessages->AddStrings(EE->MoreMessages);
  766. }
  767. Result = QueryUser(!Query.IsEmpty() ? Query : E->Message,
  768. MoreMessages->Count ? MoreMessages : NULL,
  769. Answers, Params, QueryType);
  770. }
  771. __finally
  772. {
  773. delete MoreMessages;
  774. }
  775. return Result;
  776. }
  777. //---------------------------------------------------------------------------
  778. void __fastcall TTerminal::DisplayBanner(const AnsiString & Banner)
  779. {
  780. if (OnDisplayBanner != NULL)
  781. {
  782. if (Configuration->ForceBanners ||
  783. Configuration->ShowBanner(SessionData->SessionKey, Banner))
  784. {
  785. bool NeverShowAgain = false;
  786. int Options =
  787. FLAGMASK(Configuration->ForceBanners, boDisableNeverShowAgain);
  788. OnDisplayBanner(this, SessionData->SessionName, Banner,
  789. NeverShowAgain, Options);
  790. if (!Configuration->ForceBanners && NeverShowAgain)
  791. {
  792. Configuration->NeverShowBanner(SessionData->SessionKey, Banner);
  793. }
  794. }
  795. }
  796. }
  797. //---------------------------------------------------------------------------
  798. void __fastcall TTerminal::ShowExtendedException(Exception * E)
  799. {
  800. Log->AddException(E);
  801. if (OnShowExtendedException != NULL)
  802. {
  803. OnShowExtendedException(this, E, NULL);
  804. }
  805. }
  806. //---------------------------------------------------------------------------
  807. void __fastcall TTerminal::DoInformation(const AnsiString & Str, bool Status,
  808. bool Active)
  809. {
  810. if (Active)
  811. {
  812. FAnyInformation = true;
  813. }
  814. if (OnInformation)
  815. {
  816. OnInformation(this, Str, Status, Active);
  817. }
  818. }
  819. //---------------------------------------------------------------------------
  820. void __fastcall TTerminal::Information(const AnsiString & Str, bool Status)
  821. {
  822. DoInformation(Str, Status);
  823. }
  824. //---------------------------------------------------------------------------
  825. bool __fastcall TTerminal::GetIsCapable(TFSCapability Capability) const
  826. {
  827. assert(FFileSystem);
  828. return FFileSystem->IsCapable(Capability);
  829. }
  830. //---------------------------------------------------------------------------
  831. AnsiString __fastcall TTerminal::AbsolutePath(AnsiString Path)
  832. {
  833. return FFileSystem->AbsolutePath(Path);
  834. }
  835. //---------------------------------------------------------------------------
  836. void __fastcall TTerminal::ReactOnCommand(int /*TFSCommand*/ Cmd)
  837. {
  838. bool ChangesDirectory = false;
  839. bool ModifiesFiles = false;
  840. switch ((TFSCommand)Cmd) {
  841. case fsChangeDirectory:
  842. case fsHomeDirectory:
  843. ChangesDirectory = true;
  844. break;
  845. case fsCopyToRemote:
  846. case fsDeleteFile:
  847. case fsRenameFile:
  848. case fsMoveFile:
  849. case fsCopyFile:
  850. case fsCreateDirectory:
  851. case fsChangeMode:
  852. case fsChangeGroup:
  853. case fsChangeOwner:
  854. case fsChangeProperties:
  855. ModifiesFiles = true;
  856. break;
  857. case fsAnyCommand:
  858. ChangesDirectory = true;
  859. ModifiesFiles = true;
  860. break;
  861. }
  862. if (ChangesDirectory)
  863. {
  864. if (!FInTransaction)
  865. {
  866. ReadCurrentDirectory();
  867. if (AutoReadDirectory)
  868. {
  869. ReadDirectory(false);
  870. }
  871. }
  872. else
  873. {
  874. FReadCurrentDirectoryPending = true;
  875. if (AutoReadDirectory)
  876. {
  877. FReadDirectoryPending = true;
  878. }
  879. }
  880. }
  881. else
  882. if (ModifiesFiles && AutoReadDirectory && Configuration->AutoReadDirectoryAfterOp)
  883. {
  884. if (!FInTransaction) ReadDirectory(true);
  885. else FReadDirectoryPending = true;
  886. }
  887. }
  888. //---------------------------------------------------------------------------
  889. void __fastcall TTerminal::TerminalError(AnsiString Msg)
  890. {
  891. TerminalError(NULL, Msg);
  892. }
  893. //---------------------------------------------------------------------------
  894. void __fastcall TTerminal::TerminalError(Exception * E, AnsiString Msg)
  895. {
  896. throw ETerminal(E, Msg);
  897. }
  898. //---------------------------------------------------------------------------
  899. bool __fastcall TTerminal::DoQueryReopen(Exception * E, int Params)
  900. {
  901. bool Result;
  902. if (FLAGSET(Params, ropNoConfirmation))
  903. {
  904. Result = true;
  905. }
  906. else
  907. {
  908. LogEvent("Connection was lost, asking what to do.");
  909. TQueryParams Params(qpAllowContinueOnError);
  910. Params.Timeout = Configuration->SessionReopenAuto;
  911. Params.TimeoutAnswer = qaRetry;
  912. TQueryButtonAlias Aliases[1];
  913. Aliases[0].Button = qaRetry;
  914. Aliases[0].Alias = LoadStr(RECONNECT_BUTTON);
  915. Params.Aliases = Aliases;
  916. Params.AliasesCount = LENOF(Aliases);
  917. Result = (QueryUserException("", E, qaRetry | qaAbort, &Params, qtError) == qaRetry);
  918. }
  919. return Result;
  920. }
  921. //---------------------------------------------------------------------------
  922. bool __fastcall TTerminal::QueryReopen(Exception * E, int Params,
  923. TFileOperationProgressType * OperationProgress)
  924. {
  925. TSuspendFileOperationProgress Suspend(OperationProgress);
  926. bool Result = DoQueryReopen(E, Params);
  927. if (Result)
  928. {
  929. do
  930. {
  931. try
  932. {
  933. // note that ropNoConfirmation is not set for background transfer only,
  934. // so it may cause temporary hang (e.g. for downloads to editor,
  935. // synchronization, scripting)
  936. if (FLAGSET(Params, ropNoConfirmation))
  937. {
  938. Sleep(Configuration->SessionReopenNoConfirmation);
  939. }
  940. Reopen(Params);
  941. }
  942. catch(Exception & E)
  943. {
  944. if (!Active)
  945. {
  946. Result = DoQueryReopen(&E, Params);
  947. }
  948. else
  949. {
  950. throw;
  951. }
  952. }
  953. }
  954. while (!Active && Result);
  955. }
  956. return Result;
  957. }
  958. //---------------------------------------------------------------------------
  959. bool __fastcall TTerminal::FileOperationLoopQuery(Exception & E,
  960. TFileOperationProgressType * OperationProgress, const AnsiString Message,
  961. bool AllowSkip, AnsiString SpecialRetry)
  962. {
  963. bool Result = false;
  964. Log->AddException(&E);
  965. int Answer;
  966. if (AllowSkip && OperationProgress->SkipToAll)
  967. {
  968. Answer = qaSkip;
  969. }
  970. else
  971. {
  972. int Answers = qaRetry | qaAbort |
  973. FLAGMASK(AllowSkip, (qaSkip | qaAll)) |
  974. FLAGMASK(!SpecialRetry.IsEmpty(), qaYes);
  975. TQueryParams Params(qpAllowContinueOnError | FLAGMASK(!AllowSkip, qpFatalAbort));
  976. TQueryButtonAlias Aliases[2];
  977. int AliasCount = 0;
  978. if (FLAGSET(Answers, qaAll))
  979. {
  980. Aliases[AliasCount].Button = qaAll;
  981. Aliases[AliasCount].Alias = LoadStr(SKIP_ALL_BUTTON);
  982. AliasCount++;
  983. }
  984. if (FLAGSET(Answers, qaYes))
  985. {
  986. Aliases[AliasCount].Button = qaYes;
  987. Aliases[AliasCount].Alias = SpecialRetry;
  988. AliasCount++;
  989. }
  990. if (AliasCount > 0)
  991. {
  992. Params.Aliases = Aliases;
  993. Params.AliasesCount = AliasCount;
  994. }
  995. SUSPEND_OPERATION (
  996. Answer = QueryUserException(Message, &E, Answers, &Params, qtError);
  997. );
  998. if (Answer == qaAll)
  999. {
  1000. OperationProgress->SkipToAll = true;
  1001. Answer = qaSkip;
  1002. }
  1003. if (Answer == qaYes)
  1004. {
  1005. Result = true;
  1006. Answer = qaRetry;
  1007. }
  1008. }
  1009. if (Answer != qaRetry)
  1010. {
  1011. if (Answer == qaAbort)
  1012. {
  1013. OperationProgress->Cancel = csCancel;
  1014. }
  1015. if (AllowSkip)
  1016. {
  1017. THROW_SKIP_FILE(&E, Message);
  1018. }
  1019. else
  1020. {
  1021. // this can happen only during file transfer with SCP
  1022. throw ExtException(&E, Message);
  1023. }
  1024. }
  1025. return Result;
  1026. }
  1027. //---------------------------------------------------------------------------
  1028. int __fastcall TTerminal::FileOperationLoop(TFileOperationEvent CallBackFunc,
  1029. TFileOperationProgressType * OperationProgress, bool AllowSkip,
  1030. const AnsiString Message, void * Param1, void * Param2)
  1031. {
  1032. assert(CallBackFunc);
  1033. int Result;
  1034. FILE_OPERATION_LOOP_EX
  1035. (
  1036. AllowSkip, Message,
  1037. Result = CallBackFunc(Param1, Param2);
  1038. );
  1039. return Result;
  1040. }
  1041. //---------------------------------------------------------------------------
  1042. AnsiString __fastcall TTerminal::TranslateLockedPath(AnsiString Path, bool Lock)
  1043. {
  1044. if (!SessionData->LockInHome || Path.IsEmpty() || (Path[1] != '/'))
  1045. return Path;
  1046. if (Lock)
  1047. {
  1048. if (Path.SubString(1, FLockDirectory.Length()) == FLockDirectory)
  1049. {
  1050. Path.Delete(1, FLockDirectory.Length());
  1051. if (Path.IsEmpty()) Path = "/";
  1052. }
  1053. }
  1054. else
  1055. {
  1056. Path = UnixExcludeTrailingBackslash(FLockDirectory + Path);
  1057. }
  1058. return Path;
  1059. }
  1060. //---------------------------------------------------------------------------
  1061. void __fastcall TTerminal::ClearCaches()
  1062. {
  1063. FDirectoryCache->Clear();
  1064. if (FDirectoryChangesCache != NULL)
  1065. {
  1066. FDirectoryChangesCache->Clear();
  1067. }
  1068. }
  1069. //---------------------------------------------------------------------------
  1070. void __fastcall TTerminal::ClearCachedFileList(const AnsiString Path,
  1071. bool SubDirs)
  1072. {
  1073. FDirectoryCache->ClearFileList(Path, SubDirs);
  1074. }
  1075. //---------------------------------------------------------------------------
  1076. void __fastcall TTerminal::AddCachedFileList(TRemoteFileList * FileList)
  1077. {
  1078. FDirectoryCache->AddFileList(FileList);
  1079. }
  1080. //---------------------------------------------------------------------------
  1081. bool __fastcall TTerminal::DirectoryFileList(const AnsiString Path,
  1082. TRemoteFileList *& FileList, bool CanLoad)
  1083. {
  1084. bool Result = false;
  1085. if (UnixComparePaths(FFiles->Directory, Path))
  1086. {
  1087. Result = (FileList == NULL) || (FileList->Timestamp < FFiles->Timestamp);
  1088. if (Result)
  1089. {
  1090. if (FileList == NULL)
  1091. {
  1092. FileList = new TRemoteFileList();
  1093. }
  1094. FFiles->DuplicateTo(FileList);
  1095. }
  1096. }
  1097. else
  1098. {
  1099. if (((FileList == NULL) && FDirectoryCache->HasFileList(Path)) ||
  1100. ((FileList != NULL) && FDirectoryCache->HasNewerFileList(Path, FileList->Timestamp)))
  1101. {
  1102. bool Created = (FileList == NULL);
  1103. if (Created)
  1104. {
  1105. FileList = new TRemoteFileList();
  1106. }
  1107. Result = FDirectoryCache->GetFileList(Path, FileList);
  1108. if (!Result && Created)
  1109. {
  1110. SAFE_DESTROY(FileList);
  1111. }
  1112. }
  1113. // do not attempt to load file list if there is cached version,
  1114. // only absence of cached version indicates that we consider
  1115. // the directory content obsolete
  1116. else if (CanLoad && !FDirectoryCache->HasFileList(Path))
  1117. {
  1118. bool Created = (FileList == NULL);
  1119. if (Created)
  1120. {
  1121. FileList = new TRemoteFileList();
  1122. }
  1123. FileList->Directory = Path;
  1124. try
  1125. {
  1126. ReadDirectory(FileList);
  1127. Result = true;
  1128. }
  1129. catch(...)
  1130. {
  1131. if (Created)
  1132. {
  1133. SAFE_DESTROY(FileList);
  1134. }
  1135. throw;
  1136. }
  1137. }
  1138. }
  1139. return Result;
  1140. }
  1141. //---------------------------------------------------------------------------
  1142. void __fastcall TTerminal::SetCurrentDirectory(AnsiString value)
  1143. {
  1144. assert(FFileSystem);
  1145. value = TranslateLockedPath(value, false);
  1146. if (value != FFileSystem->CurrentDirectory)
  1147. {
  1148. ChangeDirectory(value);
  1149. }
  1150. }
  1151. //---------------------------------------------------------------------------
  1152. AnsiString __fastcall TTerminal::GetCurrentDirectory()
  1153. {
  1154. if (FFileSystem)
  1155. {
  1156. FCurrentDirectory = FFileSystem->CurrentDirectory;
  1157. if (FCurrentDirectory.IsEmpty())
  1158. {
  1159. ReadCurrentDirectory();
  1160. }
  1161. }
  1162. return TranslateLockedPath(FCurrentDirectory, true);
  1163. }
  1164. //---------------------------------------------------------------------------
  1165. AnsiString __fastcall TTerminal::PeekCurrentDirectory()
  1166. {
  1167. if (FFileSystem)
  1168. {
  1169. FCurrentDirectory = FFileSystem->CurrentDirectory;
  1170. }
  1171. return TranslateLockedPath(FCurrentDirectory, true);
  1172. }
  1173. //---------------------------------------------------------------------------
  1174. TUsersGroupsList * __fastcall TTerminal::GetGroups()
  1175. {
  1176. assert(FFileSystem);
  1177. if (!FUsersGroupsLookedup && SessionData->LookupUserGroups &&
  1178. IsCapable[fcUserGroupListing])
  1179. {
  1180. LookupUsersGroups();
  1181. }
  1182. return FGroups;
  1183. }
  1184. //---------------------------------------------------------------------------
  1185. TUsersGroupsList * __fastcall TTerminal::GetUsers()
  1186. {
  1187. assert(FFileSystem);
  1188. if (!FUsersGroupsLookedup && SessionData->LookupUserGroups &&
  1189. IsCapable[fcUserGroupListing])
  1190. {
  1191. LookupUsersGroups();
  1192. }
  1193. return FUsers;
  1194. }
  1195. //---------------------------------------------------------------------------
  1196. AnsiString __fastcall TTerminal::GetUserName() const
  1197. {
  1198. // in future might also be implemented to detect username similar to GetUserGroups
  1199. assert(FFileSystem != NULL);
  1200. AnsiString Result = FFileSystem->GetUserName();
  1201. // Is empty also when stored password was used
  1202. if (Result.IsEmpty())
  1203. {
  1204. Result = SessionData->UserName;
  1205. }
  1206. return Result;
  1207. }
  1208. //---------------------------------------------------------------------------
  1209. bool __fastcall TTerminal::GetAreCachesEmpty() const
  1210. {
  1211. return FDirectoryCache->IsEmpty &&
  1212. ((FDirectoryChangesCache == NULL) || FDirectoryChangesCache->IsEmpty);
  1213. }
  1214. //---------------------------------------------------------------------------
  1215. void __fastcall TTerminal::DoChangeDirectory()
  1216. {
  1217. if (FOnChangeDirectory)
  1218. {
  1219. FOnChangeDirectory(this);
  1220. }
  1221. }
  1222. //---------------------------------------------------------------------------
  1223. void __fastcall TTerminal::DoReadDirectory(bool ReloadOnly)
  1224. {
  1225. if (FOnReadDirectory)
  1226. {
  1227. FOnReadDirectory(this, ReloadOnly);
  1228. }
  1229. }
  1230. //---------------------------------------------------------------------------
  1231. void __fastcall TTerminal::DoStartReadDirectory()
  1232. {
  1233. if (FOnStartReadDirectory)
  1234. {
  1235. FOnStartReadDirectory(this);
  1236. }
  1237. }
  1238. //---------------------------------------------------------------------------
  1239. void __fastcall TTerminal::DoReadDirectoryProgress(int Progress, bool & Cancel)
  1240. {
  1241. if (FReadingCurrentDirectory && (FOnReadDirectoryProgress != NULL))
  1242. {
  1243. FOnReadDirectoryProgress(this, Progress, Cancel);
  1244. }
  1245. }
  1246. //---------------------------------------------------------------------------
  1247. void __fastcall TTerminal::BeginTransaction()
  1248. {
  1249. if (!FInTransaction)
  1250. {
  1251. FReadCurrentDirectoryPending = false;
  1252. FReadDirectoryPending = false;
  1253. }
  1254. FInTransaction++;
  1255. if (FCommandSession != NULL)
  1256. {
  1257. FCommandSession->BeginTransaction();
  1258. }
  1259. }
  1260. //---------------------------------------------------------------------------
  1261. void __fastcall TTerminal::EndTransaction()
  1262. {
  1263. if (!FInTransaction)
  1264. TerminalError("Can't end transaction, not in transaction");
  1265. assert(FInTransaction > 0);
  1266. FInTransaction--;
  1267. // it connection was closed due to fatal error during transaction, do nothing
  1268. if (Active)
  1269. {
  1270. if (FInTransaction == 0)
  1271. {
  1272. try
  1273. {
  1274. if (FReadCurrentDirectoryPending) ReadCurrentDirectory();
  1275. if (FReadDirectoryPending) ReadDirectory(!FReadCurrentDirectoryPending);
  1276. }
  1277. __finally
  1278. {
  1279. FReadCurrentDirectoryPending = false;
  1280. FReadDirectoryPending = false;
  1281. }
  1282. }
  1283. }
  1284. if (FCommandSession != NULL)
  1285. {
  1286. FCommandSession->EndTransaction();
  1287. }
  1288. }
  1289. //---------------------------------------------------------------------------
  1290. void __fastcall TTerminal::SetExceptionOnFail(bool value)
  1291. {
  1292. if (value) FExceptionOnFail++;
  1293. else
  1294. {
  1295. if (FExceptionOnFail == 0)
  1296. throw Exception("ExceptionOnFail is already zero.");
  1297. FExceptionOnFail--;
  1298. }
  1299. if (FCommandSession != NULL)
  1300. {
  1301. FCommandSession->FExceptionOnFail = FExceptionOnFail;
  1302. }
  1303. }
  1304. //---------------------------------------------------------------------------
  1305. bool __fastcall TTerminal::GetExceptionOnFail() const
  1306. {
  1307. return (bool)(FExceptionOnFail > 0);
  1308. }
  1309. //---------------------------------------------------------------------------
  1310. void __fastcall TTerminal::FatalError(Exception * E, AnsiString Msg)
  1311. {
  1312. // the same code is in TSecureShell
  1313. if (Active)
  1314. {
  1315. // We log this instead of exception handler, because Close() would
  1316. // probably cause exception handler to loose pointer to TShellLog()
  1317. LogEvent("Attempt to close connection due to fatal exception:");
  1318. Log->Add(llException, Msg);
  1319. Log->AddException(E);
  1320. Close();
  1321. }
  1322. SSH_FATAL_ERROR_EXT(E, Msg);
  1323. }
  1324. //---------------------------------------------------------------------------
  1325. void __fastcall TTerminal::CommandError(Exception * E, const AnsiString Msg)
  1326. {
  1327. CommandError(E, Msg, 0);
  1328. }
  1329. //---------------------------------------------------------------------------
  1330. int __fastcall TTerminal::CommandError(Exception * E, const AnsiString Msg,
  1331. int Answers)
  1332. {
  1333. int Result = 0;
  1334. if (E && E->InheritsFrom(__classid(EFatal)))
  1335. {
  1336. FatalError(E, Msg);
  1337. }
  1338. else if (E && E->InheritsFrom(__classid(EAbort)))
  1339. {
  1340. // resent EAbort exception
  1341. Abort();
  1342. }
  1343. else if (ExceptionOnFail)
  1344. {
  1345. throw ECommand(E, Msg);
  1346. }
  1347. else if (!Answers)
  1348. {
  1349. ECommand * ECmd = new ECommand(E, Msg);
  1350. try
  1351. {
  1352. ShowExtendedException(ECmd);
  1353. }
  1354. __finally
  1355. {
  1356. delete ECmd;
  1357. }
  1358. }
  1359. else
  1360. {
  1361. // small hack to anable "skip to all" for COMMAND_ERROR_ARI
  1362. bool CanSkip = FLAGSET(Answers, qaSkip) && (OperationProgress != NULL);
  1363. if (CanSkip && OperationProgress->SkipToAll)
  1364. {
  1365. Result = qaSkip;
  1366. }
  1367. else
  1368. {
  1369. TQueryParams Params(qpAllowContinueOnError);
  1370. TQueryButtonAlias Aliases[1];
  1371. if (CanSkip)
  1372. {
  1373. Aliases[0].Button = qaAll;
  1374. Aliases[0].Alias = LoadStr(SKIP_ALL_BUTTON);
  1375. Params.Aliases = Aliases;
  1376. Params.AliasesCount = LENOF(Aliases);
  1377. Answers |= qaAll;
  1378. }
  1379. Result = QueryUserException(Msg, E, Answers, &Params, qtError);
  1380. if (Result == qaAll)
  1381. {
  1382. assert(OperationProgress != NULL);
  1383. OperationProgress->SkipToAll = true;
  1384. Result = qaSkip;
  1385. }
  1386. }
  1387. }
  1388. return Result;
  1389. }
  1390. //---------------------------------------------------------------------------
  1391. bool __fastcall TTerminal::HandleException(Exception * E)
  1392. {
  1393. if (ExceptionOnFail)
  1394. {
  1395. return false;
  1396. }
  1397. else
  1398. {
  1399. Log->AddException(E);
  1400. return true;
  1401. }
  1402. }
  1403. //---------------------------------------------------------------------------
  1404. void __fastcall TTerminal::CloseOnCompletion(const AnsiString Message)
  1405. {
  1406. LogEvent("Closing session after completed operation (as requested by user)");
  1407. Close();
  1408. throw ESshTerminate(NULL,
  1409. Message.IsEmpty() ? LoadStr(CLOSED_ON_COMPLETION) : Message);
  1410. }
  1411. //---------------------------------------------------------------------------
  1412. int __fastcall TTerminal::ConfirmFileOverwrite(const AnsiString FileName,
  1413. const TOverwriteFileParams * FileParams, int Answers, const TQueryParams * Params,
  1414. TOperationSide Side, TFileOperationProgressType * OperationProgress)
  1415. {
  1416. int Answer;
  1417. int AnswerForNewer =
  1418. (CompareFileTime(FileParams->SourceTimestamp, FileParams->DestTimestamp) > 0) ?
  1419. qaYes : qaNo;
  1420. if (OperationProgress->YesToNewer)
  1421. {
  1422. Answer = AnswerForNewer;
  1423. }
  1424. else
  1425. {
  1426. AnsiString Message = FMTLOAD((Side == osLocal ? LOCAL_FILE_OVERWRITE :
  1427. REMOTE_FILE_OVERWRITE), (FileName));
  1428. if (FileParams)
  1429. {
  1430. Message = FMTLOAD(FILE_OVERWRITE_DETAILS, (Message,
  1431. IntToStr(FileParams->SourceSize),
  1432. UserModificationStr(FileParams->SourceTimestamp, FileParams->SourcePrecision),
  1433. IntToStr(FileParams->DestSize),
  1434. UserModificationStr(FileParams->DestTimestamp, FileParams->DestPrecision)));
  1435. }
  1436. Answer = QueryUser(Message, NULL, Answers, Params);
  1437. switch (Answer)
  1438. {
  1439. case qaNeverAskAgain:
  1440. Configuration->ConfirmOverwriting = false;
  1441. Answer = qaYes;
  1442. break;
  1443. case qaYesToAll:
  1444. OperationProgress->YesToAll = true;
  1445. Answer = qaYes;
  1446. break;
  1447. case qaAll:
  1448. OperationProgress->YesToNewer = true;
  1449. Answer = AnswerForNewer;
  1450. break;
  1451. case qaNoToAll:
  1452. OperationProgress->NoToAll = true;
  1453. Answer = qaNo;
  1454. }
  1455. }
  1456. return Answer;
  1457. }
  1458. //---------------------------------------------------------------------------
  1459. void __fastcall TTerminal::FileModified(const TRemoteFile * File,
  1460. const AnsiString FileName, bool ClearDirectoryChange)
  1461. {
  1462. AnsiString ParentDirectory;
  1463. AnsiString Directory;
  1464. if (SessionData->CacheDirectories || SessionData->CacheDirectoryChanges)
  1465. {
  1466. if ((File != NULL) && (File->Directory != NULL))
  1467. {
  1468. if (File->IsDirectory)
  1469. {
  1470. Directory = File->Directory->FullDirectory + File->FileName;
  1471. }
  1472. ParentDirectory = File->Directory->Directory;
  1473. }
  1474. else if (!FileName.IsEmpty())
  1475. {
  1476. ParentDirectory = UnixExtractFilePath(FileName);
  1477. if (ParentDirectory.IsEmpty())
  1478. {
  1479. ParentDirectory = CurrentDirectory;
  1480. }
  1481. // this case for scripting
  1482. if ((File != NULL) && File->IsDirectory)
  1483. {
  1484. Directory = UnixIncludeTrailingBackslash(ParentDirectory) +
  1485. UnixExtractFileName(File->FileName);
  1486. }
  1487. }
  1488. }
  1489. if (SessionData->CacheDirectories)
  1490. {
  1491. if (!Directory.IsEmpty())
  1492. {
  1493. DirectoryModified(Directory, true);
  1494. }
  1495. if (!ParentDirectory.IsEmpty())
  1496. {
  1497. DirectoryModified(ParentDirectory, false);
  1498. }
  1499. }
  1500. if (SessionData->CacheDirectoryChanges && ClearDirectoryChange)
  1501. {
  1502. if (!Directory.IsEmpty())
  1503. {
  1504. FDirectoryChangesCache->ClearDirectoryChange(Directory);
  1505. FDirectoryChangesCache->ClearDirectoryChangeTarget(Directory);
  1506. }
  1507. }
  1508. }
  1509. //---------------------------------------------------------------------------
  1510. void __fastcall TTerminal::DoDirectoryModified(const AnsiString Path, bool SubDirs)
  1511. {
  1512. if (OnDirectoryModified != NULL)
  1513. {
  1514. OnDirectoryModified(this, Path, SubDirs);
  1515. }
  1516. }
  1517. //---------------------------------------------------------------------------
  1518. void __fastcall TTerminal::DirectoryModified(const AnsiString Path, bool SubDirs)
  1519. {
  1520. if (Path.IsEmpty())
  1521. {
  1522. ClearCachedFileList(CurrentDirectory, SubDirs);
  1523. }
  1524. else
  1525. {
  1526. ClearCachedFileList(Path, SubDirs);
  1527. }
  1528. DoDirectoryModified(Path, SubDirs);
  1529. }
  1530. //---------------------------------------------------------------------------
  1531. void __fastcall TTerminal::DirectoryLoaded(TRemoteFileList * FileList)
  1532. {
  1533. AddCachedFileList(FileList);
  1534. }
  1535. //---------------------------------------------------------------------------
  1536. void __fastcall TTerminal::ReloadDirectory()
  1537. {
  1538. if (SessionData->CacheDirectories)
  1539. {
  1540. DirectoryModified(CurrentDirectory, false);
  1541. }
  1542. if (SessionData->CacheDirectoryChanges)
  1543. {
  1544. assert(FDirectoryChangesCache != NULL);
  1545. FDirectoryChangesCache->ClearDirectoryChange(CurrentDirectory);
  1546. }
  1547. ReadCurrentDirectory();
  1548. FReadCurrentDirectoryPending = false;
  1549. ReadDirectory(true);
  1550. FReadDirectoryPending = false;
  1551. }
  1552. //---------------------------------------------------------------------------
  1553. void __fastcall TTerminal::RefreshDirectory()
  1554. {
  1555. if (SessionData->CacheDirectories &&
  1556. FDirectoryCache->HasNewerFileList(CurrentDirectory, FFiles->Timestamp))
  1557. {
  1558. // Second parameter was added to allow (rather force) using the cache.
  1559. // Before, the directory was reloaded always, it seems useless,
  1560. // has it any reason?
  1561. ReadDirectory(true, true);
  1562. FReadDirectoryPending = false;
  1563. }
  1564. }
  1565. //---------------------------------------------------------------------------
  1566. void __fastcall TTerminal::EnsureNonExistence(const AnsiString FileName)
  1567. {
  1568. // if filename doesn't contain path, we check for existence of file
  1569. if ((UnixExtractFileDir(FileName).IsEmpty()) &&
  1570. UnixComparePaths(CurrentDirectory, FFiles->Directory))
  1571. {
  1572. TRemoteFile *File = FFiles->FindFile(FileName);
  1573. if (File)
  1574. {
  1575. if (File->IsDirectory) throw ECommand(NULL, FMTLOAD(RENAME_CREATE_DIR_EXISTS, (FileName)));
  1576. else throw ECommand(NULL, FMTLOAD(RENAME_CREATE_FILE_EXISTS, (FileName)));
  1577. }
  1578. }
  1579. }
  1580. //---------------------------------------------------------------------------
  1581. void __fastcall inline TTerminal::LogEvent(const AnsiString & Str)
  1582. {
  1583. if (Log->Logging)
  1584. {
  1585. Log->Add(llMessage, Str);
  1586. }
  1587. }
  1588. //---------------------------------------------------------------------------
  1589. void __fastcall TTerminal::DoStartup()
  1590. {
  1591. LogEvent("Doing startup conversation with host.");
  1592. BeginTransaction();
  1593. try
  1594. {
  1595. DoInformation(LoadStr(STATUS_STARTUP), true);
  1596. // Make sure that directory would be loaded at last
  1597. FReadCurrentDirectoryPending = true;
  1598. FReadDirectoryPending = AutoReadDirectory;
  1599. FFileSystem->DoStartup();
  1600. if (SessionData->LookupUserGroups && IsCapable[fcUserGroupListing])
  1601. {
  1602. LookupUsersGroups();
  1603. }
  1604. DoInformation(LoadStr(STATUS_OPEN_DIRECTORY), true);
  1605. if (!SessionData->RemoteDirectory.IsEmpty())
  1606. {
  1607. ChangeDirectory(SessionData->RemoteDirectory);
  1608. }
  1609. }
  1610. __finally
  1611. {
  1612. EndTransaction();
  1613. }
  1614. LogEvent("Startup conversation with host finished.");
  1615. }
  1616. //---------------------------------------------------------------------------
  1617. void __fastcall TTerminal::ReadCurrentDirectory()
  1618. {
  1619. assert(FFileSystem);
  1620. try
  1621. {
  1622. // reset flag is case we are called externally (like from console dialog)
  1623. FReadCurrentDirectoryPending = false;
  1624. LogEvent("Getting current directory name.");
  1625. AnsiString OldDirectory = FFileSystem->CurrentDirectory;
  1626. FFileSystem->ReadCurrentDirectory();
  1627. ReactOnCommand(fsCurrentDirectory);
  1628. if (SessionData->CacheDirectoryChanges)
  1629. {
  1630. assert(FDirectoryChangesCache != NULL);
  1631. FDirectoryChangesCache->AddDirectoryChange(OldDirectory,
  1632. FLastDirectoryChange, CurrentDirectory);
  1633. // not to broke the cache, if the next directory change would not
  1634. // be initialited by ChangeDirectory(), which sets it
  1635. // (HomeDirectory() particularly)
  1636. FLastDirectoryChange = "";
  1637. }
  1638. if (OldDirectory.IsEmpty())
  1639. {
  1640. FLockDirectory = (SessionData->LockInHome ?
  1641. FFileSystem->CurrentDirectory : AnsiString(""));
  1642. }
  1643. if (OldDirectory != FFileSystem->CurrentDirectory) DoChangeDirectory();
  1644. }
  1645. catch (Exception &E)
  1646. {
  1647. CommandError(&E, LoadStr(READ_CURRENT_DIR_ERROR));
  1648. }
  1649. }
  1650. //---------------------------------------------------------------------------
  1651. void __fastcall TTerminal::ReadDirectory(bool ReloadOnly, bool ForceCache)
  1652. {
  1653. bool LoadedFromCache = false;
  1654. if (SessionData->CacheDirectories && FDirectoryCache->HasFileList(CurrentDirectory))
  1655. {
  1656. if (ReloadOnly && !ForceCache)
  1657. {
  1658. LogEvent("Cached directory not reloaded.");
  1659. }
  1660. else
  1661. {
  1662. DoStartReadDirectory();
  1663. try
  1664. {
  1665. LoadedFromCache = FDirectoryCache->GetFileList(CurrentDirectory, FFiles);
  1666. }
  1667. __finally
  1668. {
  1669. DoReadDirectory(ReloadOnly);
  1670. }
  1671. if (LoadedFromCache)
  1672. {
  1673. LogEvent("Directory content loaded from cache.");
  1674. }
  1675. else
  1676. {
  1677. LogEvent("Cached Directory content has been removed.");
  1678. }
  1679. }
  1680. }
  1681. if (!LoadedFromCache)
  1682. {
  1683. DoStartReadDirectory();
  1684. FReadingCurrentDirectory = true;
  1685. bool Cancel = false; // dummy
  1686. DoReadDirectoryProgress(0, Cancel);
  1687. try
  1688. {
  1689. TRemoteDirectory * Files = new TRemoteDirectory(this);
  1690. try
  1691. {
  1692. Files->Directory = CurrentDirectory;
  1693. CustomReadDirectory(Files);
  1694. }
  1695. __finally
  1696. {
  1697. DoReadDirectoryProgress(-1, Cancel);
  1698. FReadingCurrentDirectory = false;
  1699. delete FFiles;
  1700. FFiles = Files;
  1701. DoReadDirectory(ReloadOnly);
  1702. if (Active)
  1703. {
  1704. if (SessionData->CacheDirectories)
  1705. {
  1706. DirectoryLoaded(FFiles);
  1707. }
  1708. }
  1709. }
  1710. }
  1711. catch (Exception &E)
  1712. {
  1713. CommandError(&E, FmtLoadStr(LIST_DIR_ERROR, ARRAYOFCONST((FFiles->Directory))));
  1714. }
  1715. }
  1716. }
  1717. //---------------------------------------------------------------------------
  1718. void __fastcall TTerminal::CustomReadDirectory(TRemoteFileList * FileList)
  1719. {
  1720. assert(FileList);
  1721. assert(FFileSystem);
  1722. FFileSystem->ReadDirectory(FileList);
  1723. ReactOnCommand(fsListDirectory);
  1724. }
  1725. //---------------------------------------------------------------------------
  1726. TRemoteFileList * TTerminal::ReadDirectoryListing(AnsiString Directory, bool UseCache)
  1727. {
  1728. TRemoteFileList * FileList;
  1729. try
  1730. {
  1731. FileList = new TRemoteFileList();
  1732. try
  1733. {
  1734. bool Cache = UseCache && SessionData->CacheDirectories;
  1735. bool LoadedFromCache = Cache && FDirectoryCache->HasFileList(Directory);
  1736. if (LoadedFromCache)
  1737. {
  1738. LoadedFromCache = FDirectoryCache->GetFileList(Directory, FileList);
  1739. }
  1740. if (!LoadedFromCache)
  1741. {
  1742. FileList->Directory = Directory;
  1743. ExceptionOnFail = true;
  1744. try
  1745. {
  1746. ReadDirectory(FileList);
  1747. }
  1748. __finally
  1749. {
  1750. ExceptionOnFail = false;
  1751. }
  1752. if (Cache)
  1753. {
  1754. AddCachedFileList(FileList);
  1755. }
  1756. }
  1757. }
  1758. catch(...)
  1759. {
  1760. delete FileList;
  1761. FileList = NULL;
  1762. throw;
  1763. }
  1764. }
  1765. catch(Exception & E)
  1766. {
  1767. COMMAND_ERROR_ARI
  1768. (
  1769. "",
  1770. FileList = ReadDirectoryListing(Directory, UseCache);
  1771. );
  1772. }
  1773. return FileList;
  1774. }
  1775. //---------------------------------------------------------------------------
  1776. void __fastcall TTerminal::ProcessDirectory(const AnsiString DirName,
  1777. TProcessFileEvent CallBackFunc, void * Param, bool UseCache)
  1778. {
  1779. TRemoteFileList * FileList = ReadDirectoryListing(DirName, UseCache);
  1780. // skip if directory listing fails and user selects "skip"
  1781. if (FileList)
  1782. {
  1783. try
  1784. {
  1785. AnsiString Directory = UnixIncludeTrailingBackslash(DirName);
  1786. TRemoteFile * File;
  1787. for (int Index = 0; Index < FileList->Count; Index++)
  1788. {
  1789. File = FileList->Files[Index];
  1790. if (!File->IsParentDirectory && !File->IsThisDirectory)
  1791. {
  1792. CallBackFunc(Directory + File->FileName, File, Param);
  1793. }
  1794. }
  1795. }
  1796. __finally
  1797. {
  1798. delete FileList;
  1799. }
  1800. }
  1801. }
  1802. //---------------------------------------------------------------------------
  1803. void __fastcall TTerminal::ReadDirectory(TRemoteFileList * FileList)
  1804. {
  1805. try
  1806. {
  1807. CustomReadDirectory(FileList);
  1808. }
  1809. catch (Exception &E)
  1810. {
  1811. CommandError(&E, FmtLoadStr(LIST_DIR_ERROR, ARRAYOFCONST((FileList->Directory))));
  1812. }
  1813. }
  1814. //---------------------------------------------------------------------------
  1815. void __fastcall TTerminal::ReadSymlink(TRemoteFile * SymlinkFile,
  1816. TRemoteFile *& File)
  1817. {
  1818. assert(FFileSystem);
  1819. try
  1820. {
  1821. LogEvent(FORMAT("Reading symlink \"%s\".", (SymlinkFile->FileName)));
  1822. FFileSystem->ReadSymlink(SymlinkFile, File);
  1823. ReactOnCommand(fsReadSymlink);
  1824. }
  1825. catch (Exception &E)
  1826. {
  1827. CommandError(&E, FMTLOAD(READ_SYMLINK_ERROR, (SymlinkFile->FileName)));
  1828. }
  1829. }
  1830. //---------------------------------------------------------------------------
  1831. void __fastcall TTerminal::ReadFile(const AnsiString FileName,
  1832. TRemoteFile *& File)
  1833. {
  1834. assert(FFileSystem);
  1835. File = NULL;
  1836. try
  1837. {
  1838. LogEvent(FORMAT("Listing file \"%s\".", (FileName)));
  1839. FFileSystem->ReadFile(FileName, File);
  1840. ReactOnCommand(fsListFile);
  1841. }
  1842. catch (Exception &E)
  1843. {
  1844. if (File) delete File;
  1845. File = NULL;
  1846. CommandError(&E, FMTLOAD(CANT_GET_ATTRS, (FileName)));
  1847. }
  1848. }
  1849. //---------------------------------------------------------------------------
  1850. void __fastcall TTerminal::AnnounceFileListOperation()
  1851. {
  1852. FFileSystem->AnnounceFileListOperation();
  1853. }
  1854. //---------------------------------------------------------------------------
  1855. bool __fastcall TTerminal::ProcessFiles(TStrings * FileList,
  1856. TFileOperation Operation, TProcessFileEvent ProcessFile, void * Param,
  1857. TOperationSide Side, bool Ex)
  1858. {
  1859. assert(FFileSystem);
  1860. assert(FileList);
  1861. bool Result = false;
  1862. bool DisconnectWhenComplete = false;
  1863. try
  1864. {
  1865. TFileOperationProgressType Progress(FOnProgress, FOnFinished);
  1866. Progress.Start(Operation, Side, FileList->Count);
  1867. FOperationProgress = &Progress;
  1868. try
  1869. {
  1870. if (Side == osRemote)
  1871. {
  1872. BeginTransaction();
  1873. }
  1874. try
  1875. {
  1876. int Index = 0;
  1877. AnsiString FileName;
  1878. bool Success;
  1879. while ((Index < FileList->Count) && (Progress.Cancel == csContinue))
  1880. {
  1881. FileName = FileList->Strings[Index];
  1882. try
  1883. {
  1884. Success = false;
  1885. if (!Ex)
  1886. {
  1887. ProcessFile(FileName, (TRemoteFile *)FileList->Objects[Index], Param);
  1888. }
  1889. else
  1890. {
  1891. // not used anymore
  1892. TProcessFileEventEx ProcessFileEx = (TProcessFileEventEx)ProcessFile;
  1893. ProcessFileEx(FileName, (TRemoteFile *)FileList->Objects[Index], Param, Index);
  1894. }
  1895. Success = true;
  1896. }
  1897. __finally
  1898. {
  1899. Progress.Finish(FileName, Success, DisconnectWhenComplete);
  1900. }
  1901. Index++;
  1902. }
  1903. }
  1904. __finally
  1905. {
  1906. if (Side == osRemote)
  1907. {
  1908. EndTransaction();
  1909. }
  1910. }
  1911. if (Progress.Cancel == csContinue)
  1912. {
  1913. Result = true;
  1914. }
  1915. }
  1916. __finally
  1917. {
  1918. FOperationProgress = NULL;
  1919. Progress.Stop();
  1920. }
  1921. }
  1922. catch (...)
  1923. {
  1924. DisconnectWhenComplete = false;
  1925. // this was missing here. was it by purpose?
  1926. // without it any error message is lost
  1927. throw;
  1928. }
  1929. if (DisconnectWhenComplete)
  1930. {
  1931. CloseOnCompletion();
  1932. }
  1933. return Result;
  1934. }
  1935. //---------------------------------------------------------------------------
  1936. // not used anymore
  1937. bool __fastcall TTerminal::ProcessFilesEx(TStrings * FileList, TFileOperation Operation,
  1938. TProcessFileEventEx ProcessFile, void * Param, TOperationSide Side)
  1939. {
  1940. return ProcessFiles(FileList, Operation, TProcessFileEvent(ProcessFile),
  1941. Param, Side, true);
  1942. }
  1943. //---------------------------------------------------------------------------
  1944. TStrings * __fastcall TTerminal::GetFixedPaths()
  1945. {
  1946. assert(FFileSystem != NULL);
  1947. return FFileSystem->GetFixedPaths();
  1948. }
  1949. //---------------------------------------------------------------------------
  1950. bool __fastcall TTerminal::GetResolvingSymlinks()
  1951. {
  1952. return SessionData->ResolveSymlinks && IsCapable[fcResolveSymlink];
  1953. }
  1954. //---------------------------------------------------------------------------
  1955. TUsableCopyParamAttrs __fastcall TTerminal::UsableCopyParamAttrs(int Params)
  1956. {
  1957. TUsableCopyParamAttrs Result;
  1958. Result.General =
  1959. FLAGMASK(!IsCapable[fcTextMode], cpaNoTransferMode) |
  1960. FLAGMASK(!IsCapable[fcModeChanging], cpaNoRights) |
  1961. FLAGMASK(!IsCapable[fcModeChanging], cpaNoPreserveReadOnly) |
  1962. FLAGMASK(FLAGSET(Params, cpDelete), cpaNoExcludeMask) |
  1963. FLAGMASK(FLAGSET(Params, cpDelete), cpaNoClearArchive) |
  1964. FLAGMASK(!IsCapable[fcIgnorePermErrors], cpaNoIgnorePermErrors);
  1965. Result.Download = Result.General | cpaNoClearArchive | cpaNoRights |
  1966. cpaNoIgnorePermErrors;
  1967. Result.Upload = Result.General | cpaNoPreserveReadOnly |
  1968. FLAGMASK(!IsCapable[fcModeChangingUpload], cpaNoRights) |
  1969. FLAGMASK(!IsCapable[fcPreservingTimestampUpload], cpaNoPreserveTime);
  1970. return Result;
  1971. }
  1972. //---------------------------------------------------------------------------
  1973. bool __fastcall TTerminal::IsRecycledFile(AnsiString FileName)
  1974. {
  1975. AnsiString Path = UnixExtractFilePath(FileName);
  1976. if (Path.IsEmpty())
  1977. {
  1978. Path = CurrentDirectory;
  1979. }
  1980. return UnixComparePaths(Path, SessionData->RecycleBinPath);
  1981. }
  1982. //---------------------------------------------------------------------------
  1983. void __fastcall TTerminal::RecycleFile(AnsiString FileName,
  1984. const TRemoteFile * File)
  1985. {
  1986. if (FileName.IsEmpty())
  1987. {
  1988. assert(File != NULL);
  1989. FileName = File->FileName;
  1990. }
  1991. if (!IsRecycledFile(FileName))
  1992. {
  1993. LogEvent(FORMAT("Moving file \"%s\" to remote recycle bin '%s'.",
  1994. (FileName, SessionData->RecycleBinPath)));
  1995. TMoveFileParams Params;
  1996. Params.Target = SessionData->RecycleBinPath;
  1997. Params.FileMask = FORMAT("*-%s.*", (FormatDateTime("yyyymmdd-hhnnss", Now())));
  1998. MoveFile(FileName, File, &Params);
  1999. }
  2000. }
  2001. //---------------------------------------------------------------------------
  2002. void __fastcall TTerminal::DeleteFile(AnsiString FileName,
  2003. const TRemoteFile * File, void * Recursive)
  2004. {
  2005. if (FileName.IsEmpty() && File)
  2006. {
  2007. FileName = File->FileName;
  2008. }
  2009. if (OperationProgress && OperationProgress->Operation == foDelete)
  2010. {
  2011. if (OperationProgress->Cancel != csContinue) Abort();
  2012. OperationProgress->SetFile(FileName);
  2013. }
  2014. if (SessionData->DeleteToRecycleBin && !IsRecycledFile(FileName))
  2015. {
  2016. RecycleFile(FileName, File);
  2017. }
  2018. else
  2019. {
  2020. LogEvent(FORMAT("Deleting file \"%s\".", (FileName)));
  2021. if (File) FileModified(File, FileName, true);
  2022. DoDeleteFile(FileName, File, Recursive);
  2023. ReactOnCommand(fsDeleteFile);
  2024. }
  2025. }
  2026. //---------------------------------------------------------------------------
  2027. void __fastcall TTerminal::DoDeleteFile(const AnsiString FileName,
  2028. const TRemoteFile * File, void * Recursive)
  2029. {
  2030. try
  2031. {
  2032. assert(FFileSystem);
  2033. // 'File' parameter: SFTPFileSystem needs to know if file is file or directory
  2034. FFileSystem->DeleteFile(FileName, File,
  2035. Recursive ? *((bool*)Recursive) : true);
  2036. }
  2037. catch(Exception & E)
  2038. {
  2039. COMMAND_ERROR_ARI
  2040. (
  2041. FMTLOAD(DELETE_FILE_ERROR, (FileName)),
  2042. DoDeleteFile(FileName, File, Recursive)
  2043. );
  2044. }
  2045. }
  2046. //---------------------------------------------------------------------------
  2047. bool __fastcall TTerminal::DeleteFiles(TStrings * FilesToDelete, bool * Recursive)
  2048. {
  2049. // TODO: avoid resolving symlinks while reading subdirectories.
  2050. // Resolving does not work anyway for relative symlinks in subdirectories
  2051. // (at least for SFTP).
  2052. return ProcessFiles(FilesToDelete, foDelete, DeleteFile, Recursive);
  2053. }
  2054. //---------------------------------------------------------------------------
  2055. void __fastcall TTerminal::DeleteLocalFile(AnsiString FileName,
  2056. const TRemoteFile * /*File*/, void * /*Param*/)
  2057. {
  2058. if (OnDeleteLocalFile == NULL)
  2059. {
  2060. if (!RecursiveDeleteFile(FileName, false))
  2061. {
  2062. throw Exception(FMTLOAD(DELETE_FILE_ERROR, (FileName)));
  2063. }
  2064. }
  2065. else
  2066. {
  2067. OnDeleteLocalFile(FileName);
  2068. }
  2069. }
  2070. //---------------------------------------------------------------------------
  2071. bool __fastcall TTerminal::DeleteLocalFiles(TStrings * FileList)
  2072. {
  2073. return ProcessFiles(FileList, foDelete, DeleteLocalFile, NULL, osLocal);
  2074. }
  2075. //---------------------------------------------------------------------------
  2076. void __fastcall TTerminal::CustomCommandOnFile(AnsiString FileName,
  2077. const TRemoteFile * File, void * AParams)
  2078. {
  2079. TCustomCommandParams * Params = ((TCustomCommandParams *)AParams);
  2080. if (FileName.IsEmpty() && File)
  2081. {
  2082. FileName = File->FileName;
  2083. }
  2084. if (OperationProgress && OperationProgress->Operation == foCustomCommand)
  2085. {
  2086. if (OperationProgress->Cancel != csContinue) Abort();
  2087. OperationProgress->SetFile(FileName);
  2088. }
  2089. LogEvent(FORMAT("Executing custom command \"%s\" (%d) on file \"%s\".",
  2090. (Params->Command, Params->Params, FileName)));
  2091. if (File) FileModified(File, FileName);
  2092. DoCustomCommandOnFile(FileName, File, Params->Command, Params->Params,
  2093. Params->OutputEvent);
  2094. ReactOnCommand(fsAnyCommand);
  2095. }
  2096. //---------------------------------------------------------------------------
  2097. void __fastcall TTerminal::DoCustomCommandOnFile(AnsiString FileName,
  2098. const TRemoteFile * File, AnsiString Command, int Params,
  2099. TCaptureOutputEvent OutputEvent)
  2100. {
  2101. try
  2102. {
  2103. if (IsCapable[fcAnyCommand])
  2104. {
  2105. assert(FFileSystem);
  2106. assert(fcShellAnyCommand);
  2107. FFileSystem->CustomCommandOnFile(FileName, File, Command, Params, OutputEvent);
  2108. }
  2109. else
  2110. {
  2111. assert(CommandSessionOpened);
  2112. assert(FCommandSession->FSProtocol == cfsSCP);
  2113. LogEvent("Executing custom command on command session.");
  2114. FCommandSession->CurrentDirectory = CurrentDirectory;
  2115. FCommandSession->FFileSystem->CustomCommandOnFile(FileName, File, Command,
  2116. Params, OutputEvent);
  2117. }
  2118. }
  2119. catch(Exception & E)
  2120. {
  2121. COMMAND_ERROR_ARI
  2122. (
  2123. FMTLOAD(CUSTOM_COMMAND_ERROR, (Command, FileName)),
  2124. DoCustomCommandOnFile(FileName, File, Command, Params, OutputEvent)
  2125. );
  2126. }
  2127. }
  2128. //---------------------------------------------------------------------------
  2129. void __fastcall TTerminal::CustomCommandOnFiles(AnsiString Command,
  2130. int Params, TStrings * Files, TCaptureOutputEvent OutputEvent)
  2131. {
  2132. if (!TRemoteCustomCommand().IsFileListCommand(Command))
  2133. {
  2134. TCustomCommandParams AParams;
  2135. AParams.Command = Command;
  2136. AParams.Params = Params;
  2137. AParams.OutputEvent = OutputEvent;
  2138. ProcessFiles(Files, foCustomCommand, CustomCommandOnFile, &AParams);
  2139. }
  2140. else
  2141. {
  2142. AnsiString FileList;
  2143. for (int i = 0; i < Files->Count; i++)
  2144. {
  2145. TRemoteFile * File = static_cast<TRemoteFile *>(Files->Objects[i]);
  2146. bool Dir = File->IsDirectory && !File->IsSymLink;
  2147. if (!Dir || FLAGSET(Params, ccApplyToDirectories))
  2148. {
  2149. if (!FileList.IsEmpty())
  2150. {
  2151. FileList += " ";
  2152. }
  2153. FileList += "\"" + ShellDelimitStr(Files->Strings[i], '"') + "\"";
  2154. }
  2155. }
  2156. AnsiString Cmd = TRemoteCustomCommand("", FileList).Complete(Command, true);
  2157. AnyCommand(Cmd, OutputEvent);
  2158. }
  2159. }
  2160. //---------------------------------------------------------------------------
  2161. void __fastcall TTerminal::ChangeFileProperties(AnsiString FileName,
  2162. const TRemoteFile * File, /*const TRemoteProperties*/ void * Properties)
  2163. {
  2164. TRemoteProperties * RProperties = (TRemoteProperties *)Properties;
  2165. assert(RProperties && !RProperties->Valid.Empty());
  2166. if (FileName.IsEmpty() && File)
  2167. {
  2168. FileName = File->FileName;
  2169. }
  2170. if (OperationProgress && OperationProgress->Operation == foSetProperties)
  2171. {
  2172. if (OperationProgress->Cancel != csContinue) Abort();
  2173. OperationProgress->SetFile(FileName);
  2174. }
  2175. if (Log->Logging)
  2176. {
  2177. LogEvent(FORMAT("Changing properties of \"%s\" (%s)",
  2178. (FileName, BooleanToEngStr(RProperties->Recursive))));
  2179. if (RProperties->Valid.Contains(vpRights))
  2180. {
  2181. LogEvent(FORMAT(" - mode: \"%s\"", (RProperties->Rights.ModeStr)));
  2182. }
  2183. if (RProperties->Valid.Contains(vpGroup))
  2184. {
  2185. LogEvent(FORMAT(" - group: \"%s\"", (RProperties->Group)));
  2186. }
  2187. if (RProperties->Valid.Contains(vpOwner))
  2188. {
  2189. LogEvent(FORMAT(" - owner: \"%s\"", (RProperties->Owner)));
  2190. }
  2191. if (RProperties->Valid.Contains(vpModification))
  2192. {
  2193. LogEvent(FORMAT(" - modification: \"%s\"",
  2194. (FormatDateTime("dddddd tt",
  2195. UnixToDateTime(RProperties->Modification, SessionData->DSTMode)))));
  2196. }
  2197. if (RProperties->Valid.Contains(vpLastAccess))
  2198. {
  2199. LogEvent(FORMAT(" - last access: \"%s\"",
  2200. (FormatDateTime("dddddd tt",
  2201. UnixToDateTime(RProperties->LastAccess, SessionData->DSTMode)))));
  2202. }
  2203. }
  2204. if (File) FileModified(File, FileName);
  2205. DoChangeFileProperties(FileName, File, RProperties);
  2206. ReactOnCommand(fsChangeProperties);
  2207. }
  2208. //---------------------------------------------------------------------------
  2209. void __fastcall TTerminal::DoChangeFileProperties(const AnsiString FileName,
  2210. const TRemoteFile * File, const TRemoteProperties * Properties)
  2211. {
  2212. try
  2213. {
  2214. assert(FFileSystem);
  2215. FFileSystem->ChangeFileProperties(FileName, File, Properties);
  2216. }
  2217. catch(Exception & E)
  2218. {
  2219. COMMAND_ERROR_ARI
  2220. (
  2221. FMTLOAD(CHANGE_PROPERTIES_ERROR, (FileName)),
  2222. DoChangeFileProperties(FileName, File, Properties)
  2223. );
  2224. }
  2225. }
  2226. //---------------------------------------------------------------------------
  2227. void __fastcall TTerminal::ChangeFilesProperties(TStrings * FileList,
  2228. const TRemoteProperties * Properties)
  2229. {
  2230. AnnounceFileListOperation();
  2231. ProcessFiles(FileList, foSetProperties, ChangeFileProperties, (void *)Properties);
  2232. }
  2233. //---------------------------------------------------------------------------
  2234. bool __fastcall TTerminal::LoadFilesProperties(TStrings * FileList)
  2235. {
  2236. bool Result =
  2237. IsCapable[fcLoadingAdditionalProperties] &&
  2238. FFileSystem->LoadFilesProperties(FileList);
  2239. if (Result && SessionData->CacheDirectories &&
  2240. (FileList->Count > 0) &&
  2241. (dynamic_cast<TRemoteFile *>(FileList->Objects[0])->Directory == FFiles))
  2242. {
  2243. AddCachedFileList(FFiles);
  2244. }
  2245. return Result;
  2246. }
  2247. //---------------------------------------------------------------------------
  2248. void __fastcall TTerminal::CalculateFileSize(AnsiString FileName,
  2249. const TRemoteFile * File, /*TCalculateSizeParams*/ void * Param)
  2250. {
  2251. assert(Param);
  2252. assert(File);
  2253. TCalculateSizeParams * AParams = static_cast<TCalculateSizeParams*>(Param);
  2254. if (FileName.IsEmpty())
  2255. {
  2256. FileName = File->FileName;
  2257. }
  2258. bool AllowTransfer = (AParams->CopyParam == NULL);
  2259. if (!AllowTransfer)
  2260. {
  2261. TFileMasks::TParams MaskParams;
  2262. MaskParams.Size = File->Size;
  2263. AllowTransfer = AParams->CopyParam->AllowTransfer(
  2264. UnixExcludeTrailingBackslash(File->FullFileName), osRemote, File->IsDirectory,
  2265. MaskParams);
  2266. }
  2267. if (AllowTransfer)
  2268. {
  2269. if (File->IsDirectory)
  2270. {
  2271. if (!File->IsSymLink)
  2272. {
  2273. LogEvent(FORMAT("Getting size of directory \"%s\"", (FileName)));
  2274. // pass in full path so we get it back in file list for AllowTransfer() exclusion
  2275. DoCalculateDirectorySize(File->FullFileName, File, AParams);
  2276. }
  2277. else
  2278. {
  2279. AParams->Size += File->Size;
  2280. }
  2281. if (AParams->Stats != NULL)
  2282. {
  2283. AParams->Stats->Directories++;
  2284. }
  2285. }
  2286. else
  2287. {
  2288. AParams->Size += File->Size;
  2289. if (AParams->Stats != NULL)
  2290. {
  2291. AParams->Stats->Files++;
  2292. }
  2293. }
  2294. if ((AParams->Stats != NULL) && File->IsSymLink)
  2295. {
  2296. AParams->Stats->SymLinks++;
  2297. }
  2298. }
  2299. if (OperationProgress && OperationProgress->Operation == foCalculateSize)
  2300. {
  2301. if (OperationProgress->Cancel != csContinue) Abort();
  2302. OperationProgress->SetFile(FileName);
  2303. }
  2304. }
  2305. //---------------------------------------------------------------------------
  2306. void __fastcall TTerminal::DoCalculateDirectorySize(const AnsiString FileName,
  2307. const TRemoteFile * File, TCalculateSizeParams * Params)
  2308. {
  2309. try
  2310. {
  2311. ProcessDirectory(FileName, CalculateFileSize, Params);
  2312. }
  2313. catch(Exception & E)
  2314. {
  2315. if (!Active || ((Params->Params & csIgnoreErrors) == 0))
  2316. {
  2317. COMMAND_ERROR_ARI
  2318. (
  2319. FMTLOAD(CALCULATE_SIZE_ERROR, (FileName)),
  2320. DoCalculateDirectorySize(FileName, File, Params)
  2321. );
  2322. }
  2323. }
  2324. }
  2325. //---------------------------------------------------------------------------
  2326. void __fastcall TTerminal::CalculateFilesSize(TStrings * FileList,
  2327. __int64 & Size, int Params, const TCopyParamType * CopyParam,
  2328. TCalculateSizeStats * Stats)
  2329. {
  2330. TCalculateSizeParams Param;
  2331. Param.Size = 0;
  2332. Param.Params = Params;
  2333. Param.CopyParam = CopyParam;
  2334. Param.Stats = Stats;
  2335. ProcessFiles(FileList, foCalculateSize, CalculateFileSize, &Param);
  2336. Size = Param.Size;
  2337. }
  2338. //---------------------------------------------------------------------------
  2339. void __fastcall TTerminal::CalculateFilesChecksum(const AnsiString & Alg,
  2340. TStrings * FileList, TStrings * Checksums,
  2341. TCalculatedChecksumEvent OnCalculatedChecksum)
  2342. {
  2343. FFileSystem->CalculateFilesChecksum(Alg, FileList, Checksums, OnCalculatedChecksum);
  2344. }
  2345. //---------------------------------------------------------------------------
  2346. void __fastcall TTerminal::RenameFile(const AnsiString FileName,
  2347. const AnsiString NewName)
  2348. {
  2349. LogEvent(FORMAT("Renaming file \"%s\" to \"%s\".", (FileName, NewName)));
  2350. DoRenameFile(FileName, NewName, false);
  2351. ReactOnCommand(fsRenameFile);
  2352. }
  2353. //---------------------------------------------------------------------------
  2354. void __fastcall TTerminal::RenameFile(const TRemoteFile * File,
  2355. const AnsiString NewName, bool CheckExistence)
  2356. {
  2357. assert(File && File->Directory == FFiles);
  2358. bool Proceed = true;
  2359. // if filename doesn't contain path, we check for existence of file
  2360. if ((File->FileName != NewName) && CheckExistence &&
  2361. Configuration->ConfirmOverwriting &&
  2362. UnixComparePaths(CurrentDirectory, FFiles->Directory))
  2363. {
  2364. TRemoteFile * DuplicateFile = FFiles->FindFile(NewName);
  2365. if (DuplicateFile)
  2366. {
  2367. AnsiString QuestionFmt;
  2368. if (DuplicateFile->IsDirectory) QuestionFmt = LoadStr(DIRECTORY_OVERWRITE);
  2369. else QuestionFmt = LoadStr(FILE_OVERWRITE);
  2370. int Result;
  2371. TQueryParams Params(qpNeverAskAgainCheck);
  2372. Result = QueryUser(FORMAT(QuestionFmt, (NewName)), NULL,
  2373. qaYes | qaNo, &Params);
  2374. if (Result == qaNeverAskAgain)
  2375. {
  2376. Proceed = true;
  2377. Configuration->ConfirmOverwriting = false;
  2378. }
  2379. else
  2380. {
  2381. Proceed = (Result == qaYes);
  2382. }
  2383. }
  2384. }
  2385. if (Proceed)
  2386. {
  2387. FileModified(File, File->FileName);
  2388. RenameFile(File->FileName, NewName);
  2389. }
  2390. }
  2391. //---------------------------------------------------------------------------
  2392. void __fastcall TTerminal::DoRenameFile(const AnsiString FileName,
  2393. const AnsiString NewName, bool Move)
  2394. {
  2395. try
  2396. {
  2397. assert(FFileSystem);
  2398. FFileSystem->RenameFile(FileName, NewName);
  2399. }
  2400. catch(Exception & E)
  2401. {
  2402. COMMAND_ERROR_ARI
  2403. (
  2404. FMTLOAD(Move ? MOVE_FILE_ERROR : RENAME_FILE_ERROR, (FileName, NewName)),
  2405. DoRenameFile(FileName, NewName, Move)
  2406. );
  2407. }
  2408. }
  2409. //---------------------------------------------------------------------------
  2410. void __fastcall TTerminal::MoveFile(const AnsiString FileName,
  2411. const TRemoteFile * File, /*const TMoveFileParams*/ void * Param)
  2412. {
  2413. if (OperationProgress &&
  2414. ((OperationProgress->Operation == foRemoteMove) ||
  2415. (OperationProgress->Operation == foDelete)))
  2416. {
  2417. if (OperationProgress->Cancel != csContinue) Abort();
  2418. OperationProgress->SetFile(FileName);
  2419. }
  2420. assert(Param != NULL);
  2421. const TMoveFileParams & Params = *static_cast<const TMoveFileParams*>(Param);
  2422. AnsiString NewName = UnixIncludeTrailingBackslash(Params.Target) +
  2423. MaskFileName(UnixExtractFileName(FileName), Params.FileMask);
  2424. LogEvent(FORMAT("Moving file \"%s\" to \"%s\".", (FileName, NewName)));
  2425. FileModified(File, FileName);
  2426. DoRenameFile(FileName, NewName, true);
  2427. ReactOnCommand(fsMoveFile);
  2428. }
  2429. //---------------------------------------------------------------------------
  2430. bool __fastcall TTerminal::MoveFiles(TStrings * FileList, const AnsiString Target,
  2431. const AnsiString FileMask)
  2432. {
  2433. TMoveFileParams Params;
  2434. Params.Target = Target;
  2435. Params.FileMask = FileMask;
  2436. DirectoryModified(Target, true);
  2437. return ProcessFiles(FileList, foRemoteMove, MoveFile, &Params);
  2438. }
  2439. //---------------------------------------------------------------------------
  2440. void __fastcall TTerminal::DoCopyFile(const AnsiString FileName,
  2441. const AnsiString NewName)
  2442. {
  2443. try
  2444. {
  2445. assert(FFileSystem);
  2446. if (IsCapable[fcRemoteCopy])
  2447. {
  2448. FFileSystem->CopyFile(FileName, NewName);
  2449. }
  2450. else
  2451. {
  2452. assert(CommandSessionOpened);
  2453. assert(FCommandSession->FSProtocol == cfsSCP);
  2454. LogEvent("Copying file on command session.");
  2455. FCommandSession->CurrentDirectory = CurrentDirectory;
  2456. FCommandSession->FFileSystem->CopyFile(FileName, NewName);
  2457. }
  2458. }
  2459. catch(Exception & E)
  2460. {
  2461. COMMAND_ERROR_ARI
  2462. (
  2463. FMTLOAD(COPY_FILE_ERROR, (FileName, NewName)),
  2464. DoCopyFile(FileName, NewName)
  2465. );
  2466. }
  2467. }
  2468. //---------------------------------------------------------------------------
  2469. void __fastcall TTerminal::CopyFile(const AnsiString FileName,
  2470. const TRemoteFile * /*File*/, /*const TMoveFileParams*/ void * Param)
  2471. {
  2472. if (OperationProgress && (OperationProgress->Operation == foRemoteCopy))
  2473. {
  2474. if (OperationProgress->Cancel != csContinue) Abort();
  2475. OperationProgress->SetFile(FileName);
  2476. }
  2477. assert(Param != NULL);
  2478. const TMoveFileParams & Params = *static_cast<const TMoveFileParams*>(Param);
  2479. AnsiString NewName = UnixIncludeTrailingBackslash(Params.Target) +
  2480. MaskFileName(UnixExtractFileName(FileName), Params.FileMask);
  2481. LogEvent(FORMAT("Copying file \"%s\" to \"%s\".", (FileName, NewName)));
  2482. DoCopyFile(FileName, NewName);
  2483. ReactOnCommand(fsCopyFile);
  2484. }
  2485. //---------------------------------------------------------------------------
  2486. bool __fastcall TTerminal::CopyFiles(TStrings * FileList, const AnsiString Target,
  2487. const AnsiString FileMask)
  2488. {
  2489. TMoveFileParams Params;
  2490. Params.Target = Target;
  2491. Params.FileMask = FileMask;
  2492. DirectoryModified(Target, true);
  2493. return ProcessFiles(FileList, foRemoteCopy, CopyFile, &Params);
  2494. }
  2495. //---------------------------------------------------------------------------
  2496. void __fastcall TTerminal::CreateDirectory(const AnsiString DirName,
  2497. const TRemoteProperties * Properties)
  2498. {
  2499. assert(FFileSystem);
  2500. EnsureNonExistence(DirName);
  2501. FileModified(NULL, DirName);
  2502. LogEvent(FORMAT("Creating directory \"%s\".", (DirName)));
  2503. DoCreateDirectory(DirName, Properties);
  2504. ReactOnCommand(fsCreateDirectory);
  2505. }
  2506. //---------------------------------------------------------------------------
  2507. void __fastcall TTerminal::DoCreateDirectory(const AnsiString DirName,
  2508. const TRemoteProperties * Properties)
  2509. {
  2510. try
  2511. {
  2512. assert(FFileSystem);
  2513. FFileSystem->CreateDirectory(DirName, Properties);
  2514. }
  2515. catch(Exception & E)
  2516. {
  2517. COMMAND_ERROR_ARI
  2518. (
  2519. FMTLOAD(CREATE_DIR_ERROR, (DirName)),
  2520. DoCreateDirectory(DirName, Properties)
  2521. );
  2522. }
  2523. }
  2524. //---------------------------------------------------------------------------
  2525. void __fastcall TTerminal::CreateLink(const AnsiString FileName,
  2526. const AnsiString PointTo, bool Symbolic)
  2527. {
  2528. assert(FFileSystem);
  2529. EnsureNonExistence(FileName);
  2530. if (SessionData->CacheDirectories)
  2531. {
  2532. DirectoryModified(CurrentDirectory, false);
  2533. }
  2534. LogEvent(FORMAT("Creating link \"%s\" to \"%s\" (symbolic: %s).",
  2535. (FileName, PointTo, BooleanToEngStr(Symbolic))));
  2536. DoCreateLink(FileName, PointTo, Symbolic);
  2537. ReactOnCommand(fsCreateDirectory);
  2538. }
  2539. //---------------------------------------------------------------------------
  2540. void __fastcall TTerminal::DoCreateLink(const AnsiString FileName,
  2541. const AnsiString PointTo, bool Symbolic)
  2542. {
  2543. try
  2544. {
  2545. assert(FFileSystem);
  2546. FFileSystem->CreateLink(FileName, PointTo, Symbolic);
  2547. }
  2548. catch(Exception & E)
  2549. {
  2550. COMMAND_ERROR_ARI
  2551. (
  2552. FMTLOAD(CREATE_LINK_ERROR, (FileName)),
  2553. DoCreateLink(FileName, PointTo, Symbolic);
  2554. );
  2555. }
  2556. }
  2557. //---------------------------------------------------------------------------
  2558. void __fastcall TTerminal::HomeDirectory()
  2559. {
  2560. assert(FFileSystem);
  2561. try
  2562. {
  2563. LogEvent("Changing directory to home directory.");
  2564. FFileSystem->HomeDirectory();
  2565. ReactOnCommand(fsHomeDirectory);
  2566. }
  2567. catch (Exception &E)
  2568. {
  2569. CommandError(&E, LoadStr(CHANGE_HOMEDIR_ERROR));
  2570. }
  2571. }
  2572. //---------------------------------------------------------------------------
  2573. void __fastcall TTerminal::ChangeDirectory(const AnsiString Directory)
  2574. {
  2575. assert(FFileSystem);
  2576. try
  2577. {
  2578. AnsiString CachedDirectory;
  2579. assert(!SessionData->CacheDirectoryChanges || (FDirectoryChangesCache != NULL));
  2580. // never use directory change cache during startup, this ensures, we never
  2581. // end-up initially in non-existing directory
  2582. if ((Status == ssOpened) &&
  2583. SessionData->CacheDirectoryChanges &&
  2584. FDirectoryChangesCache->GetDirectoryChange(PeekCurrentDirectory(),
  2585. Directory, CachedDirectory))
  2586. {
  2587. LogEvent(FORMAT("Cached directory change via \"%s\" to \"%s\".",
  2588. (Directory, CachedDirectory)));
  2589. FFileSystem->CachedChangeDirectory(CachedDirectory);
  2590. }
  2591. else
  2592. {
  2593. LogEvent(FORMAT("Changing directory to \"%s\".", (Directory)));
  2594. FFileSystem->ChangeDirectory(Directory);
  2595. }
  2596. FLastDirectoryChange = Directory;
  2597. ReactOnCommand(fsChangeDirectory);
  2598. }
  2599. catch (Exception &E)
  2600. {
  2601. CommandError(&E, FMTLOAD(CHANGE_DIR_ERROR, (Directory)));
  2602. }
  2603. }
  2604. //---------------------------------------------------------------------------
  2605. void __fastcall TTerminal::LookupUsersGroups()
  2606. {
  2607. assert(FFileSystem);
  2608. assert(IsCapable[fcUserGroupListing]);
  2609. try
  2610. {
  2611. FUsersGroupsLookedup = true;
  2612. LogEvent("Looking up groups and users.");
  2613. FFileSystem->LookupUsersGroups();
  2614. ReactOnCommand(fsLookupUsersGroups);
  2615. if (Log->Logging)
  2616. {
  2617. if (FGroups->Count > 0)
  2618. {
  2619. LogEvent("Following groups found:");
  2620. for (int Index = 0; Index < FGroups->Count; Index++)
  2621. {
  2622. LogEvent(AnsiString(" ") + FGroups->Strings[Index]);
  2623. }
  2624. }
  2625. else
  2626. {
  2627. LogEvent("No groups found.");
  2628. }
  2629. if (FUsers->Count > 0)
  2630. {
  2631. LogEvent("Following users found:");
  2632. for (int Index = 0; Index < FUsers->Count; Index++)
  2633. {
  2634. LogEvent(AnsiString(" ") + FUsers->Strings[Index]);
  2635. }
  2636. }
  2637. else
  2638. {
  2639. LogEvent("No users found.");
  2640. }
  2641. }
  2642. }
  2643. catch (Exception &E)
  2644. {
  2645. CommandError(&E, LoadStr(LOOKUP_GROUPS_ERROR));
  2646. }
  2647. }
  2648. //---------------------------------------------------------------------------
  2649. bool __fastcall TTerminal::AllowedAnyCommand(const AnsiString Command)
  2650. {
  2651. return !Command.Trim().IsEmpty();
  2652. }
  2653. //---------------------------------------------------------------------------
  2654. bool __fastcall TTerminal::GetCommandSessionOpened()
  2655. {
  2656. // consider secodary terminal open in "ready" state only
  2657. // so we never do keepalives on it until it is completelly initialised
  2658. return (FCommandSession != NULL) &&
  2659. (FCommandSession->Status == ssOpened);
  2660. }
  2661. //---------------------------------------------------------------------------
  2662. TTerminal * __fastcall TTerminal::GetCommandSession()
  2663. {
  2664. if ((FCommandSession != NULL) && !FCommandSession->Active)
  2665. {
  2666. SAFE_DESTROY(FCommandSession);
  2667. }
  2668. if (FCommandSession == NULL)
  2669. {
  2670. // transaction cannot be started yet to allow proper matching transation
  2671. // levels between main and command session
  2672. assert(!FInTransaction);
  2673. try
  2674. {
  2675. FCommandSession = new TSecondaryTerminal(this, SessionData,
  2676. Configuration, "Shell");
  2677. FCommandSession->AutoReadDirectory = false;
  2678. FCommandSession->FSessionData->RemoteDirectory = CurrentDirectory;
  2679. FCommandSession->FSessionData->FSProtocol = fsSCPonly;
  2680. FCommandSession->FExceptionOnFail = FExceptionOnFail;
  2681. FCommandSession->OnQueryUser = OnQueryUser;
  2682. FCommandSession->OnPromptUser = OnPromptUser;
  2683. FCommandSession->OnShowExtendedException = OnShowExtendedException;
  2684. FCommandSession->OnProgress = OnProgress;
  2685. FCommandSession->OnFinished = OnFinished;
  2686. FCommandSession->OnInformation = OnInformation;
  2687. // do not copy OnDisplayBanner to avoid it being displayed
  2688. }
  2689. catch(...)
  2690. {
  2691. SAFE_DESTROY(FCommandSession);
  2692. throw;
  2693. }
  2694. }
  2695. return FCommandSession;
  2696. }
  2697. //---------------------------------------------------------------------------
  2698. void __fastcall TTerminal::AnyCommand(const AnsiString Command,
  2699. TCaptureOutputEvent OutputEvent)
  2700. {
  2701. assert(FFileSystem);
  2702. try
  2703. {
  2704. DirectoryModified(CurrentDirectory, false);
  2705. if (IsCapable[fcAnyCommand])
  2706. {
  2707. LogEvent("Executing user defined command.");
  2708. FFileSystem->AnyCommand(Command, OutputEvent);
  2709. }
  2710. else
  2711. {
  2712. assert(CommandSessionOpened);
  2713. assert(FCommandSession->FSProtocol == cfsSCP);
  2714. LogEvent("Executing user defined command on command session.");
  2715. FCommandSession->CurrentDirectory = CurrentDirectory;
  2716. FCommandSession->FFileSystem->AnyCommand(Command, OutputEvent);
  2717. FCommandSession->FFileSystem->ReadCurrentDirectory();
  2718. // synchronize pwd (by purpose we lose transaction optimalisation here)
  2719. ChangeDirectory(FCommandSession->CurrentDirectory);
  2720. }
  2721. ReactOnCommand(fsAnyCommand);
  2722. }
  2723. catch (Exception &E)
  2724. {
  2725. if (ExceptionOnFail || (E.InheritsFrom(__classid(EFatal)))) throw;
  2726. else ShowExtendedException(&E);
  2727. }
  2728. }
  2729. //---------------------------------------------------------------------------
  2730. bool __fastcall TTerminal::CreateLocalFile(const AnsiString FileName,
  2731. TFileOperationProgressType * OperationProgress, HANDLE * AHandle,
  2732. bool NoConfirmation)
  2733. {
  2734. assert(AHandle);
  2735. bool Result = true;
  2736. FILE_OPERATION_LOOP (FMTLOAD(CREATE_FILE_ERROR, (FileName)),
  2737. bool Done;
  2738. unsigned int CreateAttr = FILE_ATTRIBUTE_NORMAL;
  2739. do
  2740. {
  2741. *AHandle = CreateFile(FileName.c_str(), GENERIC_WRITE, FILE_SHARE_READ,
  2742. NULL, CREATE_ALWAYS, CreateAttr, 0);
  2743. Done = (*AHandle != INVALID_HANDLE_VALUE);
  2744. if (!Done)
  2745. {
  2746. int FileAttr;
  2747. if (FileExists(FileName) &&
  2748. (((FileAttr = FileGetAttr(FileName)) & (faReadOnly | faHidden)) != 0))
  2749. {
  2750. if (FLAGSET(FileAttr, faReadOnly))
  2751. {
  2752. if (OperationProgress->NoToAll)
  2753. {
  2754. Result = false;
  2755. }
  2756. else if (!OperationProgress->YesToAll && !NoConfirmation)
  2757. {
  2758. int Answer;
  2759. SUSPEND_OPERATION
  2760. (
  2761. Answer = QueryUser(
  2762. FMTLOAD(READ_ONLY_OVERWRITE, (FileName)), NULL,
  2763. qaYes | qaNo | qaCancel | qaYesToAll | qaNoToAll, 0);
  2764. );
  2765. switch (Answer) {
  2766. case qaYesToAll: OperationProgress->YesToAll = true; break;
  2767. case qaCancel: OperationProgress->Cancel = csCancel; // continue on next case
  2768. case qaNoToAll: OperationProgress->NoToAll = true;
  2769. case qaNo: Result = false; break;
  2770. }
  2771. }
  2772. }
  2773. else
  2774. {
  2775. assert(FLAGSET(FileAttr, faHidden));
  2776. Result = true;
  2777. }
  2778. if (Result)
  2779. {
  2780. CreateAttr |=
  2781. FLAGMASK(FLAGSET(FileAttr, faHidden), FILE_ATTRIBUTE_HIDDEN) |
  2782. FLAGMASK(FLAGSET(FileAttr, faReadOnly), FILE_ATTRIBUTE_READONLY);
  2783. FILE_OPERATION_LOOP (FMTLOAD(CANT_SET_ATTRS, (FileName)),
  2784. if (FileSetAttr(FileName, FileAttr & ~(faReadOnly | faHidden)) != 0)
  2785. {
  2786. EXCEPTION;
  2787. }
  2788. );
  2789. }
  2790. else
  2791. {
  2792. Done = true;
  2793. }
  2794. }
  2795. else
  2796. {
  2797. EXCEPTION;
  2798. }
  2799. }
  2800. }
  2801. while (!Done);
  2802. );
  2803. return Result;
  2804. }
  2805. //---------------------------------------------------------------------------
  2806. void __fastcall TTerminal::OpenLocalFile(const AnsiString FileName,
  2807. int Access, int * AAttrs, HANDLE * AHandle, __int64 * ACTime,
  2808. __int64 * AMTime, __int64 * AATime, __int64 * ASize,
  2809. bool TryWriteReadOnly)
  2810. {
  2811. int Attrs = 0;
  2812. HANDLE Handle = 0;
  2813. FILE_OPERATION_LOOP (FMTLOAD(FILE_NOT_EXISTS, (FileName)),
  2814. Attrs = FileGetAttr(FileName);
  2815. if (Attrs == -1) EXCEPTION;
  2816. )
  2817. if ((Attrs & faDirectory) == 0)
  2818. {
  2819. bool NoHandle = false;
  2820. if (!TryWriteReadOnly && (Access == GENERIC_WRITE) &&
  2821. ((Attrs & faReadOnly) != 0))
  2822. {
  2823. Access = GENERIC_READ;
  2824. NoHandle = true;
  2825. }
  2826. FILE_OPERATION_LOOP (FMTLOAD(OPENFILE_ERROR, (FileName)),
  2827. Handle = CreateFile(FileName.c_str(), Access,
  2828. Access == GENERIC_READ ? FILE_SHARE_READ | FILE_SHARE_WRITE : FILE_SHARE_READ,
  2829. NULL, OPEN_EXISTING, 0, 0);
  2830. if (Handle == INVALID_HANDLE_VALUE)
  2831. {
  2832. Handle = 0;
  2833. EXCEPTION;
  2834. }
  2835. );
  2836. try
  2837. {
  2838. if (AATime || AMTime || ACTime)
  2839. {
  2840. // Get last file access and modification time
  2841. FILE_OPERATION_LOOP (FMTLOAD(CANT_GET_ATTRS, (FileName)),
  2842. FILETIME ATime;
  2843. FILETIME MTime;
  2844. FILETIME CTime;
  2845. if (!GetFileTime(Handle, &CTime, &ATime, &MTime)) EXCEPTION;
  2846. if (ACTime)
  2847. {
  2848. *ACTime = ConvertTimestampToUnixSafe(CTime, SessionData->DSTMode);
  2849. }
  2850. if (AATime)
  2851. {
  2852. *AATime = ConvertTimestampToUnixSafe(ATime, SessionData->DSTMode);
  2853. }
  2854. if (AMTime)
  2855. {
  2856. *AMTime = ConvertTimestampToUnix(MTime, SessionData->DSTMode);
  2857. }
  2858. );
  2859. }
  2860. if (ASize)
  2861. {
  2862. // Get file size
  2863. FILE_OPERATION_LOOP (FMTLOAD(CANT_GET_ATTRS, (FileName)),
  2864. unsigned long LSize;
  2865. unsigned long HSize;
  2866. LSize = GetFileSize(Handle, &HSize);
  2867. if ((LSize == 0xFFFFFFFF) && (GetLastError() != NO_ERROR)) EXCEPTION;
  2868. *ASize = (__int64(HSize) << 32) + LSize;
  2869. );
  2870. }
  2871. if ((AHandle == NULL) || NoHandle)
  2872. {
  2873. CloseHandle(Handle);
  2874. Handle = NULL;
  2875. }
  2876. }
  2877. catch(...)
  2878. {
  2879. CloseHandle(Handle);
  2880. throw;
  2881. }
  2882. }
  2883. if (AAttrs) *AAttrs = Attrs;
  2884. if (AHandle) *AHandle = Handle;
  2885. }
  2886. //---------------------------------------------------------------------------
  2887. AnsiString __fastcall TTerminal::FileUrl(const AnsiString Protocol,
  2888. const AnsiString FileName)
  2889. {
  2890. assert(FileName.Length() > 0);
  2891. return Protocol + "://" + EncodeUrlChars(SessionData->SessionName) +
  2892. (FileName[1] == '/' ? "" : "/") + EncodeUrlChars(FileName, "/");
  2893. }
  2894. //---------------------------------------------------------------------------
  2895. AnsiString __fastcall TTerminal::FileUrl(const AnsiString FileName)
  2896. {
  2897. return FFileSystem->FileUrl(FileName);
  2898. }
  2899. //---------------------------------------------------------------------------
  2900. void __fastcall TTerminal::MakeLocalFileList(const AnsiString FileName,
  2901. const TSearchRec Rec, void * Param)
  2902. {
  2903. TMakeLocalFileListParams & Params = *static_cast<TMakeLocalFileListParams*>(Param);
  2904. bool Directory = FLAGSET(Rec.Attr, faDirectory);
  2905. if (Directory && Params.Recursive)
  2906. {
  2907. ProcessLocalDirectory(FileName, MakeLocalFileList, &Params);
  2908. }
  2909. if (!Directory || Params.IncludeDirs)
  2910. {
  2911. Params.FileList->Add(FileName);
  2912. }
  2913. }
  2914. //---------------------------------------------------------------------------
  2915. void __fastcall TTerminal::CalculateLocalFileSize(const AnsiString FileName,
  2916. const TSearchRec Rec, /*TCalculateSizeParams*/ void * Params)
  2917. {
  2918. TCalculateSizeParams * AParams = static_cast<TCalculateSizeParams*>(Params);
  2919. bool Dir = FLAGSET(Rec.Attr, faDirectory);
  2920. bool AllowTransfer = (AParams->CopyParam == NULL);
  2921. __int64 Size =
  2922. (static_cast<__int64>(Rec.FindData.nFileSizeHigh) << 32) +
  2923. Rec.FindData.nFileSizeLow;
  2924. if (!AllowTransfer)
  2925. {
  2926. TFileMasks::TParams MaskParams;
  2927. MaskParams.Size = Size;
  2928. AllowTransfer = AParams->CopyParam->AllowTransfer(FileName, osLocal, Dir, MaskParams);
  2929. }
  2930. if (AllowTransfer)
  2931. {
  2932. if (!Dir)
  2933. {
  2934. AParams->Size += Size;
  2935. }
  2936. else
  2937. {
  2938. ProcessLocalDirectory(FileName, CalculateLocalFileSize, Params);
  2939. }
  2940. }
  2941. if (OperationProgress && OperationProgress->Operation == foCalculateSize)
  2942. {
  2943. if (OperationProgress->Cancel != csContinue) Abort();
  2944. OperationProgress->SetFile(FileName);
  2945. }
  2946. }
  2947. //---------------------------------------------------------------------------
  2948. void __fastcall TTerminal::CalculateLocalFilesSize(TStrings * FileList,
  2949. __int64 & Size, const TCopyParamType * CopyParam)
  2950. {
  2951. TFileOperationProgressType OperationProgress(FOnProgress, FOnFinished);
  2952. bool DisconnectWhenComplete = false;
  2953. OperationProgress.Start(foCalculateSize, osLocal, FileList->Count);
  2954. try
  2955. {
  2956. TCalculateSizeParams Params;
  2957. Params.Size = 0;
  2958. Params.Params = 0;
  2959. Params.CopyParam = CopyParam;
  2960. assert(!FOperationProgress);
  2961. FOperationProgress = &OperationProgress;
  2962. TSearchRec Rec;
  2963. for (int Index = 0; Index < FileList->Count; Index++)
  2964. {
  2965. AnsiString FileName = FileList->Strings[Index];
  2966. if (FileSearchRec(FileName, Rec))
  2967. {
  2968. CalculateLocalFileSize(FileName, Rec, &Params);
  2969. OperationProgress.Finish(FileName, true, DisconnectWhenComplete);
  2970. }
  2971. }
  2972. Size = Params.Size;
  2973. }
  2974. __finally
  2975. {
  2976. FOperationProgress = NULL;
  2977. OperationProgress.Stop();
  2978. }
  2979. if (DisconnectWhenComplete)
  2980. {
  2981. CloseOnCompletion();
  2982. }
  2983. }
  2984. //---------------------------------------------------------------------------
  2985. struct TSynchronizeFileData
  2986. {
  2987. bool Modified;
  2988. bool New;
  2989. bool IsDirectory;
  2990. TSynchronizeChecklist::TItem::TFileInfo Info;
  2991. TSynchronizeChecklist::TItem::TFileInfo MatchingRemoteFile;
  2992. int MatchingRemoteFileImageIndex;
  2993. FILETIME LocalLastWriteTime;
  2994. };
  2995. //---------------------------------------------------------------------------
  2996. const int sfFirstLevel = 0x01;
  2997. struct TSynchronizeData
  2998. {
  2999. AnsiString LocalDirectory;
  3000. AnsiString RemoteDirectory;
  3001. TTerminal::TSynchronizeMode Mode;
  3002. int Params;
  3003. TSynchronizeDirectory OnSynchronizeDirectory;
  3004. TSynchronizeOptions * Options;
  3005. int Flags;
  3006. TStringList * LocalFileList;
  3007. const TCopyParamType * CopyParam;
  3008. TSynchronizeChecklist * Checklist;
  3009. };
  3010. //---------------------------------------------------------------------------
  3011. TSynchronizeChecklist * __fastcall TTerminal::SynchronizeCollect(const AnsiString LocalDirectory,
  3012. const AnsiString RemoteDirectory, TSynchronizeMode Mode,
  3013. const TCopyParamType * CopyParam, int Params,
  3014. TSynchronizeDirectory OnSynchronizeDirectory,
  3015. TSynchronizeOptions * Options)
  3016. {
  3017. TSynchronizeChecklist * Checklist = new TSynchronizeChecklist();
  3018. try
  3019. {
  3020. DoSynchronizeCollectDirectory(LocalDirectory, RemoteDirectory, Mode,
  3021. CopyParam, Params, OnSynchronizeDirectory, Options, sfFirstLevel,
  3022. Checklist);
  3023. Checklist->Sort();
  3024. }
  3025. catch(...)
  3026. {
  3027. delete Checklist;
  3028. throw;
  3029. }
  3030. return Checklist;
  3031. }
  3032. //---------------------------------------------------------------------------
  3033. void __fastcall TTerminal::DoSynchronizeCollectDirectory(const AnsiString LocalDirectory,
  3034. const AnsiString RemoteDirectory, TSynchronizeMode Mode,
  3035. const TCopyParamType * CopyParam, int Params,
  3036. TSynchronizeDirectory OnSynchronizeDirectory, TSynchronizeOptions * Options,
  3037. int Flags, TSynchronizeChecklist * Checklist)
  3038. {
  3039. TSynchronizeData Data;
  3040. Data.LocalDirectory = IncludeTrailingBackslash(LocalDirectory);
  3041. Data.RemoteDirectory = UnixIncludeTrailingBackslash(RemoteDirectory);
  3042. Data.Mode = Mode;
  3043. Data.Params = Params;
  3044. Data.OnSynchronizeDirectory = OnSynchronizeDirectory;
  3045. Data.LocalFileList = NULL;
  3046. Data.CopyParam = CopyParam;
  3047. Data.Options = Options;
  3048. Data.Flags = Flags;
  3049. Data.Checklist = Checklist;
  3050. LogEvent(FORMAT("Collecting synchronization list for local directory '%s' and remote directory '%s', "
  3051. "mode = %d, params = %d", (LocalDirectory, RemoteDirectory,
  3052. int(Mode), int(Params))));
  3053. if (FLAGCLEAR(Params, spDelayProgress))
  3054. {
  3055. DoSynchronizeProgress(Data, true);
  3056. }
  3057. try
  3058. {
  3059. bool Found;
  3060. TSearchRec SearchRec;
  3061. Data.LocalFileList = new TStringList();
  3062. Data.LocalFileList->Sorted = true;
  3063. Data.LocalFileList->CaseSensitive = false;
  3064. FILE_OPERATION_LOOP (FMTLOAD(LIST_DIR_ERROR, (LocalDirectory)),
  3065. int FindAttrs = faReadOnly | faHidden | faSysFile | faDirectory | faArchive;
  3066. Found = (FindFirst(Data.LocalDirectory + "*.*", FindAttrs, SearchRec) == 0);
  3067. );
  3068. if (Found)
  3069. {
  3070. try
  3071. {
  3072. AnsiString FileName;
  3073. while (Found)
  3074. {
  3075. FileName = SearchRec.Name;
  3076. // add dirs for recursive mode or when we are interested in newly
  3077. // added subdirs
  3078. int FoundIndex;
  3079. __int64 Size =
  3080. (static_cast<__int64>(SearchRec.FindData.nFileSizeHigh) << 32) +
  3081. SearchRec.FindData.nFileSizeLow;
  3082. TFileMasks::TParams MaskParams;
  3083. MaskParams.Size = Size;
  3084. if ((FileName != ".") && (FileName != "..") &&
  3085. CopyParam->AllowTransfer(Data.LocalDirectory + FileName, osLocal,
  3086. FLAGSET(SearchRec.Attr, faDirectory), MaskParams) &&
  3087. !FFileSystem->TemporaryTransferFile(FileName) &&
  3088. (FLAGCLEAR(Flags, sfFirstLevel) ||
  3089. (Options == NULL) || (Options->Filter == NULL) ||
  3090. Options->Filter->Find(FileName, FoundIndex)))
  3091. {
  3092. TSynchronizeFileData * FileData = new TSynchronizeFileData;
  3093. FILETIME LocalLastWriteTime;
  3094. SYSTEMTIME SystemLastWriteTime;
  3095. FileTimeToLocalFileTime(&SearchRec.FindData.ftLastWriteTime, &LocalLastWriteTime);
  3096. FileTimeToSystemTime(&LocalLastWriteTime, &SystemLastWriteTime);
  3097. FileData->IsDirectory = FLAGSET(SearchRec.Attr, faDirectory);
  3098. FileData->Info.Directory = Data.LocalDirectory;
  3099. FileData->Info.Modification = SystemTimeToDateTime(SystemLastWriteTime);
  3100. FileData->Info.ModificationFmt = mfFull;
  3101. FileData->Info.Size = Size;
  3102. FileData->LocalLastWriteTime = SearchRec.FindData.ftLastWriteTime;
  3103. FileData->New = true;
  3104. FileData->Modified = false;
  3105. Data.LocalFileList->AddObject(FileName,
  3106. reinterpret_cast<TObject*>(FileData));
  3107. }
  3108. FILE_OPERATION_LOOP (FMTLOAD(LIST_DIR_ERROR, (LocalDirectory)),
  3109. Found = (FindNext(SearchRec) == 0);
  3110. );
  3111. }
  3112. }
  3113. __finally
  3114. {
  3115. FindClose(SearchRec);
  3116. }
  3117. // can we expect that ProcessDirectory would take so little time
  3118. // that we can pospone showing progress window until anything actually happens?
  3119. bool Cached = FLAGSET(Params, spUseCache) && SessionData->CacheDirectories &&
  3120. FDirectoryCache->HasFileList(RemoteDirectory);
  3121. if (!Cached && FLAGSET(Params, spDelayProgress))
  3122. {
  3123. DoSynchronizeProgress(Data, true);
  3124. }
  3125. ProcessDirectory(RemoteDirectory, SynchronizeCollectFile, &Data,
  3126. FLAGSET(Params, spUseCache));
  3127. TSynchronizeFileData * FileData;
  3128. for (int Index = 0; Index < Data.LocalFileList->Count; Index++)
  3129. {
  3130. FileData = reinterpret_cast<TSynchronizeFileData *>
  3131. (Data.LocalFileList->Objects[Index]);
  3132. // add local file either if we are going to upload it
  3133. // (i.e. if it is updated or we want to upload even new files)
  3134. // or if we are going to delete it (i.e. all "new"=obsolete files)
  3135. bool Modified = (FileData->Modified && ((Mode == smBoth) || (Mode == smRemote)));
  3136. bool New = (FileData->New &&
  3137. ((Mode == smLocal) ||
  3138. (((Mode == smBoth) || (Mode == smRemote)) && FLAGCLEAR(Params, spTimestamp))));
  3139. if (Modified || New)
  3140. {
  3141. TSynchronizeChecklist::TItem * ChecklistItem = new TSynchronizeChecklist::TItem();
  3142. try
  3143. {
  3144. ChecklistItem->FileName = Data.LocalFileList->Strings[Index];
  3145. ChecklistItem->IsDirectory = FileData->IsDirectory;
  3146. ChecklistItem->Local = FileData->Info;
  3147. ChecklistItem->FLocalLastWriteTime = FileData->LocalLastWriteTime;
  3148. if (Modified)
  3149. {
  3150. assert(!FileData->MatchingRemoteFile.Directory.IsEmpty());
  3151. ChecklistItem->Remote = FileData->MatchingRemoteFile;
  3152. ChecklistItem->ImageIndex = FileData->MatchingRemoteFileImageIndex;
  3153. }
  3154. else
  3155. {
  3156. ChecklistItem->Remote.Directory = Data.RemoteDirectory;
  3157. }
  3158. if ((Mode == smBoth) || (Mode == smRemote))
  3159. {
  3160. ChecklistItem->Action =
  3161. (Modified ? TSynchronizeChecklist::saUploadUpdate : TSynchronizeChecklist::saUploadNew);
  3162. ChecklistItem->Checked =
  3163. (Modified || FLAGCLEAR(Params, spExistingOnly)) &&
  3164. (!ChecklistItem->IsDirectory || FLAGCLEAR(Params, spNoRecurse) ||
  3165. FLAGSET(Params, spSubDirs));
  3166. }
  3167. else if ((Mode == smLocal) && FLAGCLEAR(Params, spTimestamp))
  3168. {
  3169. ChecklistItem->Action = TSynchronizeChecklist::saDeleteLocal;
  3170. ChecklistItem->Checked =
  3171. FLAGSET(Params, spDelete) &&
  3172. (!ChecklistItem->IsDirectory || FLAGCLEAR(Params, spNoRecurse) ||
  3173. FLAGSET(Params, spSubDirs));
  3174. }
  3175. if (ChecklistItem->Action != TSynchronizeChecklist::saNone)
  3176. {
  3177. Data.Checklist->Add(ChecklistItem);
  3178. ChecklistItem = NULL;
  3179. }
  3180. }
  3181. __finally
  3182. {
  3183. delete ChecklistItem;
  3184. }
  3185. }
  3186. }
  3187. }
  3188. }
  3189. __finally
  3190. {
  3191. if (Data.LocalFileList != NULL)
  3192. {
  3193. for (int Index = 0; Index < Data.LocalFileList->Count; Index++)
  3194. {
  3195. TSynchronizeFileData * FileData = reinterpret_cast<TSynchronizeFileData*>
  3196. (Data.LocalFileList->Objects[Index]);
  3197. delete FileData;
  3198. }
  3199. delete Data.LocalFileList;
  3200. }
  3201. }
  3202. }
  3203. //---------------------------------------------------------------------------
  3204. void __fastcall TTerminal::SynchronizeCollectFile(const AnsiString FileName,
  3205. const TRemoteFile * File, /*TSynchronizeData*/ void * Param)
  3206. {
  3207. TSynchronizeData * Data = static_cast<TSynchronizeData *>(Param);
  3208. int FoundIndex;
  3209. TFileMasks::TParams MaskParams;
  3210. MaskParams.Size = File->Size;
  3211. if (Data->CopyParam->AllowTransfer(
  3212. UnixExcludeTrailingBackslash(File->FullFileName), osRemote,
  3213. File->IsDirectory, MaskParams) &&
  3214. !FFileSystem->TemporaryTransferFile(File->FileName) &&
  3215. (FLAGCLEAR(Data->Flags, sfFirstLevel) ||
  3216. (Data->Options == NULL) || (Data->Options->Filter == NULL) ||
  3217. Data->Options->Filter->Find(File->FileName, FoundIndex)))
  3218. {
  3219. TSynchronizeChecklist::TItem * ChecklistItem = new TSynchronizeChecklist::TItem();
  3220. try
  3221. {
  3222. ChecklistItem->FileName = File->FileName;
  3223. ChecklistItem->IsDirectory = File->IsDirectory;
  3224. ChecklistItem->ImageIndex = File->IconIndex;
  3225. ChecklistItem->Remote.Directory = Data->RemoteDirectory;
  3226. ChecklistItem->Remote.Modification = File->Modification;
  3227. ChecklistItem->Remote.ModificationFmt = File->ModificationFmt;
  3228. ChecklistItem->Remote.Size = File->Size;
  3229. bool Modified = false;
  3230. int LocalIndex = Data->LocalFileList->IndexOf(ChecklistItem->FileName);
  3231. bool New = (LocalIndex < 0);
  3232. if (!New)
  3233. {
  3234. TSynchronizeFileData * LocalData =
  3235. reinterpret_cast<TSynchronizeFileData *>(Data->LocalFileList->Objects[LocalIndex]);
  3236. LocalData->New = false;
  3237. if (File->IsDirectory != LocalData->IsDirectory)
  3238. {
  3239. LogEvent(FORMAT("%s is directory on one side, but file on the another",
  3240. (File->FileName)));
  3241. }
  3242. else if (!File->IsDirectory)
  3243. {
  3244. ChecklistItem->Local = LocalData->Info;
  3245. ReduceDateTimePrecision(ChecklistItem->Local.Modification, File->ModificationFmt);
  3246. bool LocalModified = false;
  3247. // for spTimestamp+spBySize require that the file sizes are the same
  3248. // before comparing file time
  3249. bool TimeCompare =
  3250. FLAGCLEAR(Data->Params, spNotByTime) &&
  3251. (FLAGCLEAR(Data->Params, spTimestamp) ||
  3252. FLAGCLEAR(Data->Params, spBySize) ||
  3253. (ChecklistItem->Local.Size == ChecklistItem->Remote.Size));
  3254. if (TimeCompare &&
  3255. (CompareFileTime(ChecklistItem->Local.Modification,
  3256. ChecklistItem->Remote.Modification) < 0))
  3257. {
  3258. if ((FLAGCLEAR(Data->Params, spTimestamp) && FLAGCLEAR(Data->Params, spMirror)) ||
  3259. (Data->Mode == smBoth) || (Data->Mode == smLocal))
  3260. {
  3261. Modified = true;
  3262. }
  3263. else
  3264. {
  3265. LocalModified = true;
  3266. }
  3267. }
  3268. else if (TimeCompare &&
  3269. (CompareFileTime(ChecklistItem->Local.Modification,
  3270. ChecklistItem->Remote.Modification) > 0))
  3271. {
  3272. if ((FLAGCLEAR(Data->Params, spTimestamp) && FLAGCLEAR(Data->Params, spMirror)) ||
  3273. (Data->Mode == smBoth) || (Data->Mode == smRemote))
  3274. {
  3275. LocalModified = true;
  3276. }
  3277. else
  3278. {
  3279. Modified = true;
  3280. }
  3281. }
  3282. else if (FLAGSET(Data->Params, spBySize) &&
  3283. (ChecklistItem->Local.Size != ChecklistItem->Remote.Size) &&
  3284. FLAGCLEAR(Data->Params, spTimestamp))
  3285. {
  3286. Modified = true;
  3287. LocalModified = true;
  3288. }
  3289. if (LocalModified)
  3290. {
  3291. LocalData->Modified = true;
  3292. LocalData->MatchingRemoteFile = ChecklistItem->Remote;
  3293. LocalData->MatchingRemoteFileImageIndex = ChecklistItem->ImageIndex;
  3294. }
  3295. }
  3296. else if (FLAGCLEAR(Data->Params, spNoRecurse))
  3297. {
  3298. DoSynchronizeCollectDirectory(
  3299. Data->LocalDirectory + File->FileName,
  3300. Data->RemoteDirectory + File->FileName,
  3301. Data->Mode, Data->CopyParam, Data->Params, Data->OnSynchronizeDirectory,
  3302. Data->Options, (Data->Flags & ~sfFirstLevel),
  3303. Data->Checklist);
  3304. }
  3305. }
  3306. else
  3307. {
  3308. ChecklistItem->Local.Directory = Data->LocalDirectory;
  3309. }
  3310. if (New || Modified)
  3311. {
  3312. assert(!New || !Modified);
  3313. // download the file if it changed or is new and we want to have it locally
  3314. if ((Data->Mode == smBoth) || (Data->Mode == smLocal))
  3315. {
  3316. ChecklistItem->Action =
  3317. (Modified ? TSynchronizeChecklist::saDownloadUpdate : TSynchronizeChecklist::saDownloadNew);
  3318. ChecklistItem->Checked =
  3319. (Modified || FLAGCLEAR(Data->Params, spExistingOnly)) &&
  3320. (!ChecklistItem->IsDirectory || FLAGCLEAR(Data->Params, spNoRecurse) ||
  3321. FLAGSET(Data->Params, spSubDirs));
  3322. }
  3323. else if ((Data->Mode == smRemote) && New)
  3324. {
  3325. if (FLAGCLEAR(Data->Params, spTimestamp))
  3326. {
  3327. ChecklistItem->Action = TSynchronizeChecklist::saDeleteRemote;
  3328. ChecklistItem->Checked =
  3329. FLAGSET(Data->Params, spDelete) &&
  3330. (!ChecklistItem->IsDirectory || FLAGCLEAR(Data->Params, spNoRecurse) ||
  3331. FLAGSET(Data->Params, spSubDirs));
  3332. }
  3333. }
  3334. if (ChecklistItem->Action != TSynchronizeChecklist::saNone)
  3335. {
  3336. ChecklistItem->FRemoteFile = File->Duplicate();
  3337. Data->Checklist->Add(ChecklistItem);
  3338. ChecklistItem = NULL;
  3339. }
  3340. }
  3341. }
  3342. __finally
  3343. {
  3344. delete ChecklistItem;
  3345. }
  3346. }
  3347. }
  3348. //---------------------------------------------------------------------------
  3349. void __fastcall TTerminal::SynchronizeApply(TSynchronizeChecklist * Checklist,
  3350. const AnsiString LocalDirectory, const AnsiString RemoteDirectory,
  3351. const TCopyParamType * CopyParam, int Params,
  3352. TSynchronizeDirectory OnSynchronizeDirectory)
  3353. {
  3354. TSynchronizeData Data;
  3355. Data.OnSynchronizeDirectory = OnSynchronizeDirectory;
  3356. int CopyParams =
  3357. FLAGMASK(FLAGSET(Params, spNoConfirmation), cpNoConfirmation);
  3358. TCopyParamType SyncCopyParam = *CopyParam;
  3359. SyncCopyParam.PreserveTime = true;
  3360. TStringList * DownloadList = new TStringList();
  3361. TStringList * DeleteRemoteList = new TStringList();
  3362. TStringList * UploadList = new TStringList();
  3363. TStringList * DeleteLocalList = new TStringList();
  3364. BeginTransaction();
  3365. try
  3366. {
  3367. int IIndex = 0;
  3368. while (IIndex < Checklist->Count)
  3369. {
  3370. const TSynchronizeChecklist::TItem * ChecklistItem;
  3371. DownloadList->Clear();
  3372. DeleteRemoteList->Clear();
  3373. UploadList->Clear();
  3374. DeleteLocalList->Clear();
  3375. ChecklistItem = Checklist->Item[IIndex];
  3376. AnsiString CurrentLocalDirectory = ChecklistItem->Local.Directory;
  3377. AnsiString CurrentRemoteDirectory = ChecklistItem->Remote.Directory;
  3378. LogEvent(FORMAT("Synchronizing local directory '%s' with remote directory '%s', "
  3379. "params = %d", (CurrentLocalDirectory, CurrentRemoteDirectory, int(Params))));
  3380. int Count = 0;
  3381. while ((IIndex < Checklist->Count) &&
  3382. (Checklist->Item[IIndex]->Local.Directory == CurrentLocalDirectory) &&
  3383. (Checklist->Item[IIndex]->Remote.Directory == CurrentRemoteDirectory))
  3384. {
  3385. ChecklistItem = Checklist->Item[IIndex];
  3386. if (ChecklistItem->Checked)
  3387. {
  3388. Count++;
  3389. if (FLAGSET(Params, spTimestamp))
  3390. {
  3391. switch (ChecklistItem->Action)
  3392. {
  3393. case TSynchronizeChecklist::saDownloadUpdate:
  3394. DownloadList->AddObject(
  3395. UnixIncludeTrailingBackslash(ChecklistItem->Remote.Directory) +
  3396. ChecklistItem->FileName,
  3397. (TObject *)(ChecklistItem));
  3398. break;
  3399. case TSynchronizeChecklist::saUploadUpdate:
  3400. UploadList->AddObject(
  3401. IncludeTrailingBackslash(ChecklistItem->Local.Directory) +
  3402. ChecklistItem->FileName,
  3403. (TObject *)(ChecklistItem));
  3404. break;
  3405. default:
  3406. assert(false);
  3407. break;
  3408. }
  3409. }
  3410. else
  3411. {
  3412. switch (ChecklistItem->Action)
  3413. {
  3414. case TSynchronizeChecklist::saDownloadNew:
  3415. case TSynchronizeChecklist::saDownloadUpdate:
  3416. DownloadList->AddObject(
  3417. UnixIncludeTrailingBackslash(ChecklistItem->Remote.Directory) +
  3418. ChecklistItem->FileName,
  3419. ChecklistItem->FRemoteFile);
  3420. break;
  3421. case TSynchronizeChecklist::saDeleteRemote:
  3422. DeleteRemoteList->AddObject(
  3423. UnixIncludeTrailingBackslash(ChecklistItem->Remote.Directory) +
  3424. ChecklistItem->FileName,
  3425. ChecklistItem->FRemoteFile);
  3426. break;
  3427. case TSynchronizeChecklist::saUploadNew:
  3428. case TSynchronizeChecklist::saUploadUpdate:
  3429. UploadList->Add(
  3430. IncludeTrailingBackslash(ChecklistItem->Local.Directory) +
  3431. ChecklistItem->FileName);
  3432. break;
  3433. case TSynchronizeChecklist::saDeleteLocal:
  3434. DeleteLocalList->Add(
  3435. IncludeTrailingBackslash(ChecklistItem->Local.Directory) +
  3436. ChecklistItem->FileName);
  3437. break;
  3438. default:
  3439. assert(false);
  3440. break;
  3441. }
  3442. }
  3443. }
  3444. IIndex++;
  3445. }
  3446. // prevent showing/updating of progress dialog if there's nothing to do
  3447. if (Count > 0)
  3448. {
  3449. Data.LocalDirectory = IncludeTrailingBackslash(CurrentLocalDirectory);
  3450. Data.RemoteDirectory = UnixIncludeTrailingBackslash(CurrentRemoteDirectory);
  3451. DoSynchronizeProgress(Data, false);
  3452. if (FLAGSET(Params, spTimestamp))
  3453. {
  3454. if (DownloadList->Count > 0)
  3455. {
  3456. ProcessFiles(DownloadList, foSetProperties,
  3457. SynchronizeLocalTimestamp, NULL, osLocal);
  3458. }
  3459. if (UploadList->Count > 0)
  3460. {
  3461. ProcessFiles(UploadList, foSetProperties,
  3462. SynchronizeRemoteTimestamp);
  3463. }
  3464. }
  3465. else
  3466. {
  3467. if ((DownloadList->Count > 0) &&
  3468. !CopyToLocal(DownloadList, Data.LocalDirectory, &SyncCopyParam, CopyParams))
  3469. {
  3470. Abort();
  3471. }
  3472. if ((DeleteRemoteList->Count > 0) &&
  3473. !DeleteFiles(DeleteRemoteList))
  3474. {
  3475. Abort();
  3476. }
  3477. if ((UploadList->Count > 0) &&
  3478. !CopyToRemote(UploadList, Data.RemoteDirectory, &SyncCopyParam, CopyParams))
  3479. {
  3480. Abort();
  3481. }
  3482. if ((DeleteLocalList->Count > 0) &&
  3483. !DeleteLocalFiles(DeleteLocalList))
  3484. {
  3485. Abort();
  3486. }
  3487. }
  3488. }
  3489. }
  3490. }
  3491. __finally
  3492. {
  3493. delete DownloadList;
  3494. delete DeleteRemoteList;
  3495. delete UploadList;
  3496. delete DeleteLocalList;
  3497. EndTransaction();
  3498. }
  3499. }
  3500. //---------------------------------------------------------------------------
  3501. void __fastcall TTerminal::DoSynchronizeProgress(const TSynchronizeData & Data,
  3502. bool Collect)
  3503. {
  3504. if (Data.OnSynchronizeDirectory != NULL)
  3505. {
  3506. bool Continue = true;
  3507. Data.OnSynchronizeDirectory(Data.LocalDirectory, Data.RemoteDirectory,
  3508. Continue, Collect);
  3509. if (!Continue)
  3510. {
  3511. Abort();
  3512. }
  3513. }
  3514. }
  3515. //---------------------------------------------------------------------------
  3516. void __fastcall TTerminal::SynchronizeLocalTimestamp(const AnsiString /*FileName*/,
  3517. const TRemoteFile * File, void * /*Param*/)
  3518. {
  3519. const TSynchronizeChecklist::TItem * ChecklistItem =
  3520. reinterpret_cast<const TSynchronizeChecklist::TItem *>(File);
  3521. AnsiString LocalFile =
  3522. IncludeTrailingBackslash(ChecklistItem->Local.Directory) +
  3523. ChecklistItem->FileName;
  3524. FILE_OPERATION_LOOP (FMTLOAD(CANT_SET_ATTRS, (LocalFile)),
  3525. HANDLE Handle;
  3526. OpenLocalFile(LocalFile, GENERIC_WRITE, NULL, &Handle,
  3527. NULL, NULL, NULL, NULL);
  3528. FILETIME WrTime = DateTimeToFileTime(ChecklistItem->Remote.Modification,
  3529. SessionData->DSTMode);
  3530. bool Result = SetFileTime(Handle, NULL, NULL, &WrTime);
  3531. CloseHandle(Handle);
  3532. if (!Result)
  3533. {
  3534. Abort();
  3535. }
  3536. );
  3537. }
  3538. //---------------------------------------------------------------------------
  3539. void __fastcall TTerminal::SynchronizeRemoteTimestamp(const AnsiString /*FileName*/,
  3540. const TRemoteFile * File, void * /*Param*/)
  3541. {
  3542. const TSynchronizeChecklist::TItem * ChecklistItem =
  3543. reinterpret_cast<const TSynchronizeChecklist::TItem *>(File);
  3544. TRemoteProperties Properties;
  3545. Properties.Valid << vpModification;
  3546. Properties.Modification = ConvertTimestampToUnix(ChecklistItem->FLocalLastWriteTime,
  3547. SessionData->DSTMode);
  3548. ChangeFileProperties(
  3549. UnixIncludeTrailingBackslash(ChecklistItem->Remote.Directory) + ChecklistItem->FileName,
  3550. ChecklistItem->FRemoteFile, &Properties);
  3551. }
  3552. //---------------------------------------------------------------------------
  3553. void __fastcall TTerminal::SpaceAvailable(const AnsiString Path,
  3554. TSpaceAvailable & ASpaceAvailable)
  3555. {
  3556. assert(IsCapable[fcCheckingSpaceAvailable]);
  3557. try
  3558. {
  3559. FFileSystem->SpaceAvailable(Path, ASpaceAvailable);
  3560. }
  3561. catch (Exception &E)
  3562. {
  3563. CommandError(&E, FMTLOAD(SPACE_AVAILABLE_ERROR, (Path)));
  3564. }
  3565. }
  3566. //---------------------------------------------------------------------------
  3567. const TSessionInfo & __fastcall TTerminal::GetSessionInfo()
  3568. {
  3569. return FFileSystem->GetSessionInfo();
  3570. }
  3571. //---------------------------------------------------------------------------
  3572. const TFileSystemInfo & __fastcall TTerminal::GetFileSystemInfo(bool Retrieve)
  3573. {
  3574. return FFileSystem->GetFileSystemInfo(Retrieve);
  3575. }
  3576. //---------------------------------------------------------------------
  3577. AnsiString __fastcall TTerminal::GetPassword()
  3578. {
  3579. AnsiString Result;
  3580. // FPassword is empty also when stored password was used
  3581. if (FPassword.IsEmpty())
  3582. {
  3583. Result = SessionData->Password;
  3584. }
  3585. else
  3586. {
  3587. Result = DecryptPassword(FPassword, SessionData->SessionName);
  3588. }
  3589. return Result;
  3590. }
  3591. //---------------------------------------------------------------------
  3592. bool __fastcall TTerminal::GetStoredCredentialsTried()
  3593. {
  3594. bool Result;
  3595. if (FFileSystem != NULL)
  3596. {
  3597. Result = FFileSystem->GetStoredCredentialsTried();
  3598. }
  3599. else
  3600. {
  3601. assert(FSecureShell != NULL);
  3602. Result = FSecureShell->GetStoredCredentialsTried();
  3603. }
  3604. return Result;
  3605. }
  3606. //---------------------------------------------------------------------------
  3607. bool __fastcall TTerminal::CopyToRemote(TStrings * FilesToCopy,
  3608. const AnsiString TargetDir, const TCopyParamType * CopyParam, int Params)
  3609. {
  3610. assert(FFileSystem);
  3611. assert(FilesToCopy);
  3612. assert(IsCapable[fcNewerOnlyUpload] || FLAGCLEAR(Params, cpNewerOnly));
  3613. bool Result = false;
  3614. bool DisconnectWhenComplete = false;
  3615. try
  3616. {
  3617. __int64 Size;
  3618. if (CopyParam->CalculateSize)
  3619. {
  3620. // dirty trick: when moving, do not pass copy param to avoid exclude mask
  3621. CalculateLocalFilesSize(FilesToCopy, Size,
  3622. (FLAGCLEAR(Params, cpDelete) ? CopyParam : NULL));
  3623. }
  3624. TFileOperationProgressType OperationProgress(FOnProgress, FOnFinished);
  3625. OperationProgress.Start((Params & cpDelete ? foMove : foCopy), osLocal,
  3626. FilesToCopy->Count, Params & cpTemporary, TargetDir);
  3627. OperationProgress.YesToNewer = FLAGSET(Params, cpNewerOnly);
  3628. FOperationProgress = &OperationProgress;
  3629. try
  3630. {
  3631. if (CopyParam->CalculateSize)
  3632. {
  3633. OperationProgress.SetTotalSize(Size);
  3634. }
  3635. AnsiString UnlockedTargetDir = TranslateLockedPath(TargetDir, false);
  3636. BeginTransaction();
  3637. try
  3638. {
  3639. if (Log->Logging)
  3640. {
  3641. LogEvent(FORMAT("Copying %d files/directories to remote directory "
  3642. "\"%s\"", (FilesToCopy->Count, TargetDir)));
  3643. LogEvent(CopyParam->LogStr);
  3644. }
  3645. FFileSystem->CopyToRemote(FilesToCopy, UnlockedTargetDir,
  3646. CopyParam, Params, &OperationProgress, DisconnectWhenComplete);
  3647. }
  3648. __finally
  3649. {
  3650. if (Active)
  3651. {
  3652. ReactOnCommand(fsCopyToRemote);
  3653. }
  3654. EndTransaction();
  3655. }
  3656. if (OperationProgress.Cancel == csContinue)
  3657. {
  3658. Result = true;
  3659. }
  3660. }
  3661. __finally
  3662. {
  3663. OperationProgress.Stop();
  3664. FOperationProgress = NULL;
  3665. }
  3666. }
  3667. catch (Exception &E)
  3668. {
  3669. CommandError(&E, LoadStr(TOREMOTE_COPY_ERROR));
  3670. DisconnectWhenComplete = false;
  3671. }
  3672. if (DisconnectWhenComplete) CloseOnCompletion();
  3673. return Result;
  3674. }
  3675. //---------------------------------------------------------------------------
  3676. bool __fastcall TTerminal::CopyToLocal(TStrings * FilesToCopy,
  3677. const AnsiString TargetDir, const TCopyParamType * CopyParam, int Params)
  3678. {
  3679. assert(FFileSystem);
  3680. // see scp.c: sink(), tolocal()
  3681. bool Result = false;
  3682. bool OwnsFileList = (FilesToCopy == NULL);
  3683. bool DisconnectWhenComplete = false;
  3684. try
  3685. {
  3686. if (OwnsFileList)
  3687. {
  3688. FilesToCopy = new TStringList();
  3689. FilesToCopy->Assign(Files->SelectedFiles);
  3690. }
  3691. BeginTransaction();
  3692. try
  3693. {
  3694. __int64 TotalSize;
  3695. bool TotalSizeKnown = false;
  3696. TFileOperationProgressType OperationProgress(FOnProgress, FOnFinished);
  3697. if (CopyParam->CalculateSize)
  3698. {
  3699. ExceptionOnFail = true;
  3700. try
  3701. {
  3702. // dirty trick: when moving, do not pass copy param to avoid exclude mask
  3703. CalculateFilesSize(FilesToCopy, TotalSize, csIgnoreErrors,
  3704. (FLAGCLEAR(Params, cpDelete) ? CopyParam : NULL));
  3705. TotalSizeKnown = true;
  3706. }
  3707. __finally
  3708. {
  3709. ExceptionOnFail = false;
  3710. }
  3711. }
  3712. OperationProgress.Start((Params & cpDelete ? foMove : foCopy), osRemote,
  3713. FilesToCopy->Count, Params & cpTemporary, TargetDir);
  3714. OperationProgress.YesToNewer = FLAGSET(Params, cpNewerOnly);
  3715. FOperationProgress = &OperationProgress;
  3716. try
  3717. {
  3718. if (TotalSizeKnown)
  3719. {
  3720. OperationProgress.SetTotalSize(TotalSize);
  3721. }
  3722. try
  3723. {
  3724. try
  3725. {
  3726. FFileSystem->CopyToLocal(FilesToCopy, TargetDir, CopyParam, Params,
  3727. &OperationProgress, DisconnectWhenComplete);
  3728. }
  3729. __finally
  3730. {
  3731. if (Active)
  3732. {
  3733. ReactOnCommand(fsCopyToLocal);
  3734. }
  3735. }
  3736. }
  3737. catch (Exception &E)
  3738. {
  3739. CommandError(&E, LoadStr(TOLOCAL_COPY_ERROR));
  3740. DisconnectWhenComplete = false;
  3741. }
  3742. if (OperationProgress.Cancel == csContinue)
  3743. {
  3744. Result = true;
  3745. }
  3746. }
  3747. __finally
  3748. {
  3749. FOperationProgress = NULL;
  3750. OperationProgress.Stop();
  3751. }
  3752. }
  3753. __finally
  3754. {
  3755. // If session is still active (no fatal error) we reload directory
  3756. // by calling EndTransaction
  3757. EndTransaction();
  3758. }
  3759. }
  3760. __finally
  3761. {
  3762. if (OwnsFileList) delete FilesToCopy;
  3763. }
  3764. if (DisconnectWhenComplete) CloseOnCompletion();
  3765. return Result;
  3766. }
  3767. //---------------------------------------------------------------------------
  3768. __fastcall TSecondaryTerminal::TSecondaryTerminal(TTerminal * MainTerminal,
  3769. TSessionData * ASessionData, TConfiguration * Configuration, const AnsiString & Name) :
  3770. TTerminal(ASessionData, Configuration),
  3771. FMainTerminal(MainTerminal), FMasterPasswordTried(false)
  3772. {
  3773. Log->Parent = FMainTerminal->Log;
  3774. Log->Name = Name;
  3775. SessionData->NonPersistant();
  3776. assert(FMainTerminal != NULL);
  3777. if (!FMainTerminal->UserName.IsEmpty())
  3778. {
  3779. SessionData->UserName = FMainTerminal->UserName;
  3780. }
  3781. }
  3782. //---------------------------------------------------------------------------
  3783. void __fastcall TSecondaryTerminal::DirectoryLoaded(TRemoteFileList * FileList)
  3784. {
  3785. FMainTerminal->DirectoryLoaded(FileList);
  3786. assert(FileList != NULL);
  3787. }
  3788. //---------------------------------------------------------------------------
  3789. void __fastcall TSecondaryTerminal::DirectoryModified(const AnsiString Path,
  3790. bool SubDirs)
  3791. {
  3792. // clear cache of main terminal
  3793. FMainTerminal->DirectoryModified(Path, SubDirs);
  3794. }
  3795. //---------------------------------------------------------------------------
  3796. bool __fastcall TSecondaryTerminal::DoPromptUser(TSessionData * Data,
  3797. AnsiString Prompt, TPromptKind Kind, AnsiString & Response)
  3798. {
  3799. bool Result = false;
  3800. if (!FMasterPasswordTried &&
  3801. ((Kind == pkPassword) || (Kind == pkPassphrase) || (Kind == pkServerPrompt)))
  3802. {
  3803. // let's expect that the main session is already authenticated and its password
  3804. // is not written after, so no locking is necessary
  3805. // (no longer true, once the main session can be reconnected)
  3806. Response = FMainTerminal->Password;
  3807. if (!Response.IsEmpty())
  3808. {
  3809. Result = true;
  3810. }
  3811. FMasterPasswordTried = true;
  3812. }
  3813. if (!Result)
  3814. {
  3815. Result = TTerminal::DoPromptUser(Data, Prompt, Kind, Response);
  3816. }
  3817. return Result;
  3818. }
  3819. //---------------------------------------------------------------------------
  3820. __fastcall TTerminalList::TTerminalList(TConfiguration * AConfiguration) :
  3821. TObjectList()
  3822. {
  3823. assert(AConfiguration);
  3824. FConfiguration = AConfiguration;
  3825. }
  3826. //---------------------------------------------------------------------------
  3827. __fastcall TTerminalList::~TTerminalList()
  3828. {
  3829. assert(Count == 0);
  3830. }
  3831. //---------------------------------------------------------------------------
  3832. TTerminal * __fastcall TTerminalList::CreateTerminal(TSessionData * Data)
  3833. {
  3834. return new TTerminal(Data, FConfiguration);
  3835. }
  3836. //---------------------------------------------------------------------------
  3837. TTerminal * __fastcall TTerminalList::NewTerminal(TSessionData * Data)
  3838. {
  3839. TTerminal * Terminal = CreateTerminal(Data);
  3840. Add(Terminal);
  3841. return Terminal;
  3842. }
  3843. //---------------------------------------------------------------------------
  3844. void __fastcall TTerminalList::FreeTerminal(TTerminal * Terminal)
  3845. {
  3846. assert(IndexOf(Terminal) >= 0);
  3847. Remove(Terminal);
  3848. }
  3849. //---------------------------------------------------------------------------
  3850. void __fastcall TTerminalList::FreeAndNullTerminal(TTerminal * & Terminal)
  3851. {
  3852. TTerminal * T = Terminal;
  3853. Terminal = NULL;
  3854. FreeTerminal(T);
  3855. }
  3856. //---------------------------------------------------------------------------
  3857. TTerminal * __fastcall TTerminalList::GetTerminal(int Index)
  3858. {
  3859. return dynamic_cast<TTerminal *>(Items[Index]);
  3860. }
  3861. //---------------------------------------------------------------------------
  3862. int __fastcall TTerminalList::GetActiveCount()
  3863. {
  3864. int Result = 0;
  3865. TTerminal * Terminal;
  3866. for (int i = 0; i < Count; i++)
  3867. {
  3868. Terminal = Terminals[i];
  3869. if (Terminal->Active)
  3870. {
  3871. Result++;
  3872. }
  3873. }
  3874. return Result;
  3875. }
  3876. //---------------------------------------------------------------------------
  3877. void __fastcall TTerminalList::Idle()
  3878. {
  3879. TTerminal * Terminal;
  3880. for (int i = 0; i < Count; i++)
  3881. {
  3882. Terminal = Terminals[i];
  3883. if (Terminal->Status == ssOpened)
  3884. {
  3885. Terminal->Idle();
  3886. }
  3887. }
  3888. }