1
0

Script.cpp 91 KB

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