Script.cpp 91 KB

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