Script.cpp 53 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897
  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. // only modified, implicit
  1275. StoredSessions->Save(false, false);
  1276. }
  1277. }
  1278. }
  1279. FTerminalList->FreeTerminal(Terminal);
  1280. }
  1281. //---------------------------------------------------------------------------
  1282. void __fastcall TManagementScript::Input(const AnsiString Prompt,
  1283. AnsiString & Str, bool AllowEmpty)
  1284. {
  1285. do
  1286. {
  1287. Str = "";
  1288. if (FOnInput != NULL)
  1289. {
  1290. FOnInput(this, Prompt, Str);
  1291. }
  1292. else
  1293. {
  1294. Abort();
  1295. }
  1296. }
  1297. while (Str.Trim().IsEmpty() && !AllowEmpty);
  1298. }
  1299. //---------------------------------------------------------------------------
  1300. void __fastcall TManagementScript::PrintProgress(bool First, const AnsiString Str)
  1301. {
  1302. if (FOnPrintProgress != NULL)
  1303. {
  1304. FOnPrintProgress(this, First, Str);
  1305. }
  1306. }
  1307. //---------------------------------------------------------------------------
  1308. void __fastcall TManagementScript::ResetTransfer()
  1309. {
  1310. TScript::ResetTransfer();
  1311. FLastProgressFile = "";
  1312. FLastProgressTime = 0;
  1313. FLastProgressMessage = "";
  1314. }
  1315. //---------------------------------------------------------------------------
  1316. bool __fastcall TManagementScript::QueryCancel()
  1317. {
  1318. bool Result = false;
  1319. if (OnQueryCancel != NULL)
  1320. {
  1321. OnQueryCancel(this, Result);
  1322. }
  1323. return Result;
  1324. }
  1325. //---------------------------------------------------------------------------
  1326. void __fastcall TManagementScript::TerminalInformation(TTerminal * Terminal,
  1327. const AnsiString & Str, bool /*Status*/, bool /*Active*/)
  1328. {
  1329. assert(Terminal != NULL);
  1330. if (Terminal->Status == ssOpening)
  1331. {
  1332. PrintLine(Str);
  1333. }
  1334. }
  1335. //---------------------------------------------------------------------------
  1336. void __fastcall TManagementScript::TerminalPromptUser(TTerminal * Terminal,
  1337. AnsiString Prompt, TPromptKind Kind, AnsiString & Response, bool & Result,
  1338. void * Arg)
  1339. {
  1340. if ((!Terminal->StoredCredentialsTried || (Kind == pkPrompt)) &&
  1341. (OnTerminalPromptUser != NULL))
  1342. {
  1343. OnTerminalPromptUser(Terminal, Prompt, Kind, Response, Result, Arg);
  1344. }
  1345. }
  1346. //---------------------------------------------------------------------------
  1347. bool __fastcall TManagementScript::Synchronizing()
  1348. {
  1349. return (FKeepingUpToDate || (FSynchronizeMode >= 0));
  1350. }
  1351. //---------------------------------------------------------------------------
  1352. void __fastcall TManagementScript::ShowPendingProgress()
  1353. {
  1354. if (!FSynchronizeIntro.IsEmpty())
  1355. {
  1356. if (Synchronizing())
  1357. {
  1358. PrintLine(FSynchronizeIntro);
  1359. }
  1360. FSynchronizeIntro = "";
  1361. }
  1362. }
  1363. //---------------------------------------------------------------------------
  1364. void __fastcall TManagementScript::TerminalOperationProgress(
  1365. TFileOperationProgressType & ProgressData, TCancelStatus & Cancel)
  1366. {
  1367. if (ProgressData.Operation == foCopy)
  1368. {
  1369. if (ProgressData.InProgress && !ProgressData.FileName.IsEmpty())
  1370. {
  1371. bool DoPrint = false;
  1372. bool First = false;
  1373. AnsiString ProgressFileName = ProgressData.FileName;
  1374. if (ProgressData.Side == osLocal)
  1375. {
  1376. ProgressFileName = ExcludeTrailingBackslash(ProgressFileName);
  1377. }
  1378. else
  1379. {
  1380. ProgressFileName = UnixExcludeTrailingBackslash(ProgressFileName);
  1381. }
  1382. if (ProgressFileName != FLastProgressFile)
  1383. {
  1384. First = true;
  1385. DoPrint = true;
  1386. ShowPendingProgress();
  1387. }
  1388. if (!DoPrint && ((FLastProgressTime != time(NULL)) || ProgressData.IsTransferDone()))
  1389. {
  1390. DoPrint = true;
  1391. }
  1392. if (DoPrint)
  1393. {
  1394. static int MaxFileName = 25;
  1395. AnsiString FileName = MinimizeName(ProgressFileName, MaxFileName,
  1396. ProgressData.Side == osRemote);
  1397. AnsiString ProgressMessage = FORMAT("%-*.*s | %10d kB | %6.1f kB/s | %-6.6s | %3d%%",
  1398. (MaxFileName, MaxFileName, FileName,
  1399. static_cast<int>(ProgressData.TransferedSize / 1024),
  1400. static_cast<float>(ProgressData.CPS()) / 1024,
  1401. ProgressData.AsciiTransfer ? "ascii" : "binary",
  1402. ProgressData.TransferProgress()));
  1403. if (FLastProgressMessage != ProgressMessage)
  1404. {
  1405. FLastProgressTime = time(NULL);
  1406. PrintProgress(First, ProgressMessage);
  1407. FLastProgressMessage = ProgressMessage;
  1408. FLastProgressFile = ProgressFileName;
  1409. }
  1410. }
  1411. }
  1412. else
  1413. {
  1414. FLastProgressFile = "";
  1415. }
  1416. }
  1417. if (QueryCancel())
  1418. {
  1419. Cancel = csCancel;
  1420. }
  1421. }
  1422. //---------------------------------------------------------------------------
  1423. void __fastcall TManagementScript::TerminalOperationFinished(
  1424. TFileOperation Operation, TOperationSide /*Side*/,
  1425. bool /*Temp*/, const AnsiString FileName, Boolean Success,
  1426. bool & /*DisconnectWhenComplete*/)
  1427. {
  1428. if (Success && (Operation != foCalculateSize) && (Operation != foCopy))
  1429. {
  1430. ShowPendingProgress();
  1431. // For FKeepingUpToDate we should send events to synchronize controller eventuelly.
  1432. if (Synchronizing() && (Operation == foDelete))
  1433. {
  1434. // Note that this is duplicated with "keep up to date" log.
  1435. PrintLine(FMTLOAD(SCRIPT_SYNCHRONIZE_DELETED, (FileName)));
  1436. }
  1437. else
  1438. {
  1439. PrintLine(FileName);
  1440. }
  1441. }
  1442. }
  1443. //---------------------------------------------------------------------------
  1444. void __fastcall TManagementScript::TerminalSynchronizeDirectory(
  1445. const AnsiString LocalDirectory, const AnsiString RemoteDirectory,
  1446. bool & Continue, bool /*Collect*/)
  1447. {
  1448. int SynchronizeMode = FSynchronizeMode;
  1449. if (FKeepingUpToDate)
  1450. {
  1451. SynchronizeMode = TTerminal::smRemote;
  1452. }
  1453. AnsiString Arrow;
  1454. switch (SynchronizeMode)
  1455. {
  1456. case TTerminal::smRemote:
  1457. Arrow = "=>";
  1458. break;
  1459. case TTerminal::smLocal:
  1460. Arrow = "<=";
  1461. break;
  1462. case TTerminal::smBoth:
  1463. Arrow = "<=>";
  1464. break;
  1465. }
  1466. FSynchronizeIntro = FMTLOAD(SCRIPT_SYNCHRONIZE, (ExcludeTrailingBackslash(LocalDirectory),
  1467. Arrow, UnixExcludeTrailingBackslash(RemoteDirectory)));
  1468. if (QueryCancel())
  1469. {
  1470. Continue = false;
  1471. }
  1472. }
  1473. //---------------------------------------------------------------------------
  1474. TTerminal * __fastcall TManagementScript::FindSession(const AnsiString Index)
  1475. {
  1476. int i = StrToIntDef(Index, -1);
  1477. if ((i <= 0) || (i > FTerminalList->Count))
  1478. {
  1479. throw Exception(FMTLOAD(SCRIPT_SESSION_INDEX_INVALID, (Index)));
  1480. }
  1481. else
  1482. {
  1483. return FTerminalList->Terminals[i - 1];
  1484. }
  1485. }
  1486. //---------------------------------------------------------------------------
  1487. void __fastcall TManagementScript::PrintActiveSession()
  1488. {
  1489. assert(FTerminal != NULL);
  1490. PrintLine(FMTLOAD(SCRIPT_ACTIVE_SESSION,
  1491. (FTerminalList->IndexOf(FTerminal) + 1, FTerminal->SessionData->SessionName)));
  1492. }
  1493. //---------------------------------------------------------------------------
  1494. bool __fastcall TManagementScript::HandleExtendedException(Exception * E,
  1495. TTerminal * Terminal)
  1496. {
  1497. bool Result = TScript::HandleExtendedException(E);
  1498. if (Terminal == NULL)
  1499. {
  1500. Terminal = FTerminal;
  1501. }
  1502. if ((Terminal != NULL) && (Terminal == FTerminal) && (dynamic_cast<EFatal*>(E) != NULL))
  1503. {
  1504. try
  1505. {
  1506. DoClose(Terminal);
  1507. }
  1508. catch(...)
  1509. {
  1510. // ignore disconnect errors
  1511. }
  1512. }
  1513. return Result;
  1514. }
  1515. //---------------------------------------------------------------------------
  1516. void __fastcall TManagementScript::Connect(const AnsiString Session)
  1517. {
  1518. try
  1519. {
  1520. DoConnect(Session);
  1521. }
  1522. catch(Exception & E)
  1523. {
  1524. if (!HandleExtendedException(&E))
  1525. {
  1526. throw;
  1527. }
  1528. }
  1529. }
  1530. //---------------------------------------------------------------------------
  1531. void __fastcall TManagementScript::DoConnect(const AnsiString Session)
  1532. {
  1533. bool DefaultsOnly;
  1534. TSessionData * Data = FStoredSessions->ParseUrl(Session, DefaultsOnly,
  1535. puDecodeUrlChars, NULL);
  1536. try
  1537. {
  1538. assert(Data != NULL);
  1539. if (!Data->CanLogin || DefaultsOnly)
  1540. {
  1541. if (Data->HostName.IsEmpty())
  1542. {
  1543. AnsiString Value;
  1544. Input(LoadStr(SCRIPT_HOST_PROMPT), Value, false);
  1545. Data->HostName = Value;
  1546. }
  1547. assert(Data->CanLogin);
  1548. }
  1549. TTerminal * Terminal = FTerminalList->NewTerminal(Data);
  1550. try
  1551. {
  1552. Terminal->AutoReadDirectory = false;
  1553. Terminal->OnInformation = TerminalInformation;
  1554. Terminal->OnPromptUser = TerminalPromptUser;
  1555. Terminal->OnShowExtendedException = OnShowExtendedException;
  1556. Terminal->OnQueryUser = OnTerminalQueryUser;
  1557. Terminal->OnProgress = TerminalOperationProgress;
  1558. Terminal->OnFinished = TerminalOperationFinished;
  1559. ConnectTerminal(Terminal);
  1560. }
  1561. catch(...)
  1562. {
  1563. FTerminalList->FreeTerminal(Terminal);
  1564. throw;
  1565. }
  1566. FTerminal = Terminal;
  1567. }
  1568. __finally
  1569. {
  1570. delete Data;
  1571. }
  1572. PrintActiveSession();
  1573. }
  1574. //---------------------------------------------------------------------------
  1575. void __fastcall TManagementScript::DoClose(TTerminal * Terminal)
  1576. {
  1577. int Index = FTerminalList->IndexOf(Terminal);
  1578. assert(Index >= 0);
  1579. try
  1580. {
  1581. if (Terminal->Active)
  1582. {
  1583. Terminal->Close();
  1584. }
  1585. AnsiString SessionName = Terminal->SessionData->SessionName;
  1586. FreeTerminal(Terminal);
  1587. PrintLine(FMTLOAD(SCRIPT_SESSION_CLOSED, (SessionName)));
  1588. }
  1589. __finally
  1590. {
  1591. if (FTerminalList->Count > 0)
  1592. {
  1593. if (Index < FTerminalList->Count)
  1594. {
  1595. FTerminal = FTerminalList->Terminals[Index];
  1596. }
  1597. else
  1598. {
  1599. FTerminal = FTerminalList->Terminals[0];
  1600. }
  1601. PrintActiveSession();
  1602. }
  1603. else
  1604. {
  1605. FTerminal = NULL;
  1606. PrintLine(LoadStr(SCRIPT_NO_SESSION));
  1607. }
  1608. }
  1609. }
  1610. //---------------------------------------------------------------------------
  1611. void __fastcall TManagementScript::ExitProc(TScriptProcParams * /*Parameters*/)
  1612. {
  1613. FContinue = false;
  1614. }
  1615. //---------------------------------------------------------------------------
  1616. void __fastcall TManagementScript::OpenProc(TScriptProcParams * Parameters)
  1617. {
  1618. Connect(Parameters->ParamCount > 0 ? Parameters->Param[0] : AnsiString());
  1619. }
  1620. //---------------------------------------------------------------------------
  1621. void __fastcall TManagementScript::CloseProc(TScriptProcParams * Parameters)
  1622. {
  1623. CheckSession();
  1624. TTerminal * Terminal;
  1625. if (Parameters->ParamCount == 0)
  1626. {
  1627. Terminal = FTerminal;
  1628. }
  1629. else
  1630. {
  1631. Terminal = FindSession(Parameters->Param[0]);
  1632. }
  1633. DoClose(Terminal);
  1634. }
  1635. //---------------------------------------------------------------------------
  1636. void __fastcall TManagementScript::SessionProc(TScriptProcParams * Parameters)
  1637. {
  1638. CheckSession();
  1639. if (Parameters->ParamCount == 0)
  1640. {
  1641. for (int i = 0; i < FTerminalList->Count; i++)
  1642. {
  1643. PrintLine(FORMAT("%3d %s",
  1644. (i + 1, FTerminalList->Terminals[i]->SessionData->SessionName)));
  1645. }
  1646. PrintActiveSession();
  1647. }
  1648. else
  1649. {
  1650. FTerminal = FindSession(Parameters->Param[0]);
  1651. PrintActiveSession();
  1652. }
  1653. }
  1654. //---------------------------------------------------------------------------
  1655. void __fastcall TManagementScript::LPwdProc(TScriptProcParams * /*Parameters*/)
  1656. {
  1657. PrintLine(GetCurrentDir());
  1658. }
  1659. //---------------------------------------------------------------------------
  1660. void __fastcall TManagementScript::LCdProc(TScriptProcParams * Parameters)
  1661. {
  1662. assert(Parameters->ParamCount == 1);
  1663. AnsiString Directory = Parameters->Param[0];
  1664. if (!SetCurrentDir(Directory))
  1665. {
  1666. throw Exception(FMTLOAD(CHANGE_DIR_ERROR, (Directory)));
  1667. }
  1668. PrintLine(GetCurrentDir());
  1669. }
  1670. //---------------------------------------------------------------------------
  1671. void __fastcall TManagementScript::LLsProc(TScriptProcParams * Parameters)
  1672. {
  1673. AnsiString Directory;
  1674. AnsiString Mask;
  1675. if (Parameters->ParamCount > 0)
  1676. {
  1677. Directory = Parameters->Param[0];
  1678. Mask = ExtractFileName(Directory);
  1679. if (TFileMasks::IsMask(Mask))
  1680. {
  1681. Directory = ExtractFilePath(Directory);
  1682. }
  1683. else
  1684. {
  1685. Mask = "";
  1686. }
  1687. }
  1688. if (Directory.IsEmpty())
  1689. {
  1690. Directory = GetCurrentDir();
  1691. }
  1692. if (Mask.IsEmpty())
  1693. {
  1694. Mask = "*.*";
  1695. }
  1696. TSearchRec SearchRec;
  1697. int FindAttrs = faReadOnly | faHidden | faSysFile | faDirectory | faArchive;
  1698. if (FindFirst(IncludeTrailingBackslash(Directory) + Mask, FindAttrs, SearchRec) != 0)
  1699. {
  1700. throw Exception(FMTLOAD(LIST_DIR_ERROR, (Directory)));
  1701. }
  1702. try
  1703. {
  1704. AnsiString TimeFormat = FixedLenDateTimeFormat(ShortTimeFormat);
  1705. AnsiString DateFormat = FixedLenDateTimeFormat(ShortDateFormat);
  1706. int DateLen = 0;
  1707. int TimeLen = 0;
  1708. bool First = true;
  1709. do
  1710. {
  1711. if (SearchRec.Name != ".")
  1712. {
  1713. TDateTime DateTime = FileDateToDateTime(SearchRec.Time);
  1714. AnsiString TimeStr = FormatDateTime(TimeFormat, DateTime);
  1715. AnsiString DateStr = FormatDateTime(DateFormat, DateTime);
  1716. if (First)
  1717. {
  1718. if (TimeLen < TimeStr.Length())
  1719. {
  1720. TimeLen = TimeStr.Length();
  1721. }
  1722. if (DateLen < DateStr.Length())
  1723. {
  1724. DateLen = DateStr.Length();
  1725. }
  1726. First = false;
  1727. }
  1728. PrintLine(FORMAT("%-*s %-*s %-14s %s", (
  1729. DateLen, DateStr, TimeLen, TimeStr,
  1730. (FLAGSET(SearchRec.Attr, faDirectory) ?
  1731. AnsiString("<DIR>") : FORMAT("%14.0n", (double(SearchRec.Size)))),
  1732. SearchRec.Name)));
  1733. }
  1734. }
  1735. while (FindNext(SearchRec) == 0);
  1736. }
  1737. __finally
  1738. {
  1739. FindClose(SearchRec);
  1740. }
  1741. }
  1742. //---------------------------------------------------------------------------