Script.cpp 87 KB

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