Script.cpp 84 KB

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