ScpFileSystem.cpp 92 KB

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