Script.cpp 52 KB

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