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