Script.cpp 87 KB

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