Script.cpp 91 KB

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