Terminal.cpp 132 KB

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