ScpFileSystem.cpp 81 KB

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