Script.cpp 79 KB

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