Script.cpp 93 KB

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