Script.cpp 93 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076
  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;
  1717. if (Local)
  1718. {
  1719. Path = IncludeTrailingBackslash(FileInfo.Directory) + FileInfo.FileName;
  1720. }
  1721. else
  1722. {
  1723. Path = UnixIncludeTrailingBackslash(FileInfo.Directory) + FileInfo.FileName;
  1724. }
  1725. if (SameText(RootDirectory, Path.SubString(1, RootDirectory.Length())))
  1726. {
  1727. Path[1] = L'.';
  1728. Path.Delete(2, RootDirectory.Length() - 2);
  1729. }
  1730. UnicodeString Result;
  1731. if (Item->IsDirectory)
  1732. {
  1733. if (Local)
  1734. {
  1735. Result = IncludeTrailingBackslash(Path);
  1736. }
  1737. else
  1738. {
  1739. Result = UnixIncludeTrailingBackslash(Path);
  1740. }
  1741. }
  1742. else
  1743. {
  1744. UnicodeString SizeStr = IntToStr(FileInfo.Size);
  1745. UnicodeString ModificationStr =
  1746. ::ModificationStr(FileInfo.Modification, FileInfo.ModificationFmt);
  1747. Result = FORMAT("%s [%s, %s]", (Path, SizeStr, ModificationStr));
  1748. }
  1749. return Result;
  1750. }
  1751. //---------------------------------------------------------------------------
  1752. void __fastcall TScript::SynchronizePreview(
  1753. UnicodeString LocalDirectory, UnicodeString RemoteDirectory,
  1754. TSynchronizeChecklist * Checklist)
  1755. {
  1756. LocalDirectory = IncludeTrailingBackslash(LocalDirectory);
  1757. RemoteDirectory = UnixIncludeTrailingBackslash(RemoteDirectory);
  1758. int Index = 0;
  1759. const TSynchronizeChecklist::TItem * Item;
  1760. while (Checklist->GetNextChecked(Index, Item))
  1761. {
  1762. TDifferenceSessionAction Action(FTerminal->ActionLog, Item);
  1763. UnicodeString Message;
  1764. UnicodeString LocalRecord = SynchronizeFileRecord(LocalDirectory, Item, true);
  1765. UnicodeString RemoteRecord = SynchronizeFileRecord(RemoteDirectory, Item, false);
  1766. switch (Item->Action)
  1767. {
  1768. case TSynchronizeChecklist::saUploadNew:
  1769. Message =
  1770. FMTLOAD(SCRIPT_SYNC_UPLOAD_NEW, (LocalRecord));
  1771. break;
  1772. case TSynchronizeChecklist::saDownloadNew:
  1773. Message =
  1774. FMTLOAD(SCRIPT_SYNC_DOWNLOAD_NEW, (RemoteRecord));
  1775. break;
  1776. case TSynchronizeChecklist::saUploadUpdate:
  1777. Message =
  1778. FMTLOAD(SCRIPT_SYNC_UPLOAD_UPDATE,
  1779. (LocalRecord, RemoteRecord));
  1780. break;
  1781. case TSynchronizeChecklist::saDownloadUpdate:
  1782. Message =
  1783. FMTLOAD(SCRIPT_SYNC_DOWNLOAD_UPDATE,
  1784. (RemoteRecord, LocalRecord));
  1785. break;
  1786. case TSynchronizeChecklist::saDeleteRemote:
  1787. Message =
  1788. FMTLOAD(SCRIPT_SYNC_DELETE_REMOTE, (RemoteRecord));
  1789. break;
  1790. case TSynchronizeChecklist::saDeleteLocal:
  1791. Message =
  1792. FMTLOAD(SCRIPT_SYNC_DELETE_LOCAL, (LocalRecord));
  1793. break;
  1794. default:
  1795. DebugFail();
  1796. }
  1797. PrintLine(Message);
  1798. }
  1799. }
  1800. //---------------------------------------------------------------------------
  1801. void __fastcall TScript::SynchronizeProc(TScriptProcParams * Parameters)
  1802. {
  1803. CheckSession();
  1804. ResetTransfer();
  1805. static const wchar_t * ModeNames[] = { L"remote", L"local", L"both" };
  1806. CheckDefaultCopyParam();
  1807. TCopyParamType CopyParam = FCopyParam;
  1808. CopyParamParams(CopyParam, Parameters);
  1809. RequireParams(Parameters, 1);
  1810. if (Parameters->ParamCount > 3)
  1811. {
  1812. throw Exception(FMTLOAD(SCRIPT_TOO_MANY_PARAMS, (L"synchronize")));
  1813. }
  1814. UnicodeString ModeName = Parameters->Param[1];
  1815. DebugAssert(FSynchronizeMode < 0);
  1816. FSynchronizeMode = TScriptCommands::FindCommand(ModeNames, LENOF(ModeNames), ModeName);
  1817. try
  1818. {
  1819. if (FSynchronizeMode < 0)
  1820. {
  1821. throw Exception(FMTLOAD(SCRIPT_OPTION_UNKNOWN, (ModeName)));
  1822. }
  1823. UnicodeString LocalDirectory;
  1824. UnicodeString RemoteDirectory;
  1825. SynchronizeDirectories(Parameters, LocalDirectory, RemoteDirectory, 2);
  1826. CopyParam.IncludeFileMask.SetRoots(LocalDirectory, RemoteDirectory);
  1827. CheckDefaultSynchronizeParams();
  1828. int SynchronizeParams = FSynchronizeParams | TTerminal::spNoConfirmation;
  1829. UnicodeString Value;
  1830. if (Parameters->FindSwitch(L"delete"))
  1831. {
  1832. SynchronizeParams |= TTerminal::spDelete;
  1833. }
  1834. if (Parameters->FindSwitch(L"mirror") &&
  1835. (FSynchronizeMode != TTerminal::smBoth))
  1836. {
  1837. SynchronizeParams |= TTerminal::spMirror;
  1838. }
  1839. if (Parameters->FindSwitch(L"criteria", Value))
  1840. {
  1841. enum { None, Either, EitherBoth };
  1842. static const wchar_t * CriteriaNames[] = { L"none", L"either", L"both" };
  1843. int Criteria = TScriptCommands::FindCommand(CriteriaNames, LENOF(CriteriaNames), Value);
  1844. if (Criteria >= 0)
  1845. {
  1846. switch (Criteria)
  1847. {
  1848. case None:
  1849. SynchronizeParams |= TTerminal::spNotByTime;
  1850. SynchronizeParams &= ~TTerminal::spBySize;
  1851. break;
  1852. case Either:
  1853. case EitherBoth:
  1854. SynchronizeParams &= ~TTerminal::spNotByTime;
  1855. SynchronizeParams |= TTerminal::spBySize;
  1856. break;
  1857. }
  1858. }
  1859. else
  1860. {
  1861. int Params = TTerminal::spNotByTime;
  1862. while ((Params >= 0) && !Value.IsEmpty())
  1863. {
  1864. UnicodeString Token = CutToChar(Value, L',', true);
  1865. enum { Time, Size, Checksum };
  1866. static const wchar_t * CriteriaNames[] = { L"time", L"size", L"checksum" };
  1867. int Criteria = TScriptCommands::FindCommand(CriteriaNames, LENOF(CriteriaNames), Token);
  1868. switch (Criteria)
  1869. {
  1870. case Time:
  1871. Params &= ~TTerminal::spNotByTime;
  1872. break;
  1873. case Size:
  1874. Params |= TTerminal::spBySize;
  1875. break;
  1876. case Checksum:
  1877. Params |= TTerminal::spByChecksum;
  1878. break;
  1879. default:
  1880. Params = -1;
  1881. break;
  1882. }
  1883. }
  1884. if (Params >= 0)
  1885. {
  1886. SynchronizeParams &= ~(TTerminal::spNotByTime | TTerminal::spBySize | TTerminal::spByChecksum);
  1887. SynchronizeParams |= Params;
  1888. }
  1889. }
  1890. }
  1891. bool Preview = Parameters->FindSwitch(L"preview");
  1892. // enforce rules
  1893. if (FSynchronizeMode == TTerminal::smBoth)
  1894. {
  1895. SynchronizeParams &= ~(TTerminal::spNotByTime | TTerminal::spBySize | TTerminal::spByChecksum);
  1896. }
  1897. CheckParams(Parameters);
  1898. bool Continue = true;
  1899. if (FLAGSET(SynchronizeParams, TTerminal::spByChecksum) &&
  1900. !FTerminal->IsCapable[fcCalculatingChecksum])
  1901. {
  1902. if (!FTerminal->IsCapable[fcSecondaryShell])
  1903. {
  1904. NotSupported();
  1905. }
  1906. else
  1907. {
  1908. Continue = EnsureCommandSessionFallback(fcCalculatingChecksum, NULL);
  1909. }
  1910. }
  1911. if (Continue)
  1912. {
  1913. PrintLine(LoadStr(SCRIPT_SYNCHRONIZE_COLLECTING));
  1914. TSynchronizeChecklist * Checklist =
  1915. FTerminal->SynchronizeCollect(LocalDirectory, RemoteDirectory,
  1916. static_cast<TTerminal::TSynchronizeMode>(FSynchronizeMode),
  1917. &CopyParam, SynchronizeParams, OnTerminalSynchronizeDirectory, NULL);
  1918. try
  1919. {
  1920. int Index = 0;
  1921. const TSynchronizeChecklist::TItem * DummyItem;
  1922. if (Checklist->GetNextChecked(Index, DummyItem))
  1923. {
  1924. if (Preview)
  1925. {
  1926. PrintLine(LoadStr(SCRIPT_SYNCHRONIZE_CHECKLIST));
  1927. SynchronizePreview(LocalDirectory, RemoteDirectory, Checklist);
  1928. }
  1929. else
  1930. {
  1931. PrintLine(LoadStr(SCRIPT_SYNCHRONIZE_SYNCHRONIZING));
  1932. FTerminal->SynchronizeApply(
  1933. Checklist, &CopyParam, SynchronizeParams, OnTerminalSynchronizeDirectory, NULL, NULL, NULL, NULL);
  1934. }
  1935. }
  1936. else
  1937. {
  1938. NoMatch(LoadStr(SCRIPT_SYNCHRONIZE_NODIFFERENCE));
  1939. }
  1940. }
  1941. __finally
  1942. {
  1943. delete Checklist;
  1944. }
  1945. }
  1946. }
  1947. __finally
  1948. {
  1949. FSynchronizeMode = -1;
  1950. }
  1951. }
  1952. //---------------------------------------------------------------------------
  1953. void __fastcall TScript::Synchronize(const UnicodeString LocalDirectory,
  1954. const UnicodeString RemoteDirectory, const TCopyParamType & CopyParam,
  1955. int SynchronizeParams, TSynchronizeChecklist ** Checklist)
  1956. {
  1957. try
  1958. {
  1959. FKeepingUpToDate = true;
  1960. TSynchronizeChecklist * AChecklist =
  1961. FTerminal->SynchronizeCollect(LocalDirectory, RemoteDirectory, TTerminal::smRemote,
  1962. &CopyParam, SynchronizeParams, NULL, NULL);
  1963. try
  1964. {
  1965. if (AChecklist->Count > 0)
  1966. {
  1967. FTerminal->SynchronizeApply(
  1968. AChecklist, &CopyParam, SynchronizeParams, OnTerminalSynchronizeDirectory, NULL, NULL, NULL, NULL);
  1969. }
  1970. }
  1971. __finally
  1972. {
  1973. if (Checklist == NULL)
  1974. {
  1975. delete AChecklist;
  1976. }
  1977. else
  1978. {
  1979. *Checklist = AChecklist;
  1980. }
  1981. }
  1982. // to break line after the last transfer (if any);
  1983. Print(L"");
  1984. FKeepingUpToDate = false;
  1985. }
  1986. catch(Exception & E)
  1987. {
  1988. FKeepingUpToDate = false;
  1989. HandleExtendedException(&E);
  1990. throw;
  1991. }
  1992. }
  1993. //---------------------------------------------------------------------------
  1994. void __fastcall TScript::KeepUpToDateProc(TScriptProcParams * Parameters)
  1995. {
  1996. if (OnSynchronizeStartStop == NULL)
  1997. {
  1998. Abort();
  1999. }
  2000. CheckSession();
  2001. ResetTransfer();
  2002. CheckDefaultCopyParam();
  2003. TCopyParamType CopyParam = FCopyParam;
  2004. CopyParamParams(CopyParam, Parameters);
  2005. UnicodeString LocalDirectory;
  2006. UnicodeString RemoteDirectory;
  2007. SynchronizeDirectories(Parameters, LocalDirectory, RemoteDirectory, 1);
  2008. CheckDefaultSynchronizeParams();
  2009. int SynchronizeParams = FSynchronizeParams | TTerminal::spNoConfirmation |
  2010. TTerminal::spNoRecurse | TTerminal::spUseCache | TTerminal::spDelayProgress |
  2011. TTerminal::spSubDirs;
  2012. if (Parameters->FindSwitch(L"delete"))
  2013. {
  2014. SynchronizeParams |= TTerminal::spDelete;
  2015. }
  2016. CheckParams(Parameters);
  2017. PrintLine(LoadStr(SCRIPT_KEEPING_UP_TO_DATE));
  2018. OnSynchronizeStartStop(this, LocalDirectory, RemoteDirectory, CopyParam, SynchronizeParams);
  2019. }
  2020. //---------------------------------------------------------------------------
  2021. //---------------------------------------------------------------------------
  2022. __fastcall TManagementScript::TManagementScript(TStoredSessionList * StoredSessions,
  2023. bool LimitedOutput) :
  2024. TScript(LimitedOutput)
  2025. {
  2026. DebugAssert(StoredSessions != NULL);
  2027. FOnInput = NULL;
  2028. FOnTerminalPromptUser = NULL;
  2029. FOnShowExtendedException = NULL;
  2030. FOnTerminalQueryUser = NULL;
  2031. FStoredSessions = StoredSessions;
  2032. FTerminalList = new TTerminalList(Configuration);
  2033. FOnQueryCancel = NULL;
  2034. FContinue = true;
  2035. OnTerminalSynchronizeDirectory = TerminalSynchronizeDirectory;
  2036. FCommands->Register(EXIT_COMMAND, SCRIPT_EXIT_DESC, SCRIPT_EXIT_HELP, &ExitProc, 0, 0, false);
  2037. FCommands->Register(L"bye", 0, SCRIPT_EXIT_HELP, &ExitProc, 0, 0, false);
  2038. FCommands->Register(L"open", SCRIPT_OPEN_DESC, SCRIPT_OPEN_HELP11, &OpenProc, 0, -1, true);
  2039. FCommands->Register(L"close", SCRIPT_CLOSE_DESC, SCRIPT_CLOSE_HELP, &CloseProc, 0, 1, false);
  2040. FCommands->Register(L"session", SCRIPT_SESSION_DESC, SCRIPT_SESSION_HELP, &SessionProc, 0, 1, false);
  2041. FCommands->Register(L"lpwd", SCRIPT_LPWD_DESC, SCRIPT_LPWD_HELP, &LPwdProc, 0, 0, false);
  2042. FCommands->Register(L"lcd", SCRIPT_LCD_DESC, SCRIPT_LCD_HELP, &LCdProc, 1, 1, false);
  2043. FCommands->Register(L"lls", SCRIPT_LLS_DESC, SCRIPT_LLS_HELP2, &LLsProc, 0, 1, false);
  2044. }
  2045. //---------------------------------------------------------------------------
  2046. __fastcall TManagementScript::~TManagementScript()
  2047. {
  2048. while (FTerminalList->Count > 0)
  2049. {
  2050. FreeTerminal(FTerminalList->Terminals[0]);
  2051. }
  2052. delete FTerminalList;
  2053. }
  2054. //---------------------------------------------------------------------------
  2055. void __fastcall TManagementScript::FreeTerminal(TTerminal * ATerminal)
  2056. {
  2057. TSessionData * Data = StoredSessions->FindSame(ATerminal->SessionData);
  2058. if (Data != NULL)
  2059. {
  2060. ATerminal->SessionData->RemoteDirectory = ATerminal->CurrentDirectory;
  2061. bool Changed = false;
  2062. if (ATerminal->SessionData->UpdateDirectories)
  2063. {
  2064. Data->RemoteDirectory = ATerminal->SessionData->RemoteDirectory;
  2065. Changed = true;
  2066. }
  2067. if (Changed)
  2068. {
  2069. // only modified, implicit
  2070. StoredSessions->Save(false, false);
  2071. }
  2072. }
  2073. FTerminalList->FreeTerminal(ATerminal);
  2074. }
  2075. //---------------------------------------------------------------------------
  2076. void __fastcall TManagementScript::Input(const UnicodeString Prompt,
  2077. UnicodeString & Str, bool AllowEmpty)
  2078. {
  2079. do
  2080. {
  2081. Str = L"";
  2082. if (FOnInput != NULL)
  2083. {
  2084. FOnInput(this, Prompt, Str);
  2085. }
  2086. else
  2087. {
  2088. Abort();
  2089. }
  2090. }
  2091. while (Str.Trim().IsEmpty() && !AllowEmpty);
  2092. }
  2093. //---------------------------------------------------------------------------
  2094. void __fastcall TManagementScript::PrintProgress(bool First, const UnicodeString Str)
  2095. {
  2096. if (FOnPrintProgress != NULL)
  2097. {
  2098. FOnPrintProgress(this, First, Str);
  2099. }
  2100. }
  2101. //---------------------------------------------------------------------------
  2102. void __fastcall TManagementScript::ResetTransfer()
  2103. {
  2104. TScript::ResetTransfer();
  2105. FLastProgressFile = EmptyStr;
  2106. FLastProgressTime = 0;
  2107. FLastProgressEventTime = 0;
  2108. FLastProgressEventDoneFileName = EmptyStr;
  2109. FLastProgressOverallDone = false;
  2110. FLastProgressMessage = EmptyStr;
  2111. }
  2112. //---------------------------------------------------------------------------
  2113. bool __fastcall TManagementScript::QueryCancel()
  2114. {
  2115. bool Result = false;
  2116. if (OnQueryCancel != NULL)
  2117. {
  2118. OnQueryCancel(this, Result);
  2119. }
  2120. return Result;
  2121. }
  2122. //---------------------------------------------------------------------------
  2123. void __fastcall TManagementScript::TerminalInformation(
  2124. TTerminal * ATerminal, const UnicodeString & Str, int Phase, const UnicodeString & DebugUsedArg(Additional))
  2125. {
  2126. DebugAssert(ATerminal != NULL);
  2127. if ((Phase < 0) && ((ATerminal->Status == ssOpening) || FPrintInformation))
  2128. {
  2129. PrintLine(Str, false, ATerminal);
  2130. }
  2131. }
  2132. //---------------------------------------------------------------------------
  2133. void __fastcall TManagementScript::TerminalPromptUser(TTerminal * ATerminal,
  2134. TPromptKind Kind, UnicodeString Name, UnicodeString Instructions, TStrings * Prompts,
  2135. TStrings * Results, bool & Result, void * Arg)
  2136. {
  2137. // When authentication using stored password fails,
  2138. // do not ask user for another password.
  2139. if ((!ATerminal->StoredCredentialsTried ||
  2140. !IsAuthenticationPrompt(Kind) ||
  2141. (Prompts->Count == 0)) && // allow instructions-only prompts
  2142. (OnTerminalPromptUser != NULL))
  2143. {
  2144. OnTerminalPromptUser(ATerminal, Kind, Name, Instructions, Prompts, Results, Result, Arg);
  2145. }
  2146. }
  2147. //---------------------------------------------------------------------------
  2148. bool __fastcall TManagementScript::Synchronizing()
  2149. {
  2150. return (FKeepingUpToDate || (FSynchronizeMode >= 0));
  2151. }
  2152. //---------------------------------------------------------------------------
  2153. void __fastcall TManagementScript::ShowPendingProgress()
  2154. {
  2155. if (!FSynchronizeIntro.IsEmpty())
  2156. {
  2157. if (Synchronizing())
  2158. {
  2159. PrintLine(FSynchronizeIntro);
  2160. }
  2161. FSynchronizeIntro = L"";
  2162. }
  2163. }
  2164. //---------------------------------------------------------------------------
  2165. void __fastcall TManagementScript::TerminalOperationProgress(
  2166. TFileOperationProgressType & ProgressData)
  2167. {
  2168. if (ProgressData.IsTransfer())
  2169. {
  2170. if (ProgressData.InProgress && ProgressData.FileInProgress &&
  2171. !ProgressData.FileName.IsEmpty())
  2172. {
  2173. bool DoPrint = false;
  2174. bool First = false;
  2175. UnicodeString ProgressFileName = ProgressData.FileName;
  2176. if (ProgressData.Side == osLocal)
  2177. {
  2178. ProgressFileName = ExcludeTrailingBackslash(ProgressFileName);
  2179. }
  2180. else
  2181. {
  2182. ProgressFileName = UnixExcludeTrailingBackslash(ProgressFileName);
  2183. }
  2184. if (ProgressFileName != FLastProgressFile)
  2185. {
  2186. First = true;
  2187. DoPrint = true;
  2188. ShowPendingProgress();
  2189. }
  2190. time_t Time = time(NULL);
  2191. if ((OnProgress != NULL) && WantsProgress)
  2192. {
  2193. int OverallProgress = ProgressData.OverallProgress();
  2194. bool OverallDone = (OverallProgress == 100);
  2195. if (DoPrint ||
  2196. (FLastProgressEventTime != Time) ||
  2197. (ProgressData.IsTransferDone() && (FLastProgressEventDoneFileName != ProgressData.FullFileName)) ||
  2198. (OverallDone && !FLastProgressOverallDone))
  2199. {
  2200. FLastProgressEventTime = Time;
  2201. // When transferring a growing file, we would report the progress constantly
  2202. FLastProgressEventDoneFileName = ProgressData.IsTransferDone() ? ProgressData.FullFileName : EmptyStr;
  2203. FLastProgressOverallDone = OverallDone;
  2204. TScriptProgress Progress;
  2205. Progress.Operation = ProgressData.Operation;
  2206. Progress.Side = ProgressData.Side;
  2207. Progress.FileName = ProgressData.FullFileName;
  2208. Progress.Directory = ProgressData.Directory;
  2209. Progress.OverallProgress = OverallProgress;
  2210. Progress.FileProgress = ProgressData.TransferProgress();
  2211. Progress.CPS = ProgressData.CPS();
  2212. Progress.Cancel = false;
  2213. OnProgress(this, Progress);
  2214. if (Progress.Cancel)
  2215. {
  2216. ProgressData.SetCancel(csCancel);
  2217. }
  2218. }
  2219. }
  2220. if (!DoPrint && ((FLastProgressTime != Time) || ProgressData.IsTransferDone()))
  2221. {
  2222. DoPrint = true;
  2223. }
  2224. if (DoPrint)
  2225. {
  2226. UnicodeString FileName;
  2227. if (FLimitedOutput)
  2228. {
  2229. bool Unix = (ProgressData.Side == osRemote);
  2230. FileName = MinimizeName(ProgressFileName, Configuration->ScriptProgressFileNameLimit, Unix);
  2231. }
  2232. else
  2233. {
  2234. FileName = ProgressFileName;
  2235. }
  2236. UnicodeString TransferredSizeStr;
  2237. if (ProgressData.TransferredSize < 1024)
  2238. {
  2239. TransferredSizeStr = FORMAT("%d B", (static_cast<int>(ProgressData.TransferredSize)));
  2240. }
  2241. else
  2242. {
  2243. TransferredSizeStr = FORMAT("%d KB", (static_cast<int>(ProgressData.TransferredSize / 1024)));
  2244. }
  2245. UnicodeString ProgressMessage = FORMAT(L"%-*s | %14s | %6.1f KB/s | %-6.6s | %3d%%",
  2246. (Configuration->ScriptProgressFileNameLimit, FileName,
  2247. TransferredSizeStr,
  2248. static_cast<long double>(ProgressData.CPS()) / 1024,
  2249. ProgressData.AsciiTransfer ? L"ascii" : L"binary",
  2250. ProgressData.TransferProgress()));
  2251. if (FLastProgressMessage != ProgressMessage)
  2252. {
  2253. FLastProgressTime = Time;
  2254. PrintProgress(First, ProgressMessage);
  2255. FLastProgressMessage = ProgressMessage;
  2256. FLastProgressFile = ProgressFileName;
  2257. }
  2258. }
  2259. }
  2260. else
  2261. {
  2262. FLastProgressFile = L"";
  2263. }
  2264. }
  2265. if (QueryCancel())
  2266. {
  2267. ProgressData.SetCancel(csCancel);
  2268. }
  2269. }
  2270. //---------------------------------------------------------------------------
  2271. void __fastcall TManagementScript::TerminalOperationFinished(
  2272. TFileOperation Operation, TOperationSide /*Side*/,
  2273. bool /*Temp*/, const UnicodeString & FileName, bool Success, bool NotCancelled,
  2274. TOnceDoneOperation & /*OnceDoneOperation*/)
  2275. {
  2276. if (Success && NotCancelled &&
  2277. (Operation != foCalculateSize) && (Operation != foCalculateChecksum) &&
  2278. !TFileOperationProgressType::IsTransferOperation(Operation))
  2279. {
  2280. ShowPendingProgress();
  2281. // For FKeepingUpToDate we should send events to synchronize controller eventually.
  2282. if (Synchronizing() && (Operation == foDelete))
  2283. {
  2284. // Note that this is duplicated with "keep up to date" log.
  2285. PrintLine(FMTLOAD(SCRIPT_SYNCHRONIZE_DELETED, (FileName)));
  2286. }
  2287. else
  2288. {
  2289. PrintLine(FileName);
  2290. }
  2291. }
  2292. }
  2293. //---------------------------------------------------------------------------
  2294. void __fastcall TManagementScript::TerminalSynchronizeDirectory(
  2295. const UnicodeString & LocalDirectory, const UnicodeString & RemoteDirectory,
  2296. bool & Continue, bool Collect, const TSynchronizeOptions *)
  2297. {
  2298. int SynchronizeMode = FSynchronizeMode;
  2299. if (FKeepingUpToDate)
  2300. {
  2301. SynchronizeMode = TTerminal::smRemote;
  2302. }
  2303. UnicodeString Arrow;
  2304. switch (SynchronizeMode)
  2305. {
  2306. case TTerminal::smRemote:
  2307. Arrow = L"=>";
  2308. break;
  2309. case TTerminal::smLocal:
  2310. Arrow = L"<=";
  2311. break;
  2312. case TTerminal::smBoth:
  2313. Arrow = L"<=>";
  2314. break;
  2315. }
  2316. UnicodeString Progress = FMTLOAD(SCRIPT_SYNCHRONIZE, (ExcludeTrailingBackslash(LocalDirectory),
  2317. Arrow, UnixExcludeTrailingBackslash(RemoteDirectory)));
  2318. if (Collect)
  2319. {
  2320. PrintProgress(false, Progress);
  2321. }
  2322. else
  2323. {
  2324. FSynchronizeIntro = Progress;
  2325. }
  2326. if (QueryCancel())
  2327. {
  2328. Continue = false;
  2329. }
  2330. }
  2331. //---------------------------------------------------------------------------
  2332. void __fastcall TManagementScript::TerminalInitializeLog(TObject * Sender)
  2333. {
  2334. TTerminal * ATerminal = dynamic_cast<TTerminal *>(Sender);
  2335. if (DebugAlwaysTrue(ATerminal != NULL))
  2336. {
  2337. LogPendingLines(ATerminal);
  2338. }
  2339. }
  2340. //---------------------------------------------------------------------------
  2341. TTerminal * __fastcall TManagementScript::FindSession(const UnicodeString Index)
  2342. {
  2343. int i = StrToIntDef(Index, -1);
  2344. if ((i <= 0) || (i > FTerminalList->Count))
  2345. {
  2346. throw Exception(FMTLOAD(SCRIPT_SESSION_INDEX_INVALID, (Index)));
  2347. }
  2348. else
  2349. {
  2350. return FTerminalList->Terminals[i - 1];
  2351. }
  2352. }
  2353. //---------------------------------------------------------------------------
  2354. void __fastcall TManagementScript::PrintActiveSession()
  2355. {
  2356. DebugAssert(FTerminal != NULL);
  2357. PrintLine(FMTLOAD(SCRIPT_ACTIVE_SESSION,
  2358. (FTerminalList->IndexOf(FTerminal) + 1, FTerminal->SessionData->SessionName)));
  2359. }
  2360. //---------------------------------------------------------------------------
  2361. bool __fastcall TManagementScript::HandleExtendedException(Exception * E,
  2362. TTerminal * ATerminal)
  2363. {
  2364. bool Result = TScript::HandleExtendedException(E, ATerminal);
  2365. if (ATerminal == NULL)
  2366. {
  2367. ATerminal = FTerminal;
  2368. }
  2369. if ((ATerminal != NULL) && (ATerminal == FTerminal) && (dynamic_cast<EFatal*>(E) != NULL))
  2370. {
  2371. try
  2372. {
  2373. DoClose(ATerminal);
  2374. }
  2375. catch(...)
  2376. {
  2377. // ignore disconnect errors
  2378. }
  2379. }
  2380. return Result;
  2381. }
  2382. //---------------------------------------------------------------------------
  2383. void __fastcall TManagementScript::MaskPasswordInCommandLine(UnicodeString & Command, bool Recurse)
  2384. {
  2385. UnicodeString Url;
  2386. UnicodeString MaskedParamsPre;
  2387. UnicodeString MaskedParamsPost;
  2388. UnicodeString Param;
  2389. UnicodeString RawParam;
  2390. UnicodeString Separator;
  2391. UnicodeString Separator2;
  2392. UnicodeString OptionWithParameters;
  2393. bool AnyMaskedParam = false;
  2394. TOptions Options;
  2395. UnicodeString ACommand = Command;
  2396. bool SubCommands = false;
  2397. while (CutToken(ACommand, Param, &RawParam, &Separator2))
  2398. {
  2399. Options.Add(Param);
  2400. // "Param 1" is the "winscp.exe" or "open"
  2401. if ((Options.ParamCount == 2) && Url.IsEmpty() && !SubCommands)
  2402. {
  2403. Url = Param;
  2404. }
  2405. else
  2406. {
  2407. UnicodeString & MaskedParams = Url.IsEmpty() ? MaskedParamsPre : MaskedParamsPost;
  2408. UnicodeString Switch, Value;
  2409. wchar_t SwitchMark;
  2410. if (Options.WasSwitchAdded(Switch, Value, SwitchMark))
  2411. {
  2412. OptionWithParameters = L"";
  2413. if (TSessionData::IsSensitiveOption(Switch, Value))
  2414. {
  2415. // We should use something like TProgramParams::FormatSwitch here
  2416. RawParam = FORMAT(L"%s%s=%s", (SwitchMark, Switch, PasswordMask));
  2417. AnyMaskedParam = true;
  2418. }
  2419. else if (TSessionData::IsOptionWithParameters(Switch))
  2420. {
  2421. OptionWithParameters = Switch;
  2422. }
  2423. SubCommands = SameText(Switch, COMMAND_SWITCH);
  2424. }
  2425. else
  2426. {
  2427. if (!OptionWithParameters.IsEmpty())
  2428. {
  2429. if (TSessionData::MaskPasswordInOptionParameter(OptionWithParameters, Param))
  2430. {
  2431. RawParam = Param;
  2432. AnyMaskedParam = true;
  2433. }
  2434. }
  2435. if (Recurse && SubCommands)
  2436. {
  2437. UnicodeString Cmd2 = Param;
  2438. UnicodeString Command2;
  2439. if (CutToken(Cmd2, Command2))
  2440. {
  2441. UnicodeString MaskedParam = MaskPasswordInCommand(Param, Command2);
  2442. if (MaskedParam != Param)
  2443. {
  2444. RawParam = AddQuotes(EscapeParam(MaskedParam));
  2445. AnyMaskedParam = true;
  2446. }
  2447. }
  2448. }
  2449. }
  2450. // Separator is empty on the first loop, but so is the MaskedParams
  2451. AddToList(MaskedParams, RawParam, Separator);
  2452. }
  2453. Separator = Separator2;
  2454. }
  2455. if (!Url.IsEmpty() || AnyMaskedParam)
  2456. {
  2457. UnicodeString MaskedUrl;
  2458. if (!Url.IsEmpty())
  2459. {
  2460. bool DefaultsOnly;
  2461. std::unique_ptr<TSessionData> Data(
  2462. StoredSessions->ParseUrl(Url, &Options, DefaultsOnly, NULL, NULL, &MaskedUrl));
  2463. }
  2464. if ((Url != MaskedUrl) || AnyMaskedParam)
  2465. {
  2466. Command = MaskedParamsPre;
  2467. // AddToList is noop, when respective component is empty
  2468. AddToList(Command, AddQuotes(MaskedUrl), L" ");
  2469. AddToList(Command, MaskedParamsPost, L" ");
  2470. }
  2471. }
  2472. }
  2473. //---------------------------------------------------------------------------
  2474. UnicodeString __fastcall TManagementScript::MaskPasswordInCommand(const UnicodeString & FullCommand,
  2475. const UnicodeString & Command)
  2476. {
  2477. UnicodeString Result = FullCommand;
  2478. if (SameText(FCommands->ResolveCommand(Command), L"open") &&
  2479. !Configuration->LogSensitive)
  2480. {
  2481. MaskPasswordInCommandLine(Result, false);
  2482. }
  2483. return Result;
  2484. }
  2485. //---------------------------------------------------------------------------
  2486. UnicodeString __fastcall TManagementScript::GetLogCmd(const UnicodeString & FullCommand,
  2487. const UnicodeString & Command, const UnicodeString & Params)
  2488. {
  2489. UnicodeString Result = MaskPasswordInCommand(FullCommand, Command);
  2490. return TScript::GetLogCmd(Result, Command, Params);
  2491. }
  2492. //---------------------------------------------------------------------------
  2493. void __fastcall TManagementScript::Connect(const UnicodeString Session,
  2494. TOptions * Options, bool CheckParams)
  2495. {
  2496. try
  2497. {
  2498. bool DefaultsOnly;
  2499. TSessionData * Data;
  2500. if (Options->FindSwitch(L"filezilla"))
  2501. {
  2502. UnicodeString Error;
  2503. std::unique_ptr<TStoredSessionList> FilezillaSessionList(
  2504. Configuration->SelectFilezillaSessionsForImport(StoredSessions, Error));
  2505. if (!Error.IsEmpty())
  2506. {
  2507. throw Exception(Error);
  2508. }
  2509. Data = dynamic_cast<TSessionData *>(FilezillaSessionList->FindByName(Session));
  2510. if (Data == NULL)
  2511. {
  2512. throw Exception(FMTLOAD(FILEZILLA_SITE_NOT_EXIST, (Session)));
  2513. }
  2514. else
  2515. {
  2516. Data = Data->Clone();
  2517. }
  2518. DefaultsOnly = false;
  2519. }
  2520. else
  2521. {
  2522. if (FStoredSessions->IsFolder(Session) ||
  2523. FStoredSessions->IsWorkspace(Session))
  2524. {
  2525. throw Exception(LoadStr(CANNOT_OPEN_SESSION_FOLDER));
  2526. }
  2527. Data = FStoredSessions->ParseUrl(Session, Options, DefaultsOnly);
  2528. }
  2529. try
  2530. {
  2531. if (CheckParams)
  2532. {
  2533. if (Options->ParamCount > 1)
  2534. {
  2535. throw Exception(FMTLOAD(SCRIPT_TOO_MANY_PARAMS, (L"open")));
  2536. }
  2537. TScriptCommands::CheckParams(Options, false);
  2538. }
  2539. if (!Session.IsEmpty() && (Data->Source != ::ssNone) && (Batch != TScript::BatchOff) && UsageWarnings)
  2540. {
  2541. std::unique_ptr<TSessionData> DataWithFingerprint(Data->Clone());
  2542. DataWithFingerprint->LookupLastFingerprint();
  2543. DataWithFingerprint->MaskPasswords();
  2544. PrintLine(LoadStr(SCRIPT_SITE_WARNING));
  2545. PrintLine(L"open " + DataWithFingerprint->GenerateOpenCommandArgs(false));
  2546. }
  2547. DebugAssert(Data != NULL);
  2548. if (!Data->CanLogin || DefaultsOnly)
  2549. {
  2550. if (Data->HostName.IsEmpty())
  2551. {
  2552. UnicodeString Value;
  2553. Input(LoadStr(SCRIPT_HOST_PROMPT), Value, false);
  2554. Data->HostName = Value;
  2555. }
  2556. DebugAssert(Data->CanLogin);
  2557. }
  2558. bool WasLogActions = Configuration->LogActions;
  2559. TTerminal * ATerminal = FTerminalList->NewTerminal(Data);
  2560. DebugAssert(FLoggingTerminal == NULL);
  2561. FLoggingTerminal = ATerminal;
  2562. try
  2563. {
  2564. try
  2565. {
  2566. ATerminal->AutoReadDirectory = false;
  2567. ATerminal->OnInformation = TerminalInformation;
  2568. ATerminal->OnPromptUser = TerminalPromptUser;
  2569. ATerminal->OnShowExtendedException = OnShowExtendedException;
  2570. ATerminal->OnQueryUser = OnTerminalQueryUser;
  2571. ATerminal->OnProgress = TerminalOperationProgress;
  2572. ATerminal->OnFinished = TerminalOperationFinished;
  2573. ATerminal->OnInitializeLog = TerminalInitializeLog;
  2574. ConnectTerminal(ATerminal);
  2575. }
  2576. catch(Exception & E)
  2577. {
  2578. // fatal error, most probably caused by XML logging failure (as it has been turned off),
  2579. // and XML log is required => abort
  2580. if ((dynamic_cast<EFatal *>(&E) != NULL) &&
  2581. WasLogActions && !Configuration->LogActions &&
  2582. Configuration->LogActionsRequired)
  2583. {
  2584. FContinue = false;
  2585. }
  2586. // make sure errors (mainly fatal ones) are associated
  2587. // with this terminal, not the last active one
  2588. bool Handled = HandleExtendedException(&E, ATerminal);
  2589. FTerminalList->FreeTerminal(ATerminal);
  2590. ATerminal = NULL;
  2591. if (!Handled)
  2592. {
  2593. throw;
  2594. }
  2595. }
  2596. }
  2597. __finally
  2598. {
  2599. FLoggingTerminal = NULL;
  2600. }
  2601. if (ATerminal != NULL)
  2602. {
  2603. FTerminal = ATerminal;
  2604. if (!Data->LocalDirectory.IsEmpty())
  2605. {
  2606. try
  2607. {
  2608. DoChangeLocalDirectory(Data->LocalDirectoryExpanded);
  2609. }
  2610. catch(Exception & E)
  2611. {
  2612. if (!HandleExtendedException(&E))
  2613. {
  2614. throw;
  2615. }
  2616. }
  2617. }
  2618. PrintActiveSession();
  2619. }
  2620. }
  2621. __finally
  2622. {
  2623. delete Data;
  2624. }
  2625. }
  2626. catch(Exception & E)
  2627. {
  2628. if (!HandleExtendedException(&E))
  2629. {
  2630. throw;
  2631. }
  2632. }
  2633. }
  2634. //---------------------------------------------------------------------------
  2635. void __fastcall TManagementScript::DoClose(TTerminal * ATerminal)
  2636. {
  2637. int Index = FTerminalList->IndexOf(ATerminal);
  2638. DebugAssert(Index >= 0);
  2639. bool WasActiveTerminal = (FTerminal == ATerminal);
  2640. try
  2641. {
  2642. if (ATerminal->Active)
  2643. {
  2644. ATerminal->Close();
  2645. }
  2646. UnicodeString SessionName = ATerminal->SessionData->SessionName;
  2647. FreeTerminal(ATerminal);
  2648. if (WasActiveTerminal)
  2649. {
  2650. FTerminal = NULL;
  2651. }
  2652. PrintLine(FMTLOAD(SCRIPT_SESSION_CLOSED, (SessionName)));
  2653. }
  2654. __finally
  2655. {
  2656. if (WasActiveTerminal)
  2657. {
  2658. if (FTerminalList->Count > 0)
  2659. {
  2660. if (Index < FTerminalList->Count)
  2661. {
  2662. FTerminal = FTerminalList->Terminals[Index];
  2663. }
  2664. else
  2665. {
  2666. FTerminal = FTerminalList->Terminals[0];
  2667. }
  2668. PrintActiveSession();
  2669. }
  2670. else
  2671. {
  2672. PrintLine(LoadStr(SCRIPT_NO_SESSION));
  2673. }
  2674. }
  2675. }
  2676. }
  2677. //---------------------------------------------------------------------------
  2678. void __fastcall TManagementScript::DoChangeLocalDirectory(UnicodeString Directory)
  2679. {
  2680. if (!SetCurrentDir(ApiPath(Directory)))
  2681. {
  2682. throw EOSExtException(FMTLOAD(CHANGE_DIR_ERROR, (Directory)));
  2683. }
  2684. }
  2685. //---------------------------------------------------------------------------
  2686. void __fastcall TManagementScript::ExitProc(TScriptProcParams * /*Parameters*/)
  2687. {
  2688. FContinue = false;
  2689. }
  2690. //---------------------------------------------------------------------------
  2691. void __fastcall TManagementScript::OpenProc(TScriptProcParams * Parameters)
  2692. {
  2693. Connect(Parameters->ParamCount > 0 ? Parameters->Param[1] : UnicodeString(),
  2694. Parameters, true);
  2695. }
  2696. //---------------------------------------------------------------------------
  2697. void __fastcall TManagementScript::CloseProc(TScriptProcParams * Parameters)
  2698. {
  2699. CheckSession();
  2700. TTerminal * ATerminal;
  2701. if (Parameters->ParamCount == 0)
  2702. {
  2703. ATerminal = FTerminal;
  2704. }
  2705. else
  2706. {
  2707. ATerminal = FindSession(Parameters->Param[1]);
  2708. }
  2709. DoClose(ATerminal);
  2710. }
  2711. //---------------------------------------------------------------------------
  2712. void __fastcall TManagementScript::SessionProc(TScriptProcParams * Parameters)
  2713. {
  2714. CheckSession();
  2715. if (Parameters->ParamCount == 0)
  2716. {
  2717. for (int i = 0; i < FTerminalList->Count; i++)
  2718. {
  2719. PrintLine(FORMAT(L"%3d %s",
  2720. (i + 1, FTerminalList->Terminals[i]->SessionData->SessionName)));
  2721. }
  2722. PrintActiveSession();
  2723. }
  2724. else
  2725. {
  2726. FTerminal = FindSession(Parameters->Param[1]);
  2727. PrintActiveSession();
  2728. }
  2729. }
  2730. //---------------------------------------------------------------------------
  2731. void __fastcall TManagementScript::LPwdProc(TScriptProcParams * /*Parameters*/)
  2732. {
  2733. PrintLine(GetCurrentDir());
  2734. }
  2735. //---------------------------------------------------------------------------
  2736. void __fastcall TManagementScript::LCdProc(TScriptProcParams * Parameters)
  2737. {
  2738. DebugAssert(Parameters->ParamCount == 1);
  2739. DoChangeLocalDirectory(Parameters->Param[1]);
  2740. PrintLine(GetCurrentDir());
  2741. }
  2742. //---------------------------------------------------------------------------
  2743. void __fastcall TManagementScript::LLsProc(TScriptProcParams * Parameters)
  2744. {
  2745. UnicodeString Directory;
  2746. UnicodeString Mask;
  2747. if (Parameters->ParamCount > 0)
  2748. {
  2749. Directory = Parameters->Param[1];
  2750. Mask = ExtractFileName(Directory);
  2751. if (TFileMasks::IsMask(Mask))
  2752. {
  2753. Directory = ExtractFilePath(Directory);
  2754. }
  2755. else
  2756. {
  2757. Mask = L"";
  2758. }
  2759. }
  2760. if (Directory.IsEmpty())
  2761. {
  2762. Directory = GetCurrentDir();
  2763. }
  2764. if (Mask.IsEmpty())
  2765. {
  2766. Mask = L"*.*";
  2767. }
  2768. TSearchRecOwned SearchRec;
  2769. int FindAttrs = faReadOnly | faHidden | faSysFile | faDirectory | faArchive;
  2770. if (FindFirstUnchecked(IncludeTrailingBackslash(Directory) + Mask, FindAttrs, SearchRec) != 0)
  2771. {
  2772. NoMatch(Mask, ListingSysErrorMessage());
  2773. }
  2774. else
  2775. {
  2776. UnicodeString TimeFormat = FixedLenDateTimeFormat(FormatSettings.ShortTimeFormat);
  2777. UnicodeString DateFormat = FixedLenDateTimeFormat(FormatSettings.ShortDateFormat);
  2778. int DateLen = 0;
  2779. int TimeLen = 0;
  2780. bool First = true;
  2781. do
  2782. {
  2783. if (SearchRec.Name != L".")
  2784. {
  2785. TDateTime DateTime = SearchRec.GetLastWriteTime();
  2786. UnicodeString TimeStr = FormatDateTime(TimeFormat, DateTime);
  2787. UnicodeString DateStr = FormatDateTime(DateFormat, DateTime);
  2788. if (First)
  2789. {
  2790. if (TimeLen < TimeStr.Length())
  2791. {
  2792. TimeLen = TimeStr.Length();
  2793. }
  2794. if (DateLen < DateStr.Length())
  2795. {
  2796. DateLen = DateStr.Length();
  2797. }
  2798. First = false;
  2799. }
  2800. UnicodeString SizeStr;
  2801. if (SearchRec.IsDirectory())
  2802. {
  2803. SizeStr = L"<DIR>";
  2804. }
  2805. else
  2806. {
  2807. SizeStr = FORMAT(L"%14.0n", (static_cast<long double>(SearchRec.Size)));
  2808. }
  2809. PrintLine(FORMAT(L"%-*s %-*s %-14s %s", (
  2810. DateLen, DateStr, TimeLen, TimeStr, SizeStr, SearchRec.Name)));
  2811. }
  2812. }
  2813. while (FindNextChecked(SearchRec) == 0);
  2814. }
  2815. }
  2816. //---------------------------------------------------------------------------
  2817. void __fastcall TManagementScript::ReflectSettings()
  2818. {
  2819. for (int i = 0; i < FTerminalList->Count; i++)
  2820. {
  2821. FTerminalList->Terminals[i]->ReflectSettings();
  2822. }
  2823. }
  2824. //---------------------------------------------------------------------------