Script.cpp 77 KB

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