ScpFileSystem.cpp 78 KB

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