ScpFileSystem.cpp 87 KB

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