Script.cpp 53 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867
  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. if (!File->HaveFullFileName)
  477. {
  478. File->FullFileName = FileName;
  479. }
  480. }
  481. __finally
  482. {
  483. FTerminal->ExceptionOnFail = false;
  484. }
  485. }
  486. Result->AddObject(FileName, File);
  487. }
  488. }
  489. }
  490. catch(...)
  491. {
  492. FreeFileList(Result);
  493. throw;
  494. }
  495. }
  496. __finally
  497. {
  498. if (FileLists != NULL)
  499. {
  500. for (int i = 0; i < FileLists->Count; i++)
  501. {
  502. delete FileLists->Objects[i];
  503. }
  504. delete FileLists;
  505. }
  506. }
  507. return Result;
  508. }
  509. //---------------------------------------------------------------------------
  510. TStrings * __fastcall TScript::CreateLocalFileList(TScriptProcParams * Parameters,
  511. int Start, int End, TFileListType ListType)
  512. {
  513. TStrings * Result = new TStringList();
  514. try
  515. {
  516. for (int i = Start; i <= End; i++)
  517. {
  518. AnsiString FileName = Parameters->Param[i];
  519. if (FLAGSET(ListType, fltMask))
  520. {
  521. TSearchRec SearchRec;
  522. int FindAttrs = faReadOnly | faHidden | faSysFile | faDirectory | faArchive;
  523. if (FindFirst(FileName, FindAttrs, SearchRec) == 0)
  524. {
  525. AnsiString Directory = ExtractFilePath(FileName);
  526. try
  527. {
  528. do
  529. {
  530. if ((SearchRec.Name != ".") && (SearchRec.Name != ".."))
  531. {
  532. Result->Add(Directory + SearchRec.Name);
  533. }
  534. }
  535. while (FindNext(SearchRec) == 0);
  536. }
  537. __finally
  538. {
  539. FindClose(SearchRec);
  540. }
  541. }
  542. else
  543. {
  544. // not match, let it fail latter however
  545. Result->Add(FileName);
  546. }
  547. }
  548. else
  549. {
  550. Result->Add(FileName);
  551. }
  552. }
  553. }
  554. catch(...)
  555. {
  556. delete Result;
  557. throw;
  558. }
  559. return Result;
  560. }
  561. //---------------------------------------------------------------------------
  562. void __fastcall TScript::FreeFileList(TStrings * FileList)
  563. {
  564. for (int i = 0; i < FileList->Count; i++)
  565. {
  566. if (FileList->Objects[i] != NULL)
  567. {
  568. TRemoteFile * File = dynamic_cast<TRemoteFile *>(FileList->Objects[i]);
  569. delete File;
  570. }
  571. }
  572. delete FileList;
  573. }
  574. //---------------------------------------------------------------------------
  575. void __fastcall TScript::ConnectTerminal(TTerminal * Terminal)
  576. {
  577. Terminal->Open();
  578. }
  579. //---------------------------------------------------------------------------
  580. void __fastcall TScript::Print(const AnsiString Str)
  581. {
  582. if (FOnPrint != NULL)
  583. {
  584. FOnPrint(this, Str);
  585. }
  586. }
  587. //---------------------------------------------------------------------------
  588. void __fastcall TScript::PrintLine(const AnsiString Str)
  589. {
  590. Print(Str + "\n");
  591. }
  592. //---------------------------------------------------------------------------
  593. bool __fastcall TScript::HandleExtendedException(Exception * E, TTerminal * Terminal)
  594. {
  595. bool Result = (OnShowExtendedException != NULL);
  596. if (Result)
  597. {
  598. if (Terminal == NULL)
  599. {
  600. Terminal = FTerminal;
  601. }
  602. OnShowExtendedException(Terminal, E, NULL);
  603. }
  604. return Result;
  605. }
  606. //---------------------------------------------------------------------------
  607. void __fastcall TScript::CheckSession()
  608. {
  609. if (FTerminal == NULL)
  610. {
  611. throw Exception(LoadStr(SCRIPT_NO_SESSION));
  612. }
  613. }
  614. //---------------------------------------------------------------------------
  615. void __fastcall TScript::ResetTransfer()
  616. {
  617. }
  618. //---------------------------------------------------------------------------
  619. bool __fastcall TScript::EnsureCommandSessionFallback(TFSCapability Capability)
  620. {
  621. bool Result = FTerminal->IsCapable[Capability] ||
  622. FTerminal->CommandSessionOpened;
  623. if (!Result)
  624. {
  625. try
  626. {
  627. ConnectTerminal(FTerminal->CommandSession);
  628. Result = true;
  629. }
  630. catch(Exception & E)
  631. {
  632. HandleExtendedException(&E, FTerminal->CommandSession);
  633. Result = false;
  634. }
  635. }
  636. return Result;
  637. }
  638. //---------------------------------------------------------------------------
  639. void __fastcall TScript::SecondaryProc(TScriptProcParams * Parameters)
  640. {
  641. TScriptCommands * Commands = static_cast<TScriptCommands *>(Parameters->Arg);
  642. assert(Commands != NULL);
  643. if (Parameters->ParamCount == 0)
  644. {
  645. assert(Commands->DefaultProc != NULL);
  646. Commands->DefaultProc(Parameters);
  647. }
  648. else
  649. {
  650. Commands->Execute(Parameters);
  651. }
  652. }
  653. //---------------------------------------------------------------------------
  654. void __fastcall TScript::DummyProc(TScriptProcParams * /*Parameters*/)
  655. {
  656. // noop
  657. }
  658. //---------------------------------------------------------------------------
  659. void __fastcall TScript::HelpProc(TScriptProcParams * Parameters)
  660. {
  661. AnsiString Output;
  662. if (Parameters->ParamCount == 0)
  663. {
  664. AnsiString Command;
  665. AnsiString Description;
  666. int Index = 0;
  667. while (FCommands->Enumerate(Index, &Command, &Description, NULL))
  668. {
  669. if (!Description.IsEmpty())
  670. {
  671. Output += FORMAT("%-8s %s\n", (Command, Description));
  672. }
  673. Index++;
  674. }
  675. }
  676. else
  677. {
  678. for (int i = 0; i < Parameters->ParamCount; i++)
  679. {
  680. AnsiString Help;
  681. if (FCommands->Info(Parameters->Param[i], NULL, &Help))
  682. {
  683. Output += Help;
  684. }
  685. else
  686. {
  687. throw Exception(FMTLOAD(SCRIPT_COMMAND_UNKNOWN, (Parameters->Param[i])));
  688. }
  689. }
  690. }
  691. Print(Output);
  692. }
  693. //---------------------------------------------------------------------------
  694. void __fastcall TScript::CallProc(TScriptProcParams * Parameters)
  695. {
  696. CheckSession();
  697. if (EnsureCommandSessionFallback(fcAnyCommand))
  698. {
  699. FTerminal->AnyCommand(Parameters->ParamsStr, TerminalCaptureLog);
  700. }
  701. }
  702. //---------------------------------------------------------------------------
  703. void __fastcall TScript::TerminalCaptureLog(TObject* /*Sender*/,
  704. TLogLineType Type, const AnsiString AddedLine)
  705. {
  706. USEDPARAM(Type);
  707. assert((Type == llOutput) || (Type == llStdError));
  708. PrintLine(AddedLine);
  709. }
  710. //---------------------------------------------------------------------------
  711. void __fastcall TScript::PwdProc(TScriptProcParams * /*Parameters*/)
  712. {
  713. CheckSession();
  714. PrintLine(FTerminal->CurrentDirectory);
  715. }
  716. //---------------------------------------------------------------------------
  717. void __fastcall TScript::CdProc(TScriptProcParams * Parameters)
  718. {
  719. CheckSession();
  720. if (Parameters->ParamCount == 0)
  721. {
  722. FTerminal->HomeDirectory();
  723. }
  724. else
  725. {
  726. FTerminal->ChangeDirectory(Parameters->Param[0]);
  727. }
  728. PrintLine(FTerminal->CurrentDirectory);
  729. }
  730. //---------------------------------------------------------------------------
  731. void __fastcall TScript::LsProc(TScriptProcParams * Parameters)
  732. {
  733. CheckSession();
  734. AnsiString Directory;
  735. AnsiString Mask;
  736. if (Parameters->ParamCount > 0)
  737. {
  738. Directory = Parameters->Param[0];
  739. Mask = UnixExtractFileName(Directory);
  740. if (TFileMasks::IsMask(Mask))
  741. {
  742. Directory = UnixExtractFilePath(Directory);
  743. }
  744. else
  745. {
  746. Mask = "";
  747. }
  748. }
  749. if (Directory.IsEmpty())
  750. {
  751. Directory = FTerminal->CurrentDirectory;
  752. }
  753. TRemoteFileList * FileList = FTerminal->ReadDirectoryListing(Directory, false);
  754. try
  755. {
  756. for (int i = 0; i < FileList->Count; i++)
  757. {
  758. TRemoteFile * File = FileList->Files[i];
  759. if (Mask.IsEmpty() || TFileMasks::SingleMaskMatch(Mask, File->FileName))
  760. {
  761. PrintLine(FileList->Files[i]->ListingStr);
  762. }
  763. }
  764. }
  765. __finally
  766. {
  767. delete FileList;
  768. }
  769. }
  770. //---------------------------------------------------------------------------
  771. void __fastcall TScript::RmProc(TScriptProcParams * Parameters)
  772. {
  773. CheckSession();
  774. TStrings * FileList = CreateFileList(Parameters, 0, Parameters->ParamCount - 1, fltMask);
  775. try
  776. {
  777. FTerminal->DeleteFiles(FileList);
  778. }
  779. __finally
  780. {
  781. FreeFileList(FileList);
  782. }
  783. }
  784. //---------------------------------------------------------------------------
  785. void __fastcall TScript::RmDirProc(TScriptProcParams * Parameters)
  786. {
  787. CheckSession();
  788. TStrings * FileList = CreateFileList(Parameters, 0, Parameters->ParamCount - 1, fltDirectories);
  789. try
  790. {
  791. FTerminal->DeleteFiles(FileList);
  792. }
  793. __finally
  794. {
  795. FreeFileList(FileList);
  796. }
  797. }
  798. //---------------------------------------------------------------------------
  799. void __fastcall TScript::MvProc(TScriptProcParams * Parameters)
  800. {
  801. CheckSession();
  802. TStrings * FileList = CreateFileList(Parameters, 0, Parameters->ParamCount - 2,
  803. fltMask);
  804. try
  805. {
  806. assert(Parameters->ParamCount >= 1);
  807. AnsiString Target = Parameters->Param[Parameters->ParamCount - 1];
  808. AnsiString TargetDirectory = UnixExtractFilePath(Target);
  809. AnsiString FileMask = UnixExtractFileName(Target);
  810. FTerminal->MoveFiles(FileList, TargetDirectory, FileMask);
  811. }
  812. __finally
  813. {
  814. FreeFileList(FileList);
  815. }
  816. }
  817. //---------------------------------------------------------------------------
  818. void __fastcall TScript::ChModProc(TScriptProcParams * Parameters)
  819. {
  820. CheckSession();
  821. TStrings * FileList = CreateFileList(Parameters, 1, Parameters->ParamCount - 1,
  822. fltMask);
  823. try
  824. {
  825. TRemoteProperties Properties;
  826. Properties.Valid = TValidProperties() << vpRights;
  827. Properties.Rights.Octal = Parameters->Param[0];
  828. FTerminal->ChangeFilesProperties(FileList, &Properties);
  829. }
  830. __finally
  831. {
  832. FreeFileList(FileList);
  833. }
  834. }
  835. //---------------------------------------------------------------------------
  836. void __fastcall TScript::LnProc(TScriptProcParams * Parameters)
  837. {
  838. CheckSession();
  839. assert(Parameters->ParamCount == 2);
  840. FTerminal->CreateLink(Parameters->Param[1], Parameters->Param[0], true);
  841. }
  842. //---------------------------------------------------------------------------
  843. void __fastcall TScript::MkDirProc(TScriptProcParams * Parameters)
  844. {
  845. CheckSession();
  846. FTerminal->CreateDirectory(Parameters->Param[0]);
  847. }
  848. //---------------------------------------------------------------------------
  849. void __fastcall TScript::GetProc(TScriptProcParams * Parameters)
  850. {
  851. CheckSession();
  852. ResetTransfer();
  853. int LastFileParam = (Parameters->ParamCount == 1 ? 0 : Parameters->ParamCount - 2);
  854. TStrings * FileList = CreateFileList(Parameters, 0, LastFileParam,
  855. fltQueryServer | fltMask);
  856. try
  857. {
  858. TCopyParamType CopyParam = FCopyParam;
  859. CopyParam.CalculateSize = false;
  860. AnsiString TargetDirectory;
  861. if (Parameters->ParamCount == 1)
  862. {
  863. TargetDirectory = GetCurrentDir();
  864. CopyParam.FileMask = "";
  865. }
  866. else
  867. {
  868. AnsiString Target = Parameters->Param[Parameters->ParamCount - 1];
  869. TargetDirectory = ExtractFilePath(Target);
  870. if (TargetDirectory.IsEmpty())
  871. {
  872. TargetDirectory = GetCurrentDir();
  873. }
  874. CopyParam.FileMask = ExtractFileName(Target);
  875. }
  876. int Params = FLAGMASK(!FConfirm, cpNoConfirmation);
  877. FTerminal->CopyToLocal(FileList, TargetDirectory, &CopyParam, Params);
  878. }
  879. __finally
  880. {
  881. FreeFileList(FileList);
  882. }
  883. }
  884. //---------------------------------------------------------------------------
  885. void __fastcall TScript::PutProc(TScriptProcParams * Parameters)
  886. {
  887. CheckSession();
  888. ResetTransfer();
  889. int LastFileParam = (Parameters->ParamCount == 1 ? 0 : Parameters->ParamCount - 2);
  890. TStrings * FileList = CreateLocalFileList(Parameters, 0, LastFileParam, fltMask);
  891. try
  892. {
  893. TCopyParamType CopyParam = FCopyParam;
  894. CopyParam.CalculateSize = false;
  895. AnsiString TargetDirectory;
  896. if (Parameters->ParamCount == 1)
  897. {
  898. TargetDirectory = FTerminal->CurrentDirectory;
  899. CopyParam.FileMask = "";
  900. }
  901. else
  902. {
  903. AnsiString Target = Parameters->Param[Parameters->ParamCount - 1];
  904. TargetDirectory = UnixExtractFilePath(Target);
  905. if (TargetDirectory.IsEmpty())
  906. {
  907. TargetDirectory = FTerminal->CurrentDirectory;
  908. }
  909. CopyParam.FileMask = UnixExtractFileName(Target);
  910. }
  911. int Params = FLAGMASK(!FConfirm, cpNoConfirmation);
  912. FTerminal->CopyToRemote(FileList, TargetDirectory, &CopyParam, Params);
  913. }
  914. __finally
  915. {
  916. FreeFileList(FileList);
  917. }
  918. }
  919. //---------------------------------------------------------------------------
  920. void __fastcall TScript::OptionImpl(AnsiString OptionName, AnsiString ValueName)
  921. {
  922. enum { Batch, Confirm, Transfer, SynchDelete, Exclude, Include };
  923. static const char * Names[] = { "batch", "confirm", "transfer", "synchdelete",
  924. "exclude", "include" };
  925. enum { Off, On };
  926. static const char * ToggleNames[] = { "off", "on" };
  927. assert((BatchOff == 0) && (BatchOn == 1) && (BatchAbort == 2));
  928. static const char * BatchModeNames[] = { "off", "on", "abort" };
  929. assert((tmBinary == 0) && (tmAscii == 1) && (tmAutomatic == 2));
  930. static const char * TransferModeNames[] = { "binary", "ascii", "automatic" };
  931. int Option = -1;
  932. if (!OptionName.IsEmpty())
  933. {
  934. Option = TScriptCommands::FindCommand(Names, LENOF(Names), OptionName);
  935. if (Option < 0)
  936. {
  937. throw Exception(FMTLOAD(SCRIPT_OPTION_UNKNOWN, (OptionName)));
  938. }
  939. else
  940. {
  941. OptionName = Names[Option];
  942. }
  943. }
  944. #define OPT(OPT) ((Option < 0) || (Option == OPT))
  945. const char * ListFormat = "%-12s %-10s";
  946. bool SetValue = !ValueName.IsEmpty();
  947. if (OPT(Batch))
  948. {
  949. if (SetValue)
  950. {
  951. int Value = TScriptCommands::FindCommand(BatchModeNames, LENOF(BatchModeNames), ValueName);
  952. if (Value < 0)
  953. {
  954. throw Exception(FMTLOAD(SCRIPT_VALUE_UNKNOWN, (ValueName, OptionName)));
  955. }
  956. FBatch = (TBatchMode)Value;
  957. }
  958. PrintLine(FORMAT(ListFormat, (Names[Batch], BatchModeNames[FBatch])));
  959. }
  960. if (OPT(Confirm))
  961. {
  962. if (SetValue)
  963. {
  964. int Value = TScriptCommands::FindCommand(ToggleNames, LENOF(ToggleNames), ValueName);
  965. if (Value < 0)
  966. {
  967. throw Exception(FMTLOAD(SCRIPT_VALUE_UNKNOWN, (ValueName, OptionName)));
  968. }
  969. FConfirm = (Value == On);
  970. }
  971. PrintLine(FORMAT(ListFormat, (Names[Confirm], ToggleNames[FConfirm ? On : Off])));
  972. }
  973. if (OPT(Transfer))
  974. {
  975. if (SetValue)
  976. {
  977. int Value = TScriptCommands::FindCommand(TransferModeNames,
  978. LENOF(TransferModeNames), ValueName);
  979. if (Value < 0)
  980. {
  981. throw Exception(FMTLOAD(SCRIPT_VALUE_UNKNOWN, (ValueName, OptionName)));
  982. }
  983. FCopyParam.TransferMode = (TTransferMode)Value;
  984. }
  985. assert(FCopyParam.TransferMode < LENOF(TransferModeNames));
  986. const char * Value = TransferModeNames[FCopyParam.TransferMode];
  987. PrintLine(FORMAT(ListFormat, (Names[Transfer], Value)));
  988. }
  989. if (OPT(SynchDelete))
  990. {
  991. if (SetValue)
  992. {
  993. int Value = TScriptCommands::FindCommand(ToggleNames, LENOF(ToggleNames), ValueName);
  994. if (Value < 0)
  995. {
  996. throw Exception(FMTLOAD(SCRIPT_VALUE_UNKNOWN, (ValueName, OptionName)));
  997. }
  998. FSynchronizeParams =
  999. (FSynchronizeParams & ~TTerminal::spDelete) |
  1000. FLAGMASK(Value == On, TTerminal::spDelete);
  1001. }
  1002. PrintLine(FORMAT(ListFormat, (Names[SynchDelete],
  1003. ToggleNames[FLAGSET(FSynchronizeParams, TTerminal::spDelete) ? On : Off])));
  1004. }
  1005. static const char * Clear = "clear";
  1006. if (OPT(Include))
  1007. {
  1008. if (SetValue)
  1009. {
  1010. FCopyParam.NegativeExclude = true;
  1011. FCopyParam.ExcludeFileMask =
  1012. (ValueName == Clear ? AnsiString() : ValueName);
  1013. }
  1014. if (SetValue ||
  1015. (FCopyParam.NegativeExclude && !FCopyParam.ExcludeFileMask.Masks.IsEmpty()))
  1016. {
  1017. PrintLine(FORMAT(ListFormat, (Names[Include], FCopyParam.ExcludeFileMask.Masks)));
  1018. }
  1019. }
  1020. if (OPT(Exclude))
  1021. {
  1022. if (SetValue)
  1023. {
  1024. FCopyParam.NegativeExclude = false;
  1025. FCopyParam.ExcludeFileMask =
  1026. (ValueName == Clear ? AnsiString() : ValueName);
  1027. }
  1028. if (SetValue ||
  1029. (!FCopyParam.NegativeExclude && !FCopyParam.ExcludeFileMask.Masks.IsEmpty()))
  1030. {
  1031. PrintLine(FORMAT(ListFormat, (Names[Exclude], FCopyParam.ExcludeFileMask.Masks)));
  1032. }
  1033. }
  1034. #undef OPT
  1035. }
  1036. //---------------------------------------------------------------------------
  1037. void __fastcall TScript::OptionProc(TScriptProcParams * Parameters)
  1038. {
  1039. AnsiString OptionName;
  1040. AnsiString ValueName;
  1041. if (Parameters->ParamCount >= 1)
  1042. {
  1043. OptionName = Parameters->Param[0];
  1044. }
  1045. if (Parameters->ParamCount >= 2)
  1046. {
  1047. ValueName = Parameters->Param[1];
  1048. }
  1049. OptionImpl(OptionName, ValueName);
  1050. }
  1051. //---------------------------------------------------------------------------
  1052. void __fastcall TScript::AsciiProc(TScriptProcParams * /*Parameters*/)
  1053. {
  1054. OptionImpl("transfer", "ascii");
  1055. }
  1056. //---------------------------------------------------------------------------
  1057. void __fastcall TScript::BinaryProc(TScriptProcParams * /*Parameters*/)
  1058. {
  1059. OptionImpl("transfer", "binary");
  1060. }
  1061. //---------------------------------------------------------------------------
  1062. void __fastcall TScript::SynchronizeDirectories(TScriptProcParams * Parameters,
  1063. AnsiString & LocalDirectory, AnsiString & RemoteDirectory, int FirstParam)
  1064. {
  1065. if (Parameters->ParamCount > FirstParam)
  1066. {
  1067. LocalDirectory = Parameters->Param[FirstParam];
  1068. }
  1069. else
  1070. {
  1071. LocalDirectory = GetCurrentDir();
  1072. }
  1073. if (Parameters->ParamCount > FirstParam + 1)
  1074. {
  1075. RemoteDirectory = Parameters->Param[FirstParam + 1];
  1076. }
  1077. else
  1078. {
  1079. RemoteDirectory = FTerminal->CurrentDirectory;
  1080. }
  1081. }
  1082. //---------------------------------------------------------------------------
  1083. void __fastcall TScript::SynchronizeProc(TScriptProcParams * Parameters)
  1084. {
  1085. CheckSession();
  1086. ResetTransfer();
  1087. static const char * ModeNames[] = { "remote", "local", "both" };
  1088. AnsiString ModeName = Parameters->Param[0];
  1089. assert(FSynchronizeMode < 0);
  1090. FSynchronizeMode = TScriptCommands::FindCommand(ModeNames, LENOF(ModeNames), ModeName);
  1091. try
  1092. {
  1093. if (FSynchronizeMode < 0)
  1094. {
  1095. throw Exception(FMTLOAD(SCRIPT_OPTION_UNKNOWN, (ModeName)));
  1096. }
  1097. AnsiString LocalDirectory;
  1098. AnsiString RemoteDirectory;
  1099. SynchronizeDirectories(Parameters, LocalDirectory, RemoteDirectory, 1);
  1100. TCopyParamType CopyParam = FCopyParam;
  1101. CopyParam.CalculateSize = false;
  1102. int SynchronizeParams = FSynchronizeParams | TTerminal::spNoConfirmation;
  1103. PrintLine(FMTLOAD(SCRIPT_SYNCHRONIZE_COLLECT,
  1104. (ExcludeTrailingBackslash(LocalDirectory),
  1105. UnixExcludeTrailingBackslash(RemoteDirectory))));
  1106. TSynchronizeChecklist * Checklist =
  1107. FTerminal->SynchronizeCollect(LocalDirectory, RemoteDirectory,
  1108. static_cast<TTerminal::TSynchronizeMode>(FSynchronizeMode),
  1109. &CopyParam, SynchronizeParams, NULL, NULL);
  1110. try
  1111. {
  1112. if (Checklist->Count > 0)
  1113. {
  1114. FTerminal->SynchronizeApply(Checklist, LocalDirectory, RemoteDirectory,
  1115. &CopyParam, SynchronizeParams, OnTerminalSynchronizeDirectory);
  1116. }
  1117. }
  1118. __finally
  1119. {
  1120. delete Checklist;
  1121. }
  1122. }
  1123. __finally
  1124. {
  1125. FSynchronizeMode = -1;
  1126. }
  1127. }
  1128. //---------------------------------------------------------------------------
  1129. void __fastcall TScript::Synchronize(const AnsiString LocalDirectory,
  1130. const AnsiString RemoteDirectory, const TCopyParamType & ACopyParam,
  1131. TSynchronizeChecklist ** Checklist)
  1132. {
  1133. try
  1134. {
  1135. FKeepingUpToDate = true;
  1136. TCopyParamType CopyParam = ACopyParam;
  1137. CopyParam.CalculateSize = false;
  1138. int SynchronizeParams = FSynchronizeParams | TTerminal::spNoConfirmation |
  1139. TTerminal::spNoRecurse | TTerminal::spUseCache | TTerminal::spDelayProgress |
  1140. TTerminal::spSubDirs;
  1141. TSynchronizeChecklist * AChecklist =
  1142. FTerminal->SynchronizeCollect(LocalDirectory, RemoteDirectory, TTerminal::smRemote,
  1143. &CopyParam, SynchronizeParams, NULL, NULL);
  1144. try
  1145. {
  1146. if (AChecklist->Count > 0)
  1147. {
  1148. FTerminal->SynchronizeApply(AChecklist, LocalDirectory, RemoteDirectory,
  1149. &CopyParam, SynchronizeParams, OnTerminalSynchronizeDirectory);
  1150. }
  1151. }
  1152. __finally
  1153. {
  1154. if (Checklist == NULL)
  1155. {
  1156. delete AChecklist;
  1157. }
  1158. else
  1159. {
  1160. *Checklist = AChecklist;
  1161. }
  1162. }
  1163. // to break line after the last transfer (if any);
  1164. Print("");
  1165. FKeepingUpToDate = false;
  1166. }
  1167. catch(Exception & E)
  1168. {
  1169. FKeepingUpToDate = false;
  1170. HandleExtendedException(&E);
  1171. throw;
  1172. }
  1173. }
  1174. //---------------------------------------------------------------------------
  1175. void __fastcall TScript::KeepUpToDateProc(TScriptProcParams * Parameters)
  1176. {
  1177. if (OnSynchronizeStartStop == NULL)
  1178. {
  1179. Abort();
  1180. }
  1181. CheckSession();
  1182. ResetTransfer();
  1183. AnsiString LocalDirectory;
  1184. AnsiString RemoteDirectory;
  1185. SynchronizeDirectories(Parameters, LocalDirectory, RemoteDirectory, 0);
  1186. PrintLine(LoadStr(SCRIPT_KEEPING_UP_TO_DATE));
  1187. OnSynchronizeStartStop(this, LocalDirectory, RemoteDirectory);
  1188. }
  1189. //---------------------------------------------------------------------------
  1190. //---------------------------------------------------------------------------
  1191. __fastcall TManagementScript::TManagementScript(TStoredSessionList * StoredSessions) :
  1192. TScript()
  1193. {
  1194. assert(StoredSessions != NULL);
  1195. FOnInput = NULL;
  1196. FOnTerminalUpdateStatus = NULL;
  1197. FOnTerminalPromptUser = NULL;
  1198. FOnShowExtendedException = NULL;
  1199. FOnTerminalQueryUser = NULL;
  1200. FStoredSessions = StoredSessions;
  1201. FTerminalList = new TTerminalList(Configuration);
  1202. FOnQueryCancel = NULL;
  1203. FContinue = true;
  1204. OnTerminalSynchronizeDirectory = TerminalSynchronizeDirectory;
  1205. FCommands->Register("exit", SCRIPT_EXIT_DESC, SCRIPT_EXIT_HELP, &ExitProc, 0, 0);
  1206. FCommands->Register("bye", 0, SCRIPT_EXIT_HELP, &ExitProc, 0, 0);
  1207. FCommands->Register("open", SCRIPT_OPEN_DESC, SCRIPT_OPEN_HELP, &OpenProc, 0, 1);
  1208. FCommands->Register("close", SCRIPT_CLOSE_DESC, SCRIPT_CLOSE_HELP, &CloseProc, 0, 1);
  1209. FCommands->Register("session", SCRIPT_SESSION_DESC, SCRIPT_SESSION_HELP, &SessionProc, 0, 1);
  1210. FCommands->Register("lpwd", SCRIPT_LPWD_DESC, SCRIPT_LPWD_HELP, &LPwdProc, 0, 0);
  1211. FCommands->Register("lcd", SCRIPT_LCD_DESC, SCRIPT_LCD_HELP, &LCdProc, 1, 1);
  1212. FCommands->Register("lls", SCRIPT_LLS_DESC, SCRIPT_LLS_HELP, &LLsProc, 0, 1);
  1213. }
  1214. //---------------------------------------------------------------------------
  1215. __fastcall TManagementScript::~TManagementScript()
  1216. {
  1217. while (FTerminalList->Count > 0)
  1218. {
  1219. FreeTerminal(FTerminalList->Terminals[0]);
  1220. }
  1221. delete FTerminalList;
  1222. }
  1223. //---------------------------------------------------------------------------
  1224. void __fastcall TManagementScript::FreeTerminal(TTerminal * Terminal)
  1225. {
  1226. if (!Terminal->SessionData->Name.IsEmpty())
  1227. {
  1228. Terminal->SessionData->RemoteDirectory = Terminal->CurrentDirectory;
  1229. TSessionData * Data;
  1230. Data = (TSessionData *)StoredSessions->FindByName(Terminal->SessionData->Name);
  1231. if (Data != NULL)
  1232. {
  1233. bool Changed = false;
  1234. if (Terminal->SessionData->UpdateDirectories)
  1235. {
  1236. Data->RemoteDirectory = Terminal->SessionData->RemoteDirectory;
  1237. Changed = true;
  1238. }
  1239. if (Changed)
  1240. {
  1241. StoredSessions->Save();
  1242. }
  1243. }
  1244. }
  1245. FTerminalList->FreeTerminal(Terminal);
  1246. }
  1247. //---------------------------------------------------------------------------
  1248. void __fastcall TManagementScript::Input(const AnsiString Prompt,
  1249. AnsiString & Str, bool AllowEmpty)
  1250. {
  1251. do
  1252. {
  1253. Str = "";
  1254. if (FOnInput != NULL)
  1255. {
  1256. FOnInput(this, Prompt, Str);
  1257. }
  1258. else
  1259. {
  1260. Abort();
  1261. }
  1262. }
  1263. while (Str.Trim().IsEmpty() && !AllowEmpty);
  1264. }
  1265. //---------------------------------------------------------------------------
  1266. void __fastcall TManagementScript::PrintProgress(bool First, const AnsiString Str)
  1267. {
  1268. if (FOnPrintProgress != NULL)
  1269. {
  1270. FOnPrintProgress(this, First, Str);
  1271. }
  1272. }
  1273. //---------------------------------------------------------------------------
  1274. void __fastcall TManagementScript::ResetTransfer()
  1275. {
  1276. TScript::ResetTransfer();
  1277. FLastProgressFile = "";
  1278. FLastProgressTime = 0;
  1279. FLastProgressMessage = "";
  1280. }
  1281. //---------------------------------------------------------------------------
  1282. bool __fastcall TManagementScript::QueryCancel()
  1283. {
  1284. bool Result = false;
  1285. if (OnQueryCancel != NULL)
  1286. {
  1287. OnQueryCancel(this, Result);
  1288. }
  1289. return Result;
  1290. }
  1291. //---------------------------------------------------------------------------
  1292. void __fastcall TManagementScript::TerminalOnStdError(TObject * Sender,
  1293. TLogLineType /*Type*/, const AnsiString AddedLine)
  1294. {
  1295. TTerminal * Terminal = dynamic_cast<TTerminal*>(Sender);
  1296. assert(Terminal != NULL);
  1297. if (Terminal->Status == sshAuthenticate)
  1298. {
  1299. PrintLine(AddedLine);
  1300. }
  1301. }
  1302. //---------------------------------------------------------------------------
  1303. void __fastcall TManagementScript::TerminalPromptUser(TSecureShell * SecureShell,
  1304. AnsiString Prompt, TPromptKind Kind, AnsiString & Response, bool & Result,
  1305. void * Arg)
  1306. {
  1307. if (!SecureShell->StoredPasswordTried && (OnTerminalPromptUser != NULL))
  1308. {
  1309. OnTerminalPromptUser(SecureShell, Prompt, Kind, Response, Result, Arg);
  1310. }
  1311. }
  1312. //---------------------------------------------------------------------------
  1313. bool __fastcall TManagementScript::Synchronizing()
  1314. {
  1315. return (FKeepingUpToDate || (FSynchronizeMode >= 0));
  1316. }
  1317. //---------------------------------------------------------------------------
  1318. void __fastcall TManagementScript::ShowPendingProgress()
  1319. {
  1320. if (!FSynchronizeIntro.IsEmpty())
  1321. {
  1322. if (Synchronizing())
  1323. {
  1324. PrintLine(FSynchronizeIntro);
  1325. }
  1326. FSynchronizeIntro = "";
  1327. }
  1328. }
  1329. //---------------------------------------------------------------------------
  1330. void __fastcall TManagementScript::TerminalOperationProgress(
  1331. TFileOperationProgressType & ProgressData, TCancelStatus & Cancel)
  1332. {
  1333. if (ProgressData.Operation == foCopy)
  1334. {
  1335. if (ProgressData.InProgress && !ProgressData.FileName.IsEmpty())
  1336. {
  1337. bool DoPrint = false;
  1338. bool First = false;
  1339. AnsiString ProgressFileName = ProgressData.FileName;
  1340. if (ProgressData.Side == osLocal)
  1341. {
  1342. ProgressFileName = ExcludeTrailingBackslash(ProgressFileName);
  1343. }
  1344. else
  1345. {
  1346. ProgressFileName = UnixExcludeTrailingBackslash(ProgressFileName);
  1347. }
  1348. if (ProgressFileName != FLastProgressFile)
  1349. {
  1350. First = true;
  1351. DoPrint = true;
  1352. ShowPendingProgress();
  1353. }
  1354. if (!DoPrint && ((FLastProgressTime != time(NULL)) || ProgressData.IsTransferDone()))
  1355. {
  1356. DoPrint = true;
  1357. }
  1358. if (DoPrint)
  1359. {
  1360. static int MaxFileName = 25;
  1361. AnsiString FileName = MinimizeName(ProgressFileName, MaxFileName,
  1362. ProgressData.Side == osRemote);
  1363. AnsiString ProgressMessage = FORMAT("%-*.*s | %10d kB | %6.1f kB/s | %-6.6s | %3d%%",
  1364. (MaxFileName, MaxFileName, FileName,
  1365. static_cast<int>(ProgressData.TransferedSize / 1024),
  1366. static_cast<float>(ProgressData.CPS()) / 1024,
  1367. ProgressData.AsciiTransfer ? "ascii" : "binary",
  1368. ProgressData.TransferProgress()));
  1369. if (FLastProgressMessage != ProgressMessage)
  1370. {
  1371. FLastProgressTime = time(NULL);
  1372. PrintProgress(First, ProgressMessage);
  1373. FLastProgressMessage = ProgressMessage;
  1374. FLastProgressFile = ProgressFileName;
  1375. }
  1376. }
  1377. }
  1378. else
  1379. {
  1380. FLastProgressFile = "";
  1381. }
  1382. }
  1383. if (QueryCancel())
  1384. {
  1385. Cancel = csCancel;
  1386. }
  1387. }
  1388. //---------------------------------------------------------------------------
  1389. void __fastcall TManagementScript::TerminalOperationFinished(
  1390. TFileOperation Operation, TOperationSide /*Side*/,
  1391. bool /*Temp*/, const AnsiString FileName, Boolean Success,
  1392. bool & /*DisconnectWhenComplete*/)
  1393. {
  1394. if (Success && (Operation != foCalculateSize) && (Operation != foCopy))
  1395. {
  1396. ShowPendingProgress();
  1397. // For FKeepingUpToDate we should send events to synchronize controller eventuelly.
  1398. if (Synchronizing() && (Operation == foDelete))
  1399. {
  1400. // Note that this is duplicated with "keep up to date" log.
  1401. PrintLine(FMTLOAD(SCRIPT_SYNCHRONIZE_DELETED, (FileName)));
  1402. }
  1403. else
  1404. {
  1405. PrintLine(FileName);
  1406. }
  1407. }
  1408. }
  1409. //---------------------------------------------------------------------------
  1410. void __fastcall TManagementScript::TerminalSynchronizeDirectory(
  1411. const AnsiString LocalDirectory, const AnsiString RemoteDirectory,
  1412. bool & Continue)
  1413. {
  1414. int SynchronizeMode = FSynchronizeMode;
  1415. if (FKeepingUpToDate)
  1416. {
  1417. SynchronizeMode = TTerminal::smRemote;
  1418. }
  1419. AnsiString Arrow;
  1420. switch (SynchronizeMode)
  1421. {
  1422. case TTerminal::smRemote:
  1423. Arrow = "=>";
  1424. break;
  1425. case TTerminal::smLocal:
  1426. Arrow = "<=";
  1427. break;
  1428. case TTerminal::smBoth:
  1429. Arrow = "<=>";
  1430. break;
  1431. }
  1432. FSynchronizeIntro = FMTLOAD(SCRIPT_SYNCHRONIZE, (ExcludeTrailingBackslash(LocalDirectory),
  1433. Arrow, UnixExcludeTrailingBackslash(RemoteDirectory)));
  1434. if (QueryCancel())
  1435. {
  1436. Continue = false;
  1437. }
  1438. }
  1439. //---------------------------------------------------------------------------
  1440. TTerminal * __fastcall TManagementScript::FindSession(const AnsiString Index)
  1441. {
  1442. int i = StrToIntDef(Index, -1);
  1443. if ((i <= 0) || (i > FTerminalList->Count))
  1444. {
  1445. throw Exception(FMTLOAD(SCRIPT_SESSION_INDEX_INVALID, (Index)));
  1446. }
  1447. else
  1448. {
  1449. return FTerminalList->Terminals[i - 1];
  1450. }
  1451. }
  1452. //---------------------------------------------------------------------------
  1453. void __fastcall TManagementScript::PrintActiveSession()
  1454. {
  1455. assert(FTerminal != NULL);
  1456. PrintLine(FMTLOAD(SCRIPT_ACTIVE_SESSION,
  1457. (FTerminalList->IndexOf(FTerminal) + 1, FTerminal->SessionData->SessionName)));
  1458. }
  1459. //---------------------------------------------------------------------------
  1460. bool __fastcall TManagementScript::HandleExtendedException(Exception * E,
  1461. TTerminal * Terminal)
  1462. {
  1463. bool Result = TScript::HandleExtendedException(E);
  1464. if (Terminal == NULL)
  1465. {
  1466. Terminal = FTerminal;
  1467. }
  1468. if ((Terminal != NULL) && (Terminal == FTerminal) && (dynamic_cast<EFatal*>(E) != NULL))
  1469. {
  1470. try
  1471. {
  1472. DoClose(Terminal);
  1473. }
  1474. catch(...)
  1475. {
  1476. // ignore disconnect errors
  1477. }
  1478. }
  1479. return Result;
  1480. }
  1481. //---------------------------------------------------------------------------
  1482. void __fastcall TManagementScript::Connect(const AnsiString Session)
  1483. {
  1484. try
  1485. {
  1486. DoConnect(Session);
  1487. }
  1488. catch(Exception & E)
  1489. {
  1490. if (!HandleExtendedException(&E))
  1491. {
  1492. throw;
  1493. }
  1494. }
  1495. }
  1496. //---------------------------------------------------------------------------
  1497. void __fastcall TManagementScript::DoConnect(const AnsiString Session)
  1498. {
  1499. bool DefaultsOnly;
  1500. TSessionData * Data = FStoredSessions->ParseUrl(Session, DefaultsOnly,
  1501. puDecodeUrlChars, NULL);
  1502. try
  1503. {
  1504. assert(Data != NULL);
  1505. if (!Data->CanLogin || DefaultsOnly)
  1506. {
  1507. if (Data->HostName.IsEmpty())
  1508. {
  1509. AnsiString Value;
  1510. Input(LoadStr(SCRIPT_HOST_PROMPT), Value, false);
  1511. Data->HostName = Value;
  1512. }
  1513. if (Data->UserName.IsEmpty())
  1514. {
  1515. AnsiString Value;
  1516. Input(LoadStr(SCRIPT_USERNAME_PROMPT), Value, false);
  1517. Data->UserName = Value;
  1518. }
  1519. assert(Data->CanLogin);
  1520. }
  1521. TTerminal * Terminal = FTerminalList->NewTerminal(Data);
  1522. try
  1523. {
  1524. Terminal->AutoReadDirectory = false;
  1525. Terminal->OnStdError = TerminalOnStdError;
  1526. Terminal->OnPromptUser = TerminalPromptUser;
  1527. Terminal->OnShowExtendedException = OnShowExtendedException;
  1528. Terminal->OnQueryUser = OnTerminalQueryUser;
  1529. Terminal->OnProgress = TerminalOperationProgress;
  1530. Terminal->OnFinished = TerminalOperationFinished;
  1531. Terminal->OnUpdateStatus = OnTerminalUpdateStatus;
  1532. ConnectTerminal(Terminal);
  1533. }
  1534. catch(...)
  1535. {
  1536. FTerminalList->FreeTerminal(Terminal);
  1537. throw;
  1538. }
  1539. FTerminal = Terminal;
  1540. }
  1541. __finally
  1542. {
  1543. delete Data;
  1544. }
  1545. PrintActiveSession();
  1546. }
  1547. //---------------------------------------------------------------------------
  1548. void __fastcall TManagementScript::DoClose(TTerminal * Terminal)
  1549. {
  1550. int Index = FTerminalList->IndexOf(Terminal);
  1551. assert(Index >= 0);
  1552. try
  1553. {
  1554. Terminal->Active = false;
  1555. AnsiString SessionName = Terminal->SessionData->SessionName;
  1556. FreeTerminal(Terminal);
  1557. PrintLine(FMTLOAD(SCRIPT_SESSION_CLOSED, (SessionName)));
  1558. }
  1559. __finally
  1560. {
  1561. if (FTerminalList->Count > 0)
  1562. {
  1563. if (Index < FTerminalList->Count)
  1564. {
  1565. FTerminal = FTerminalList->Terminals[Index];
  1566. }
  1567. else
  1568. {
  1569. FTerminal = FTerminalList->Terminals[0];
  1570. }
  1571. PrintActiveSession();
  1572. }
  1573. else
  1574. {
  1575. FTerminal = NULL;
  1576. PrintLine(LoadStr(SCRIPT_NO_SESSION));
  1577. }
  1578. }
  1579. }
  1580. //---------------------------------------------------------------------------
  1581. void __fastcall TManagementScript::ExitProc(TScriptProcParams * /*Parameters*/)
  1582. {
  1583. FContinue = false;
  1584. }
  1585. //---------------------------------------------------------------------------
  1586. void __fastcall TManagementScript::OpenProc(TScriptProcParams * Parameters)
  1587. {
  1588. Connect(Parameters->ParamCount > 0 ? Parameters->Param[0] : AnsiString());
  1589. }
  1590. //---------------------------------------------------------------------------
  1591. void __fastcall TManagementScript::CloseProc(TScriptProcParams * Parameters)
  1592. {
  1593. CheckSession();
  1594. TTerminal * Terminal;
  1595. if (Parameters->ParamCount == 0)
  1596. {
  1597. Terminal = FTerminal;
  1598. }
  1599. else
  1600. {
  1601. Terminal = FindSession(Parameters->Param[0]);
  1602. }
  1603. DoClose(Terminal);
  1604. }
  1605. //---------------------------------------------------------------------------
  1606. void __fastcall TManagementScript::SessionProc(TScriptProcParams * Parameters)
  1607. {
  1608. CheckSession();
  1609. if (Parameters->ParamCount == 0)
  1610. {
  1611. for (int i = 0; i < FTerminalList->Count; i++)
  1612. {
  1613. PrintLine(FORMAT("%3d %s",
  1614. (i + 1, FTerminalList->Terminals[i]->SessionData->SessionName)));
  1615. }
  1616. PrintActiveSession();
  1617. }
  1618. else
  1619. {
  1620. FTerminal = FindSession(Parameters->Param[0]);
  1621. PrintActiveSession();
  1622. }
  1623. }
  1624. //---------------------------------------------------------------------------
  1625. void __fastcall TManagementScript::LPwdProc(TScriptProcParams * /*Parameters*/)
  1626. {
  1627. PrintLine(GetCurrentDir());
  1628. }
  1629. //---------------------------------------------------------------------------
  1630. void __fastcall TManagementScript::LCdProc(TScriptProcParams * Parameters)
  1631. {
  1632. assert(Parameters->ParamCount == 1);
  1633. AnsiString Directory = Parameters->Param[0];
  1634. if (!SetCurrentDir(Directory))
  1635. {
  1636. throw Exception(FMTLOAD(CHANGE_DIR_ERROR, (Directory)));
  1637. }
  1638. PrintLine(GetCurrentDir());
  1639. }
  1640. //---------------------------------------------------------------------------
  1641. void __fastcall TManagementScript::LLsProc(TScriptProcParams * Parameters)
  1642. {
  1643. AnsiString Directory;
  1644. AnsiString Mask;
  1645. if (Parameters->ParamCount > 0)
  1646. {
  1647. Directory = Parameters->Param[0];
  1648. Mask = ExtractFileName(Directory);
  1649. if (TFileMasks::IsMask(Mask))
  1650. {
  1651. Directory = ExtractFilePath(Directory);
  1652. }
  1653. else
  1654. {
  1655. Mask = "";
  1656. }
  1657. }
  1658. if (Directory.IsEmpty())
  1659. {
  1660. Directory = GetCurrentDir();
  1661. }
  1662. if (Mask.IsEmpty())
  1663. {
  1664. Mask = "*.*";
  1665. }
  1666. TSearchRec SearchRec;
  1667. int FindAttrs = faReadOnly | faHidden | faSysFile | faDirectory | faArchive;
  1668. if (FindFirst(IncludeTrailingBackslash(Directory) + Mask, FindAttrs, SearchRec) != 0)
  1669. {
  1670. throw Exception(FMTLOAD(LIST_DIR_ERROR, (Directory)));
  1671. }
  1672. try
  1673. {
  1674. AnsiString TimeFormat = FixedLenDateTimeFormat(ShortTimeFormat);
  1675. AnsiString DateFormat = FixedLenDateTimeFormat(ShortDateFormat);
  1676. int DateLen = 0;
  1677. int TimeLen = 0;
  1678. bool First = true;
  1679. do
  1680. {
  1681. if (SearchRec.Name != ".")
  1682. {
  1683. TDateTime DateTime = FileDateToDateTime(SearchRec.Time);
  1684. AnsiString TimeStr = FormatDateTime(TimeFormat, DateTime);
  1685. AnsiString DateStr = FormatDateTime(DateFormat, DateTime);
  1686. if (First)
  1687. {
  1688. if (TimeLen < TimeStr.Length())
  1689. {
  1690. TimeLen = TimeStr.Length();
  1691. }
  1692. if (DateLen < DateStr.Length())
  1693. {
  1694. DateLen = DateStr.Length();
  1695. }
  1696. First = false;
  1697. }
  1698. PrintLine(FORMAT("%-*s %-*s %-14s %s", (
  1699. DateLen, DateStr, TimeLen, TimeStr,
  1700. (FLAGSET(SearchRec.Attr, faDirectory) ?
  1701. AnsiString("<DIR>") : FORMAT("%14.0n", (double(SearchRec.Size)))),
  1702. SearchRec.Name)));
  1703. }
  1704. }
  1705. while (FindNext(SearchRec) == 0);
  1706. }
  1707. __finally
  1708. {
  1709. FindClose(SearchRec);
  1710. }
  1711. }
  1712. //---------------------------------------------------------------------------