Terminal.cpp 127 KB

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