Script.cpp 88 KB

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