Script.cpp 84 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875
  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. DebugAssert(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, true);
  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_HELP8, &GetProc, 1, -1, true);
  336. FCommands->Register(L"recv", 0, SCRIPT_GET_HELP8, &GetProc, 1, -1, true);
  337. FCommands->Register(L"mget", 0, SCRIPT_GET_HELP8, &GetProc, 1, -1, true);
  338. FCommands->Register(L"put", SCRIPT_PUT_DESC, SCRIPT_PUT_HELP8, &PutProc, 1, -1, true);
  339. FCommands->Register(L"send", 0, SCRIPT_PUT_HELP8, &PutProc, 1, -1, true);
  340. FCommands->Register(L"mput", 0, SCRIPT_PUT_HELP8, &PutProc, 1, -1, true);
  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, UnicodeString 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 (SimpleUnixExcludeTrailingBackslash(FileName) != FileName)
  538. {
  539. PrintLine(LoadStr(SCRIPT_AMBIGUOUS_SLASH_IN_PATH));
  540. }
  541. if (FLAGSET(ListType, fltDirectories))
  542. {
  543. TRemoteFile * File = new TRemoteFile();
  544. File->FileName = FileName;
  545. File->Type = FILETYPE_DIRECTORY;
  546. Result->AddObject(FileName, File);
  547. }
  548. else if (FLAGSET(ListType, fltMask) && TFileMasks::IsMask(FileName))
  549. {
  550. UnicodeString FileDirectory = UnixExtractFilePath(FileName);
  551. UnicodeString Directory = FileDirectory;
  552. if (Directory.IsEmpty())
  553. {
  554. Directory = UnixIncludeTrailingBackslash(FTerminal->CurrentDirectory);
  555. }
  556. TRemoteFileList * FileList = NULL;
  557. if (FileLists != NULL)
  558. {
  559. int Index = FileLists->IndexOf(Directory);
  560. if (Index > 0)
  561. {
  562. FileList = dynamic_cast<TRemoteFileList *>(FileLists->Objects[Index]);
  563. }
  564. }
  565. if (FileList == NULL)
  566. {
  567. FileList = FTerminal->CustomReadDirectoryListing(Directory, false);
  568. if (FileLists == NULL)
  569. {
  570. FileLists = new TStringList();
  571. }
  572. FileLists->AddObject(Directory, FileList);
  573. }
  574. TFileMasks Mask;
  575. Mask.SetMask(UnixExtractFileName(FileName));
  576. bool AnyFound = false;
  577. // Can happen in "batch continue" mode
  578. if (FileList != NULL)
  579. {
  580. for (int i = 0; i < FileList->Count; i++)
  581. {
  582. TRemoteFile * File = FileList->Files[i];
  583. TFileMasks::TParams Params;
  584. Params.Size = File->Size;
  585. Params.Modification = File->Modification;
  586. if (!File->IsThisDirectory && !File->IsParentDirectory &&
  587. Mask.Matches(File->FileName, false, UnicodeString(), &Params))
  588. {
  589. Result->AddObject(FileDirectory + File->FileName,
  590. FLAGSET(ListType, fltQueryServer) ? File->Duplicate() : NULL);
  591. AnyFound = true;
  592. }
  593. }
  594. }
  595. if (!AnyFound)
  596. {
  597. NoMatch(Mask.Masks, UnicodeString());
  598. }
  599. }
  600. else
  601. {
  602. TRemoteFile * File = NULL;
  603. if (FLAGSET(ListType, fltQueryServer))
  604. {
  605. FTerminal->ExceptionOnFail = true;
  606. try
  607. {
  608. FTerminal->ReadFile(UnixExcludeTrailingBackslash(FileName), File);
  609. if (!File->HaveFullFileName)
  610. {
  611. File->FullFileName = FileName;
  612. }
  613. }
  614. __finally
  615. {
  616. FTerminal->ExceptionOnFail = false;
  617. }
  618. }
  619. Result->AddObject(FileName, File);
  620. }
  621. }
  622. }
  623. catch(...)
  624. {
  625. FreeFileList(Result);
  626. throw;
  627. }
  628. }
  629. __finally
  630. {
  631. if (FileLists != NULL)
  632. {
  633. for (int i = 0; i < FileLists->Count; i++)
  634. {
  635. delete FileLists->Objects[i];
  636. }
  637. delete FileLists;
  638. }
  639. }
  640. if (FLAGSET(ListType, fltLatest) && (Result->Count > 1))
  641. {
  642. // otherwise we do not have TRemoteFile's
  643. assert(FLAGSET(ListType, fltQueryServer));
  644. int LatestIndex = 0;
  645. for (int Index = 1; Index < Result->Count; Index++)
  646. {
  647. TRemoteFile * File = dynamic_cast<TRemoteFile *>(Result->Objects[Index]);
  648. if (dynamic_cast<TRemoteFile *>(Result->Objects[LatestIndex])->Modification < File->Modification)
  649. {
  650. LatestIndex = Index;
  651. }
  652. }
  653. TRemoteFile * File = dynamic_cast<TRemoteFile *>(Result->Objects[LatestIndex]);
  654. UnicodeString Path = Result->Strings[LatestIndex];
  655. Result->Delete(LatestIndex);
  656. FreeFiles(Result);
  657. Result->Clear();
  658. Result->AddObject(Path, File);
  659. }
  660. return Result;
  661. }
  662. //---------------------------------------------------------------------------
  663. TStrings * __fastcall TScript::CreateLocalFileList(TScriptProcParams * Parameters,
  664. int Start, int End, TFileListType ListType)
  665. {
  666. TStrings * Result = new TStringList();
  667. try
  668. {
  669. UnicodeString LatestFileName;
  670. TDateTime LatestModification; // initialized to 0
  671. for (int i = Start; i <= End; i++)
  672. {
  673. // FindFirstFile called (indirectly) below fails if path ends with slash.
  674. // (it actually won't make a difference functionally as we fall back to adding
  675. // the path as is in "else" branch, but the comment "let it fail later" won't stand)
  676. UnicodeString FileName = ExcludeTrailingBackslash(Parameters->Param[i]);
  677. if (FileName != Parameters->Param[i])
  678. {
  679. PrintLine(LoadStr(SCRIPT_AMBIGUOUS_SLASH_IN_PATH));
  680. }
  681. if (FLAGSET(ListType, fltMask))
  682. {
  683. TSearchRecChecked SearchRec;
  684. int FindAttrs = faReadOnly | faHidden | faSysFile | faDirectory | faArchive;
  685. UnicodeString Error;
  686. bool AnyFound = false;
  687. if (FindFirstUnchecked(FileName, FindAttrs, SearchRec) == 0)
  688. {
  689. UnicodeString Directory = ExtractFilePath(FileName);
  690. try
  691. {
  692. do
  693. {
  694. if ((SearchRec.Name != L".") && (SearchRec.Name != L".."))
  695. {
  696. UnicodeString FileName = Directory + SearchRec.Name;
  697. Result->Add(FileName);
  698. if (SearchRec.TimeStamp > LatestModification)
  699. {
  700. LatestFileName = FileName;
  701. LatestModification = SearchRec.TimeStamp;
  702. }
  703. AnyFound = true;
  704. }
  705. }
  706. while (FindNextChecked(SearchRec) == 0);
  707. }
  708. __finally
  709. {
  710. FindClose(SearchRec);
  711. }
  712. }
  713. else
  714. {
  715. if (FileName.LastDelimiter(L"?*") == 0)
  716. {
  717. // No match, and it is not a mask, let it fail latter.
  718. // But with -latest, we have to fail straight away
  719. // (so maybe we should fail unconditionally now,
  720. // once we need to have the code in place anyway)
  721. if (FLAGSET(ListType, fltLatest))
  722. {
  723. throw Exception(FMTLOAD(FILE_NOT_EXISTS, (FileName)));
  724. }
  725. Result->Add(FileName);
  726. AnyFound = true;
  727. }
  728. else
  729. {
  730. Error = ListingSysErrorMessage();
  731. }
  732. }
  733. if (!AnyFound)
  734. {
  735. NoMatch(ExtractFileName(FileName), Error);
  736. }
  737. }
  738. else
  739. {
  740. assert(FLAGCLEAR(ListType, fltLatest));
  741. // this branch is currently never used
  742. Result->Add(FileName);
  743. }
  744. }
  745. if (FLAGSET(ListType, fltLatest))
  746. {
  747. Result->Clear();
  748. if (!LatestFileName.IsEmpty())
  749. {
  750. Result->Add(LatestFileName);
  751. }
  752. }
  753. }
  754. catch(...)
  755. {
  756. delete Result;
  757. throw;
  758. }
  759. return Result;
  760. }
  761. //---------------------------------------------------------------------------
  762. UnicodeString __fastcall TScript::ListingSysErrorMessage()
  763. {
  764. UnicodeString Result;
  765. int LastError = GetLastError();
  766. // System error text for ERROR_FILE_NOT_FOUND is more or less redundant to ours
  767. // SCRIPT_MATCH_NO_MATCH. Also the system error does not look nice/user friendly
  768. // so avoid using it for this frequent case.
  769. if (LastError != ERROR_FILE_NOT_FOUND)
  770. {
  771. Result = SysErrorMessageForError(LastError);
  772. }
  773. return Result;
  774. }
  775. //---------------------------------------------------------------------------
  776. void __fastcall TScript::NoMatch(const UnicodeString & Mask, const UnicodeString & Error)
  777. {
  778. UnicodeString Message = FMTLOAD(SCRIPT_MATCH_NO_MATCH, (Mask));
  779. if (!Error.IsEmpty())
  780. {
  781. Message += FORMAT(L" (%s)", (Error));
  782. }
  783. if (FFailOnNoMatch)
  784. {
  785. throw Exception(Message);
  786. }
  787. else
  788. {
  789. PrintLine(Message);
  790. }
  791. }
  792. //---------------------------------------------------------------------------
  793. void __fastcall TScript::FreeFiles(TStrings * FileList)
  794. {
  795. for (int i = 0; i < FileList->Count; i++)
  796. {
  797. if (FileList->Objects[i] != NULL)
  798. {
  799. TRemoteFile * File = dynamic_cast<TRemoteFile *>(FileList->Objects[i]);
  800. delete File;
  801. }
  802. }
  803. }
  804. //---------------------------------------------------------------------------
  805. void __fastcall TScript::FreeFileList(TStrings * FileList)
  806. {
  807. FreeFiles(FileList);
  808. delete FileList;
  809. }
  810. //---------------------------------------------------------------------------
  811. void __fastcall TScript::ConnectTerminal(TTerminal * ATerminal)
  812. {
  813. ATerminal->Open();
  814. }
  815. //---------------------------------------------------------------------------
  816. void __fastcall TScript::Print(const UnicodeString Str)
  817. {
  818. if (FOnPrint != NULL)
  819. {
  820. FOnPrint(this, Str);
  821. }
  822. }
  823. //---------------------------------------------------------------------------
  824. void __fastcall TScript::PrintLine(const UnicodeString Str)
  825. {
  826. Log(llOutput, Str);
  827. Print(Str + L"\n");
  828. }
  829. //---------------------------------------------------------------------------
  830. bool __fastcall TScript::HandleExtendedException(Exception * E, TTerminal * ATerminal)
  831. {
  832. bool Result = (OnShowExtendedException != NULL);
  833. if (Result)
  834. {
  835. if (ATerminal == NULL)
  836. {
  837. ATerminal = FTerminal;
  838. }
  839. OnShowExtendedException(ATerminal, E, NULL);
  840. }
  841. return Result;
  842. }
  843. //---------------------------------------------------------------------------
  844. void __fastcall TScript::CheckSession()
  845. {
  846. if (FTerminal == NULL)
  847. {
  848. throw Exception(LoadStr(SCRIPT_NO_SESSION));
  849. }
  850. }
  851. //---------------------------------------------------------------------------
  852. void __fastcall TScript::NotSupported()
  853. {
  854. throw Exception(LoadStr(NOTSUPPORTED));
  855. }
  856. //---------------------------------------------------------------------------
  857. void __fastcall TScript::CheckMultiFilesToOne(TStrings * FileList, const UnicodeString & Target, bool Unix)
  858. {
  859. UnicodeString Name;
  860. if (Unix)
  861. {
  862. Name = UnixExtractFileName(Target);
  863. }
  864. else
  865. {
  866. Name = ExtractFileName(Target);
  867. }
  868. if (!IsFileNameMask(Name) && (FileList->Count > 1))
  869. {
  870. UnicodeString Message =
  871. RemoveEmptyLines(UnformatMessage(FormatMultiFilesToOneConfirmation(Target, Unix)));
  872. PrintLine(Message);
  873. }
  874. }
  875. //---------------------------------------------------------------------------
  876. void __fastcall TScript::CheckParams(TScriptProcParams * Parameters)
  877. {
  878. TScriptCommands::CheckParams(Parameters, false);
  879. }
  880. //---------------------------------------------------------------------------
  881. void __fastcall TScript::TransferParamParams(int & Params, TScriptProcParams * Parameters)
  882. {
  883. Params |= FLAGMASK(!FConfirm, cpNoConfirmation);
  884. if (Parameters->FindSwitch(L"delete"))
  885. {
  886. Params |= cpDelete;
  887. }
  888. if (Parameters->FindSwitch(L"resume"))
  889. {
  890. Params |= cpResume;
  891. }
  892. else if (Parameters->FindSwitch(L"append"))
  893. {
  894. Params |= cpAppend;
  895. }
  896. }
  897. //---------------------------------------------------------------------------
  898. void __fastcall TScript::CopyParamParams(TCopyParamType & CopyParam, TScriptProcParams * Parameters)
  899. {
  900. UnicodeString Value;
  901. if (!FWantsProgress)
  902. {
  903. // total size is not visualized, hence it makes no sense to calculate it
  904. CopyParam.CalculateSize = false;
  905. }
  906. if (Parameters->FindSwitch(L"nopreservetime"))
  907. {
  908. CopyParam.PreserveTime = false;
  909. CopyParam.PreserveTimeDirs = false;
  910. }
  911. if (Parameters->FindSwitch(L"preservetime", Value))
  912. {
  913. CopyParam.PreserveTime = true;
  914. if (SameText(Value, L"all"))
  915. {
  916. CopyParam.PreserveTimeDirs = true;
  917. }
  918. }
  919. if (Parameters->FindSwitch(L"nopermissions"))
  920. {
  921. CopyParam.PreserveRights = false;
  922. }
  923. if (Parameters->FindSwitch(L"permissions", Value))
  924. {
  925. CopyParam.PreserveRights = true;
  926. CopyParam.Rights.Octal = Value;
  927. }
  928. if (Parameters->FindSwitch(L"speed", Value))
  929. {
  930. int CPSLimit;
  931. if (Value.IsEmpty())
  932. {
  933. CPSLimit = 0;
  934. }
  935. else
  936. {
  937. CPSLimit = StrToInt(Value) * 1024;
  938. if (CPSLimit < 0)
  939. {
  940. CPSLimit = 0;
  941. }
  942. }
  943. CopyParam.CPSLimit = CPSLimit;
  944. }
  945. if (Parameters->FindSwitch(L"transfer", Value))
  946. {
  947. CopyParam.TransferMode = ParseTransferModeName(Value);
  948. }
  949. if (Parameters->FindSwitch(L"filemask", Value))
  950. {
  951. CopyParam.IncludeFileMask = Value;
  952. if (FIncludeFileMaskOptionUsed)
  953. {
  954. PrintLine(LoadStr(SCRIPT_FILEMASK_INCLUDE_EXCLUDE));
  955. }
  956. }
  957. if (Parameters->FindSwitch(L"resumesupport", Value))
  958. {
  959. int ToggleValue = TScriptCommands::FindCommand(ToggleNames,
  960. LENOF(ToggleNames), Value);
  961. if (ToggleValue >= 0)
  962. {
  963. switch (ToggleValue)
  964. {
  965. case Off:
  966. CopyParam.ResumeSupport = rsOff;
  967. break;
  968. case On:
  969. CopyParam.ResumeSupport = rsOn;
  970. break;
  971. default:
  972. FAIL;
  973. break;
  974. }
  975. }
  976. else
  977. {
  978. int ThresholdValue;
  979. if (!TryStrToInt(Value, ThresholdValue))
  980. {
  981. throw Exception(FMTLOAD(SCRIPT_VALUE_UNKNOWN, (L"resumesupport", Value)));
  982. }
  983. CopyParam.ResumeSupport = rsSmart;
  984. CopyParam.ResumeThreshold = ThresholdValue * 1024;
  985. }
  986. }
  987. if (Parameters->FindSwitch(L"noneweronly"))
  988. {
  989. CopyParam.NewerOnly = false;
  990. }
  991. if (Parameters->FindSwitch(L"neweronly"))
  992. {
  993. CopyParam.NewerOnly = true;
  994. }
  995. }
  996. //---------------------------------------------------------------------------
  997. void __fastcall TScript::ResetTransfer()
  998. {
  999. }
  1000. //---------------------------------------------------------------------------
  1001. bool __fastcall TScript::EnsureCommandSessionFallback(
  1002. TFSCapability Capability, TSessionAction & Action)
  1003. {
  1004. bool Result = FTerminal->IsCapable[Capability] ||
  1005. FTerminal->CommandSessionOpened;
  1006. if (!Result)
  1007. {
  1008. try
  1009. {
  1010. ConnectTerminal(FTerminal->CommandSession);
  1011. Result = true;
  1012. }
  1013. catch(Exception & E)
  1014. {
  1015. Action.Rollback(&E);
  1016. HandleExtendedException(&E, FTerminal->CommandSession);
  1017. Result = false;
  1018. }
  1019. }
  1020. return Result;
  1021. }
  1022. //---------------------------------------------------------------------------
  1023. void __fastcall TScript::HelpProc(TScriptProcParams * Parameters)
  1024. {
  1025. UnicodeString Output;
  1026. if (Parameters->ParamCount == 0)
  1027. {
  1028. UnicodeString Command;
  1029. UnicodeString Description;
  1030. int Index = 0;
  1031. while (FCommands->Enumerate(Index, &Command, &Description, NULL))
  1032. {
  1033. if (!Description.IsEmpty())
  1034. {
  1035. Output += FORMAT(L"%-8s %s\n", (Command, Description));
  1036. }
  1037. Index++;
  1038. }
  1039. }
  1040. else
  1041. {
  1042. for (int i = 1; i <= Parameters->ParamCount; i++)
  1043. {
  1044. UnicodeString Help;
  1045. if (FCommands->Info(Parameters->Param[i], NULL, &Help))
  1046. {
  1047. Output += Help;
  1048. }
  1049. else
  1050. {
  1051. throw Exception(FMTLOAD(SCRIPT_COMMAND_UNKNOWN, (Parameters->Param[i])));
  1052. }
  1053. }
  1054. }
  1055. Print(Output);
  1056. }
  1057. //---------------------------------------------------------------------------
  1058. void __fastcall TScript::CallProc(TScriptProcParams * Parameters)
  1059. {
  1060. CheckSession();
  1061. if (!FTerminal->IsCapable[fcAnyCommand] &&
  1062. !FTerminal->IsCapable[fcSecondaryShell])
  1063. {
  1064. NotSupported();
  1065. }
  1066. // this is used only to log failures to open separate shell session,
  1067. // the actual call logging is done in TTerminal::AnyCommand
  1068. TCallSessionAction Action(
  1069. FTerminal->ActionLog, Parameters->ParamsStr, FTerminal->CurrentDirectory);
  1070. if (EnsureCommandSessionFallback(fcAnyCommand, Action))
  1071. {
  1072. Action.Cancel();
  1073. FTerminal->AnyCommand(Parameters->ParamsStr, TerminalCaptureLog);
  1074. }
  1075. }
  1076. //---------------------------------------------------------------------------
  1077. void __fastcall TScript::EchoProc(TScriptProcParams * Parameters)
  1078. {
  1079. PrintLine(Parameters->ParamsStr);
  1080. }
  1081. //---------------------------------------------------------------------------
  1082. void __fastcall TScript::StatProc(TScriptProcParams * Parameters)
  1083. {
  1084. CheckSession();
  1085. UnicodeString Path = UnixExcludeTrailingBackslash(Parameters->Param[1]);
  1086. FTerminal->ExceptionOnFail = true;
  1087. TRemoteFile * File = NULL;
  1088. try
  1089. {
  1090. File = FTerminal->ReadFileListing(Path);
  1091. PrintLine(File->ListingStr);
  1092. }
  1093. __finally
  1094. {
  1095. FTerminal->ExceptionOnFail = false;
  1096. delete File;
  1097. }
  1098. }
  1099. //---------------------------------------------------------------------------
  1100. void __fastcall TScript::ChecksumProc(TScriptProcParams * Parameters)
  1101. {
  1102. CheckSession();
  1103. if (!FTerminal->IsCapable[fcCalculatingChecksum])
  1104. {
  1105. NotSupported();
  1106. }
  1107. UnicodeString Alg = Parameters->Param[1];
  1108. std::unique_ptr<TStrings> Checksums(new TStringList());
  1109. TStrings * FileList = CreateFileList(Parameters, 2, 2, fltQueryServer);
  1110. FTerminal->ExceptionOnFail = true;
  1111. try
  1112. {
  1113. if ((FileList->Count != 1) ||
  1114. NOT_NULL(dynamic_cast<TRemoteFile *>(FileList->Objects[0]))->IsDirectory)
  1115. {
  1116. throw Exception(FMTLOAD(NOT_FILE_ERROR, (FileList->Strings[0])));
  1117. }
  1118. FTerminal->CalculateFilesChecksum(Alg, FileList, Checksums.get(), NULL);
  1119. if (ALWAYS_TRUE(Checksums->Count == 1))
  1120. {
  1121. PrintLine(FORMAT(L"%s %s", (Checksums->Strings[0], FileList->Strings[0])));
  1122. }
  1123. }
  1124. __finally
  1125. {
  1126. FTerminal->ExceptionOnFail = false;
  1127. FreeFileList(FileList);
  1128. }
  1129. }
  1130. //---------------------------------------------------------------------------
  1131. void __fastcall TScript::TerminalCaptureLog(const UnicodeString & AddedLine,
  1132. TCaptureOutputType OutputType)
  1133. {
  1134. if ((OutputType == cotOutput) || (OutputType == cotError))
  1135. {
  1136. PrintLine(AddedLine);
  1137. }
  1138. }
  1139. //---------------------------------------------------------------------------
  1140. void __fastcall TScript::PwdProc(TScriptProcParams * /*Parameters*/)
  1141. {
  1142. CheckSession();
  1143. PrintLine(FTerminal->CurrentDirectory);
  1144. TCwdSessionAction Action(FTerminal->ActionLog, FTerminal->CurrentDirectory);
  1145. }
  1146. //---------------------------------------------------------------------------
  1147. void __fastcall TScript::CdProc(TScriptProcParams * Parameters)
  1148. {
  1149. CheckSession();
  1150. if (Parameters->ParamCount == 0)
  1151. {
  1152. FTerminal->HomeDirectory();
  1153. }
  1154. else
  1155. {
  1156. FTerminal->ChangeDirectory(Parameters->Param[1]);
  1157. }
  1158. PrintLine(FTerminal->CurrentDirectory);
  1159. }
  1160. //---------------------------------------------------------------------------
  1161. void __fastcall TScript::LsProc(TScriptProcParams * Parameters)
  1162. {
  1163. CheckSession();
  1164. UnicodeString Directory;
  1165. TFileMasks Mask;
  1166. bool HaveMask = false;
  1167. if (Parameters->ParamCount > 0)
  1168. {
  1169. Directory = Parameters->Param[1];
  1170. UnicodeString MaskStr = UnixExtractFileName(Directory);
  1171. HaveMask = TFileMasks::IsMask(MaskStr);
  1172. if (HaveMask)
  1173. {
  1174. Mask.SetMask(MaskStr);
  1175. Directory = UnixExtractFilePath(Directory);
  1176. }
  1177. }
  1178. if (Directory.IsEmpty())
  1179. {
  1180. Directory = FTerminal->CurrentDirectory;
  1181. }
  1182. TRemoteFileList * FileList = FTerminal->ReadDirectoryListing(Directory, Mask);
  1183. // on error user may select "skip", then we get NULL
  1184. if (FileList != NULL)
  1185. {
  1186. try
  1187. {
  1188. if (FileList->Count > 0)
  1189. {
  1190. for (int i = 0; i < FileList->Count; i++)
  1191. {
  1192. PrintLine(FileList->Files[i]->ListingStr);
  1193. }
  1194. }
  1195. else
  1196. {
  1197. if (HaveMask)
  1198. {
  1199. NoMatch(Mask.Masks, UnicodeString());
  1200. }
  1201. }
  1202. }
  1203. __finally
  1204. {
  1205. delete FileList;
  1206. }
  1207. }
  1208. }
  1209. //---------------------------------------------------------------------------
  1210. void __fastcall TScript::RmProc(TScriptProcParams * Parameters)
  1211. {
  1212. CheckSession();
  1213. TStrings * FileList = CreateFileList(
  1214. Parameters, 1, Parameters->ParamCount,
  1215. (TFileListType)(fltQueryServer | fltMask));
  1216. try
  1217. {
  1218. FTerminal->DeleteFiles(FileList);
  1219. }
  1220. __finally
  1221. {
  1222. FreeFileList(FileList);
  1223. }
  1224. }
  1225. //---------------------------------------------------------------------------
  1226. void __fastcall TScript::RmDirProc(TScriptProcParams * Parameters)
  1227. {
  1228. CheckSession();
  1229. TStrings * FileList = CreateFileList(Parameters, 1, Parameters->ParamCount, fltDirectories);
  1230. try
  1231. {
  1232. FTerminal->DeleteFiles(FileList);
  1233. }
  1234. __finally
  1235. {
  1236. FreeFileList(FileList);
  1237. }
  1238. }
  1239. //---------------------------------------------------------------------------
  1240. void __fastcall TScript::MvProc(TScriptProcParams * Parameters)
  1241. {
  1242. CheckSession();
  1243. TStrings * FileList = CreateFileList(Parameters, 1, Parameters->ParamCount - 1,
  1244. fltMask);
  1245. try
  1246. {
  1247. DebugAssert(Parameters->ParamCount >= 1);
  1248. UnicodeString Target = Parameters->Param[Parameters->ParamCount];
  1249. UnicodeString TargetDirectory = UnixExtractFilePath(Target);
  1250. UnicodeString FileMask = UnixExtractFileName(Target);
  1251. Target = UnixIncludeTrailingBackslash(TargetDirectory) + FileMask;
  1252. CheckMultiFilesToOne(FileList, Target, true);
  1253. FTerminal->MoveFiles(FileList, TargetDirectory, FileMask);
  1254. }
  1255. __finally
  1256. {
  1257. FreeFileList(FileList);
  1258. }
  1259. }
  1260. //---------------------------------------------------------------------------
  1261. void __fastcall TScript::ChModProc(TScriptProcParams * Parameters)
  1262. {
  1263. CheckSession();
  1264. if (!FTerminal->IsCapable[fcModeChanging])
  1265. {
  1266. NotSupported();
  1267. }
  1268. TStrings * FileList = CreateFileList(Parameters, 2, Parameters->ParamCount,
  1269. fltMask);
  1270. try
  1271. {
  1272. TRemoteProperties Properties;
  1273. Properties.Valid = TValidProperties() << vpRights;
  1274. Properties.Rights.Octal = Parameters->Param[1];
  1275. FTerminal->ChangeFilesProperties(FileList, &Properties);
  1276. }
  1277. __finally
  1278. {
  1279. FreeFileList(FileList);
  1280. }
  1281. }
  1282. //---------------------------------------------------------------------------
  1283. void __fastcall TScript::LnProc(TScriptProcParams * Parameters)
  1284. {
  1285. CheckSession();
  1286. DebugAssert(Parameters->ParamCount == 2);
  1287. FTerminal->CreateLink(Parameters->Param[2], Parameters->Param[1], true);
  1288. }
  1289. //---------------------------------------------------------------------------
  1290. void __fastcall TScript::MkDirProc(TScriptProcParams * Parameters)
  1291. {
  1292. CheckSession();
  1293. FTerminal->CreateDirectory(Parameters->Param[1]);
  1294. }
  1295. //---------------------------------------------------------------------------
  1296. void __fastcall TScript::GetProc(TScriptProcParams * Parameters)
  1297. {
  1298. CheckSession();
  1299. ResetTransfer();
  1300. bool Latest = Parameters->FindSwitch(L"latest");
  1301. int LastFileParam = (Parameters->ParamCount == 1 ? 1 : Parameters->ParamCount - 1);
  1302. TStrings * FileList = CreateFileList(Parameters, 1, LastFileParam,
  1303. (TFileListType)(fltQueryServer | fltMask | FLAGMASK(Latest, fltLatest)));
  1304. try
  1305. {
  1306. CheckDefaultCopyParam();
  1307. TCopyParamType CopyParam = FCopyParam;
  1308. UnicodeString TargetDirectory;
  1309. if (Parameters->ParamCount == 1)
  1310. {
  1311. TargetDirectory = GetCurrentDir();
  1312. CopyParam.FileMask = L"";
  1313. }
  1314. else
  1315. {
  1316. UnicodeString Target = Parameters->Param[Parameters->ParamCount];
  1317. TargetDirectory = ExtractFilePath(Target);
  1318. if (TargetDirectory.IsEmpty())
  1319. {
  1320. TargetDirectory = GetCurrentDir();
  1321. }
  1322. CopyParam.FileMask = ExtractFileName(Target);
  1323. Target = IncludeTrailingBackslash(TargetDirectory) + CopyParam.FileMask;
  1324. CheckMultiFilesToOne(FileList, Target, false);
  1325. }
  1326. int Params = 0;
  1327. TransferParamParams(Params, Parameters);
  1328. CopyParamParams(CopyParam, Parameters);
  1329. CheckParams(Parameters);
  1330. FTerminal->CopyToLocal(FileList, TargetDirectory, &CopyParam, Params);
  1331. }
  1332. __finally
  1333. {
  1334. FreeFileList(FileList);
  1335. }
  1336. }
  1337. //---------------------------------------------------------------------------
  1338. void __fastcall TScript::PutProc(TScriptProcParams * Parameters)
  1339. {
  1340. CheckSession();
  1341. ResetTransfer();
  1342. bool Latest = Parameters->FindSwitch(L"latest");
  1343. int LastFileParam = (Parameters->ParamCount == 1 ? 1 : Parameters->ParamCount - 1);
  1344. TStrings * FileList =
  1345. CreateLocalFileList(
  1346. Parameters, 1, LastFileParam, (TFileListType)(fltMask | FLAGMASK(Latest, fltLatest)));
  1347. try
  1348. {
  1349. CheckDefaultCopyParam();
  1350. TCopyParamType CopyParam = FCopyParam;
  1351. UnicodeString TargetDirectory;
  1352. if (Parameters->ParamCount == 1)
  1353. {
  1354. TargetDirectory = FTerminal->CurrentDirectory;
  1355. CopyParam.FileMask = L"";
  1356. }
  1357. else
  1358. {
  1359. UnicodeString Target = Parameters->Param[Parameters->ParamCount];
  1360. TargetDirectory = UnixExtractFilePath(Target);
  1361. if (TargetDirectory.IsEmpty())
  1362. {
  1363. TargetDirectory = FTerminal->CurrentDirectory;
  1364. }
  1365. CopyParam.FileMask = UnixExtractFileName(Target);
  1366. Target = UnixIncludeTrailingBackslash(TargetDirectory) + CopyParam.FileMask;
  1367. CheckMultiFilesToOne(FileList, Target, true);
  1368. }
  1369. int Params = 0;
  1370. TransferParamParams(Params, Parameters);
  1371. CopyParamParams(CopyParam, Parameters);
  1372. CheckParams(Parameters);
  1373. FTerminal->CopyToRemote(FileList, TargetDirectory, &CopyParam, Params);
  1374. }
  1375. __finally
  1376. {
  1377. FreeFileList(FileList);
  1378. }
  1379. }
  1380. //---------------------------------------------------------------------------
  1381. TTransferMode __fastcall TScript::ParseTransferModeName(UnicodeString Name)
  1382. {
  1383. DebugAssert((tmBinary == 0) && (tmAscii == 1) && (tmAutomatic == 2));
  1384. int Value = TScriptCommands::FindCommand(TransferModeNames,
  1385. LENOF(TransferModeNames), Name);
  1386. if (Value < 0)
  1387. {
  1388. throw Exception(FMTLOAD(SCRIPT_VALUE_UNKNOWN, (L"transfer", Name)));
  1389. }
  1390. return (TTransferMode)Value;
  1391. }
  1392. //---------------------------------------------------------------------------
  1393. void __fastcall TScript::OptionImpl(UnicodeString OptionName, UnicodeString ValueName)
  1394. {
  1395. enum { Echo, Batch, Confirm, Transfer, SynchDelete, Exclude, Include, ReconnectTime, FailOnNoMatch };
  1396. static const wchar_t * Names[] = { L"echo", L"batch", L"confirm", L"transfer",
  1397. L"synchdelete", L"exclude", L"include", L"reconnecttime", L"failonnomatch" };
  1398. DebugAssert((BatchOff == 0) && (BatchOn == 1) && (BatchAbort == 2) && (BatchContinue == 3));
  1399. static const wchar_t * BatchModeNames[] = { L"off", L"on", L"abort", L"continue" };
  1400. int Option = -1;
  1401. if (!OptionName.IsEmpty())
  1402. {
  1403. Option = TScriptCommands::FindCommand(Names, LENOF(Names), OptionName);
  1404. if (Option < 0)
  1405. {
  1406. throw Exception(FMTLOAD(SCRIPT_OPTION_UNKNOWN, (OptionName)));
  1407. }
  1408. else
  1409. {
  1410. OptionName = Names[Option];
  1411. }
  1412. }
  1413. #define OPT(OPT) ((Option < 0) || (Option == OPT))
  1414. const wchar_t * ListFormat = L"%-15s %-10s";
  1415. bool SetValue = !ValueName.IsEmpty();
  1416. bool PrintReconnectTime = false;
  1417. if (OPT(Echo))
  1418. {
  1419. if (SetValue)
  1420. {
  1421. int Value = TScriptCommands::FindCommand(ToggleNames, LENOF(ToggleNames), ValueName);
  1422. if (Value < 0)
  1423. {
  1424. throw Exception(FMTLOAD(SCRIPT_VALUE_UNKNOWN, (ValueName, OptionName)));
  1425. }
  1426. FEcho = (Value == On);
  1427. }
  1428. PrintLine(FORMAT(ListFormat, (Names[Echo], ToggleNames[FEcho ? On : Off])));
  1429. }
  1430. if (OPT(Batch))
  1431. {
  1432. if (SetValue)
  1433. {
  1434. int Value = TScriptCommands::FindCommand(BatchModeNames, LENOF(BatchModeNames), ValueName);
  1435. if (Value < 0)
  1436. {
  1437. throw Exception(FMTLOAD(SCRIPT_VALUE_UNKNOWN, (ValueName, OptionName)));
  1438. }
  1439. FBatch = (TBatchMode)Value;
  1440. FInteractiveBatch = FBatch;
  1441. if (SetValue && (FBatch != BatchOff) && (FSessionReopenTimeout == 0))
  1442. {
  1443. // keep in sync with Session constructor in .NET
  1444. FSessionReopenTimeout = 2 * MSecsPerSec * SecsPerMin; // 2 mins
  1445. PrintReconnectTime = true;
  1446. }
  1447. }
  1448. PrintLine(FORMAT(ListFormat, (Names[Batch], BatchModeNames[FBatch])));
  1449. }
  1450. if (OPT(Confirm))
  1451. {
  1452. if (SetValue)
  1453. {
  1454. int Value = TScriptCommands::FindCommand(ToggleNames, LENOF(ToggleNames), ValueName);
  1455. if (Value < 0)
  1456. {
  1457. throw Exception(FMTLOAD(SCRIPT_VALUE_UNKNOWN, (ValueName, OptionName)));
  1458. }
  1459. FConfirm = (Value == On);
  1460. FInteractiveConfirm = FConfirm;
  1461. }
  1462. PrintLine(FORMAT(ListFormat, (Names[Confirm], ToggleNames[FConfirm ? On : Off])));
  1463. }
  1464. // omit the option in listing
  1465. if (Option == Transfer)
  1466. {
  1467. if (SetValue)
  1468. {
  1469. FCopyParam.TransferMode = ParseTransferModeName(ValueName);
  1470. }
  1471. DebugAssert(FCopyParam.TransferMode < (TTransferMode)LENOF(TransferModeNames));
  1472. const wchar_t * Value = TransferModeNames[FCopyParam.TransferMode];
  1473. PrintLine(FORMAT(ListFormat, (Names[Transfer], Value)));
  1474. }
  1475. // omit the option in listing
  1476. if (Option == SynchDelete)
  1477. {
  1478. if (SetValue)
  1479. {
  1480. int Value = TScriptCommands::FindCommand(ToggleNames, LENOF(ToggleNames), ValueName);
  1481. if (Value < 0)
  1482. {
  1483. throw Exception(FMTLOAD(SCRIPT_VALUE_UNKNOWN, (ValueName, OptionName)));
  1484. }
  1485. FSynchronizeParams =
  1486. (FSynchronizeParams & ~TTerminal::spDelete) |
  1487. FLAGMASK(Value == On, TTerminal::spDelete);
  1488. }
  1489. PrintLine(FORMAT(ListFormat, (Names[SynchDelete],
  1490. ToggleNames[FLAGSET(FSynchronizeParams, TTerminal::spDelete) ? On : Off])));
  1491. }
  1492. static const wchar_t * Clear = L"clear";
  1493. // omit the option in listing
  1494. if (Option == Include)
  1495. {
  1496. if (SetValue)
  1497. {
  1498. FCopyParam.IncludeFileMask =
  1499. (ValueName == Clear ? UnicodeString() : ValueName);
  1500. FIncludeFileMaskOptionUsed = (ValueName != Clear);
  1501. }
  1502. PrintLine(FORMAT(ListFormat, (Names[Include], FCopyParam.IncludeFileMask.Masks)));
  1503. }
  1504. // omit the option in listing
  1505. if (Option == Exclude)
  1506. {
  1507. if (SetValue)
  1508. {
  1509. // will throw if ValueName already includes IncludeExcludeFileMasksDelimiter
  1510. FCopyParam.IncludeFileMask =
  1511. (ValueName == Clear ? UnicodeString() : UnicodeString(IncludeExcludeFileMasksDelimiter) + ValueName);
  1512. FIncludeFileMaskOptionUsed = (ValueName != Clear);
  1513. }
  1514. PrintLine(FORMAT(ListFormat, (Names[Include], FCopyParam.IncludeFileMask.Masks)));
  1515. }
  1516. if (OPT(ReconnectTime) || PrintReconnectTime)
  1517. {
  1518. if (SetValue && !PrintReconnectTime)
  1519. {
  1520. int Value;
  1521. if (AnsiSameText(ValueName, ToggleNames[Off]))
  1522. {
  1523. Value = 0;
  1524. }
  1525. else
  1526. {
  1527. if (!TryStrToInt(ValueName, Value))
  1528. {
  1529. throw Exception(FMTLOAD(SCRIPT_VALUE_UNKNOWN, (ValueName, OptionName)));
  1530. }
  1531. else
  1532. {
  1533. Value *= MSecsPerSec;
  1534. }
  1535. }
  1536. FSessionReopenTimeout = Value;
  1537. }
  1538. if (FSessionReopenTimeout == 0)
  1539. {
  1540. ValueName = ToggleNames[Off];
  1541. }
  1542. else
  1543. {
  1544. ValueName = IntToStr(FSessionReopenTimeout / MSecsPerSec);
  1545. }
  1546. PrintLine(FORMAT(ListFormat, (Names[ReconnectTime], ValueName)));
  1547. }
  1548. if (OPT(FailOnNoMatch))
  1549. {
  1550. if (SetValue)
  1551. {
  1552. int Value = TScriptCommands::FindCommand(ToggleNames, LENOF(ToggleNames), ValueName);
  1553. if (Value < 0)
  1554. {
  1555. throw Exception(FMTLOAD(SCRIPT_VALUE_UNKNOWN, (ValueName, OptionName)));
  1556. }
  1557. FFailOnNoMatch = (Value == On);
  1558. }
  1559. PrintLine(FORMAT(ListFormat, (Names[FailOnNoMatch], ToggleNames[FFailOnNoMatch ? On : Off])));
  1560. }
  1561. #undef OPT
  1562. }
  1563. //---------------------------------------------------------------------------
  1564. void __fastcall TScript::OptionProc(TScriptProcParams * Parameters)
  1565. {
  1566. UnicodeString OptionName;
  1567. UnicodeString ValueName;
  1568. if (Parameters->ParamCount >= 1)
  1569. {
  1570. OptionName = Parameters->Param[1];
  1571. }
  1572. if (Parameters->ParamCount >= 2)
  1573. {
  1574. ValueName = Parameters->Param[2];
  1575. }
  1576. OptionImpl(OptionName, ValueName);
  1577. }
  1578. //---------------------------------------------------------------------------
  1579. void __fastcall TScript::AsciiProc(TScriptProcParams * /*Parameters*/)
  1580. {
  1581. OptionImpl(L"transfer", L"ascii");
  1582. }
  1583. //---------------------------------------------------------------------------
  1584. void __fastcall TScript::BinaryProc(TScriptProcParams * /*Parameters*/)
  1585. {
  1586. OptionImpl(L"transfer", L"binary");
  1587. }
  1588. //---------------------------------------------------------------------------
  1589. void __fastcall TScript::SynchronizeDirectories(TScriptProcParams * Parameters,
  1590. UnicodeString & LocalDirectory, UnicodeString & RemoteDirectory, int FirstParam)
  1591. {
  1592. if (Parameters->ParamCount >= FirstParam)
  1593. {
  1594. LocalDirectory = Parameters->Param[FirstParam];
  1595. }
  1596. else
  1597. {
  1598. LocalDirectory = GetCurrentDir();
  1599. }
  1600. if (Parameters->ParamCount >= FirstParam + 1)
  1601. {
  1602. RemoteDirectory = Parameters->Param[FirstParam + 1];
  1603. }
  1604. else
  1605. {
  1606. RemoteDirectory = FTerminal->CurrentDirectory;
  1607. }
  1608. }
  1609. //---------------------------------------------------------------------------
  1610. UnicodeString __fastcall TScript::SynchronizeFileRecord(
  1611. const UnicodeString & RootDirectory, const TSynchronizeChecklist::TItem * Item, bool Local)
  1612. {
  1613. const TSynchronizeChecklist::TItem::TFileInfo & FileInfo =
  1614. Local ? Item->Local : Item->Remote;
  1615. UnicodeString Path;
  1616. if (Local)
  1617. {
  1618. Path = IncludeTrailingBackslash(FileInfo.Directory) + FileInfo.FileName;
  1619. }
  1620. else
  1621. {
  1622. Path = UnixIncludeTrailingBackslash(FileInfo.Directory) + FileInfo.FileName;
  1623. }
  1624. if (SameText(RootDirectory, Path.SubString(1, RootDirectory.Length())))
  1625. {
  1626. Path[1] = L'.';
  1627. Path.Delete(2, RootDirectory.Length() - 2);
  1628. }
  1629. UnicodeString Result;
  1630. if (Item->IsDirectory)
  1631. {
  1632. if (Local)
  1633. {
  1634. Result = IncludeTrailingBackslash(Path);
  1635. }
  1636. else
  1637. {
  1638. Result = UnixIncludeTrailingBackslash(Path);
  1639. }
  1640. }
  1641. else
  1642. {
  1643. UnicodeString SizeStr = IntToStr(FileInfo.Size);
  1644. UnicodeString ModificationStr =
  1645. ::ModificationStr(FileInfo.Modification, FileInfo.ModificationFmt);
  1646. Result = FORMAT("%s [%s, %s]", (Path, SizeStr, ModificationStr));
  1647. }
  1648. return Result;
  1649. }
  1650. //---------------------------------------------------------------------------
  1651. void __fastcall TScript::SynchronizePreview(
  1652. UnicodeString LocalDirectory, UnicodeString RemoteDirectory,
  1653. TSynchronizeChecklist * Checklist)
  1654. {
  1655. LocalDirectory = IncludeTrailingBackslash(LocalDirectory);
  1656. RemoteDirectory = UnixIncludeTrailingBackslash(RemoteDirectory);
  1657. for (int Index = 0; (Index < Checklist->Count); Index++)
  1658. {
  1659. const TSynchronizeChecklist::TItem * Item = Checklist->Item[Index];
  1660. if (Item->Checked)
  1661. {
  1662. UnicodeString Message;
  1663. UnicodeString LocalRecord = SynchronizeFileRecord(LocalDirectory, Item, true);
  1664. UnicodeString RemoteRecord = SynchronizeFileRecord(RemoteDirectory, Item, false);
  1665. switch (Item->Action)
  1666. {
  1667. case TSynchronizeChecklist::saUploadNew:
  1668. Message =
  1669. FMTLOAD(SCRIPT_SYNC_UPLOAD_NEW, (LocalRecord));
  1670. break;
  1671. case TSynchronizeChecklist::saDownloadNew:
  1672. Message =
  1673. FMTLOAD(SCRIPT_SYNC_DOWNLOAD_NEW, (RemoteRecord));
  1674. break;
  1675. case TSynchronizeChecklist::saUploadUpdate:
  1676. Message =
  1677. FMTLOAD(SCRIPT_SYNC_UPLOAD_UPDATE,
  1678. (LocalRecord, RemoteRecord));
  1679. break;
  1680. case TSynchronizeChecklist::saDownloadUpdate:
  1681. Message =
  1682. FMTLOAD(SCRIPT_SYNC_DOWNLOAD_UPDATE,
  1683. (RemoteRecord, LocalRecord));
  1684. break;
  1685. case TSynchronizeChecklist::saDeleteRemote:
  1686. Message =
  1687. FMTLOAD(SCRIPT_SYNC_DELETE_REMOTE, (RemoteRecord));
  1688. break;
  1689. case TSynchronizeChecklist::saDeleteLocal:
  1690. Message =
  1691. FMTLOAD(SCRIPT_SYNC_DELETE_LOCAL, (LocalRecord));
  1692. break;
  1693. default:
  1694. FAIL;
  1695. }
  1696. PrintLine(Message);
  1697. }
  1698. }
  1699. }
  1700. //---------------------------------------------------------------------------
  1701. void __fastcall TScript::SynchronizeProc(TScriptProcParams * Parameters)
  1702. {
  1703. CheckSession();
  1704. ResetTransfer();
  1705. static const wchar_t * ModeNames[] = { L"remote", L"local", L"both" };
  1706. UnicodeString ModeName = Parameters->Param[1];
  1707. DebugAssert(FSynchronizeMode < 0);
  1708. FSynchronizeMode = TScriptCommands::FindCommand(ModeNames, LENOF(ModeNames), ModeName);
  1709. try
  1710. {
  1711. if (FSynchronizeMode < 0)
  1712. {
  1713. throw Exception(FMTLOAD(SCRIPT_OPTION_UNKNOWN, (ModeName)));
  1714. }
  1715. UnicodeString LocalDirectory;
  1716. UnicodeString RemoteDirectory;
  1717. SynchronizeDirectories(Parameters, LocalDirectory, RemoteDirectory, 2);
  1718. CheckDefaultCopyParam();
  1719. TCopyParamType CopyParam = FCopyParam;
  1720. CopyParamParams(CopyParam, Parameters);
  1721. CheckDefaultSynchronizeParams();
  1722. int SynchronizeParams = FSynchronizeParams | TTerminal::spNoConfirmation;
  1723. UnicodeString Value;
  1724. if (Parameters->FindSwitch(L"delete"))
  1725. {
  1726. SynchronizeParams |= TTerminal::spDelete;
  1727. }
  1728. if (Parameters->FindSwitch(L"mirror") &&
  1729. (FSynchronizeMode != TTerminal::smBoth))
  1730. {
  1731. SynchronizeParams |= TTerminal::spMirror;
  1732. }
  1733. if (Parameters->FindSwitch(L"criteria", Value))
  1734. {
  1735. enum { None, Time, Size, Either, EitherBoth };
  1736. static const wchar_t * CriteriaNames[] = { L"none", L"time", L"size", L"either", L"both" };
  1737. int Criteria = TScriptCommands::FindCommand(CriteriaNames, LENOF(CriteriaNames), Value);
  1738. switch (Criteria)
  1739. {
  1740. case None:
  1741. SynchronizeParams |= TTerminal::spNotByTime;
  1742. SynchronizeParams &= ~TTerminal::spBySize;
  1743. break;
  1744. case Time:
  1745. SynchronizeParams &= ~(TTerminal::spNotByTime | TTerminal::spBySize);
  1746. break;
  1747. case Size:
  1748. SynchronizeParams |= TTerminal::spNotByTime | TTerminal::spBySize;
  1749. break;
  1750. case Either:
  1751. case EitherBoth:
  1752. SynchronizeParams &= ~TTerminal::spNotByTime;
  1753. SynchronizeParams |= TTerminal::spBySize;
  1754. break;
  1755. }
  1756. }
  1757. bool Preview = Parameters->FindSwitch(L"preview");
  1758. // enforce rules
  1759. if (FSynchronizeMode == TTerminal::smBoth)
  1760. {
  1761. SynchronizeParams &= ~(TTerminal::spNotByTime | TTerminal::spBySize);
  1762. }
  1763. CheckParams(Parameters);
  1764. PrintLine(LoadStr(SCRIPT_SYNCHRONIZE_COLLECTING));
  1765. TSynchronizeChecklist * Checklist =
  1766. FTerminal->SynchronizeCollect(LocalDirectory, RemoteDirectory,
  1767. static_cast<TTerminal::TSynchronizeMode>(FSynchronizeMode),
  1768. &CopyParam, SynchronizeParams, OnTerminalSynchronizeDirectory, NULL);
  1769. try
  1770. {
  1771. bool AnyChecked = false;
  1772. for (int Index = 0; !AnyChecked && (Index < Checklist->Count); Index++)
  1773. {
  1774. AnyChecked = Checklist->Item[Index]->Checked;
  1775. }
  1776. if (AnyChecked)
  1777. {
  1778. if (Preview)
  1779. {
  1780. PrintLine(LoadStr(SCRIPT_SYNCHRONIZE_CHECKLIST));
  1781. SynchronizePreview(LocalDirectory, RemoteDirectory, Checklist);
  1782. }
  1783. else
  1784. {
  1785. PrintLine(LoadStr(SCRIPT_SYNCHRONIZE_SYNCHRONIZING));
  1786. FTerminal->SynchronizeApply(Checklist, LocalDirectory, RemoteDirectory,
  1787. &CopyParam, SynchronizeParams, OnTerminalSynchronizeDirectory);
  1788. }
  1789. }
  1790. else
  1791. {
  1792. PrintLine(LoadStr(SCRIPT_SYNCHRONIZE_NODIFFERENCE));
  1793. }
  1794. }
  1795. __finally
  1796. {
  1797. delete Checklist;
  1798. }
  1799. }
  1800. __finally
  1801. {
  1802. FSynchronizeMode = -1;
  1803. }
  1804. }
  1805. //---------------------------------------------------------------------------
  1806. void __fastcall TScript::Synchronize(const UnicodeString LocalDirectory,
  1807. const UnicodeString RemoteDirectory, const TCopyParamType & CopyParam,
  1808. int SynchronizeParams, TSynchronizeChecklist ** Checklist)
  1809. {
  1810. try
  1811. {
  1812. FKeepingUpToDate = true;
  1813. TSynchronizeChecklist * AChecklist =
  1814. FTerminal->SynchronizeCollect(LocalDirectory, RemoteDirectory, TTerminal::smRemote,
  1815. &CopyParam, SynchronizeParams, NULL, NULL);
  1816. try
  1817. {
  1818. if (AChecklist->Count > 0)
  1819. {
  1820. FTerminal->SynchronizeApply(AChecklist, LocalDirectory, RemoteDirectory,
  1821. &CopyParam, SynchronizeParams, OnTerminalSynchronizeDirectory);
  1822. }
  1823. }
  1824. __finally
  1825. {
  1826. if (Checklist == NULL)
  1827. {
  1828. delete AChecklist;
  1829. }
  1830. else
  1831. {
  1832. *Checklist = AChecklist;
  1833. }
  1834. }
  1835. // to break line after the last transfer (if any);
  1836. Print(L"");
  1837. FKeepingUpToDate = false;
  1838. }
  1839. catch(Exception & E)
  1840. {
  1841. FKeepingUpToDate = false;
  1842. HandleExtendedException(&E);
  1843. throw;
  1844. }
  1845. }
  1846. //---------------------------------------------------------------------------
  1847. void __fastcall TScript::KeepUpToDateProc(TScriptProcParams * Parameters)
  1848. {
  1849. if (OnSynchronizeStartStop == NULL)
  1850. {
  1851. Abort();
  1852. }
  1853. CheckSession();
  1854. ResetTransfer();
  1855. UnicodeString LocalDirectory;
  1856. UnicodeString RemoteDirectory;
  1857. SynchronizeDirectories(Parameters, LocalDirectory, RemoteDirectory, 1);
  1858. CheckDefaultSynchronizeParams();
  1859. int SynchronizeParams = FSynchronizeParams | TTerminal::spNoConfirmation |
  1860. TTerminal::spNoRecurse | TTerminal::spUseCache | TTerminal::spDelayProgress |
  1861. TTerminal::spSubDirs;
  1862. if (Parameters->FindSwitch(L"delete"))
  1863. {
  1864. SynchronizeParams |= TTerminal::spDelete;
  1865. }
  1866. CheckDefaultCopyParam();
  1867. TCopyParamType CopyParam = FCopyParam;
  1868. CopyParamParams(CopyParam, Parameters);
  1869. CheckParams(Parameters);
  1870. PrintLine(LoadStr(SCRIPT_KEEPING_UP_TO_DATE));
  1871. OnSynchronizeStartStop(this, LocalDirectory, RemoteDirectory, CopyParam, SynchronizeParams);
  1872. }
  1873. //---------------------------------------------------------------------------
  1874. //---------------------------------------------------------------------------
  1875. __fastcall TManagementScript::TManagementScript(TStoredSessionList * StoredSessions,
  1876. bool LimitedOutput) :
  1877. TScript(LimitedOutput)
  1878. {
  1879. DebugAssert(StoredSessions != NULL);
  1880. FOnInput = NULL;
  1881. FOnTerminalPromptUser = NULL;
  1882. FOnShowExtendedException = NULL;
  1883. FOnTerminalQueryUser = NULL;
  1884. FStoredSessions = StoredSessions;
  1885. FTerminalList = new TTerminalList(Configuration);
  1886. FOnQueryCancel = NULL;
  1887. FContinue = true;
  1888. OnTerminalSynchronizeDirectory = TerminalSynchronizeDirectory;
  1889. FCommands->Register(L"exit", SCRIPT_EXIT_DESC, SCRIPT_EXIT_HELP, &ExitProc, 0, 0, false);
  1890. FCommands->Register(L"bye", 0, SCRIPT_EXIT_HELP, &ExitProc, 0, 0, false);
  1891. FCommands->Register(L"open", SCRIPT_OPEN_DESC, SCRIPT_OPEN_HELP8, &OpenProc, 0, -1, true);
  1892. FCommands->Register(L"close", SCRIPT_CLOSE_DESC, SCRIPT_CLOSE_HELP, &CloseProc, 0, 1, false);
  1893. FCommands->Register(L"session", SCRIPT_SESSION_DESC, SCRIPT_SESSION_HELP, &SessionProc, 0, 1, false);
  1894. FCommands->Register(L"lpwd", SCRIPT_LPWD_DESC, SCRIPT_LPWD_HELP, &LPwdProc, 0, 0, false);
  1895. FCommands->Register(L"lcd", SCRIPT_LCD_DESC, SCRIPT_LCD_HELP, &LCdProc, 1, 1, false);
  1896. FCommands->Register(L"lls", SCRIPT_LLS_DESC, SCRIPT_LLS_HELP2, &LLsProc, 0, 1, false);
  1897. }
  1898. //---------------------------------------------------------------------------
  1899. __fastcall TManagementScript::~TManagementScript()
  1900. {
  1901. while (FTerminalList->Count > 0)
  1902. {
  1903. FreeTerminal(FTerminalList->Terminals[0]);
  1904. }
  1905. delete FTerminalList;
  1906. }
  1907. //---------------------------------------------------------------------------
  1908. void __fastcall TManagementScript::FreeTerminal(TTerminal * ATerminal)
  1909. {
  1910. TSessionData * Data = StoredSessions->FindSame(ATerminal->SessionData);
  1911. if (Data != NULL)
  1912. {
  1913. ATerminal->SessionData->RemoteDirectory = ATerminal->CurrentDirectory;
  1914. bool Changed = false;
  1915. if (ATerminal->SessionData->UpdateDirectories)
  1916. {
  1917. Data->RemoteDirectory = ATerminal->SessionData->RemoteDirectory;
  1918. Changed = true;
  1919. }
  1920. if (Changed)
  1921. {
  1922. // only modified, implicit
  1923. StoredSessions->Save(false, false);
  1924. }
  1925. }
  1926. FTerminalList->FreeTerminal(ATerminal);
  1927. }
  1928. //---------------------------------------------------------------------------
  1929. void __fastcall TManagementScript::Input(const UnicodeString Prompt,
  1930. UnicodeString & Str, bool AllowEmpty)
  1931. {
  1932. do
  1933. {
  1934. Str = L"";
  1935. if (FOnInput != NULL)
  1936. {
  1937. FOnInput(this, Prompt, Str);
  1938. }
  1939. else
  1940. {
  1941. Abort();
  1942. }
  1943. }
  1944. while (Str.Trim().IsEmpty() && !AllowEmpty);
  1945. }
  1946. //---------------------------------------------------------------------------
  1947. void __fastcall TManagementScript::PrintProgress(bool First, const UnicodeString Str)
  1948. {
  1949. if (FOnPrintProgress != NULL)
  1950. {
  1951. FOnPrintProgress(this, First, Str);
  1952. }
  1953. }
  1954. //---------------------------------------------------------------------------
  1955. void __fastcall TManagementScript::ResetTransfer()
  1956. {
  1957. TScript::ResetTransfer();
  1958. FLastProgressFile = L"";
  1959. FLastProgressTime = 0;
  1960. FLastProgressEventTime = 0;
  1961. FLastProgressMessage = L"";
  1962. }
  1963. //---------------------------------------------------------------------------
  1964. bool __fastcall TManagementScript::QueryCancel()
  1965. {
  1966. bool Result = false;
  1967. if (OnQueryCancel != NULL)
  1968. {
  1969. OnQueryCancel(this, Result);
  1970. }
  1971. return Result;
  1972. }
  1973. //---------------------------------------------------------------------------
  1974. void __fastcall TManagementScript::TerminalInformation(TTerminal * ATerminal,
  1975. const UnicodeString & Str, bool /*Status*/, int Phase)
  1976. {
  1977. DebugAssert(ATerminal != NULL);
  1978. if ((Phase < 0) && (ATerminal->Status == ssOpening))
  1979. {
  1980. PrintLine(Str);
  1981. }
  1982. }
  1983. //---------------------------------------------------------------------------
  1984. void __fastcall TManagementScript::TerminalPromptUser(TTerminal * ATerminal,
  1985. TPromptKind Kind, UnicodeString Name, UnicodeString Instructions, TStrings * Prompts,
  1986. TStrings * Results, bool & Result, void * Arg)
  1987. {
  1988. // When authentication using stored password fails,
  1989. // do not ask user for another password.
  1990. if ((!ATerminal->StoredCredentialsTried ||
  1991. !IsAuthenticationPrompt(Kind) ||
  1992. (Prompts->Count == 0)) && // allow instructions-only prompts
  1993. (OnTerminalPromptUser != NULL))
  1994. {
  1995. OnTerminalPromptUser(ATerminal, Kind, Name, Instructions, Prompts, Results, Result, Arg);
  1996. }
  1997. }
  1998. //---------------------------------------------------------------------------
  1999. bool __fastcall TManagementScript::Synchronizing()
  2000. {
  2001. return (FKeepingUpToDate || (FSynchronizeMode >= 0));
  2002. }
  2003. //---------------------------------------------------------------------------
  2004. void __fastcall TManagementScript::ShowPendingProgress()
  2005. {
  2006. if (!FSynchronizeIntro.IsEmpty())
  2007. {
  2008. if (Synchronizing())
  2009. {
  2010. PrintLine(FSynchronizeIntro);
  2011. }
  2012. FSynchronizeIntro = L"";
  2013. }
  2014. }
  2015. //---------------------------------------------------------------------------
  2016. void __fastcall TManagementScript::TerminalOperationProgress(
  2017. TFileOperationProgressType & ProgressData)
  2018. {
  2019. if ((ProgressData.Operation == foCopy) ||
  2020. (ProgressData.Operation == foMove))
  2021. {
  2022. if (ProgressData.InProgress && ProgressData.FileInProgress &&
  2023. !ProgressData.FileName.IsEmpty())
  2024. {
  2025. bool DoPrint = false;
  2026. bool First = false;
  2027. UnicodeString ProgressFileName = ProgressData.FileName;
  2028. if (ProgressData.Side == osLocal)
  2029. {
  2030. ProgressFileName = ExcludeTrailingBackslash(ProgressFileName);
  2031. }
  2032. else
  2033. {
  2034. ProgressFileName = UnixExcludeTrailingBackslash(ProgressFileName);
  2035. }
  2036. if (ProgressFileName != FLastProgressFile)
  2037. {
  2038. First = true;
  2039. DoPrint = true;
  2040. ShowPendingProgress();
  2041. }
  2042. time_t Time = time(NULL);
  2043. if ((OnProgress != NULL) && WantsProgress &&
  2044. (DoPrint || (FLastProgressEventTime != Time) || ProgressData.IsTransferDone()))
  2045. {
  2046. FLastProgressEventTime = Time;
  2047. TScriptProgress Progress;
  2048. Progress.Operation = ProgressData.Operation;
  2049. Progress.Side = ProgressData.Side;
  2050. Progress.FileName = ProgressData.FileName;
  2051. Progress.Directory = ProgressData.Directory;
  2052. Progress.OverallProgress = ProgressData.OverallProgress();
  2053. Progress.FileProgress = ProgressData.TransferProgress();
  2054. Progress.CPS = ProgressData.CPS();
  2055. OnProgress(this, Progress);
  2056. }
  2057. if (!DoPrint && ((FLastProgressTime != Time) || ProgressData.IsTransferDone()))
  2058. {
  2059. DoPrint = true;
  2060. }
  2061. if (DoPrint)
  2062. {
  2063. static int WidthFileName = 25;
  2064. UnicodeString FileName;
  2065. if (FLimitedOutput)
  2066. {
  2067. FileName = MinimizeName(ProgressFileName, WidthFileName,
  2068. ProgressData.Side == osRemote);
  2069. }
  2070. else
  2071. {
  2072. FileName = ProgressFileName;
  2073. }
  2074. UnicodeString TransferedSizeStr;
  2075. if (ProgressData.TransferedSize < 1024)
  2076. {
  2077. TransferedSizeStr = FORMAT("%d B", (static_cast<int>(ProgressData.TransferedSize)));
  2078. }
  2079. else
  2080. {
  2081. TransferedSizeStr = FORMAT("%d KB", (static_cast<int>(ProgressData.TransferedSize / 1024)));
  2082. }
  2083. UnicodeString ProgressMessage = FORMAT(L"%-*s | %14s | %6.1f KB/s | %-6.6s | %3d%%",
  2084. (WidthFileName, FileName,
  2085. TransferedSizeStr,
  2086. static_cast<float>(ProgressData.CPS()) / 1024,
  2087. ProgressData.AsciiTransfer ? L"ascii" : L"binary",
  2088. ProgressData.TransferProgress()));
  2089. if (FLastProgressMessage != ProgressMessage)
  2090. {
  2091. FLastProgressTime = Time;
  2092. PrintProgress(First, ProgressMessage);
  2093. FLastProgressMessage = ProgressMessage;
  2094. FLastProgressFile = ProgressFileName;
  2095. }
  2096. }
  2097. }
  2098. else
  2099. {
  2100. FLastProgressFile = L"";
  2101. }
  2102. }
  2103. if (QueryCancel())
  2104. {
  2105. ProgressData.Cancel = csCancel;
  2106. }
  2107. }
  2108. //---------------------------------------------------------------------------
  2109. void __fastcall TManagementScript::TerminalOperationFinished(
  2110. TFileOperation Operation, TOperationSide /*Side*/,
  2111. bool /*Temp*/, const UnicodeString & FileName, Boolean Success,
  2112. TOnceDoneOperation & /*OnceDoneOperation*/)
  2113. {
  2114. if (Success &&
  2115. (Operation != foCalculateSize) && (Operation != foCalculateChecksum) &&
  2116. (Operation != foCopy) && (Operation != foMove))
  2117. {
  2118. ShowPendingProgress();
  2119. // For FKeepingUpToDate we should send events to synchronize controller eventually.
  2120. if (Synchronizing() && (Operation == foDelete))
  2121. {
  2122. // Note that this is duplicated with "keep up to date" log.
  2123. PrintLine(FMTLOAD(SCRIPT_SYNCHRONIZE_DELETED, (FileName)));
  2124. }
  2125. else
  2126. {
  2127. PrintLine(FileName);
  2128. }
  2129. }
  2130. }
  2131. //---------------------------------------------------------------------------
  2132. void __fastcall TManagementScript::TerminalSynchronizeDirectory(
  2133. const UnicodeString LocalDirectory, const UnicodeString RemoteDirectory,
  2134. bool & Continue, bool Collect)
  2135. {
  2136. int SynchronizeMode = FSynchronizeMode;
  2137. if (FKeepingUpToDate)
  2138. {
  2139. SynchronizeMode = TTerminal::smRemote;
  2140. }
  2141. UnicodeString Arrow;
  2142. switch (SynchronizeMode)
  2143. {
  2144. case TTerminal::smRemote:
  2145. Arrow = L"=>";
  2146. break;
  2147. case TTerminal::smLocal:
  2148. Arrow = L"<=";
  2149. break;
  2150. case TTerminal::smBoth:
  2151. Arrow = L"<=>";
  2152. break;
  2153. }
  2154. UnicodeString Progress = FMTLOAD(SCRIPT_SYNCHRONIZE, (ExcludeTrailingBackslash(LocalDirectory),
  2155. Arrow, UnixExcludeTrailingBackslash(RemoteDirectory)));
  2156. if (Collect)
  2157. {
  2158. PrintProgress(false, Progress);
  2159. }
  2160. else
  2161. {
  2162. FSynchronizeIntro = Progress;
  2163. }
  2164. if (QueryCancel())
  2165. {
  2166. Continue = false;
  2167. }
  2168. }
  2169. //---------------------------------------------------------------------------
  2170. void __fastcall TManagementScript::TerminalInitializeLog(TObject * Sender)
  2171. {
  2172. TTerminal * ATerminal = dynamic_cast<TTerminal *>(Sender);
  2173. if (ALWAYS_TRUE(ATerminal != NULL))
  2174. {
  2175. LogPendingLines(ATerminal);
  2176. }
  2177. }
  2178. //---------------------------------------------------------------------------
  2179. TTerminal * __fastcall TManagementScript::FindSession(const UnicodeString Index)
  2180. {
  2181. int i = StrToIntDef(Index, -1);
  2182. if ((i <= 0) || (i > FTerminalList->Count))
  2183. {
  2184. throw Exception(FMTLOAD(SCRIPT_SESSION_INDEX_INVALID, (Index)));
  2185. }
  2186. else
  2187. {
  2188. return FTerminalList->Terminals[i - 1];
  2189. }
  2190. }
  2191. //---------------------------------------------------------------------------
  2192. void __fastcall TManagementScript::PrintActiveSession()
  2193. {
  2194. DebugAssert(FTerminal != NULL);
  2195. PrintLine(FMTLOAD(SCRIPT_ACTIVE_SESSION,
  2196. (FTerminalList->IndexOf(FTerminal) + 1, FTerminal->SessionData->SessionName)));
  2197. }
  2198. //---------------------------------------------------------------------------
  2199. bool __fastcall TManagementScript::HandleExtendedException(Exception * E,
  2200. TTerminal * ATerminal)
  2201. {
  2202. bool Result = TScript::HandleExtendedException(E, ATerminal);
  2203. if (ATerminal == NULL)
  2204. {
  2205. ATerminal = FTerminal;
  2206. }
  2207. if ((ATerminal != NULL) && (ATerminal == FTerminal) && (dynamic_cast<EFatal*>(E) != NULL))
  2208. {
  2209. try
  2210. {
  2211. DoClose(ATerminal);
  2212. }
  2213. catch(...)
  2214. {
  2215. // ignore disconnect errors
  2216. }
  2217. }
  2218. return Result;
  2219. }
  2220. //---------------------------------------------------------------------------
  2221. void __fastcall TManagementScript::MaskPasswordInCommandLine(UnicodeString & Command, bool Recurse)
  2222. {
  2223. UnicodeString Url;
  2224. UnicodeString MaskedParamsPre;
  2225. UnicodeString MaskedParamsPost;
  2226. UnicodeString Param;
  2227. UnicodeString RawParam;
  2228. UnicodeString Separator;
  2229. UnicodeString Separator2;
  2230. bool AnyMaskedParam = false;
  2231. TOptions Options;
  2232. UnicodeString ACommand = Command;
  2233. bool SubCommands = false;
  2234. while (CutToken(ACommand, Param, &RawParam, &Separator2))
  2235. {
  2236. Options.Add(Param);
  2237. // "Param 1" is the "winscp.exe" or "open"
  2238. if ((Options.ParamCount == 2) && Url.IsEmpty() && !SubCommands)
  2239. {
  2240. Url = Param;
  2241. }
  2242. else
  2243. {
  2244. UnicodeString & MaskedParams = Url.IsEmpty() ? MaskedParamsPre : MaskedParamsPost;
  2245. UnicodeString Switch;
  2246. wchar_t SwitchMark;
  2247. if (Options.WasSwitchAdded(Switch, SwitchMark))
  2248. {
  2249. if (TSessionData::IsSensitiveOption(Switch))
  2250. {
  2251. // We should use something like TProgramParams::FormatSwitch here
  2252. RawParam = FORMAT(L"%s%s=***", (SwitchMark, Switch));
  2253. AnyMaskedParam = true;
  2254. }
  2255. SubCommands = SameText(Switch, COMMAND_SWITCH);
  2256. }
  2257. else
  2258. {
  2259. if (Recurse && SubCommands)
  2260. {
  2261. UnicodeString Cmd2 = Param;
  2262. UnicodeString Command2;
  2263. if (CutToken(Cmd2, Command2))
  2264. {
  2265. UnicodeString MaskedParam = MaskPasswordInCommand(Param, Command2);
  2266. if (MaskedParam != Param)
  2267. {
  2268. RawParam = AddQuotes(EscapeParam(MaskedParam));
  2269. AnyMaskedParam = true;
  2270. }
  2271. }
  2272. }
  2273. }
  2274. // Separator is empty on the first loop, but so is the MaskedParams
  2275. AddToList(MaskedParams, RawParam, Separator);
  2276. }
  2277. Separator = Separator2;
  2278. }
  2279. if (!Url.IsEmpty() || AnyMaskedParam)
  2280. {
  2281. UnicodeString MaskedUrl;
  2282. if (!Url.IsEmpty())
  2283. {
  2284. bool DefaultsOnly;
  2285. std::unique_ptr<TSessionData> Data(
  2286. StoredSessions->ParseUrl(Url, &Options, DefaultsOnly, NULL, NULL, &MaskedUrl));
  2287. }
  2288. if ((Url != MaskedUrl) || AnyMaskedParam)
  2289. {
  2290. Command = MaskedParamsPre;
  2291. // AddToList is noop, when respective component is empty
  2292. AddToList(Command, AddQuotes(MaskedUrl), L" ");
  2293. AddToList(Command, MaskedParamsPost, L" ");
  2294. }
  2295. }
  2296. }
  2297. //---------------------------------------------------------------------------
  2298. UnicodeString __fastcall TManagementScript::MaskPasswordInCommand(const UnicodeString & FullCommand,
  2299. const UnicodeString & Command)
  2300. {
  2301. UnicodeString Result = FullCommand;
  2302. if (SameText(FCommands->ResolveCommand(Command), L"open") &&
  2303. !Configuration->LogSensitive)
  2304. {
  2305. MaskPasswordInCommandLine(Result, false);
  2306. }
  2307. return Result;
  2308. }
  2309. //---------------------------------------------------------------------------
  2310. UnicodeString __fastcall TManagementScript::GetLogCmd(const UnicodeString & FullCommand,
  2311. const UnicodeString & Command, const UnicodeString & Params)
  2312. {
  2313. UnicodeString Result = MaskPasswordInCommand(FullCommand, Command);
  2314. return TScript::GetLogCmd(Result, Command, Params);
  2315. }
  2316. //---------------------------------------------------------------------------
  2317. void __fastcall TManagementScript::Connect(const UnicodeString Session,
  2318. TOptions * Options, bool CheckParams)
  2319. {
  2320. try
  2321. {
  2322. bool DefaultsOnly;
  2323. TSessionData * Data;
  2324. if (Options->FindSwitch(L"filezilla"))
  2325. {
  2326. UnicodeString Error;
  2327. std::unique_ptr<TStoredSessionList> FilezillaSessionList(
  2328. Configuration->SelectFilezillaSessionsForImport(StoredSessions, Error));
  2329. if (!Error.IsEmpty())
  2330. {
  2331. throw Exception(Error);
  2332. }
  2333. Data = dynamic_cast<TSessionData *>(FilezillaSessionList->FindByName(Session));
  2334. if (Data == NULL)
  2335. {
  2336. throw Exception(FMTLOAD(FILEZILLA_SITE_NOT_EXIST, (Session)));
  2337. }
  2338. else
  2339. {
  2340. Data = Data->Clone();
  2341. }
  2342. }
  2343. else
  2344. {
  2345. if (FStoredSessions->IsFolder(Session) ||
  2346. FStoredSessions->IsWorkspace(Session))
  2347. {
  2348. throw Exception(LoadStr(CANNOT_OPEN_SESSION_FOLDER));
  2349. }
  2350. Data = FStoredSessions->ParseUrl(Session, Options, DefaultsOnly);
  2351. }
  2352. try
  2353. {
  2354. if (CheckParams)
  2355. {
  2356. if (Options->ParamCount > 1)
  2357. {
  2358. throw Exception(FMTLOAD(SCRIPT_TOO_MANY_PARAMS, (L"open")));
  2359. }
  2360. TScriptCommands::CheckParams(Options, false);
  2361. }
  2362. if (!Data->Name.IsEmpty() && (Batch != TScript::BatchOff))
  2363. {
  2364. std::unique_ptr<TSessionData> DataWithFingerprint(Data->Clone());
  2365. DataWithFingerprint->LookupLastFingerprint();
  2366. PrintLine(LoadStr(SCRIPT_SITE_WARNING));
  2367. PrintLine(L"open " + DataWithFingerprint->GenerateOpenCommandArgs());
  2368. }
  2369. DebugAssert(Data != NULL);
  2370. if (!Data->CanLogin || DefaultsOnly)
  2371. {
  2372. if (Data->HostName.IsEmpty())
  2373. {
  2374. UnicodeString Value;
  2375. Input(LoadStr(SCRIPT_HOST_PROMPT), Value, false);
  2376. Data->HostName = Value;
  2377. }
  2378. DebugAssert(Data->CanLogin);
  2379. }
  2380. TTerminal * ATerminal = FTerminalList->NewTerminal(Data);
  2381. try
  2382. {
  2383. ATerminal->AutoReadDirectory = false;
  2384. ATerminal->OnInformation = TerminalInformation;
  2385. ATerminal->OnPromptUser = TerminalPromptUser;
  2386. ATerminal->OnShowExtendedException = OnShowExtendedException;
  2387. ATerminal->OnQueryUser = OnTerminalQueryUser;
  2388. ATerminal->OnProgress = TerminalOperationProgress;
  2389. ATerminal->OnFinished = TerminalOperationFinished;
  2390. ATerminal->OnInitializeLog = TerminalInitializeLog;
  2391. ConnectTerminal(ATerminal);
  2392. }
  2393. catch(Exception & E)
  2394. {
  2395. // make sure errors (mainly fatal ones) are associated
  2396. // with this terminal, not the last active one
  2397. bool Handled = HandleExtendedException(&E, ATerminal);
  2398. FTerminalList->FreeTerminal(ATerminal);
  2399. ATerminal = NULL;
  2400. if (!Handled)
  2401. {
  2402. throw;
  2403. }
  2404. }
  2405. if (ATerminal != NULL)
  2406. {
  2407. FTerminal = ATerminal;
  2408. if (!Data->LocalDirectory.IsEmpty())
  2409. {
  2410. try
  2411. {
  2412. DoChangeLocalDirectory(ExpandFileName(Data->LocalDirectory));
  2413. }
  2414. catch(Exception & E)
  2415. {
  2416. if (!HandleExtendedException(&E))
  2417. {
  2418. throw;
  2419. }
  2420. }
  2421. }
  2422. PrintActiveSession();
  2423. }
  2424. }
  2425. __finally
  2426. {
  2427. delete Data;
  2428. }
  2429. }
  2430. catch(Exception & E)
  2431. {
  2432. if (!HandleExtendedException(&E))
  2433. {
  2434. throw;
  2435. }
  2436. }
  2437. }
  2438. //---------------------------------------------------------------------------
  2439. void __fastcall TManagementScript::DoClose(TTerminal * ATerminal)
  2440. {
  2441. int Index = FTerminalList->IndexOf(ATerminal);
  2442. DebugAssert(Index >= 0);
  2443. bool WasActiveTerminal = (FTerminal == ATerminal);
  2444. try
  2445. {
  2446. if (ATerminal->Active)
  2447. {
  2448. ATerminal->Close();
  2449. }
  2450. UnicodeString SessionName = ATerminal->SessionData->SessionName;
  2451. FreeTerminal(ATerminal);
  2452. if (WasActiveTerminal)
  2453. {
  2454. FTerminal = NULL;
  2455. }
  2456. PrintLine(FMTLOAD(SCRIPT_SESSION_CLOSED, (SessionName)));
  2457. }
  2458. __finally
  2459. {
  2460. if (WasActiveTerminal)
  2461. {
  2462. if (FTerminalList->Count > 0)
  2463. {
  2464. if (Index < FTerminalList->Count)
  2465. {
  2466. FTerminal = FTerminalList->Terminals[Index];
  2467. }
  2468. else
  2469. {
  2470. FTerminal = FTerminalList->Terminals[0];
  2471. }
  2472. PrintActiveSession();
  2473. }
  2474. else
  2475. {
  2476. PrintLine(LoadStr(SCRIPT_NO_SESSION));
  2477. }
  2478. }
  2479. }
  2480. }
  2481. //---------------------------------------------------------------------------
  2482. void __fastcall TManagementScript::DoChangeLocalDirectory(UnicodeString Directory)
  2483. {
  2484. if (!SetCurrentDir(ApiPath(Directory)))
  2485. {
  2486. throw EOSExtException(FMTLOAD(CHANGE_DIR_ERROR, (Directory)));
  2487. }
  2488. }
  2489. //---------------------------------------------------------------------------
  2490. void __fastcall TManagementScript::ExitProc(TScriptProcParams * /*Parameters*/)
  2491. {
  2492. FContinue = false;
  2493. }
  2494. //---------------------------------------------------------------------------
  2495. void __fastcall TManagementScript::OpenProc(TScriptProcParams * Parameters)
  2496. {
  2497. Connect(Parameters->ParamCount > 0 ? Parameters->Param[1] : UnicodeString(),
  2498. Parameters, true);
  2499. }
  2500. //---------------------------------------------------------------------------
  2501. void __fastcall TManagementScript::CloseProc(TScriptProcParams * Parameters)
  2502. {
  2503. CheckSession();
  2504. TTerminal * ATerminal;
  2505. if (Parameters->ParamCount == 0)
  2506. {
  2507. ATerminal = FTerminal;
  2508. }
  2509. else
  2510. {
  2511. ATerminal = FindSession(Parameters->Param[1]);
  2512. }
  2513. DoClose(ATerminal);
  2514. }
  2515. //---------------------------------------------------------------------------
  2516. void __fastcall TManagementScript::SessionProc(TScriptProcParams * Parameters)
  2517. {
  2518. CheckSession();
  2519. if (Parameters->ParamCount == 0)
  2520. {
  2521. for (int i = 0; i < FTerminalList->Count; i++)
  2522. {
  2523. PrintLine(FORMAT(L"%3d %s",
  2524. (i + 1, FTerminalList->Terminals[i]->SessionData->SessionName)));
  2525. }
  2526. PrintActiveSession();
  2527. }
  2528. else
  2529. {
  2530. FTerminal = FindSession(Parameters->Param[1]);
  2531. PrintActiveSession();
  2532. }
  2533. }
  2534. //---------------------------------------------------------------------------
  2535. void __fastcall TManagementScript::LPwdProc(TScriptProcParams * /*Parameters*/)
  2536. {
  2537. PrintLine(GetCurrentDir());
  2538. }
  2539. //---------------------------------------------------------------------------
  2540. void __fastcall TManagementScript::LCdProc(TScriptProcParams * Parameters)
  2541. {
  2542. DebugAssert(Parameters->ParamCount == 1);
  2543. DoChangeLocalDirectory(Parameters->Param[1]);
  2544. PrintLine(GetCurrentDir());
  2545. }
  2546. //---------------------------------------------------------------------------
  2547. void __fastcall TManagementScript::LLsProc(TScriptProcParams * Parameters)
  2548. {
  2549. UnicodeString Directory;
  2550. UnicodeString Mask;
  2551. if (Parameters->ParamCount > 0)
  2552. {
  2553. Directory = Parameters->Param[1];
  2554. Mask = ExtractFileName(Directory);
  2555. if (TFileMasks::IsMask(Mask))
  2556. {
  2557. Directory = ExtractFilePath(Directory);
  2558. }
  2559. else
  2560. {
  2561. Mask = L"";
  2562. }
  2563. }
  2564. if (Directory.IsEmpty())
  2565. {
  2566. Directory = GetCurrentDir();
  2567. }
  2568. if (Mask.IsEmpty())
  2569. {
  2570. Mask = L"*.*";
  2571. }
  2572. TSearchRecChecked SearchRec;
  2573. int FindAttrs = faReadOnly | faHidden | faSysFile | faDirectory | faArchive;
  2574. if (FindFirstUnchecked(IncludeTrailingBackslash(Directory) + Mask, FindAttrs, SearchRec) != 0)
  2575. {
  2576. NoMatch(Mask, ListingSysErrorMessage());
  2577. }
  2578. else
  2579. {
  2580. try
  2581. {
  2582. UnicodeString TimeFormat = FixedLenDateTimeFormat(FormatSettings.ShortTimeFormat);
  2583. UnicodeString DateFormat = FixedLenDateTimeFormat(FormatSettings.ShortDateFormat);
  2584. int DateLen = 0;
  2585. int TimeLen = 0;
  2586. bool First = true;
  2587. do
  2588. {
  2589. if (SearchRec.Name != L".")
  2590. {
  2591. TDateTime DateTime = SearchRec.TimeStamp;
  2592. UnicodeString TimeStr = FormatDateTime(TimeFormat, DateTime);
  2593. UnicodeString DateStr = FormatDateTime(DateFormat, DateTime);
  2594. if (First)
  2595. {
  2596. if (TimeLen < TimeStr.Length())
  2597. {
  2598. TimeLen = TimeStr.Length();
  2599. }
  2600. if (DateLen < DateStr.Length())
  2601. {
  2602. DateLen = DateStr.Length();
  2603. }
  2604. First = false;
  2605. }
  2606. UnicodeString SizeStr;
  2607. if (FLAGSET(SearchRec.Attr, faDirectory))
  2608. {
  2609. SizeStr = L"<DIR>";
  2610. }
  2611. else
  2612. {
  2613. SizeStr = FORMAT(L"%14.0n", (double(SearchRec.Size)));
  2614. }
  2615. PrintLine(FORMAT(L"%-*s %-*s %-14s %s", (
  2616. DateLen, DateStr, TimeLen, TimeStr, SizeStr, SearchRec.Name)));
  2617. }
  2618. }
  2619. while (FindNextChecked(SearchRec) == 0);
  2620. }
  2621. __finally
  2622. {
  2623. FindClose(SearchRec);
  2624. }
  2625. }
  2626. }
  2627. //---------------------------------------------------------------------------
  2628. void __fastcall TManagementScript::ReflectSettings()
  2629. {
  2630. for (int i = 0; i < FTerminalList->Count; i++)
  2631. {
  2632. FTerminalList->Terminals[i]->ReflectSettings();
  2633. }
  2634. }
  2635. //---------------------------------------------------------------------------