ScpFileSystem.cpp 85 KB

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