Script.cpp 89 KB

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