ScpFileSystem.cpp 99 KB

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