Script.cpp 78 KB

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