Script.cpp 88 KB

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