ScpFileSystem.cpp 72 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170
  1. //---------------------------------------------------------------------------
  2. #include <vcl.h>
  3. #pragma hdrstop
  4. #include "ScpFileSystem.h"
  5. #include "Common.h"
  6. #include "Interface.h"
  7. #include "Terminal.h"
  8. #include "TextsCore.h"
  9. #include <stdio.h>
  10. //---------------------------------------------------------------------------
  11. #pragma package(smart_init)
  12. //---------------------------------------------------------------------------
  13. #define FILE_OPERATION_LOOP_EX(ALLOW_SKIP, MESSAGE, OPERATION) \
  14. FILE_OPERATION_LOOP_CUSTOM(FTerminal, ALLOW_SKIP, MESSAGE, OPERATION)
  15. //---------------------------------------------------------------------------
  16. const coRaiseExcept = 1;
  17. const coExpectNoOutput = 2;
  18. const coWaitForLastLine = 4;
  19. const coOnlyReturnCode = 8;
  20. const coIgnoreWarnings = 16;
  21. const ecRaiseExcept = 1;
  22. const ecIgnoreWarnings = 2;
  23. //---------------------------------------------------------------------------
  24. #define THROW_FILE_SKIPPED(EXCEPTION, MESSAGE) \
  25. throw EScpFileSkipped(EXCEPTION, MESSAGE)
  26. #define THROW_SCP_ERROR(EXCEPTION, MESSAGE) \
  27. throw EScp(EXCEPTION, MESSAGE)
  28. //===========================================================================
  29. #define MaxShellCommand fsAnyCommand
  30. #define ShellCommandCount MaxShellCommand + 1
  31. #define MaxCommandLen 40
  32. struct TCommandType
  33. {
  34. int MinLines;
  35. int MaxLines;
  36. bool ModifiesFiles;
  37. bool ChangesDirectory;
  38. bool InteractiveCommand;
  39. char Command[MaxCommandLen];
  40. };
  41. // Only one character! See TSCPFileSystem::ReadCommandOutput()
  42. #define LastLineSeparator ":"
  43. #define LAST_LINE "WinSCP: this is end-of-file"
  44. #define FIRST_LINE "WinSCP: this is begin-of-file"
  45. extern const TCommandType DefaultCommandSet[];
  46. #define NationalVarCount 10
  47. extern const char NationalVars[NationalVarCount][15];
  48. #define CHECK_CMD assert((Cmd >=0) && (Cmd <= MaxShellCommand))
  49. class TSessionData;
  50. //---------------------------------------------------------------------------
  51. class TCommandSet
  52. {
  53. private:
  54. TCommandType CommandSet[ShellCommandCount];
  55. TSessionData * FSessionData;
  56. AnsiString FReturnVar;
  57. int __fastcall GetMaxLines(TFSCommand Cmd);
  58. int __fastcall GetMinLines(TFSCommand Cmd);
  59. bool __fastcall GetModifiesFiles(TFSCommand Cmd);
  60. bool __fastcall GetChangesDirectory(TFSCommand Cmd);
  61. bool __fastcall GetOneLineCommand(TFSCommand Cmd);
  62. void __fastcall SetCommands(TFSCommand Cmd, AnsiString value);
  63. AnsiString __fastcall GetCommands(TFSCommand Cmd);
  64. AnsiString __fastcall GetFirstLine();
  65. bool __fastcall GetInteractiveCommand(TFSCommand Cmd);
  66. AnsiString __fastcall GetLastLine();
  67. AnsiString __fastcall GetReturnVar();
  68. public:
  69. __fastcall TCommandSet(TSessionData *aSessionData);
  70. void __fastcall Default();
  71. void __fastcall CopyFrom(TCommandSet * Source);
  72. AnsiString __fastcall Command(TFSCommand Cmd, const TVarRec * args, int size);
  73. TStrings * __fastcall CreateCommandList();
  74. AnsiString __fastcall FullCommand(TFSCommand Cmd, const TVarRec * args, int size);
  75. __property int MaxLines[TFSCommand Cmd] = { read=GetMaxLines};
  76. __property int MinLines[TFSCommand Cmd] = { read=GetMinLines };
  77. __property bool ModifiesFiles[TFSCommand Cmd] = { read=GetModifiesFiles };
  78. __property bool ChangesDirectory[TFSCommand Cmd] = { read=GetChangesDirectory };
  79. __property bool OneLineCommand[TFSCommand Cmd] = { read=GetOneLineCommand };
  80. __property AnsiString Commands[TFSCommand Cmd] = { read=GetCommands, write=SetCommands };
  81. __property AnsiString FirstLine = { read = GetFirstLine };
  82. __property bool InteractiveCommand[TFSCommand Cmd] = { read = GetInteractiveCommand };
  83. __property AnsiString LastLine = { read=GetLastLine };
  84. __property TSessionData * SessionData = { read=FSessionData, write=FSessionData };
  85. __property AnsiString ReturnVar = { read=GetReturnVar, write=FReturnVar };
  86. };
  87. //===========================================================================
  88. const char NationalVars[NationalVarCount][15] =
  89. {"LANG", "LANGUAGE", "LC_CTYPE", "LC_COLLATE", "LC_MONETARY", "LC_NUMERIC",
  90. "LC_TIME", "LC_MESSAGES", "LC_ALL", "HUMAN_BLOCKS" };
  91. //---------------------------------------------------------------------------
  92. #define F false
  93. #define T true
  94. // TODO: remove "mf" and "cd", it is implemented in TTerminal already
  95. const TCommandType DefaultCommandSet[ShellCommandCount] = {
  96. // min max mf cd ia command
  97. /*Null*/ { -1, -1, F, F, F, "" },
  98. /*VarValue*/ { -1, -1, F, F, F, "echo \"$%s\"" /* variable */ },
  99. /*LastLine*/ { -1, -1, F, F, F, "echo \"%s" LastLineSeparator "%s\"" /* last line, return var */ },
  100. /*FirstLine*/ { -1, -1, F, F, F, "echo \"%s\"" /* first line */ },
  101. /*CurrentDirectory*/ { 1, 1, F, F, F, "pwd" },
  102. /*ChangeDirectory*/ { 0, 0, F, T, F, "cd %s" /* directory */ },
  103. // list directory can be empty on permission denied, this is handled in ReadDirectory
  104. /*ListDirectory*/ { -1, -1, F, F, F, "ls -la \"%s\"" /* directory */ },
  105. /*ListCurrentDirectory*/{ -1, -1, F, F, F, "ls -la" },
  106. /*ListFile*/ { 1, 1, F, F, F, "ls -lad \"%s\"" /* file/directory */ },
  107. /*LookupUserGroups*/ { 0, 1, F, F, F, "groups" },
  108. /*CopyToRemote*/ { -1, -1, T, F, T, "scp -r %s -d -t \"%s\"" /* options, directory */ },
  109. /*CopyToLocal*/ { -1, -1, F, F, T, "scp -r %s -d -f \"%s\"" /* options, file */ },
  110. /*DeleteFile*/ { 0, 0, T, F, F, "rm -f -r \"%s\"" /* file/directory */},
  111. /*RenameFile*/ { 0, 0, T, F, F, "mv -f \"%s\" \"%s\"" /* file/directory, new name*/},
  112. /*CreateDirectory*/ { 0, 0, T, F, F, "mkdir \"%s\"" /* new directory */},
  113. /*ChangeMode*/ { 0, 0, T, F, F, "chmod %s %s \"%s\"" /* options, mode, filename */},
  114. /*ChangeGroup*/ { 0, 0, T, F, F, "chgrp %s \"%s\" \"%s\"" /* options, group, filename */},
  115. /*ChangeOwner*/ { 0, 0, T, F, F, "chown %s \"%s\" \"%s\"" /* options, owner, filename */},
  116. /*HomeDirectory*/ { 0, 0, F, T, F, "cd" },
  117. /*Unset*/ { 0, 0, F, F, F, "unset \"%s\"" /* variable */ },
  118. /*Unalias*/ { 0, 0, F, F, F, "unalias \"%s\"" /* alias */ },
  119. /*AliasGroupList*/ { 0, 0, F, F, F, "alias ls=\"ls -g\"" },
  120. /*CreateLink*/ { 0, 0, T, F, F, "ln %s \"%s\" \"%s\"" /*symbolic (-s), filename, point to*/},
  121. /*AnyCommand*/ { 0, -1, T, T, F, "%s" }
  122. };
  123. #undef F
  124. #undef T
  125. //---------------------------------------------------------------------------
  126. __fastcall TCommandSet::TCommandSet(TSessionData *aSessionData):
  127. FSessionData(aSessionData), FReturnVar("")
  128. {
  129. assert(FSessionData);
  130. Default();
  131. }
  132. //---------------------------------------------------------------------------
  133. void __fastcall TCommandSet::CopyFrom(TCommandSet * Source)
  134. {
  135. memcpy(&CommandSet, Source->CommandSet, sizeof(CommandSet));
  136. }
  137. //---------------------------------------------------------------------------
  138. void __fastcall TCommandSet::Default()
  139. {
  140. assert(sizeof(CommandSet) == sizeof(DefaultCommandSet));
  141. memcpy(&CommandSet, &DefaultCommandSet, sizeof(CommandSet));
  142. }
  143. //---------------------------------------------------------------------------
  144. int __fastcall TCommandSet::GetMaxLines(TFSCommand Cmd)
  145. {
  146. CHECK_CMD;
  147. return CommandSet[Cmd].MaxLines;
  148. }
  149. //---------------------------------------------------------------------------
  150. int __fastcall TCommandSet::GetMinLines(TFSCommand Cmd)
  151. {
  152. CHECK_CMD;
  153. return CommandSet[Cmd].MinLines;
  154. }
  155. //---------------------------------------------------------------------------
  156. bool __fastcall TCommandSet::GetModifiesFiles(TFSCommand Cmd)
  157. {
  158. CHECK_CMD;
  159. return CommandSet[Cmd].ModifiesFiles;
  160. }
  161. //---------------------------------------------------------------------------
  162. bool __fastcall TCommandSet::GetChangesDirectory(TFSCommand Cmd)
  163. {
  164. CHECK_CMD;
  165. return CommandSet[Cmd].ChangesDirectory;
  166. }
  167. //---------------------------------------------------------------------------
  168. bool __fastcall TCommandSet::GetInteractiveCommand(TFSCommand Cmd)
  169. {
  170. CHECK_CMD;
  171. return CommandSet[Cmd].InteractiveCommand;
  172. }
  173. //---------------------------------------------------------------------------
  174. bool __fastcall TCommandSet::GetOneLineCommand(TFSCommand /*Cmd*/)
  175. {
  176. //CHECK_CMD;
  177. // #56: we send "echo last line" from all commands on same line
  178. // just as it was in 1.0
  179. return True; //CommandSet[Cmd].OneLineCommand;
  180. }
  181. //---------------------------------------------------------------------------
  182. void __fastcall TCommandSet::SetCommands(TFSCommand Cmd, AnsiString value)
  183. {
  184. CHECK_CMD;
  185. strcpy(CommandSet[Cmd].Command, value.SubString(1, MaxCommandLen).c_str());
  186. }
  187. //---------------------------------------------------------------------------
  188. AnsiString __fastcall TCommandSet::GetCommands(TFSCommand Cmd)
  189. {
  190. CHECK_CMD;
  191. return CommandSet[Cmd].Command;
  192. }
  193. //---------------------------------------------------------------------------
  194. AnsiString __fastcall TCommandSet::Command(TFSCommand Cmd, const TVarRec * args, int size)
  195. {
  196. if (args) return Format(Commands[Cmd], args, size);
  197. else return Commands[Cmd];
  198. }
  199. //---------------------------------------------------------------------------
  200. AnsiString __fastcall TCommandSet::FullCommand(TFSCommand Cmd, const TVarRec * args, int size)
  201. {
  202. AnsiString Separator;
  203. if (OneLineCommand[Cmd]) Separator = " ; ";
  204. else Separator = "\n";
  205. AnsiString Line = Command(Cmd, args, size);
  206. AnsiString LastLineCmd =
  207. Command(fsLastLine, ARRAYOFCONST((LastLine, ReturnVar)));
  208. AnsiString FirstLineCmd;
  209. if (InteractiveCommand[Cmd])
  210. FirstLineCmd = Command(fsFirstLine, ARRAYOFCONST((FirstLine))) + Separator;
  211. AnsiString Result;
  212. if (!Line.IsEmpty())
  213. Result = FORMAT("%s%s%s%s", (FirstLineCmd, Line, Separator, LastLineCmd));
  214. else
  215. Result = FORMAT("%s%s", (FirstLineCmd, LastLineCmd));
  216. return Result;
  217. }
  218. //---------------------------------------------------------------------------
  219. AnsiString __fastcall TCommandSet::GetFirstLine()
  220. {
  221. return FIRST_LINE;
  222. }
  223. //---------------------------------------------------------------------------
  224. AnsiString __fastcall TCommandSet::GetLastLine()
  225. {
  226. return LAST_LINE;
  227. }
  228. //---------------------------------------------------------------------------
  229. AnsiString __fastcall TCommandSet::GetReturnVar()
  230. {
  231. assert(SessionData);
  232. if (!FReturnVar.IsEmpty()) return AnsiString('$') + FReturnVar;
  233. else
  234. if (SessionData->DetectReturnVar) return '0';
  235. else return AnsiString('$') + SessionData->ReturnVar;
  236. }
  237. //---------------------------------------------------------------------------
  238. TStrings * __fastcall TCommandSet::CreateCommandList()
  239. {
  240. TStrings * CommandList = new TStringList();
  241. for (Integer Index = 0; Index < ShellCommandCount; Index++)
  242. {
  243. AnsiString Cmd = Commands[(TFSCommand)Index];
  244. if (!Cmd.IsEmpty())
  245. {
  246. Integer P = Cmd.Pos(" ");
  247. if (P) Cmd.SetLength(P-1);
  248. if (CommandList->IndexOf(Cmd) < 0)
  249. CommandList->Add(Cmd);
  250. }
  251. }
  252. return CommandList;
  253. }
  254. //===========================================================================
  255. __fastcall TSCPFileSystem::TSCPFileSystem(TTerminal * ATerminal):
  256. TCustomFileSystem(ATerminal)
  257. {
  258. FCommandSet = new TCommandSet(FTerminal->SessionData);
  259. FOutput = new TStringList();
  260. FProcessingCommand = false;
  261. }
  262. //---------------------------------------------------------------------------
  263. __fastcall TSCPFileSystem::~TSCPFileSystem()
  264. {
  265. delete FCommandSet;
  266. delete FOutput;
  267. }
  268. //---------------------------------------------------------------------------
  269. AnsiString __fastcall TSCPFileSystem::GetProtocolName() const
  270. {
  271. return "SCP";
  272. }
  273. //---------------------------------------------------------------------------
  274. AnsiString __fastcall TSCPFileSystem::AbsolutePath(AnsiString Path)
  275. {
  276. AnsiString Result;
  277. if (Path.IsEmpty())
  278. {
  279. Result = CurrentDirectory;
  280. }
  281. else if (Path[1] == '/')
  282. {
  283. Result = UnixExcludeTrailingBackslash(Path);
  284. }
  285. else
  286. {
  287. Result = UnixIncludeTrailingBackslash(
  288. UnixIncludeTrailingBackslash(CurrentDirectory) + Path);
  289. int P;
  290. while ((P = Result.Pos("/../")) > 0)
  291. {
  292. int P2 = Result.SubString(1, P-1).LastDelimiter("/");
  293. assert(P2 > 0);
  294. Result.Delete(P2, P - P2 + 3);
  295. }
  296. while ((P = Result.Pos("/./")) > 0)
  297. {
  298. Result.Delete(P, 2);
  299. }
  300. Result = UnixExcludeTrailingBackslash(Result);
  301. }
  302. return Result;
  303. }
  304. //---------------------------------------------------------------------------
  305. bool __fastcall TSCPFileSystem::IsCapable(int Capability) const
  306. {
  307. assert(FTerminal);
  308. switch (Capability) {
  309. case fcUserGroupListing:
  310. case fcModeChanging:
  311. case fcGroupChanging:
  312. case fcOwnerChanging:
  313. case fcAnyCommand:
  314. case fcHardLink:
  315. case fcSymbolicLink:
  316. case fcResolveSymlink:
  317. case fcRename:
  318. return true;
  319. case fcTextMode:
  320. return FTerminal->SessionData->EOLType != FTerminal->Configuration->LocalEOLType;
  321. case fcNativeTextMode:
  322. case fcNewerOnlyUpload:
  323. return false;
  324. default:
  325. assert(false);
  326. return false;
  327. }
  328. }
  329. //---------------------------------------------------------------------------
  330. void __fastcall TSCPFileSystem::KeepAlive()
  331. {
  332. if (!FProcessingCommand)
  333. {
  334. ExecCommand(fsNull, NULL, 0, 0);
  335. }
  336. else
  337. {
  338. FTerminal->LogEvent("Cannot send keepalive, command is being executed");
  339. }
  340. }
  341. //---------------------------------------------------------------------------
  342. void __fastcall TSCPFileSystem::AdditionalInfo(TStrings * AdditionalInfo,
  343. bool Initial)
  344. {
  345. if (Initial)
  346. {
  347. AnsiString UName;
  348. FTerminal->ExceptionOnFail = true;
  349. try
  350. {
  351. try
  352. {
  353. AnyCommand("uname -a");
  354. for (int Index = 0; Index < Output->Count; Index++)
  355. {
  356. if (Index > 0)
  357. {
  358. UName += "; ";
  359. }
  360. UName += Output->Strings[Index];
  361. }
  362. }
  363. catch(...)
  364. {
  365. if (!FTerminal->Active)
  366. {
  367. throw;
  368. }
  369. }
  370. }
  371. __finally
  372. {
  373. FTerminal->ExceptionOnFail = false;
  374. }
  375. if (!UName.IsEmpty())
  376. {
  377. AdditionalInfo->Add(LoadStr(SCP_UNIX_NAME));
  378. AdditionalInfo->Add(UName);
  379. }
  380. else
  381. {
  382. AdditionalInfo->Add(LoadStr(SCP_NO_UNIX_NAME));
  383. }
  384. }
  385. }
  386. //---------------------------------------------------------------------------
  387. AnsiString __fastcall TSCPFileSystem::DelimitStr(AnsiString Str)
  388. {
  389. if (!Str.IsEmpty())
  390. {
  391. #define DELIMITCHAR(C) { \
  392. Integer P, X = 0; \
  393. while ((P = Str.SubString(X+1, Str.Length() - X).Pos(C)) != 0) { \
  394. Str.Insert("\\", X+P); \
  395. X += P+1; } \
  396. }
  397. DELIMITCHAR('\\');
  398. DELIMITCHAR('`');
  399. DELIMITCHAR('$');
  400. DELIMITCHAR('"');
  401. // #62 19.10.2001: delimiting ! doesn't work on BASH
  402. //DELIMITCHAR('!');
  403. #undef DELIMITCHAR
  404. if (Str[1] == '-') Str = "./"+Str;
  405. }
  406. return Str;
  407. }
  408. //---------------------------------------------------------------------------
  409. void __fastcall TSCPFileSystem::EnsureLocation()
  410. {
  411. if (!FCachedDirectoryChange.IsEmpty())
  412. {
  413. FTerminal->LogEvent(FORMAT("Locating to cached directory \"%s\".",
  414. (FCachedDirectoryChange)));
  415. AnsiString Directory = FCachedDirectoryChange;
  416. FCachedDirectoryChange = "";
  417. try
  418. {
  419. ChangeDirectory(Directory);
  420. }
  421. catch(...)
  422. {
  423. // when location to cached directory fails, pretend again
  424. // location in cached directory
  425. if (FTerminal->Active && (CurrentDirectory != Directory))
  426. {
  427. FCachedDirectoryChange = Directory;
  428. }
  429. throw;
  430. }
  431. }
  432. }
  433. //---------------------------------------------------------------------------
  434. void __fastcall TSCPFileSystem::SendCommand(const AnsiString Cmd)
  435. {
  436. EnsureLocation();
  437. AnsiString Line;
  438. FTerminal->ClearStdError();
  439. FReturnCode = 0;
  440. FOutput->Clear();
  441. // We suppose, that 'Cmd' already contains command that ensures,
  442. // that 'LastLine' will be printed
  443. FTerminal->SendLine(Cmd);
  444. FProcessingCommand = true;
  445. }
  446. //---------------------------------------------------------------------------
  447. bool __fastcall TSCPFileSystem::IsTotalListingLine(const AnsiString Line)
  448. {
  449. // On some hosts there is not "total" but "totalt". What's the reason??
  450. // see mail from "Jan Wiklund (SysOp)" <[email protected]>
  451. return !Line.SubString(1, 5).AnsiCompareIC("total");
  452. }
  453. //---------------------------------------------------------------------------
  454. bool __fastcall TSCPFileSystem::RemoveLastLine(AnsiString & Line,
  455. int & ReturnCode, AnsiString LastLine)
  456. {
  457. bool IsLastLine = false;
  458. if (LastLine.IsEmpty()) LastLine = LAST_LINE;
  459. // #55: fixed so, even when last line of command output does not
  460. // contain CR/LF, we can recognize last line
  461. int Pos = Line.Pos(LastLine);
  462. if (Pos)
  463. {
  464. // 2003-07-14: There must be nothing after return code number to
  465. // consider string as last line. This fixes bug with 'set' command
  466. // in console window
  467. AnsiString ReturnCodeStr = Line.SubString(Pos + LastLine.Length() + 1,
  468. Line.Length() - Pos + LastLine.Length());
  469. if (TryStrToInt(ReturnCodeStr, ReturnCode))
  470. {
  471. IsLastLine = true;
  472. Line.SetLength(Pos - 1);
  473. }
  474. }
  475. return IsLastLine;
  476. }
  477. //---------------------------------------------------------------------------
  478. bool __fastcall TSCPFileSystem::IsLastLine(AnsiString & Line)
  479. {
  480. bool Result = false;
  481. try
  482. {
  483. Result = RemoveLastLine(Line, FReturnCode, FCommandSet->LastLine);
  484. }
  485. catch (Exception &E)
  486. {
  487. FTerminal->TerminalError(&E, LoadStr(CANT_DETECT_RETURN_CODE));
  488. }
  489. return Result;
  490. }
  491. //---------------------------------------------------------------------------
  492. void __fastcall TSCPFileSystem::SkipFirstLine()
  493. {
  494. AnsiString Line = FTerminal->ReceiveLine();
  495. if (Line != FCommandSet->FirstLine)
  496. {
  497. FTerminal->TerminalError(NULL, FMTLOAD(FIRST_LINE_EXPECTED, (Line)));
  498. }
  499. }
  500. //---------------------------------------------------------------------------
  501. void __fastcall TSCPFileSystem::ReadCommandOutput(int Params)
  502. {
  503. FProcessingCommand = false;
  504. if (Params & coWaitForLastLine)
  505. {
  506. AnsiString Line;
  507. bool IsLast;
  508. // #55: fixed so, even when last line of command output does not
  509. // contain CR/LF, we can recognize last line
  510. do
  511. {
  512. Line = FTerminal->ReceiveLine();
  513. IsLast = IsLastLine(Line);
  514. if (!IsLast || !Line.IsEmpty()) FOutput->Add(Line);
  515. }
  516. while (!IsLast);
  517. }
  518. if (Params & coRaiseExcept)
  519. {
  520. AnsiString Message = FTerminal->StdError;
  521. if ((Params & coExpectNoOutput) && FOutput->Count)
  522. {
  523. if (!Message.IsEmpty()) Message += "\n";
  524. Message += FOutput->Text;
  525. }
  526. while (!Message.IsEmpty() && (Message.LastDelimiter("\n\r") == Message.Length()))
  527. Message.SetLength(Message.Length() - 1);
  528. bool WrongReturnCode =
  529. (ReturnCode > 1) || (ReturnCode == 1 && !(Params & coIgnoreWarnings));
  530. if (Params & coOnlyReturnCode && WrongReturnCode)
  531. {
  532. FTerminal->TerminalError(FMTLOAD(COMMAND_FAILED_CODEONLY, (ReturnCode)));
  533. }
  534. else
  535. if (!(Params & coOnlyReturnCode) &&
  536. ((!Message.IsEmpty() && !(Params & coIgnoreWarnings)) ||
  537. WrongReturnCode))
  538. {
  539. FTerminal->TerminalError(FMTLOAD(COMMAND_FAILED, ("%s", ReturnCode, Message)));
  540. }
  541. }
  542. }
  543. //---------------------------------------------------------------------------
  544. void __fastcall TSCPFileSystem::ExecCommand(const AnsiString Cmd, int Params)
  545. {
  546. if (Params < 0) Params = ecRaiseExcept;
  547. if (FTerminal->UseBusyCursor)
  548. {
  549. Busy(true);
  550. }
  551. try
  552. {
  553. SendCommand(Cmd);
  554. try
  555. {
  556. int COParams = coWaitForLastLine;
  557. if (Params & ecRaiseExcept) COParams |= coRaiseExcept;
  558. if (Params & ecIgnoreWarnings) COParams |= coIgnoreWarnings;
  559. ReadCommandOutput(COParams);
  560. }
  561. catch (ETerminal &E)
  562. {
  563. AnsiString OnlyCmd = Cmd;
  564. Integer P = OnlyCmd.Pos('\n');
  565. if (!P) P = OnlyCmd.Pos(";");
  566. if (P) OnlyCmd.Delete(P, Cmd.Length() - P + 1);
  567. FTerminal->TerminalError(FORMAT(E.Message, (OnlyCmd.Trim())));
  568. }
  569. }
  570. __finally
  571. {
  572. if (FTerminal->UseBusyCursor)
  573. {
  574. Busy(false);
  575. }
  576. }
  577. }
  578. //---------------------------------------------------------------------------
  579. void __fastcall TSCPFileSystem::ExecCommand(TFSCommand Cmd, const TVarRec * args,
  580. int size, int Params)
  581. {
  582. if (Params < 0) Params = ecRaiseExcept;
  583. AnsiString FullCommand = FCommandSet->FullCommand(Cmd, args, size);
  584. if (FTerminal->SessionData->IgnoreLsWarnings &&
  585. (Cmd == fsListDirectory || Cmd == fsListCurrentDirectory ||
  586. Cmd == fsListFile))
  587. {
  588. Params |= ecIgnoreWarnings;
  589. }
  590. ExecCommand(FullCommand, Params);
  591. if (Params & ecRaiseExcept)
  592. {
  593. Integer MinL = FCommandSet->MinLines[Cmd];
  594. Integer MaxL = FCommandSet->MaxLines[Cmd];
  595. if (((MinL >= 0) && (MinL > FOutput->Count)) ||
  596. ((MaxL >= 0) && (MaxL > FOutput->Count)))
  597. {
  598. FTerminal->TerminalError(FmtLoadStr(INVALID_OUTPUT_ERROR,
  599. ARRAYOFCONST((FullCommand, Output->Text))));
  600. }
  601. }
  602. }
  603. //---------------------------------------------------------------------------
  604. void __fastcall TSCPFileSystem::SetCurrentDirectory(AnsiString value)
  605. {
  606. assert(false);
  607. }
  608. //---------------------------------------------------------------------------
  609. AnsiString __fastcall TSCPFileSystem::GetCurrentDirectory()
  610. {
  611. return FCurrentDirectory;
  612. }
  613. //---------------------------------------------------------------------------
  614. void __fastcall TSCPFileSystem::DoStartup()
  615. {
  616. // SkipStartupMessage and DetectReturnVar must succeed,
  617. // otherwise session is to be closed.
  618. FTerminal->ExceptionOnFail = true;
  619. SkipStartupMessage();
  620. if (FTerminal->SessionData->DetectReturnVar) DetectReturnVar();
  621. FTerminal->ExceptionOnFail = false;
  622. #define COND_OPER(OPER) if (FTerminal->SessionData->OPER) OPER()
  623. COND_OPER(ClearAliases);
  624. COND_OPER(UnsetNationalVars);
  625. COND_OPER(AliasGroupList);
  626. #undef COND_OPER
  627. }
  628. //---------------------------------------------------------------------------
  629. void __fastcall TSCPFileSystem::SkipStartupMessage()
  630. {
  631. try
  632. {
  633. FTerminal->LogEvent("Skipping host startup message (if any).");
  634. ExecCommand(fsNull, NULL, 0, 0);
  635. }
  636. catch (Exception & E)
  637. {
  638. FTerminal->CommandError(&E, LoadStr(SKIP_STARTUP_MESSAGE_ERROR));
  639. }
  640. }
  641. //---------------------------------------------------------------------------
  642. void __fastcall TSCPFileSystem::LookupUsersGroups()
  643. {
  644. ExecCommand(fsLookupUsersGroups);
  645. FTerminal->FUsers->Clear();
  646. FTerminal->FGroups->Clear();
  647. if (FOutput->Count > 0)
  648. {
  649. FTerminal->FGroups->BeginUpdate();
  650. try
  651. {
  652. AnsiString Groups = FOutput->Strings[0];
  653. while (!Groups.IsEmpty())
  654. {
  655. AnsiString NewGroup = CutToChar(Groups, ' ', False);
  656. FTerminal->FGroups->Add(NewGroup);
  657. }
  658. }
  659. __finally
  660. {
  661. FTerminal->FGroups->EndUpdate();
  662. }
  663. }
  664. }
  665. //---------------------------------------------------------------------------
  666. void __fastcall TSCPFileSystem::DetectReturnVar()
  667. {
  668. // This suppose that something was already executed (probably SkipStartupMessage())
  669. // or return code variable is already set on start up.
  670. try
  671. {
  672. // #60 17.10.01: "status" and "?" switched
  673. AnsiString ReturnVars[2] = { "status", "?" };
  674. AnsiString NewReturnVar = "";
  675. FTerminal->LogEvent("Detecting variable containing return code of last command.");
  676. for (int Index = 0; Index < 2; Index++)
  677. {
  678. bool Success = true;
  679. try
  680. {
  681. FTerminal->LogEvent(FORMAT("Trying \"$%s\".", (ReturnVars[Index])));
  682. ExecCommand(fsVarValue, ARRAYOFCONST((ReturnVars[Index])));
  683. if ((Output->Count != 1) || (StrToIntDef(Output->Strings[0], 256) > 255)) Abort();
  684. }
  685. catch (EFatal &E)
  686. {
  687. // if fatal error occurs, we need to exit ...
  688. throw;
  689. }
  690. catch (Exception &E)
  691. {
  692. // ...otherwise, we will try next variable (if any)
  693. Success = false;
  694. }
  695. if (Success)
  696. {
  697. NewReturnVar = ReturnVars[Index];
  698. break;
  699. }
  700. }
  701. if (NewReturnVar.IsEmpty())
  702. {
  703. Abort();
  704. }
  705. else
  706. {
  707. FCommandSet->ReturnVar = NewReturnVar;
  708. FTerminal->LogEvent(FORMAT("Return code variable \"%s\" selected.",
  709. (FCommandSet->ReturnVar)));
  710. }
  711. }
  712. catch (Exception &E)
  713. {
  714. FTerminal->CommandError(&E, LoadStr(DETECT_RETURNVAR_ERROR));
  715. }
  716. }
  717. //---------------------------------------------------------------------------
  718. void __fastcall TSCPFileSystem::ClearAliases()
  719. {
  720. try
  721. {
  722. FTerminal->LogEvent("Clearing all aliases.");
  723. TStrings * CommandList = FCommandSet->CreateCommandList();
  724. try
  725. {
  726. for (int Index = 0; Index < CommandList->Count; Index++)
  727. {
  728. // this command usually fails, becouse there will never be
  729. // aliases on all commands -> see last False parametr
  730. ExecCommand(fsUnalias, ARRAYOFCONST((CommandList->Strings[Index])), false);
  731. }
  732. }
  733. __finally
  734. {
  735. delete CommandList;
  736. }
  737. }
  738. catch (Exception &E)
  739. {
  740. FTerminal->CommandError(&E, LoadStr(UNALIAS_ALL_ERROR));
  741. }
  742. }
  743. //---------------------------------------------------------------------------
  744. void __fastcall TSCPFileSystem::AliasGroupList()
  745. {
  746. try
  747. {
  748. FTerminal->LogEvent("Aliasing LS to display file group.");
  749. ExecCommand(fsAliasGroupList);
  750. }
  751. catch (Exception &E)
  752. {
  753. FTerminal->CommandError(&E, LoadStr(ALIAS_GROUPLIST_ERROR));
  754. }
  755. }
  756. //---------------------------------------------------------------------------
  757. void __fastcall TSCPFileSystem::UnsetNationalVars()
  758. {
  759. try
  760. {
  761. FTerminal->LogEvent("Clearing national user variables.");
  762. for (int Index = 0; Index < NationalVarCount; Index++)
  763. {
  764. ExecCommand(fsUnset, ARRAYOFCONST((NationalVars[Index])), false);
  765. }
  766. }
  767. catch (Exception &E)
  768. {
  769. FTerminal->CommandError(&E, LoadStr(UNSET_NATIONAL_ERROR));
  770. }
  771. }
  772. //---------------------------------------------------------------------------
  773. void __fastcall TSCPFileSystem::ReadCurrentDirectory()
  774. {
  775. if (FCachedDirectoryChange.IsEmpty())
  776. {
  777. ExecCommand(fsCurrentDirectory);
  778. FCurrentDirectory = UnixExcludeTrailingBackslash(FOutput->Strings[0]);
  779. }
  780. else
  781. {
  782. FCurrentDirectory = FCachedDirectoryChange;
  783. }
  784. }
  785. //---------------------------------------------------------------------------
  786. void __fastcall TSCPFileSystem::HomeDirectory()
  787. {
  788. ExecCommand(fsHomeDirectory);
  789. }
  790. //---------------------------------------------------------------------------
  791. void __fastcall TSCPFileSystem::ChangeDirectory(const AnsiString Directory)
  792. {
  793. AnsiString ToDir;
  794. if (!Directory.IsEmpty() &&
  795. ((Directory[1] != '~') || (Directory.SubString(1, 2) == "~ ")))
  796. {
  797. ToDir = "\"" + DelimitStr(Directory) + "\"";
  798. }
  799. else
  800. {
  801. ToDir = DelimitStr(Directory);
  802. }
  803. ExecCommand(fsChangeDirectory, ARRAYOFCONST((ToDir)));
  804. FCachedDirectoryChange = "";
  805. }
  806. //---------------------------------------------------------------------------
  807. void __fastcall TSCPFileSystem::CachedChangeDirectory(const AnsiString Directory)
  808. {
  809. FCachedDirectoryChange = Directory;
  810. }
  811. //---------------------------------------------------------------------------
  812. void __fastcall TSCPFileSystem::ReadDirectory(TRemoteFileList * FileList)
  813. {
  814. assert(FileList);
  815. TStringList * OutputCopy = NULL;
  816. try
  817. {
  818. if (FileList->Directory == FTerminal->CurrentDirectory)
  819. {
  820. FTerminal->LogEvent("Listing current directory.");
  821. ExecCommand(fsListCurrentDirectory);
  822. }
  823. else
  824. {
  825. FTerminal->LogEvent(FORMAT("Listing directory \"%s\".",
  826. (FileList->Directory)));
  827. ExecCommand(fsListDirectory, ARRAYOFCONST((DelimitStr(FileList->Directory))));
  828. }
  829. FileList->Clear();
  830. TRemoteFile * File;
  831. // If output is not empty, we have succesfully got file listing,
  832. // otherwise there was an error, in case it was "permission denied"
  833. // we try to get at least parent directory (see "else" statement below)
  834. if (FOutput->Count > 0)
  835. {
  836. // Copy LS command output, because eventual symlink analysis would
  837. // modify FTerminal->Output
  838. OutputCopy = new TStringList();
  839. OutputCopy->Assign(FOutput);
  840. // delete leading "total xxx" line
  841. // On some hosts there is not "total" but "totalt". What's the reason??
  842. // see mail from "Jan Wiklund (SysOp)" <[email protected]>
  843. if (IsTotalListingLine(OutputCopy->Strings[0]))
  844. {
  845. OutputCopy->Delete(0);
  846. }
  847. for (int Index = 0; Index < OutputCopy->Count; Index++)
  848. {
  849. File = CreateRemoteFile(OutputCopy->Strings[Index]);
  850. FileList->AddFile(File);
  851. }
  852. }
  853. else
  854. {
  855. // Empty file list -> probably "permision denied", we
  856. // at least get link to parent directory ("..")
  857. FTerminal->ReadFile(
  858. UnixIncludeTrailingBackslash(FTerminal->FFiles->Directory) +
  859. PARENTDIRECTORY, File);
  860. assert(File->IsParentDirectory);
  861. FileList->AddFile(File);
  862. }
  863. }
  864. __finally
  865. {
  866. delete OutputCopy;
  867. }
  868. }
  869. //---------------------------------------------------------------------------
  870. void __fastcall TSCPFileSystem::ReadSymlink(TRemoteFile * SymlinkFile,
  871. TRemoteFile *& File)
  872. {
  873. CustomReadFile(SymlinkFile->LinkTo, File, SymlinkFile);
  874. }
  875. //---------------------------------------------------------------------------
  876. void __fastcall TSCPFileSystem::ReadFile(const AnsiString FileName,
  877. TRemoteFile *& File)
  878. {
  879. CustomReadFile(FileName, File, NULL);
  880. }
  881. //---------------------------------------------------------------------------
  882. TRemoteFile * __fastcall TSCPFileSystem::CreateRemoteFile(
  883. const AnsiString & ListingStr, TRemoteFile * LinkedByFile)
  884. {
  885. TRemoteFile * File = new TRemoteFile(LinkedByFile);
  886. try
  887. {
  888. File->Terminal = FTerminal;
  889. File->ListingStr = ListingStr;
  890. File->ShiftTime(FTerminal->SessionData->TimeDifference);
  891. File->Complete();
  892. }
  893. catch(...)
  894. {
  895. delete File;
  896. throw;
  897. }
  898. return File;
  899. }
  900. //---------------------------------------------------------------------------
  901. void __fastcall TSCPFileSystem::CustomReadFile(const AnsiString FileName,
  902. TRemoteFile *& File, TRemoteFile * ALinkedByFile)
  903. {
  904. File = NULL;
  905. ExecCommand(fsListFile, ARRAYOFCONST((DelimitStr(FileName))));
  906. if (FOutput->Count)
  907. {
  908. int LineIndex = 0;
  909. if (IsTotalListingLine(FOutput->Strings[LineIndex]) && FOutput->Count > 1)
  910. {
  911. LineIndex++;
  912. }
  913. File = CreateRemoteFile(FOutput->Strings[LineIndex], ALinkedByFile);
  914. }
  915. }
  916. //---------------------------------------------------------------------------
  917. void __fastcall TSCPFileSystem::DeleteFile(const AnsiString FileName,
  918. const TRemoteFile * File, bool Recursive)
  919. {
  920. USEDPARAM(Recursive);
  921. USEDPARAM(File);
  922. assert(Recursive || (File && File->IsSymLink));
  923. ExecCommand(fsDeleteFile, ARRAYOFCONST((DelimitStr(FileName))));
  924. }
  925. //---------------------------------------------------------------------------
  926. void __fastcall TSCPFileSystem::RenameFile(const AnsiString FileName,
  927. const AnsiString NewName)
  928. {
  929. ExecCommand(fsRenameFile, ARRAYOFCONST((DelimitStr(FileName), DelimitStr(NewName))));
  930. }
  931. //---------------------------------------------------------------------------
  932. void __fastcall TSCPFileSystem::CreateDirectory(const AnsiString DirName,
  933. const TRemoteProperties * Properties)
  934. {
  935. USEDPARAM(Properties);
  936. assert(!Properties); // not implemented yet
  937. ExecCommand(fsCreateDirectory, ARRAYOFCONST((DelimitStr(DirName))));
  938. }
  939. //---------------------------------------------------------------------------
  940. void __fastcall TSCPFileSystem::CreateLink(const AnsiString FileName,
  941. const AnsiString PointTo, bool Symbolic)
  942. {
  943. ExecCommand(fsCreateLink,
  944. ARRAYOFCONST((Symbolic ? "-s" : "", DelimitStr(PointTo), DelimitStr(FileName))));
  945. }
  946. //---------------------------------------------------------------------------
  947. void __fastcall TSCPFileSystem::ChangeFileProperties(const AnsiString FileName,
  948. const TRemoteFile * File, const TRemoteProperties * Properties)
  949. {
  950. assert(Properties);
  951. bool IsDirectory = File && File->IsDirectory;
  952. bool Recursive = Properties->Recursive && IsDirectory;
  953. AnsiString RecursiveStr = Recursive ? "-R" : "";
  954. AnsiString DelimitedName = DelimitStr(FileName);
  955. if (Properties->Valid.Contains(vpRights))
  956. {
  957. TRights Rights = Properties->Rights;
  958. // if we don't set modes recursively, we may add X at once with other
  959. // options. Otherwise we have to add X after recusive command
  960. if (!Recursive && IsDirectory && Properties->AddXToDirectories)
  961. Rights.AddExecute();
  962. ExecCommand(fsChangeMode,
  963. ARRAYOFCONST((RecursiveStr, Rights.SimplestStr, DelimitedName)));
  964. // if file is directory and we do recursive mode settings with
  965. // add-x-to-directories option on, add those X
  966. if (Recursive && IsDirectory && Properties->AddXToDirectories)
  967. {
  968. Rights.AddExecute();
  969. ExecCommand(fsChangeMode,
  970. ARRAYOFCONST(("", Rights.SimplestStr, DelimitedName)));
  971. }
  972. }
  973. if (Properties->Valid.Contains(vpGroup))
  974. {
  975. ExecCommand(fsChangeGroup,
  976. ARRAYOFCONST((RecursiveStr, Properties->Group, DelimitedName)));
  977. }
  978. if (Properties->Valid.Contains(vpOwner))
  979. {
  980. ExecCommand(fsChangeOwner,
  981. ARRAYOFCONST((RecursiveStr, DelimitStr(Properties->Owner), DelimitedName)));
  982. }
  983. }
  984. //---------------------------------------------------------------------------
  985. void __fastcall TSCPFileSystem::CustomCommandOnFile(const AnsiString FileName,
  986. const TRemoteFile * File, AnsiString Command, int Params)
  987. {
  988. assert(File);
  989. bool Dir = File->IsDirectory && !File->IsSymLink;
  990. if (Dir && (Params & ccRecursive))
  991. {
  992. TCustomCommandParams AParams;
  993. AParams.Command = Command;
  994. AParams.Params = Params;
  995. FTerminal->ProcessDirectory(FileName, FTerminal->CustomCommandOnFile,
  996. &AParams);
  997. }
  998. if (!Dir || (Params & ccApplyToDirectories))
  999. {
  1000. AnsiString Cmd = CompleteCustomCommand(Command, FileName, NULL);
  1001. AnyCommand(Cmd);
  1002. }
  1003. }
  1004. //---------------------------------------------------------------------------
  1005. void __fastcall TSCPFileSystem::AnyCommand(const AnsiString Command)
  1006. {
  1007. ExecCommand(fsAnyCommand, ARRAYOFCONST((Command)));
  1008. }
  1009. //---------------------------------------------------------------------------
  1010. // transfer protocol
  1011. //---------------------------------------------------------------------------
  1012. void __fastcall TSCPFileSystem::SCPResponse(bool * GotLastLine)
  1013. {
  1014. // Taken from scp.c response() and modified
  1015. char Resp;
  1016. FTerminal->Receive(&Resp, 1);
  1017. switch (Resp)
  1018. {
  1019. case 0: /* ok */
  1020. FTerminal->LogEvent("SCP remote side confirmation (0)");
  1021. return;
  1022. default:
  1023. case 1: /* error */
  1024. case 2: /* fatal error */
  1025. // pscp adds 'Resp' to 'Msg', why?
  1026. AnsiString Msg = FTerminal->ReceiveLine();
  1027. AnsiString Line = AnsiString(Resp) + Msg;
  1028. if (IsLastLine(Line))
  1029. {
  1030. if (GotLastLine)
  1031. {
  1032. *GotLastLine = true;
  1033. }
  1034. /* TODO 1 : Show stderror to user? */
  1035. FTerminal->ClearStdError();
  1036. try
  1037. {
  1038. ReadCommandOutput(coExpectNoOutput | coRaiseExcept | coOnlyReturnCode);
  1039. }
  1040. catch(...)
  1041. {
  1042. // when ReadCommandOutput() fails than remote SCP is terminated already
  1043. *GotLastLine = true;
  1044. throw;
  1045. }
  1046. }
  1047. else
  1048. if (Resp == 1)
  1049. {
  1050. FTerminal->LogEvent("SCP remote side error (1):");
  1051. }
  1052. else
  1053. {
  1054. FTerminal->LogEvent("SCP remote side fatal error (2):");
  1055. }
  1056. if (Resp == 1)
  1057. {
  1058. THROW_FILE_SKIPPED(NULL, Msg);
  1059. }
  1060. else
  1061. {
  1062. THROW_SCP_ERROR(NULL, Msg);
  1063. }
  1064. }
  1065. }
  1066. //---------------------------------------------------------------------------
  1067. void __fastcall TSCPFileSystem::CopyToRemote(TStrings * FilesToCopy,
  1068. const AnsiString TargetDir, const TCopyParamType * CopyParam,
  1069. int Params, TFileOperationProgressType * OperationProgress,
  1070. bool & DisconnectWhenComplete)
  1071. {
  1072. // scp.c: source(), toremote()
  1073. assert(FilesToCopy && OperationProgress);
  1074. AnsiString Options = "";
  1075. bool CheckExistence = UnixComparePaths(TargetDir, FTerminal->CurrentDirectory);
  1076. bool CopyBatchStarted = false;
  1077. bool Failed = true;
  1078. bool GotLastLine = false;
  1079. if (CopyParam->PreserveRights) Options = "-p";
  1080. if (FTerminal->SessionData->Scp1Compatibility) Options += " -1";
  1081. SendCommand(FCommandSet->FullCommand(fsCopyToRemote,
  1082. ARRAYOFCONST((Options, DelimitStr(UnixExcludeTrailingBackslash(TargetDir))))));
  1083. SkipFirstLine();
  1084. try
  1085. {
  1086. try
  1087. {
  1088. SCPResponse(&GotLastLine);
  1089. // This can happen only if SCP command is not executed and return code is 0
  1090. // It has never happened to me (return code is usually 127)
  1091. if (GotLastLine)
  1092. {
  1093. throw Exception("");
  1094. }
  1095. }
  1096. catch(Exception & E)
  1097. {
  1098. if (GotLastLine && FTerminal->Active)
  1099. {
  1100. FTerminal->TerminalError(&E, LoadStr(SCP_INIT_ERROR));
  1101. }
  1102. else
  1103. {
  1104. throw;
  1105. }
  1106. }
  1107. CopyBatchStarted = true;
  1108. for (int IFile = 0; (IFile < FilesToCopy->Count) &&
  1109. !OperationProgress->Cancel; IFile++)
  1110. {
  1111. AnsiString FileName = FilesToCopy->Strings[IFile];
  1112. bool CanProceed;
  1113. AnsiString FileNameOnly =
  1114. CopyParam->ChangeFileName(ExtractFileName(FileName), osLocal, true);
  1115. if (CheckExistence)
  1116. {
  1117. assert(FTerminal->FFiles && FTerminal->FFiles->Loaded);
  1118. TRemoteFile * File = FTerminal->FFiles->FindFile(FileNameOnly);
  1119. if (File && OperationProgress->NoToAll)
  1120. {
  1121. CanProceed = false;
  1122. }
  1123. else if (File && !OperationProgress->YesToAll &&
  1124. FTerminal->Configuration->ConfirmOverwriting && !(Params & cpNoConfirmation))
  1125. {
  1126. int Answer;
  1127. if (File->IsDirectory)
  1128. {
  1129. TQueryParams Params(qpNeverAskAgainCheck);
  1130. SUSPEND_OPERATION
  1131. (
  1132. Answer = FTerminal->DoQueryUser(
  1133. FMTLOAD(DIRECTORY_OVERWRITE, (FileNameOnly)),
  1134. qaYes | qaNo | qaAbort | qaYesToAll | qaNoToAll,
  1135. &Params);
  1136. );
  1137. switch (Answer)
  1138. {
  1139. case qaNeverAskAgain:
  1140. FTerminal->Configuration->ConfirmOverwriting = false;
  1141. Answer = qaYes;
  1142. break;
  1143. case qaYesToAll:
  1144. OperationProgress->YesToAll = true;
  1145. Answer = qaYes;
  1146. break;
  1147. case qaNoToAll:
  1148. OperationProgress->NoToAll = true;
  1149. Answer = qaNo;
  1150. break;
  1151. }
  1152. }
  1153. else
  1154. {
  1155. unsigned long MTime;
  1156. TOverwriteFileParams FileParams;
  1157. FTerminal->OpenLocalFile(FileName, GENERIC_READ,
  1158. NULL, NULL, NULL, &MTime, NULL,
  1159. &FileParams.SourceSize);
  1160. FileParams.SourceTimestamp = UnixToDateTime(MTime,
  1161. FTerminal->SessionData->ConsiderDST);
  1162. FileParams.DestSize = File->Size;
  1163. FileParams.DestTimestamp = File->Modification;
  1164. TQueryButtonAlias Aliases[1];
  1165. Aliases[0].Button = qaAll;
  1166. Aliases[0].Alias = LoadStr(YES_TO_NEWER_BUTTON);
  1167. TQueryParams Params(qpNeverAskAgainCheck);
  1168. Params.Aliases = Aliases;
  1169. Params.AliasesCount = LENOF(Aliases);
  1170. SUSPEND_OPERATION
  1171. (
  1172. Answer = FTerminal->ConfirmFileOverwrite(
  1173. FileNameOnly, &FileParams,
  1174. qaYes | qaNo | qaAbort | qaYesToAll | qaNoToAll | qaAll,
  1175. &Params, osRemote, OperationProgress);
  1176. );
  1177. }
  1178. switch (Answer) {
  1179. case qaYes:
  1180. CanProceed = true;
  1181. break;
  1182. case qaAbort:
  1183. if (!OperationProgress->Cancel) OperationProgress->Cancel = csCancel;
  1184. case qaNo:
  1185. CanProceed = false;
  1186. break;
  1187. default:
  1188. assert(false);
  1189. }
  1190. }
  1191. else CanProceed = true;
  1192. }
  1193. else CanProceed = true;
  1194. if (CanProceed)
  1195. {
  1196. if (FTerminal->SessionData->CacheDirectories)
  1197. {
  1198. FTerminal->DirectoryModified(TargetDir, false);
  1199. if (DirectoryExists(FileName))
  1200. {
  1201. FTerminal->DirectoryModified(UnixIncludeTrailingBackslash(TargetDir)+
  1202. FileNameOnly, true);
  1203. }
  1204. }
  1205. try
  1206. {
  1207. SCPSource(FileName, CopyParam, Params, OperationProgress, 0);
  1208. OperationProgress->Finish(FileName, true, DisconnectWhenComplete);
  1209. }
  1210. catch (EScpFileSkipped &E)
  1211. {
  1212. TQueryParams Params(qpAllowContinueOnError);
  1213. SUSPEND_OPERATION (
  1214. if (FTerminal->DoQueryUser(FMTLOAD(COPY_ERROR, (FileName)), E.Message,
  1215. qaOK | qaAbort, &Params) == qaAbort)
  1216. {
  1217. OperationProgress->Cancel = csCancel;
  1218. }
  1219. OperationProgress->Finish(FileName, false, DisconnectWhenComplete);
  1220. if (!FTerminal->HandleException(&E)) throw;
  1221. );
  1222. }
  1223. catch (EScpSkipFile &E)
  1224. {
  1225. OperationProgress->Finish(FileName, false, DisconnectWhenComplete);
  1226. // If ESkipFile occurs, just log it and continue with next file
  1227. SUSPEND_OPERATION (
  1228. if (!FTerminal->HandleException(&E)) throw;
  1229. );
  1230. }
  1231. catch (...)
  1232. {
  1233. OperationProgress->Finish(FileName, false, DisconnectWhenComplete);
  1234. throw;
  1235. }
  1236. }
  1237. }
  1238. Failed = false;
  1239. }
  1240. __finally
  1241. {
  1242. // Tell remote side, that we're done.
  1243. if (FTerminal->Active)
  1244. {
  1245. try
  1246. {
  1247. if (!GotLastLine)
  1248. {
  1249. if (CopyBatchStarted)
  1250. {
  1251. // What about case, remote side sends fatal error ???
  1252. // (Not sure, if it causes remote side to terminate scp)
  1253. FTerminal->SendLine("E");
  1254. SCPResponse();
  1255. };
  1256. /* TODO 1 : Show stderror to user? */
  1257. FTerminal->ClearStdError();
  1258. ReadCommandOutput(coExpectNoOutput | coWaitForLastLine | coOnlyReturnCode |
  1259. (Failed ? 0 : coRaiseExcept));
  1260. }
  1261. }
  1262. catch (Exception &E)
  1263. {
  1264. // Only show error message (it should always succeed, but
  1265. // some pending error maybe in queque) }
  1266. FTerminal->DoHandleExtendedException(&E);
  1267. }
  1268. }
  1269. }
  1270. }
  1271. //---------------------------------------------------------------------------
  1272. void __fastcall TSCPFileSystem::SCPSource(const AnsiString FileName,
  1273. const TCopyParamType * CopyParam, int Params,
  1274. TFileOperationProgressType * OperationProgress, int Level)
  1275. {
  1276. if (FLAGCLEAR(Params, cpDelete) &&
  1277. !CopyParam->AllowTransfer(ExtractFileName(FileName)))
  1278. {
  1279. FTerminal->LogEvent(FORMAT("File \"%s\" excluded from transfer", (FileName)));
  1280. THROW_SKIP_FILE_NULL;
  1281. }
  1282. AnsiString DestFileName = CopyParam->ChangeFileName(
  1283. ExtractFileName(FileName), osLocal, Level == 0);
  1284. FTerminal->LogEvent(FORMAT("File: \"%s\"", (FileName)));
  1285. OperationProgress->SetFile(FileName);
  1286. HANDLE File;
  1287. int Attrs;
  1288. unsigned long MTime, ATime;
  1289. __int64 Size;
  1290. FTerminal->OpenLocalFile(FileName, GENERIC_READ,
  1291. &Attrs, &File, NULL, &MTime, &ATime, &Size);
  1292. if (Attrs & faDirectory)
  1293. {
  1294. SCPDirectorySource(FileName, CopyParam, Params, OperationProgress, Level);
  1295. }
  1296. else
  1297. try
  1298. {
  1299. assert(File);
  1300. // File is regular file (not directory)
  1301. FTerminal->LogEvent(FORMAT("Copying \"%s\" to remote directory started.", (FileName)));
  1302. OperationProgress->SetLocalSize(Size);
  1303. // Suppose same data size to transfer as to read
  1304. // (not true with ASCII transfer)
  1305. OperationProgress->SetTransferSize(OperationProgress->LocalSize);
  1306. OperationProgress->TransferingFile = false;
  1307. // Will we use ASCII of BINARY file tranfer?
  1308. OperationProgress->SetAsciiTransfer(CopyParam->UseAsciiTransfer(FileName));
  1309. FTerminal->LogEvent(
  1310. AnsiString((OperationProgress->AsciiTransfer ? "Ascii" : "Binary")) +
  1311. " transfer mode selected.");
  1312. try
  1313. {
  1314. // During ASCII transfer we will load whole file to this buffer
  1315. // than convert EOL and send it at once, because before converting EOL
  1316. // we can't know its size
  1317. TFileBuffer AsciiBuf;
  1318. do
  1319. {
  1320. // Buffer for one block of data
  1321. TFileBuffer BlockBuf;
  1322. // This is crucial, if it fails during file transfer, it's fatal error
  1323. FILE_OPERATION_LOOP (FMTLOAD(READ_ERROR, (FileName)),
  1324. BlockBuf.LoadFile(File, OperationProgress->LocalBlockSize(), true);
  1325. );
  1326. OperationProgress->AddLocalyUsed(BlockBuf.Size);
  1327. // We do ASCII transfer: convert EOL of current block
  1328. // (we don't convert whole buffer, cause it would produce
  1329. // huge memory-transfers while inserting/deleting EOL characters)
  1330. // Than we add current block to file buffer
  1331. if (OperationProgress->AsciiTransfer)
  1332. {
  1333. BlockBuf.Convert(FTerminal->Configuration->LocalEOLType,
  1334. FTerminal->SessionData->EOLType, cpRemoveCtrlZ);
  1335. BlockBuf.Memory->Seek(0, soFromBeginning);
  1336. AsciiBuf.ReadStream(BlockBuf.Memory, BlockBuf.Size, true);
  1337. // We don't need it any more
  1338. BlockBuf.Memory->Clear();
  1339. // Calculate total size to sent (assume that ratio between
  1340. // size of source and size of EOL-transformed data would remain same)
  1341. // First check if file contains anything (div by zero!)
  1342. if (OperationProgress->LocalyUsed)
  1343. {
  1344. __int64 X = OperationProgress->LocalSize;
  1345. X *= AsciiBuf.Size;
  1346. X /= OperationProgress->LocalyUsed;
  1347. OperationProgress->ChangeTransferSize(X);
  1348. }
  1349. else
  1350. {
  1351. OperationProgress->ChangeTransferSize(0);
  1352. }
  1353. }
  1354. // We send file information on first pass during BINARY transfer
  1355. // and on last pass during ASCII transfer
  1356. // BINARY: We succeeded reading first buffer from file, hopefully
  1357. // we will be able to read whole, so we send file info to remote side
  1358. // This is done, because when reading fails we can't interrupt sending
  1359. // (don't know how to tell other side that it failed)
  1360. if (!OperationProgress->TransferingFile &&
  1361. (!OperationProgress->AsciiTransfer || OperationProgress->IsLocalyDone()))
  1362. {
  1363. AnsiString Buf;
  1364. if (CopyParam->PreserveTime)
  1365. {
  1366. // Send last file access and modification time
  1367. // TVarRec don't understand 'unsigned int' -> we use sprintf()
  1368. Buf.sprintf("T%lu 0 %lu 0", MTime, ATime);
  1369. FTerminal->SendLine(Buf);
  1370. SCPResponse();
  1371. }
  1372. // Send file modes (rights), filesize and file name
  1373. // TVarRec don't understand 'unsigned int' -> we use sprintf()
  1374. Buf.sprintf("C%s %Ld %s",
  1375. CopyParam->RemoteFileRights(Attrs).Octal.data(),
  1376. (OperationProgress->AsciiTransfer ? (__int64)AsciiBuf.Size :
  1377. OperationProgress->LocalSize),
  1378. DestFileName.data());
  1379. FTerminal->SendLine(Buf);
  1380. SCPResponse();
  1381. // Indicate we started transfering file, we need to finish it
  1382. // If not, it's fatal error
  1383. OperationProgress->TransferingFile = true;
  1384. // If we're doing ASCII transfer, this is last pass
  1385. // so we send whole file
  1386. /* TODO : We can't send file above 32bit size in ASCII mode! */
  1387. if (OperationProgress->AsciiTransfer)
  1388. {
  1389. FTerminal->LogEvent(FORMAT("Sending ASCII data (%ud bytes)",
  1390. (AsciiBuf.Size)));
  1391. // Should be equal, just in case it's rounded (see above)
  1392. OperationProgress->ChangeTransferSize(AsciiBuf.Size);
  1393. while (!OperationProgress->IsTransferDone())
  1394. {
  1395. FTerminal->Send(
  1396. AsciiBuf.Data + (unsigned int)OperationProgress->TransferedSize,
  1397. OperationProgress->TransferBlockSize());
  1398. OperationProgress->AddTransfered(OperationProgress->TransferBlockSize());
  1399. }
  1400. }
  1401. }
  1402. // At end of BINARY transfer pass, send current block
  1403. if (!OperationProgress->AsciiTransfer)
  1404. {
  1405. if (!OperationProgress->TransferedSize)
  1406. {
  1407. FTerminal->LogEvent("Sending BINARY data (first block)");
  1408. }
  1409. FTerminal->Send(BlockBuf.Data, BlockBuf.Size);
  1410. OperationProgress->AddTransfered(BlockBuf.Size);
  1411. }
  1412. if ((OperationProgress->Cancel == csCancelTransfer) ||
  1413. (OperationProgress->Cancel == csCancel && !OperationProgress->TransferingFile))
  1414. {
  1415. throw Exception(USER_TERMINATED);
  1416. }
  1417. }
  1418. while (!OperationProgress->IsLocalyDone() || !OperationProgress->IsTransferDone());
  1419. FTerminal->SendNull();
  1420. try
  1421. {
  1422. SCPResponse();
  1423. // If one of two following exceptions occurs, is means, that remote
  1424. // side already know, that file transfer finished, even if it failed
  1425. // so we don't have to throw EFatal
  1426. }
  1427. catch (EScp &E)
  1428. {
  1429. // SCP protocol fatal error
  1430. OperationProgress->TransferingFile = false;
  1431. throw;
  1432. }
  1433. catch (EScpFileSkipped &E)
  1434. {
  1435. // SCP protocol non-fatal error
  1436. OperationProgress->TransferingFile = false;
  1437. throw;
  1438. }
  1439. // We succeded transfering file, from now we can handle exceptions
  1440. // normally -> no fatal error
  1441. OperationProgress->TransferingFile = false;
  1442. }
  1443. catch (Exception &E)
  1444. {
  1445. // Every exception during file transfer is fatal
  1446. if (OperationProgress->TransferingFile)
  1447. {
  1448. FTerminal->FatalError(&E, FMTLOAD(COPY_FATAL, (FileName)));
  1449. }
  1450. else
  1451. {
  1452. throw;
  1453. }
  1454. }
  1455. }
  1456. __finally
  1457. {
  1458. CloseHandle(File);
  1459. }
  1460. /* TODO : Delete also read-only files. */
  1461. /* TODO : Show error message on failure. */
  1462. if (Params & cpDelete) Sysutils::DeleteFile(FileName);
  1463. FTerminal->LogEvent(FORMAT("Copying \"%s\" to remote directory finished.", (FileName)));
  1464. }
  1465. //---------------------------------------------------------------------------
  1466. void __fastcall TSCPFileSystem::SCPDirectorySource(const AnsiString DirectoryName,
  1467. const TCopyParamType * CopyParam, int Params,
  1468. TFileOperationProgressType * OperationProgress, int Level)
  1469. {
  1470. int Attrs;
  1471. FTerminal->LogEvent(FORMAT("Entering directory \"%s\".", (DirectoryName)));
  1472. OperationProgress->SetFile(DirectoryName);
  1473. AnsiString DestFileName = CopyParam->ChangeFileName(
  1474. ExtractFileName(DirectoryName), osLocal, Level == 0);
  1475. // Get directory attributes
  1476. FILE_OPERATION_LOOP (FMTLOAD(CANT_GET_ATTRS, (DirectoryName)),
  1477. Attrs = FileGetAttr(DirectoryName);
  1478. if (Attrs == -1) EXCEPTION;
  1479. )
  1480. AnsiString Buf;
  1481. /* TODO 1: maybe send filetime */
  1482. // Send directory modes (rights), filesize and file name
  1483. Buf = FORMAT("D%s 0 %s",
  1484. (CopyParam->RemoteFileRights(Attrs).Octal, DestFileName));
  1485. FTerminal->SendLine(Buf);
  1486. SCPResponse();
  1487. try
  1488. {
  1489. int FindAttrs = faReadOnly | faHidden | faSysFile | faDirectory | faArchive;
  1490. TSearchRec SearchRec;
  1491. bool FindOK;
  1492. FILE_OPERATION_LOOP (FMTLOAD(LIST_DIR_ERROR, (DirectoryName)),
  1493. FindOK = (bool)(FindFirst(IncludeTrailingBackslash(DirectoryName) + "*.*",
  1494. FindAttrs, SearchRec) == 0);
  1495. );
  1496. while (FindOK && !OperationProgress->Cancel)
  1497. {
  1498. AnsiString FileName = IncludeTrailingBackslash(DirectoryName) + SearchRec.Name;
  1499. try
  1500. {
  1501. if ((SearchRec.Name != ".") && (SearchRec.Name != ".."))
  1502. {
  1503. SCPSource(FileName, CopyParam, Params, OperationProgress, Level + 1);
  1504. }
  1505. }
  1506. catch (EScpSkipFile &E)
  1507. {
  1508. TQueryParams Params(qpAllowContinueOnError);
  1509. // If ESkipFile occurs, just log it and continue with next file
  1510. SUSPEND_OPERATION (
  1511. if (FTerminal->DoQueryUser(FMTLOAD(COPY_ERROR, (FileName)), E.Message,
  1512. qaOK | qaAbort, &Params) == qaAbort)
  1513. {
  1514. OperationProgress->Cancel = csCancel;
  1515. }
  1516. if (!FTerminal->HandleException(&E)) throw;
  1517. );
  1518. }
  1519. FILE_OPERATION_LOOP (FMTLOAD(LIST_DIR_ERROR, (DirectoryName)),
  1520. FindOK = (FindNext(SearchRec) == 0);
  1521. );
  1522. };
  1523. FindClose(SearchRec);
  1524. /* TODO : Delete also read-only directories. */
  1525. /* TODO : Show error message on failure. */
  1526. if ((Params & cpDelete) && !OperationProgress->Cancel) RemoveDir(DirectoryName);
  1527. }
  1528. __finally
  1529. {
  1530. if (FTerminal->Active)
  1531. {
  1532. // Tell remote side, that we're done.
  1533. FTerminal->LogEvent(FORMAT("Leaving directory \"%s\".", (DirectoryName)));
  1534. FTerminal->SendLine("E");
  1535. SCPResponse();
  1536. }
  1537. }
  1538. }
  1539. //---------------------------------------------------------------------------
  1540. void __fastcall TSCPFileSystem::CopyToLocal(TStrings * FilesToCopy,
  1541. const AnsiString TargetDir, const TCopyParamType * CopyParam,
  1542. int Params, TFileOperationProgressType * OperationProgress,
  1543. bool & DisconnectWhenComplete)
  1544. {
  1545. bool CloseSCP = False;
  1546. AnsiString Options = "";
  1547. if (CopyParam->PreserveRights || CopyParam->PreserveTime) Options = "-p";
  1548. if (FTerminal->SessionData->Scp1Compatibility) Options += " -1";
  1549. FTerminal->LogEvent(FORMAT("Copying %d files/directories to local directory "
  1550. "\"%s\"", (FilesToCopy->Count, TargetDir)));
  1551. FTerminal->LogEvent(CopyParam->LogStr);
  1552. try
  1553. {
  1554. for (int IFile = 0; (IFile < FilesToCopy->Count) &&
  1555. !OperationProgress->Cancel; IFile++)
  1556. {
  1557. AnsiString FileName = FilesToCopy->Strings[IFile];
  1558. TRemoteFile * File = (TRemoteFile *)FilesToCopy->Objects[IFile];
  1559. assert(File);
  1560. try
  1561. {
  1562. bool Success = true; // Have to be set to True (see ::SCPSink)
  1563. SendCommand(FCommandSet->FullCommand(fsCopyToLocal,
  1564. ARRAYOFCONST((Options, DelimitStr(FileName)))));
  1565. SkipFirstLine();
  1566. // Filename is used only for error messaging
  1567. SCPSink(TargetDir, FileName, CopyParam, Success, OperationProgress,
  1568. Params, 0);
  1569. // operation succeded (no exception), so it's ok that
  1570. // remote side closed SCP, but we continue with next file
  1571. if (OperationProgress->Cancel == csRemoteAbort)
  1572. {
  1573. OperationProgress->Cancel = csContinue;
  1574. }
  1575. // Move operation -> delete file/directory afterwards
  1576. // but only if copying succeded
  1577. if ((Params & cpDelete) && Success && !OperationProgress->Cancel)
  1578. {
  1579. try
  1580. {
  1581. FTerminal->ExceptionOnFail = true;
  1582. try
  1583. {
  1584. FILE_OPERATION_LOOP(FMTLOAD(DELETE_FILE_ERROR, (FileName)),
  1585. // pass full file name in FileName, in case we are not moving
  1586. // from current directory
  1587. FTerminal->DeleteFile(FileName, File)
  1588. );
  1589. }
  1590. __finally
  1591. {
  1592. FTerminal->ExceptionOnFail = false;
  1593. }
  1594. }
  1595. catch (EFatal &E)
  1596. {
  1597. throw;
  1598. }
  1599. catch (...)
  1600. {
  1601. // If user selects skip (or abort), nothing special actualy occures
  1602. // we just run DoFinished with Success = False, so file won't
  1603. // be deselected in panel (depends on assigned event handler)
  1604. // On csCancel we would later try to close remote SCP, but it
  1605. // is closed already
  1606. if (OperationProgress->Cancel == csCancel)
  1607. {
  1608. OperationProgress->Cancel = csRemoteAbort;
  1609. }
  1610. Success = false;
  1611. }
  1612. }
  1613. OperationProgress->Finish(FileName,
  1614. (!OperationProgress->Cancel && Success), DisconnectWhenComplete);
  1615. }
  1616. catch (...)
  1617. {
  1618. OperationProgress->Finish(FileName, false, DisconnectWhenComplete);
  1619. CloseSCP = (OperationProgress->Cancel != csRemoteAbort);
  1620. throw;
  1621. }
  1622. }
  1623. }
  1624. __finally
  1625. {
  1626. // In case that copying don't causes fatal error (ie. connection is
  1627. // still active) but weren't succesful (exception or user termination)
  1628. // we need to ensure, that SCP on remote side is closed
  1629. if (FTerminal->Active && (CloseSCP ||
  1630. (OperationProgress->Cancel == csCancel) ||
  1631. (OperationProgress->Cancel == csCancelTransfer)))
  1632. {
  1633. bool LastLineRead;
  1634. // If we get LastLine, it means that remote side 'scp' is already
  1635. // terminated, so we need not to terminate it. There is also
  1636. // possibility that remote side waits for confirmation, so it will hang.
  1637. // This should not happen (hope)
  1638. AnsiString Line = FTerminal->ReceiveLine();
  1639. LastLineRead = IsLastLine(Line);
  1640. if (!LastLineRead)
  1641. {
  1642. SCPSendError((OperationProgress->Cancel ? "Terminated by user." : "Exception"), true);
  1643. }
  1644. // Just in case, remote side already sent some more data (it's probable)
  1645. // but we don't want to raise exception (user asked to terminate, it's not error)
  1646. int ECParams = coOnlyReturnCode;
  1647. if (!LastLineRead) ECParams |= coWaitForLastLine;
  1648. ReadCommandOutput(ECParams);
  1649. }
  1650. }
  1651. }
  1652. //---------------------------------------------------------------------------
  1653. void __fastcall TSCPFileSystem::SCPError(const AnsiString Message, bool Fatal)
  1654. {
  1655. SCPSendError(Message, Fatal);
  1656. THROW_FILE_SKIPPED(NULL, Message);
  1657. }
  1658. //---------------------------------------------------------------------------
  1659. void __fastcall TSCPFileSystem::SCPSendError(const AnsiString Message, bool Fatal)
  1660. {
  1661. char ErrorLevel = (char)(Fatal ? 2 : 1);
  1662. FTerminal->LogEvent(FORMAT("Sending SCP error (%d) to remote side:",
  1663. ((int)ErrorLevel)));
  1664. FTerminal->Send(&ErrorLevel, 1);
  1665. // We don't send exact error message, because some unspecified
  1666. // characters can terminate remote scp
  1667. FTerminal->SendLine("scp: error");
  1668. }
  1669. //---------------------------------------------------------------------------
  1670. void __fastcall TSCPFileSystem::SCPSink(const AnsiString TargetDir,
  1671. const AnsiString FileName, const TCopyParamType * CopyParam, bool & Success,
  1672. TFileOperationProgressType * OperationProgress, int Params,
  1673. int Level)
  1674. {
  1675. struct
  1676. {
  1677. int SetTime;
  1678. FILETIME AcTime;
  1679. FILETIME WrTime;
  1680. TRights RemoteRights;
  1681. int Attrs;
  1682. bool Exists;
  1683. } FileData;
  1684. TDateTime SourceTimestamp;
  1685. bool SkipConfirmed = false;
  1686. bool Initialized = (Level > 0);
  1687. FileData.SetTime = 0;
  1688. FTerminal->SendNull();
  1689. while (!OperationProgress->Cancel)
  1690. {
  1691. // See (switch ... case 'T':)
  1692. if (FileData.SetTime) FileData.SetTime--;
  1693. // In case of error occured before control record arrived
  1694. OperationProgress->FileName = FileName;
  1695. try
  1696. {
  1697. // Receive control record
  1698. AnsiString Line = FTerminal->ReceiveLine();
  1699. if (Line.Length() == 0) FTerminal->FatalError(LoadStr(SCP_EMPTY_LINE));
  1700. if (IsLastLine(Line))
  1701. {
  1702. // Remote side finished copying, so remote SCP was closed
  1703. // and we don't need to terminate it manualy, see CopyToLocal()
  1704. OperationProgress->Cancel = csRemoteAbort;
  1705. /* TODO 1 : Show stderror to user? */
  1706. FTerminal->ClearStdError();
  1707. try
  1708. {
  1709. // coIgnoreWarnings should allow batch transfer to continue when
  1710. // download of one the files failes (user denies overwritting
  1711. // of target local file, no read permissions...)
  1712. ReadCommandOutput(coExpectNoOutput | coRaiseExcept |
  1713. coOnlyReturnCode | coIgnoreWarnings);
  1714. if (!Initialized)
  1715. {
  1716. throw Exception("");
  1717. }
  1718. }
  1719. catch(Exception & E)
  1720. {
  1721. if (!Initialized && FTerminal->Active)
  1722. {
  1723. FTerminal->TerminalError(&E, LoadStr(SCP_INIT_ERROR));
  1724. }
  1725. else
  1726. {
  1727. throw;
  1728. }
  1729. }
  1730. return;
  1731. }
  1732. else
  1733. {
  1734. Initialized = true;
  1735. // First characted distinguish type of control record
  1736. char Ctrl = Line[1];
  1737. Line.Delete(1, 1);
  1738. switch (Ctrl) {
  1739. case 1:
  1740. // Error (already logged by ReceiveLine())
  1741. THROW_FILE_SKIPPED(NULL, FMTLOAD(REMOTE_ERROR, (Line)));
  1742. case 2:
  1743. // Fatal error, terminate copying
  1744. FTerminal->TerminalError(Line);
  1745. return; // Unreachable
  1746. case 'E': // Exit
  1747. FTerminal->SendNull();
  1748. return;
  1749. case 'T':
  1750. unsigned long MTime, ATime;
  1751. if (sscanf(Line.c_str(), "%ld %*d %ld %*d", &MTime, &ATime) == 2)
  1752. {
  1753. FileData.AcTime = DateTimeToFileTime(UnixToDateTime(ATime,
  1754. FTerminal->SessionData->ConsiderDST), FTerminal->SessionData->ConsiderDST);
  1755. FileData.WrTime = DateTimeToFileTime(UnixToDateTime(MTime,
  1756. FTerminal->SessionData->ConsiderDST), FTerminal->SessionData->ConsiderDST);
  1757. SourceTimestamp = UnixToDateTime(MTime,
  1758. FTerminal->SessionData->ConsiderDST);
  1759. FTerminal->SendNull();
  1760. // File time is only valid until next pass
  1761. FileData.SetTime = 2;
  1762. continue;
  1763. }
  1764. else
  1765. {
  1766. SCPError(LoadStr(SCP_ILLEGAL_TIME_FORMAT), False);
  1767. }
  1768. case 'C':
  1769. case 'D':
  1770. break; // continue pass switch{}
  1771. default:
  1772. FTerminal->FatalError(FMTLOAD(SCP_INVALID_CONTROL_RECORD, (Ctrl, Line)));
  1773. }
  1774. // We reach this point only if control record was 'C' or 'D'
  1775. try
  1776. {
  1777. FileData.RemoteRights.Octal = CutToChar(Line, ' ', True);
  1778. __int64 TSize = StrToInt64(CutToChar(Line, ' ', True));
  1779. // Security fix: ensure the file ends up where we asked for it.
  1780. // (accept only filename, not path)
  1781. AnsiString OnlyFileName = UnixExtractFileName(Line);
  1782. if (Line != OnlyFileName)
  1783. {
  1784. FTerminal->LogEvent(FORMAT("Warning: Remote host set a compound pathname '%s'", (Line)));
  1785. }
  1786. OperationProgress->SetFile(OnlyFileName);
  1787. OperationProgress->SetTransferSize(TSize);
  1788. }
  1789. catch (Exception &E)
  1790. {
  1791. SUSPEND_OPERATION (
  1792. FTerminal->DoHandleExtendedException(&E);
  1793. );
  1794. SCPError(LoadStr(SCP_ILLEGAL_FILE_DESCRIPTOR), false);
  1795. }
  1796. // last possibility to cancel transfer before it starts
  1797. if (OperationProgress->Cancel)
  1798. {
  1799. THROW_SKIP_FILE(NULL, LoadStr(USER_TERMINATED));
  1800. }
  1801. // Security fix
  1802. if (IsDots(OperationProgress->FileName))
  1803. {
  1804. FTerminal->FatalError(LoadStr(ATTEMPT_TO_WRITE_TO_PARENT_DIR));
  1805. }
  1806. if (FLAGCLEAR(Params, cpDelete) &&
  1807. !CopyParam->AllowTransfer(OperationProgress->FileName))
  1808. {
  1809. FTerminal->LogEvent(FORMAT("File \"%s\" excluded from transfer",
  1810. (OperationProgress->FileName)));
  1811. SkipConfirmed = true;
  1812. SCPError("", false);
  1813. }
  1814. AnsiString DestFileName =
  1815. IncludeTrailingBackslash(TargetDir) +
  1816. CopyParam->ChangeFileName(OperationProgress->FileName, osRemote,
  1817. Level == 0);
  1818. FileData.Attrs = FileGetAttr(DestFileName);
  1819. // If getting attrs failes, we suppose, that file/folder doesn't exists
  1820. FileData.Exists = (FileData.Attrs != -1);
  1821. if (Ctrl == 'D')
  1822. {
  1823. if (FileData.Exists && !(FileData.Attrs & faDirectory))
  1824. {
  1825. SCPError(FMTLOAD(NOT_DIRECTORY_ERROR, (DestFileName)), false);
  1826. }
  1827. if (!FileData.Exists)
  1828. {
  1829. FILE_OPERATION_LOOP (FMTLOAD(CREATE_DIR_ERROR, (DestFileName)),
  1830. if (!ForceDirectories(DestFileName)) EXCEPTION;
  1831. );
  1832. /* SCP: can we set the timestamp for directories ? */
  1833. }
  1834. /* TODO 1 : Send whole path, CopyData.SourceFileName is not enough
  1835. (just error messaging)*/
  1836. SCPSink(DestFileName, OperationProgress->FileName, CopyParam,
  1837. Success, OperationProgress, Params, Level + 1);
  1838. continue;
  1839. }
  1840. else
  1841. if (Ctrl == 'C')
  1842. {
  1843. HANDLE File = NULL;
  1844. TStream * FileStream = NULL;
  1845. /* TODO 1 : Turn off read-only attr */
  1846. try
  1847. {
  1848. try
  1849. {
  1850. if (FileExists(DestFileName))
  1851. {
  1852. int Answer;
  1853. if (OperationProgress->NoToAll)
  1854. {
  1855. Answer = qaNo;
  1856. }
  1857. // if overwrite confirmation is required or
  1858. // only newer files should be transfered, get both file timestamps
  1859. else if (FLAGSET(Params, cpNewerOnly) ||
  1860. (!OperationProgress->YesToAll &&
  1861. FTerminal->Configuration->ConfirmOverwriting &&
  1862. FLAGCLEAR(Params, cpNoConfirmation)))
  1863. {
  1864. unsigned long MTime;
  1865. TOverwriteFileParams FileParams;
  1866. FileParams.SourceSize = OperationProgress->TransferSize;
  1867. FileParams.SourceTimestamp = SourceTimestamp;
  1868. FTerminal->OpenLocalFile(DestFileName, GENERIC_READ,
  1869. NULL, NULL, NULL, &MTime, NULL,
  1870. &FileParams.DestSize);
  1871. FileParams.DestTimestamp = UnixToDateTime(MTime,
  1872. FTerminal->SessionData->ConsiderDST);
  1873. TQueryButtonAlias Aliases[1];
  1874. Aliases[0].Button = qaAll;
  1875. Aliases[0].Alias = LoadStr(YES_TO_NEWER_BUTTON);
  1876. TQueryParams Params(qpNeverAskAgainCheck);
  1877. Params.Aliases = Aliases;
  1878. Params.AliasesCount = LENOF(Aliases);
  1879. SUSPEND_OPERATION (
  1880. Answer = FTerminal->ConfirmFileOverwrite(
  1881. OperationProgress->FileName, &FileParams,
  1882. qaYes | qaNo | qaAbort | qaYesToAll | qaNoToAll | qaAll,
  1883. &Params, osLocal, OperationProgress);
  1884. );
  1885. }
  1886. switch (Answer)
  1887. {
  1888. case qaAbort: OperationProgress->Cancel = csCancel; // continue on next case
  1889. case qaNo: SkipConfirmed = true; EXCEPTION;
  1890. }
  1891. }
  1892. if (!FTerminal->CreateLocalFile(DestFileName, OperationProgress, &File))
  1893. {
  1894. SkipConfirmed = true;
  1895. EXCEPTION;
  1896. }
  1897. FileStream = new THandleStream((THandle)File);
  1898. }
  1899. catch (Exception &E)
  1900. {
  1901. // In this step we can still cancel transfer, so we do it
  1902. SCPError(E.Message, false);
  1903. throw;
  1904. }
  1905. // We succeded, so we confirm transfer to remote side
  1906. FTerminal->SendNull();
  1907. // From now we need to finish file transfer, if not it's fatal error
  1908. OperationProgress->TransferingFile = true;
  1909. // Suppose same data size to transfer as to write
  1910. // (not true with ASCII transfer)
  1911. OperationProgress->SetLocalSize(OperationProgress->TransferSize);
  1912. // Will we use ASCII of BINARY file tranfer?
  1913. OperationProgress->SetAsciiTransfer(CopyParam->UseAsciiTransfer(DestFileName));
  1914. FTerminal->LogEvent(AnsiString((OperationProgress->AsciiTransfer ? "Ascii" : "Binary")) +
  1915. " transfer mode selected.");
  1916. try
  1917. {
  1918. // Buffer for one block of data
  1919. TFileBuffer BlockBuf;
  1920. do
  1921. {
  1922. BlockBuf.Size = OperationProgress->TransferBlockSize();
  1923. BlockBuf.Position = 0;
  1924. FTerminal->Receive(BlockBuf.Data, BlockBuf.Size);
  1925. OperationProgress->AddTransfered(BlockBuf.Size);
  1926. if (OperationProgress->AsciiTransfer)
  1927. {
  1928. unsigned int PrevBlockSize = BlockBuf.Size;
  1929. BlockBuf.Convert(FTerminal->SessionData->EOLType,
  1930. FTerminal->Configuration->LocalEOLType, 0);
  1931. OperationProgress->SetLocalSize(
  1932. OperationProgress->LocalSize - PrevBlockSize + BlockBuf.Size);
  1933. }
  1934. // This is crucial, if it fails during file transfer, it's fatal error
  1935. FILE_OPERATION_LOOP_EX (false, FMTLOAD(WRITE_ERROR, (DestFileName)),
  1936. BlockBuf.WriteToStream(FileStream, BlockBuf.Size);
  1937. );
  1938. OperationProgress->AddLocalyUsed(BlockBuf.Size);
  1939. if (OperationProgress->Cancel == csCancelTransfer)
  1940. {
  1941. throw Exception(USER_TERMINATED);
  1942. }
  1943. }
  1944. while (!OperationProgress->IsLocalyDone() || !
  1945. OperationProgress->IsTransferDone());
  1946. }
  1947. catch (Exception &E)
  1948. {
  1949. // Every exception during file transfer is fatal
  1950. FTerminal->FatalError(&E,
  1951. FMTLOAD(COPY_FATAL, (OperationProgress->FileName)));
  1952. }
  1953. OperationProgress->TransferingFile = false;
  1954. try
  1955. {
  1956. SCPResponse();
  1957. // If one of following exception occurs, we still need
  1958. // to send confirmation to other side
  1959. }
  1960. catch (EScp &E)
  1961. {
  1962. FTerminal->SendNull();
  1963. throw;
  1964. }
  1965. catch (EScpFileSkipped &E)
  1966. {
  1967. FTerminal->SendNull();
  1968. throw;
  1969. }
  1970. FTerminal->SendNull();
  1971. if (FileData.SetTime && CopyParam->PreserveTime)
  1972. {
  1973. SetFileTime(File, NULL, &FileData.AcTime, &FileData.WrTime);
  1974. }
  1975. }
  1976. __finally
  1977. {
  1978. if (File) CloseHandle(File);
  1979. if (FileStream) delete FileStream;
  1980. }
  1981. if (FileData.Attrs == -1) FileData.Attrs = faArchive;
  1982. int NewAttrs = CopyParam->LocalFileAttrs(FileData.RemoteRights);
  1983. if ((NewAttrs & FileData.Attrs) != NewAttrs)
  1984. {
  1985. FILE_OPERATION_LOOP (FMTLOAD(CANT_SET_ATTRS, (DestFileName)),
  1986. FileSetAttr(DestFileName, FileData.Attrs | NewAttrs);
  1987. );
  1988. }
  1989. }
  1990. }
  1991. }
  1992. catch (EScpFileSkipped &E)
  1993. {
  1994. if (!SkipConfirmed)
  1995. {
  1996. SUSPEND_OPERATION (
  1997. TQueryParams Params(qpAllowContinueOnError);
  1998. if (FTerminal->DoQueryUser(FMTLOAD(COPY_ERROR, (OperationProgress->FileName)),
  1999. E.Message, qaOK | qaAbort, &Params) == qaAbort)
  2000. {
  2001. OperationProgress->Cancel = csCancel;
  2002. }
  2003. FTerminal->DoHandleExtendedException(&E);
  2004. );
  2005. }
  2006. // this was inside above condition, but then transfer was considered
  2007. // succesfull, even when for example user refused to overwrite file
  2008. Success = false;
  2009. }
  2010. catch (EScpSkipFile &E)
  2011. {
  2012. SCPSendError(E.Message, false);
  2013. Success = false;
  2014. if (!FTerminal->HandleException(&E)) throw;
  2015. }
  2016. }
  2017. }