Script.cpp 93 KB

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