Script.cpp 86 KB

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