SftpFileSystem.cpp 91 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138
  1. //---------------------------------------------------------------------------
  2. #include <vcl.h>
  3. #pragma hdrstop
  4. #include "SftpFileSystem.h"
  5. #include <sftp.h>
  6. #include "PuttyIntf.h"
  7. #include "Common.h"
  8. #include "Interface.h"
  9. #include "Terminal.h"
  10. #include "TextsCore.h"
  11. #include <memory>
  12. //---------------------------------------------------------------------------
  13. #pragma package(smart_init)
  14. //---------------------------------------------------------------------------
  15. #define FILE_OPERATION_LOOP_EX(ALLOW_SKIP, MESSAGE, OPERATION) \
  16. FILE_OPERATION_LOOP_CUSTOM(FTerminal, ALLOW_SKIP, MESSAGE, OPERATION)
  17. //---------------------------------------------------------------------------
  18. // additional constants for SFTP protocol not defined in Putty's sftp.h
  19. #define SSH_FXP_READLINK 19
  20. #define SSH_FXP_SYMLINK 20
  21. #define SSH_FILEXFER_ATTR_ACCESSTIME 0x00000008
  22. #define SSH_FILEXFER_ATTR_CREATETIME 0x00000010
  23. #define SSH_FILEXFER_ATTR_MODIFYTIME 0x00000020
  24. #define SSH_FILEXFER_ATTR_OWNERGROUP 0x00000080
  25. #define SSH_FILEXFER_ATTR_SUBSECOND_TIMES 0x00000100
  26. #define SSH_FILEXFER_TYPE_REGULAR 1
  27. #define SSH_FILEXFER_TYPE_DIRECTORY 2
  28. #define SSH_FILEXFER_TYPE_SYMLINK 3
  29. #define SSH_FILEXFER_TYPE_SPECIAL 4
  30. #define SSH_FILEXFER_TYPE_UNKNOWN 5
  31. #define SSH_FXF_TEXT 0x00000040
  32. #define SFTP_MAX_PACKET_LEN 102400
  33. //---------------------------------------------------------------------------
  34. const int SFTPMinVersion = 0;
  35. const int SFTPMaxVersion = 4;
  36. const int SFTPNoMessageNumber = -1;
  37. const int asNo = 0;
  38. const int asOK = 1 << SSH_FX_OK;
  39. const int asEOF = 1 << SSH_FX_EOF;
  40. const int asOpUnsupported = 1 << SSH_FX_OP_UNSUPPORTED;
  41. const int asNoSuchFile = 1 << SSH_FX_NO_SUCH_FILE;
  42. const int asAll = 0xFFFF;
  43. //---------------------------------------------------------------------------
  44. #define GET_32BIT(cp) \
  45. (((unsigned long)(unsigned char)(cp)[0] << 24) | \
  46. ((unsigned long)(unsigned char)(cp)[1] << 16) | \
  47. ((unsigned long)(unsigned char)(cp)[2] << 8) | \
  48. ((unsigned long)(unsigned char)(cp)[3]))
  49. #define PUT_32BIT(cp, value) { \
  50. (cp)[0] = (unsigned char)((value) >> 24); \
  51. (cp)[1] = (unsigned char)((value) >> 16); \
  52. (cp)[2] = (unsigned char)((value) >> 8); \
  53. (cp)[3] = (unsigned char)(value); }
  54. #define THROW_SKIP_FILE_NULL THROW_SKIP_FILE(NULL, "")
  55. //---------------------------------------------------------------------------
  56. #define SFTP_PACKET_ALLOC_DELTA 256
  57. //---------------------------------------------------------------------------
  58. class TSFTPPacket
  59. {
  60. public:
  61. TSFTPPacket()
  62. {
  63. Init();
  64. }
  65. TSFTPPacket(const TSFTPPacket & Source)
  66. {
  67. Init();
  68. *this = Source;
  69. }
  70. TSFTPPacket(unsigned char AType)
  71. {
  72. Init();
  73. ChangeType(AType);
  74. }
  75. ~TSFTPPacket()
  76. {
  77. delete[] FData;
  78. if (FReservedBy) FReservedBy->UnreserveResponse(this);
  79. }
  80. void ChangeType(unsigned char AType)
  81. {
  82. FPosition = 0;
  83. FLength = 0;
  84. Capacity = 0;
  85. FType = AType;
  86. AddByte(FType);
  87. if (FType != SSH_FXP_INIT)
  88. {
  89. AssignNumber();
  90. AddCardinal(FMessageNumber);
  91. }
  92. }
  93. void Reuse()
  94. {
  95. AssignNumber();
  96. assert(Length >= 5);
  97. // duplicated in AddCardinal()
  98. unsigned char Buf[4];
  99. PUT_32BIT(Buf, FMessageNumber);
  100. memcpy(FData + 1, Buf, sizeof(Buf));
  101. }
  102. void AddByte(unsigned char Value)
  103. {
  104. Add(&Value, sizeof(Value));
  105. }
  106. void AddCardinal(unsigned long Value)
  107. {
  108. // duplicated in Reuse()
  109. unsigned char Buf[4];
  110. PUT_32BIT(Buf, Value);
  111. Add(&Buf, sizeof(Buf));
  112. }
  113. void AddInt64(__int64 Value)
  114. {
  115. AddCardinal((unsigned long)(Value >> 32));
  116. AddCardinal((unsigned long)(Value & 0xFFFFFFFF));
  117. }
  118. void AddData(const void * Data, int ALength)
  119. {
  120. AddCardinal(ALength);
  121. Add(Data, ALength);
  122. }
  123. void AddString(const AnsiString Value)
  124. {
  125. AddCardinal(Value.Length());
  126. Add(Value.c_str(), Value.Length());
  127. }
  128. void AddProperties(const TRemoteProperties * Properties,
  129. unsigned short BaseRights, bool IsDirectory, int Version)
  130. {
  131. int Flags = 0;
  132. if (Properties)
  133. {
  134. if (Properties->Valid.Contains(vpOwner) || Properties->Valid.Contains(vpGroup))
  135. {
  136. Flags |= SSH_FILEXFER_ATTR_OWNERGROUP;
  137. }
  138. if (Properties->Valid.Contains(vpRights))
  139. {
  140. Flags |= SSH_FILEXFER_ATTR_PERMISSIONS;
  141. }
  142. }
  143. AddCardinal(Flags);
  144. if (Version >= 4)
  145. {
  146. AddByte((unsigned char)(IsDirectory ? SSH_FILEXFER_TYPE_DIRECTORY : SSH_FILEXFER_TYPE_REGULAR));
  147. }
  148. if (Properties)
  149. {
  150. if (Flags & SSH_FILEXFER_ATTR_OWNERGROUP)
  151. {
  152. assert(Version >= 4);
  153. AddString(Properties->Valid.Contains(vpOwner) ?
  154. Properties->Owner : AnsiString());
  155. AddString(Properties->Valid.Contains(vpGroup) ?
  156. Properties->Group : AnsiString());
  157. }
  158. if (Flags & SSH_FILEXFER_ATTR_PERMISSIONS)
  159. {
  160. TRights Rights = BaseRights;
  161. Rights |= Properties->Rights.NumberSet;
  162. Rights &= (unsigned short)~Properties->Rights.NumberUnset;
  163. if (IsDirectory && Properties->AddXToDirectories)
  164. {
  165. Rights.AddExecute();
  166. }
  167. AddCardinal(Rights);
  168. }
  169. }
  170. }
  171. char GetByte()
  172. {
  173. assert(FPosition <= FLength - sizeof(char));
  174. char Result = FData[FPosition];
  175. FPosition++;
  176. return Result;
  177. }
  178. unsigned long GetCardinal()
  179. {
  180. unsigned long Result;
  181. assert(FPosition <= FLength - sizeof(Result));
  182. Result = GET_32BIT(FData + FPosition);
  183. FPosition += sizeof(Result);
  184. return Result;
  185. }
  186. __int64 GetInt64()
  187. {
  188. __int64 Hi = GetCardinal();
  189. __int64 Lo = GetCardinal();
  190. return (Hi << 32) + Lo;
  191. }
  192. AnsiString GetString()
  193. {
  194. AnsiString Result;
  195. unsigned long Len = GetCardinal();
  196. Result.SetLength(Len);
  197. assert(FLength >= Len && FPosition <= FLength - Len);
  198. memcpy(Result.c_str(), FData + FPosition, Len);
  199. FPosition += Len;
  200. return Result;
  201. }
  202. void GetFile(TRemoteFile * File, int Version)
  203. {
  204. assert(File);
  205. unsigned int Flags;
  206. AnsiString ListingStr;
  207. unsigned long Permissions;
  208. bool ParsingFailed = false;
  209. if (Type != SSH_FXP_ATTRS)
  210. {
  211. File->FileName = GetString();
  212. if (Version < 4)
  213. {
  214. ListingStr = GetString();
  215. }
  216. }
  217. Flags = GetCardinal();
  218. if (Version >= 4)
  219. {
  220. char FXType = GetByte();
  221. char Types[] = "-DLSU";
  222. if (FXType < 1 || FXType > (char)strlen(Types))
  223. {
  224. throw Exception(FMTLOAD(SFTP_UNKNOWN_FILE_TYPE, (int(FXType))));
  225. }
  226. File->Type = Types[FXType-1];
  227. }
  228. if (Flags & SSH_FILEXFER_ATTR_SIZE)
  229. {
  230. File->Size = GetInt64();
  231. }
  232. if (Flags & SSH_FILEXFER_ATTR_UIDGID)
  233. {
  234. assert(Version < 4);
  235. GetCardinal(); // skip UID
  236. GetCardinal(); // skip GUID
  237. }
  238. if (Flags & SSH_FILEXFER_ATTR_OWNERGROUP)
  239. {
  240. assert(Version >= 4);
  241. File->Owner = GetString();
  242. File->Group = GetString();
  243. }
  244. if (Flags & SSH_FILEXFER_ATTR_PERMISSIONS)
  245. {
  246. Permissions = GetCardinal();
  247. }
  248. if (Version < 4)
  249. {
  250. if (Flags & SSH_FILEXFER_ATTR_ACMODTIME)
  251. {
  252. File->LastAccess = UnixToDateTime(GetCardinal());
  253. File->Modification = UnixToDateTime(GetCardinal());
  254. }
  255. }
  256. else
  257. {
  258. if (Flags & SSH_FILEXFER_ATTR_ACCESSTIME)
  259. {
  260. File->LastAccess = UnixToDateTime((unsigned long)GetInt64());
  261. }
  262. if (Flags & SSH_FILEXFER_ATTR_SUBSECOND_TIMES)
  263. {
  264. GetCardinal(); // skip access time subseconds
  265. }
  266. if (Flags & SSH_FILEXFER_ATTR_CREATETIME)
  267. {
  268. GetInt64(); // skip create time
  269. }
  270. if (Flags & SSH_FILEXFER_ATTR_SUBSECOND_TIMES)
  271. {
  272. GetCardinal(); // skip create time subseconds
  273. }
  274. if (Flags & SSH_FILEXFER_ATTR_MODIFYTIME)
  275. {
  276. File->Modification = UnixToDateTime((unsigned long)GetInt64());
  277. }
  278. if (Flags & SSH_FILEXFER_ATTR_SUBSECOND_TIMES)
  279. {
  280. GetCardinal(); // skip modification time subseconds
  281. }
  282. }
  283. if ((Version < 4) && (Type != SSH_FXP_ATTRS))
  284. {
  285. try
  286. {
  287. // update permissions and user/group name
  288. // modification time and filename is ignored
  289. File->ListingStr = ListingStr;
  290. }
  291. catch(...)
  292. {
  293. // ignore any error while parsing listing line,
  294. // SFTP specification do not recommend to parse it
  295. ParsingFailed = true;
  296. }
  297. }
  298. if (Type == SSH_FXP_ATTRS || Version >= 4 || ParsingFailed)
  299. {
  300. File->Rights->Number = (unsigned short)(Permissions & 0777);
  301. if (Version < 4)
  302. {
  303. File->Type = (Permissions & 0040000 ? FILETYPE_DIRECTORY : '-');
  304. }
  305. }
  306. // TODO: read extended attributes (Flags & SSH_FILEXFER_ATTR_EXTENDED)
  307. // Format: Count=Cardinal, Count*(Name=String, Value=String)
  308. }
  309. void DataUpdated(int ALength)
  310. {
  311. FPosition = 0;
  312. FLength = ALength;
  313. FType = GetByte();
  314. if (FType != SSH_FXP_VERSION)
  315. {
  316. FMessageNumber = GetCardinal();
  317. }
  318. else
  319. {
  320. FMessageNumber = SFTPNoMessageNumber;
  321. }
  322. }
  323. AnsiString __fastcall Dump() const
  324. {
  325. AnsiString Result;
  326. for (unsigned int Index = 0; Index < Length; Index++)
  327. {
  328. Result += IntToHex(int((unsigned char)Data[Index]), 2) + ",";
  329. if (((Index + 1) % 25) == 0)
  330. {
  331. Result += "\n";
  332. }
  333. }
  334. return Result;
  335. }
  336. TSFTPPacket & operator = (const TSFTPPacket & Source)
  337. {
  338. Capacity = 0;
  339. Add(Source.Data, Source.Length);
  340. DataUpdated(Source.Length);
  341. FPosition = Source.FPosition;
  342. return *this;
  343. }
  344. __property unsigned int Length = { read = FLength };
  345. __property char * Data = { read = FData };
  346. __property char * NextData = { read = GetNextData };
  347. __property char * Content = { read = GetContent };
  348. __property unsigned int ContentLength = { read = GetContentLength };
  349. __property unsigned int Capacity = { read = FCapacity, write = SetCapacity };
  350. __property unsigned char Type = { read = FType };
  351. __property unsigned char RequestType = { read = GetRequestType };
  352. __property unsigned int MessageNumber = { read = FMessageNumber, write = FMessageNumber };
  353. __property TSFTPFileSystem * ReservedBy = { read = FReservedBy, write = FReservedBy };
  354. __property AnsiString TypeName = { read = GetTypeName };
  355. private:
  356. char * FData;
  357. unsigned int FLength;
  358. unsigned int FCapacity;
  359. unsigned int FPosition;
  360. unsigned char FType;
  361. unsigned int FMessageNumber;
  362. TSFTPFileSystem * FReservedBy;
  363. static int FMessageCounter;
  364. void Init()
  365. {
  366. FData = NULL;
  367. FCapacity = 0;
  368. FLength = 0;
  369. FPosition = 0;
  370. FMessageNumber = SFTPNoMessageNumber;
  371. FType = -1;
  372. FReservedBy = NULL;
  373. }
  374. void AssignNumber()
  375. {
  376. FMessageNumber = (FMessageCounter << 8) + FType;
  377. FMessageCounter++;
  378. }
  379. unsigned char GetRequestType()
  380. {
  381. if (FMessageNumber != SFTPNoMessageNumber)
  382. {
  383. return (unsigned char)(FMessageNumber & 0xFF);
  384. }
  385. else
  386. {
  387. assert(Type == SSH_FXP_VERSION);
  388. return SSH_FXP_INIT;
  389. }
  390. }
  391. void Add(const void * AData, int ALength)
  392. {
  393. if (Length + ALength > Capacity)
  394. {
  395. Capacity = Length + ALength + SFTP_PACKET_ALLOC_DELTA;
  396. }
  397. memcpy(FData + Length, AData, ALength);
  398. FLength += ALength;
  399. }
  400. void SetCapacity(unsigned int ACapacity)
  401. {
  402. if (ACapacity != Capacity)
  403. {
  404. FCapacity = ACapacity;
  405. if (FCapacity > 0)
  406. {
  407. char * NData = new char[FCapacity];
  408. if (FData)
  409. {
  410. memcpy(NData, FData, (FLength < FCapacity ? FLength : FCapacity));
  411. delete[] FData;
  412. }
  413. FData = NData;
  414. }
  415. else
  416. {
  417. if (FData) delete[] FData;
  418. FData = NULL;
  419. }
  420. if (FLength > FCapacity) FLength = FCapacity;
  421. }
  422. }
  423. AnsiString GetTypeName() const
  424. {
  425. #define TYPE_CASE(TYPE) case TYPE: return #TYPE
  426. switch (Type) {
  427. TYPE_CASE(SSH_FXP_INIT);
  428. TYPE_CASE(SSH_FXP_VERSION);
  429. TYPE_CASE(SSH_FXP_OPEN);
  430. TYPE_CASE(SSH_FXP_CLOSE);
  431. TYPE_CASE(SSH_FXP_READ);
  432. TYPE_CASE(SSH_FXP_WRITE);
  433. TYPE_CASE(SSH_FXP_LSTAT);
  434. TYPE_CASE(SSH_FXP_FSTAT);
  435. TYPE_CASE(SSH_FXP_SETSTAT);
  436. TYPE_CASE(SSH_FXP_FSETSTAT);
  437. TYPE_CASE(SSH_FXP_OPENDIR);
  438. TYPE_CASE(SSH_FXP_READDIR);
  439. TYPE_CASE(SSH_FXP_REMOVE);
  440. TYPE_CASE(SSH_FXP_MKDIR);
  441. TYPE_CASE(SSH_FXP_RMDIR);
  442. TYPE_CASE(SSH_FXP_REALPATH);
  443. TYPE_CASE(SSH_FXP_STAT);
  444. TYPE_CASE(SSH_FXP_RENAME);
  445. TYPE_CASE(SSH_FXP_READLINK);
  446. TYPE_CASE(SSH_FXP_SYMLINK);
  447. TYPE_CASE(SSH_FXP_STATUS);
  448. TYPE_CASE(SSH_FXP_HANDLE);
  449. TYPE_CASE(SSH_FXP_DATA);
  450. TYPE_CASE(SSH_FXP_NAME);
  451. TYPE_CASE(SSH_FXP_ATTRS);
  452. TYPE_CASE(SSH_FXP_EXTENDED);
  453. TYPE_CASE(SSH_FXP_EXTENDED_REPLY);
  454. default:
  455. return FORMAT("Unknown message (%d)", (int(Type)));
  456. }
  457. }
  458. char * GetContent()
  459. {
  460. return Data + sizeof(Byte) + (FType != SSH_FXP_VERSION ? sizeof(Cardinal) : 0);
  461. }
  462. unsigned int GetContentLength()
  463. {
  464. return Length - sizeof(Byte) - (FType != SSH_FXP_VERSION ? sizeof(Cardinal) : 0);
  465. }
  466. char * GetNextData()
  467. {
  468. return FPosition < FLength ? FData + FPosition : NULL;
  469. }
  470. };
  471. //---------------------------------------------------------------------------
  472. int TSFTPPacket::FMessageCounter = 0;
  473. //---------------------------------------------------------------------------
  474. class TSFTPQueue
  475. {
  476. public:
  477. __fastcall TSFTPQueue(TSFTPFileSystem * AFileSystem)
  478. {
  479. FFileSystem = AFileSystem;
  480. assert(FFileSystem);
  481. FRequests = new TList();
  482. FResponses = new TList();
  483. }
  484. __fastcall ~TSFTPQueue()
  485. {
  486. try
  487. {
  488. if (FFileSystem->FTerminal->Active)
  489. {
  490. Dispose();
  491. }
  492. }
  493. __finally
  494. {
  495. TSFTPPacket * Request;
  496. TSFTPPacket * Response;
  497. assert(FResponses->Count == FRequests->Count);
  498. for (int Index = 0; Index < FRequests->Count; Index++)
  499. {
  500. Request = static_cast<TSFTPPacket*>(FRequests->Items[Index]);
  501. assert(Request);
  502. delete Request;
  503. Response = static_cast<TSFTPPacket*>(FResponses->Items[Index]);
  504. assert(Response);
  505. delete Response;
  506. }
  507. delete FRequests;
  508. delete FResponses;
  509. }
  510. }
  511. bool __fastcall Init(int QueueLen)
  512. {
  513. bool Result = false;
  514. while ((QueueLen > 0) && SendRequest())
  515. {
  516. Result = true;
  517. QueueLen--;
  518. }
  519. return Result;
  520. }
  521. void __fastcall Dispose()
  522. {
  523. assert(FFileSystem->FTerminal->Active);
  524. TSFTPPacket * Request;
  525. TSFTPPacket * Response;
  526. while (FRequests->Count)
  527. {
  528. assert(FResponses->Count);
  529. Request = static_cast<TSFTPPacket*>(FRequests->Items[0]);
  530. assert(Request);
  531. Response = static_cast<TSFTPPacket*>(FResponses->Items[0]);
  532. assert(Response);
  533. try
  534. {
  535. FFileSystem->ReceiveResponse(Request, Response);
  536. }
  537. catch(Exception & E)
  538. {
  539. if (FFileSystem->FTerminal->Active)
  540. {
  541. FFileSystem->FTerminal->LogEvent("Error while disposing the SFTP queue.");
  542. HandleExtendedException(&E);
  543. }
  544. else
  545. {
  546. FFileSystem->FTerminal->LogEvent("Fatal error while disposing the SFTP queue.");
  547. throw;
  548. }
  549. }
  550. FRequests->Delete(0);
  551. delete Request;
  552. FResponses->Delete(0);
  553. delete Response;
  554. }
  555. }
  556. bool __fastcall ReceivePacket(TSFTPPacket * Packet,
  557. int ExpectedType = -1, int AllowStatus = -1)
  558. {
  559. assert(FRequests->Count);
  560. bool Result;
  561. TSFTPPacket * Request = NULL;
  562. TSFTPPacket * Response = NULL;
  563. try
  564. {
  565. Request = static_cast<TSFTPPacket*>(FRequests->Items[0]);
  566. FRequests->Delete(0);
  567. assert(Request);
  568. Response = static_cast<TSFTPPacket*>(FResponses->Items[0]);
  569. FResponses->Delete(0);
  570. assert(Response);
  571. FFileSystem->ReceiveResponse(Request, Response,
  572. ExpectedType, AllowStatus);
  573. if (Packet)
  574. {
  575. *Packet = *Response;
  576. }
  577. Result = SendNext(Response);
  578. if (Result)
  579. {
  580. Result = SendRequest();
  581. }
  582. }
  583. __finally
  584. {
  585. delete Request;
  586. delete Response;
  587. }
  588. return Result;
  589. }
  590. bool __fastcall Next(int ExpectedType = -1, int AllowStatus = -1)
  591. {
  592. return ReceivePacket(NULL, ExpectedType, AllowStatus);
  593. }
  594. protected:
  595. virtual bool __fastcall InitRequest(TSFTPPacket * Request) = 0;
  596. virtual bool __fastcall SendNext(TSFTPPacket * Request) = 0;
  597. virtual void __fastcall SendPacket(TSFTPPacket * Packet)
  598. {
  599. FFileSystem->SendPacket(Packet);
  600. }
  601. protected:
  602. TList * FRequests;
  603. TList * FResponses;
  604. TSFTPFileSystem * FFileSystem;
  605. private:
  606. bool __fastcall SendRequest()
  607. {
  608. TSFTPPacket * Request = NULL;
  609. try
  610. {
  611. Request = new TSFTPPacket();
  612. if (!InitRequest(Request))
  613. {
  614. delete Request;
  615. Request = NULL;
  616. }
  617. }
  618. catch(...)
  619. {
  620. delete Request;
  621. throw;
  622. }
  623. if (Request != NULL)
  624. {
  625. TSFTPPacket * Response = new TSFTPPacket();
  626. FRequests->Add(Request);
  627. FResponses->Add(Response);
  628. SendPacket(Request);
  629. FFileSystem->ReserveResponse(Request, Response);
  630. }
  631. return (Request != NULL);
  632. }
  633. };
  634. //---------------------------------------------------------------------------
  635. class TSFTPTransferQueue : public TSFTPQueue
  636. {
  637. public:
  638. TSFTPTransferQueue(TSFTPFileSystem * AFileSystem) : TSFTPQueue(AFileSystem)
  639. {
  640. }
  641. protected:
  642. __int64 FTransfered;
  643. AnsiString FHandle;
  644. unsigned long FBlockSize;
  645. };
  646. //---------------------------------------------------------------------------
  647. class TSFTPDownloadQueue : public TSFTPTransferQueue
  648. {
  649. public:
  650. TSFTPDownloadQueue(TSFTPFileSystem * AFileSystem) :
  651. TSFTPTransferQueue(AFileSystem)
  652. {
  653. }
  654. bool __fastcall Init(int QueueLen, const AnsiString AHandle,
  655. unsigned long ABlockSize, __int64 ATransfered)
  656. {
  657. FHandle = AHandle;
  658. FBlockSize = ABlockSize;
  659. FTransfered = ATransfered;
  660. return TSFTPTransferQueue::Init(QueueLen);
  661. }
  662. void __fastcall InitFillGapRequest(__int64 Offset, unsigned long Missing,
  663. TSFTPPacket * Packet)
  664. {
  665. InitRequest(Packet, Offset, Missing);
  666. }
  667. protected:
  668. virtual bool __fastcall InitRequest(TSFTPPacket * Request)
  669. {
  670. InitRequest(Request, FTransfered, FBlockSize);
  671. FTransfered += FBlockSize;
  672. return true;
  673. }
  674. void __fastcall InitRequest(TSFTPPacket * Request, __int64 Offset,
  675. unsigned long Size)
  676. {
  677. Request->ChangeType(SSH_FXP_READ);
  678. Request->AddString(FHandle);
  679. Request->AddInt64(Offset);
  680. Request->AddCardinal(Size);
  681. }
  682. virtual bool __fastcall SendNext(TSFTPPacket * Request)
  683. {
  684. return (Request->Type == SSH_FXP_DATA);
  685. }
  686. };
  687. //---------------------------------------------------------------------------
  688. class TSFTPUploadQueue : public TSFTPTransferQueue
  689. {
  690. public:
  691. TSFTPUploadQueue(TSFTPFileSystem * AFileSystem) :
  692. TSFTPTransferQueue(AFileSystem)
  693. {
  694. FFile = NULL;
  695. OperationProgress = NULL;
  696. FLastBlockSize = 0;
  697. }
  698. bool __fastcall Init(int QueueLen, const AnsiString AFileName,
  699. HANDLE AFile, TFileOperationProgressType * AOperationProgress,
  700. const AnsiString AHandle, unsigned long ABlockSize, __int64 ATransfered)
  701. {
  702. FFileName = AFileName;
  703. FFile = AFile;
  704. OperationProgress = AOperationProgress;
  705. FHandle = AHandle;
  706. FBlockSize = ABlockSize;
  707. FTransfered = ATransfered;
  708. return TSFTPTransferQueue::Init(QueueLen);
  709. }
  710. protected:
  711. virtual bool __fastcall InitRequest(TSFTPPacket * Request)
  712. {
  713. TTerminal * FTerminal = FFileSystem->FTerminal;
  714. // Buffer for one block of data
  715. TFileBuffer BlockBuf;
  716. FILE_OPERATION_LOOP(FMTLOAD(READ_ERROR, (FFileName)),
  717. BlockBuf.LoadFile(FFile, FBlockSize, false);
  718. );
  719. bool Result = (BlockBuf.Size != 0);
  720. if (Result)
  721. {
  722. OperationProgress->AddLocalyUsed(BlockBuf.Size);
  723. // We do ASCII transfer: convert EOL of current block
  724. if (OperationProgress->AsciiTransfer)
  725. {
  726. __int64 PrevBufSize = BlockBuf.Size;
  727. BlockBuf.Convert(FTerminal->Configuration->LocalEOLType,
  728. FFileSystem->GetEOL(), cpRemoveCtrlZ);
  729. // update transfer size with difference arised from EOL conversion
  730. OperationProgress->SetTransferSize(OperationProgress->TransferSize -
  731. PrevBufSize + BlockBuf.Size);
  732. }
  733. Request->ChangeType(SSH_FXP_WRITE);
  734. Request->AddString(FHandle);
  735. Request->AddInt64(FTransfered);
  736. Request->AddData(BlockBuf.Data, BlockBuf.Size);
  737. FLastBlockSize = BlockBuf.Size;
  738. FTransfered += BlockBuf.Size;
  739. }
  740. return Result;
  741. }
  742. virtual void __fastcall SendPacket(TSFTPPacket * Packet)
  743. {
  744. TSFTPTransferQueue::SendPacket(Packet);
  745. OperationProgress->AddTransfered(FLastBlockSize);
  746. }
  747. virtual bool __fastcall SendNext(TSFTPPacket * Request)
  748. {
  749. return true;
  750. }
  751. private:
  752. HANDLE FFile;
  753. TFileOperationProgressType * OperationProgress;
  754. AnsiString FFileName;
  755. unsigned long FLastBlockSize;
  756. };
  757. //---------------------------------------------------------------------------
  758. class TSFTPBusy
  759. {
  760. public:
  761. __fastcall TSFTPBusy(TSFTPFileSystem * FileSystem)
  762. {
  763. FFileSystem = FileSystem;
  764. assert(FFileSystem != NULL);
  765. FFileSystem->BusyStart();
  766. }
  767. __fastcall ~TSFTPBusy()
  768. {
  769. FFileSystem->BusyEnd();
  770. }
  771. private:
  772. TSFTPFileSystem * FFileSystem;
  773. };
  774. //===========================================================================
  775. struct TOpenRemoteFileParams
  776. {
  777. int LocalFileAttrs;
  778. AnsiString RemoteFileName;
  779. TFileOperationProgressType * OperationProgress;
  780. const TCopyParamType * CopyParam;
  781. int Params;
  782. bool Resume;
  783. TSFTPOverwriteMode OverwriteMode;
  784. __int64 DestFileSize; // output
  785. AnsiString RemoteFileHandle; // output
  786. TOverwriteFileParams * FileParams;
  787. };
  788. //---------------------------------------------------------------------------
  789. struct TSinkFileParams
  790. {
  791. AnsiString TargetDir;
  792. const TCopyParamType * CopyParam;
  793. int Params;
  794. TFileOperationProgressType * OperationProgress;
  795. bool Skipped;
  796. int Level;
  797. };
  798. //===========================================================================
  799. __fastcall TSFTPFileSystem::TSFTPFileSystem(TTerminal * ATerminal):
  800. TCustomFileSystem(ATerminal)
  801. {
  802. FPacketReservations = new TList();
  803. FPacketNumbers = VarArrayCreate(OPENARRAY(int, (0, 1)), varInteger);
  804. FPreviousLoggedPacket = 0;
  805. FNotLoggedPackets = 0;
  806. FBusy = 0;
  807. FAvoidBusy = false;
  808. FExtensions = new TStringList();
  809. }
  810. //---------------------------------------------------------------------------
  811. __fastcall TSFTPFileSystem::~TSFTPFileSystem()
  812. {
  813. delete FPacketReservations;
  814. delete FExtensions;
  815. }
  816. //---------------------------------------------------------------------------
  817. AnsiString __fastcall TSFTPFileSystem::GetProtocolName() const
  818. {
  819. return FMTLOAD(SFTP_PROTOCOL_NAME, (FVersion));
  820. }
  821. //---------------------------------------------------------------------------
  822. bool __fastcall TSFTPFileSystem::IsCapable(int Capability) const
  823. {
  824. assert(FTerminal);
  825. switch (Capability) {
  826. case fcUserGroupListing:
  827. case fcAnyCommand:
  828. case fcHardLink:
  829. return false;
  830. case fcOwnerChanging:
  831. case fcGroupChanging:
  832. return (FVersion >= 4);
  833. case fcSymbolicLink:
  834. case fcResolveSymlink:
  835. return (FVersion >= 3);
  836. case fcModeChanging:
  837. return true;
  838. case fcTextMode:
  839. return (FVersion >= 4) ||
  840. strcmp(GetEOL(), EOLToStr(FTerminal->Configuration->LocalEOLType)) != 0;
  841. case fcNativeTextMode:
  842. return (FVersion >= 4);
  843. case fcRename:
  844. return (FVersion >= 2);
  845. default:
  846. assert(false);
  847. return false;
  848. }
  849. }
  850. //---------------------------------------------------------------------------
  851. void __fastcall TSFTPFileSystem::KeepAlive()
  852. {
  853. TSFTPPacket Packet(SSH_FXP_REALPATH);
  854. Packet.AddString("/");
  855. SendPacketAndReceiveResponse(&Packet, &Packet);
  856. }
  857. //---------------------------------------------------------------------------
  858. void __fastcall TSFTPFileSystem::AdditionalInfo(TStrings * AdditionalInfo,
  859. bool Initial)
  860. {
  861. if (Initial)
  862. {
  863. if (!IsCapable(fcRename))
  864. {
  865. AdditionalInfo->Add(LoadStr(FS_RENAME_NOT_SUPPORTED));
  866. AdditionalInfo->Add("");
  867. }
  868. if (FExtensions->Count > 0)
  869. {
  870. AnsiString Name;
  871. AnsiString Value;
  872. AnsiString Line;
  873. AdditionalInfo->Add(LoadStr(SFTP_EXTENSION_INFO));
  874. for (int Index = 0; Index < FExtensions->Count; Index++)
  875. {
  876. AnsiString Name = FExtensions->Names[Index];
  877. AnsiString Value = FExtensions->Values[Name];
  878. AnsiString Line;
  879. if (Value.IsEmpty())
  880. {
  881. Line = Name;
  882. }
  883. else
  884. {
  885. if (!IsDisplayableStr(Value))
  886. {
  887. Value = "0x" + StrToHex(Value);
  888. }
  889. Line = FORMAT("%s=%s", (Name, Value));
  890. }
  891. AdditionalInfo->Add(FORMAT(" %s", (Line)));;
  892. }
  893. }
  894. else
  895. {
  896. AdditionalInfo->Add(LoadStr(SFTP_NO_EXTENSION_INFO));
  897. }
  898. }
  899. }
  900. //---------------------------------------------------------------------------
  901. struct TUnicodeEmitParams
  902. {
  903. WideString Buffer;
  904. int Pos;
  905. int Len;
  906. };
  907. //---------------------------------------------------------------------------
  908. extern "C" void UnicodeEmit(void * AParams, long int Output)
  909. {
  910. if (Output == 0xFFFFL) // see Putty's charset\internal.h
  911. {
  912. throw Exception(LoadStr(DECODE_UTF_ERROR));
  913. }
  914. TUnicodeEmitParams * Params = (TUnicodeEmitParams *)AParams;
  915. if (Params->Pos >= Params->Len)
  916. {
  917. Params->Len += 50;
  918. Params->Buffer.SetLength(Params->Len);
  919. }
  920. Params->Buffer[Params->Pos + 1] = (wchar_t)Output;
  921. Params->Pos++;
  922. }
  923. //---------------------------------------------------------------------------
  924. AnsiString __fastcall TSFTPFileSystem::DecodeUTF(const AnsiString UTF)
  925. {
  926. charset_state State;
  927. char * Str;
  928. TUnicodeEmitParams Params;
  929. AnsiString Result;
  930. State.s0 = 0;
  931. Str = UTF.c_str();
  932. Params.Pos = 0;
  933. Params.Len = UTF.Length();
  934. Params.Buffer.SetLength(Params.Len);
  935. while (*Str)
  936. {
  937. read_utf8(NULL, (unsigned char)*Str, &State, UnicodeEmit, &Params);
  938. Str++;
  939. }
  940. Params.Buffer.SetLength(Params.Pos);
  941. return Params.Buffer;
  942. }
  943. //---------------------------------------------------------------------------
  944. inline void __fastcall TSFTPFileSystem::BusyStart()
  945. {
  946. if (FBusy == 0 && FTerminal->UseBusyCursor && !FAvoidBusy)
  947. {
  948. Busy(true);
  949. }
  950. FBusy++;
  951. assert(FBusy < 10);
  952. }
  953. //---------------------------------------------------------------------------
  954. inline void __fastcall TSFTPFileSystem::BusyEnd()
  955. {
  956. assert(FBusy > 0);
  957. FBusy--;
  958. if (FBusy == 0 && FTerminal->UseBusyCursor && !FAvoidBusy)
  959. {
  960. Busy(false);
  961. }
  962. }
  963. //---------------------------------------------------------------------------
  964. unsigned long __fastcall TSFTPFileSystem::MaxTransferBlockSize(unsigned long Overhead)
  965. {
  966. unsigned long MaxPacketSize = FTerminal->MaxPacketSize();
  967. unsigned long Result = TFileOperationProgressType::StaticBlockSize();
  968. if (MaxPacketSize > 0)
  969. {
  970. MaxPacketSize -= 4 + 1 + Overhead;
  971. if (Result > MaxPacketSize)
  972. {
  973. Result = MaxPacketSize;
  974. }
  975. }
  976. return Result;
  977. }
  978. //---------------------------------------------------------------------------
  979. void __fastcall TSFTPFileSystem::SendPacket(const TSFTPPacket * Packet)
  980. {
  981. BusyStart();
  982. try
  983. {
  984. if (FTerminal->IsLogging())
  985. {
  986. if ((FPreviousLoggedPacket != SSH_FXP_READ &&
  987. FPreviousLoggedPacket != SSH_FXP_WRITE) ||
  988. (Packet->Type != FPreviousLoggedPacket))
  989. {
  990. if (FNotLoggedPackets)
  991. {
  992. FTerminal->LogEvent(FORMAT("%d skipped SSH_FXP_WRITE, SSH_FXP_READ, SSH_FXP_DATA and SSH_FXP_STATUS packets.",
  993. (FNotLoggedPackets)));
  994. FNotLoggedPackets = 0;
  995. }
  996. FTerminal->Log->Add(llInput, FORMAT("Type: %s, Size: %d, Number: %d",
  997. (Packet->TypeName, (int)Packet->Length, (int)Packet->MessageNumber)));
  998. FPreviousLoggedPacket = Packet->Type;
  999. }
  1000. else
  1001. {
  1002. FNotLoggedPackets++;
  1003. }
  1004. }
  1005. char LenBuf[4];
  1006. PUT_32BIT(LenBuf, Packet->Length);
  1007. FTerminal->Send(LenBuf, sizeof(LenBuf));
  1008. FTerminal->Send(Packet->Data, Packet->Length);
  1009. }
  1010. __finally
  1011. {
  1012. BusyEnd();
  1013. }
  1014. }
  1015. //---------------------------------------------------------------------------
  1016. unsigned long __fastcall TSFTPFileSystem::GotStatusPacket(TSFTPPacket * Packet,
  1017. int AllowStatus)
  1018. {
  1019. unsigned long Code = Packet->GetCardinal();
  1020. static int Messages[] = {
  1021. SFTP_STATUS_OK,
  1022. SFTP_STATUS_EOF,
  1023. SFTP_STATUS_NO_SUCH_FILE,
  1024. SFTP_STATUS_PERMISSION_DENIED,
  1025. SFTP_STATUS_FAILURE,
  1026. SFTP_STATUS_BAD_MESSAGE,
  1027. SFTP_STATUS_NO_CONNECTION,
  1028. SFTP_STATUS_CONNECTION_LOST,
  1029. SFTP_STATUS_OP_UNSUPPORTED,
  1030. SFTP_STATUS_INVALID_HANDLE,
  1031. SFTP_STATUS_NO_SUCH_PATH,
  1032. SFTP_STATUS_FILE_ALREADY_EXISTS,
  1033. SFTP_STATUS_WRITE_PROTECT,
  1034. SFTP_STATUS_NO_MEDIA,
  1035. };
  1036. int Message;
  1037. if ((AllowStatus & (0x01 << Code)) == 0)
  1038. {
  1039. if (Code >= sizeof(Messages) / sizeof(*Messages))
  1040. {
  1041. Message = SFTP_STATUS_UNKNOWN;
  1042. }
  1043. else
  1044. {
  1045. Message = Messages[Code];
  1046. }
  1047. AnsiString ServerMessage;
  1048. AnsiString LanguageTag;
  1049. if (FVersion >= 3)
  1050. {
  1051. ServerMessage = DecodeUTF(Packet->GetString());
  1052. LanguageTag = Packet->GetString();
  1053. }
  1054. else
  1055. {
  1056. ServerMessage = LoadStr(SFTP_SERVER_MESSAGE_UNSUPPORTED);
  1057. }
  1058. if (LanguageTag.IsEmpty())
  1059. {
  1060. LanguageTag = "*";
  1061. }
  1062. if (FTerminal->IsLogging())
  1063. {
  1064. FTerminal->Log->Add(llOutput, FORMAT("Status/error code: %d, Message: %d, Server: %s, Language: %s ",
  1065. (int(Code), (int)Packet->MessageNumber, ServerMessage, LanguageTag)));
  1066. }
  1067. AnsiString Error = FMTLOAD(SFTP_ERROR_FORMAT, (LoadStr(Message), int(Code),
  1068. ServerMessage, LanguageTag, int(Packet->RequestType)));
  1069. FTerminal->TerminalError(NULL, Error);
  1070. return 0;
  1071. }
  1072. else
  1073. {
  1074. if (!FNotLoggedPackets || Code)
  1075. {
  1076. FTerminal->Log->Add(llOutput, FORMAT("Status/error code: %d", ((int)Code)));
  1077. }
  1078. return Code;
  1079. }
  1080. }
  1081. //---------------------------------------------------------------------------
  1082. void __fastcall TSFTPFileSystem::RemoveReservation(int Reservation)
  1083. {
  1084. for (int Index = Reservation+1; Index < FPacketReservations->Count; Index++)
  1085. {
  1086. FPacketNumbers.PutElement(FPacketNumbers.GetElement(Index), Index-1);
  1087. }
  1088. TSFTPPacket * Packet = (TSFTPPacket *)FPacketReservations->Items[Reservation];
  1089. if (Packet)
  1090. {
  1091. assert(Packet->ReservedBy == this);
  1092. Packet->ReservedBy = NULL;
  1093. }
  1094. FPacketReservations->Delete(Reservation);
  1095. }
  1096. //---------------------------------------------------------------------------
  1097. int __fastcall TSFTPFileSystem::ReceivePacket(TSFTPPacket * Packet,
  1098. int ExpectedType, int AllowStatus)
  1099. {
  1100. TSFTPBusy Busy(this);
  1101. int Result = SSH_FX_OK;
  1102. int Reservation = FPacketReservations->IndexOf(Packet);
  1103. if (Reservation < 0 || Packet->Capacity == 0)
  1104. {
  1105. bool IsReserved;
  1106. do
  1107. {
  1108. IsReserved = false;
  1109. assert(Packet);
  1110. char LenBuf[5];
  1111. LenBuf[sizeof(LenBuf) - 1] = '\0';
  1112. FTerminal->Receive(LenBuf, sizeof(LenBuf) - 1);
  1113. int Length = GET_32BIT(LenBuf);
  1114. if (Length > SFTP_MAX_PACKET_LEN)
  1115. {
  1116. AnsiString Message = FMTLOAD(SFTP_PACKET_TOO_BIG, (
  1117. int(Length), SFTP_MAX_PACKET_LEN));
  1118. if (ExpectedType == SSH_FXP_VERSION)
  1119. {
  1120. AnsiString LenString = LenBuf;
  1121. if (!IsDisplayableStr(LenString))
  1122. {
  1123. LenString = "0x" + StrToHex(LenString);
  1124. }
  1125. Message = FMTLOAD(SFTP_PACKET_TOO_BIG_INIT_EXPLAIN,
  1126. (Message, LenString));
  1127. }
  1128. FTerminal->FatalError(Message);
  1129. }
  1130. Packet->Capacity = Length;
  1131. FTerminal->Receive(Packet->Data, Length);
  1132. Packet->DataUpdated(Length);
  1133. if (FTerminal->IsLogging())
  1134. {
  1135. if ((FPreviousLoggedPacket != SSH_FXP_READ &&
  1136. FPreviousLoggedPacket != SSH_FXP_WRITE) ||
  1137. (Packet->Type != SSH_FXP_STATUS && Packet->Type != SSH_FXP_DATA))
  1138. {
  1139. if (FNotLoggedPackets)
  1140. {
  1141. FTerminal->LogEvent(FORMAT("%d skipped SSH_FXP_WRITE, SSH_FXP_READ, SSH_FXP_DATA and SSH_FXP_STATUS packets.",
  1142. (FNotLoggedPackets)));
  1143. FNotLoggedPackets = 0;
  1144. }
  1145. FTerminal->Log->Add(llOutput, FORMAT("Type: %s, Size: %d, Number: %d",
  1146. (Packet->TypeName, (int)Packet->Length, (int)Packet->MessageNumber)));
  1147. }
  1148. else
  1149. {
  1150. FNotLoggedPackets++;
  1151. }
  1152. }
  1153. if (Reservation < 0 ||
  1154. Packet->MessageNumber != (unsigned long)FPacketNumbers.GetElement(Reservation))
  1155. {
  1156. TSFTPPacket * ReservedPacket;
  1157. unsigned long MessageNumber;
  1158. for (int Index = 0; Index < FPacketReservations->Count; Index++)
  1159. {
  1160. MessageNumber = FPacketNumbers.GetElement(Index);
  1161. if (MessageNumber == Packet->MessageNumber)
  1162. {
  1163. ReservedPacket = (TSFTPPacket *)FPacketReservations->Items[Index];
  1164. IsReserved = true;
  1165. if (ReservedPacket)
  1166. {
  1167. *ReservedPacket = *Packet;
  1168. }
  1169. else
  1170. {
  1171. RemoveReservation(Index);
  1172. }
  1173. break;
  1174. }
  1175. }
  1176. }
  1177. }
  1178. while (IsReserved);
  1179. }
  1180. if (ExpectedType >= 0)
  1181. {
  1182. if (Packet->Type == SSH_FXP_STATUS)
  1183. {
  1184. Result = GotStatusPacket(Packet, (AllowStatus >= 0 ? AllowStatus : asOK));
  1185. }
  1186. else if (ExpectedType != Packet->Type)
  1187. {
  1188. FTerminal->FatalError(FMTLOAD(SFTP_INVALID_TYPE, ((int)Packet->Type)));
  1189. }
  1190. }
  1191. if (Reservation >= 0)
  1192. {
  1193. // order might have changed, when reserved, but not longer needed packet
  1194. // was receive in above loop
  1195. Reservation = FPacketReservations->IndexOf(Packet);
  1196. assert(Reservation >= 0);
  1197. assert(Packet->MessageNumber == (unsigned long)FPacketNumbers.GetElement(Reservation));
  1198. RemoveReservation(Reservation);
  1199. }
  1200. return Result;
  1201. }
  1202. //---------------------------------------------------------------------------
  1203. void __fastcall TSFTPFileSystem::ReserveResponse(const TSFTPPacket * Packet,
  1204. TSFTPPacket * Response)
  1205. {
  1206. assert(FPacketReservations->IndexOf(Response) < 0);
  1207. // mark response as not received yet
  1208. Response->Capacity = 0;
  1209. Response->ReservedBy = this;
  1210. FPacketReservations->Add(Response);
  1211. if (FPacketReservations->Count >= FPacketNumbers.ArrayHighBound())
  1212. {
  1213. FPacketNumbers.ArrayRedim(FPacketReservations->Count + 10);
  1214. }
  1215. FPacketNumbers.PutElement(Packet->MessageNumber, FPacketReservations->Count - 1);
  1216. }
  1217. //---------------------------------------------------------------------------
  1218. void __fastcall TSFTPFileSystem::UnreserveResponse(TSFTPPacket * Response)
  1219. {
  1220. int Reservation = FPacketReservations->IndexOf(Response);
  1221. if (Reservation >= 0)
  1222. {
  1223. FPacketReservations->Items[Reservation] = NULL;
  1224. }
  1225. }
  1226. //---------------------------------------------------------------------------
  1227. int __fastcall TSFTPFileSystem::ReceiveResponse(
  1228. const TSFTPPacket * Packet, TSFTPPacket * Response, int ExpectedType,
  1229. int AllowStatus)
  1230. {
  1231. int Result;
  1232. unsigned int MessageNumber = Packet->MessageNumber;
  1233. TSFTPPacket * AResponse = (Response ? Response : new TSFTPPacket());
  1234. try
  1235. {
  1236. Result = ReceivePacket(AResponse, ExpectedType, AllowStatus);
  1237. if (MessageNumber != AResponse->MessageNumber)
  1238. {
  1239. FTerminal->FatalError(FMTLOAD(SFTP_MESSAGE_NUMBER,
  1240. ((int)AResponse->MessageNumber, (int)MessageNumber)));
  1241. }
  1242. }
  1243. __finally
  1244. {
  1245. if (!Response) delete AResponse;
  1246. }
  1247. return Result;
  1248. }
  1249. //---------------------------------------------------------------------------
  1250. int __fastcall TSFTPFileSystem::SendPacketAndReceiveResponse(
  1251. const TSFTPPacket * Packet, TSFTPPacket * Response, int ExpectedType,
  1252. int AllowStatus)
  1253. {
  1254. int Result;
  1255. TSFTPBusy Busy(this);
  1256. SendPacket(Packet);
  1257. Result = ReceiveResponse(Packet, Response, ExpectedType, AllowStatus);
  1258. return Result;
  1259. }
  1260. //---------------------------------------------------------------------------
  1261. AnsiString __fastcall TSFTPFileSystem::RealPath(const AnsiString Path)
  1262. {
  1263. try
  1264. {
  1265. FTerminal->LogEvent(FORMAT("Getting real path for '%s'",
  1266. (Path)));
  1267. TSFTPPacket Packet(SSH_FXP_REALPATH);
  1268. Packet.AddString(Path);
  1269. SendPacketAndReceiveResponse(&Packet, &Packet, SSH_FXP_NAME);
  1270. if (Packet.GetCardinal() != 1)
  1271. {
  1272. FTerminal->FatalError(LoadStr(SFTP_NON_ONE_FXP_NAME_PACKET));
  1273. }
  1274. AnsiString RealDir = Packet.GetString();
  1275. // ignore rest of SSH_FXP_NAME packet
  1276. FTerminal->LogEvent(FORMAT("Real path is '%s'", (RealDir)));
  1277. return RealDir;
  1278. }
  1279. catch(Exception & E)
  1280. {
  1281. if (FTerminal->Active)
  1282. {
  1283. throw ExtException(&E, FMTLOAD(SFTP_REALPATH_ERROR, (Path)));
  1284. }
  1285. else
  1286. {
  1287. throw;
  1288. }
  1289. }
  1290. }
  1291. //---------------------------------------------------------------------------
  1292. AnsiString __fastcall TSFTPFileSystem::RealPath(const AnsiString Path,
  1293. const AnsiString BaseDir)
  1294. {
  1295. AnsiString APath;
  1296. if (TTerminal::IsAbsolutePath(Path))
  1297. {
  1298. APath = Path;
  1299. }
  1300. else
  1301. {
  1302. if (!Path.IsEmpty())
  1303. {
  1304. // this condition/block was outside (before) current block
  1305. // but it dod not work when Path was empty
  1306. if (!BaseDir.IsEmpty())
  1307. {
  1308. APath = UnixIncludeTrailingBackslash(BaseDir);
  1309. }
  1310. APath = APath + Path;
  1311. }
  1312. if (APath.IsEmpty()) APath = UnixIncludeTrailingBackslash(".");
  1313. }
  1314. return RealPath(APath);
  1315. }
  1316. //---------------------------------------------------------------------------
  1317. AnsiString __fastcall inline TSFTPFileSystem::LocalCanonify(const AnsiString Path)
  1318. {
  1319. // TODO: improve (handle .. etc.)
  1320. if (TTerminal::IsAbsolutePath(Path)) return Path;
  1321. else
  1322. {
  1323. return UnixIncludeTrailingBackslash(FCurrentDirectory) + Path;
  1324. }
  1325. }
  1326. //---------------------------------------------------------------------------
  1327. AnsiString __fastcall inline TSFTPFileSystem::Canonify(AnsiString Path)
  1328. {
  1329. // inspired by canonify() from PSFTP.C
  1330. AnsiString Result;
  1331. FTerminal->LogEvent(FORMAT("Canonifying: \"%s\"", (Path)));
  1332. Path = LocalCanonify(Path);
  1333. try
  1334. {
  1335. Result = RealPath(Path);
  1336. }
  1337. catch(...)
  1338. {
  1339. if (FTerminal->Active)
  1340. {
  1341. AnsiString APath = UnixExcludeTrailingBackslash(Path);
  1342. AnsiString Name = UnixExtractFileName(APath);
  1343. if (Name == "." || Name == "..")
  1344. {
  1345. Result = Path;
  1346. }
  1347. else
  1348. {
  1349. AnsiString FPath = UnixExtractFilePath(APath);
  1350. try
  1351. {
  1352. Result = RealPath(FPath);
  1353. Result = UnixIncludeTrailingBackslash(Result) + Name;
  1354. }
  1355. catch(...)
  1356. {
  1357. if (FTerminal->Active)
  1358. {
  1359. Result = Path;
  1360. }
  1361. else
  1362. {
  1363. throw;
  1364. }
  1365. }
  1366. }
  1367. }
  1368. else
  1369. {
  1370. throw;
  1371. }
  1372. }
  1373. FTerminal->LogEvent(FORMAT("Canonified: \"%s\"", (Result)));
  1374. return Result;
  1375. }
  1376. //---------------------------------------------------------------------------
  1377. AnsiString __fastcall TSFTPFileSystem::AbsolutePath(AnsiString Path)
  1378. {
  1379. return RealPath(Path, CurrentDirectory);
  1380. }
  1381. //---------------------------------------------------------------------------
  1382. AnsiString __fastcall TSFTPFileSystem::GetHomeDirectory()
  1383. {
  1384. if (FHomeDirectory.IsEmpty())
  1385. {
  1386. FHomeDirectory = RealPath(".");
  1387. }
  1388. return FHomeDirectory;
  1389. }
  1390. //---------------------------------------------------------------------------
  1391. TRemoteFile * __fastcall TSFTPFileSystem::LoadFile(TSFTPPacket * Packet,
  1392. TRemoteFile * ALinkedByFile)
  1393. {
  1394. TRemoteFile * File = new TRemoteFile(ALinkedByFile);
  1395. try
  1396. {
  1397. File->Terminal = FTerminal;
  1398. Packet->GetFile(File, FVersion);
  1399. }
  1400. catch(...)
  1401. {
  1402. delete File;
  1403. throw;
  1404. }
  1405. return File;
  1406. }
  1407. //---------------------------------------------------------------------------
  1408. void __fastcall TSFTPFileSystem::SetCurrentDirectory(AnsiString value)
  1409. {
  1410. assert(false);
  1411. }
  1412. //---------------------------------------------------------------------------
  1413. AnsiString __fastcall TSFTPFileSystem::GetCurrentDirectory()
  1414. {
  1415. return FCurrentDirectory;
  1416. }
  1417. //---------------------------------------------------------------------------
  1418. void __fastcall TSFTPFileSystem::DoStartup()
  1419. {
  1420. TSFTPPacket Packet(SSH_FXP_INIT);
  1421. Packet.AddCardinal(SFTPMaxVersion);
  1422. try
  1423. {
  1424. SendPacketAndReceiveResponse(&Packet, &Packet, SSH_FXP_VERSION);
  1425. }
  1426. catch(Exception &E)
  1427. {
  1428. FTerminal->FatalError(&E, LoadStr(SFTP_INITIALIZE_ERROR));
  1429. }
  1430. FVersion = Packet.GetCardinal();
  1431. FTerminal->LogEvent(FORMAT("SFTP version %d negotiated.", (FVersion)));
  1432. if (FVersion < SFTPMinVersion || FVersion > SFTPMaxVersion)
  1433. {
  1434. FTerminal->FatalError(FMTLOAD(SFTP_VERSION_NOT_SUPPORTED,
  1435. (FVersion, SFTPMinVersion, SFTPMaxVersion)));
  1436. }
  1437. if (FVersion >= 3)
  1438. {
  1439. FEOL = "\r\n";
  1440. AnsiString ExtensionName;
  1441. AnsiString ExtensionData;
  1442. AnsiString ExtensionDisplayData;
  1443. while (Packet.NextData)
  1444. {
  1445. ExtensionName = Packet.GetString();
  1446. ExtensionData = Packet.GetString();
  1447. ExtensionDisplayData = IsDisplayableStr(ExtensionData) ? ExtensionData :
  1448. "0x" + StrToHex(ExtensionData);
  1449. if (ExtensionName == "newline")
  1450. {
  1451. FEOL = ExtensionData;
  1452. FTerminal->LogEvent(FORMAT("Server requests EOL sequence %s.",
  1453. (ExtensionDisplayData)));
  1454. if (FEOL.Length() < 1 || FEOL.Length() > 2)
  1455. {
  1456. FTerminal->FatalError(FMTLOAD(SFTP_INVALID_EOL, (ExtensionDisplayData)));
  1457. }
  1458. }
  1459. else
  1460. {
  1461. FTerminal->LogEvent(FORMAT("Unknown server extension %s=%s",
  1462. (ExtensionName, ExtensionDisplayData)));
  1463. }
  1464. FExtensions->Values[ExtensionName] = ExtensionData;
  1465. }
  1466. Packet.ChangeType(SSH_FXP_EXTENDED);
  1467. Packet.AddString("[email protected]");
  1468. int Status = SendPacketAndReceiveResponse(&Packet, &Packet, SSH_FXP_STATUS,
  1469. asOK | asOpUnsupported);
  1470. if (Status == SSH_FX_OK)
  1471. {
  1472. FTerminal->LogEvent("Server recognises WinSCP.");
  1473. }
  1474. else
  1475. {
  1476. FTerminal->LogEvent("Server does not recognise WinSCP.");
  1477. }
  1478. }
  1479. }
  1480. //---------------------------------------------------------------------------
  1481. char * __fastcall TSFTPFileSystem::GetEOL() const
  1482. {
  1483. if (FVersion >= 4)
  1484. {
  1485. assert(!FEOL.IsEmpty());
  1486. return FEOL.c_str();
  1487. }
  1488. else
  1489. {
  1490. return EOLToStr(FTerminal->SessionData->EOLType);
  1491. }
  1492. }
  1493. //---------------------------------------------------------------------------
  1494. void __fastcall TSFTPFileSystem::LookupUserGroups()
  1495. {
  1496. assert(false);
  1497. }
  1498. //---------------------------------------------------------------------------
  1499. void __fastcall TSFTPFileSystem::ReadCurrentDirectory()
  1500. {
  1501. if (!FDirectoryToChangeTo.IsEmpty())
  1502. {
  1503. FCurrentDirectory = FDirectoryToChangeTo;
  1504. FDirectoryToChangeTo = "";
  1505. }
  1506. else if (FCurrentDirectory.IsEmpty())
  1507. {
  1508. // this happens only after startup when default remote directory is not specified
  1509. FCurrentDirectory = GetHomeDirectory();
  1510. }
  1511. }
  1512. //---------------------------------------------------------------------------
  1513. void __fastcall TSFTPFileSystem::HomeDirectory()
  1514. {
  1515. ChangeDirectory(GetHomeDirectory());
  1516. }
  1517. //---------------------------------------------------------------------------
  1518. void __fastcall TSFTPFileSystem::TryOpenDirectory(const AnsiString Directory)
  1519. {
  1520. FTerminal->LogEvent(FORMAT("Trying to open directory \"%s\".", (Directory)));
  1521. TSFTPPacket Packet(SSH_FXP_OPENDIR);
  1522. Packet.AddString(Directory);
  1523. SendPacketAndReceiveResponse(&Packet, &Packet, SSH_FXP_HANDLE);
  1524. AnsiString Handle = Packet.GetString();
  1525. Packet.ChangeType(SSH_FXP_CLOSE);
  1526. Packet.AddString(Handle);
  1527. SendPacketAndReceiveResponse(&Packet, &Packet, SSH_FXP_STATUS, asAll);
  1528. }
  1529. //---------------------------------------------------------------------------
  1530. void __fastcall TSFTPFileSystem::ChangeDirectory(const AnsiString Directory)
  1531. {
  1532. AnsiString Path, Current;
  1533. Current = !FDirectoryToChangeTo.IsEmpty() ? FDirectoryToChangeTo : FCurrentDirectory;
  1534. Path = RealPath(Directory, Current);
  1535. // to verify existence of directory try to open it (SSH_FXP_REALPATH succeeds
  1536. // for invalid paths on some systems, like CygWin)
  1537. TryOpenDirectory(Path);
  1538. // if open dir did not fail, directory exists -> success.
  1539. FDirectoryToChangeTo = Path;
  1540. }
  1541. //---------------------------------------------------------------------------
  1542. void __fastcall TSFTPFileSystem::CachedChangeDirectory(const AnsiString Directory)
  1543. {
  1544. FDirectoryToChangeTo = Directory;
  1545. }
  1546. //---------------------------------------------------------------------------
  1547. void __fastcall TSFTPFileSystem::ReadDirectory(TRemoteFileList * FileList)
  1548. {
  1549. assert(FileList && !FileList->Directory.IsEmpty());
  1550. AnsiString Directory = LocalCanonify(FileList->Directory);
  1551. FTerminal->LogEvent(FORMAT("Listing directory \"%s\".", (Directory)));
  1552. // moved before SSH_FXP_OPENDIR, so directory listing does not retain
  1553. // old data (e.g. parent directory) when reading fails
  1554. FileList->Clear();
  1555. TSFTPPacket Packet(SSH_FXP_OPENDIR);
  1556. AnsiString Handle;
  1557. try
  1558. {
  1559. Packet.AddString(Directory);
  1560. SendPacketAndReceiveResponse(&Packet, &Packet, SSH_FXP_HANDLE);
  1561. Handle = Packet.GetString();
  1562. }
  1563. catch(...)
  1564. {
  1565. if (FTerminal->Active)
  1566. {
  1567. FileList->AddFile(new TRemoteParentDirectory());
  1568. }
  1569. throw;
  1570. }
  1571. TSFTPPacket Response;
  1572. try
  1573. {
  1574. bool isEOF = false;
  1575. int Total = 0;
  1576. TRemoteFile * File;
  1577. Packet.ChangeType(SSH_FXP_READDIR);
  1578. Packet.AddString(Handle);
  1579. SendPacket(&Packet);
  1580. do
  1581. {
  1582. ReceiveResponse(&Packet, &Response);
  1583. if (Response.Type == SSH_FXP_NAME)
  1584. {
  1585. TSFTPPacket ListingPacket = Response;
  1586. Packet.ChangeType(SSH_FXP_READDIR);
  1587. Packet.AddString(Handle);
  1588. SendPacket(&Packet);
  1589. ReserveResponse(&Packet, &Response);
  1590. unsigned int Count = ListingPacket.GetCardinal();
  1591. for (unsigned long Index = 0; Index < Count; Index++)
  1592. {
  1593. File = LoadFile(&ListingPacket, NULL);
  1594. FileList->AddFile(File);
  1595. Total++;
  1596. }
  1597. if (Count == 0)
  1598. {
  1599. FTerminal->LogEvent("Empty directory listing packet. Aborting directory reading.");
  1600. isEOF = true;
  1601. }
  1602. }
  1603. else if (Response.Type == SSH_FXP_STATUS)
  1604. {
  1605. isEOF = (GotStatusPacket(&Response, asEOF) == SSH_FX_EOF);
  1606. }
  1607. else
  1608. {
  1609. FTerminal->FatalError(FMTLOAD(SFTP_INVALID_TYPE, ((int)Response.Type)));
  1610. }
  1611. }
  1612. while (!isEOF);
  1613. if (Total == 0)
  1614. {
  1615. // Empty file list -> probably "permision denied", we
  1616. // at least get link to parent directory ("..")
  1617. try
  1618. {
  1619. FTerminal->ExceptionOnFail = true;
  1620. try
  1621. {
  1622. File = NULL;
  1623. FTerminal->ReadFile(
  1624. UnixIncludeTrailingBackslash(FileList->Directory) + PARENTDIRECTORY, File);
  1625. }
  1626. __finally
  1627. {
  1628. FTerminal->ExceptionOnFail = false;
  1629. }
  1630. }
  1631. catch(Exception &E)
  1632. {
  1633. if (E.InheritsFrom(__classid(EFatal))) throw;
  1634. else File = NULL;
  1635. }
  1636. // on some systems even getting ".." fails, we create dummy ".." instead
  1637. bool Failure = (File == NULL);
  1638. if (Failure)
  1639. {
  1640. File = new TRemoteFile();
  1641. File->FileName = PARENTDIRECTORY;
  1642. File->Modification = Now();
  1643. File->Type = FILETYPE_DIRECTORY;
  1644. }
  1645. assert(File && File->IsParentDirectory);
  1646. FileList->AddFile(File);
  1647. if (Failure)
  1648. {
  1649. throw Exception(FMTLOAD(EMPTY_DIRECTORY, (FileList->Directory)));
  1650. }
  1651. }
  1652. }
  1653. __finally
  1654. {
  1655. if (FTerminal->Active)
  1656. {
  1657. Packet.ChangeType(SSH_FXP_CLOSE);
  1658. Packet.AddString(Handle);
  1659. SendPacketAndReceiveResponse(&Packet, &Packet, SSH_FXP_STATUS, asAll);
  1660. }
  1661. }
  1662. }
  1663. //---------------------------------------------------------------------------
  1664. void __fastcall TSFTPFileSystem::ReadSymlink(TRemoteFile * SymlinkFile,
  1665. TRemoteFile *& File)
  1666. {
  1667. assert(SymlinkFile && SymlinkFile->IsSymLink);
  1668. assert(FVersion >= 3); // symlinks are supported with SFTP version 3 and later
  1669. AnsiString FileName = LocalCanonify(SymlinkFile->FileName);
  1670. TSFTPPacket ReadLinkPacket(SSH_FXP_READLINK);
  1671. ReadLinkPacket.AddString(FileName);
  1672. SendPacket(&ReadLinkPacket);
  1673. ReserveResponse(&ReadLinkPacket, &ReadLinkPacket);
  1674. // send second request before reading response to first one
  1675. // (performance benefit)
  1676. TSFTPPacket AttrsPacket(SSH_FXP_STAT);
  1677. AttrsPacket.AddString(FileName);
  1678. SendPacket(&AttrsPacket);
  1679. ReserveResponse(&AttrsPacket, &AttrsPacket);
  1680. ReceiveResponse(&ReadLinkPacket, &ReadLinkPacket, SSH_FXP_NAME);
  1681. if (ReadLinkPacket.GetCardinal() != 1)
  1682. {
  1683. FTerminal->FatalError(LoadStr(SFTP_NON_ONE_FXP_NAME_PACKET));
  1684. }
  1685. SymlinkFile->LinkTo = ReadLinkPacket.GetString();
  1686. ReceiveResponse(&AttrsPacket, &AttrsPacket, SSH_FXP_ATTRS);
  1687. File = LoadFile(&AttrsPacket, SymlinkFile);
  1688. File->FileName = UnixExtractFileName(SymlinkFile->FileName);
  1689. }
  1690. //---------------------------------------------------------------------------
  1691. void __fastcall TSFTPFileSystem::ReadFile(const AnsiString FileName,
  1692. TRemoteFile *& File)
  1693. {
  1694. CustomReadFile(FileName, File, SSH_FXP_LSTAT);
  1695. }
  1696. //---------------------------------------------------------------------------
  1697. bool __fastcall inline TSFTPFileSystem::RemoteFileExists(const AnsiString FullPath,
  1698. TRemoteFile ** File)
  1699. {
  1700. bool Result;
  1701. try
  1702. {
  1703. TRemoteFile * AFile;
  1704. CustomReadFile(FullPath, AFile, SSH_FXP_LSTAT, NULL, true);
  1705. Result = (AFile != NULL);
  1706. if (Result)
  1707. {
  1708. if (File)
  1709. {
  1710. *File = AFile;
  1711. }
  1712. else
  1713. {
  1714. delete AFile;
  1715. }
  1716. }
  1717. }
  1718. catch(...)
  1719. {
  1720. if (!FTerminal->Active)
  1721. {
  1722. throw;
  1723. }
  1724. Result = false;
  1725. }
  1726. return Result;
  1727. }
  1728. //---------------------------------------------------------------------------
  1729. void __fastcall TSFTPFileSystem::CustomReadFile(const AnsiString FileName,
  1730. TRemoteFile *& File, char Type, TRemoteFile * ALinkedByFile,
  1731. bool AllowNonexistence)
  1732. {
  1733. TSFTPPacket Packet(Type);
  1734. Packet.AddString(LocalCanonify(FileName));
  1735. if (FVersion >= 4)
  1736. {
  1737. Packet.AddCardinal(SSH_FILEXFER_ATTR_SIZE | SSH_FILEXFER_ATTR_PERMISSIONS |
  1738. SSH_FILEXFER_ATTR_ACCESSTIME | SSH_FILEXFER_ATTR_MODIFYTIME |
  1739. SSH_FILEXFER_ATTR_OWNERGROUP);
  1740. }
  1741. SendPacketAndReceiveResponse(&Packet, &Packet, SSH_FXP_ATTRS,
  1742. AllowNonexistence ? asNoSuchFile : -1);
  1743. if (Packet.Type == SSH_FXP_ATTRS)
  1744. {
  1745. File = LoadFile(&Packet, ALinkedByFile);
  1746. File->FileName = UnixExtractFileName(FileName);
  1747. }
  1748. else
  1749. {
  1750. assert(AllowNonexistence);
  1751. File = NULL;
  1752. }
  1753. }
  1754. //---------------------------------------------------------------------------
  1755. void __fastcall TSFTPFileSystem::DeleteFile(const AnsiString FileName,
  1756. const TRemoteFile * File, bool Recursive)
  1757. {
  1758. char Type;
  1759. AnsiString RealFileName = LocalCanonify(FileName);
  1760. if (File && File->IsDirectory && !File->IsSymLink)
  1761. {
  1762. if (Recursive)
  1763. {
  1764. FTerminal->ProcessDirectory(FileName, FTerminal->DeleteFile, &Recursive);
  1765. }
  1766. Type = SSH_FXP_RMDIR;
  1767. }
  1768. else
  1769. {
  1770. Type = SSH_FXP_REMOVE;
  1771. }
  1772. TSFTPPacket Packet(Type);
  1773. Packet.AddString(RealFileName);
  1774. SendPacketAndReceiveResponse(&Packet, &Packet, SSH_FXP_STATUS);
  1775. }
  1776. //---------------------------------------------------------------------------
  1777. void __fastcall TSFTPFileSystem::RenameFile(const AnsiString FileName,
  1778. const AnsiString NewName)
  1779. {
  1780. TSFTPPacket Packet(SSH_FXP_RENAME);
  1781. AnsiString RealName = LocalCanonify(FileName);
  1782. Packet.AddString(RealName);
  1783. Packet.AddString(UnixExtractFilePath(RealName) + NewName);
  1784. SendPacketAndReceiveResponse(&Packet, &Packet, SSH_FXP_STATUS);
  1785. }
  1786. //---------------------------------------------------------------------------
  1787. void __fastcall TSFTPFileSystem::CreateDirectory(const AnsiString DirName,
  1788. const TRemoteProperties * Properties)
  1789. {
  1790. TSFTPPacket Packet(SSH_FXP_MKDIR);
  1791. AnsiString CanonifiedName = Canonify(DirName);
  1792. Packet.AddString(CanonifiedName);
  1793. Packet.AddProperties(Properties, 0, true, FVersion);
  1794. SendPacketAndReceiveResponse(&Packet, &Packet, SSH_FXP_STATUS);
  1795. }
  1796. //---------------------------------------------------------------------------
  1797. void __fastcall TSFTPFileSystem::CreateLink(const AnsiString FileName,
  1798. const AnsiString PointTo, bool Symbolic)
  1799. {
  1800. assert(Symbolic); // only symlinks are supported by SFTP
  1801. assert(FVersion >= 3); // symlinks are supported with SFTP version 3 and later
  1802. TSFTPPacket Packet(SSH_FXP_SYMLINK);
  1803. Packet.AddString(PointTo);
  1804. Packet.AddString(Canonify(FileName));
  1805. SendPacketAndReceiveResponse(&Packet, &Packet, SSH_FXP_STATUS);
  1806. }
  1807. //---------------------------------------------------------------------------
  1808. void __fastcall TSFTPFileSystem::ChangeFileProperties(const AnsiString FileName,
  1809. const TRemoteFile * /*File*/, const TRemoteProperties * Properties)
  1810. {
  1811. assert(Properties);
  1812. TRemoteFile * File;
  1813. AnsiString RealFileName = LocalCanonify(FileName);
  1814. ReadFile(RealFileName, File);
  1815. try
  1816. {
  1817. assert(File);
  1818. if (File->IsDirectory && !File->IsSymLink && Properties->Recursive)
  1819. {
  1820. FTerminal->ProcessDirectory(FileName, FTerminal->ChangeFileProperties,
  1821. (void*)Properties);
  1822. }
  1823. TSFTPPacket Packet(SSH_FXP_SETSTAT);
  1824. Packet.AddString(RealFileName);
  1825. Packet.AddProperties(Properties, *File->Rights, File->IsDirectory, FVersion);
  1826. SendPacketAndReceiveResponse(&Packet, &Packet, SSH_FXP_STATUS);
  1827. }
  1828. __finally
  1829. {
  1830. delete File;
  1831. }
  1832. }
  1833. //---------------------------------------------------------------------------
  1834. void __fastcall TSFTPFileSystem::CustomCommandOnFile(const AnsiString /*FileName*/,
  1835. const TRemoteFile * /*File*/, AnsiString /*Command*/, int /*Params*/)
  1836. {
  1837. assert(false);
  1838. }
  1839. //---------------------------------------------------------------------------
  1840. void __fastcall TSFTPFileSystem::AnyCommand(const AnsiString /*Command*/)
  1841. {
  1842. assert(false);
  1843. }
  1844. //---------------------------------------------------------------------------
  1845. // transfer protocol
  1846. //---------------------------------------------------------------------------
  1847. void __fastcall TSFTPFileSystem::CopyToRemote(TStrings * FilesToCopy,
  1848. const AnsiString TargetDir, const TCopyParamType * CopyParam,
  1849. int Params, TFileOperationProgressType * OperationProgress,
  1850. bool & DisconnectWhenComplete)
  1851. {
  1852. assert(FilesToCopy && OperationProgress);
  1853. AnsiString FileName, FileNameOnly;
  1854. AnsiString FullTargetDir = UnixIncludeTrailingBackslash(TargetDir);
  1855. int Index = 0;
  1856. while (Index < FilesToCopy->Count && !OperationProgress->Cancel)
  1857. {
  1858. bool Success = false;
  1859. FileName = FilesToCopy->Strings[Index];
  1860. FileNameOnly = ExtractFileName(FileName);
  1861. assert(!FAvoidBusy);
  1862. FAvoidBusy = true;
  1863. try
  1864. {
  1865. try
  1866. {
  1867. if (FTerminal->SessionData->CacheDirectories)
  1868. {
  1869. FTerminal->DirectoryModified(TargetDir, false);
  1870. if (DirectoryExists(FileName))
  1871. {
  1872. FTerminal->DirectoryModified(UnixIncludeTrailingBackslash(TargetDir)+
  1873. FileNameOnly, true);
  1874. }
  1875. }
  1876. SFTPSource(FileName, FullTargetDir, CopyParam, Params, OperationProgress, 0);
  1877. Success = true;
  1878. }
  1879. catch(EScpSkipFile & E)
  1880. {
  1881. SUSPEND_OPERATION (
  1882. if (!FTerminal->HandleException(&E)) throw;
  1883. );
  1884. }
  1885. }
  1886. __finally
  1887. {
  1888. FAvoidBusy = false;
  1889. OperationProgress->Finish(FileNameOnly, Success, DisconnectWhenComplete);
  1890. }
  1891. Index++;
  1892. }
  1893. }
  1894. //---------------------------------------------------------------------------
  1895. void __fastcall TSFTPFileSystem::SFTPConfirmOverwrite(const AnsiString FileName,
  1896. bool TargetBiggerThanSource, TFileOperationProgressType * OperationProgress,
  1897. TSFTPOverwriteMode & OverwriteMode, const TOverwriteFileParams * FileParams)
  1898. {
  1899. if (OperationProgress->NoToAll)
  1900. {
  1901. THROW_SKIP_FILE_NULL;
  1902. }
  1903. else
  1904. {
  1905. int Answer;
  1906. SUSPEND_OPERATION
  1907. (
  1908. int Answers = qaYes | qaNo | qaAbort | qaYesToAll | qaNoToAll;
  1909. if ((FVersion < 4) || !OperationProgress->AsciiTransfer)
  1910. {
  1911. Answers |= qaAppend;
  1912. }
  1913. Answer = FTerminal->ConfirmFileOverwrite(FileName, FileParams,
  1914. Answers, qpNeverAskAgainCheck);
  1915. );
  1916. if (Answer == qaAppend)
  1917. {
  1918. if (TargetBiggerThanSource || OperationProgress->AsciiTransfer)
  1919. {
  1920. OverwriteMode = omAppend;
  1921. }
  1922. else
  1923. {
  1924. SUSPEND_OPERATION
  1925. (
  1926. Answer = FTerminal->DoQueryUser(FORMAT(LoadStr(APPEND_OR_RESUME), (FileName)),
  1927. qaYes | qaNo | qaCancel, 0);
  1928. );
  1929. if (Answer == qaCancel)
  1930. {
  1931. if (!OperationProgress->Cancel)
  1932. {
  1933. OperationProgress->Cancel = csCancel;
  1934. }
  1935. Abort();
  1936. }
  1937. else
  1938. {
  1939. OverwriteMode = ((Answer == qaYes) ? omAppend : omResume);
  1940. }
  1941. }
  1942. }
  1943. else
  1944. {
  1945. OverwriteMode = omOverwrite;
  1946. switch (Answer) {
  1947. case qaNeverAskAgain:
  1948. FTerminal->Configuration->ConfirmOverwriting = false;
  1949. case qaYesToAll:
  1950. OperationProgress->YesToAll = true;
  1951. case qaYes:
  1952. // file overwriting was confirmed, try to open file
  1953. // second time, now without exclusive flag (SSH_FXF_EXCL)
  1954. break;
  1955. case qaAbort:
  1956. if (!OperationProgress->Cancel)
  1957. {
  1958. OperationProgress->Cancel = csCancel;
  1959. }
  1960. Abort();
  1961. break;
  1962. case qaNoToAll:
  1963. OperationProgress->NoToAll = true;
  1964. case qaNo:
  1965. THROW_SKIP_FILE_NULL;
  1966. }
  1967. }
  1968. }
  1969. }
  1970. //---------------------------------------------------------------------------
  1971. bool TSFTPFileSystem::SFTPConfirmResume(const AnsiString DestFileName,
  1972. bool PartialBiggerThanSource, TFileOperationProgressType * OperationProgress)
  1973. {
  1974. bool ResumeTransfer;
  1975. assert(OperationProgress);
  1976. if (PartialBiggerThanSource)
  1977. {
  1978. int Answer;
  1979. SUSPEND_OPERATION
  1980. (
  1981. Answer = FTerminal->DoQueryUser(
  1982. FMTLOAD(PARTIAL_BIGGER_THAN_SOURCE, (DestFileName)), NULL,
  1983. qaOK | qaAbort, qpAllowContinueOnError, qtWarning);
  1984. )
  1985. if (Answer == qaAbort)
  1986. {
  1987. if (!OperationProgress->Cancel)
  1988. {
  1989. OperationProgress->Cancel = csCancel;
  1990. }
  1991. Abort();
  1992. }
  1993. ResumeTransfer = false;
  1994. }
  1995. else
  1996. {
  1997. int Answer;
  1998. SUSPEND_OPERATION
  1999. (
  2000. Answer = FTerminal->DoQueryUser(
  2001. FMTLOAD(RESUME_TRANSFER, (DestFileName)), qaYes | qaNo | qaAbort,
  2002. qpAllowContinueOnError);
  2003. );
  2004. switch (Answer) {
  2005. case qaYes:
  2006. ResumeTransfer = true;
  2007. break;
  2008. case qaNo:
  2009. ResumeTransfer = false;
  2010. break;
  2011. case qaAbort:
  2012. if (!OperationProgress->Cancel)
  2013. {
  2014. OperationProgress->Cancel = csCancel;
  2015. }
  2016. Abort();
  2017. break;
  2018. }
  2019. }
  2020. return ResumeTransfer;
  2021. }
  2022. //---------------------------------------------------------------------------
  2023. void __fastcall TSFTPFileSystem::SFTPSource(const AnsiString FileName,
  2024. const AnsiString TargetDir, const TCopyParamType * CopyParam, int Params,
  2025. TFileOperationProgressType * OperationProgress, int Level)
  2026. {
  2027. FTerminal->LogEvent(FORMAT("File: \"%s\"", (FileName)));
  2028. OperationProgress->SetFile(FileName);
  2029. TOpenRemoteFileParams OpenParams;
  2030. OpenParams.OverwriteMode = omOverwrite;
  2031. HANDLE File;
  2032. unsigned long MTime, ATime;
  2033. __int64 Size;
  2034. FTerminal->OpenLocalFile(FileName, GENERIC_READ, &OpenParams.LocalFileAttrs,
  2035. &File, NULL, &MTime, &ATime, &Size);
  2036. if (OpenParams.LocalFileAttrs & faDirectory)
  2037. {
  2038. SFTPDirectorySource(IncludeTrailingBackslash(FileName), TargetDir,
  2039. OpenParams.LocalFileAttrs, CopyParam, Params, OperationProgress, Level);
  2040. }
  2041. else
  2042. {
  2043. try
  2044. {
  2045. // File is regular file (not directory)
  2046. assert(File);
  2047. AnsiString DestFileName = CopyParam->ChangeFileName(ExtractFileName(FileName),
  2048. osLocal, Level == 0);
  2049. AnsiString DestFullName = LocalCanonify(TargetDir + DestFileName);
  2050. AnsiString DestPartinalFullName;
  2051. bool ResumeAllowed;
  2052. bool ResumeTransfer = false;
  2053. bool DestFileExists = false;
  2054. __int64 ResumeOffset;
  2055. FTerminal->LogEvent(FORMAT("Copying \"%s\" to remote directory started.", (FileName)));
  2056. OperationProgress->SetLocalSize(Size);
  2057. // Suppose same data size to transfer as to read
  2058. // (not true with ASCII transfer)
  2059. OperationProgress->SetTransferSize(OperationProgress->LocalSize);
  2060. OperationProgress->TransferingFile = false;
  2061. // Will we use ASCII of BINARY file tranfer?
  2062. OperationProgress->SetAsciiTransfer(CopyParam->UseAsciiTransfer(FileName));
  2063. FTerminal->LogEvent(
  2064. AnsiString((OperationProgress->AsciiTransfer ? "Ascii" : "Binary")) +
  2065. " transfer mode selected.");
  2066. ResumeAllowed = !OperationProgress->AsciiTransfer &&
  2067. CopyParam->AllowResume(OperationProgress->LocalSize) &&
  2068. IsCapable(fcRename);
  2069. OperationProgress->SetResumeStatus(ResumeAllowed ? rsEnabled : rsDisabled);
  2070. TOverwriteFileParams FileParams;
  2071. FileParams.SourceSize = OperationProgress->LocalSize;
  2072. FileParams.SourceTimestamp = UnixToDateTime(MTime);
  2073. if (ResumeAllowed)
  2074. {
  2075. DestPartinalFullName = DestFullName + FTerminal->Configuration->PartialExt;
  2076. FTerminal->LogEvent("Checking existence of file.");
  2077. TRemoteFile * File = new TRemoteFile();
  2078. DestFileExists = RemoteFileExists(DestFullName, &File);
  2079. if (DestFileExists)
  2080. {
  2081. OpenParams.DestFileSize = File->Size;
  2082. FileParams.DestSize = OpenParams.DestFileSize;
  2083. FileParams.DestTimestamp = File->Modification;
  2084. delete File;
  2085. File = NULL;
  2086. }
  2087. FTerminal->LogEvent("Checking existence of partially transfered file.");
  2088. if (RemoteFileExists(DestPartinalFullName, &File))
  2089. {
  2090. ResumeOffset = File->Size;
  2091. delete File;
  2092. File = NULL;
  2093. ResumeTransfer = SFTPConfirmResume(DestFileName,
  2094. ResumeOffset > OperationProgress->LocalSize, OperationProgress);
  2095. if (!ResumeTransfer)
  2096. {
  2097. DeleteFile(DestPartinalFullName);
  2098. }
  2099. else
  2100. {
  2101. FTerminal->LogEvent("Resuming file transfer.");
  2102. }
  2103. }
  2104. else
  2105. {
  2106. // partial upload file does not exists, check for full file
  2107. if (DestFileExists && FTerminal->Configuration->ConfirmOverwriting &&
  2108. !OperationProgress->YesToAll && !(Params & cpNoConfirmation))
  2109. {
  2110. SFTPConfirmOverwrite(DestFileName,
  2111. OpenParams.DestFileSize >= OperationProgress->LocalSize,
  2112. OperationProgress, OpenParams.OverwriteMode, &FileParams);
  2113. }
  2114. }
  2115. }
  2116. bool DoResume = (ResumeAllowed && (OpenParams.OverwriteMode == omOverwrite));
  2117. OpenParams.RemoteFileName = DoResume ? DestPartinalFullName : DestFullName;
  2118. OpenParams.Resume = DoResume;
  2119. OpenParams.OperationProgress = OperationProgress;
  2120. OpenParams.CopyParam = CopyParam;
  2121. OpenParams.Params = Params;
  2122. OpenParams.FileParams = &FileParams;
  2123. FTerminal->LogEvent("Opening remote file.");
  2124. FTerminal->FileOperationLoop(SFTPOpenRemote, OperationProgress, true,
  2125. FMTLOAD(SFTP_CREATE_FILE_ERROR, (OpenParams.RemoteFileName)),
  2126. &OpenParams);
  2127. bool TransferFinished = false;
  2128. __int64 DestWriteOffset = 0;
  2129. try
  2130. {
  2131. if (OpenParams.OverwriteMode == omAppend)
  2132. {
  2133. FTerminal->LogEvent("Appending file.");
  2134. DestWriteOffset = OpenParams.DestFileSize;
  2135. }
  2136. else if (ResumeTransfer || (OpenParams.OverwriteMode == omResume))
  2137. {
  2138. if (OpenParams.OverwriteMode == omResume)
  2139. {
  2140. FTerminal->LogEvent("Resuming file transfer (append style).");
  2141. ResumeOffset = OpenParams.DestFileSize;
  2142. }
  2143. FileSeek((THandle)File, ResumeOffset, 0);
  2144. OperationProgress->AddResumed(ResumeOffset);
  2145. }
  2146. // at end of this block queue is disposed
  2147. {
  2148. TSFTPUploadQueue Queue(this);
  2149. unsigned long BlockSize = MaxTransferBlockSize(4);
  2150. int QueueLen = int(OperationProgress->LocalSize / BlockSize);
  2151. if (QueueLen > FTerminal->SessionData->SFTPUploadQueue)
  2152. {
  2153. QueueLen = FTerminal->SessionData->SFTPUploadQueue;
  2154. }
  2155. if (QueueLen < 1)
  2156. {
  2157. QueueLen = 1;
  2158. }
  2159. bool Initialized;
  2160. Initialized = Queue.Init(QueueLen, FileName, File, OperationProgress,
  2161. OpenParams.RemoteFileHandle, BlockSize,
  2162. DestWriteOffset + OperationProgress->TransferedSize);
  2163. if (Initialized)
  2164. {
  2165. while (Queue.Next(SSH_FXP_STATUS))
  2166. {
  2167. if (OperationProgress->Cancel == csCancel)
  2168. {
  2169. Abort();
  2170. }
  2171. }
  2172. }
  2173. }
  2174. TransferFinished = true;
  2175. }
  2176. __finally
  2177. {
  2178. if (FTerminal->Active)
  2179. {
  2180. SFTPCloseRemote(OpenParams.RemoteFileHandle, DestFileName,
  2181. OperationProgress, TransferFinished);
  2182. // delete file if transfer was not completed and resuming is not allowed
  2183. if (!TransferFinished && !DoResume)
  2184. {
  2185. DeleteFile(OpenParams.RemoteFileName);
  2186. }
  2187. }
  2188. }
  2189. // originally this was before CLOSE (last __finally statement),
  2190. // on VShell it failed
  2191. if (DoResume)
  2192. {
  2193. FILE_OPERATION_LOOP(FMTLOAD(RENAME_AFTER_RESUME_ERROR,
  2194. (UnixExtractFileName(OpenParams.RemoteFileName), DestFileName)),
  2195. if (DestFileExists)
  2196. {
  2197. DeleteFile(DestFullName);
  2198. DestFileExists = false;
  2199. }
  2200. RenameFile(OpenParams.RemoteFileName, DestFileName);
  2201. );
  2202. }
  2203. if (CopyParam->PreserveTime)
  2204. {
  2205. FILE_OPERATION_LOOP(FMTLOAD(PRESERVE_TIME_ERROR, (DestFileName)),
  2206. TSFTPPacket Packet(SSH_FXP_SETSTAT);
  2207. Packet.AddString(DestFullName);
  2208. if (FVersion >= 4)
  2209. {
  2210. Packet.AddCardinal(SSH_FILEXFER_ATTR_ACCESSTIME |
  2211. SSH_FILEXFER_ATTR_MODIFYTIME);
  2212. Packet.AddByte(SSH_FILEXFER_TYPE_REGULAR);
  2213. Packet.AddInt64(ATime);
  2214. Packet.AddInt64(MTime);
  2215. }
  2216. else
  2217. {
  2218. Packet.AddCardinal(SSH_FILEXFER_ATTR_ACMODTIME);
  2219. Packet.AddCardinal(ATime);
  2220. Packet.AddCardinal(MTime);
  2221. }
  2222. SendPacketAndReceiveResponse(&Packet, NULL, SSH_FXP_STATUS);
  2223. );
  2224. }
  2225. }
  2226. __finally
  2227. {
  2228. CloseHandle(File);
  2229. }
  2230. }
  2231. /* TODO : Delete also read-only files. */
  2232. /* TODO : Show error message on failure. */
  2233. if (Params & cpDelete) Sysutils::DeleteFile(FileName);
  2234. }
  2235. //---------------------------------------------------------------------------
  2236. int __fastcall TSFTPFileSystem::SFTPOpenRemote(void * AOpenParams, void * /*Param2*/)
  2237. {
  2238. TOpenRemoteFileParams * OpenParams = (TOpenRemoteFileParams *)AOpenParams;
  2239. assert(OpenParams);
  2240. TFileOperationProgressType * OperationProgress = OpenParams->OperationProgress;
  2241. TSFTPPacket OpenRequest;
  2242. int OpenType;
  2243. bool Confirmed = false;
  2244. bool Success = false;
  2245. do
  2246. {
  2247. try
  2248. {
  2249. OpenType = 0;
  2250. OpenRequest.ChangeType(SSH_FXP_OPEN);
  2251. if (FTerminal->Configuration->ConfirmOverwriting &&
  2252. !Confirmed && !OperationProgress->YesToAll && !OpenParams->Resume &&
  2253. !(OpenParams->Params & cpNoConfirmation) &&
  2254. (OpenParams->OverwriteMode == omOverwrite))
  2255. {
  2256. OpenType |= SSH_FXF_EXCL;
  2257. }
  2258. if (!OpenParams->Resume && (OpenParams->OverwriteMode == omOverwrite))
  2259. {
  2260. OpenType |= SSH_FXF_TRUNC;
  2261. }
  2262. if ((FVersion >= 4) && OpenParams->OperationProgress->AsciiTransfer)
  2263. {
  2264. OpenType |= SSH_FXF_TEXT;
  2265. }
  2266. OpenRequest.AddString(OpenParams->RemoteFileName);
  2267. OpenRequest.AddCardinal(SSH_FXF_WRITE | SSH_FXF_CREAT | OpenType );
  2268. OpenRequest.AddCardinal(
  2269. OpenParams->CopyParam->PreserveRights ? SSH_FILEXFER_ATTR_PERMISSIONS : 0);
  2270. if (FVersion >= 4)
  2271. {
  2272. OpenRequest.AddByte(SSH_FILEXFER_TYPE_REGULAR);
  2273. }
  2274. if (OpenParams->CopyParam->PreserveRights)
  2275. {
  2276. OpenRequest.AddCardinal(
  2277. OpenParams->CopyParam->RemoteFileRights(OpenParams->LocalFileAttrs));
  2278. }
  2279. SendPacketAndReceiveResponse(&OpenRequest, &OpenRequest, SSH_FXP_HANDLE);
  2280. OpenParams->RemoteFileHandle = OpenRequest.GetString();
  2281. Success = true;
  2282. }
  2283. catch(...)
  2284. {
  2285. if (!Confirmed && (OpenType & SSH_FXF_EXCL) && FTerminal->Active)
  2286. {
  2287. bool TargetBiggerThanSource;
  2288. bool ThrowOriginal = false;
  2289. // When exclusive opening of file fails, try to detect if file exists.
  2290. // When file does not exist, failure was probably caused by 'permission denied'
  2291. // or similar error. In this case throw original exception.
  2292. try
  2293. {
  2294. TRemoteFile * File;
  2295. AnsiString RealFileName = LocalCanonify(OpenParams->RemoteFileName);
  2296. ReadFile(RealFileName, File);
  2297. OpenParams->DestFileSize = File->Size;
  2298. if (OpenParams->FileParams != NULL)
  2299. {
  2300. OpenParams->FileParams->DestTimestamp = File->Modification;
  2301. OpenParams->FileParams->DestSize = OpenParams->DestFileSize;
  2302. }
  2303. TargetBiggerThanSource = File->Size >= OperationProgress->LocalSize;
  2304. // file exists (otherwise exception was thrown)
  2305. assert(File);
  2306. SAFE_DESTROY(File);
  2307. }
  2308. catch(...)
  2309. {
  2310. if (!FTerminal->Active)
  2311. {
  2312. throw;
  2313. }
  2314. else
  2315. {
  2316. ThrowOriginal = true;
  2317. }
  2318. }
  2319. if (ThrowOriginal)
  2320. {
  2321. throw;
  2322. }
  2323. // confirmation duplicated in SFTPSource for resumable file transfers.
  2324. SFTPConfirmOverwrite(UnixExtractFileName(OpenParams->RemoteFileName),
  2325. TargetBiggerThanSource, OperationProgress, OpenParams->OverwriteMode,
  2326. OpenParams->FileParams);
  2327. Confirmed = true;
  2328. }
  2329. else
  2330. {
  2331. throw;
  2332. }
  2333. }
  2334. }
  2335. while (!Success);
  2336. return 0;
  2337. }
  2338. //---------------------------------------------------------------------------
  2339. void __fastcall TSFTPFileSystem::SFTPCloseRemote(const AnsiString Handle,
  2340. const AnsiString FileName, TFileOperationProgressType * OperationProgress,
  2341. bool TransferFinished)
  2342. {
  2343. // Moving this out of SFTPSource() fixed external exception 0xC0000029 error
  2344. FILE_OPERATION_LOOP(FMTLOAD(SFTP_CLOSE_FILE_ERROR, (FileName)),
  2345. try
  2346. {
  2347. TSFTPPacket CloseRequest(SSH_FXP_CLOSE);
  2348. CloseRequest.AddString(Handle);
  2349. SendPacketAndReceiveResponse(&CloseRequest, NULL, SSH_FXP_STATUS);
  2350. }
  2351. catch(...)
  2352. {
  2353. if (!FTerminal->Active || TransferFinished)
  2354. {
  2355. throw;
  2356. }
  2357. }
  2358. );
  2359. }
  2360. //---------------------------------------------------------------------------
  2361. void __fastcall TSFTPFileSystem::SFTPDirectorySource(const AnsiString DirectoryName,
  2362. const AnsiString TargetDir, int Attrs, const TCopyParamType * CopyParam,
  2363. int Params, TFileOperationProgressType * OperationProgress, int Level)
  2364. {
  2365. AnsiString DestDirectoryName = CopyParam->ChangeFileName(
  2366. ExtractFileName(ExcludeTrailingBackslash(DirectoryName)), osLocal, Level == 0);
  2367. AnsiString DestFullName = UnixIncludeTrailingBackslash(TargetDir + DestDirectoryName);
  2368. OperationProgress->SetFile(DirectoryName);
  2369. bool CreateDir = false;
  2370. try
  2371. {
  2372. TryOpenDirectory(DestFullName);
  2373. }
  2374. catch(...)
  2375. {
  2376. if (FTerminal->Active)
  2377. {
  2378. // opening directory failed, it probably does not exists, try to
  2379. // create it
  2380. CreateDir = true;
  2381. }
  2382. else
  2383. {
  2384. throw;
  2385. }
  2386. }
  2387. if (CreateDir)
  2388. {
  2389. TRemoteProperties Properties;
  2390. if (CopyParam->PreserveRights)
  2391. {
  2392. Properties.Valid = TValidProperties() << vpRights;
  2393. Properties.Rights = CopyParam->RemoteFileRights(Attrs);
  2394. }
  2395. FTerminal->CreateDirectory(DestFullName, &Properties);
  2396. }
  2397. int FindAttrs = faReadOnly | faHidden | faSysFile | faDirectory | faArchive;
  2398. TSearchRec SearchRec;
  2399. bool FindOK;
  2400. FILE_OPERATION_LOOP (FMTLOAD(LIST_DIR_ERROR, (DirectoryName)),
  2401. FindOK = (bool)(FindFirst(DirectoryName + "*.*",
  2402. FindAttrs, SearchRec) == 0);
  2403. );
  2404. while (FindOK && !OperationProgress->Cancel)
  2405. {
  2406. AnsiString FileName = DirectoryName + SearchRec.Name;
  2407. try
  2408. {
  2409. if ((SearchRec.Name != ".") && (SearchRec.Name != ".."))
  2410. {
  2411. SFTPSource(FileName, DestFullName, CopyParam, Params, OperationProgress,
  2412. Level + 1);
  2413. }
  2414. }
  2415. catch (EScpSkipFile &E)
  2416. {
  2417. // If ESkipFile occurs, just log it and continue with next file
  2418. SUSPEND_OPERATION (
  2419. // here a message to user was displayed, which was not appropriate
  2420. // when user refused to overwrite the file in subdirectory.
  2421. // hopefuly it won't be missing in other situations.
  2422. if (!FTerminal->HandleException(&E)) throw;
  2423. );
  2424. }
  2425. FILE_OPERATION_LOOP (FMTLOAD(LIST_DIR_ERROR, (DirectoryName)),
  2426. FindOK = (FindNext(SearchRec) == 0);
  2427. );
  2428. };
  2429. FindClose(SearchRec);
  2430. /* TODO : Delete also read-only directories. */
  2431. /* TODO : Show error message on failure. */
  2432. if ((Params & cpDelete) && !OperationProgress->Cancel) RemoveDir(DirectoryName);
  2433. }
  2434. //---------------------------------------------------------------------------
  2435. void __fastcall TSFTPFileSystem::CopyToLocal(TStrings * FilesToCopy,
  2436. const AnsiString TargetDir, const TCopyParamType * CopyParam,
  2437. int Params, TFileOperationProgressType * OperationProgress,
  2438. bool & DisconnectWhenComplete)
  2439. {
  2440. assert(FilesToCopy && OperationProgress);
  2441. AnsiString FileName, FileNameOnly;
  2442. AnsiString FullTargetDir = IncludeTrailingBackslash(TargetDir);
  2443. const TRemoteFile * File;
  2444. bool Success;
  2445. int Index = 0;
  2446. while (Index < FilesToCopy->Count && !OperationProgress->Cancel)
  2447. {
  2448. Success = false;
  2449. FileName = FilesToCopy->Strings[Index];
  2450. FileNameOnly = UnixExtractFileName(FileName);
  2451. File = (TRemoteFile *)FilesToCopy->Objects[Index];
  2452. assert(!FAvoidBusy);
  2453. FAvoidBusy = true;
  2454. try
  2455. {
  2456. try
  2457. {
  2458. SFTPSink(LocalCanonify(FileName), File, FullTargetDir, CopyParam,
  2459. Params, OperationProgress, 0);
  2460. Success = true;
  2461. }
  2462. catch(EScpSkipFile & E)
  2463. {
  2464. SUSPEND_OPERATION (
  2465. if (!FTerminal->HandleException(&E)) throw;
  2466. );
  2467. }
  2468. catch(...)
  2469. {
  2470. throw;
  2471. }
  2472. }
  2473. __finally
  2474. {
  2475. FAvoidBusy = false;
  2476. OperationProgress->Finish(FileNameOnly, Success, DisconnectWhenComplete);
  2477. }
  2478. Index++;
  2479. }
  2480. }
  2481. //---------------------------------------------------------------------------
  2482. void __fastcall TSFTPFileSystem::SFTPSink(const AnsiString FileName,
  2483. const TRemoteFile * File, const AnsiString TargetDir,
  2484. const TCopyParamType * CopyParam, int Params,
  2485. TFileOperationProgressType * OperationProgress, int Level)
  2486. {
  2487. assert(File);
  2488. FTerminal->LogEvent(FORMAT("File: \"%s\"", (FileName)));
  2489. AnsiString OnlyFileName = UnixExtractFileName(FileName);
  2490. OperationProgress->SetFile(OnlyFileName);
  2491. AnsiString DestFileName = CopyParam->ChangeFileName(OnlyFileName,
  2492. osRemote, Level == 0);
  2493. AnsiString DestFullName = TargetDir + DestFileName;
  2494. if (File->IsDirectory)
  2495. {
  2496. if (!File->IsSymLink)
  2497. {
  2498. FILE_OPERATION_LOOP (FMTLOAD(NOT_DIRECTORY_ERROR, (DestFullName)),
  2499. int Attrs = FileGetAttr(DestFullName);
  2500. if ((Attrs & faDirectory) == 0) EXCEPTION;
  2501. );
  2502. FILE_OPERATION_LOOP (FMTLOAD(CREATE_DIR_ERROR, (DestFullName)),
  2503. if (!ForceDirectories(DestFullName)) EXCEPTION;
  2504. );
  2505. TSinkFileParams SinkFileParams;
  2506. SinkFileParams.TargetDir = IncludeTrailingBackslash(DestFullName);
  2507. SinkFileParams.CopyParam = CopyParam;
  2508. SinkFileParams.Params = Params;
  2509. SinkFileParams.OperationProgress = OperationProgress;
  2510. SinkFileParams.Skipped = false;
  2511. SinkFileParams.Level = Level + 1;
  2512. FTerminal->ProcessDirectory(FileName, SFTPSinkFile, &SinkFileParams);
  2513. // Do not delete directory if some of its files were skip.
  2514. // Throw "skip file" for the directory to avoid attempt to deletion
  2515. // of any parent directory
  2516. if ((Params & cpDelete) && SinkFileParams.Skipped)
  2517. {
  2518. THROW_SKIP_FILE_NULL;
  2519. }
  2520. }
  2521. else
  2522. {
  2523. // file is symlink to directory, currently do nothing, but it should be
  2524. // reported to user
  2525. }
  2526. }
  2527. else
  2528. {
  2529. FTerminal->LogEvent(FORMAT("Copying \"%s\" to local directory started.", (FileName)));
  2530. AnsiString DestPartinalFullName;
  2531. bool ResumeAllowed;
  2532. bool ResumeTransfer = false;
  2533. __int64 ResumeOffset;
  2534. // Will we use ASCII of BINARY file tranfer?
  2535. OperationProgress->SetAsciiTransfer(CopyParam->UseAsciiTransfer(DestFileName));
  2536. FTerminal->LogEvent(AnsiString((OperationProgress->AsciiTransfer ? "Ascii" : "Binary")) +
  2537. " transfer mode selected.");
  2538. // Suppose same data size to transfer as to write
  2539. // (not true with ASCII transfer)
  2540. OperationProgress->SetTransferSize(File->Size);
  2541. OperationProgress->SetLocalSize(OperationProgress->TransferSize);
  2542. // resume has no sense for drag&drop downloads, because files are downloaded
  2543. // to temp directory, but anyway TTerminal does know this, so the condition
  2544. // placement is currently wrong.
  2545. ResumeAllowed = ((Params & cpDragDrop) == 0) &&
  2546. !OperationProgress->AsciiTransfer &&
  2547. CopyParam->AllowResume(OperationProgress->TransferSize);
  2548. OperationProgress->SetResumeStatus(ResumeAllowed ? rsEnabled : rsDisabled);
  2549. int Attrs;
  2550. FILE_OPERATION_LOOP (FMTLOAD(NOT_FILE_ERROR, (DestFullName)),
  2551. Attrs = FileGetAttr(DestFullName);
  2552. if ((Attrs >= 0) && (Attrs & faDirectory)) EXCEPTION;
  2553. );
  2554. OperationProgress->TransferingFile = false; // not set with SFTP protocol
  2555. HANDLE LocalHandle = NULL;
  2556. TStream * FileStream = NULL;
  2557. bool DeleteLocalFile = false;
  2558. AnsiString RemoteHandle;
  2559. AnsiString LocalFileName = DestFullName;
  2560. try
  2561. {
  2562. if (ResumeAllowed)
  2563. {
  2564. DestPartinalFullName = DestFullName + FTerminal->Configuration->PartialExt;
  2565. LocalFileName = DestPartinalFullName;
  2566. FTerminal->LogEvent("Checking existence of partially transfered file.");
  2567. if (FileExists(DestPartinalFullName))
  2568. {
  2569. FTerminal->OpenLocalFile(DestPartinalFullName, GENERIC_WRITE,
  2570. NULL, &LocalHandle, NULL, NULL, NULL, &ResumeOffset);
  2571. ResumeTransfer = SFTPConfirmResume(DestFileName,
  2572. ResumeOffset > OperationProgress->TransferSize, OperationProgress);
  2573. if (!ResumeTransfer)
  2574. {
  2575. CloseHandle(LocalHandle);
  2576. LocalHandle = NULL;
  2577. Sysutils::DeleteFile(DestPartinalFullName);
  2578. }
  2579. else
  2580. {
  2581. FTerminal->LogEvent("Resuming file transfer.");
  2582. FileSeek((THandle)LocalHandle, ResumeOffset, 0);
  2583. OperationProgress->AddResumed(ResumeOffset);
  2584. }
  2585. }
  2586. }
  2587. if ((Attrs >= 0) && FTerminal->Configuration->ConfirmOverwriting &&
  2588. !OperationProgress->YesToAll && !ResumeTransfer &&
  2589. !(Params & cpNoConfirmation))
  2590. {
  2591. __int64 DestFileSize;
  2592. unsigned long MTime;
  2593. FTerminal->OpenLocalFile(DestFullName, GENERIC_WRITE,
  2594. NULL, &LocalHandle, NULL, &MTime, NULL, &DestFileSize, false);
  2595. FTerminal->LogEvent("Checking existence of file.");
  2596. TSFTPOverwriteMode OverwriteMode;
  2597. TOverwriteFileParams FileParams;
  2598. FileParams.SourceSize = OperationProgress->TransferSize;
  2599. FileParams.SourceTimestamp = File->Modification;
  2600. FileParams.DestTimestamp = UnixToDateTime(MTime);
  2601. FileParams.DestSize = DestFileSize;
  2602. SFTPConfirmOverwrite(DestFileName, (DestFileSize >= OperationProgress->TransferSize),
  2603. OperationProgress, OverwriteMode, &FileParams);
  2604. if (OverwriteMode == omOverwrite)
  2605. {
  2606. // is NULL when overwritting read-only file
  2607. if (LocalHandle)
  2608. {
  2609. CloseHandle(LocalHandle);
  2610. LocalHandle = NULL;
  2611. }
  2612. }
  2613. else
  2614. {
  2615. // is NULL when overwritting read-only file, so following will
  2616. // probably fail anyway
  2617. if (LocalHandle == NULL)
  2618. {
  2619. FTerminal->OpenLocalFile(DestFullName, GENERIC_WRITE,
  2620. NULL, &LocalHandle, NULL, NULL, NULL, NULL);
  2621. }
  2622. ResumeAllowed = false;
  2623. FileSeek((THandle)LocalHandle, DestFileSize, 0);
  2624. if (OverwriteMode == omAppend)
  2625. {
  2626. FTerminal->LogEvent("Appending to file.");
  2627. }
  2628. else
  2629. {
  2630. FTerminal->LogEvent("Resuming file transfer (append style).");
  2631. assert(OverwriteMode == omResume);
  2632. OperationProgress->AddResumed(DestFileSize);
  2633. }
  2634. }
  2635. }
  2636. // if not already opened (resume, append...), create new empty file
  2637. if (!LocalHandle)
  2638. {
  2639. if (!FTerminal->CreateLocalFile(LocalFileName, OperationProgress, &LocalHandle))
  2640. {
  2641. THROW_SKIP_FILE_NULL;
  2642. }
  2643. }
  2644. assert(LocalHandle);
  2645. DeleteLocalFile = true;
  2646. FTerminal->LogEvent("Opening remote file.");
  2647. FILE_OPERATION_LOOP (FMTLOAD(SFTP_OPEN_FILE_ERROR, (FileName)),
  2648. TSFTPPacket Packet;
  2649. Packet.ChangeType(SSH_FXP_OPEN);
  2650. Packet.AddString(FileName);
  2651. int OpenType = SSH_FXF_READ;
  2652. if ((FVersion >= 4) && OperationProgress->AsciiTransfer)
  2653. {
  2654. OpenType |= SSH_FXF_TEXT;
  2655. }
  2656. Packet.AddCardinal(OpenType);
  2657. Packet.AddCardinal(0); // no attrs
  2658. if (FVersion >= 4)
  2659. {
  2660. Packet.AddByte(SSH_FILEXFER_TYPE_REGULAR);
  2661. }
  2662. SendPacketAndReceiveResponse(&Packet, &Packet, SSH_FXP_HANDLE);
  2663. RemoteHandle = Packet.GetString();
  2664. );
  2665. FileStream = new THandleStream((THandle)LocalHandle);
  2666. unsigned long BlockSize = MaxTransferBlockSize(
  2667. 4 + 4 + RemoteHandle.Length() + 8);
  2668. // at end of this block queue is disposed
  2669. {
  2670. TSFTPDownloadQueue Queue(this);
  2671. TSFTPPacket DataPacket;
  2672. int QueueLen = int(File->Size / BlockSize) + 1;
  2673. if (QueueLen > FTerminal->SessionData->SFTPDownloadQueue)
  2674. {
  2675. QueueLen = FTerminal->SessionData->SFTPDownloadQueue;
  2676. }
  2677. Queue.Init(QueueLen, RemoteHandle, BlockSize,
  2678. OperationProgress->TransferedSize);
  2679. bool Eof = false;
  2680. bool PrevIncomplete = false;
  2681. int GapFillCount = 0;
  2682. int GapCount = 0;
  2683. unsigned long Missing = 0;
  2684. unsigned long DataLen = 0;
  2685. while (!Eof)
  2686. {
  2687. if (Missing > 0)
  2688. {
  2689. Queue.InitFillGapRequest(OperationProgress->TransferedSize, Missing,
  2690. &DataPacket);
  2691. GapFillCount++;
  2692. SendPacketAndReceiveResponse(&DataPacket, &DataPacket,
  2693. SSH_FXP_DATA, asEOF);
  2694. }
  2695. else
  2696. {
  2697. Queue.ReceivePacket(&DataPacket, SSH_FXP_DATA, asEOF);
  2698. }
  2699. if (DataPacket.Type == SSH_FXP_STATUS)
  2700. {
  2701. // must be SSH_FX_EOF, any other status packet would raise exception
  2702. Eof = true;
  2703. }
  2704. if (!Eof)
  2705. {
  2706. if ((Missing == 0) && PrevIncomplete)
  2707. {
  2708. // This can happen only if last request returned less bytes
  2709. // than expected, but exacly number of bytes missing to last
  2710. // known file size, but actually EOF was not reached.
  2711. // Can happen only when filesize has changed since directory
  2712. // listing and server returns less bytes than requested and
  2713. // fiel has some special file size.
  2714. FTerminal->LogEvent(FORMAT(
  2715. "Received incomplete data packet before end of file, "
  2716. "offset: %s, size: %d, requested: %d",
  2717. (IntToStr(OperationProgress->TransferedSize), int(DataLen),
  2718. int(BlockSize))));
  2719. FTerminal->TerminalError(NULL, LoadStr(SFTP_INCOMPLETE_BEFORE_EOF));
  2720. }
  2721. // Buffer for one block of data
  2722. TFileBuffer BlockBuf;
  2723. DataLen = DataPacket.GetCardinal();
  2724. PrevIncomplete = false;
  2725. if (Missing > 0)
  2726. {
  2727. assert(DataLen <= Missing);
  2728. Missing -= DataLen;
  2729. }
  2730. else if (DataLen < BlockSize)
  2731. {
  2732. if (OperationProgress->TransferedSize + DataLen !=
  2733. OperationProgress->TransferSize)
  2734. {
  2735. // with native text transfer mode (SFTP>=4), do not bother about
  2736. // getting less than requested, read offset is ignored anyway
  2737. if ((FVersion < 4) || !OperationProgress->AsciiTransfer)
  2738. {
  2739. GapCount++;
  2740. Missing = BlockSize - DataLen;
  2741. }
  2742. }
  2743. else
  2744. {
  2745. PrevIncomplete = true;
  2746. }
  2747. }
  2748. assert(DataLen <= BlockSize);
  2749. BlockBuf.Insert(0, DataPacket.NextData, DataLen);
  2750. OperationProgress->AddTransfered(DataLen);
  2751. if (OperationProgress->AsciiTransfer)
  2752. {
  2753. assert(!ResumeTransfer && !ResumeAllowed);
  2754. unsigned int PrevBlockSize = BlockBuf.Size;
  2755. BlockBuf.Convert(GetEOL(), FTerminal->Configuration->LocalEOLType, 0);
  2756. OperationProgress->SetLocalSize(
  2757. OperationProgress->LocalSize - PrevBlockSize + BlockBuf.Size);
  2758. }
  2759. FILE_OPERATION_LOOP (FMTLOAD(WRITE_ERROR, (LocalFileName)),
  2760. BlockBuf.WriteToStream(FileStream, BlockBuf.Size);
  2761. );
  2762. OperationProgress->AddLocalyUsed(BlockBuf.Size);
  2763. if (OperationProgress->Cancel == csCancel)
  2764. {
  2765. Abort();
  2766. }
  2767. }
  2768. };
  2769. if (GapCount > 0)
  2770. {
  2771. FTerminal->LogEvent(FORMAT(
  2772. "%d requests to fill %d data gaps were issued.",
  2773. (GapFillCount, GapCount)));
  2774. }
  2775. }
  2776. if (CopyParam->PreserveTime)
  2777. {
  2778. FILETIME AcTime = DateTimeToFileTime(File->LastAccess);
  2779. FILETIME WrTime = DateTimeToFileTime(File->Modification);
  2780. SetFileTime(LocalHandle, NULL, &AcTime, &WrTime);
  2781. }
  2782. CloseHandle(LocalHandle);
  2783. LocalHandle = NULL;
  2784. if (ResumeAllowed)
  2785. {
  2786. FILE_OPERATION_LOOP(FMTLOAD(RENAME_AFTER_RESUME_ERROR,
  2787. (ExtractFileName(DestPartinalFullName), DestFileName)),
  2788. if (FileExists(DestFullName))
  2789. {
  2790. if (!Sysutils::DeleteFile(DestFullName)) EXCEPTION;
  2791. }
  2792. if (!Sysutils::RenameFile(DestPartinalFullName, DestFullName))
  2793. {
  2794. EXCEPTION;
  2795. }
  2796. );
  2797. }
  2798. DeleteLocalFile = false;
  2799. if (Attrs == -1)
  2800. {
  2801. Attrs = faArchive;
  2802. }
  2803. int NewAttrs = CopyParam->LocalFileAttrs(*File->Rights);
  2804. if ((NewAttrs & Attrs) != NewAttrs)
  2805. {
  2806. FILE_OPERATION_LOOP (FMTLOAD(CANT_SET_ATTRS, (DestFullName)),
  2807. FileSetAttr(DestFullName, Attrs | NewAttrs);
  2808. );
  2809. }
  2810. }
  2811. __finally
  2812. {
  2813. if (LocalHandle) CloseHandle(LocalHandle);
  2814. if (FileStream) delete FileStream;
  2815. if (DeleteLocalFile && (!ResumeAllowed || OperationProgress->LocalyUsed == 0))
  2816. {
  2817. Sysutils::DeleteFile(LocalFileName);
  2818. }
  2819. if (FTerminal->Active && !RemoteHandle.IsEmpty())
  2820. {
  2821. FILE_OPERATION_LOOP(FMTLOAD(SFTP_CLOSE_FILE_ERROR, (DestFileName)),
  2822. TSFTPPacket CloseRequest(SSH_FXP_CLOSE);
  2823. CloseRequest.AddString(RemoteHandle);
  2824. SendPacketAndReceiveResponse(&CloseRequest, NULL, SSH_FXP_STATUS);
  2825. );
  2826. }
  2827. }
  2828. }
  2829. if (Params & cpDelete)
  2830. {
  2831. // If file is directory, do not delete it recursively, because it should be
  2832. // empty already. If not, it should not be deleted (some files were
  2833. // skipped or some new files were copied to it, while we were downloading)
  2834. bool Recursive = false;
  2835. FTerminal->DeleteFile(FileName, File, &Recursive);
  2836. }
  2837. }
  2838. //---------------------------------------------------------------------------
  2839. void __fastcall TSFTPFileSystem::SFTPSinkFile(AnsiString FileName,
  2840. const TRemoteFile * File, void * Param)
  2841. {
  2842. TSinkFileParams * Params = (TSinkFileParams *)Param;
  2843. assert(Params->OperationProgress);
  2844. try
  2845. {
  2846. SFTPSink(FileName, File, Params->TargetDir, Params->CopyParam,
  2847. Params->Params, Params->OperationProgress, Params->Level);
  2848. }
  2849. catch(EScpSkipFile & E)
  2850. {
  2851. TFileOperationProgressType * OperationProgress = Params->OperationProgress;
  2852. Params->Skipped = true;
  2853. SUSPEND_OPERATION (
  2854. if (!FTerminal->HandleException(&E)) throw;
  2855. );
  2856. if (OperationProgress->Cancel)
  2857. {
  2858. Abort();
  2859. }
  2860. }
  2861. }