ScpFileSystem.cpp 84 KB

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