ScpFileSystem.cpp 86 KB

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