ScpFileSystem.cpp 85 KB

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