ScpFileSystem.cpp 80 KB

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