1
0

Script.cpp 88 KB

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