Script.cpp 87 KB

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