Script.cpp 86 KB

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