Script.cpp 53 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896
  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. __fastcall TScriptProcParams::TScriptProcParams(TStrings * Params,
  16. const AnsiString & ParamsStr)
  17. {
  18. FParams = Params;
  19. FParamsStr = ParamsStr;
  20. FSkipParams = 0;
  21. FArg = 0;
  22. }
  23. //---------------------------------------------------------------------------
  24. void __fastcall TScriptProcParams::SkipParam()
  25. {
  26. assert(FSkipParams < FParams->Count);
  27. FSkipParams++;
  28. }
  29. //---------------------------------------------------------------------------
  30. int __fastcall TScriptProcParams::GetParamCount()
  31. {
  32. return (FSkipParams > FParams->Count ? 0 : FParams->Count - FSkipParams);
  33. }
  34. //---------------------------------------------------------------------------
  35. AnsiString __fastcall TScriptProcParams::GetParam(int Index)
  36. {
  37. return FParams->Strings[FSkipParams + Index];
  38. }
  39. //---------------------------------------------------------------------------
  40. //---------------------------------------------------------------------------
  41. class TScriptCommands : TStringList
  42. {
  43. public:
  44. typedef void __fastcall (__closure *TCommandProc)(TScriptProcParams * Parameters);
  45. __fastcall TScriptCommands();
  46. virtual __fastcall ~TScriptCommands();
  47. void __fastcall Execute(TScriptProcParams * Parameters);
  48. void __fastcall Execute(TStrings * Tokens, AnsiString Params);
  49. void __fastcall Register(const char * Command,
  50. const AnsiString Description, const AnsiString Help, TCommandProc Proc,
  51. int MinParams, int MaxParams, void * Arg = NULL);
  52. void __fastcall Register(const char * Command,
  53. int Description, int Help, TCommandProc Proc,
  54. int MinParams, int MaxParams, void * Arg = NULL);
  55. void __fastcall Register(const char * Command, TCommandProc Proc,
  56. int MinParams, int MaxParams, void * Arg = NULL);
  57. bool __fastcall Info(const AnsiString Command,
  58. AnsiString * Description, AnsiString * Help);
  59. bool __fastcall Enumerate(int Index,
  60. AnsiString * Command, AnsiString * Description, AnsiString * Help);
  61. static int __fastcall FindCommand(TStrings * Commands, const AnsiString Command,
  62. AnsiString * Matches = NULL);
  63. static int __fastcall FindCommand(const char ** Commands, size_t Count,
  64. const AnsiString Command, AnsiString * Matches = NULL);
  65. __property TCommandProc DefaultProc = { read = FDefaultProc, write = FDefaultProc };
  66. protected:
  67. TCommandProc FDefaultProc;
  68. struct TScriptCommand
  69. {
  70. AnsiString Description;
  71. AnsiString Help;
  72. TCommandProc Proc;
  73. int MinParams;
  74. int MaxParams;
  75. void * Arg;
  76. };
  77. };
  78. //---------------------------------------------------------------------------
  79. __fastcall TScriptCommands::TScriptCommands()
  80. {
  81. Sorted = true;
  82. CaseSensitive = false;
  83. FDefaultProc = NULL;
  84. }
  85. //---------------------------------------------------------------------------
  86. __fastcall TScriptCommands::~TScriptCommands()
  87. {
  88. for (int Index = 0; Index < Count; Index++)
  89. {
  90. delete reinterpret_cast<TScriptCommand *>(Objects[Index]);
  91. }
  92. }
  93. //---------------------------------------------------------------------------
  94. void __fastcall TScriptCommands::Register(const char * Command,
  95. const AnsiString Description, const AnsiString Help, TCommandProc Proc,
  96. int MinParams, int MaxParams, void * Arg)
  97. {
  98. TScriptCommand * ScriptCommand = new TScriptCommand;
  99. ScriptCommand->Description = Description;
  100. ScriptCommand->Help = Help;
  101. ScriptCommand->Proc = Proc;
  102. ScriptCommand->MinParams = MinParams;
  103. ScriptCommand->MaxParams = MaxParams;
  104. ScriptCommand->Arg = Arg;
  105. AddObject(Command, reinterpret_cast<TObject *>(ScriptCommand));
  106. }
  107. //---------------------------------------------------------------------------
  108. void __fastcall TScriptCommands::Register(const char * Command,
  109. int Description, int Help, TCommandProc Proc,
  110. int MinParams, int MaxParams, void * Arg)
  111. {
  112. AnsiString ADescription;
  113. if (Description > 0)
  114. {
  115. ADescription = LoadStr(Description);
  116. }
  117. AnsiString AHelp;
  118. if (Help > 0)
  119. {
  120. AHelp = LoadStr(Help, 10240);
  121. }
  122. Register(Command, ADescription, AHelp,
  123. Proc, MinParams, MaxParams, Arg);
  124. }
  125. //---------------------------------------------------------------------------
  126. void __fastcall TScriptCommands::Register(const char * Command, TCommandProc Proc,
  127. int MinParams, int MaxParams, void * Arg)
  128. {
  129. Register(Command, "", "", Proc, MinParams, MaxParams, Arg);
  130. }
  131. //---------------------------------------------------------------------------
  132. bool __fastcall TScriptCommands::Info(const AnsiString Command,
  133. AnsiString * Description, AnsiString * Help)
  134. {
  135. int Index = FindCommand(this, Command);
  136. bool Result = (Index >= 0);
  137. if (Result)
  138. {
  139. TScriptCommand * ScriptCommand = reinterpret_cast<TScriptCommand *>(Objects[Index]);
  140. if (Description != NULL)
  141. {
  142. *Description = ScriptCommand->Description;
  143. }
  144. if (Help != NULL)
  145. {
  146. *Help = ScriptCommand->Help;
  147. }
  148. }
  149. return Result;
  150. }
  151. //---------------------------------------------------------------------------
  152. bool __fastcall TScriptCommands::Enumerate(int Index,
  153. AnsiString * Command, AnsiString * Description, AnsiString * Help)
  154. {
  155. bool Result = (Index < Count);
  156. if (Result)
  157. {
  158. TScriptCommand * ScriptCommand = reinterpret_cast<TScriptCommand *>(Objects[Index]);
  159. if (Command != NULL)
  160. {
  161. *Command = Strings[Index];
  162. }
  163. if (Description != NULL)
  164. {
  165. *Description = ScriptCommand->Description;
  166. }
  167. if (Help != NULL)
  168. {
  169. *Help = ScriptCommand->Help;
  170. }
  171. }
  172. return Result;
  173. }
  174. //---------------------------------------------------------------------------
  175. int __fastcall TScriptCommands::FindCommand(TStrings * Commands,
  176. const AnsiString Command, AnsiString * Matches)
  177. {
  178. int Result = Commands->IndexOf(Command);
  179. if (Result < 0)
  180. {
  181. int MatchesCount = 0;
  182. for (int i = 0; i < Commands->Count; i++)
  183. {
  184. if ((Command.Length() <= Commands->Strings[i].Length()) &&
  185. SameText(Command, Commands->Strings[i].SubString(1, Command.Length())))
  186. {
  187. if (Matches != NULL)
  188. {
  189. if (!Matches->IsEmpty())
  190. {
  191. *Matches += ", ";
  192. }
  193. *Matches += Commands->Strings[i];
  194. }
  195. MatchesCount++;
  196. Result = i;
  197. }
  198. }
  199. if (MatchesCount == 0)
  200. {
  201. Result = -1;
  202. }
  203. else if (MatchesCount > 1)
  204. {
  205. Result = -2;
  206. }
  207. }
  208. return Result;
  209. }
  210. //---------------------------------------------------------------------------
  211. int __fastcall TScriptCommands::FindCommand(const char ** Commands, size_t Count,
  212. const AnsiString Command, AnsiString * Matches)
  213. {
  214. int Result;
  215. TStringList * Strings = new TStringList;
  216. try
  217. {
  218. Strings->CaseSensitive = false;
  219. for (unsigned int i = 0; i < Count; i++)
  220. {
  221. Strings->Add(Commands[i]);
  222. }
  223. Result = FindCommand(Strings, Command, Matches);
  224. }
  225. __finally
  226. {
  227. delete Strings;
  228. }
  229. return Result;
  230. }
  231. //---------------------------------------------------------------------------
  232. void __fastcall TScriptCommands::Execute(TScriptProcParams * Parameters)
  233. {
  234. assert(Parameters->ParamCount > 0);
  235. AnsiString Command = Parameters->Param[0];
  236. AnsiString Matches;
  237. int Index = FindCommand(this, Command, &Matches);
  238. if (Index == -2)
  239. {
  240. throw Exception(FMTLOAD(SCRIPT_COMMAND_AMBIGUOUS, (Command, Matches)));
  241. }
  242. else if (Index < 0)
  243. {
  244. throw Exception(FMTLOAD(SCRIPT_COMMAND_UNKNOWN, (Command)));
  245. }
  246. TScriptCommand * ScriptCommand = reinterpret_cast<TScriptCommand *>(Objects[Index]);
  247. Command = Strings[Index];
  248. Parameters->SkipParam();
  249. Parameters->Arg = ScriptCommand->Arg;
  250. if (Parameters->ParamCount < ScriptCommand->MinParams)
  251. {
  252. throw Exception(FMTLOAD(SCRIPT_MISSING_PARAMS, (Command)));
  253. }
  254. else if ((ScriptCommand->MaxParams >= 0) && (Parameters->ParamCount > ScriptCommand->MaxParams))
  255. {
  256. throw Exception(FMTLOAD(SCRIPT_TOO_MANY_PARAMS, (Command)));
  257. }
  258. else
  259. {
  260. ScriptCommand->Proc(Parameters);
  261. }
  262. }
  263. //---------------------------------------------------------------------------
  264. void __fastcall TScriptCommands::Execute(TStrings * Tokens, AnsiString Params)
  265. {
  266. TScriptProcParams * Parameters = new TScriptProcParams(Tokens, Params);
  267. try
  268. {
  269. Execute(Parameters);
  270. }
  271. __finally
  272. {
  273. delete Parameters;
  274. }
  275. }
  276. //---------------------------------------------------------------------------
  277. //---------------------------------------------------------------------------
  278. __fastcall TScript::TScript()
  279. {
  280. FTerminal = NULL;
  281. Init();
  282. }
  283. //---------------------------------------------------------------------------
  284. __fastcall TScript::~TScript()
  285. {
  286. delete FCommands;
  287. }
  288. //---------------------------------------------------------------------------
  289. __fastcall TScript::TScript(TTerminal * Terminal)
  290. {
  291. FTerminal = Terminal;
  292. Init();
  293. }
  294. //---------------------------------------------------------------------------
  295. void __fastcall TScript::Init()
  296. {
  297. FBatch = BatchOff;
  298. FConfirm = true;
  299. FEcho = false;
  300. FSynchronizeParams = 0;
  301. FOnPrint = NULL;
  302. FOnTerminalSynchronizeDirectory = NULL;
  303. FOnSynchronizeStartStop = NULL;
  304. FSynchronizeMode = -1;
  305. FKeepingUpToDate = false;
  306. FCommands = new TScriptCommands;
  307. FCommands->Register(";", 0, 0, &DummyProc, 0, -1);
  308. FCommands->Register("#", 0, 0, &DummyProc, 0, -1);
  309. FCommands->Register("help", SCRIPT_HELP_DESC, SCRIPT_HELP_HELP, &HelpProc, 0, -1);
  310. FCommands->Register("man", 0, SCRIPT_HELP_HELP, &HelpProc, 0, -1);
  311. FCommands->Register("call", SCRIPT_CALL_DESC, SCRIPT_CALL_HELP, &CallProc, 1, -1);
  312. FCommands->Register("!", 0, SCRIPT_CALL_HELP, &CallProc, 1, -1);
  313. FCommands->Register("pwd", SCRIPT_PWD_DESC, SCRIPT_PWD_HELP, &PwdProc, 0, 0);
  314. FCommands->Register("cd", SCRIPT_CD_DESC, SCRIPT_CD_HELP, &CdProc, 0, 1);
  315. FCommands->Register("ls", SCRIPT_LS_DESC, SCRIPT_LS_HELP, &LsProc, 0, 1);
  316. FCommands->Register("dir", 0, SCRIPT_LS_HELP, &LsProc, 0, 1);
  317. FCommands->Register("rm", SCRIPT_RM_DESC, SCRIPT_RM_HELP, &RmProc, 1, -1);
  318. FCommands->Register("rmdir", SCRIPT_RMDIR_DESC, SCRIPT_RMDIR_HELP, &RmDirProc, 1, -1);
  319. FCommands->Register("mv", SCRIPT_MV_DESC, SCRIPT_MV_HELP, &MvProc, 2, -1);
  320. FCommands->Register("rename", 0, SCRIPT_MV_HELP, &MvProc, 2, -1);
  321. FCommands->Register("chmod", SCRIPT_CHMOD_DESC, SCRIPT_CHMOD_HELP, &ChModProc, 2, -1);
  322. FCommands->Register("ln", SCRIPT_LN_DESC, SCRIPT_LN_HELP, &LnProc, 2, 2);
  323. FCommands->Register("symlink", 0, SCRIPT_LN_HELP, &LnProc, 2, 2);
  324. FCommands->Register("mkdir", SCRIPT_MKDIR_DESC, SCRIPT_MKDIR_HELP, &MkDirProc, 1, 1);
  325. FCommands->Register("get", SCRIPT_GET_DESC, SCRIPT_GET_HELP, &GetProc, 1, -1);
  326. FCommands->Register("recv", 0, SCRIPT_GET_HELP, &GetProc, 1, -1);
  327. FCommands->Register("put", SCRIPT_PUT_DESC, SCRIPT_PUT_HELP, &PutProc, 1, -1);
  328. FCommands->Register("send", 0, SCRIPT_PUT_HELP, &PutProc, 1, -1);
  329. FCommands->Register("option", SCRIPT_OPTION_DESC, SCRIPT_OPTION_HELP4, &OptionProc, -1, 2);
  330. FCommands->Register("ascii", 0, SCRIPT_OPTION_HELP4, &AsciiProc, 0, 0);
  331. FCommands->Register("binary", 0, SCRIPT_OPTION_HELP4, &BinaryProc, 0, 0);
  332. FCommands->Register("synchronize", SCRIPT_SYNCHRONIZE_DESC, SCRIPT_SYNCHRONIZE_HELP, &SynchronizeProc, 1, 3);
  333. FCommands->Register("keepuptodate", SCRIPT_KEEPUPTODATE_DESC, SCRIPT_KEEPUPTODATE_HELP, &KeepUpToDateProc, 0, 2);
  334. }
  335. //---------------------------------------------------------------------------
  336. void __fastcall TScript::SetCopyParam(const TCopyParamType & value)
  337. {
  338. FCopyParam.Assign(&value);
  339. }
  340. //---------------------------------------------------------------------------
  341. void __fastcall TScript::SetSynchronizeParams(int value)
  342. {
  343. FSynchronizeParams = (value &
  344. (TTerminal::spDelete | TTerminal::spExistingOnly | TTerminal::spTimestamp |
  345. TTerminal::spNotByTime | TTerminal::spBySize));
  346. }
  347. //---------------------------------------------------------------------------
  348. void __fastcall TScript::Command(const AnsiString Cmd)
  349. {
  350. try
  351. {
  352. if (FEcho)
  353. {
  354. PrintLine(Cmd);
  355. }
  356. TStrings * Tokens = new TStringList();
  357. try
  358. {
  359. AnsiString AllButFirst;
  360. Tokenize(Cmd, Tokens, AllButFirst);
  361. if (Tokens->Count > 0)
  362. {
  363. FCommands->Execute(Tokens, AllButFirst);
  364. }
  365. }
  366. __finally
  367. {
  368. delete Tokens;
  369. }
  370. }
  371. catch(Exception & E)
  372. {
  373. if (!HandleExtendedException(&E))
  374. {
  375. throw;
  376. }
  377. }
  378. }
  379. //---------------------------------------------------------------------------
  380. void __fastcall TScript::Tokenize(const AnsiString Str, TStrings * Tokens,
  381. AnsiString & AllButFirst)
  382. {
  383. assert(Tokens->Count == 0);
  384. // inspired by Putty's sftp_getcmd() from PSFTP.C
  385. int Index = 1;
  386. while (Index <= Str.Length())
  387. {
  388. while ((Index <= Str.Length()) &&
  389. ((Str[Index] == ' ') || (Str[Index] == '\t')))
  390. {
  391. Index++;
  392. }
  393. if (Tokens->Count == 1)
  394. {
  395. AllButFirst = Str.SubString(Index, Str.Length() - Index + 1);
  396. }
  397. if (Index <= Str.Length())
  398. {
  399. bool Quoting = false;
  400. AnsiString Token;
  401. while (Index <= Str.Length())
  402. {
  403. if (!Quoting && ((Str[Index] == ' ') || (Str[Index] == '\t')))
  404. {
  405. break;
  406. }
  407. else if ((Str[Index] == '"') && (Index + 1 <= Str.Length()) &&
  408. (Str[Index + 1] == '"'))
  409. {
  410. Index += 2;
  411. Token += '"';
  412. }
  413. else if (Str[Index] == '"')
  414. {
  415. Index++;
  416. Quoting = !Quoting;
  417. }
  418. else
  419. {
  420. Token += Str[Index];
  421. Index++;
  422. }
  423. }
  424. if (Index <= Str.Length())
  425. {
  426. Index++;
  427. }
  428. Tokens->Add(Token);
  429. }
  430. }
  431. }
  432. //---------------------------------------------------------------------------
  433. TStrings * __fastcall TScript::CreateFileList(TScriptProcParams * Parameters, int Start,
  434. int End, TFileListType ListType)
  435. {
  436. TStrings * Result = new TStringList();
  437. TStrings * FileLists = NULL;
  438. try
  439. {
  440. try
  441. {
  442. for (int i = Start; i <= End; i++)
  443. {
  444. AnsiString FileName = Parameters->Param[i];
  445. if (FLAGSET(ListType, fltDirectories))
  446. {
  447. TRemoteFile * File = new TRemoteFile();
  448. File->FileName = FileName;
  449. File->Type = FILETYPE_DIRECTORY;
  450. Result->AddObject(FileName, File);
  451. }
  452. else if (FLAGSET(ListType, fltMask) && TFileMasks::IsMask(FileName))
  453. {
  454. AnsiString FileDirectory = UnixExtractFilePath(FileName);
  455. AnsiString Directory = FileDirectory;
  456. if (Directory.IsEmpty())
  457. {
  458. Directory = UnixIncludeTrailingBackslash(FTerminal->CurrentDirectory);
  459. }
  460. TRemoteFileList * FileList = NULL;
  461. if (FileLists != NULL)
  462. {
  463. int Index = FileLists->IndexOf(Directory);
  464. if (Index > 0)
  465. {
  466. FileList = dynamic_cast<TRemoteFileList *>(FileLists->Objects[Index]);
  467. }
  468. }
  469. if (FileList == NULL)
  470. {
  471. FileList = FTerminal->ReadDirectoryListing(Directory, false);
  472. if (FileLists == NULL)
  473. {
  474. FileLists = new TStringList();
  475. }
  476. FileLists->AddObject(Directory, FileList);
  477. }
  478. AnsiString Mask = UnixExtractFileName(FileName);
  479. for (int i = 0; i < FileList->Count; i++)
  480. {
  481. TRemoteFile * File = FileList->Files[i];
  482. if (!File->IsThisDirectory && !File->IsParentDirectory &&
  483. TFileMasks::SingleMaskMatch(Mask, File->FileName))
  484. {
  485. Result->AddObject(FileDirectory + File->FileName,
  486. FLAGSET(ListType, fltQueryServer) ? File->Duplicate() : NULL);
  487. }
  488. }
  489. }
  490. else
  491. {
  492. TRemoteFile * File = NULL;
  493. if (FLAGSET(ListType, fltQueryServer))
  494. {
  495. FTerminal->ExceptionOnFail = true;
  496. try
  497. {
  498. FTerminal->ReadFile(FileName, File);
  499. if (!File->HaveFullFileName)
  500. {
  501. File->FullFileName = FileName;
  502. }
  503. }
  504. __finally
  505. {
  506. FTerminal->ExceptionOnFail = false;
  507. }
  508. }
  509. Result->AddObject(FileName, File);
  510. }
  511. }
  512. }
  513. catch(...)
  514. {
  515. FreeFileList(Result);
  516. throw;
  517. }
  518. }
  519. __finally
  520. {
  521. if (FileLists != NULL)
  522. {
  523. for (int i = 0; i < FileLists->Count; i++)
  524. {
  525. delete FileLists->Objects[i];
  526. }
  527. delete FileLists;
  528. }
  529. }
  530. return Result;
  531. }
  532. //---------------------------------------------------------------------------
  533. TStrings * __fastcall TScript::CreateLocalFileList(TScriptProcParams * Parameters,
  534. int Start, int End, TFileListType ListType)
  535. {
  536. TStrings * Result = new TStringList();
  537. try
  538. {
  539. for (int i = Start; i <= End; i++)
  540. {
  541. AnsiString FileName = Parameters->Param[i];
  542. if (FLAGSET(ListType, fltMask))
  543. {
  544. TSearchRec SearchRec;
  545. int FindAttrs = faReadOnly | faHidden | faSysFile | faDirectory | faArchive;
  546. if (FindFirst(FileName, FindAttrs, SearchRec) == 0)
  547. {
  548. AnsiString Directory = ExtractFilePath(FileName);
  549. try
  550. {
  551. do
  552. {
  553. if ((SearchRec.Name != ".") && (SearchRec.Name != ".."))
  554. {
  555. Result->Add(Directory + SearchRec.Name);
  556. }
  557. }
  558. while (FindNext(SearchRec) == 0);
  559. }
  560. __finally
  561. {
  562. FindClose(SearchRec);
  563. }
  564. }
  565. else
  566. {
  567. // not match, let it fail latter however
  568. Result->Add(FileName);
  569. }
  570. }
  571. else
  572. {
  573. Result->Add(FileName);
  574. }
  575. }
  576. }
  577. catch(...)
  578. {
  579. delete Result;
  580. throw;
  581. }
  582. return Result;
  583. }
  584. //---------------------------------------------------------------------------
  585. void __fastcall TScript::FreeFileList(TStrings * FileList)
  586. {
  587. for (int i = 0; i < FileList->Count; i++)
  588. {
  589. if (FileList->Objects[i] != NULL)
  590. {
  591. TRemoteFile * File = dynamic_cast<TRemoteFile *>(FileList->Objects[i]);
  592. delete File;
  593. }
  594. }
  595. delete FileList;
  596. }
  597. //---------------------------------------------------------------------------
  598. void __fastcall TScript::ConnectTerminal(TTerminal * Terminal)
  599. {
  600. Terminal->Open();
  601. }
  602. //---------------------------------------------------------------------------
  603. void __fastcall TScript::Print(const AnsiString Str)
  604. {
  605. if (FOnPrint != NULL)
  606. {
  607. FOnPrint(this, Str);
  608. }
  609. }
  610. //---------------------------------------------------------------------------
  611. void __fastcall TScript::PrintLine(const AnsiString Str)
  612. {
  613. Print(Str + "\n");
  614. }
  615. //---------------------------------------------------------------------------
  616. bool __fastcall TScript::HandleExtendedException(Exception * E, TTerminal * Terminal)
  617. {
  618. bool Result = (OnShowExtendedException != NULL);
  619. if (Result)
  620. {
  621. if (Terminal == NULL)
  622. {
  623. Terminal = FTerminal;
  624. }
  625. OnShowExtendedException(Terminal, E, NULL);
  626. }
  627. return Result;
  628. }
  629. //---------------------------------------------------------------------------
  630. void __fastcall TScript::CheckSession()
  631. {
  632. if (FTerminal == NULL)
  633. {
  634. throw Exception(LoadStr(SCRIPT_NO_SESSION));
  635. }
  636. }
  637. //---------------------------------------------------------------------------
  638. void __fastcall TScript::ResetTransfer()
  639. {
  640. }
  641. //---------------------------------------------------------------------------
  642. bool __fastcall TScript::EnsureCommandSessionFallback(TFSCapability Capability)
  643. {
  644. bool Result = FTerminal->IsCapable[Capability] ||
  645. FTerminal->CommandSessionOpened;
  646. if (!Result)
  647. {
  648. try
  649. {
  650. ConnectTerminal(FTerminal->CommandSession);
  651. Result = true;
  652. }
  653. catch(Exception & E)
  654. {
  655. HandleExtendedException(&E, FTerminal->CommandSession);
  656. Result = false;
  657. }
  658. }
  659. return Result;
  660. }
  661. //---------------------------------------------------------------------------
  662. void __fastcall TScript::SecondaryProc(TScriptProcParams * Parameters)
  663. {
  664. TScriptCommands * Commands = static_cast<TScriptCommands *>(Parameters->Arg);
  665. assert(Commands != NULL);
  666. if (Parameters->ParamCount == 0)
  667. {
  668. assert(Commands->DefaultProc != NULL);
  669. Commands->DefaultProc(Parameters);
  670. }
  671. else
  672. {
  673. Commands->Execute(Parameters);
  674. }
  675. }
  676. //---------------------------------------------------------------------------
  677. void __fastcall TScript::DummyProc(TScriptProcParams * /*Parameters*/)
  678. {
  679. // noop
  680. }
  681. //---------------------------------------------------------------------------
  682. void __fastcall TScript::HelpProc(TScriptProcParams * Parameters)
  683. {
  684. AnsiString Output;
  685. if (Parameters->ParamCount == 0)
  686. {
  687. AnsiString Command;
  688. AnsiString Description;
  689. int Index = 0;
  690. while (FCommands->Enumerate(Index, &Command, &Description, NULL))
  691. {
  692. if (!Description.IsEmpty())
  693. {
  694. Output += FORMAT("%-8s %s\n", (Command, Description));
  695. }
  696. Index++;
  697. }
  698. }
  699. else
  700. {
  701. for (int i = 0; i < Parameters->ParamCount; i++)
  702. {
  703. AnsiString Help;
  704. if (FCommands->Info(Parameters->Param[i], NULL, &Help))
  705. {
  706. Output += Help;
  707. }
  708. else
  709. {
  710. throw Exception(FMTLOAD(SCRIPT_COMMAND_UNKNOWN, (Parameters->Param[i])));
  711. }
  712. }
  713. }
  714. Print(Output);
  715. }
  716. //---------------------------------------------------------------------------
  717. void __fastcall TScript::CallProc(TScriptProcParams * Parameters)
  718. {
  719. CheckSession();
  720. if (EnsureCommandSessionFallback(fcAnyCommand))
  721. {
  722. FTerminal->AnyCommand(Parameters->ParamsStr, TerminalCaptureLog);
  723. }
  724. }
  725. //---------------------------------------------------------------------------
  726. void __fastcall TScript::TerminalCaptureLog(const AnsiString & AddedLine,
  727. bool /*StdError*/)
  728. {
  729. PrintLine(AddedLine);
  730. }
  731. //---------------------------------------------------------------------------
  732. void __fastcall TScript::PwdProc(TScriptProcParams * /*Parameters*/)
  733. {
  734. CheckSession();
  735. PrintLine(FTerminal->CurrentDirectory);
  736. }
  737. //---------------------------------------------------------------------------
  738. void __fastcall TScript::CdProc(TScriptProcParams * Parameters)
  739. {
  740. CheckSession();
  741. if (Parameters->ParamCount == 0)
  742. {
  743. FTerminal->HomeDirectory();
  744. }
  745. else
  746. {
  747. FTerminal->ChangeDirectory(Parameters->Param[0]);
  748. }
  749. PrintLine(FTerminal->CurrentDirectory);
  750. }
  751. //---------------------------------------------------------------------------
  752. void __fastcall TScript::LsProc(TScriptProcParams * Parameters)
  753. {
  754. CheckSession();
  755. AnsiString Directory;
  756. AnsiString Mask;
  757. if (Parameters->ParamCount > 0)
  758. {
  759. Directory = Parameters->Param[0];
  760. Mask = UnixExtractFileName(Directory);
  761. if (TFileMasks::IsMask(Mask))
  762. {
  763. Directory = UnixExtractFilePath(Directory);
  764. }
  765. else
  766. {
  767. Mask = "";
  768. }
  769. }
  770. if (Directory.IsEmpty())
  771. {
  772. Directory = FTerminal->CurrentDirectory;
  773. }
  774. TRemoteFileList * FileList = FTerminal->ReadDirectoryListing(Directory, false);
  775. try
  776. {
  777. for (int i = 0; i < FileList->Count; i++)
  778. {
  779. TRemoteFile * File = FileList->Files[i];
  780. if (Mask.IsEmpty() || TFileMasks::SingleMaskMatch(Mask, File->FileName))
  781. {
  782. PrintLine(FileList->Files[i]->ListingStr);
  783. }
  784. }
  785. }
  786. __finally
  787. {
  788. delete FileList;
  789. }
  790. }
  791. //---------------------------------------------------------------------------
  792. void __fastcall TScript::RmProc(TScriptProcParams * Parameters)
  793. {
  794. CheckSession();
  795. TStrings * FileList = CreateFileList(Parameters, 0, Parameters->ParamCount - 1, fltMask);
  796. try
  797. {
  798. FTerminal->DeleteFiles(FileList);
  799. }
  800. __finally
  801. {
  802. FreeFileList(FileList);
  803. }
  804. }
  805. //---------------------------------------------------------------------------
  806. void __fastcall TScript::RmDirProc(TScriptProcParams * Parameters)
  807. {
  808. CheckSession();
  809. TStrings * FileList = CreateFileList(Parameters, 0, Parameters->ParamCount - 1, fltDirectories);
  810. try
  811. {
  812. FTerminal->DeleteFiles(FileList);
  813. }
  814. __finally
  815. {
  816. FreeFileList(FileList);
  817. }
  818. }
  819. //---------------------------------------------------------------------------
  820. void __fastcall TScript::MvProc(TScriptProcParams * Parameters)
  821. {
  822. CheckSession();
  823. TStrings * FileList = CreateFileList(Parameters, 0, Parameters->ParamCount - 2,
  824. fltMask);
  825. try
  826. {
  827. assert(Parameters->ParamCount >= 1);
  828. AnsiString Target = Parameters->Param[Parameters->ParamCount - 1];
  829. AnsiString TargetDirectory = UnixExtractFilePath(Target);
  830. AnsiString FileMask = UnixExtractFileName(Target);
  831. FTerminal->MoveFiles(FileList, TargetDirectory, FileMask);
  832. }
  833. __finally
  834. {
  835. FreeFileList(FileList);
  836. }
  837. }
  838. //---------------------------------------------------------------------------
  839. void __fastcall TScript::ChModProc(TScriptProcParams * Parameters)
  840. {
  841. CheckSession();
  842. TStrings * FileList = CreateFileList(Parameters, 1, Parameters->ParamCount - 1,
  843. fltMask);
  844. try
  845. {
  846. TRemoteProperties Properties;
  847. Properties.Valid = TValidProperties() << vpRights;
  848. Properties.Rights.Octal = Parameters->Param[0];
  849. FTerminal->ChangeFilesProperties(FileList, &Properties);
  850. }
  851. __finally
  852. {
  853. FreeFileList(FileList);
  854. }
  855. }
  856. //---------------------------------------------------------------------------
  857. void __fastcall TScript::LnProc(TScriptProcParams * Parameters)
  858. {
  859. CheckSession();
  860. assert(Parameters->ParamCount == 2);
  861. FTerminal->CreateLink(Parameters->Param[1], Parameters->Param[0], true);
  862. }
  863. //---------------------------------------------------------------------------
  864. void __fastcall TScript::MkDirProc(TScriptProcParams * Parameters)
  865. {
  866. CheckSession();
  867. FTerminal->CreateDirectory(Parameters->Param[0]);
  868. }
  869. //---------------------------------------------------------------------------
  870. void __fastcall TScript::GetProc(TScriptProcParams * Parameters)
  871. {
  872. CheckSession();
  873. ResetTransfer();
  874. int LastFileParam = (Parameters->ParamCount == 1 ? 0 : Parameters->ParamCount - 2);
  875. TStrings * FileList = CreateFileList(Parameters, 0, LastFileParam,
  876. fltQueryServer | fltMask);
  877. try
  878. {
  879. TCopyParamType CopyParam = FCopyParam;
  880. CopyParam.CalculateSize = false;
  881. AnsiString TargetDirectory;
  882. if (Parameters->ParamCount == 1)
  883. {
  884. TargetDirectory = GetCurrentDir();
  885. CopyParam.FileMask = "";
  886. }
  887. else
  888. {
  889. AnsiString Target = Parameters->Param[Parameters->ParamCount - 1];
  890. TargetDirectory = ExtractFilePath(Target);
  891. if (TargetDirectory.IsEmpty())
  892. {
  893. TargetDirectory = GetCurrentDir();
  894. }
  895. CopyParam.FileMask = ExtractFileName(Target);
  896. }
  897. int Params = FLAGMASK(!FConfirm, cpNoConfirmation);
  898. FTerminal->CopyToLocal(FileList, TargetDirectory, &CopyParam, Params);
  899. }
  900. __finally
  901. {
  902. FreeFileList(FileList);
  903. }
  904. }
  905. //---------------------------------------------------------------------------
  906. void __fastcall TScript::PutProc(TScriptProcParams * Parameters)
  907. {
  908. CheckSession();
  909. ResetTransfer();
  910. int LastFileParam = (Parameters->ParamCount == 1 ? 0 : Parameters->ParamCount - 2);
  911. TStrings * FileList = CreateLocalFileList(Parameters, 0, LastFileParam, fltMask);
  912. try
  913. {
  914. TCopyParamType CopyParam = FCopyParam;
  915. CopyParam.CalculateSize = false;
  916. AnsiString TargetDirectory;
  917. if (Parameters->ParamCount == 1)
  918. {
  919. TargetDirectory = FTerminal->CurrentDirectory;
  920. CopyParam.FileMask = "";
  921. }
  922. else
  923. {
  924. AnsiString Target = Parameters->Param[Parameters->ParamCount - 1];
  925. TargetDirectory = UnixExtractFilePath(Target);
  926. if (TargetDirectory.IsEmpty())
  927. {
  928. TargetDirectory = FTerminal->CurrentDirectory;
  929. }
  930. CopyParam.FileMask = UnixExtractFileName(Target);
  931. }
  932. int Params = FLAGMASK(!FConfirm, cpNoConfirmation);
  933. FTerminal->CopyToRemote(FileList, TargetDirectory, &CopyParam, Params);
  934. }
  935. __finally
  936. {
  937. FreeFileList(FileList);
  938. }
  939. }
  940. //---------------------------------------------------------------------------
  941. void __fastcall TScript::OptionImpl(AnsiString OptionName, AnsiString ValueName)
  942. {
  943. enum { Echo, Batch, Confirm, Transfer, SynchDelete, Exclude, Include };
  944. static const char * Names[] = { "echo", "batch", "confirm", "transfer",
  945. "synchdelete", "exclude", "include" };
  946. enum { Off, On };
  947. static const char * ToggleNames[] = { "off", "on" };
  948. assert((BatchOff == 0) && (BatchOn == 1) && (BatchAbort == 2) && (BatchContinue == 3));
  949. static const char * BatchModeNames[] = { "off", "on", "abort", "continue" };
  950. assert((tmBinary == 0) && (tmAscii == 1) && (tmAutomatic == 2));
  951. static const char * TransferModeNames[] = { "binary", "ascii", "automatic" };
  952. int Option = -1;
  953. if (!OptionName.IsEmpty())
  954. {
  955. Option = TScriptCommands::FindCommand(Names, LENOF(Names), OptionName);
  956. if (Option < 0)
  957. {
  958. throw Exception(FMTLOAD(SCRIPT_OPTION_UNKNOWN, (OptionName)));
  959. }
  960. else
  961. {
  962. OptionName = Names[Option];
  963. }
  964. }
  965. #define OPT(OPT) ((Option < 0) || (Option == OPT))
  966. const char * ListFormat = "%-12s %-10s";
  967. bool SetValue = !ValueName.IsEmpty();
  968. if (OPT(Echo))
  969. {
  970. if (SetValue)
  971. {
  972. int Value = TScriptCommands::FindCommand(ToggleNames, LENOF(ToggleNames), ValueName);
  973. if (Value < 0)
  974. {
  975. throw Exception(FMTLOAD(SCRIPT_VALUE_UNKNOWN, (ValueName, OptionName)));
  976. }
  977. FEcho = (Value == On);
  978. }
  979. PrintLine(FORMAT(ListFormat, (Names[Echo], ToggleNames[FEcho ? On : Off])));
  980. }
  981. if (OPT(Batch))
  982. {
  983. if (SetValue)
  984. {
  985. int Value = TScriptCommands::FindCommand(BatchModeNames, LENOF(BatchModeNames), ValueName);
  986. if (Value < 0)
  987. {
  988. throw Exception(FMTLOAD(SCRIPT_VALUE_UNKNOWN, (ValueName, OptionName)));
  989. }
  990. FBatch = (TBatchMode)Value;
  991. }
  992. PrintLine(FORMAT(ListFormat, (Names[Batch], BatchModeNames[FBatch])));
  993. }
  994. if (OPT(Confirm))
  995. {
  996. if (SetValue)
  997. {
  998. int Value = TScriptCommands::FindCommand(ToggleNames, LENOF(ToggleNames), ValueName);
  999. if (Value < 0)
  1000. {
  1001. throw Exception(FMTLOAD(SCRIPT_VALUE_UNKNOWN, (ValueName, OptionName)));
  1002. }
  1003. FConfirm = (Value == On);
  1004. }
  1005. PrintLine(FORMAT(ListFormat, (Names[Confirm], ToggleNames[FConfirm ? On : Off])));
  1006. }
  1007. if (OPT(Transfer))
  1008. {
  1009. if (SetValue)
  1010. {
  1011. int Value = TScriptCommands::FindCommand(TransferModeNames,
  1012. LENOF(TransferModeNames), ValueName);
  1013. if (Value < 0)
  1014. {
  1015. throw Exception(FMTLOAD(SCRIPT_VALUE_UNKNOWN, (ValueName, OptionName)));
  1016. }
  1017. FCopyParam.TransferMode = (TTransferMode)Value;
  1018. }
  1019. assert(FCopyParam.TransferMode < LENOF(TransferModeNames));
  1020. const char * Value = TransferModeNames[FCopyParam.TransferMode];
  1021. PrintLine(FORMAT(ListFormat, (Names[Transfer], Value)));
  1022. }
  1023. if (OPT(SynchDelete))
  1024. {
  1025. if (SetValue)
  1026. {
  1027. int Value = TScriptCommands::FindCommand(ToggleNames, LENOF(ToggleNames), ValueName);
  1028. if (Value < 0)
  1029. {
  1030. throw Exception(FMTLOAD(SCRIPT_VALUE_UNKNOWN, (ValueName, OptionName)));
  1031. }
  1032. FSynchronizeParams =
  1033. (FSynchronizeParams & ~TTerminal::spDelete) |
  1034. FLAGMASK(Value == On, TTerminal::spDelete);
  1035. }
  1036. PrintLine(FORMAT(ListFormat, (Names[SynchDelete],
  1037. ToggleNames[FLAGSET(FSynchronizeParams, TTerminal::spDelete) ? On : Off])));
  1038. }
  1039. static const char * Clear = "clear";
  1040. if (OPT(Include))
  1041. {
  1042. if (SetValue)
  1043. {
  1044. FCopyParam.NegativeExclude = true;
  1045. FCopyParam.ExcludeFileMask =
  1046. (ValueName == Clear ? AnsiString() : ValueName);
  1047. }
  1048. if (SetValue ||
  1049. (FCopyParam.NegativeExclude && !FCopyParam.ExcludeFileMask.Masks.IsEmpty()))
  1050. {
  1051. PrintLine(FORMAT(ListFormat, (Names[Include], FCopyParam.ExcludeFileMask.Masks)));
  1052. }
  1053. }
  1054. if (OPT(Exclude))
  1055. {
  1056. if (SetValue)
  1057. {
  1058. FCopyParam.NegativeExclude = false;
  1059. FCopyParam.ExcludeFileMask =
  1060. (ValueName == Clear ? AnsiString() : ValueName);
  1061. }
  1062. if (SetValue ||
  1063. (!FCopyParam.NegativeExclude && !FCopyParam.ExcludeFileMask.Masks.IsEmpty()))
  1064. {
  1065. PrintLine(FORMAT(ListFormat, (Names[Exclude], FCopyParam.ExcludeFileMask.Masks)));
  1066. }
  1067. }
  1068. #undef OPT
  1069. }
  1070. //---------------------------------------------------------------------------
  1071. void __fastcall TScript::OptionProc(TScriptProcParams * Parameters)
  1072. {
  1073. AnsiString OptionName;
  1074. AnsiString ValueName;
  1075. if (Parameters->ParamCount >= 1)
  1076. {
  1077. OptionName = Parameters->Param[0];
  1078. }
  1079. if (Parameters->ParamCount >= 2)
  1080. {
  1081. ValueName = Parameters->Param[1];
  1082. }
  1083. OptionImpl(OptionName, ValueName);
  1084. }
  1085. //---------------------------------------------------------------------------
  1086. void __fastcall TScript::AsciiProc(TScriptProcParams * /*Parameters*/)
  1087. {
  1088. OptionImpl("transfer", "ascii");
  1089. }
  1090. //---------------------------------------------------------------------------
  1091. void __fastcall TScript::BinaryProc(TScriptProcParams * /*Parameters*/)
  1092. {
  1093. OptionImpl("transfer", "binary");
  1094. }
  1095. //---------------------------------------------------------------------------
  1096. void __fastcall TScript::SynchronizeDirectories(TScriptProcParams * Parameters,
  1097. AnsiString & LocalDirectory, AnsiString & RemoteDirectory, int FirstParam)
  1098. {
  1099. if (Parameters->ParamCount > FirstParam)
  1100. {
  1101. LocalDirectory = Parameters->Param[FirstParam];
  1102. }
  1103. else
  1104. {
  1105. LocalDirectory = GetCurrentDir();
  1106. }
  1107. if (Parameters->ParamCount > FirstParam + 1)
  1108. {
  1109. RemoteDirectory = Parameters->Param[FirstParam + 1];
  1110. }
  1111. else
  1112. {
  1113. RemoteDirectory = FTerminal->CurrentDirectory;
  1114. }
  1115. }
  1116. //---------------------------------------------------------------------------
  1117. void __fastcall TScript::SynchronizeProc(TScriptProcParams * Parameters)
  1118. {
  1119. CheckSession();
  1120. ResetTransfer();
  1121. static const char * ModeNames[] = { "remote", "local", "both" };
  1122. AnsiString ModeName = Parameters->Param[0];
  1123. assert(FSynchronizeMode < 0);
  1124. FSynchronizeMode = TScriptCommands::FindCommand(ModeNames, LENOF(ModeNames), ModeName);
  1125. try
  1126. {
  1127. if (FSynchronizeMode < 0)
  1128. {
  1129. throw Exception(FMTLOAD(SCRIPT_OPTION_UNKNOWN, (ModeName)));
  1130. }
  1131. AnsiString LocalDirectory;
  1132. AnsiString RemoteDirectory;
  1133. SynchronizeDirectories(Parameters, LocalDirectory, RemoteDirectory, 1);
  1134. TCopyParamType CopyParam = FCopyParam;
  1135. CopyParam.CalculateSize = false;
  1136. int SynchronizeParams = FSynchronizeParams | TTerminal::spNoConfirmation;
  1137. PrintLine(FMTLOAD(SCRIPT_SYNCHRONIZE_COLLECT,
  1138. (ExcludeTrailingBackslash(LocalDirectory),
  1139. UnixExcludeTrailingBackslash(RemoteDirectory))));
  1140. TSynchronizeChecklist * Checklist =
  1141. FTerminal->SynchronizeCollect(LocalDirectory, RemoteDirectory,
  1142. static_cast<TTerminal::TSynchronizeMode>(FSynchronizeMode),
  1143. &CopyParam, SynchronizeParams, NULL, NULL);
  1144. try
  1145. {
  1146. if (Checklist->Count > 0)
  1147. {
  1148. FTerminal->SynchronizeApply(Checklist, LocalDirectory, RemoteDirectory,
  1149. &CopyParam, SynchronizeParams, OnTerminalSynchronizeDirectory);
  1150. }
  1151. }
  1152. __finally
  1153. {
  1154. delete Checklist;
  1155. }
  1156. }
  1157. __finally
  1158. {
  1159. FSynchronizeMode = -1;
  1160. }
  1161. }
  1162. //---------------------------------------------------------------------------
  1163. void __fastcall TScript::Synchronize(const AnsiString LocalDirectory,
  1164. const AnsiString RemoteDirectory, const TCopyParamType & ACopyParam,
  1165. TSynchronizeChecklist ** Checklist)
  1166. {
  1167. try
  1168. {
  1169. FKeepingUpToDate = true;
  1170. TCopyParamType CopyParam = ACopyParam;
  1171. CopyParam.CalculateSize = false;
  1172. int SynchronizeParams = FSynchronizeParams | TTerminal::spNoConfirmation |
  1173. TTerminal::spNoRecurse | TTerminal::spUseCache | TTerminal::spDelayProgress |
  1174. TTerminal::spSubDirs;
  1175. TSynchronizeChecklist * AChecklist =
  1176. FTerminal->SynchronizeCollect(LocalDirectory, RemoteDirectory, TTerminal::smRemote,
  1177. &CopyParam, SynchronizeParams, NULL, NULL);
  1178. try
  1179. {
  1180. if (AChecklist->Count > 0)
  1181. {
  1182. FTerminal->SynchronizeApply(AChecklist, LocalDirectory, RemoteDirectory,
  1183. &CopyParam, SynchronizeParams, OnTerminalSynchronizeDirectory);
  1184. }
  1185. }
  1186. __finally
  1187. {
  1188. if (Checklist == NULL)
  1189. {
  1190. delete AChecklist;
  1191. }
  1192. else
  1193. {
  1194. *Checklist = AChecklist;
  1195. }
  1196. }
  1197. // to break line after the last transfer (if any);
  1198. Print("");
  1199. FKeepingUpToDate = false;
  1200. }
  1201. catch(Exception & E)
  1202. {
  1203. FKeepingUpToDate = false;
  1204. HandleExtendedException(&E);
  1205. throw;
  1206. }
  1207. }
  1208. //---------------------------------------------------------------------------
  1209. void __fastcall TScript::KeepUpToDateProc(TScriptProcParams * Parameters)
  1210. {
  1211. if (OnSynchronizeStartStop == NULL)
  1212. {
  1213. Abort();
  1214. }
  1215. CheckSession();
  1216. ResetTransfer();
  1217. AnsiString LocalDirectory;
  1218. AnsiString RemoteDirectory;
  1219. SynchronizeDirectories(Parameters, LocalDirectory, RemoteDirectory, 0);
  1220. PrintLine(LoadStr(SCRIPT_KEEPING_UP_TO_DATE));
  1221. OnSynchronizeStartStop(this, LocalDirectory, RemoteDirectory);
  1222. }
  1223. //---------------------------------------------------------------------------
  1224. //---------------------------------------------------------------------------
  1225. __fastcall TManagementScript::TManagementScript(TStoredSessionList * StoredSessions) :
  1226. TScript()
  1227. {
  1228. assert(StoredSessions != NULL);
  1229. FOnInput = NULL;
  1230. FOnTerminalPromptUser = NULL;
  1231. FOnShowExtendedException = NULL;
  1232. FOnTerminalQueryUser = NULL;
  1233. FStoredSessions = StoredSessions;
  1234. FTerminalList = new TTerminalList(Configuration);
  1235. FOnQueryCancel = NULL;
  1236. FContinue = true;
  1237. OnTerminalSynchronizeDirectory = TerminalSynchronizeDirectory;
  1238. FCommands->Register("exit", SCRIPT_EXIT_DESC, SCRIPT_EXIT_HELP, &ExitProc, 0, 0);
  1239. FCommands->Register("bye", 0, SCRIPT_EXIT_HELP, &ExitProc, 0, 0);
  1240. FCommands->Register("open", SCRIPT_OPEN_DESC, SCRIPT_OPEN_HELP, &OpenProc, 0, 1);
  1241. FCommands->Register("close", SCRIPT_CLOSE_DESC, SCRIPT_CLOSE_HELP, &CloseProc, 0, 1);
  1242. FCommands->Register("session", SCRIPT_SESSION_DESC, SCRIPT_SESSION_HELP, &SessionProc, 0, 1);
  1243. FCommands->Register("lpwd", SCRIPT_LPWD_DESC, SCRIPT_LPWD_HELP, &LPwdProc, 0, 0);
  1244. FCommands->Register("lcd", SCRIPT_LCD_DESC, SCRIPT_LCD_HELP, &LCdProc, 1, 1);
  1245. FCommands->Register("lls", SCRIPT_LLS_DESC, SCRIPT_LLS_HELP, &LLsProc, 0, 1);
  1246. }
  1247. //---------------------------------------------------------------------------
  1248. __fastcall TManagementScript::~TManagementScript()
  1249. {
  1250. while (FTerminalList->Count > 0)
  1251. {
  1252. FreeTerminal(FTerminalList->Terminals[0]);
  1253. }
  1254. delete FTerminalList;
  1255. }
  1256. //---------------------------------------------------------------------------
  1257. void __fastcall TManagementScript::FreeTerminal(TTerminal * Terminal)
  1258. {
  1259. if (!Terminal->SessionData->Name.IsEmpty())
  1260. {
  1261. Terminal->SessionData->RemoteDirectory = Terminal->CurrentDirectory;
  1262. TSessionData * Data;
  1263. Data = (TSessionData *)StoredSessions->FindByName(Terminal->SessionData->Name);
  1264. if (Data != NULL)
  1265. {
  1266. bool Changed = false;
  1267. if (Terminal->SessionData->UpdateDirectories)
  1268. {
  1269. Data->RemoteDirectory = Terminal->SessionData->RemoteDirectory;
  1270. Changed = true;
  1271. }
  1272. if (Changed)
  1273. {
  1274. StoredSessions->Save();
  1275. }
  1276. }
  1277. }
  1278. FTerminalList->FreeTerminal(Terminal);
  1279. }
  1280. //---------------------------------------------------------------------------
  1281. void __fastcall TManagementScript::Input(const AnsiString Prompt,
  1282. AnsiString & Str, bool AllowEmpty)
  1283. {
  1284. do
  1285. {
  1286. Str = "";
  1287. if (FOnInput != NULL)
  1288. {
  1289. FOnInput(this, Prompt, Str);
  1290. }
  1291. else
  1292. {
  1293. Abort();
  1294. }
  1295. }
  1296. while (Str.Trim().IsEmpty() && !AllowEmpty);
  1297. }
  1298. //---------------------------------------------------------------------------
  1299. void __fastcall TManagementScript::PrintProgress(bool First, const AnsiString Str)
  1300. {
  1301. if (FOnPrintProgress != NULL)
  1302. {
  1303. FOnPrintProgress(this, First, Str);
  1304. }
  1305. }
  1306. //---------------------------------------------------------------------------
  1307. void __fastcall TManagementScript::ResetTransfer()
  1308. {
  1309. TScript::ResetTransfer();
  1310. FLastProgressFile = "";
  1311. FLastProgressTime = 0;
  1312. FLastProgressMessage = "";
  1313. }
  1314. //---------------------------------------------------------------------------
  1315. bool __fastcall TManagementScript::QueryCancel()
  1316. {
  1317. bool Result = false;
  1318. if (OnQueryCancel != NULL)
  1319. {
  1320. OnQueryCancel(this, Result);
  1321. }
  1322. return Result;
  1323. }
  1324. //---------------------------------------------------------------------------
  1325. void __fastcall TManagementScript::TerminalInformation(TTerminal * Terminal,
  1326. const AnsiString & Str, bool /*Status*/, bool /*Active*/)
  1327. {
  1328. assert(Terminal != NULL);
  1329. if (Terminal->Status == ssOpening)
  1330. {
  1331. PrintLine(Str);
  1332. }
  1333. }
  1334. //---------------------------------------------------------------------------
  1335. void __fastcall TManagementScript::TerminalPromptUser(TTerminal * Terminal,
  1336. AnsiString Prompt, TPromptKind Kind, AnsiString & Response, bool & Result,
  1337. void * Arg)
  1338. {
  1339. if ((!Terminal->StoredCredentialsTried || (Kind == pkPrompt)) &&
  1340. (OnTerminalPromptUser != NULL))
  1341. {
  1342. OnTerminalPromptUser(Terminal, Prompt, Kind, Response, Result, Arg);
  1343. }
  1344. }
  1345. //---------------------------------------------------------------------------
  1346. bool __fastcall TManagementScript::Synchronizing()
  1347. {
  1348. return (FKeepingUpToDate || (FSynchronizeMode >= 0));
  1349. }
  1350. //---------------------------------------------------------------------------
  1351. void __fastcall TManagementScript::ShowPendingProgress()
  1352. {
  1353. if (!FSynchronizeIntro.IsEmpty())
  1354. {
  1355. if (Synchronizing())
  1356. {
  1357. PrintLine(FSynchronizeIntro);
  1358. }
  1359. FSynchronizeIntro = "";
  1360. }
  1361. }
  1362. //---------------------------------------------------------------------------
  1363. void __fastcall TManagementScript::TerminalOperationProgress(
  1364. TFileOperationProgressType & ProgressData, TCancelStatus & Cancel)
  1365. {
  1366. if (ProgressData.Operation == foCopy)
  1367. {
  1368. if (ProgressData.InProgress && !ProgressData.FileName.IsEmpty())
  1369. {
  1370. bool DoPrint = false;
  1371. bool First = false;
  1372. AnsiString ProgressFileName = ProgressData.FileName;
  1373. if (ProgressData.Side == osLocal)
  1374. {
  1375. ProgressFileName = ExcludeTrailingBackslash(ProgressFileName);
  1376. }
  1377. else
  1378. {
  1379. ProgressFileName = UnixExcludeTrailingBackslash(ProgressFileName);
  1380. }
  1381. if (ProgressFileName != FLastProgressFile)
  1382. {
  1383. First = true;
  1384. DoPrint = true;
  1385. ShowPendingProgress();
  1386. }
  1387. if (!DoPrint && ((FLastProgressTime != time(NULL)) || ProgressData.IsTransferDone()))
  1388. {
  1389. DoPrint = true;
  1390. }
  1391. if (DoPrint)
  1392. {
  1393. static int MaxFileName = 25;
  1394. AnsiString FileName = MinimizeName(ProgressFileName, MaxFileName,
  1395. ProgressData.Side == osRemote);
  1396. AnsiString ProgressMessage = FORMAT("%-*.*s | %10d kB | %6.1f kB/s | %-6.6s | %3d%%",
  1397. (MaxFileName, MaxFileName, FileName,
  1398. static_cast<int>(ProgressData.TransferedSize / 1024),
  1399. static_cast<float>(ProgressData.CPS()) / 1024,
  1400. ProgressData.AsciiTransfer ? "ascii" : "binary",
  1401. ProgressData.TransferProgress()));
  1402. if (FLastProgressMessage != ProgressMessage)
  1403. {
  1404. FLastProgressTime = time(NULL);
  1405. PrintProgress(First, ProgressMessage);
  1406. FLastProgressMessage = ProgressMessage;
  1407. FLastProgressFile = ProgressFileName;
  1408. }
  1409. }
  1410. }
  1411. else
  1412. {
  1413. FLastProgressFile = "";
  1414. }
  1415. }
  1416. if (QueryCancel())
  1417. {
  1418. Cancel = csCancel;
  1419. }
  1420. }
  1421. //---------------------------------------------------------------------------
  1422. void __fastcall TManagementScript::TerminalOperationFinished(
  1423. TFileOperation Operation, TOperationSide /*Side*/,
  1424. bool /*Temp*/, const AnsiString FileName, Boolean Success,
  1425. bool & /*DisconnectWhenComplete*/)
  1426. {
  1427. if (Success && (Operation != foCalculateSize) && (Operation != foCopy))
  1428. {
  1429. ShowPendingProgress();
  1430. // For FKeepingUpToDate we should send events to synchronize controller eventuelly.
  1431. if (Synchronizing() && (Operation == foDelete))
  1432. {
  1433. // Note that this is duplicated with "keep up to date" log.
  1434. PrintLine(FMTLOAD(SCRIPT_SYNCHRONIZE_DELETED, (FileName)));
  1435. }
  1436. else
  1437. {
  1438. PrintLine(FileName);
  1439. }
  1440. }
  1441. }
  1442. //---------------------------------------------------------------------------
  1443. void __fastcall TManagementScript::TerminalSynchronizeDirectory(
  1444. const AnsiString LocalDirectory, const AnsiString RemoteDirectory,
  1445. bool & Continue, bool /*Collect*/)
  1446. {
  1447. int SynchronizeMode = FSynchronizeMode;
  1448. if (FKeepingUpToDate)
  1449. {
  1450. SynchronizeMode = TTerminal::smRemote;
  1451. }
  1452. AnsiString Arrow;
  1453. switch (SynchronizeMode)
  1454. {
  1455. case TTerminal::smRemote:
  1456. Arrow = "=>";
  1457. break;
  1458. case TTerminal::smLocal:
  1459. Arrow = "<=";
  1460. break;
  1461. case TTerminal::smBoth:
  1462. Arrow = "<=>";
  1463. break;
  1464. }
  1465. FSynchronizeIntro = FMTLOAD(SCRIPT_SYNCHRONIZE, (ExcludeTrailingBackslash(LocalDirectory),
  1466. Arrow, UnixExcludeTrailingBackslash(RemoteDirectory)));
  1467. if (QueryCancel())
  1468. {
  1469. Continue = false;
  1470. }
  1471. }
  1472. //---------------------------------------------------------------------------
  1473. TTerminal * __fastcall TManagementScript::FindSession(const AnsiString Index)
  1474. {
  1475. int i = StrToIntDef(Index, -1);
  1476. if ((i <= 0) || (i > FTerminalList->Count))
  1477. {
  1478. throw Exception(FMTLOAD(SCRIPT_SESSION_INDEX_INVALID, (Index)));
  1479. }
  1480. else
  1481. {
  1482. return FTerminalList->Terminals[i - 1];
  1483. }
  1484. }
  1485. //---------------------------------------------------------------------------
  1486. void __fastcall TManagementScript::PrintActiveSession()
  1487. {
  1488. assert(FTerminal != NULL);
  1489. PrintLine(FMTLOAD(SCRIPT_ACTIVE_SESSION,
  1490. (FTerminalList->IndexOf(FTerminal) + 1, FTerminal->SessionData->SessionName)));
  1491. }
  1492. //---------------------------------------------------------------------------
  1493. bool __fastcall TManagementScript::HandleExtendedException(Exception * E,
  1494. TTerminal * Terminal)
  1495. {
  1496. bool Result = TScript::HandleExtendedException(E);
  1497. if (Terminal == NULL)
  1498. {
  1499. Terminal = FTerminal;
  1500. }
  1501. if ((Terminal != NULL) && (Terminal == FTerminal) && (dynamic_cast<EFatal*>(E) != NULL))
  1502. {
  1503. try
  1504. {
  1505. DoClose(Terminal);
  1506. }
  1507. catch(...)
  1508. {
  1509. // ignore disconnect errors
  1510. }
  1511. }
  1512. return Result;
  1513. }
  1514. //---------------------------------------------------------------------------
  1515. void __fastcall TManagementScript::Connect(const AnsiString Session)
  1516. {
  1517. try
  1518. {
  1519. DoConnect(Session);
  1520. }
  1521. catch(Exception & E)
  1522. {
  1523. if (!HandleExtendedException(&E))
  1524. {
  1525. throw;
  1526. }
  1527. }
  1528. }
  1529. //---------------------------------------------------------------------------
  1530. void __fastcall TManagementScript::DoConnect(const AnsiString Session)
  1531. {
  1532. bool DefaultsOnly;
  1533. TSessionData * Data = FStoredSessions->ParseUrl(Session, DefaultsOnly,
  1534. puDecodeUrlChars, NULL);
  1535. try
  1536. {
  1537. assert(Data != NULL);
  1538. if (!Data->CanLogin || DefaultsOnly)
  1539. {
  1540. if (Data->HostName.IsEmpty())
  1541. {
  1542. AnsiString Value;
  1543. Input(LoadStr(SCRIPT_HOST_PROMPT), Value, false);
  1544. Data->HostName = Value;
  1545. }
  1546. assert(Data->CanLogin);
  1547. }
  1548. TTerminal * Terminal = FTerminalList->NewTerminal(Data);
  1549. try
  1550. {
  1551. Terminal->AutoReadDirectory = false;
  1552. Terminal->OnInformation = TerminalInformation;
  1553. Terminal->OnPromptUser = TerminalPromptUser;
  1554. Terminal->OnShowExtendedException = OnShowExtendedException;
  1555. Terminal->OnQueryUser = OnTerminalQueryUser;
  1556. Terminal->OnProgress = TerminalOperationProgress;
  1557. Terminal->OnFinished = TerminalOperationFinished;
  1558. ConnectTerminal(Terminal);
  1559. }
  1560. catch(...)
  1561. {
  1562. FTerminalList->FreeTerminal(Terminal);
  1563. throw;
  1564. }
  1565. FTerminal = Terminal;
  1566. }
  1567. __finally
  1568. {
  1569. delete Data;
  1570. }
  1571. PrintActiveSession();
  1572. }
  1573. //---------------------------------------------------------------------------
  1574. void __fastcall TManagementScript::DoClose(TTerminal * Terminal)
  1575. {
  1576. int Index = FTerminalList->IndexOf(Terminal);
  1577. assert(Index >= 0);
  1578. try
  1579. {
  1580. if (Terminal->Active)
  1581. {
  1582. Terminal->Close();
  1583. }
  1584. AnsiString SessionName = Terminal->SessionData->SessionName;
  1585. FreeTerminal(Terminal);
  1586. PrintLine(FMTLOAD(SCRIPT_SESSION_CLOSED, (SessionName)));
  1587. }
  1588. __finally
  1589. {
  1590. if (FTerminalList->Count > 0)
  1591. {
  1592. if (Index < FTerminalList->Count)
  1593. {
  1594. FTerminal = FTerminalList->Terminals[Index];
  1595. }
  1596. else
  1597. {
  1598. FTerminal = FTerminalList->Terminals[0];
  1599. }
  1600. PrintActiveSession();
  1601. }
  1602. else
  1603. {
  1604. FTerminal = NULL;
  1605. PrintLine(LoadStr(SCRIPT_NO_SESSION));
  1606. }
  1607. }
  1608. }
  1609. //---------------------------------------------------------------------------
  1610. void __fastcall TManagementScript::ExitProc(TScriptProcParams * /*Parameters*/)
  1611. {
  1612. FContinue = false;
  1613. }
  1614. //---------------------------------------------------------------------------
  1615. void __fastcall TManagementScript::OpenProc(TScriptProcParams * Parameters)
  1616. {
  1617. Connect(Parameters->ParamCount > 0 ? Parameters->Param[0] : AnsiString());
  1618. }
  1619. //---------------------------------------------------------------------------
  1620. void __fastcall TManagementScript::CloseProc(TScriptProcParams * Parameters)
  1621. {
  1622. CheckSession();
  1623. TTerminal * Terminal;
  1624. if (Parameters->ParamCount == 0)
  1625. {
  1626. Terminal = FTerminal;
  1627. }
  1628. else
  1629. {
  1630. Terminal = FindSession(Parameters->Param[0]);
  1631. }
  1632. DoClose(Terminal);
  1633. }
  1634. //---------------------------------------------------------------------------
  1635. void __fastcall TManagementScript::SessionProc(TScriptProcParams * Parameters)
  1636. {
  1637. CheckSession();
  1638. if (Parameters->ParamCount == 0)
  1639. {
  1640. for (int i = 0; i < FTerminalList->Count; i++)
  1641. {
  1642. PrintLine(FORMAT("%3d %s",
  1643. (i + 1, FTerminalList->Terminals[i]->SessionData->SessionName)));
  1644. }
  1645. PrintActiveSession();
  1646. }
  1647. else
  1648. {
  1649. FTerminal = FindSession(Parameters->Param[0]);
  1650. PrintActiveSession();
  1651. }
  1652. }
  1653. //---------------------------------------------------------------------------
  1654. void __fastcall TManagementScript::LPwdProc(TScriptProcParams * /*Parameters*/)
  1655. {
  1656. PrintLine(GetCurrentDir());
  1657. }
  1658. //---------------------------------------------------------------------------
  1659. void __fastcall TManagementScript::LCdProc(TScriptProcParams * Parameters)
  1660. {
  1661. assert(Parameters->ParamCount == 1);
  1662. AnsiString Directory = Parameters->Param[0];
  1663. if (!SetCurrentDir(Directory))
  1664. {
  1665. throw Exception(FMTLOAD(CHANGE_DIR_ERROR, (Directory)));
  1666. }
  1667. PrintLine(GetCurrentDir());
  1668. }
  1669. //---------------------------------------------------------------------------
  1670. void __fastcall TManagementScript::LLsProc(TScriptProcParams * Parameters)
  1671. {
  1672. AnsiString Directory;
  1673. AnsiString Mask;
  1674. if (Parameters->ParamCount > 0)
  1675. {
  1676. Directory = Parameters->Param[0];
  1677. Mask = ExtractFileName(Directory);
  1678. if (TFileMasks::IsMask(Mask))
  1679. {
  1680. Directory = ExtractFilePath(Directory);
  1681. }
  1682. else
  1683. {
  1684. Mask = "";
  1685. }
  1686. }
  1687. if (Directory.IsEmpty())
  1688. {
  1689. Directory = GetCurrentDir();
  1690. }
  1691. if (Mask.IsEmpty())
  1692. {
  1693. Mask = "*.*";
  1694. }
  1695. TSearchRec SearchRec;
  1696. int FindAttrs = faReadOnly | faHidden | faSysFile | faDirectory | faArchive;
  1697. if (FindFirst(IncludeTrailingBackslash(Directory) + Mask, FindAttrs, SearchRec) != 0)
  1698. {
  1699. throw Exception(FMTLOAD(LIST_DIR_ERROR, (Directory)));
  1700. }
  1701. try
  1702. {
  1703. AnsiString TimeFormat = FixedLenDateTimeFormat(ShortTimeFormat);
  1704. AnsiString DateFormat = FixedLenDateTimeFormat(ShortDateFormat);
  1705. int DateLen = 0;
  1706. int TimeLen = 0;
  1707. bool First = true;
  1708. do
  1709. {
  1710. if (SearchRec.Name != ".")
  1711. {
  1712. TDateTime DateTime = FileDateToDateTime(SearchRec.Time);
  1713. AnsiString TimeStr = FormatDateTime(TimeFormat, DateTime);
  1714. AnsiString DateStr = FormatDateTime(DateFormat, DateTime);
  1715. if (First)
  1716. {
  1717. if (TimeLen < TimeStr.Length())
  1718. {
  1719. TimeLen = TimeStr.Length();
  1720. }
  1721. if (DateLen < DateStr.Length())
  1722. {
  1723. DateLen = DateStr.Length();
  1724. }
  1725. First = false;
  1726. }
  1727. PrintLine(FORMAT("%-*s %-*s %-14s %s", (
  1728. DateLen, DateStr, TimeLen, TimeStr,
  1729. (FLAGSET(SearchRec.Attr, faDirectory) ?
  1730. AnsiString("<DIR>") : FORMAT("%14.0n", (double(SearchRec.Size)))),
  1731. SearchRec.Name)));
  1732. }
  1733. }
  1734. while (FindNext(SearchRec) == 0);
  1735. }
  1736. __finally
  1737. {
  1738. FindClose(SearchRec);
  1739. }
  1740. }
  1741. //---------------------------------------------------------------------------