Script.cpp 91 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040
  1. //---------------------------------------------------------------------------
  2. #include <vcl.h>
  3. #pragma hdrstop
  4. #include <SysUtils.hpp>
  5. #include "Common.h"
  6. #include "Exceptions.h"
  7. #include "TextsCore.h"
  8. #include "Script.h"
  9. #include "Terminal.h"
  10. #include "SessionData.h"
  11. #include "CoreMain.h"
  12. //---------------------------------------------------------------------------
  13. #pragma package(smart_init)
  14. //---------------------------------------------------------------------------
  15. const wchar_t * ToggleNames[] = { L"off", L"on" };
  16. const UnicodeString InOutParam(TraceInitStr(L"-"));
  17. //---------------------------------------------------------------------------
  18. __fastcall TScriptProcParams::TScriptProcParams(const UnicodeString & FullCommand, const UnicodeString & ParamsStr)
  19. {
  20. int P = FSwitchMarks.Pos(L"/");
  21. DebugAssert(P > 0);
  22. if (P > 0)
  23. {
  24. FSwitchMarks.Delete(P, 1);
  25. }
  26. FFullCommand = FullCommand;
  27. FParamsStr = ParamsStr;
  28. Parse(ParamsStr);
  29. }
  30. //---------------------------------------------------------------------------
  31. //---------------------------------------------------------------------------
  32. class TScriptCommands : TStringList
  33. {
  34. public:
  35. typedef void __fastcall (__closure *TCommandProc)(TScriptProcParams * Parameters);
  36. __fastcall TScriptCommands(TScript * Script);
  37. virtual __fastcall ~TScriptCommands();
  38. void __fastcall Execute(const UnicodeString & Command, const UnicodeString & Params);
  39. UnicodeString __fastcall ResolveCommand(const UnicodeString & Command);
  40. void __fastcall Register(const wchar_t * Command,
  41. const UnicodeString Description, const UnicodeString Help, TCommandProc Proc,
  42. int MinParams, int MaxParams, bool Switches);
  43. void __fastcall Register(const wchar_t * Command,
  44. int Description, int Help, TCommandProc Proc,
  45. int MinParams, int MaxParams, bool Switches);
  46. bool __fastcall Info(const UnicodeString Command,
  47. UnicodeString * Description, UnicodeString * Help);
  48. bool __fastcall Enumerate(int Index,
  49. UnicodeString * Command, UnicodeString * Description, UnicodeString * Help);
  50. static int __fastcall FindCommand(TStrings * Commands, const UnicodeString Command,
  51. UnicodeString * Matches = NULL);
  52. static int __fastcall FindCommand(const wchar_t ** Commands, size_t Count,
  53. const UnicodeString Command, UnicodeString * Matches = NULL);
  54. static void __fastcall CheckParams(TOptions * Parameters, bool Switches);
  55. protected:
  56. struct TScriptCommand
  57. {
  58. UnicodeString Description;
  59. UnicodeString Help;
  60. TCommandProc Proc;
  61. int MinParams;
  62. int MaxParams;
  63. bool Switches;
  64. };
  65. TScript * FScript;
  66. };
  67. //---------------------------------------------------------------------------
  68. __fastcall TScriptCommands::TScriptCommands(TScript * Script)
  69. {
  70. FScript = Script;
  71. Sorted = true;
  72. CaseSensitive = false;
  73. }
  74. //---------------------------------------------------------------------------
  75. __fastcall TScriptCommands::~TScriptCommands()
  76. {
  77. for (int Index = 0; Index < Count; Index++)
  78. {
  79. delete reinterpret_cast<TScriptCommand *>(Objects[Index]);
  80. }
  81. }
  82. //---------------------------------------------------------------------------
  83. void __fastcall TScriptCommands::Register(const wchar_t * Command,
  84. const UnicodeString Description, const UnicodeString Help, TCommandProc Proc,
  85. int MinParams, int MaxParams, bool Switches)
  86. {
  87. TScriptCommand * ScriptCommand = new TScriptCommand;
  88. ScriptCommand->Description = Description;
  89. ScriptCommand->Help = Help;
  90. ScriptCommand->Proc = Proc;
  91. ScriptCommand->MinParams = MinParams;
  92. ScriptCommand->MaxParams = MaxParams;
  93. ScriptCommand->Switches = Switches;
  94. AddObject(Command, reinterpret_cast<TObject *>(ScriptCommand));
  95. }
  96. //---------------------------------------------------------------------------
  97. void __fastcall TScriptCommands::Register(const wchar_t * Command,
  98. int Description, int Help, TCommandProc Proc,
  99. int MinParams, int MaxParams, bool Switches)
  100. {
  101. UnicodeString ADescription;
  102. if (Description > 0)
  103. {
  104. ADescription = LoadStr(Description);
  105. }
  106. UnicodeString AHelp;
  107. if (Help > 0)
  108. {
  109. AHelp = LoadStr(Help, 10240);
  110. }
  111. Register(Command, ADescription, AHelp, Proc, MinParams, MaxParams, Switches);
  112. }
  113. //---------------------------------------------------------------------------
  114. bool __fastcall TScriptCommands::Info(const UnicodeString Command,
  115. UnicodeString * Description, UnicodeString * Help)
  116. {
  117. int Index = FindCommand(this, Command);
  118. bool Result = (Index >= 0);
  119. if (Result)
  120. {
  121. TScriptCommand * ScriptCommand = reinterpret_cast<TScriptCommand *>(Objects[Index]);
  122. if (Description != NULL)
  123. {
  124. *Description = ScriptCommand->Description;
  125. }
  126. if (Help != NULL)
  127. {
  128. *Help = ScriptCommand->Help;
  129. }
  130. }
  131. return Result;
  132. }
  133. //---------------------------------------------------------------------------
  134. bool __fastcall TScriptCommands::Enumerate(int Index,
  135. UnicodeString * Command, UnicodeString * Description, UnicodeString * Help)
  136. {
  137. bool Result = (Index < Count);
  138. if (Result)
  139. {
  140. TScriptCommand * ScriptCommand = reinterpret_cast<TScriptCommand *>(Objects[Index]);
  141. if (Command != NULL)
  142. {
  143. *Command = Strings[Index];
  144. }
  145. if (Description != NULL)
  146. {
  147. *Description = ScriptCommand->Description;
  148. }
  149. if (Help != NULL)
  150. {
  151. *Help = ScriptCommand->Help;
  152. }
  153. }
  154. return Result;
  155. }
  156. //---------------------------------------------------------------------------
  157. int __fastcall TScriptCommands::FindCommand(TStrings * Commands,
  158. const UnicodeString Command, UnicodeString * Matches)
  159. {
  160. int Result = Commands->IndexOf(Command);
  161. if (Result < 0)
  162. {
  163. int MatchesCount = 0;
  164. for (int i = 0; i < Commands->Count; i++)
  165. {
  166. if ((Command.Length() <= Commands->Strings[i].Length()) &&
  167. SameText(Command, Commands->Strings[i].SubString(1, Command.Length())))
  168. {
  169. if (Matches != NULL)
  170. {
  171. if (!Matches->IsEmpty())
  172. {
  173. *Matches += L", ";
  174. }
  175. *Matches += Commands->Strings[i];
  176. }
  177. MatchesCount++;
  178. Result = i;
  179. }
  180. }
  181. if (MatchesCount == 0)
  182. {
  183. Result = -1;
  184. }
  185. else if (MatchesCount > 1)
  186. {
  187. Result = -2;
  188. }
  189. }
  190. return Result;
  191. }
  192. //---------------------------------------------------------------------------
  193. int __fastcall TScriptCommands::FindCommand(const wchar_t ** Commands, size_t Count,
  194. const UnicodeString Command, UnicodeString * Matches)
  195. {
  196. int Result;
  197. TStringList * Strings = new TStringList;
  198. try
  199. {
  200. Strings->CaseSensitive = false;
  201. for (unsigned int i = 0; i < Count; i++)
  202. {
  203. Strings->Add(Commands[i]);
  204. }
  205. Result = FindCommand(Strings, Command, Matches);
  206. }
  207. __finally
  208. {
  209. delete Strings;
  210. }
  211. return Result;
  212. }
  213. //---------------------------------------------------------------------------
  214. void __fastcall TScriptCommands::CheckParams(TOptions * Parameters,
  215. bool Switches)
  216. {
  217. UnicodeString Switch;
  218. if (!Switches && Parameters->UnusedSwitch(Switch))
  219. {
  220. throw Exception(FMTLOAD(SCRIPT_UNKNOWN_SWITCH, (Switch)));
  221. }
  222. }
  223. //---------------------------------------------------------------------------
  224. UnicodeString __fastcall TScriptCommands::ResolveCommand(const UnicodeString & Command)
  225. {
  226. UnicodeString Matches;
  227. int Index = FindCommand(this, Command, &Matches);
  228. if (Index >= 0)
  229. {
  230. return Strings[Index];
  231. }
  232. else
  233. {
  234. return UnicodeString();
  235. }
  236. }
  237. //---------------------------------------------------------------------------
  238. // parameters are by purpose passed by (constant) reference.
  239. // because if passed by value (copy), UnicodeString reference is not for some reason
  240. // decreased on exit by exception, leading to memory leak
  241. void __fastcall TScriptCommands::Execute(const UnicodeString & Command, const UnicodeString & Params)
  242. {
  243. UnicodeString Matches;
  244. int Index = FindCommand(this, Command, &Matches);
  245. if (Index == -2)
  246. {
  247. throw Exception(FMTLOAD(SCRIPT_COMMAND_AMBIGUOUS, (Command, Matches)));
  248. }
  249. else if (Index < 0)
  250. {
  251. throw Exception(FMTLOAD(SCRIPT_COMMAND_UNKNOWN, (Command)));
  252. }
  253. TScriptCommand * ScriptCommand = reinterpret_cast<TScriptCommand *>(Objects[Index]);
  254. UnicodeString FullCommand = Strings[Index];
  255. std::unique_ptr<TScriptProcParams> Parameters(new TScriptProcParams(FullCommand, Params));
  256. if (Parameters->ParamCount < ScriptCommand->MinParams)
  257. {
  258. throw Exception(FMTLOAD(SCRIPT_MISSING_PARAMS, (FullCommand)));
  259. }
  260. else if ((ScriptCommand->MaxParams >= 0) && (Parameters->ParamCount > ScriptCommand->MaxParams))
  261. {
  262. throw Exception(FMTLOAD(SCRIPT_TOO_MANY_PARAMS, (FullCommand)));
  263. }
  264. else
  265. {
  266. CheckParams(Parameters.get(), ScriptCommand->Switches);
  267. ScriptCommand->Proc(Parameters.get());
  268. }
  269. }
  270. //---------------------------------------------------------------------------
  271. //---------------------------------------------------------------------------
  272. // keep in sync with Session constructor in .NET
  273. const int BatchSessionReopenTimeout = 2 * MSecsPerSec * SecsPerMin; // 2 mins
  274. //---------------------------------------------------------------------------
  275. __fastcall TScript::TScript(bool LimitedOutput)
  276. {
  277. FLimitedOutput = LimitedOutput;
  278. FTerminal = NULL;
  279. FLoggingTerminal = NULL;
  280. FGroups = false;
  281. FWantsProgress = false;
  282. FInteractive = false;
  283. FOnTransferOut = NULL;
  284. FOnTransferIn = NULL;
  285. FIncludeFileMaskOptionUsed = false;
  286. FPendingLogLines = new TStringList();
  287. Init();
  288. }
  289. //---------------------------------------------------------------------------
  290. __fastcall TScript::~TScript()
  291. {
  292. delete FCommands;
  293. delete FPendingLogLines;
  294. }
  295. //---------------------------------------------------------------------------
  296. void __fastcall TScript::Init()
  297. {
  298. FBatch = BatchAbort;
  299. FInteractiveBatch = BatchOff;
  300. FConfirm = false;
  301. FInteractiveConfirm = true;
  302. FSessionReopenTimeout = Configuration->SessionReopenTimeout;
  303. FInteractiveSessionReopenTimeout = FSessionReopenTimeout;
  304. if (FSessionReopenTimeout == 0)
  305. {
  306. FSessionReopenTimeout = BatchSessionReopenTimeout;
  307. }
  308. FEcho = false;
  309. FFailOnNoMatch = false;
  310. FSynchronizeParams = 0;
  311. FOnPrint = NULL;
  312. FOnTerminalSynchronizeDirectory = NULL;
  313. FOnSynchronizeStartStop = NULL;
  314. FSynchronizeMode = -1;
  315. FKeepingUpToDate = false;
  316. FWarnNonDefaultCopyParam = false;
  317. FWarnNonDefaultSynchronizeParams = false;
  318. FCommands = new TScriptCommands(this);
  319. FCommands->Register(L"help", SCRIPT_HELP_DESC, SCRIPT_HELP_HELP, &HelpProc, 0, -1, false);
  320. FCommands->Register(L"man", 0, SCRIPT_HELP_HELP, &HelpProc, 0, -1, false);
  321. // the call command does not have switches itself, but the commands may have
  322. FCommands->Register(L"call", SCRIPT_CALL_DESC2, SCRIPT_CALL_HELP2, &CallProc, 1, -1, true);
  323. FCommands->Register(L"!", 0, SCRIPT_CALL_HELP2, &CallProc, 1, -1, true);
  324. FCommands->Register(L"pwd", SCRIPT_PWD_DESC, SCRIPT_PWD_HELP, &PwdProc, 0, 0, false);
  325. FCommands->Register(L"cd", SCRIPT_CD_DESC, SCRIPT_CD_HELP, &CdProc, 0, 1, false);
  326. FCommands->Register(L"ls", SCRIPT_LS_DESC, SCRIPT_LS_HELP2, &LsProc, 0, 1, false);
  327. FCommands->Register(L"dir", 0, SCRIPT_LS_HELP2, &LsProc, 0, 1, false);
  328. FCommands->Register(L"rm", SCRIPT_RM_DESC, SCRIPT_RM_HELP2, &RmProc, 1, -1, true);
  329. FCommands->Register(L"rmdir", SCRIPT_RMDIR_DESC, SCRIPT_RMDIR_HELP, &RmDirProc, 1, -1, false);
  330. FCommands->Register(L"mv", SCRIPT_MV_DESC, SCRIPT_MV_HELP2, &MvProc, 2, -1, false);
  331. FCommands->Register(L"rename", 0, SCRIPT_MV_HELP2, &MvProc, 2, -1, false);
  332. FCommands->Register(L"cp", SCRIPT_CP_DESC, SCRIPT_CP_HELP, &CpProc, 2, -1, false);
  333. FCommands->Register(L"chmod", SCRIPT_CHMOD_DESC, SCRIPT_CHMOD_HELP2, &ChModProc, 2, -1, false);
  334. FCommands->Register(L"ln", SCRIPT_LN_DESC, SCRIPT_LN_HELP, &LnProc, 2, 2, false);
  335. FCommands->Register(L"symlink", 0, SCRIPT_LN_HELP, &LnProc, 2, 2, false);
  336. FCommands->Register(L"mkdir", SCRIPT_MKDIR_DESC, SCRIPT_MKDIR_HELP, &MkDirProc, 1, 1, false);
  337. FCommands->Register(L"get", SCRIPT_GET_DESC, SCRIPT_GET_HELP8, &GetProc, 0, -1, true);
  338. FCommands->Register(L"recv", 0, SCRIPT_GET_HELP8, &GetProc, 0, -1, true);
  339. FCommands->Register(L"mget", 0, SCRIPT_GET_HELP8, &GetProc, 0, -1, true);
  340. FCommands->Register(L"put", SCRIPT_PUT_DESC, SCRIPT_PUT_HELP8, &PutProc, 0, -1, true);
  341. FCommands->Register(L"send", 0, SCRIPT_PUT_HELP8, &PutProc, 0, -1, true);
  342. FCommands->Register(L"mput", 0, SCRIPT_PUT_HELP8, &PutProc, 0, -1, true);
  343. FCommands->Register(L"option", SCRIPT_OPTION_DESC, SCRIPT_OPTION_HELP7, &OptionProc, -1, 2, false);
  344. FCommands->Register(L"ascii", 0, SCRIPT_OPTION_HELP7, &AsciiProc, 0, 0, false);
  345. FCommands->Register(L"binary", 0, SCRIPT_OPTION_HELP7, &BinaryProc, 0, 0, false);
  346. FCommands->Register(L"synchronize", SCRIPT_SYNCHRONIZE_DESC, SCRIPT_SYNCHRONIZE_HELP7, &SynchronizeProc, 0, -1, true);
  347. FCommands->Register(L"keepuptodate", SCRIPT_KEEPUPTODATE_DESC, SCRIPT_KEEPUPTODATE_HELP5, &KeepUpToDateProc, 0, 2, true);
  348. // the echo command does not have switches actually, but it must handle dashes in its arguments
  349. FCommands->Register(L"echo", SCRIPT_ECHO_DESC, SCRIPT_ECHO_HELP, &EchoProc, -1, -1, true);
  350. FCommands->Register(L"stat", SCRIPT_STAT_DESC, SCRIPT_STAT_HELP, &StatProc, 1, 1, false);
  351. FCommands->Register(L"checksum", SCRIPT_CHECKSUM_DESC, SCRIPT_CHECKSUM_HELP, &ChecksumProc, 2, 2, false);
  352. }
  353. //---------------------------------------------------------------------------
  354. void __fastcall TScript::RequireParams(TScriptProcParams * Parameters, int MinParams)
  355. {
  356. if (Parameters->ParamCount < MinParams)
  357. {
  358. throw Exception(FMTLOAD(SCRIPT_MISSING_PARAMS, (Parameters->FullCommand)));
  359. }
  360. }
  361. //---------------------------------------------------------------------------
  362. void __fastcall TScript::CheckDefaultCopyParam()
  363. {
  364. if (FWarnNonDefaultCopyParam)
  365. {
  366. // started with non-factory settings and still have them, warn
  367. if (HasNonDefaultCopyParams())
  368. {
  369. PrintLine(LoadStr(SCRIPT_NON_DEFAULT_COPY_PARAM));
  370. }
  371. FWarnNonDefaultCopyParam = false;
  372. }
  373. }
  374. //---------------------------------------------------------------------------
  375. bool __fastcall TScript::HasNonDefaultCopyParams()
  376. {
  377. return !(FCopyParam == TCopyParamType());
  378. }
  379. //---------------------------------------------------------------------------
  380. void __fastcall TScript::SetCopyParam(const TCopyParamType & value)
  381. {
  382. FCopyParam.Assign(&value);
  383. FWarnNonDefaultCopyParam = HasNonDefaultCopyParams();
  384. }
  385. //---------------------------------------------------------------------------
  386. void __fastcall TScript::CheckDefaultSynchronizeParams()
  387. {
  388. if (FWarnNonDefaultSynchronizeParams)
  389. {
  390. // as opposite to CheckDefaultCopyParam(), not checking
  391. // current params as we cannot override any of those we accept anyway
  392. PrintLine(LoadStr(SCRIPT_NON_DEFAULT_SYNC_PARAM));
  393. FWarnNonDefaultSynchronizeParams = false;
  394. }
  395. }
  396. //---------------------------------------------------------------------------
  397. void __fastcall TScript::SetSynchronizeParams(int value)
  398. {
  399. const int AcceptedParams =
  400. TTerminal::spExistingOnly | TTerminal::spTimestamp |
  401. TTerminal::spNotByTime | TTerminal::spBySize | TTerminal::spCaseSensitive;
  402. FSynchronizeParams = (value & AcceptedParams);
  403. FWarnNonDefaultSynchronizeParams =
  404. (FSynchronizeParams != (TTerminal::spDefault & AcceptedParams));
  405. }
  406. //---------------------------------------------------------------------------
  407. bool __fastcall TScript::IsTerminalLogging(TTerminal * ATerminal)
  408. {
  409. return (ATerminal != NULL) && ATerminal->Log->Logging;
  410. }
  411. //---------------------------------------------------------------------------
  412. const static UnicodeString ScriptLogFormat(L"Script: %s");
  413. void __fastcall TScript::Log(TLogLineType Type, const UnicodeString & AStr, TTerminal * ATerminal)
  414. {
  415. UnicodeString Str = FORMAT(ScriptLogFormat, (AStr));
  416. TTerminal * LoggingTerminal = (ATerminal != NULL ? ATerminal : (FLoggingTerminal != NULL ? FLoggingTerminal : Terminal));
  417. if (IsTerminalLogging(LoggingTerminal))
  418. {
  419. LoggingTerminal->Log->Add(Type, Str);
  420. }
  421. else if (Configuration->Logging)
  422. {
  423. FPendingLogLines->AddObject(Str, reinterpret_cast<TObject *>(Type));
  424. }
  425. }
  426. //---------------------------------------------------------------------------
  427. void __fastcall TScript::LogOption(const UnicodeString & LogStr)
  428. {
  429. Log(llInput, LogStr);
  430. }
  431. //---------------------------------------------------------------------------
  432. void __fastcall TScript::LogPendingLines(TTerminal * ATerminal)
  433. {
  434. if (IsTerminalLogging(ATerminal) && (FPendingLogLines->Count > 0))
  435. {
  436. // not using Log(), as we want to log to ATerminal, not Terminal,
  437. // what is different here, as we are called from TManagementScript::Connect()
  438. ATerminal->Log->Add(llMessage, FORMAT(ScriptLogFormat, (L"Retrospectively logging previous script records:")));
  439. for (int Index = 0; Index < FPendingLogLines->Count; Index++)
  440. {
  441. ATerminal->Log->Add(
  442. reinterpret_cast<TLogLineType>(FPendingLogLines->Objects[Index]),
  443. FPendingLogLines->Strings[Index]);
  444. }
  445. FPendingLogLines->Clear();
  446. ATerminal->Log->AddSeparator();
  447. }
  448. }
  449. //---------------------------------------------------------------------------
  450. UnicodeString __fastcall TScript::GetLogCmd(const UnicodeString & FullCommand,
  451. const UnicodeString & /*Command*/, const UnicodeString & /*Params*/)
  452. {
  453. return FullCommand;
  454. }
  455. //---------------------------------------------------------------------------
  456. void __fastcall TScript::StartInteractive()
  457. {
  458. FBatch = FInteractiveBatch;
  459. FConfirm = FInteractiveConfirm;
  460. FSessionReopenTimeout = FInteractiveSessionReopenTimeout;
  461. }
  462. //---------------------------------------------------------------------------
  463. void __fastcall TScript::Command(UnicodeString Cmd)
  464. {
  465. try
  466. {
  467. if (!Cmd.Trim().IsEmpty() && (Cmd[1] != L';') && (Cmd[1] != L'#'))
  468. {
  469. UnicodeString FullCmd = Cmd;
  470. UnicodeString Command;
  471. if (CutToken(Cmd, Command))
  472. {
  473. UnicodeString LogCmd = GetLogCmd(FullCmd, Command, Cmd);
  474. Log(llInput, LogCmd);
  475. if (Configuration->ActualLogProtocol >= 1)
  476. {
  477. UnicodeString LogCmdParams = LogCmd;
  478. UnicodeString DummyLogCmd;
  479. if (DebugAlwaysTrue(CutToken(LogCmdParams, DummyLogCmd)))
  480. {
  481. std::unique_ptr<TScriptProcParams> Parameters(new TScriptProcParams(FCommands->ResolveCommand(Cmd), LogCmdParams));
  482. Parameters->LogOptions(LogOption);
  483. }
  484. }
  485. if (FEcho)
  486. {
  487. PrintLine(LogCmd);
  488. }
  489. TTerminal * BeforeGroupTerminal = FGroups ? Terminal : NULL;
  490. if (BeforeGroupTerminal != NULL)
  491. {
  492. BeforeGroupTerminal->ActionLog->BeginGroup(LogCmd);
  493. }
  494. int ASessionReopenTimeout = Configuration->SessionReopenTimeout;
  495. try
  496. {
  497. Configuration->SessionReopenTimeout = FSessionReopenTimeout;
  498. try
  499. {
  500. FCommands->Execute(Command, Cmd);
  501. }
  502. catch(Exception & E)
  503. {
  504. // seemingly duplicate (to the method-level one) catch clause,
  505. // ensures the <failure/> tag is enclosed in <group/> tag
  506. if (!HandleExtendedException(&E))
  507. {
  508. throw;
  509. }
  510. }
  511. }
  512. __finally
  513. {
  514. Configuration->SessionReopenTimeout = ASessionReopenTimeout;
  515. TTerminal * AfterGroupTerminal = FGroups ? Terminal : NULL;
  516. if (AfterGroupTerminal != NULL)
  517. {
  518. // this happens for "open" command
  519. if (AfterGroupTerminal != BeforeGroupTerminal)
  520. {
  521. AfterGroupTerminal->ActionLog->BeginGroup(LogCmd);
  522. }
  523. AfterGroupTerminal->ActionLog->EndGroup();
  524. }
  525. }
  526. }
  527. }
  528. }
  529. catch(Exception & E)
  530. {
  531. if (!HandleExtendedException(&E))
  532. {
  533. throw;
  534. }
  535. }
  536. }
  537. //---------------------------------------------------------------------------
  538. TStrings * __fastcall TScript::CreateFileList(TScriptProcParams * Parameters, int Start,
  539. int End, TFileListType ListType)
  540. {
  541. TStrings * Result = new TStringList();
  542. try
  543. {
  544. TStrings * FileLists = NULL;
  545. try
  546. {
  547. for (int i = Start; i <= End; i++)
  548. {
  549. UnicodeString FileName = Parameters->Param[i];
  550. if (SimpleUnixExcludeTrailingBackslash(FileName) != FileName)
  551. {
  552. PrintLine(LoadStr(SCRIPT_AMBIGUOUS_SLASH_IN_PATH));
  553. }
  554. if (FLAGSET(ListType, fltDirectories))
  555. {
  556. TRemoteFile * File = new TRemoteFile();
  557. File->FileName = FileName;
  558. File->Type = FILETYPE_DIRECTORY;
  559. Result->AddObject(FileName, File);
  560. }
  561. else if (FLAGSET(ListType, fltMask) && TFileMasks::IsMask(FileName))
  562. {
  563. UnicodeString FileDirectory = UnixExtractFilePath(FileName);
  564. UnicodeString Directory = FileDirectory;
  565. if (Directory.IsEmpty())
  566. {
  567. Directory = UnixIncludeTrailingBackslash(FTerminal->CurrentDirectory);
  568. }
  569. TRemoteFileList * FileList = NULL;
  570. if (FileLists != NULL)
  571. {
  572. int Index = FileLists->IndexOf(Directory);
  573. if (Index > 0)
  574. {
  575. FileList = dynamic_cast<TRemoteFileList *>(FileLists->Objects[Index]);
  576. }
  577. }
  578. if (FileList == NULL)
  579. {
  580. FileList = FTerminal->CustomReadDirectoryListing(Directory, false);
  581. if (FileLists == NULL)
  582. {
  583. FileLists = new TStringList();
  584. }
  585. FileLists->AddObject(Directory, FileList);
  586. }
  587. TFileMasks Mask;
  588. Mask.SetMask(UnixExtractFileName(FileName));
  589. bool AnyFound = false;
  590. // Can happen in "batch continue" mode
  591. if (FileList != NULL)
  592. {
  593. for (int i = 0; i < FileList->Count; i++)
  594. {
  595. TRemoteFile * File = FileList->Files[i];
  596. TFileMasks::TParams Params;
  597. Params.Size = File->Size;
  598. Params.Modification = File->Modification;
  599. if (IsRealFile(File->FileName) &&
  600. Mask.MatchesFileName(File->FileName, false, &Params))
  601. {
  602. Result->AddObject(FileDirectory + File->FileName,
  603. FLAGSET(ListType, fltQueryServer) ? File->Duplicate() : NULL);
  604. AnyFound = true;
  605. }
  606. }
  607. }
  608. if (!AnyFound)
  609. {
  610. NoMatch(Mask.Masks, UnicodeString());
  611. }
  612. }
  613. else
  614. {
  615. TRemoteFile * File = NULL;
  616. if (FLAGSET(ListType, fltQueryServer))
  617. {
  618. FTerminal->ExceptionOnFail = true;
  619. try
  620. {
  621. File = FTerminal->ReadFile(UnixExcludeTrailingBackslash(FileName));
  622. if (!File->HaveFullFileName)
  623. {
  624. File->FullFileName = FileName;
  625. }
  626. }
  627. __finally
  628. {
  629. FTerminal->ExceptionOnFail = false;
  630. }
  631. }
  632. Result->AddObject(FileName, File);
  633. }
  634. }
  635. }
  636. __finally
  637. {
  638. if (FileLists != NULL)
  639. {
  640. for (int i = 0; i < FileLists->Count; i++)
  641. {
  642. delete FileLists->Objects[i];
  643. }
  644. delete FileLists;
  645. }
  646. }
  647. if (FLAGSET(ListType, fltLatest) && (Result->Count > 1))
  648. {
  649. // otherwise we do not have TRemoteFile's
  650. DebugAssert(FLAGSET(ListType, fltQueryServer));
  651. int LatestIndex = 0;
  652. for (int Index = 1; Index < Result->Count; Index++)
  653. {
  654. TRemoteFile * File = dynamic_cast<TRemoteFile *>(Result->Objects[Index]);
  655. if (dynamic_cast<TRemoteFile *>(Result->Objects[LatestIndex])->Modification < File->Modification)
  656. {
  657. LatestIndex = Index;
  658. }
  659. }
  660. TRemoteFile * File = dynamic_cast<TRemoteFile *>(Result->Objects[LatestIndex]);
  661. UnicodeString Path = Result->Strings[LatestIndex];
  662. Result->Delete(LatestIndex);
  663. FreeFiles(Result);
  664. Result->Clear();
  665. Result->AddObject(Path, File);
  666. }
  667. if (FLAGSET(ListType, fltOnlyFile))
  668. {
  669. for (int Index = 0; Index < Result->Count; Index++)
  670. {
  671. TRemoteFile * File = dynamic_cast<TRemoteFile *>(Result->Objects[Index]);
  672. if (File->IsDirectory)
  673. {
  674. throw Exception(FMTLOAD(NOT_FILE_ERROR, (File->FileName)));
  675. }
  676. }
  677. }
  678. }
  679. catch (...)
  680. {
  681. FreeFileList(Result);
  682. throw;
  683. }
  684. return Result;
  685. }
  686. //---------------------------------------------------------------------------
  687. TStrings * __fastcall TScript::CreateLocalFileList(TScriptProcParams * Parameters,
  688. int Start, int End, TFileListType ListType)
  689. {
  690. TStringList * Result = new TStringList();
  691. try
  692. {
  693. Result->OwnsObjects = true;
  694. UnicodeString LatestFileName;
  695. TDateTime LatestModification; // initialized to 0
  696. for (int i = Start; i <= End; i++)
  697. {
  698. // FindFirstFile called (indirectly) below fails if path ends with slash.
  699. // (it actually won't make a difference functionally as we fall back to adding
  700. // the path as is in "else" branch, but the comment "let it fail later" won't stand)
  701. UnicodeString FileName = ExcludeTrailingBackslash(Parameters->Param[i]);
  702. if (FileName != Parameters->Param[i])
  703. {
  704. PrintLine(LoadStr(SCRIPT_AMBIGUOUS_SLASH_IN_PATH));
  705. }
  706. if (FLAGSET(ListType, fltMask))
  707. {
  708. TSearchRecOwned SearchRec;
  709. int FindAttrs = faReadOnly | faHidden | faSysFile | faDirectory | faArchive;
  710. UnicodeString Error;
  711. bool AnyFound = false;
  712. if (FindFirstUnchecked(FileName, FindAttrs, SearchRec) == 0)
  713. {
  714. UnicodeString Directory = ExtractFilePath(FileName);
  715. do
  716. {
  717. if (SearchRec.IsRealFile())
  718. {
  719. UnicodeString FileName = Directory + SearchRec.Name;
  720. TLocalFile * LocalFile = new TLocalFile;
  721. CopySearchRec(SearchRec, LocalFile->SearchRec);
  722. Result->AddObject(FileName, LocalFile);
  723. if (SearchRec.TimeStamp > LatestModification)
  724. {
  725. LatestFileName = FileName;
  726. LatestModification = SearchRec.TimeStamp;
  727. }
  728. AnyFound = true;
  729. }
  730. }
  731. while (FindNextChecked(SearchRec) == 0);
  732. }
  733. else
  734. {
  735. if (FileName.LastDelimiter(L"?*") == 0)
  736. {
  737. // No match, and it is not a mask, let it fail latter.
  738. // But with -latest, we have to fail straight away
  739. // (so maybe we should fail unconditionally now,
  740. // once we need to have the code in place anyway)
  741. if (FLAGSET(ListType, fltLatest))
  742. {
  743. throw Exception(FMTLOAD(FILE_NOT_EXISTS, (FileName)));
  744. }
  745. Result->Add(FileName);
  746. AnyFound = true;
  747. }
  748. else
  749. {
  750. Error = ListingSysErrorMessage();
  751. }
  752. }
  753. if (!AnyFound)
  754. {
  755. NoMatch(ExtractFileName(FileName), Error);
  756. }
  757. }
  758. else
  759. {
  760. DebugAssert(FLAGCLEAR(ListType, fltLatest));
  761. // this branch is currently never used
  762. Result->Add(FileName);
  763. }
  764. }
  765. if (FLAGSET(ListType, fltLatest))
  766. {
  767. Result->Clear();
  768. if (!LatestFileName.IsEmpty())
  769. {
  770. Result->Add(LatestFileName);
  771. }
  772. }
  773. }
  774. catch(...)
  775. {
  776. delete Result;
  777. throw;
  778. }
  779. return Result;
  780. }
  781. //---------------------------------------------------------------------------
  782. UnicodeString __fastcall TScript::ListingSysErrorMessage()
  783. {
  784. UnicodeString Result;
  785. int LastError = GetLastError();
  786. // System error text for ERROR_FILE_NOT_FOUND is more or less redundant to ours
  787. // SCRIPT_MATCH_NO_MATCH. Also the system error does not look nice/user friendly
  788. // so avoid using it for this frequent case.
  789. if (LastError != ERROR_FILE_NOT_FOUND)
  790. {
  791. Result = SysErrorMessageForError(LastError);
  792. }
  793. return Result;
  794. }
  795. //---------------------------------------------------------------------------
  796. void __fastcall TScript::NoMatch(const UnicodeString & Message)
  797. {
  798. if (FFailOnNoMatch)
  799. {
  800. throw Exception(Message);
  801. }
  802. else
  803. {
  804. PrintLine(Message);
  805. }
  806. }
  807. //---------------------------------------------------------------------------
  808. void __fastcall TScript::NoMatch(const UnicodeString & Mask, const UnicodeString & Error)
  809. {
  810. UnicodeString Message = FMTLOAD(SCRIPT_MATCH_NO_MATCH, (Mask));
  811. if (!Error.IsEmpty())
  812. {
  813. Message += FORMAT(L" (%s)", (Error));
  814. }
  815. NoMatch(Message);
  816. }
  817. //---------------------------------------------------------------------------
  818. void __fastcall TScript::FreeFiles(TStrings * FileList)
  819. {
  820. for (int i = 0; i < FileList->Count; i++)
  821. {
  822. if (FileList->Objects[i] != NULL)
  823. {
  824. TRemoteFile * File = dynamic_cast<TRemoteFile *>(FileList->Objects[i]);
  825. delete File;
  826. }
  827. }
  828. }
  829. //---------------------------------------------------------------------------
  830. void __fastcall TScript::FreeFileList(TStrings * FileList)
  831. {
  832. FreeFiles(FileList);
  833. delete FileList;
  834. }
  835. //---------------------------------------------------------------------------
  836. void __fastcall TScript::ConnectTerminal(TTerminal * ATerminal)
  837. {
  838. ATerminal->Open();
  839. }
  840. //---------------------------------------------------------------------------
  841. void __fastcall TScript::Print(const UnicodeString Str, bool Error)
  842. {
  843. if (FOnPrint != NULL)
  844. {
  845. FOnPrint(this, Str, Error);
  846. }
  847. }
  848. //---------------------------------------------------------------------------
  849. void __fastcall TScript::PrintLine(const UnicodeString Str, bool Error, TTerminal * ATerminal)
  850. {
  851. Log(llOutput, Str, ATerminal);
  852. Print(Str + L"\n", Error);
  853. }
  854. //---------------------------------------------------------------------------
  855. bool __fastcall TScript::HandleExtendedException(Exception * E, TTerminal * ATerminal)
  856. {
  857. bool Result = (OnShowExtendedException != NULL);
  858. if (Result)
  859. {
  860. if (ATerminal == NULL)
  861. {
  862. ATerminal = FTerminal;
  863. }
  864. OnShowExtendedException(ATerminal, E, NULL);
  865. }
  866. return Result;
  867. }
  868. //---------------------------------------------------------------------------
  869. void __fastcall TScript::CheckSession()
  870. {
  871. if (FTerminal == NULL)
  872. {
  873. throw Exception(LoadStr(SCRIPT_NO_SESSION));
  874. }
  875. }
  876. //---------------------------------------------------------------------------
  877. void __fastcall TScript::NotSupported()
  878. {
  879. throw Exception(LoadStr(NOTSUPPORTED));
  880. }
  881. //---------------------------------------------------------------------------
  882. void __fastcall TScript::CheckMultiFilesToOne(TStrings * FileList, const UnicodeString & Target, bool Unix)
  883. {
  884. UnicodeString Name;
  885. if (Unix)
  886. {
  887. Name = UnixExtractFileName(Target);
  888. }
  889. else
  890. {
  891. Name = ExtractFileName(Target);
  892. }
  893. if (!IsFileNameMask(Name) && (FileList->Count > 1))
  894. {
  895. UnicodeString Message =
  896. RemoveEmptyLines(UnformatMessage(FormatMultiFilesToOneConfirmation(Target, Unix)));
  897. PrintLine(Message);
  898. }
  899. }
  900. //---------------------------------------------------------------------------
  901. void __fastcall TScript::CheckParams(TScriptProcParams * Parameters)
  902. {
  903. TScriptCommands::CheckParams(Parameters, false);
  904. }
  905. //---------------------------------------------------------------------------
  906. void __fastcall TScript::TransferParamParams(int & Params, TScriptProcParams * Parameters)
  907. {
  908. Params |= FLAGMASK(!FConfirm, cpNoConfirmation);
  909. if (Parameters->FindSwitch(DELETE_SWITCH))
  910. {
  911. Params |= cpDelete;
  912. }
  913. if (Parameters->FindSwitch(L"resume"))
  914. {
  915. Params |= cpResume;
  916. }
  917. else if (Parameters->FindSwitch(L"append"))
  918. {
  919. Params |= cpAppend;
  920. }
  921. }
  922. //---------------------------------------------------------------------------
  923. void __fastcall TScript::CopyParamParams(TCopyParamType & CopyParam, TScriptProcParams * Parameters)
  924. {
  925. UnicodeString Value;
  926. if (!FWantsProgress)
  927. {
  928. // total size is not visualized, hence it makes no sense to calculate it
  929. CopyParam.CalculateSize = false;
  930. }
  931. if (Parameters->FindSwitch(NOPRESERVETIME_SWITCH))
  932. {
  933. CopyParam.PreserveTime = false;
  934. CopyParam.PreserveTimeDirs = false;
  935. }
  936. if (Parameters->FindSwitch(PRESERVETIME_SWITCH, Value))
  937. {
  938. CopyParam.PreserveTime = true;
  939. if (SameText(Value, PRESERVETIMEDIRS_SWITCH_VALUE))
  940. {
  941. CopyParam.PreserveTimeDirs = true;
  942. }
  943. }
  944. if (Parameters->FindSwitch(NOPERMISSIONS_SWITCH))
  945. {
  946. CopyParam.PreserveRights = false;
  947. }
  948. if (Parameters->FindSwitch(PERMISSIONS_SWITCH, Value))
  949. {
  950. CopyParam.PreserveRights = true;
  951. CopyParam.Rights.Octal = Value;
  952. }
  953. if (Parameters->FindSwitch(SPEED_SWITCH, Value))
  954. {
  955. int CPSLimit;
  956. if (Value.IsEmpty())
  957. {
  958. CPSLimit = 0;
  959. }
  960. else
  961. {
  962. CPSLimit = StrToInt(Value) * 1024;
  963. if (CPSLimit < 0)
  964. {
  965. CPSLimit = 0;
  966. }
  967. }
  968. CopyParam.CPSLimit = CPSLimit;
  969. }
  970. if (Parameters->FindSwitch(TRANSFER_SWITCH, Value))
  971. {
  972. CopyParam.TransferMode = ParseTransferModeName(Value);
  973. }
  974. if (Parameters->FindSwitch(FILEMASK_SWITCH, Value))
  975. {
  976. CopyParam.IncludeFileMask = Value;
  977. if (FIncludeFileMaskOptionUsed)
  978. {
  979. PrintLine(LoadStr(SCRIPT_FILEMASK_INCLUDE_EXCLUDE));
  980. }
  981. }
  982. if (Parameters->FindSwitch(RESUMESUPPORT_SWITCH, Value))
  983. {
  984. int ToggleValue = TScriptCommands::FindCommand(ToggleNames,
  985. LENOF(ToggleNames), Value);
  986. if (ToggleValue >= 0)
  987. {
  988. switch (ToggleValue)
  989. {
  990. case ToggleOff:
  991. CopyParam.ResumeSupport = rsOff;
  992. break;
  993. case ToggleOn:
  994. CopyParam.ResumeSupport = rsOn;
  995. break;
  996. default:
  997. DebugFail();
  998. break;
  999. }
  1000. }
  1001. else
  1002. {
  1003. int ThresholdValue;
  1004. if (!TryStrToInt(Value, ThresholdValue))
  1005. {
  1006. throw Exception(FMTLOAD(SCRIPT_VALUE_UNKNOWN, (RESUMESUPPORT_SWITCH, Value)));
  1007. }
  1008. CopyParam.ResumeSupport = rsSmart;
  1009. CopyParam.ResumeThreshold = ThresholdValue * 1024;
  1010. }
  1011. }
  1012. if (Parameters->FindSwitch(NONEWERONLY_SWICH))
  1013. {
  1014. CopyParam.NewerOnly = false;
  1015. }
  1016. if (Parameters->FindSwitch(NEWERONLY_SWICH))
  1017. {
  1018. CopyParam.NewerOnly = true;
  1019. }
  1020. std::unique_ptr<TStrings> RawSettings(new TStringList());
  1021. if (Parameters->FindSwitch(RAWTRANSFERSETTINGS_SWITCH, RawSettings.get()))
  1022. {
  1023. std::unique_ptr<TOptionsStorage> OptionsStorage(new TOptionsStorage(RawSettings.get(), false));
  1024. CopyParam.Load(OptionsStorage.get());
  1025. }
  1026. }
  1027. //---------------------------------------------------------------------------
  1028. void __fastcall TScript::ResetTransfer()
  1029. {
  1030. }
  1031. //---------------------------------------------------------------------------
  1032. bool __fastcall TScript::EnsureCommandSessionFallback(
  1033. TFSCapability Capability, TSessionAction & Action)
  1034. {
  1035. bool Result = FTerminal->IsCapable[Capability] ||
  1036. FTerminal->CommandSessionOpened;
  1037. if (!Result)
  1038. {
  1039. try
  1040. {
  1041. ConnectTerminal(FTerminal->CommandSession);
  1042. Result = true;
  1043. }
  1044. catch(Exception & E)
  1045. {
  1046. Action.Rollback(&E);
  1047. HandleExtendedException(&E, FTerminal->CommandSession);
  1048. Result = false;
  1049. }
  1050. }
  1051. return Result;
  1052. }
  1053. //---------------------------------------------------------------------------
  1054. void __fastcall TScript::HelpProc(TScriptProcParams * Parameters)
  1055. {
  1056. UnicodeString Output;
  1057. if (Parameters->ParamCount == 0)
  1058. {
  1059. UnicodeString Command;
  1060. UnicodeString Description;
  1061. int Index = 0;
  1062. while (FCommands->Enumerate(Index, &Command, &Description, NULL))
  1063. {
  1064. if (!Description.IsEmpty())
  1065. {
  1066. Output += FORMAT(L"%-8s %s\n", (Command, Description));
  1067. }
  1068. Index++;
  1069. }
  1070. }
  1071. else
  1072. {
  1073. for (int i = 1; i <= Parameters->ParamCount; i++)
  1074. {
  1075. UnicodeString Help;
  1076. if (FCommands->Info(Parameters->Param[i], NULL, &Help))
  1077. {
  1078. Output += Help;
  1079. }
  1080. else
  1081. {
  1082. throw Exception(FMTLOAD(SCRIPT_COMMAND_UNKNOWN, (Parameters->Param[i])));
  1083. }
  1084. }
  1085. }
  1086. Print(Output);
  1087. }
  1088. //---------------------------------------------------------------------------
  1089. void __fastcall TScript::CallProc(TScriptProcParams * Parameters)
  1090. {
  1091. CheckSession();
  1092. if (!FTerminal->IsCapable[fcAnyCommand] &&
  1093. !FTerminal->IsCapable[fcSecondaryShell])
  1094. {
  1095. NotSupported();
  1096. }
  1097. // this is used only to log failures to open separate shell session,
  1098. // the actual call logging is done in TTerminal::AnyCommand
  1099. TCallSessionAction Action(
  1100. FTerminal->ActionLog, Parameters->ParamsStr, FTerminal->CurrentDirectory);
  1101. if (EnsureCommandSessionFallback(fcAnyCommand, Action))
  1102. {
  1103. Action.Cancel();
  1104. FTerminal->AnyCommand(Parameters->ParamsStr, TerminalCaptureLog);
  1105. }
  1106. }
  1107. //---------------------------------------------------------------------------
  1108. void __fastcall TScript::EchoProc(TScriptProcParams * Parameters)
  1109. {
  1110. PrintLine(Parameters->ParamsStr);
  1111. }
  1112. //---------------------------------------------------------------------------
  1113. void __fastcall TScript::StatProc(TScriptProcParams * Parameters)
  1114. {
  1115. CheckSession();
  1116. UnicodeString Path = UnixExcludeTrailingBackslash(Parameters->Param[1]);
  1117. FTerminal->ExceptionOnFail = true;
  1118. TRemoteFile * File = NULL;
  1119. try
  1120. {
  1121. File = FTerminal->ReadFileListing(Path);
  1122. PrintLine(File->ListingStr);
  1123. }
  1124. __finally
  1125. {
  1126. FTerminal->ExceptionOnFail = false;
  1127. delete File;
  1128. }
  1129. }
  1130. //---------------------------------------------------------------------------
  1131. void __fastcall TScript::DoCalculatedChecksum(
  1132. const UnicodeString & FileName, const UnicodeString & DebugUsedArg(Alg), const UnicodeString & Hash)
  1133. {
  1134. PrintLine(FORMAT(L"%s %s", (Hash, FileName)));
  1135. }
  1136. //---------------------------------------------------------------------------
  1137. void __fastcall TScript::ChecksumProc(TScriptProcParams * Parameters)
  1138. {
  1139. CheckSession();
  1140. if (!FTerminal->IsCapable[fcCalculatingChecksum] &&
  1141. (!FTerminal->IsCapable[fcSecondaryShell] || FTerminal->IsEncryptingFiles()))
  1142. {
  1143. NotSupported();
  1144. }
  1145. // this is used only to log failures to open separate shell session,
  1146. // the actual call logging is done in TTerminal::CalculateFilesChecksum
  1147. TChecksumSessionAction Action(FTerminal->ActionLog);
  1148. if (EnsureCommandSessionFallback(fcCalculatingChecksum, Action))
  1149. {
  1150. Action.Cancel();
  1151. UnicodeString Alg = Parameters->Param[1];
  1152. TStrings * FileList = CreateFileList(Parameters, 2, 2, fltQueryServer);
  1153. FTerminal->ExceptionOnFail = true;
  1154. try
  1155. {
  1156. if ((FileList->Count != 1) ||
  1157. DebugNotNull(dynamic_cast<TRemoteFile *>(FileList->Objects[0]))->IsDirectory)
  1158. {
  1159. throw Exception(FMTLOAD(NOT_FILE_ERROR, (FileList->Strings[0])));
  1160. }
  1161. FTerminal->CalculateFilesChecksum(Alg, FileList, DoCalculatedChecksum);
  1162. }
  1163. __finally
  1164. {
  1165. FTerminal->ExceptionOnFail = false;
  1166. FreeFileList(FileList);
  1167. }
  1168. }
  1169. }
  1170. //---------------------------------------------------------------------------
  1171. void __fastcall TScript::TerminalCaptureLog(const UnicodeString & AddedLine,
  1172. TCaptureOutputType OutputType)
  1173. {
  1174. if ((OutputType == cotOutput) || (OutputType == cotError))
  1175. {
  1176. PrintLine(AddedLine);
  1177. }
  1178. }
  1179. //---------------------------------------------------------------------------
  1180. void __fastcall TScript::PwdProc(TScriptProcParams * /*Parameters*/)
  1181. {
  1182. CheckSession();
  1183. PrintLine(FTerminal->CurrentDirectory);
  1184. TCwdSessionAction Action(FTerminal->ActionLog, FTerminal->CurrentDirectory);
  1185. }
  1186. //---------------------------------------------------------------------------
  1187. void __fastcall TScript::CdProc(TScriptProcParams * Parameters)
  1188. {
  1189. CheckSession();
  1190. if (Parameters->ParamCount == 0)
  1191. {
  1192. FTerminal->HomeDirectory();
  1193. }
  1194. else
  1195. {
  1196. FTerminal->ChangeDirectory(Parameters->Param[1]);
  1197. }
  1198. PrintLine(FTerminal->CurrentDirectory);
  1199. }
  1200. //---------------------------------------------------------------------------
  1201. void __fastcall TScript::LsProc(TScriptProcParams * Parameters)
  1202. {
  1203. CheckSession();
  1204. UnicodeString Directory;
  1205. TFileMasks Mask;
  1206. bool HaveMask = false;
  1207. if (Parameters->ParamCount > 0)
  1208. {
  1209. Directory = Parameters->Param[1];
  1210. UnicodeString MaskStr = UnixExtractFileName(Directory);
  1211. HaveMask = TFileMasks::IsMask(MaskStr);
  1212. if (HaveMask)
  1213. {
  1214. Mask.SetMask(MaskStr);
  1215. Directory = UnixExtractFilePath(Directory);
  1216. }
  1217. }
  1218. if (Directory.IsEmpty())
  1219. {
  1220. Directory = FTerminal->CurrentDirectory;
  1221. }
  1222. TRemoteFileList * FileList = FTerminal->ReadDirectoryListing(Directory, Mask);
  1223. // on error user may select "skip", then we get NULL
  1224. if (FileList != NULL)
  1225. {
  1226. try
  1227. {
  1228. if (FileList->Count > 0)
  1229. {
  1230. for (int i = 0; i < FileList->Count; i++)
  1231. {
  1232. PrintLine(FileList->Files[i]->ListingStr);
  1233. }
  1234. }
  1235. else
  1236. {
  1237. if (HaveMask)
  1238. {
  1239. NoMatch(Mask.Masks, UnicodeString());
  1240. }
  1241. }
  1242. }
  1243. __finally
  1244. {
  1245. delete FileList;
  1246. }
  1247. }
  1248. }
  1249. //---------------------------------------------------------------------------
  1250. void __fastcall TScript::RmProc(TScriptProcParams * Parameters)
  1251. {
  1252. CheckSession();
  1253. bool OnlyFile = Parameters->FindSwitch(L"onlyfile");
  1254. TStrings * FileList = CreateFileList(
  1255. Parameters, 1, Parameters->ParamCount,
  1256. (TFileListType)(fltQueryServer | fltMask| FLAGMASK(OnlyFile, fltOnlyFile)));
  1257. try
  1258. {
  1259. CheckParams(Parameters);
  1260. FTerminal->DeleteFiles(FileList);
  1261. }
  1262. __finally
  1263. {
  1264. FreeFileList(FileList);
  1265. }
  1266. }
  1267. //---------------------------------------------------------------------------
  1268. void __fastcall TScript::RmDirProc(TScriptProcParams * Parameters)
  1269. {
  1270. CheckSession();
  1271. TStrings * FileList = CreateFileList(Parameters, 1, Parameters->ParamCount, fltDirectories);
  1272. try
  1273. {
  1274. FTerminal->DeleteFiles(FileList);
  1275. }
  1276. __finally
  1277. {
  1278. FreeFileList(FileList);
  1279. }
  1280. }
  1281. //---------------------------------------------------------------------------
  1282. void __fastcall TScript::DoMvOrCp(TScriptProcParams * Parameters, TFSCapability Capability, bool Cp)
  1283. {
  1284. CheckSession();
  1285. if (!FTerminal->IsCapable[Capability])
  1286. {
  1287. NotSupported();
  1288. }
  1289. TStrings * FileList =
  1290. CreateFileList(Parameters, 1, Parameters->ParamCount - 1, TFileListType(fltMask | fltQueryServer));
  1291. try
  1292. {
  1293. DebugAssert(Parameters->ParamCount >= 1);
  1294. UnicodeString Target = Parameters->Param[Parameters->ParamCount];
  1295. UnicodeString TargetDirectory = UnixExtractFilePath(Target);
  1296. UnicodeString FileMask = UnixExtractFileName(Target);
  1297. Target = UnixIncludeTrailingBackslash(TargetDirectory) + FileMask;
  1298. CheckMultiFilesToOne(FileList, Target, true);
  1299. if (Cp)
  1300. {
  1301. FTerminal->CopyFiles(FileList, TargetDirectory, FileMask);
  1302. }
  1303. else
  1304. {
  1305. bool DontOverwrite = true; // might use FConfirm eventually, but that would be breaking change
  1306. FTerminal->MoveFiles(FileList, TargetDirectory, FileMask, DontOverwrite);
  1307. }
  1308. }
  1309. __finally
  1310. {
  1311. FreeFileList(FileList);
  1312. }
  1313. }
  1314. //---------------------------------------------------------------------------
  1315. void __fastcall TScript::MvProc(TScriptProcParams * Parameters)
  1316. {
  1317. DoMvOrCp(Parameters, fcRemoteMove, false);
  1318. }
  1319. //---------------------------------------------------------------------------
  1320. void __fastcall TScript::CpProc(TScriptProcParams * Parameters)
  1321. {
  1322. DoMvOrCp(Parameters, fcRemoteCopy, true);
  1323. }
  1324. //---------------------------------------------------------------------------
  1325. void __fastcall TScript::ChModProc(TScriptProcParams * Parameters)
  1326. {
  1327. CheckSession();
  1328. if (!FTerminal->IsCapable[fcModeChanging])
  1329. {
  1330. NotSupported();
  1331. }
  1332. TStrings * FileList = CreateFileList(Parameters, 2, Parameters->ParamCount,
  1333. fltMask);
  1334. try
  1335. {
  1336. TRemoteProperties Properties;
  1337. Properties.Valid = TValidProperties() << vpRights;
  1338. Properties.Rights.Octal = Parameters->Param[1];
  1339. FTerminal->ChangeFilesProperties(FileList, &Properties);
  1340. }
  1341. __finally
  1342. {
  1343. FreeFileList(FileList);
  1344. }
  1345. }
  1346. //---------------------------------------------------------------------------
  1347. void __fastcall TScript::LnProc(TScriptProcParams * Parameters)
  1348. {
  1349. CheckSession();
  1350. if (!FTerminal->IsCapable[fcSymbolicLink])
  1351. {
  1352. NotSupported();
  1353. }
  1354. DebugAssert(Parameters->ParamCount == 2);
  1355. FTerminal->CreateLink(Parameters->Param[2], Parameters->Param[1], true);
  1356. }
  1357. //---------------------------------------------------------------------------
  1358. void __fastcall TScript::MkDirProc(TScriptProcParams * Parameters)
  1359. {
  1360. CheckSession();
  1361. TRemoteProperties Properties;
  1362. Properties.Valid = TValidProperties() << vpEncrypt;
  1363. Properties.Encrypt = FCopyParam.EncryptNewFiles;
  1364. FTerminal->CreateDirectory(Parameters->Param[1], &Properties);
  1365. }
  1366. //---------------------------------------------------------------------------
  1367. void __fastcall TScript::GetProc(TScriptProcParams * Parameters)
  1368. {
  1369. CheckSession();
  1370. ResetTransfer();
  1371. bool Latest = Parameters->FindSwitch(L"latest");
  1372. bool OnlyFile = Parameters->FindSwitch(L"onlyfile");
  1373. CheckDefaultCopyParam();
  1374. TCopyParamType CopyParam = FCopyParam;
  1375. CopyParamParams(CopyParam, Parameters);
  1376. int Params = 0;
  1377. TransferParamParams(Params, Parameters);
  1378. RequireParams(Parameters, 1);
  1379. int LastFileParam = (Parameters->ParamCount == 1 ? 1 : Parameters->ParamCount - 1);
  1380. DebugAssert(CopyParam.OnTransferOut == NULL);
  1381. if ((OnTransferOut != NULL) && (Parameters->ParamCount > 1) && SameText(Parameters->Param[Parameters->ParamCount], InOutParam))
  1382. {
  1383. CopyParam.OnTransferOut = OnTransferOut;
  1384. OnlyFile = true;
  1385. }
  1386. TStrings * FileList = CreateFileList(Parameters, 1, LastFileParam,
  1387. (TFileListType)(fltQueryServer | fltMask | FLAGMASK(Latest, fltLatest) | FLAGMASK(OnlyFile, fltOnlyFile)));
  1388. try
  1389. {
  1390. UnicodeString TargetDirectory;
  1391. if (CopyParam.OnTransferOut == NULL)
  1392. {
  1393. if (Parameters->ParamCount == 1)
  1394. {
  1395. TargetDirectory = GetCurrentDir();
  1396. CopyParam.FileMask = L"";
  1397. }
  1398. else
  1399. {
  1400. UnicodeString Target = Parameters->Param[Parameters->ParamCount];
  1401. TargetDirectory = ExtractFilePath(Target);
  1402. if (TargetDirectory.IsEmpty())
  1403. {
  1404. TargetDirectory = GetCurrentDir();
  1405. }
  1406. CopyParam.FileMask = ExtractFileName(Target);
  1407. Target = IncludeTrailingBackslash(TargetDirectory) + CopyParam.FileMask;
  1408. CheckMultiFilesToOne(FileList, Target, false);
  1409. }
  1410. }
  1411. CheckParams(Parameters);
  1412. CopyParam.IncludeFileMask.SetRoots(TargetDirectory, FileList);
  1413. FTerminal->CopyToLocal(FileList, TargetDirectory, &CopyParam, Params, NULL);
  1414. }
  1415. __finally
  1416. {
  1417. FreeFileList(FileList);
  1418. }
  1419. }
  1420. //---------------------------------------------------------------------------
  1421. void __fastcall TScript::PutProc(TScriptProcParams * Parameters)
  1422. {
  1423. CheckSession();
  1424. ResetTransfer();
  1425. bool Latest = Parameters->FindSwitch(L"latest");
  1426. CheckDefaultCopyParam();
  1427. TCopyParamType CopyParam = FCopyParam;
  1428. CopyParamParams(CopyParam, Parameters);
  1429. int Params = 0;
  1430. TransferParamParams(Params, Parameters);
  1431. RequireParams(Parameters, 1);
  1432. int LastFileParam = (Parameters->ParamCount == 1 ? 1 : Parameters->ParamCount - 1);
  1433. DebugAssert(CopyParam.OnTransferIn == NULL);
  1434. TStrings * FileList;
  1435. // We use stdin only if - is the very first parameter
  1436. if ((OnTransferIn != NULL) && SameText(Parameters->Param[1], InOutParam))
  1437. {
  1438. if (Parameters->ParamCount > 2)
  1439. {
  1440. throw Exception(LoadStr(STREAM_IN_SCRIPT_ERROR));
  1441. }
  1442. CopyParam.OnTransferIn = OnTransferIn;
  1443. FileList = new TStringList();
  1444. }
  1445. else
  1446. {
  1447. FileList = CreateLocalFileList(Parameters, 1, LastFileParam, (TFileListType)(fltMask | FLAGMASK(Latest, fltLatest)));
  1448. }
  1449. try
  1450. {
  1451. UnicodeString TargetDirectory;
  1452. if (Parameters->ParamCount == 1)
  1453. {
  1454. TargetDirectory = FTerminal->CurrentDirectory;
  1455. CopyParam.FileMask = L"";
  1456. }
  1457. else
  1458. {
  1459. UnicodeString Target = Parameters->Param[Parameters->ParamCount];
  1460. TargetDirectory = UnixExtractFilePath(Target);
  1461. if (TargetDirectory.IsEmpty())
  1462. {
  1463. TargetDirectory = FTerminal->CurrentDirectory;
  1464. }
  1465. CopyParam.FileMask = UnixExtractFileName(Target);
  1466. Target = UnixIncludeTrailingBackslash(TargetDirectory) + CopyParam.FileMask;
  1467. CheckMultiFilesToOne(FileList, Target, true);
  1468. }
  1469. if (CopyParam.OnTransferIn != NULL)
  1470. {
  1471. if (IsFileNameMask(CopyParam.FileMask))
  1472. {
  1473. throw Exception(LoadStr(STREAM_IN_SCRIPT_ERROR));
  1474. }
  1475. FileList->Add(CopyParam.FileMask);
  1476. }
  1477. CheckParams(Parameters);
  1478. CopyParam.IncludeFileMask.SetRoots(FileList, TargetDirectory);
  1479. FTerminal->CopyToRemote(FileList, TargetDirectory, &CopyParam, Params, NULL);
  1480. }
  1481. __finally
  1482. {
  1483. delete FileList;
  1484. }
  1485. }
  1486. //---------------------------------------------------------------------------
  1487. TTransferMode __fastcall TScript::ParseTransferModeName(UnicodeString Name)
  1488. {
  1489. DebugAssert((tmBinary == 0) && (tmAscii == 1) && (tmAutomatic == 2));
  1490. int Value = TScriptCommands::FindCommand(TransferModeNames,
  1491. TransferModeNamesCount, Name);
  1492. if (Value < 0)
  1493. {
  1494. throw Exception(FMTLOAD(SCRIPT_VALUE_UNKNOWN, (L"transfer", Name)));
  1495. }
  1496. return (TTransferMode)Value;
  1497. }
  1498. //---------------------------------------------------------------------------
  1499. void __fastcall TScript::OptionImpl(UnicodeString OptionName, UnicodeString ValueName)
  1500. {
  1501. enum { Echo, Batch, Confirm, Transfer, SynchDelete, Exclude, Include, ReconnectTime, FailOnNoMatch };
  1502. static const wchar_t * Names[] = { L"echo", L"batch", L"confirm", L"transfer",
  1503. L"synchdelete", L"exclude", L"include", L"reconnecttime", L"failonnomatch" };
  1504. DebugAssert((BatchOff == 0) && (BatchOn == 1) && (BatchAbort == 2) && (BatchContinue == 3));
  1505. static const wchar_t * BatchModeNames[] = { L"off", L"on", L"abort", L"continue" };
  1506. int Option = -1;
  1507. if (!OptionName.IsEmpty())
  1508. {
  1509. Option = TScriptCommands::FindCommand(Names, LENOF(Names), OptionName);
  1510. if (Option < 0)
  1511. {
  1512. throw Exception(FMTLOAD(SCRIPT_OPTION_UNKNOWN, (OptionName)));
  1513. }
  1514. else
  1515. {
  1516. OptionName = Names[Option];
  1517. }
  1518. }
  1519. #define OPT(OPT) ((Option < 0) || (Option == OPT))
  1520. const wchar_t * ListFormat = L"%-15s %-10s";
  1521. bool SetValue = !ValueName.IsEmpty();
  1522. bool PrintReconnectTime = false;
  1523. if (OPT(Echo))
  1524. {
  1525. if (SetValue)
  1526. {
  1527. int Value = TScriptCommands::FindCommand(ToggleNames, LENOF(ToggleNames), ValueName);
  1528. if (Value < 0)
  1529. {
  1530. throw Exception(FMTLOAD(SCRIPT_VALUE_UNKNOWN, (ValueName, OptionName)));
  1531. }
  1532. FEcho = (Value == ToggleOn);
  1533. }
  1534. PrintLine(FORMAT(ListFormat, (Names[Echo], ToggleNames[FEcho ? ToggleOn : ToggleOff])));
  1535. }
  1536. if (OPT(Batch))
  1537. {
  1538. if (SetValue)
  1539. {
  1540. int Value = TScriptCommands::FindCommand(BatchModeNames, LENOF(BatchModeNames), ValueName);
  1541. if (Value < 0)
  1542. {
  1543. throw Exception(FMTLOAD(SCRIPT_VALUE_UNKNOWN, (ValueName, OptionName)));
  1544. }
  1545. FBatch = (TBatchMode)Value;
  1546. FInteractiveBatch = FBatch;
  1547. if (SetValue && (FBatch != BatchOff) && (FSessionReopenTimeout == 0))
  1548. {
  1549. FSessionReopenTimeout = BatchSessionReopenTimeout;
  1550. FInteractiveSessionReopenTimeout = FSessionReopenTimeout;
  1551. PrintReconnectTime = true;
  1552. }
  1553. }
  1554. PrintLine(FORMAT(ListFormat, (Names[Batch], BatchModeNames[FBatch])));
  1555. }
  1556. if (OPT(Confirm))
  1557. {
  1558. if (SetValue)
  1559. {
  1560. int Value = TScriptCommands::FindCommand(ToggleNames, LENOF(ToggleNames), ValueName);
  1561. if (Value < 0)
  1562. {
  1563. throw Exception(FMTLOAD(SCRIPT_VALUE_UNKNOWN, (ValueName, OptionName)));
  1564. }
  1565. FConfirm = (Value == ToggleOn);
  1566. FInteractiveConfirm = FConfirm;
  1567. }
  1568. PrintLine(FORMAT(ListFormat, (Names[Confirm], ToggleNames[FConfirm ? ToggleOn : ToggleOff])));
  1569. }
  1570. // omit the option in listing
  1571. if (Option == Transfer)
  1572. {
  1573. if (SetValue)
  1574. {
  1575. FCopyParam.TransferMode = ParseTransferModeName(ValueName);
  1576. }
  1577. DebugAssert(FCopyParam.TransferMode < (TTransferMode)TransferModeNamesCount);
  1578. const wchar_t * Value = TransferModeNames[FCopyParam.TransferMode];
  1579. PrintLine(FORMAT(ListFormat, (Names[Transfer], Value)));
  1580. }
  1581. // omit the option in listing
  1582. if (Option == SynchDelete)
  1583. {
  1584. if (SetValue)
  1585. {
  1586. int Value = TScriptCommands::FindCommand(ToggleNames, LENOF(ToggleNames), ValueName);
  1587. if (Value < 0)
  1588. {
  1589. throw Exception(FMTLOAD(SCRIPT_VALUE_UNKNOWN, (ValueName, OptionName)));
  1590. }
  1591. FSynchronizeParams =
  1592. (FSynchronizeParams & ~TTerminal::spDelete) |
  1593. FLAGMASK(Value == ToggleOn, TTerminal::spDelete);
  1594. }
  1595. PrintLine(FORMAT(ListFormat, (Names[SynchDelete],
  1596. ToggleNames[FLAGSET(FSynchronizeParams, TTerminal::spDelete) ? ToggleOn : ToggleOff])));
  1597. }
  1598. static const wchar_t * Clear = L"clear";
  1599. // omit the option in listing
  1600. if (Option == Include)
  1601. {
  1602. if (SetValue)
  1603. {
  1604. FCopyParam.IncludeFileMask =
  1605. (ValueName == Clear ? UnicodeString() : ValueName);
  1606. FIncludeFileMaskOptionUsed = (ValueName != Clear);
  1607. }
  1608. PrintLine(FORMAT(ListFormat, (Names[Include], FCopyParam.IncludeFileMask.Masks)));
  1609. }
  1610. // omit the option in listing
  1611. if (Option == Exclude)
  1612. {
  1613. if (SetValue)
  1614. {
  1615. // will throw if ValueName already includes IncludeExcludeFileMasksDelimiter
  1616. FCopyParam.IncludeFileMask =
  1617. (ValueName == Clear ? UnicodeString() : UnicodeString(IncludeExcludeFileMasksDelimiter) + ValueName);
  1618. FIncludeFileMaskOptionUsed = (ValueName != Clear);
  1619. }
  1620. PrintLine(FORMAT(ListFormat, (Names[Include], FCopyParam.IncludeFileMask.Masks)));
  1621. }
  1622. if (OPT(ReconnectTime) || PrintReconnectTime)
  1623. {
  1624. if (SetValue && !PrintReconnectTime)
  1625. {
  1626. int Value;
  1627. if (SameText(ValueName, ToggleNames[ToggleOff]))
  1628. {
  1629. Value = 0;
  1630. }
  1631. else
  1632. {
  1633. if (!TryStrToInt(ValueName, Value))
  1634. {
  1635. throw Exception(FMTLOAD(SCRIPT_VALUE_UNKNOWN, (ValueName, OptionName)));
  1636. }
  1637. else
  1638. {
  1639. Value *= MSecsPerSec;
  1640. }
  1641. }
  1642. FSessionReopenTimeout = Value;
  1643. FInteractiveSessionReopenTimeout = FSessionReopenTimeout;
  1644. }
  1645. if (FSessionReopenTimeout == 0)
  1646. {
  1647. ValueName = ToggleNames[ToggleOff];
  1648. }
  1649. else
  1650. {
  1651. ValueName = IntToStr(FSessionReopenTimeout / MSecsPerSec);
  1652. }
  1653. PrintLine(FORMAT(ListFormat, (Names[ReconnectTime], ValueName)));
  1654. }
  1655. if (OPT(FailOnNoMatch))
  1656. {
  1657. if (SetValue)
  1658. {
  1659. int Value = TScriptCommands::FindCommand(ToggleNames, LENOF(ToggleNames), ValueName);
  1660. if (Value < 0)
  1661. {
  1662. throw Exception(FMTLOAD(SCRIPT_VALUE_UNKNOWN, (ValueName, OptionName)));
  1663. }
  1664. FFailOnNoMatch = (Value == ToggleOn);
  1665. }
  1666. PrintLine(FORMAT(ListFormat, (Names[FailOnNoMatch], ToggleNames[FFailOnNoMatch ? ToggleOn : ToggleOff])));
  1667. }
  1668. #undef OPT
  1669. }
  1670. //---------------------------------------------------------------------------
  1671. void __fastcall TScript::OptionProc(TScriptProcParams * Parameters)
  1672. {
  1673. UnicodeString OptionName;
  1674. UnicodeString ValueName;
  1675. if (Parameters->ParamCount >= 1)
  1676. {
  1677. OptionName = Parameters->Param[1];
  1678. }
  1679. if (Parameters->ParamCount >= 2)
  1680. {
  1681. ValueName = Parameters->Param[2];
  1682. }
  1683. OptionImpl(OptionName, ValueName);
  1684. }
  1685. //---------------------------------------------------------------------------
  1686. void __fastcall TScript::AsciiProc(TScriptProcParams * /*Parameters*/)
  1687. {
  1688. OptionImpl(L"transfer", L"ascii");
  1689. }
  1690. //---------------------------------------------------------------------------
  1691. void __fastcall TScript::BinaryProc(TScriptProcParams * /*Parameters*/)
  1692. {
  1693. OptionImpl(L"transfer", L"binary");
  1694. }
  1695. //---------------------------------------------------------------------------
  1696. void __fastcall TScript::SynchronizeDirectories(TScriptProcParams * Parameters,
  1697. UnicodeString & LocalDirectory, UnicodeString & RemoteDirectory, int FirstParam)
  1698. {
  1699. if (Parameters->ParamCount >= FirstParam)
  1700. {
  1701. LocalDirectory = Parameters->Param[FirstParam];
  1702. }
  1703. else
  1704. {
  1705. LocalDirectory = GetCurrentDir();
  1706. }
  1707. if (Parameters->ParamCount >= FirstParam + 1)
  1708. {
  1709. RemoteDirectory = Parameters->Param[FirstParam + 1];
  1710. }
  1711. else
  1712. {
  1713. RemoteDirectory = FTerminal->CurrentDirectory;
  1714. }
  1715. }
  1716. //---------------------------------------------------------------------------
  1717. UnicodeString __fastcall TScript::SynchronizeFileRecord(
  1718. const UnicodeString & RootDirectory, const TSynchronizeChecklist::TItem * Item, bool Local)
  1719. {
  1720. const TSynchronizeChecklist::TItem::TFileInfo & FileInfo =
  1721. Local ? Item->Local : Item->Remote;
  1722. UnicodeString Path;
  1723. if (Local)
  1724. {
  1725. Path = IncludeTrailingBackslash(FileInfo.Directory) + FileInfo.FileName;
  1726. }
  1727. else
  1728. {
  1729. Path = UnixIncludeTrailingBackslash(FileInfo.Directory) + FileInfo.FileName;
  1730. }
  1731. if (SameText(RootDirectory, Path.SubString(1, RootDirectory.Length())))
  1732. {
  1733. Path[1] = L'.';
  1734. Path.Delete(2, RootDirectory.Length() - 2);
  1735. }
  1736. UnicodeString Result;
  1737. if (Item->IsDirectory)
  1738. {
  1739. if (Local)
  1740. {
  1741. Result = IncludeTrailingBackslash(Path);
  1742. }
  1743. else
  1744. {
  1745. Result = UnixIncludeTrailingBackslash(Path);
  1746. }
  1747. }
  1748. else
  1749. {
  1750. UnicodeString SizeStr = IntToStr(FileInfo.Size);
  1751. UnicodeString ModificationStr =
  1752. ::ModificationStr(FileInfo.Modification, FileInfo.ModificationFmt);
  1753. Result = FORMAT("%s [%s, %s]", (Path, SizeStr, ModificationStr));
  1754. }
  1755. return Result;
  1756. }
  1757. //---------------------------------------------------------------------------
  1758. void __fastcall TScript::SynchronizePreview(
  1759. UnicodeString LocalDirectory, UnicodeString RemoteDirectory,
  1760. TSynchronizeChecklist * Checklist)
  1761. {
  1762. LocalDirectory = IncludeTrailingBackslash(LocalDirectory);
  1763. RemoteDirectory = UnixIncludeTrailingBackslash(RemoteDirectory);
  1764. for (int Index = 0; (Index < Checklist->Count); Index++)
  1765. {
  1766. const TSynchronizeChecklist::TItem * Item = Checklist->Item[Index];
  1767. if (Item->Checked)
  1768. {
  1769. TDifferenceSessionAction Action(FTerminal->ActionLog, Item);
  1770. UnicodeString Message;
  1771. UnicodeString LocalRecord = SynchronizeFileRecord(LocalDirectory, Item, true);
  1772. UnicodeString RemoteRecord = SynchronizeFileRecord(RemoteDirectory, Item, false);
  1773. switch (Item->Action)
  1774. {
  1775. case TSynchronizeChecklist::saUploadNew:
  1776. Message =
  1777. FMTLOAD(SCRIPT_SYNC_UPLOAD_NEW, (LocalRecord));
  1778. break;
  1779. case TSynchronizeChecklist::saDownloadNew:
  1780. Message =
  1781. FMTLOAD(SCRIPT_SYNC_DOWNLOAD_NEW, (RemoteRecord));
  1782. break;
  1783. case TSynchronizeChecklist::saUploadUpdate:
  1784. Message =
  1785. FMTLOAD(SCRIPT_SYNC_UPLOAD_UPDATE,
  1786. (LocalRecord, RemoteRecord));
  1787. break;
  1788. case TSynchronizeChecklist::saDownloadUpdate:
  1789. Message =
  1790. FMTLOAD(SCRIPT_SYNC_DOWNLOAD_UPDATE,
  1791. (RemoteRecord, LocalRecord));
  1792. break;
  1793. case TSynchronizeChecklist::saDeleteRemote:
  1794. Message =
  1795. FMTLOAD(SCRIPT_SYNC_DELETE_REMOTE, (RemoteRecord));
  1796. break;
  1797. case TSynchronizeChecklist::saDeleteLocal:
  1798. Message =
  1799. FMTLOAD(SCRIPT_SYNC_DELETE_LOCAL, (LocalRecord));
  1800. break;
  1801. default:
  1802. DebugFail();
  1803. }
  1804. PrintLine(Message);
  1805. }
  1806. }
  1807. }
  1808. //---------------------------------------------------------------------------
  1809. void __fastcall TScript::SynchronizeProc(TScriptProcParams * Parameters)
  1810. {
  1811. CheckSession();
  1812. ResetTransfer();
  1813. static const wchar_t * ModeNames[] = { L"remote", L"local", L"both" };
  1814. CheckDefaultCopyParam();
  1815. TCopyParamType CopyParam = FCopyParam;
  1816. CopyParamParams(CopyParam, Parameters);
  1817. RequireParams(Parameters, 1);
  1818. if (Parameters->ParamCount > 3)
  1819. {
  1820. throw Exception(FMTLOAD(SCRIPT_TOO_MANY_PARAMS, (L"synchronize")));
  1821. }
  1822. UnicodeString ModeName = Parameters->Param[1];
  1823. DebugAssert(FSynchronizeMode < 0);
  1824. FSynchronizeMode = TScriptCommands::FindCommand(ModeNames, LENOF(ModeNames), ModeName);
  1825. try
  1826. {
  1827. if (FSynchronizeMode < 0)
  1828. {
  1829. throw Exception(FMTLOAD(SCRIPT_OPTION_UNKNOWN, (ModeName)));
  1830. }
  1831. UnicodeString LocalDirectory;
  1832. UnicodeString RemoteDirectory;
  1833. SynchronizeDirectories(Parameters, LocalDirectory, RemoteDirectory, 2);
  1834. CopyParam.IncludeFileMask.SetRoots(LocalDirectory, RemoteDirectory);
  1835. CheckDefaultSynchronizeParams();
  1836. int SynchronizeParams = FSynchronizeParams | TTerminal::spNoConfirmation;
  1837. UnicodeString Value;
  1838. if (Parameters->FindSwitch(L"delete"))
  1839. {
  1840. SynchronizeParams |= TTerminal::spDelete;
  1841. }
  1842. if (Parameters->FindSwitch(L"mirror") &&
  1843. (FSynchronizeMode != TTerminal::smBoth))
  1844. {
  1845. SynchronizeParams |= TTerminal::spMirror;
  1846. }
  1847. if (Parameters->FindSwitch(L"criteria", Value))
  1848. {
  1849. enum { None, Time, Size, Either, EitherBoth };
  1850. static const wchar_t * CriteriaNames[] = { L"none", L"time", L"size", L"either", L"both" };
  1851. int Criteria = TScriptCommands::FindCommand(CriteriaNames, LENOF(CriteriaNames), Value);
  1852. switch (Criteria)
  1853. {
  1854. case None:
  1855. SynchronizeParams |= TTerminal::spNotByTime;
  1856. SynchronizeParams &= ~TTerminal::spBySize;
  1857. break;
  1858. case Time:
  1859. SynchronizeParams &= ~(TTerminal::spNotByTime | TTerminal::spBySize);
  1860. break;
  1861. case Size:
  1862. SynchronizeParams |= TTerminal::spNotByTime | TTerminal::spBySize;
  1863. break;
  1864. case Either:
  1865. case EitherBoth:
  1866. SynchronizeParams &= ~TTerminal::spNotByTime;
  1867. SynchronizeParams |= TTerminal::spBySize;
  1868. break;
  1869. }
  1870. }
  1871. bool Preview = Parameters->FindSwitch(L"preview");
  1872. // enforce rules
  1873. if (FSynchronizeMode == TTerminal::smBoth)
  1874. {
  1875. SynchronizeParams &= ~(TTerminal::spNotByTime | TTerminal::spBySize);
  1876. }
  1877. CheckParams(Parameters);
  1878. PrintLine(LoadStr(SCRIPT_SYNCHRONIZE_COLLECTING));
  1879. TSynchronizeChecklist * Checklist =
  1880. FTerminal->SynchronizeCollect(LocalDirectory, RemoteDirectory,
  1881. static_cast<TTerminal::TSynchronizeMode>(FSynchronizeMode),
  1882. &CopyParam, SynchronizeParams, OnTerminalSynchronizeDirectory, NULL);
  1883. try
  1884. {
  1885. bool AnyChecked = false;
  1886. for (int Index = 0; !AnyChecked && (Index < Checklist->Count); Index++)
  1887. {
  1888. AnyChecked = Checklist->Item[Index]->Checked;
  1889. }
  1890. if (AnyChecked)
  1891. {
  1892. if (Preview)
  1893. {
  1894. PrintLine(LoadStr(SCRIPT_SYNCHRONIZE_CHECKLIST));
  1895. SynchronizePreview(LocalDirectory, RemoteDirectory, Checklist);
  1896. }
  1897. else
  1898. {
  1899. PrintLine(LoadStr(SCRIPT_SYNCHRONIZE_SYNCHRONIZING));
  1900. FTerminal->SynchronizeApply(
  1901. Checklist, &CopyParam, SynchronizeParams, OnTerminalSynchronizeDirectory, NULL, NULL, NULL, NULL);
  1902. }
  1903. }
  1904. else
  1905. {
  1906. NoMatch(LoadStr(SCRIPT_SYNCHRONIZE_NODIFFERENCE));
  1907. }
  1908. }
  1909. __finally
  1910. {
  1911. delete Checklist;
  1912. }
  1913. }
  1914. __finally
  1915. {
  1916. FSynchronizeMode = -1;
  1917. }
  1918. }
  1919. //---------------------------------------------------------------------------
  1920. void __fastcall TScript::Synchronize(const UnicodeString LocalDirectory,
  1921. const UnicodeString RemoteDirectory, const TCopyParamType & CopyParam,
  1922. int SynchronizeParams, TSynchronizeChecklist ** Checklist)
  1923. {
  1924. try
  1925. {
  1926. FKeepingUpToDate = true;
  1927. TSynchronizeChecklist * AChecklist =
  1928. FTerminal->SynchronizeCollect(LocalDirectory, RemoteDirectory, TTerminal::smRemote,
  1929. &CopyParam, SynchronizeParams, NULL, NULL);
  1930. try
  1931. {
  1932. if (AChecklist->Count > 0)
  1933. {
  1934. FTerminal->SynchronizeApply(
  1935. AChecklist, &CopyParam, SynchronizeParams, OnTerminalSynchronizeDirectory, NULL, NULL, NULL, NULL);
  1936. }
  1937. }
  1938. __finally
  1939. {
  1940. if (Checklist == NULL)
  1941. {
  1942. delete AChecklist;
  1943. }
  1944. else
  1945. {
  1946. *Checklist = AChecklist;
  1947. }
  1948. }
  1949. // to break line after the last transfer (if any);
  1950. Print(L"");
  1951. FKeepingUpToDate = false;
  1952. }
  1953. catch(Exception & E)
  1954. {
  1955. FKeepingUpToDate = false;
  1956. HandleExtendedException(&E);
  1957. throw;
  1958. }
  1959. }
  1960. //---------------------------------------------------------------------------
  1961. void __fastcall TScript::KeepUpToDateProc(TScriptProcParams * Parameters)
  1962. {
  1963. if (OnSynchronizeStartStop == NULL)
  1964. {
  1965. Abort();
  1966. }
  1967. CheckSession();
  1968. ResetTransfer();
  1969. CheckDefaultCopyParam();
  1970. TCopyParamType CopyParam = FCopyParam;
  1971. CopyParamParams(CopyParam, Parameters);
  1972. UnicodeString LocalDirectory;
  1973. UnicodeString RemoteDirectory;
  1974. SynchronizeDirectories(Parameters, LocalDirectory, RemoteDirectory, 1);
  1975. CheckDefaultSynchronizeParams();
  1976. int SynchronizeParams = FSynchronizeParams | TTerminal::spNoConfirmation |
  1977. TTerminal::spNoRecurse | TTerminal::spUseCache | TTerminal::spDelayProgress |
  1978. TTerminal::spSubDirs;
  1979. if (Parameters->FindSwitch(L"delete"))
  1980. {
  1981. SynchronizeParams |= TTerminal::spDelete;
  1982. }
  1983. CheckParams(Parameters);
  1984. PrintLine(LoadStr(SCRIPT_KEEPING_UP_TO_DATE));
  1985. OnSynchronizeStartStop(this, LocalDirectory, RemoteDirectory, CopyParam, SynchronizeParams);
  1986. }
  1987. //---------------------------------------------------------------------------
  1988. //---------------------------------------------------------------------------
  1989. __fastcall TManagementScript::TManagementScript(TStoredSessionList * StoredSessions,
  1990. bool LimitedOutput) :
  1991. TScript(LimitedOutput)
  1992. {
  1993. DebugAssert(StoredSessions != NULL);
  1994. FOnInput = NULL;
  1995. FOnTerminalPromptUser = NULL;
  1996. FOnShowExtendedException = NULL;
  1997. FOnTerminalQueryUser = NULL;
  1998. FStoredSessions = StoredSessions;
  1999. FTerminalList = new TTerminalList(Configuration);
  2000. FOnQueryCancel = NULL;
  2001. FContinue = true;
  2002. OnTerminalSynchronizeDirectory = TerminalSynchronizeDirectory;
  2003. FCommands->Register(L"exit", SCRIPT_EXIT_DESC, SCRIPT_EXIT_HELP, &ExitProc, 0, 0, false);
  2004. FCommands->Register(L"bye", 0, SCRIPT_EXIT_HELP, &ExitProc, 0, 0, false);
  2005. FCommands->Register(L"open", SCRIPT_OPEN_DESC, SCRIPT_OPEN_HELP11, &OpenProc, 0, -1, true);
  2006. FCommands->Register(L"close", SCRIPT_CLOSE_DESC, SCRIPT_CLOSE_HELP, &CloseProc, 0, 1, false);
  2007. FCommands->Register(L"session", SCRIPT_SESSION_DESC, SCRIPT_SESSION_HELP, &SessionProc, 0, 1, false);
  2008. FCommands->Register(L"lpwd", SCRIPT_LPWD_DESC, SCRIPT_LPWD_HELP, &LPwdProc, 0, 0, false);
  2009. FCommands->Register(L"lcd", SCRIPT_LCD_DESC, SCRIPT_LCD_HELP, &LCdProc, 1, 1, false);
  2010. FCommands->Register(L"lls", SCRIPT_LLS_DESC, SCRIPT_LLS_HELP2, &LLsProc, 0, 1, false);
  2011. }
  2012. //---------------------------------------------------------------------------
  2013. __fastcall TManagementScript::~TManagementScript()
  2014. {
  2015. while (FTerminalList->Count > 0)
  2016. {
  2017. FreeTerminal(FTerminalList->Terminals[0]);
  2018. }
  2019. delete FTerminalList;
  2020. }
  2021. //---------------------------------------------------------------------------
  2022. void __fastcall TManagementScript::FreeTerminal(TTerminal * ATerminal)
  2023. {
  2024. TSessionData * Data = StoredSessions->FindSame(ATerminal->SessionData);
  2025. if (Data != NULL)
  2026. {
  2027. ATerminal->SessionData->RemoteDirectory = ATerminal->CurrentDirectory;
  2028. bool Changed = false;
  2029. if (ATerminal->SessionData->UpdateDirectories)
  2030. {
  2031. Data->RemoteDirectory = ATerminal->SessionData->RemoteDirectory;
  2032. Changed = true;
  2033. }
  2034. if (Changed)
  2035. {
  2036. // only modified, implicit
  2037. StoredSessions->Save(false, false);
  2038. }
  2039. }
  2040. FTerminalList->FreeTerminal(ATerminal);
  2041. }
  2042. //---------------------------------------------------------------------------
  2043. void __fastcall TManagementScript::Input(const UnicodeString Prompt,
  2044. UnicodeString & Str, bool AllowEmpty)
  2045. {
  2046. do
  2047. {
  2048. Str = L"";
  2049. if (FOnInput != NULL)
  2050. {
  2051. FOnInput(this, Prompt, Str);
  2052. }
  2053. else
  2054. {
  2055. Abort();
  2056. }
  2057. }
  2058. while (Str.Trim().IsEmpty() && !AllowEmpty);
  2059. }
  2060. //---------------------------------------------------------------------------
  2061. void __fastcall TManagementScript::PrintProgress(bool First, const UnicodeString Str)
  2062. {
  2063. if (FOnPrintProgress != NULL)
  2064. {
  2065. FOnPrintProgress(this, First, Str);
  2066. }
  2067. }
  2068. //---------------------------------------------------------------------------
  2069. void __fastcall TManagementScript::ResetTransfer()
  2070. {
  2071. TScript::ResetTransfer();
  2072. FLastProgressFile = EmptyStr;
  2073. FLastProgressTime = 0;
  2074. FLastProgressEventTime = 0;
  2075. FLastProgressEventDoneFileName = EmptyStr;
  2076. FLastProgressOverallDone = false;
  2077. FLastProgressMessage = EmptyStr;
  2078. }
  2079. //---------------------------------------------------------------------------
  2080. bool __fastcall TManagementScript::QueryCancel()
  2081. {
  2082. bool Result = false;
  2083. if (OnQueryCancel != NULL)
  2084. {
  2085. OnQueryCancel(this, Result);
  2086. }
  2087. return Result;
  2088. }
  2089. //---------------------------------------------------------------------------
  2090. void __fastcall TManagementScript::TerminalInformation(
  2091. TTerminal * ATerminal, const UnicodeString & Str, bool DebugUsedArg(Status), int Phase, const UnicodeString & DebugUsedArg(Additional))
  2092. {
  2093. DebugAssert(ATerminal != NULL);
  2094. if ((Phase < 0) && (ATerminal->Status == ssOpening))
  2095. {
  2096. PrintLine(Str, false, ATerminal);
  2097. }
  2098. }
  2099. //---------------------------------------------------------------------------
  2100. void __fastcall TManagementScript::TerminalPromptUser(TTerminal * ATerminal,
  2101. TPromptKind Kind, UnicodeString Name, UnicodeString Instructions, TStrings * Prompts,
  2102. TStrings * Results, bool & Result, void * Arg)
  2103. {
  2104. // When authentication using stored password fails,
  2105. // do not ask user for another password.
  2106. if ((!ATerminal->StoredCredentialsTried ||
  2107. !IsAuthenticationPrompt(Kind) ||
  2108. (Prompts->Count == 0)) && // allow instructions-only prompts
  2109. (OnTerminalPromptUser != NULL))
  2110. {
  2111. OnTerminalPromptUser(ATerminal, Kind, Name, Instructions, Prompts, Results, Result, Arg);
  2112. }
  2113. }
  2114. //---------------------------------------------------------------------------
  2115. bool __fastcall TManagementScript::Synchronizing()
  2116. {
  2117. return (FKeepingUpToDate || (FSynchronizeMode >= 0));
  2118. }
  2119. //---------------------------------------------------------------------------
  2120. void __fastcall TManagementScript::ShowPendingProgress()
  2121. {
  2122. if (!FSynchronizeIntro.IsEmpty())
  2123. {
  2124. if (Synchronizing())
  2125. {
  2126. PrintLine(FSynchronizeIntro);
  2127. }
  2128. FSynchronizeIntro = L"";
  2129. }
  2130. }
  2131. //---------------------------------------------------------------------------
  2132. void __fastcall TManagementScript::TerminalOperationProgress(
  2133. TFileOperationProgressType & ProgressData)
  2134. {
  2135. if (ProgressData.IsTransfer())
  2136. {
  2137. if (ProgressData.InProgress && ProgressData.FileInProgress &&
  2138. !ProgressData.FileName.IsEmpty())
  2139. {
  2140. bool DoPrint = false;
  2141. bool First = false;
  2142. UnicodeString ProgressFileName = ProgressData.FileName;
  2143. if (ProgressData.Side == osLocal)
  2144. {
  2145. ProgressFileName = ExcludeTrailingBackslash(ProgressFileName);
  2146. }
  2147. else
  2148. {
  2149. ProgressFileName = UnixExcludeTrailingBackslash(ProgressFileName);
  2150. }
  2151. if (ProgressFileName != FLastProgressFile)
  2152. {
  2153. First = true;
  2154. DoPrint = true;
  2155. ShowPendingProgress();
  2156. }
  2157. time_t Time = time(NULL);
  2158. if ((OnProgress != NULL) && WantsProgress)
  2159. {
  2160. int OverallProgress = ProgressData.OverallProgress();
  2161. bool OverallDone = (OverallProgress == 100);
  2162. if (DoPrint ||
  2163. (FLastProgressEventTime != Time) ||
  2164. (ProgressData.IsTransferDone() && (FLastProgressEventDoneFileName != ProgressData.FullFileName)) ||
  2165. (OverallDone && !FLastProgressOverallDone))
  2166. {
  2167. FLastProgressEventTime = Time;
  2168. // When transferring a growing file, we would report the progress constantly
  2169. FLastProgressEventDoneFileName = ProgressData.IsTransferDone() ? ProgressData.FullFileName : EmptyStr;
  2170. FLastProgressOverallDone = OverallDone;
  2171. TScriptProgress Progress;
  2172. Progress.Operation = ProgressData.Operation;
  2173. Progress.Side = ProgressData.Side;
  2174. Progress.FileName = ProgressData.FullFileName;
  2175. Progress.Directory = ProgressData.Directory;
  2176. Progress.OverallProgress = OverallProgress;
  2177. Progress.FileProgress = ProgressData.TransferProgress();
  2178. Progress.CPS = ProgressData.CPS();
  2179. Progress.Cancel = false;
  2180. OnProgress(this, Progress);
  2181. if (Progress.Cancel)
  2182. {
  2183. ProgressData.SetCancel(csCancel);
  2184. }
  2185. }
  2186. }
  2187. if (!DoPrint && ((FLastProgressTime != Time) || ProgressData.IsTransferDone()))
  2188. {
  2189. DoPrint = true;
  2190. }
  2191. if (DoPrint)
  2192. {
  2193. UnicodeString FileName;
  2194. if (FLimitedOutput)
  2195. {
  2196. bool Unix = (ProgressData.Side == osRemote);
  2197. FileName = MinimizeName(ProgressFileName, Configuration->ScriptProgressFileNameLimit, Unix);
  2198. }
  2199. else
  2200. {
  2201. FileName = ProgressFileName;
  2202. }
  2203. UnicodeString TransferredSizeStr;
  2204. if (ProgressData.TransferredSize < 1024)
  2205. {
  2206. TransferredSizeStr = FORMAT("%d B", (static_cast<int>(ProgressData.TransferredSize)));
  2207. }
  2208. else
  2209. {
  2210. TransferredSizeStr = FORMAT("%d KB", (static_cast<int>(ProgressData.TransferredSize / 1024)));
  2211. }
  2212. UnicodeString ProgressMessage = FORMAT(L"%-*s | %14s | %6.1f KB/s | %-6.6s | %3d%%",
  2213. (Configuration->ScriptProgressFileNameLimit, FileName,
  2214. TransferredSizeStr,
  2215. static_cast<float>(ProgressData.CPS()) / 1024,
  2216. ProgressData.AsciiTransfer ? L"ascii" : L"binary",
  2217. ProgressData.TransferProgress()));
  2218. if (FLastProgressMessage != ProgressMessage)
  2219. {
  2220. FLastProgressTime = Time;
  2221. PrintProgress(First, ProgressMessage);
  2222. FLastProgressMessage = ProgressMessage;
  2223. FLastProgressFile = ProgressFileName;
  2224. }
  2225. }
  2226. }
  2227. else
  2228. {
  2229. FLastProgressFile = L"";
  2230. }
  2231. }
  2232. if (QueryCancel())
  2233. {
  2234. ProgressData.SetCancel(csCancel);
  2235. }
  2236. }
  2237. //---------------------------------------------------------------------------
  2238. void __fastcall TManagementScript::TerminalOperationFinished(
  2239. TFileOperation Operation, TOperationSide /*Side*/,
  2240. bool /*Temp*/, const UnicodeString & FileName, Boolean Success,
  2241. TOnceDoneOperation & /*OnceDoneOperation*/)
  2242. {
  2243. if (Success &&
  2244. (Operation != foCalculateSize) && (Operation != foCalculateChecksum) &&
  2245. !TFileOperationProgressType::IsTransferOperation(Operation))
  2246. {
  2247. ShowPendingProgress();
  2248. // For FKeepingUpToDate we should send events to synchronize controller eventually.
  2249. if (Synchronizing() && (Operation == foDelete))
  2250. {
  2251. // Note that this is duplicated with "keep up to date" log.
  2252. PrintLine(FMTLOAD(SCRIPT_SYNCHRONIZE_DELETED, (FileName)));
  2253. }
  2254. else
  2255. {
  2256. PrintLine(FileName);
  2257. }
  2258. }
  2259. }
  2260. //---------------------------------------------------------------------------
  2261. void __fastcall TManagementScript::TerminalSynchronizeDirectory(
  2262. const UnicodeString & LocalDirectory, const UnicodeString & RemoteDirectory,
  2263. bool & Continue, bool Collect, const TSynchronizeOptions *)
  2264. {
  2265. int SynchronizeMode = FSynchronizeMode;
  2266. if (FKeepingUpToDate)
  2267. {
  2268. SynchronizeMode = TTerminal::smRemote;
  2269. }
  2270. UnicodeString Arrow;
  2271. switch (SynchronizeMode)
  2272. {
  2273. case TTerminal::smRemote:
  2274. Arrow = L"=>";
  2275. break;
  2276. case TTerminal::smLocal:
  2277. Arrow = L"<=";
  2278. break;
  2279. case TTerminal::smBoth:
  2280. Arrow = L"<=>";
  2281. break;
  2282. }
  2283. UnicodeString Progress = FMTLOAD(SCRIPT_SYNCHRONIZE, (ExcludeTrailingBackslash(LocalDirectory),
  2284. Arrow, UnixExcludeTrailingBackslash(RemoteDirectory)));
  2285. if (Collect)
  2286. {
  2287. PrintProgress(false, Progress);
  2288. }
  2289. else
  2290. {
  2291. FSynchronizeIntro = Progress;
  2292. }
  2293. if (QueryCancel())
  2294. {
  2295. Continue = false;
  2296. }
  2297. }
  2298. //---------------------------------------------------------------------------
  2299. void __fastcall TManagementScript::TerminalInitializeLog(TObject * Sender)
  2300. {
  2301. TTerminal * ATerminal = dynamic_cast<TTerminal *>(Sender);
  2302. if (DebugAlwaysTrue(ATerminal != NULL))
  2303. {
  2304. LogPendingLines(ATerminal);
  2305. }
  2306. }
  2307. //---------------------------------------------------------------------------
  2308. TTerminal * __fastcall TManagementScript::FindSession(const UnicodeString Index)
  2309. {
  2310. int i = StrToIntDef(Index, -1);
  2311. if ((i <= 0) || (i > FTerminalList->Count))
  2312. {
  2313. throw Exception(FMTLOAD(SCRIPT_SESSION_INDEX_INVALID, (Index)));
  2314. }
  2315. else
  2316. {
  2317. return FTerminalList->Terminals[i - 1];
  2318. }
  2319. }
  2320. //---------------------------------------------------------------------------
  2321. void __fastcall TManagementScript::PrintActiveSession()
  2322. {
  2323. DebugAssert(FTerminal != NULL);
  2324. PrintLine(FMTLOAD(SCRIPT_ACTIVE_SESSION,
  2325. (FTerminalList->IndexOf(FTerminal) + 1, FTerminal->SessionData->SessionName)));
  2326. }
  2327. //---------------------------------------------------------------------------
  2328. bool __fastcall TManagementScript::HandleExtendedException(Exception * E,
  2329. TTerminal * ATerminal)
  2330. {
  2331. bool Result = TScript::HandleExtendedException(E, ATerminal);
  2332. if (ATerminal == NULL)
  2333. {
  2334. ATerminal = FTerminal;
  2335. }
  2336. if ((ATerminal != NULL) && (ATerminal == FTerminal) && (dynamic_cast<EFatal*>(E) != NULL))
  2337. {
  2338. try
  2339. {
  2340. DoClose(ATerminal);
  2341. }
  2342. catch(...)
  2343. {
  2344. // ignore disconnect errors
  2345. }
  2346. }
  2347. return Result;
  2348. }
  2349. //---------------------------------------------------------------------------
  2350. void __fastcall TManagementScript::MaskPasswordInCommandLine(UnicodeString & Command, bool Recurse)
  2351. {
  2352. UnicodeString Url;
  2353. UnicodeString MaskedParamsPre;
  2354. UnicodeString MaskedParamsPost;
  2355. UnicodeString Param;
  2356. UnicodeString RawParam;
  2357. UnicodeString Separator;
  2358. UnicodeString Separator2;
  2359. UnicodeString OptionWithParameters;
  2360. bool AnyMaskedParam = false;
  2361. TOptions Options;
  2362. UnicodeString ACommand = Command;
  2363. bool SubCommands = false;
  2364. while (CutToken(ACommand, Param, &RawParam, &Separator2))
  2365. {
  2366. Options.Add(Param);
  2367. // "Param 1" is the "winscp.exe" or "open"
  2368. if ((Options.ParamCount == 2) && Url.IsEmpty() && !SubCommands)
  2369. {
  2370. Url = Param;
  2371. }
  2372. else
  2373. {
  2374. UnicodeString & MaskedParams = Url.IsEmpty() ? MaskedParamsPre : MaskedParamsPost;
  2375. UnicodeString Switch, Value;
  2376. wchar_t SwitchMark;
  2377. if (Options.WasSwitchAdded(Switch, Value, SwitchMark))
  2378. {
  2379. OptionWithParameters = L"";
  2380. if (TSessionData::IsSensitiveOption(Switch, Value))
  2381. {
  2382. // We should use something like TProgramParams::FormatSwitch here
  2383. RawParam = FORMAT(L"%s%s=%s", (SwitchMark, Switch, PasswordMask));
  2384. AnyMaskedParam = true;
  2385. }
  2386. else if (TSessionData::IsOptionWithParameters(Switch))
  2387. {
  2388. OptionWithParameters = Switch;
  2389. }
  2390. SubCommands = SameText(Switch, COMMAND_SWITCH);
  2391. }
  2392. else
  2393. {
  2394. if (!OptionWithParameters.IsEmpty())
  2395. {
  2396. if (TSessionData::MaskPasswordInOptionParameter(OptionWithParameters, Param))
  2397. {
  2398. RawParam = Param;
  2399. AnyMaskedParam = true;
  2400. }
  2401. }
  2402. if (Recurse && SubCommands)
  2403. {
  2404. UnicodeString Cmd2 = Param;
  2405. UnicodeString Command2;
  2406. if (CutToken(Cmd2, Command2))
  2407. {
  2408. UnicodeString MaskedParam = MaskPasswordInCommand(Param, Command2);
  2409. if (MaskedParam != Param)
  2410. {
  2411. RawParam = AddQuotes(EscapeParam(MaskedParam));
  2412. AnyMaskedParam = true;
  2413. }
  2414. }
  2415. }
  2416. }
  2417. // Separator is empty on the first loop, but so is the MaskedParams
  2418. AddToList(MaskedParams, RawParam, Separator);
  2419. }
  2420. Separator = Separator2;
  2421. }
  2422. if (!Url.IsEmpty() || AnyMaskedParam)
  2423. {
  2424. UnicodeString MaskedUrl;
  2425. if (!Url.IsEmpty())
  2426. {
  2427. bool DefaultsOnly;
  2428. std::unique_ptr<TSessionData> Data(
  2429. StoredSessions->ParseUrl(Url, &Options, DefaultsOnly, NULL, NULL, &MaskedUrl));
  2430. }
  2431. if ((Url != MaskedUrl) || AnyMaskedParam)
  2432. {
  2433. Command = MaskedParamsPre;
  2434. // AddToList is noop, when respective component is empty
  2435. AddToList(Command, AddQuotes(MaskedUrl), L" ");
  2436. AddToList(Command, MaskedParamsPost, L" ");
  2437. }
  2438. }
  2439. }
  2440. //---------------------------------------------------------------------------
  2441. UnicodeString __fastcall TManagementScript::MaskPasswordInCommand(const UnicodeString & FullCommand,
  2442. const UnicodeString & Command)
  2443. {
  2444. UnicodeString Result = FullCommand;
  2445. if (SameText(FCommands->ResolveCommand(Command), L"open") &&
  2446. !Configuration->LogSensitive)
  2447. {
  2448. MaskPasswordInCommandLine(Result, false);
  2449. }
  2450. return Result;
  2451. }
  2452. //---------------------------------------------------------------------------
  2453. UnicodeString __fastcall TManagementScript::GetLogCmd(const UnicodeString & FullCommand,
  2454. const UnicodeString & Command, const UnicodeString & Params)
  2455. {
  2456. UnicodeString Result = MaskPasswordInCommand(FullCommand, Command);
  2457. return TScript::GetLogCmd(Result, Command, Params);
  2458. }
  2459. //---------------------------------------------------------------------------
  2460. void __fastcall TManagementScript::Connect(const UnicodeString Session,
  2461. TOptions * Options, bool CheckParams)
  2462. {
  2463. try
  2464. {
  2465. bool DefaultsOnly;
  2466. TSessionData * Data;
  2467. if (Options->FindSwitch(L"filezilla"))
  2468. {
  2469. UnicodeString Error;
  2470. std::unique_ptr<TStoredSessionList> FilezillaSessionList(
  2471. Configuration->SelectFilezillaSessionsForImport(StoredSessions, Error));
  2472. if (!Error.IsEmpty())
  2473. {
  2474. throw Exception(Error);
  2475. }
  2476. Data = dynamic_cast<TSessionData *>(FilezillaSessionList->FindByName(Session));
  2477. if (Data == NULL)
  2478. {
  2479. throw Exception(FMTLOAD(FILEZILLA_SITE_NOT_EXIST, (Session)));
  2480. }
  2481. else
  2482. {
  2483. Data = Data->Clone();
  2484. }
  2485. }
  2486. else
  2487. {
  2488. if (FStoredSessions->IsFolder(Session) ||
  2489. FStoredSessions->IsWorkspace(Session))
  2490. {
  2491. throw Exception(LoadStr(CANNOT_OPEN_SESSION_FOLDER));
  2492. }
  2493. Data = FStoredSessions->ParseUrl(Session, Options, DefaultsOnly);
  2494. }
  2495. try
  2496. {
  2497. if (CheckParams)
  2498. {
  2499. if (Options->ParamCount > 1)
  2500. {
  2501. throw Exception(FMTLOAD(SCRIPT_TOO_MANY_PARAMS, (L"open")));
  2502. }
  2503. TScriptCommands::CheckParams(Options, false);
  2504. }
  2505. if (!Session.IsEmpty() && !Data->Name.IsEmpty() && (Batch != TScript::BatchOff) && !Interactive)
  2506. {
  2507. std::unique_ptr<TSessionData> DataWithFingerprint(Data->Clone());
  2508. DataWithFingerprint->LookupLastFingerprint();
  2509. DataWithFingerprint->MaskPasswords();
  2510. PrintLine(LoadStr(SCRIPT_SITE_WARNING));
  2511. PrintLine(L"open " + DataWithFingerprint->GenerateOpenCommandArgs(false));
  2512. }
  2513. DebugAssert(Data != NULL);
  2514. if (!Data->CanLogin || DefaultsOnly)
  2515. {
  2516. if (Data->HostName.IsEmpty())
  2517. {
  2518. UnicodeString Value;
  2519. Input(LoadStr(SCRIPT_HOST_PROMPT), Value, false);
  2520. Data->HostName = Value;
  2521. }
  2522. DebugAssert(Data->CanLogin);
  2523. }
  2524. bool WasLogActions = Configuration->LogActions;
  2525. TTerminal * ATerminal = FTerminalList->NewTerminal(Data);
  2526. DebugAssert(FLoggingTerminal == NULL);
  2527. FLoggingTerminal = ATerminal;
  2528. try
  2529. {
  2530. try
  2531. {
  2532. ATerminal->AutoReadDirectory = false;
  2533. ATerminal->OnInformation = TerminalInformation;
  2534. ATerminal->OnPromptUser = TerminalPromptUser;
  2535. ATerminal->OnShowExtendedException = OnShowExtendedException;
  2536. ATerminal->OnQueryUser = OnTerminalQueryUser;
  2537. ATerminal->OnProgress = TerminalOperationProgress;
  2538. ATerminal->OnFinished = TerminalOperationFinished;
  2539. ATerminal->OnInitializeLog = TerminalInitializeLog;
  2540. ConnectTerminal(ATerminal);
  2541. }
  2542. catch(Exception & E)
  2543. {
  2544. // fatal error, most probably caused by XML logging failure (as it has been turned off),
  2545. // and XML log is required => abort
  2546. if ((dynamic_cast<EFatal *>(&E) != NULL) &&
  2547. WasLogActions && !Configuration->LogActions &&
  2548. Configuration->LogActionsRequired)
  2549. {
  2550. FContinue = false;
  2551. }
  2552. // make sure errors (mainly fatal ones) are associated
  2553. // with this terminal, not the last active one
  2554. bool Handled = HandleExtendedException(&E, ATerminal);
  2555. FTerminalList->FreeTerminal(ATerminal);
  2556. ATerminal = NULL;
  2557. if (!Handled)
  2558. {
  2559. throw;
  2560. }
  2561. }
  2562. }
  2563. __finally
  2564. {
  2565. FLoggingTerminal = NULL;
  2566. }
  2567. if (ATerminal != NULL)
  2568. {
  2569. FTerminal = ATerminal;
  2570. if (!Data->LocalDirectory.IsEmpty())
  2571. {
  2572. try
  2573. {
  2574. DoChangeLocalDirectory(Data->LocalDirectoryExpanded);
  2575. }
  2576. catch(Exception & E)
  2577. {
  2578. if (!HandleExtendedException(&E))
  2579. {
  2580. throw;
  2581. }
  2582. }
  2583. }
  2584. PrintActiveSession();
  2585. }
  2586. }
  2587. __finally
  2588. {
  2589. delete Data;
  2590. }
  2591. }
  2592. catch(Exception & E)
  2593. {
  2594. if (!HandleExtendedException(&E))
  2595. {
  2596. throw;
  2597. }
  2598. }
  2599. }
  2600. //---------------------------------------------------------------------------
  2601. void __fastcall TManagementScript::DoClose(TTerminal * ATerminal)
  2602. {
  2603. int Index = FTerminalList->IndexOf(ATerminal);
  2604. DebugAssert(Index >= 0);
  2605. bool WasActiveTerminal = (FTerminal == ATerminal);
  2606. try
  2607. {
  2608. if (ATerminal->Active)
  2609. {
  2610. ATerminal->Close();
  2611. }
  2612. UnicodeString SessionName = ATerminal->SessionData->SessionName;
  2613. FreeTerminal(ATerminal);
  2614. if (WasActiveTerminal)
  2615. {
  2616. FTerminal = NULL;
  2617. }
  2618. PrintLine(FMTLOAD(SCRIPT_SESSION_CLOSED, (SessionName)));
  2619. }
  2620. __finally
  2621. {
  2622. if (WasActiveTerminal)
  2623. {
  2624. if (FTerminalList->Count > 0)
  2625. {
  2626. if (Index < FTerminalList->Count)
  2627. {
  2628. FTerminal = FTerminalList->Terminals[Index];
  2629. }
  2630. else
  2631. {
  2632. FTerminal = FTerminalList->Terminals[0];
  2633. }
  2634. PrintActiveSession();
  2635. }
  2636. else
  2637. {
  2638. PrintLine(LoadStr(SCRIPT_NO_SESSION));
  2639. }
  2640. }
  2641. }
  2642. }
  2643. //---------------------------------------------------------------------------
  2644. void __fastcall TManagementScript::DoChangeLocalDirectory(UnicodeString Directory)
  2645. {
  2646. if (!SetCurrentDir(ApiPath(Directory)))
  2647. {
  2648. throw EOSExtException(FMTLOAD(CHANGE_DIR_ERROR, (Directory)));
  2649. }
  2650. }
  2651. //---------------------------------------------------------------------------
  2652. void __fastcall TManagementScript::ExitProc(TScriptProcParams * /*Parameters*/)
  2653. {
  2654. FContinue = false;
  2655. }
  2656. //---------------------------------------------------------------------------
  2657. void __fastcall TManagementScript::OpenProc(TScriptProcParams * Parameters)
  2658. {
  2659. Connect(Parameters->ParamCount > 0 ? Parameters->Param[1] : UnicodeString(),
  2660. Parameters, true);
  2661. }
  2662. //---------------------------------------------------------------------------
  2663. void __fastcall TManagementScript::CloseProc(TScriptProcParams * Parameters)
  2664. {
  2665. CheckSession();
  2666. TTerminal * ATerminal;
  2667. if (Parameters->ParamCount == 0)
  2668. {
  2669. ATerminal = FTerminal;
  2670. }
  2671. else
  2672. {
  2673. ATerminal = FindSession(Parameters->Param[1]);
  2674. }
  2675. DoClose(ATerminal);
  2676. }
  2677. //---------------------------------------------------------------------------
  2678. void __fastcall TManagementScript::SessionProc(TScriptProcParams * Parameters)
  2679. {
  2680. CheckSession();
  2681. if (Parameters->ParamCount == 0)
  2682. {
  2683. for (int i = 0; i < FTerminalList->Count; i++)
  2684. {
  2685. PrintLine(FORMAT(L"%3d %s",
  2686. (i + 1, FTerminalList->Terminals[i]->SessionData->SessionName)));
  2687. }
  2688. PrintActiveSession();
  2689. }
  2690. else
  2691. {
  2692. FTerminal = FindSession(Parameters->Param[1]);
  2693. PrintActiveSession();
  2694. }
  2695. }
  2696. //---------------------------------------------------------------------------
  2697. void __fastcall TManagementScript::LPwdProc(TScriptProcParams * /*Parameters*/)
  2698. {
  2699. PrintLine(GetCurrentDir());
  2700. }
  2701. //---------------------------------------------------------------------------
  2702. void __fastcall TManagementScript::LCdProc(TScriptProcParams * Parameters)
  2703. {
  2704. DebugAssert(Parameters->ParamCount == 1);
  2705. DoChangeLocalDirectory(Parameters->Param[1]);
  2706. PrintLine(GetCurrentDir());
  2707. }
  2708. //---------------------------------------------------------------------------
  2709. void __fastcall TManagementScript::LLsProc(TScriptProcParams * Parameters)
  2710. {
  2711. UnicodeString Directory;
  2712. UnicodeString Mask;
  2713. if (Parameters->ParamCount > 0)
  2714. {
  2715. Directory = Parameters->Param[1];
  2716. Mask = ExtractFileName(Directory);
  2717. if (TFileMasks::IsMask(Mask))
  2718. {
  2719. Directory = ExtractFilePath(Directory);
  2720. }
  2721. else
  2722. {
  2723. Mask = L"";
  2724. }
  2725. }
  2726. if (Directory.IsEmpty())
  2727. {
  2728. Directory = GetCurrentDir();
  2729. }
  2730. if (Mask.IsEmpty())
  2731. {
  2732. Mask = L"*.*";
  2733. }
  2734. TSearchRecOwned SearchRec;
  2735. int FindAttrs = faReadOnly | faHidden | faSysFile | faDirectory | faArchive;
  2736. if (FindFirstUnchecked(IncludeTrailingBackslash(Directory) + Mask, FindAttrs, SearchRec) != 0)
  2737. {
  2738. NoMatch(Mask, ListingSysErrorMessage());
  2739. }
  2740. else
  2741. {
  2742. UnicodeString TimeFormat = FixedLenDateTimeFormat(FormatSettings.ShortTimeFormat);
  2743. UnicodeString DateFormat = FixedLenDateTimeFormat(FormatSettings.ShortDateFormat);
  2744. int DateLen = 0;
  2745. int TimeLen = 0;
  2746. bool First = true;
  2747. do
  2748. {
  2749. if (SearchRec.Name != L".")
  2750. {
  2751. TDateTime DateTime = SearchRec.GetLastWriteTime();
  2752. UnicodeString TimeStr = FormatDateTime(TimeFormat, DateTime);
  2753. UnicodeString DateStr = FormatDateTime(DateFormat, DateTime);
  2754. if (First)
  2755. {
  2756. if (TimeLen < TimeStr.Length())
  2757. {
  2758. TimeLen = TimeStr.Length();
  2759. }
  2760. if (DateLen < DateStr.Length())
  2761. {
  2762. DateLen = DateStr.Length();
  2763. }
  2764. First = false;
  2765. }
  2766. UnicodeString SizeStr;
  2767. if (SearchRec.IsDirectory())
  2768. {
  2769. SizeStr = L"<DIR>";
  2770. }
  2771. else
  2772. {
  2773. SizeStr = FORMAT(L"%14.0n", (double(SearchRec.Size)));
  2774. }
  2775. PrintLine(FORMAT(L"%-*s %-*s %-14s %s", (
  2776. DateLen, DateStr, TimeLen, TimeStr, SizeStr, SearchRec.Name)));
  2777. }
  2778. }
  2779. while (FindNextChecked(SearchRec) == 0);
  2780. }
  2781. }
  2782. //---------------------------------------------------------------------------
  2783. void __fastcall TManagementScript::ReflectSettings()
  2784. {
  2785. for (int i = 0; i < FTerminalList->Count; i++)
  2786. {
  2787. FTerminalList->Terminals[i]->ReflectSettings();
  2788. }
  2789. }
  2790. //---------------------------------------------------------------------------