Script.cpp 79 KB

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