ScpFileSystem.cpp 82 KB

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