SftpFileSystem.cpp 105 KB

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