ScpFileSystem.cpp 91 KB

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