Script.cpp 92 KB

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