Script.cpp 87 KB

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