Script.cpp 92 KB

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