Script.cpp 71 KB

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