ScpFileSystem.cpp 91 KB

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