SFTP.js 104 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778
  1. 'use strict';
  2. const EventEmitter = require('events');
  3. const fs = require('fs');
  4. const { constants } = fs;
  5. const {
  6. Readable: ReadableStream,
  7. Writable: WritableStream
  8. } = require('stream');
  9. const { inherits, isDate } = require('util');
  10. const FastBuffer = Buffer[Symbol.species];
  11. const {
  12. bufferCopy,
  13. bufferSlice,
  14. makeBufferParser,
  15. writeUInt32BE,
  16. } = require('./utils.js');
  17. const ATTR = {
  18. SIZE: 0x00000001,
  19. UIDGID: 0x00000002,
  20. PERMISSIONS: 0x00000004,
  21. ACMODTIME: 0x00000008,
  22. EXTENDED: 0x80000000,
  23. };
  24. // Large enough to store all possible attributes
  25. const ATTRS_BUF = Buffer.alloc(28);
  26. const STATUS_CODE = {
  27. OK: 0,
  28. EOF: 1,
  29. NO_SUCH_FILE: 2,
  30. PERMISSION_DENIED: 3,
  31. FAILURE: 4,
  32. BAD_MESSAGE: 5,
  33. NO_CONNECTION: 6,
  34. CONNECTION_LOST: 7,
  35. OP_UNSUPPORTED: 8
  36. };
  37. const VALID_STATUS_CODES = new Map(
  38. Object.values(STATUS_CODE).map((n) => [n, 1])
  39. );
  40. const STATUS_CODE_STR = {
  41. [STATUS_CODE.OK]: 'No error',
  42. [STATUS_CODE.EOF]: 'End of file',
  43. [STATUS_CODE.NO_SUCH_FILE]: 'No such file or directory',
  44. [STATUS_CODE.PERMISSION_DENIED]: 'Permission denied',
  45. [STATUS_CODE.FAILURE]: 'Failure',
  46. [STATUS_CODE.BAD_MESSAGE]: 'Bad message',
  47. [STATUS_CODE.NO_CONNECTION]: 'No connection',
  48. [STATUS_CODE.CONNECTION_LOST]: 'Connection lost',
  49. [STATUS_CODE.OP_UNSUPPORTED]: 'Operation unsupported',
  50. };
  51. const REQUEST = {
  52. INIT: 1,
  53. OPEN: 3,
  54. CLOSE: 4,
  55. READ: 5,
  56. WRITE: 6,
  57. LSTAT: 7,
  58. FSTAT: 8,
  59. SETSTAT: 9,
  60. FSETSTAT: 10,
  61. OPENDIR: 11,
  62. READDIR: 12,
  63. REMOVE: 13,
  64. MKDIR: 14,
  65. RMDIR: 15,
  66. REALPATH: 16,
  67. STAT: 17,
  68. RENAME: 18,
  69. READLINK: 19,
  70. SYMLINK: 20,
  71. EXTENDED: 200
  72. };
  73. const RESPONSE = {
  74. VERSION: 2,
  75. STATUS: 101,
  76. HANDLE: 102,
  77. DATA: 103,
  78. NAME: 104,
  79. ATTRS: 105,
  80. EXTENDED: 201
  81. };
  82. const OPEN_MODE = {
  83. READ: 0x00000001,
  84. WRITE: 0x00000002,
  85. APPEND: 0x00000004,
  86. CREAT: 0x00000008,
  87. TRUNC: 0x00000010,
  88. EXCL: 0x00000020
  89. };
  90. const PKT_RW_OVERHEAD = 2 * 1024;
  91. const MAX_REQID = 2 ** 32 - 1;
  92. const CLIENT_VERSION_BUFFER = Buffer.from([
  93. 0, 0, 0, 5 /* length */,
  94. REQUEST.INIT,
  95. 0, 0, 0, 3 /* version */
  96. ]);
  97. const SERVER_VERSION_BUFFER = Buffer.from([
  98. 0, 0, 0, 5 /* length */,
  99. RESPONSE.VERSION,
  100. 0, 0, 0, 3 /* version */
  101. ]);
  102. const RE_OPENSSH = /^SSH-2.0-(?:OpenSSH|dropbear)/;
  103. const OPENSSH_MAX_PKT_LEN = 256 * 1024;
  104. const bufferParser = makeBufferParser();
  105. const fakeStderr = {
  106. readable: false,
  107. writable: false,
  108. push: (data) => {},
  109. once: () => {},
  110. on: () => {},
  111. emit: () => {},
  112. end: () => {},
  113. };
  114. function noop() {}
  115. // Emulates enough of `Channel` to be able to be used as a drop-in replacement
  116. // in order to process incoming data with as little overhead as possible
  117. class SFTP extends EventEmitter {
  118. constructor(client, chanInfo, cfg) {
  119. super();
  120. if (typeof cfg !== 'object' || !cfg)
  121. cfg = {};
  122. const remoteIdentRaw = client._protocol._remoteIdentRaw;
  123. this.server = !!cfg.server;
  124. this._debug = (typeof cfg.debug === 'function' ? cfg.debug : undefined);
  125. this._isOpenSSH = (remoteIdentRaw && RE_OPENSSH.test(remoteIdentRaw));
  126. this._version = -1;
  127. this._extensions = {};
  128. this._biOpt = cfg.biOpt;
  129. this._pktLenBytes = 0;
  130. this._pktLen = 0;
  131. this._pktPos = 0;
  132. this._pktType = 0;
  133. this._pktData = undefined;
  134. this._writeReqid = -1;
  135. this._requests = {};
  136. this._maxInPktLen = OPENSSH_MAX_PKT_LEN;
  137. this._maxOutPktLen = 34000;
  138. this._maxReadLen =
  139. (this._isOpenSSH ? OPENSSH_MAX_PKT_LEN : 34000) - PKT_RW_OVERHEAD;
  140. this._maxWriteLen =
  141. (this._isOpenSSH ? OPENSSH_MAX_PKT_LEN : 34000) - PKT_RW_OVERHEAD;
  142. this.maxOpenHandles = undefined;
  143. // Channel compatibility
  144. this._client = client;
  145. this._protocol = client._protocol;
  146. this._callbacks = [];
  147. this._hasX11 = false;
  148. this._exit = {
  149. code: undefined,
  150. signal: undefined,
  151. dump: undefined,
  152. desc: undefined,
  153. };
  154. this._waitWindow = false; // SSH-level backpressure
  155. this._chunkcb = undefined;
  156. this._buffer = [];
  157. this.type = chanInfo.type;
  158. this.subtype = undefined;
  159. this.incoming = chanInfo.incoming;
  160. this.outgoing = chanInfo.outgoing;
  161. this.stderr = fakeStderr;
  162. this.readable = true;
  163. }
  164. // This handles incoming data to parse
  165. push(data) {
  166. if (data === null) {
  167. cleanupRequests(this);
  168. if (!this.readable)
  169. return;
  170. // No more incoming data from the remote side
  171. this.readable = false;
  172. this.emit('end');
  173. return;
  174. }
  175. /*
  176. uint32 length
  177. byte type
  178. byte[length - 1] data payload
  179. */
  180. let p = 0;
  181. while (p < data.length) {
  182. if (this._pktLenBytes < 4) {
  183. let nb = Math.min(4 - this._pktLenBytes, data.length - p);
  184. this._pktLenBytes += nb;
  185. while (nb--)
  186. this._pktLen = (this._pktLen << 8) + data[p++];
  187. if (this._pktLenBytes < 4)
  188. return;
  189. if (this._pktLen === 0)
  190. return doFatalSFTPError(this, 'Invalid packet length');
  191. if (this._pktLen > this._maxInPktLen) {
  192. const max = this._maxInPktLen;
  193. return doFatalSFTPError(
  194. this,
  195. `Packet length ${this._pktLen} exceeds max length of ${max}`
  196. );
  197. }
  198. if (p >= data.length)
  199. return;
  200. }
  201. if (this._pktPos < this._pktLen) {
  202. const nb = Math.min(this._pktLen - this._pktPos, data.length - p);
  203. if (p !== 0 || nb !== data.length) {
  204. if (nb === this._pktLen) {
  205. this._pkt = new FastBuffer(data.buffer, data.byteOffset + p, nb);
  206. } else {
  207. if (!this._pkt)
  208. this._pkt = Buffer.allocUnsafe(this._pktLen);
  209. this._pkt.set(
  210. new Uint8Array(data.buffer, data.byteOffset + p, nb),
  211. this._pktPos
  212. );
  213. }
  214. } else if (nb === this._pktLen) {
  215. this._pkt = data;
  216. } else {
  217. if (!this._pkt)
  218. this._pkt = Buffer.allocUnsafe(this._pktLen);
  219. this._pkt.set(data, this._pktPos);
  220. }
  221. p += nb;
  222. this._pktPos += nb;
  223. if (this._pktPos < this._pktLen)
  224. return;
  225. }
  226. const type = this._pkt[0];
  227. const payload = this._pkt;
  228. // Prepare for next packet
  229. this._pktLen = 0;
  230. this._pktLenBytes = 0;
  231. this._pkt = undefined;
  232. this._pktPos = 0;
  233. const handler = (this.server
  234. ? SERVER_HANDLERS[type]
  235. : CLIENT_HANDLERS[type]);
  236. if (!handler)
  237. return doFatalSFTPError(this, `Unknown packet type ${type}`);
  238. if (this._version === -1) {
  239. if (this.server) {
  240. if (type !== REQUEST.INIT)
  241. return doFatalSFTPError(this, `Expected INIT packet, got ${type}`);
  242. } else if (type !== RESPONSE.VERSION) {
  243. return doFatalSFTPError(this, `Expected VERSION packet, got ${type}`);
  244. }
  245. }
  246. if (handler(this, payload) === false)
  247. return;
  248. }
  249. }
  250. end() {
  251. this.destroy();
  252. }
  253. destroy() {
  254. if (this.outgoing.state === 'open' || this.outgoing.state === 'eof') {
  255. this.outgoing.state = 'closing';
  256. this._protocol.channelClose(this.outgoing.id);
  257. }
  258. }
  259. _init() {
  260. this._init = noop;
  261. if (!this.server)
  262. sendOrBuffer(this, CLIENT_VERSION_BUFFER);
  263. }
  264. // ===========================================================================
  265. // Client-specific ===========================================================
  266. // ===========================================================================
  267. createReadStream(path, options) {
  268. if (this.server)
  269. throw new Error('Client-only method called in server mode');
  270. return new ReadStream(this, path, options);
  271. }
  272. createWriteStream(path, options) {
  273. if (this.server)
  274. throw new Error('Client-only method called in server mode');
  275. return new WriteStream(this, path, options);
  276. }
  277. open(path, flags_, attrs, cb) {
  278. if (this.server)
  279. throw new Error('Client-only method called in server mode');
  280. if (typeof attrs === 'function') {
  281. cb = attrs;
  282. attrs = undefined;
  283. }
  284. const flags = (typeof flags_ === 'number' ? flags_ : stringToFlags(flags_));
  285. if (flags === null)
  286. throw new Error(`Unknown flags string: ${flags_}`);
  287. let attrsFlags = 0;
  288. let attrsLen = 0;
  289. if (typeof attrs === 'string' || typeof attrs === 'number')
  290. attrs = { mode: attrs };
  291. if (typeof attrs === 'object' && attrs !== null) {
  292. attrs = attrsToBytes(attrs);
  293. attrsFlags = attrs.flags;
  294. attrsLen = attrs.nb;
  295. }
  296. /*
  297. uint32 id
  298. string filename
  299. uint32 pflags
  300. ATTRS attrs
  301. */
  302. const pathLen = Buffer.byteLength(path);
  303. let p = 9;
  304. const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + pathLen + 4 + 4 + attrsLen);
  305. writeUInt32BE(buf, buf.length - 4, 0);
  306. buf[4] = REQUEST.OPEN;
  307. const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID;
  308. writeUInt32BE(buf, reqid, 5);
  309. writeUInt32BE(buf, pathLen, p);
  310. buf.utf8Write(path, p += 4, pathLen);
  311. writeUInt32BE(buf, flags, p += pathLen);
  312. writeUInt32BE(buf, attrsFlags, p += 4);
  313. if (attrsLen) {
  314. p += 4;
  315. if (attrsLen === ATTRS_BUF.length)
  316. buf.set(ATTRS_BUF, p);
  317. else
  318. bufferCopy(ATTRS_BUF, buf, 0, attrsLen, p);
  319. p += attrsLen;
  320. }
  321. this._requests[reqid] = { cb };
  322. const isBuffered = sendOrBuffer(this, buf);
  323. this._debug && this._debug(
  324. `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} OPEN`
  325. );
  326. }
  327. close(handle, cb) {
  328. if (this.server)
  329. throw new Error('Client-only method called in server mode');
  330. if (!Buffer.isBuffer(handle))
  331. throw new Error('handle is not a Buffer');
  332. /*
  333. uint32 id
  334. string handle
  335. */
  336. const handleLen = handle.length;
  337. let p = 9;
  338. const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + handleLen);
  339. writeUInt32BE(buf, buf.length - 4, 0);
  340. buf[4] = REQUEST.CLOSE;
  341. const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID;
  342. writeUInt32BE(buf, reqid, 5);
  343. writeUInt32BE(buf, handleLen, p);
  344. buf.set(handle, p += 4);
  345. this._requests[reqid] = { cb };
  346. const isBuffered = sendOrBuffer(this, buf);
  347. this._debug && this._debug(
  348. `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} CLOSE`
  349. );
  350. }
  351. read(handle, buf, off, len, position, cb) {
  352. if (this.server)
  353. throw new Error('Client-only method called in server mode');
  354. if (!Buffer.isBuffer(handle))
  355. throw new Error('handle is not a Buffer');
  356. if (!Buffer.isBuffer(buf))
  357. throw new Error('buffer is not a Buffer');
  358. if (off >= buf.length)
  359. throw new Error('offset is out of bounds');
  360. if (off + len > buf.length)
  361. throw new Error('length extends beyond buffer');
  362. if (position === null)
  363. throw new Error('null position currently unsupported');
  364. read_(this, handle, buf, off, len, position, cb);
  365. }
  366. readData(handle, buf, off, len, position, cb) {
  367. // Backwards compatibility
  368. this.read(handle, buf, off, len, position, cb);
  369. }
  370. write(handle, buf, off, len, position, cb) {
  371. if (this.server)
  372. throw new Error('Client-only method called in server mode');
  373. if (!Buffer.isBuffer(handle))
  374. throw new Error('handle is not a Buffer');
  375. if (!Buffer.isBuffer(buf))
  376. throw new Error('buffer is not a Buffer');
  377. if (off > buf.length)
  378. throw new Error('offset is out of bounds');
  379. if (off + len > buf.length)
  380. throw new Error('length extends beyond buffer');
  381. if (position === null)
  382. throw new Error('null position currently unsupported');
  383. if (!len) {
  384. cb && process.nextTick(cb, undefined, 0);
  385. return;
  386. }
  387. const maxDataLen = this._maxWriteLen;
  388. const overflow = Math.max(len - maxDataLen, 0);
  389. const origPosition = position;
  390. if (overflow)
  391. len = maxDataLen;
  392. /*
  393. uint32 id
  394. string handle
  395. uint64 offset
  396. string data
  397. */
  398. const handleLen = handle.length;
  399. let p = 9;
  400. const out = Buffer.allocUnsafe(4 + 1 + 4 + 4 + handleLen + 8 + 4 + len);
  401. writeUInt32BE(out, out.length - 4, 0);
  402. out[4] = REQUEST.WRITE;
  403. const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID;
  404. writeUInt32BE(out, reqid, 5);
  405. writeUInt32BE(out, handleLen, p);
  406. out.set(handle, p += 4);
  407. p += handleLen;
  408. for (let i = 7; i >= 0; --i) {
  409. out[p + i] = position & 0xFF;
  410. position /= 256;
  411. }
  412. writeUInt32BE(out, len, p += 8);
  413. bufferCopy(buf, out, off, off + len, p += 4);
  414. this._requests[reqid] = {
  415. cb: (err) => {
  416. if (err) {
  417. if (typeof cb === 'function')
  418. cb(err);
  419. } else if (overflow) {
  420. this.write(handle,
  421. buf,
  422. off + len,
  423. overflow,
  424. origPosition + len,
  425. cb);
  426. } else if (typeof cb === 'function') {
  427. cb(undefined, off + len);
  428. }
  429. }
  430. };
  431. const isSent = sendOrBuffer(this, out);
  432. if (this._debug) {
  433. const how = (isSent ? 'Sent' : 'Buffered');
  434. this._debug(`SFTP: Outbound: ${how} WRITE (id:${reqid})`);
  435. }
  436. }
  437. writeData(handle, buf, off, len, position, cb) {
  438. // Backwards compatibility
  439. this.write(handle, buf, off, len, position, cb);
  440. }
  441. fastGet(remotePath, localPath, opts, cb) {
  442. if (this.server)
  443. throw new Error('Client-only method called in server mode');
  444. fastXfer(this, fs, remotePath, localPath, opts, cb);
  445. }
  446. fastPut(localPath, remotePath, opts, cb) {
  447. if (this.server)
  448. throw new Error('Client-only method called in server mode');
  449. fastXfer(fs, this, localPath, remotePath, opts, cb);
  450. }
  451. readFile(path, options, callback_) {
  452. if (this.server)
  453. throw new Error('Client-only method called in server mode');
  454. let callback;
  455. if (typeof callback_ === 'function') {
  456. callback = callback_;
  457. } else if (typeof options === 'function') {
  458. callback = options;
  459. options = undefined;
  460. }
  461. if (typeof options === 'string')
  462. options = { encoding: options, flag: 'r' };
  463. else if (!options)
  464. options = { encoding: null, flag: 'r' };
  465. else if (typeof options !== 'object')
  466. throw new TypeError('Bad arguments');
  467. const encoding = options.encoding;
  468. if (encoding && !Buffer.isEncoding(encoding))
  469. throw new Error(`Unknown encoding: ${encoding}`);
  470. // First stat the file, so we know the size.
  471. let size;
  472. let buffer; // Single buffer with file data
  473. let buffers; // List for when size is unknown
  474. let pos = 0;
  475. let handle;
  476. // SFTPv3 does not support using -1 for read position, so we have to track
  477. // read position manually
  478. let bytesRead = 0;
  479. const flag = options.flag || 'r';
  480. const read = () => {
  481. if (size === 0) {
  482. buffer = Buffer.allocUnsafe(8192);
  483. this.read(handle, buffer, 0, 8192, bytesRead, afterRead);
  484. } else {
  485. this.read(handle, buffer, pos, size - pos, bytesRead, afterRead);
  486. }
  487. };
  488. const afterRead = (er, nbytes) => {
  489. let eof;
  490. if (er) {
  491. eof = (er.code === STATUS_CODE.EOF);
  492. if (!eof) {
  493. return this.close(handle, () => {
  494. return callback && callback(er);
  495. });
  496. }
  497. } else {
  498. eof = false;
  499. }
  500. if (eof || (size === 0 && nbytes === 0))
  501. return close();
  502. bytesRead += nbytes;
  503. pos += nbytes;
  504. if (size !== 0) {
  505. if (pos === size)
  506. close();
  507. else
  508. read();
  509. } else {
  510. // Unknown size, just read until we don't get bytes.
  511. buffers.push(bufferSlice(buffer, 0, nbytes));
  512. read();
  513. }
  514. };
  515. afterRead._wantEOFError = true;
  516. const close = () => {
  517. this.close(handle, (er) => {
  518. if (size === 0) {
  519. // Collect the data into the buffers list.
  520. buffer = Buffer.concat(buffers, pos);
  521. } else if (pos < size) {
  522. buffer = bufferSlice(buffer, 0, pos);
  523. }
  524. if (encoding)
  525. buffer = buffer.toString(encoding);
  526. return callback && callback(er, buffer);
  527. });
  528. };
  529. this.open(path, flag, 0o666, (er, handle_) => {
  530. if (er)
  531. return callback && callback(er);
  532. handle = handle_;
  533. const tryStat = (er, st) => {
  534. if (er) {
  535. // Try stat() for sftp servers that may not support fstat() for
  536. // whatever reason
  537. this.stat(path, (er_, st_) => {
  538. if (er_) {
  539. return this.close(handle, () => {
  540. callback && callback(er);
  541. });
  542. }
  543. tryStat(null, st_);
  544. });
  545. return;
  546. }
  547. size = st.size || 0;
  548. if (size === 0) {
  549. // The kernel lies about many files.
  550. // Go ahead and try to read some bytes.
  551. buffers = [];
  552. return read();
  553. }
  554. buffer = Buffer.allocUnsafe(size);
  555. read();
  556. };
  557. this.fstat(handle, tryStat);
  558. });
  559. }
  560. writeFile(path, data, options, callback_) {
  561. if (this.server)
  562. throw new Error('Client-only method called in server mode');
  563. let callback;
  564. if (typeof callback_ === 'function') {
  565. callback = callback_;
  566. } else if (typeof options === 'function') {
  567. callback = options;
  568. options = undefined;
  569. }
  570. if (typeof options === 'string')
  571. options = { encoding: options, mode: 0o666, flag: 'w' };
  572. else if (!options)
  573. options = { encoding: 'utf8', mode: 0o666, flag: 'w' };
  574. else if (typeof options !== 'object')
  575. throw new TypeError('Bad arguments');
  576. if (options.encoding && !Buffer.isEncoding(options.encoding))
  577. throw new Error(`Unknown encoding: ${options.encoding}`);
  578. const flag = options.flag || 'w';
  579. this.open(path, flag, options.mode, (openErr, handle) => {
  580. if (openErr) {
  581. callback && callback(openErr);
  582. } else {
  583. const buffer = (Buffer.isBuffer(data)
  584. ? data
  585. : Buffer.from('' + data, options.encoding || 'utf8'));
  586. const position = (/a/.test(flag) ? null : 0);
  587. // SFTPv3 does not support the notion of 'current position'
  588. // (null position), so we just attempt to append to the end of the file
  589. // instead
  590. if (position === null) {
  591. const tryStat = (er, st) => {
  592. if (er) {
  593. // Try stat() for sftp servers that may not support fstat() for
  594. // whatever reason
  595. this.stat(path, (er_, st_) => {
  596. if (er_) {
  597. return this.close(handle, () => {
  598. callback && callback(er);
  599. });
  600. }
  601. tryStat(null, st_);
  602. });
  603. return;
  604. }
  605. writeAll(this, handle, buffer, 0, buffer.length, st.size, callback);
  606. };
  607. this.fstat(handle, tryStat);
  608. return;
  609. }
  610. writeAll(this, handle, buffer, 0, buffer.length, position, callback);
  611. }
  612. });
  613. }
  614. appendFile(path, data, options, callback_) {
  615. if (this.server)
  616. throw new Error('Client-only method called in server mode');
  617. let callback;
  618. if (typeof callback_ === 'function') {
  619. callback = callback_;
  620. } else if (typeof options === 'function') {
  621. callback = options;
  622. options = undefined;
  623. }
  624. if (typeof options === 'string')
  625. options = { encoding: options, mode: 0o666, flag: 'a' };
  626. else if (!options)
  627. options = { encoding: 'utf8', mode: 0o666, flag: 'a' };
  628. else if (typeof options !== 'object')
  629. throw new TypeError('Bad arguments');
  630. if (!options.flag)
  631. options = Object.assign({ flag: 'a' }, options);
  632. this.writeFile(path, data, options, callback);
  633. }
  634. exists(path, cb) {
  635. if (this.server)
  636. throw new Error('Client-only method called in server mode');
  637. this.stat(path, (err) => {
  638. cb && cb(err ? false : true);
  639. });
  640. }
  641. unlink(filename, cb) {
  642. if (this.server)
  643. throw new Error('Client-only method called in server mode');
  644. /*
  645. uint32 id
  646. string filename
  647. */
  648. const fnameLen = Buffer.byteLength(filename);
  649. let p = 9;
  650. const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + fnameLen);
  651. writeUInt32BE(buf, buf.length - 4, 0);
  652. buf[4] = REQUEST.REMOVE;
  653. const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID;
  654. writeUInt32BE(buf, reqid, 5);
  655. writeUInt32BE(buf, fnameLen, p);
  656. buf.utf8Write(filename, p += 4, fnameLen);
  657. this._requests[reqid] = { cb };
  658. const isBuffered = sendOrBuffer(this, buf);
  659. this._debug && this._debug(
  660. `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} REMOVE`
  661. );
  662. }
  663. rename(oldPath, newPath, cb) {
  664. if (this.server)
  665. throw new Error('Client-only method called in server mode');
  666. /*
  667. uint32 id
  668. string oldpath
  669. string newpath
  670. */
  671. const oldLen = Buffer.byteLength(oldPath);
  672. const newLen = Buffer.byteLength(newPath);
  673. let p = 9;
  674. const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + oldLen + 4 + newLen);
  675. writeUInt32BE(buf, buf.length - 4, 0);
  676. buf[4] = REQUEST.RENAME;
  677. const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID;
  678. writeUInt32BE(buf, reqid, 5);
  679. writeUInt32BE(buf, oldLen, p);
  680. buf.utf8Write(oldPath, p += 4, oldLen);
  681. writeUInt32BE(buf, newLen, p += oldLen);
  682. buf.utf8Write(newPath, p += 4, newLen);
  683. this._requests[reqid] = { cb };
  684. const isBuffered = sendOrBuffer(this, buf);
  685. this._debug && this._debug(
  686. `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} RENAME`
  687. );
  688. }
  689. mkdir(path, attrs, cb) {
  690. if (this.server)
  691. throw new Error('Client-only method called in server mode');
  692. let flags = 0;
  693. let attrsLen = 0;
  694. if (typeof attrs === 'function') {
  695. cb = attrs;
  696. attrs = undefined;
  697. }
  698. if (typeof attrs === 'object' && attrs !== null) {
  699. attrs = attrsToBytes(attrs);
  700. flags = attrs.flags;
  701. attrsLen = attrs.nb;
  702. }
  703. /*
  704. uint32 id
  705. string path
  706. ATTRS attrs
  707. */
  708. const pathLen = Buffer.byteLength(path);
  709. let p = 9;
  710. const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + pathLen + 4 + attrsLen);
  711. writeUInt32BE(buf, buf.length - 4, 0);
  712. buf[4] = REQUEST.MKDIR;
  713. const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID;
  714. writeUInt32BE(buf, reqid, 5);
  715. writeUInt32BE(buf, pathLen, p);
  716. buf.utf8Write(path, p += 4, pathLen);
  717. writeUInt32BE(buf, flags, p += pathLen);
  718. if (attrsLen) {
  719. p += 4;
  720. if (attrsLen === ATTRS_BUF.length)
  721. buf.set(ATTRS_BUF, p);
  722. else
  723. bufferCopy(ATTRS_BUF, buf, 0, attrsLen, p);
  724. p += attrsLen;
  725. }
  726. this._requests[reqid] = { cb };
  727. const isBuffered = sendOrBuffer(this, buf);
  728. this._debug && this._debug(
  729. `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} MKDIR`
  730. );
  731. }
  732. rmdir(path, cb) {
  733. if (this.server)
  734. throw new Error('Client-only method called in server mode');
  735. /*
  736. uint32 id
  737. string path
  738. */
  739. const pathLen = Buffer.byteLength(path);
  740. let p = 9;
  741. const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + pathLen);
  742. writeUInt32BE(buf, buf.length - 4, 0);
  743. buf[4] = REQUEST.RMDIR;
  744. const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID;
  745. writeUInt32BE(buf, reqid, 5);
  746. writeUInt32BE(buf, pathLen, p);
  747. buf.utf8Write(path, p += 4, pathLen);
  748. this._requests[reqid] = { cb };
  749. const isBuffered = sendOrBuffer(this, buf);
  750. this._debug && this._debug(
  751. `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} RMDIR`
  752. );
  753. }
  754. readdir(where, opts, cb) {
  755. if (this.server)
  756. throw new Error('Client-only method called in server mode');
  757. if (typeof opts === 'function') {
  758. cb = opts;
  759. opts = {};
  760. }
  761. if (typeof opts !== 'object' || opts === null)
  762. opts = {};
  763. const doFilter = (opts && opts.full ? false : true);
  764. if (!Buffer.isBuffer(where) && typeof where !== 'string')
  765. throw new Error('missing directory handle or path');
  766. if (typeof where === 'string') {
  767. const entries = [];
  768. let e = 0;
  769. const reread = (err, handle) => {
  770. if (err)
  771. return cb(err);
  772. this.readdir(handle, opts, (err, list) => {
  773. const eof = (err && err.code === STATUS_CODE.EOF);
  774. if (err && !eof)
  775. return this.close(handle, () => cb(err));
  776. if (eof) {
  777. return this.close(handle, (err) => {
  778. if (err)
  779. return cb(err);
  780. cb(undefined, entries);
  781. });
  782. }
  783. for (let i = 0; i < list.length; ++i, ++e)
  784. entries[e] = list[i];
  785. reread(undefined, handle);
  786. });
  787. };
  788. return this.opendir(where, reread);
  789. }
  790. /*
  791. uint32 id
  792. string handle
  793. */
  794. const handleLen = where.length;
  795. let p = 9;
  796. const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + handleLen);
  797. writeUInt32BE(buf, buf.length - 4, 0);
  798. buf[4] = REQUEST.READDIR;
  799. const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID;
  800. writeUInt32BE(buf, reqid, 5);
  801. writeUInt32BE(buf, handleLen, p);
  802. buf.set(where, p += 4);
  803. this._requests[reqid] = {
  804. cb: (doFilter
  805. ? (err, list) => {
  806. if (typeof cb !== 'function')
  807. return;
  808. if (err)
  809. return cb(err);
  810. for (let i = list.length - 1; i >= 0; --i) {
  811. if (list[i].filename === '.' || list[i].filename === '..')
  812. list.splice(i, 1);
  813. }
  814. cb(undefined, list);
  815. }
  816. : cb)
  817. };
  818. const isBuffered = sendOrBuffer(this, buf);
  819. this._debug && this._debug(
  820. `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} READDIR`
  821. );
  822. }
  823. fstat(handle, cb) {
  824. if (this.server)
  825. throw new Error('Client-only method called in server mode');
  826. if (!Buffer.isBuffer(handle))
  827. throw new Error('handle is not a Buffer');
  828. /*
  829. uint32 id
  830. string handle
  831. */
  832. const handleLen = handle.length;
  833. let p = 9;
  834. const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + handleLen);
  835. writeUInt32BE(buf, buf.length - 4, 0);
  836. buf[4] = REQUEST.FSTAT;
  837. const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID;
  838. writeUInt32BE(buf, reqid, 5);
  839. writeUInt32BE(buf, handleLen, p);
  840. buf.set(handle, p += 4);
  841. this._requests[reqid] = { cb };
  842. const isBuffered = sendOrBuffer(this, buf);
  843. this._debug && this._debug(
  844. `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} FSTAT`
  845. );
  846. }
  847. stat(path, cb) {
  848. if (this.server)
  849. throw new Error('Client-only method called in server mode');
  850. /*
  851. uint32 id
  852. string path
  853. */
  854. const pathLen = Buffer.byteLength(path);
  855. let p = 9;
  856. const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + pathLen);
  857. writeUInt32BE(buf, buf.length - 4, 0);
  858. buf[4] = REQUEST.STAT;
  859. const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID;
  860. writeUInt32BE(buf, reqid, 5);
  861. writeUInt32BE(buf, pathLen, p);
  862. buf.utf8Write(path, p += 4, pathLen);
  863. this._requests[reqid] = { cb };
  864. const isBuffered = sendOrBuffer(this, buf);
  865. this._debug && this._debug(
  866. `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} STAT`
  867. );
  868. }
  869. lstat(path, cb) {
  870. if (this.server)
  871. throw new Error('Client-only method called in server mode');
  872. /*
  873. uint32 id
  874. string path
  875. */
  876. const pathLen = Buffer.byteLength(path);
  877. let p = 9;
  878. const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + pathLen);
  879. writeUInt32BE(buf, buf.length - 4, 0);
  880. buf[4] = REQUEST.LSTAT;
  881. const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID;
  882. writeUInt32BE(buf, reqid, 5);
  883. writeUInt32BE(buf, pathLen, p);
  884. buf.utf8Write(path, p += 4, pathLen);
  885. this._requests[reqid] = { cb };
  886. const isBuffered = sendOrBuffer(this, buf);
  887. this._debug && this._debug(
  888. `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} LSTAT`
  889. );
  890. }
  891. opendir(path, cb) {
  892. if (this.server)
  893. throw new Error('Client-only method called in server mode');
  894. /*
  895. uint32 id
  896. string path
  897. */
  898. const pathLen = Buffer.byteLength(path);
  899. let p = 9;
  900. const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + pathLen);
  901. writeUInt32BE(buf, buf.length - 4, 0);
  902. buf[4] = REQUEST.OPENDIR;
  903. const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID;
  904. writeUInt32BE(buf, reqid, 5);
  905. writeUInt32BE(buf, pathLen, p);
  906. buf.utf8Write(path, p += 4, pathLen);
  907. this._requests[reqid] = { cb };
  908. const isBuffered = sendOrBuffer(this, buf);
  909. this._debug && this._debug(
  910. `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} OPENDIR`
  911. );
  912. }
  913. setstat(path, attrs, cb) {
  914. if (this.server)
  915. throw new Error('Client-only method called in server mode');
  916. let flags = 0;
  917. let attrsLen = 0;
  918. if (typeof attrs === 'object' && attrs !== null) {
  919. attrs = attrsToBytes(attrs);
  920. flags = attrs.flags;
  921. attrsLen = attrs.nb;
  922. } else if (typeof attrs === 'function') {
  923. cb = attrs;
  924. }
  925. /*
  926. uint32 id
  927. string path
  928. ATTRS attrs
  929. */
  930. const pathLen = Buffer.byteLength(path);
  931. let p = 9;
  932. const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + pathLen + 4 + attrsLen);
  933. writeUInt32BE(buf, buf.length - 4, 0);
  934. buf[4] = REQUEST.SETSTAT;
  935. const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID;
  936. writeUInt32BE(buf, reqid, 5);
  937. writeUInt32BE(buf, pathLen, p);
  938. buf.utf8Write(path, p += 4, pathLen);
  939. writeUInt32BE(buf, flags, p += pathLen);
  940. if (attrsLen) {
  941. p += 4;
  942. if (attrsLen === ATTRS_BUF.length)
  943. buf.set(ATTRS_BUF, p);
  944. else
  945. bufferCopy(ATTRS_BUF, buf, 0, attrsLen, p);
  946. p += attrsLen;
  947. }
  948. this._requests[reqid] = { cb };
  949. const isBuffered = sendOrBuffer(this, buf);
  950. this._debug && this._debug(
  951. `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} SETSTAT`
  952. );
  953. }
  954. fsetstat(handle, attrs, cb) {
  955. if (this.server)
  956. throw new Error('Client-only method called in server mode');
  957. if (!Buffer.isBuffer(handle))
  958. throw new Error('handle is not a Buffer');
  959. let flags = 0;
  960. let attrsLen = 0;
  961. if (typeof attrs === 'object' && attrs !== null) {
  962. attrs = attrsToBytes(attrs);
  963. flags = attrs.flags;
  964. attrsLen = attrs.nb;
  965. } else if (typeof attrs === 'function') {
  966. cb = attrs;
  967. }
  968. /*
  969. uint32 id
  970. string handle
  971. ATTRS attrs
  972. */
  973. const handleLen = handle.length;
  974. let p = 9;
  975. const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + handleLen + 4 + attrsLen);
  976. writeUInt32BE(buf, buf.length - 4, 0);
  977. buf[4] = REQUEST.FSETSTAT;
  978. const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID;
  979. writeUInt32BE(buf, reqid, 5);
  980. writeUInt32BE(buf, handleLen, p);
  981. buf.set(handle, p += 4);
  982. writeUInt32BE(buf, flags, p += handleLen);
  983. if (attrsLen) {
  984. p += 4;
  985. if (attrsLen === ATTRS_BUF.length)
  986. buf.set(ATTRS_BUF, p);
  987. else
  988. bufferCopy(ATTRS_BUF, buf, 0, attrsLen, p);
  989. p += attrsLen;
  990. }
  991. this._requests[reqid] = { cb };
  992. const isBuffered = sendOrBuffer(this, buf);
  993. this._debug && this._debug(
  994. `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} FSETSTAT`
  995. );
  996. }
  997. futimes(handle, atime, mtime, cb) {
  998. return this.fsetstat(handle, {
  999. atime: toUnixTimestamp(atime),
  1000. mtime: toUnixTimestamp(mtime)
  1001. }, cb);
  1002. }
  1003. utimes(path, atime, mtime, cb) {
  1004. return this.setstat(path, {
  1005. atime: toUnixTimestamp(atime),
  1006. mtime: toUnixTimestamp(mtime)
  1007. }, cb);
  1008. }
  1009. fchown(handle, uid, gid, cb) {
  1010. return this.fsetstat(handle, {
  1011. uid: uid,
  1012. gid: gid
  1013. }, cb);
  1014. }
  1015. chown(path, uid, gid, cb) {
  1016. return this.setstat(path, {
  1017. uid: uid,
  1018. gid: gid
  1019. }, cb);
  1020. }
  1021. fchmod(handle, mode, cb) {
  1022. return this.fsetstat(handle, {
  1023. mode: mode
  1024. }, cb);
  1025. }
  1026. chmod(path, mode, cb) {
  1027. return this.setstat(path, {
  1028. mode: mode
  1029. }, cb);
  1030. }
  1031. readlink(path, cb) {
  1032. if (this.server)
  1033. throw new Error('Client-only method called in server mode');
  1034. /*
  1035. uint32 id
  1036. string path
  1037. */
  1038. const pathLen = Buffer.byteLength(path);
  1039. let p = 9;
  1040. const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + pathLen);
  1041. writeUInt32BE(buf, buf.length - 4, 0);
  1042. buf[4] = REQUEST.READLINK;
  1043. const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID;
  1044. writeUInt32BE(buf, reqid, 5);
  1045. writeUInt32BE(buf, pathLen, p);
  1046. buf.utf8Write(path, p += 4, pathLen);
  1047. this._requests[reqid] = {
  1048. cb: (err, names) => {
  1049. if (typeof cb !== 'function')
  1050. return;
  1051. if (err)
  1052. return cb(err);
  1053. if (!names || !names.length)
  1054. return cb(new Error('Response missing link info'));
  1055. cb(undefined, names[0].filename);
  1056. }
  1057. };
  1058. const isBuffered = sendOrBuffer(this, buf);
  1059. this._debug && this._debug(
  1060. `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} READLINK`
  1061. );
  1062. }
  1063. symlink(targetPath, linkPath, cb) {
  1064. if (this.server)
  1065. throw new Error('Client-only method called in server mode');
  1066. /*
  1067. uint32 id
  1068. string linkpath
  1069. string targetpath
  1070. */
  1071. const linkLen = Buffer.byteLength(linkPath);
  1072. const targetLen = Buffer.byteLength(targetPath);
  1073. let p = 9;
  1074. const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + linkLen + 4 + targetLen);
  1075. writeUInt32BE(buf, buf.length - 4, 0);
  1076. buf[4] = REQUEST.SYMLINK;
  1077. const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID;
  1078. writeUInt32BE(buf, reqid, 5);
  1079. if (this._isOpenSSH) {
  1080. // OpenSSH has linkpath and targetpath positions switched
  1081. writeUInt32BE(buf, targetLen, p);
  1082. buf.utf8Write(targetPath, p += 4, targetLen);
  1083. writeUInt32BE(buf, linkLen, p += targetLen);
  1084. buf.utf8Write(linkPath, p += 4, linkLen);
  1085. } else {
  1086. writeUInt32BE(buf, linkLen, p);
  1087. buf.utf8Write(linkPath, p += 4, linkLen);
  1088. writeUInt32BE(buf, targetLen, p += linkLen);
  1089. buf.utf8Write(targetPath, p += 4, targetLen);
  1090. }
  1091. this._requests[reqid] = { cb };
  1092. const isBuffered = sendOrBuffer(this, buf);
  1093. this._debug && this._debug(
  1094. `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} SYMLINK`
  1095. );
  1096. }
  1097. realpath(path, cb) {
  1098. if (this.server)
  1099. throw new Error('Client-only method called in server mode');
  1100. /*
  1101. uint32 id
  1102. string path
  1103. */
  1104. const pathLen = Buffer.byteLength(path);
  1105. let p = 9;
  1106. const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + pathLen);
  1107. writeUInt32BE(buf, buf.length - 4, 0);
  1108. buf[4] = REQUEST.REALPATH;
  1109. const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID;
  1110. writeUInt32BE(buf, reqid, 5);
  1111. writeUInt32BE(buf, pathLen, p);
  1112. buf.utf8Write(path, p += 4, pathLen);
  1113. this._requests[reqid] = {
  1114. cb: (err, names) => {
  1115. if (typeof cb !== 'function')
  1116. return;
  1117. if (err)
  1118. return cb(err);
  1119. if (!names || !names.length)
  1120. return cb(new Error('Response missing path info'));
  1121. cb(undefined, names[0].filename);
  1122. }
  1123. };
  1124. const isBuffered = sendOrBuffer(this, buf);
  1125. this._debug && this._debug(
  1126. `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} REALPATH`
  1127. );
  1128. }
  1129. // extended requests
  1130. ext_openssh_rename(oldPath, newPath, cb) {
  1131. if (this.server)
  1132. throw new Error('Client-only method called in server mode');
  1133. const ext = this._extensions['posix-rename@openssh.com'];
  1134. if (!ext || ext !== '1')
  1135. throw new Error('Server does not support this extended request');
  1136. /*
  1137. uint32 id
  1138. string "posix-rename@openssh.com"
  1139. string oldpath
  1140. string newpath
  1141. */
  1142. const oldLen = Buffer.byteLength(oldPath);
  1143. const newLen = Buffer.byteLength(newPath);
  1144. let p = 9;
  1145. const buf =
  1146. Buffer.allocUnsafe(4 + 1 + 4 + 4 + 24 + 4 + oldLen + 4 + newLen);
  1147. writeUInt32BE(buf, buf.length - 4, 0);
  1148. buf[4] = REQUEST.EXTENDED;
  1149. const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID;
  1150. writeUInt32BE(buf, reqid, 5);
  1151. writeUInt32BE(buf, 24, p);
  1152. buf.utf8Write('posix-rename@openssh.com', p += 4, 24);
  1153. writeUInt32BE(buf, oldLen, p += 24);
  1154. buf.utf8Write(oldPath, p += 4, oldLen);
  1155. writeUInt32BE(buf, newLen, p += oldLen);
  1156. buf.utf8Write(newPath, p += 4, newLen);
  1157. this._requests[reqid] = { cb };
  1158. const isBuffered = sendOrBuffer(this, buf);
  1159. if (this._debug) {
  1160. const which = (isBuffered ? 'Buffered' : 'Sending');
  1161. this._debug(`SFTP: Outbound: ${which} posix-rename@openssh.com`);
  1162. }
  1163. }
  1164. ext_openssh_statvfs(path, cb) {
  1165. if (this.server)
  1166. throw new Error('Client-only method called in server mode');
  1167. const ext = this._extensions['statvfs@openssh.com'];
  1168. if (!ext || ext !== '2')
  1169. throw new Error('Server does not support this extended request');
  1170. /*
  1171. uint32 id
  1172. string "statvfs@openssh.com"
  1173. string path
  1174. */
  1175. const pathLen = Buffer.byteLength(path);
  1176. let p = 9;
  1177. const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + 19 + 4 + pathLen);
  1178. writeUInt32BE(buf, buf.length - 4, 0);
  1179. buf[4] = REQUEST.EXTENDED;
  1180. const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID;
  1181. writeUInt32BE(buf, reqid, 5);
  1182. writeUInt32BE(buf, 19, p);
  1183. buf.utf8Write('statvfs@openssh.com', p += 4, 19);
  1184. writeUInt32BE(buf, pathLen, p += 19);
  1185. buf.utf8Write(path, p += 4, pathLen);
  1186. this._requests[reqid] = { extended: 'statvfs@openssh.com', cb };
  1187. const isBuffered = sendOrBuffer(this, buf);
  1188. if (this._debug) {
  1189. const which = (isBuffered ? 'Buffered' : 'Sending');
  1190. this._debug(`SFTP: Outbound: ${which} statvfs@openssh.com`);
  1191. }
  1192. }
  1193. ext_openssh_fstatvfs(handle, cb) {
  1194. if (this.server)
  1195. throw new Error('Client-only method called in server mode');
  1196. const ext = this._extensions['fstatvfs@openssh.com'];
  1197. if (!ext || ext !== '2')
  1198. throw new Error('Server does not support this extended request');
  1199. if (!Buffer.isBuffer(handle))
  1200. throw new Error('handle is not a Buffer');
  1201. /*
  1202. uint32 id
  1203. string "fstatvfs@openssh.com"
  1204. string handle
  1205. */
  1206. const handleLen = handle.length;
  1207. let p = 9;
  1208. const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + 20 + 4 + handleLen);
  1209. writeUInt32BE(buf, buf.length - 4, 0);
  1210. buf[4] = REQUEST.EXTENDED;
  1211. const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID;
  1212. writeUInt32BE(buf, reqid, 5);
  1213. writeUInt32BE(buf, 20, p);
  1214. buf.utf8Write('fstatvfs@openssh.com', p += 4, 20);
  1215. writeUInt32BE(buf, handleLen, p += 20);
  1216. buf.set(handle, p += 4);
  1217. this._requests[reqid] = { extended: 'fstatvfs@openssh.com', cb };
  1218. const isBuffered = sendOrBuffer(this, buf);
  1219. if (this._debug) {
  1220. const which = (isBuffered ? 'Buffered' : 'Sending');
  1221. this._debug(`SFTP: Outbound: ${which} fstatvfs@openssh.com`);
  1222. }
  1223. }
  1224. ext_openssh_hardlink(oldPath, newPath, cb) {
  1225. if (this.server)
  1226. throw new Error('Client-only method called in server mode');
  1227. const ext = this._extensions['hardlink@openssh.com'];
  1228. if (ext !== '1')
  1229. throw new Error('Server does not support this extended request');
  1230. /*
  1231. uint32 id
  1232. string "hardlink@openssh.com"
  1233. string oldpath
  1234. string newpath
  1235. */
  1236. const oldLen = Buffer.byteLength(oldPath);
  1237. const newLen = Buffer.byteLength(newPath);
  1238. let p = 9;
  1239. const buf =
  1240. Buffer.allocUnsafe(4 + 1 + 4 + 4 + 20 + 4 + oldLen + 4 + newLen);
  1241. writeUInt32BE(buf, buf.length - 4, 0);
  1242. buf[4] = REQUEST.EXTENDED;
  1243. const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID;
  1244. writeUInt32BE(buf, reqid, 5);
  1245. writeUInt32BE(buf, 20, p);
  1246. buf.utf8Write('hardlink@openssh.com', p += 4, 20);
  1247. writeUInt32BE(buf, oldLen, p += 20);
  1248. buf.utf8Write(oldPath, p += 4, oldLen);
  1249. writeUInt32BE(buf, newLen, p += oldLen);
  1250. buf.utf8Write(newPath, p += 4, newLen);
  1251. this._requests[reqid] = { cb };
  1252. const isBuffered = sendOrBuffer(this, buf);
  1253. if (this._debug) {
  1254. const which = (isBuffered ? 'Buffered' : 'Sending');
  1255. this._debug(`SFTP: Outbound: ${which} hardlink@openssh.com`);
  1256. }
  1257. }
  1258. ext_openssh_fsync(handle, cb) {
  1259. if (this.server)
  1260. throw new Error('Client-only method called in server mode');
  1261. const ext = this._extensions['fsync@openssh.com'];
  1262. if (ext !== '1')
  1263. throw new Error('Server does not support this extended request');
  1264. if (!Buffer.isBuffer(handle))
  1265. throw new Error('handle is not a Buffer');
  1266. /*
  1267. uint32 id
  1268. string "fsync@openssh.com"
  1269. string handle
  1270. */
  1271. const handleLen = handle.length;
  1272. let p = 9;
  1273. const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + 17 + 4 + handleLen);
  1274. writeUInt32BE(buf, buf.length - 4, 0);
  1275. buf[4] = REQUEST.EXTENDED;
  1276. const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID;
  1277. writeUInt32BE(buf, reqid, 5);
  1278. writeUInt32BE(buf, 17, p);
  1279. buf.utf8Write('fsync@openssh.com', p += 4, 17);
  1280. writeUInt32BE(buf, handleLen, p += 17);
  1281. buf.set(handle, p += 4);
  1282. this._requests[reqid] = { cb };
  1283. const isBuffered = sendOrBuffer(this, buf);
  1284. this._debug && this._debug(
  1285. `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} fsync@openssh.com`
  1286. );
  1287. }
  1288. ext_openssh_lsetstat(path, attrs, cb) {
  1289. if (this.server)
  1290. throw new Error('Client-only method called in server mode');
  1291. const ext = this._extensions['lsetstat@openssh.com'];
  1292. if (ext !== '1')
  1293. throw new Error('Server does not support this extended request');
  1294. let flags = 0;
  1295. let attrsLen = 0;
  1296. if (typeof attrs === 'object' && attrs !== null) {
  1297. attrs = attrsToBytes(attrs);
  1298. flags = attrs.flags;
  1299. attrsLen = attrs.nb;
  1300. } else if (typeof attrs === 'function') {
  1301. cb = attrs;
  1302. }
  1303. /*
  1304. uint32 id
  1305. string "lsetstat@openssh.com"
  1306. string path
  1307. ATTRS attrs
  1308. */
  1309. const pathLen = Buffer.byteLength(path);
  1310. let p = 9;
  1311. const buf =
  1312. Buffer.allocUnsafe(4 + 1 + 4 + 4 + 20 + 4 + pathLen + 4 + attrsLen);
  1313. writeUInt32BE(buf, buf.length - 4, 0);
  1314. buf[4] = REQUEST.EXTENDED;
  1315. const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID;
  1316. writeUInt32BE(buf, reqid, 5);
  1317. writeUInt32BE(buf, 20, p);
  1318. buf.utf8Write('lsetstat@openssh.com', p += 4, 20);
  1319. writeUInt32BE(buf, pathLen, p += 20);
  1320. buf.utf8Write(path, p += 4, pathLen);
  1321. writeUInt32BE(buf, flags, p += pathLen);
  1322. if (attrsLen) {
  1323. p += 4;
  1324. if (attrsLen === ATTRS_BUF.length)
  1325. buf.set(ATTRS_BUF, p);
  1326. else
  1327. bufferCopy(ATTRS_BUF, buf, 0, attrsLen, p);
  1328. p += attrsLen;
  1329. }
  1330. this._requests[reqid] = { cb };
  1331. const isBuffered = sendOrBuffer(this, buf);
  1332. if (this._debug) {
  1333. const status = (isBuffered ? 'Buffered' : 'Sending');
  1334. this._debug(`SFTP: Outbound: ${status} lsetstat@openssh.com`);
  1335. }
  1336. }
  1337. ext_openssh_expandPath(path, cb) {
  1338. if (this.server)
  1339. throw new Error('Client-only method called in server mode');
  1340. const ext = this._extensions['expand-path@openssh.com'];
  1341. if (ext !== '1')
  1342. throw new Error('Server does not support this extended request');
  1343. /*
  1344. uint32 id
  1345. string "expand-path@openssh.com"
  1346. string path
  1347. */
  1348. const pathLen = Buffer.byteLength(path);
  1349. let p = 9;
  1350. const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + 23 + 4 + pathLen);
  1351. writeUInt32BE(buf, buf.length - 4, 0);
  1352. buf[4] = REQUEST.EXTENDED;
  1353. const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID;
  1354. writeUInt32BE(buf, reqid, 5);
  1355. writeUInt32BE(buf, 23, p);
  1356. buf.utf8Write('expand-path@openssh.com', p += 4, 23);
  1357. writeUInt32BE(buf, pathLen, p += 20);
  1358. buf.utf8Write(path, p += 4, pathLen);
  1359. this._requests[reqid] = { cb };
  1360. const isBuffered = sendOrBuffer(this, buf);
  1361. if (this._debug) {
  1362. const status = (isBuffered ? 'Buffered' : 'Sending');
  1363. this._debug(`SFTP: Outbound: ${status} expand-path@openssh.com`);
  1364. }
  1365. }
  1366. // ===========================================================================
  1367. // Server-specific ===========================================================
  1368. // ===========================================================================
  1369. handle(reqid, handle) {
  1370. if (!this.server)
  1371. throw new Error('Server-only method called in client mode');
  1372. if (!Buffer.isBuffer(handle))
  1373. throw new Error('handle is not a Buffer');
  1374. const handleLen = handle.length;
  1375. if (handleLen > 256)
  1376. throw new Error('handle too large (> 256 bytes)');
  1377. let p = 9;
  1378. const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + handleLen);
  1379. writeUInt32BE(buf, buf.length - 4, 0);
  1380. buf[4] = RESPONSE.HANDLE;
  1381. writeUInt32BE(buf, reqid, 5);
  1382. writeUInt32BE(buf, handleLen, p);
  1383. if (handleLen)
  1384. buf.set(handle, p += 4);
  1385. const isBuffered = sendOrBuffer(this, buf);
  1386. this._debug && this._debug(
  1387. `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} HANDLE`
  1388. );
  1389. }
  1390. status(reqid, code, message) {
  1391. if (!this.server)
  1392. throw new Error('Server-only method called in client mode');
  1393. if (!VALID_STATUS_CODES.has(code))
  1394. throw new Error(`Bad status code: ${code}`);
  1395. message || (message = '');
  1396. const msgLen = Buffer.byteLength(message);
  1397. let p = 9;
  1398. const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + 4 + msgLen + 4);
  1399. writeUInt32BE(buf, buf.length - 4, 0);
  1400. buf[4] = RESPONSE.STATUS;
  1401. writeUInt32BE(buf, reqid, 5);
  1402. writeUInt32BE(buf, code, p);
  1403. writeUInt32BE(buf, msgLen, p += 4);
  1404. p += 4;
  1405. if (msgLen) {
  1406. buf.utf8Write(message, p, msgLen);
  1407. p += msgLen;
  1408. }
  1409. writeUInt32BE(buf, 0, p); // Empty language tag
  1410. const isBuffered = sendOrBuffer(this, buf);
  1411. this._debug && this._debug(
  1412. `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} STATUS`
  1413. );
  1414. }
  1415. data(reqid, data, encoding) {
  1416. if (!this.server)
  1417. throw new Error('Server-only method called in client mode');
  1418. const isBuffer = Buffer.isBuffer(data);
  1419. if (!isBuffer && typeof data !== 'string')
  1420. throw new Error('data is not a Buffer or string');
  1421. let isUTF8;
  1422. if (!isBuffer && !encoding) {
  1423. encoding = undefined;
  1424. isUTF8 = true;
  1425. }
  1426. const dataLen = (
  1427. isBuffer
  1428. ? data.length
  1429. : Buffer.byteLength(data, encoding)
  1430. );
  1431. let p = 9;
  1432. const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + dataLen);
  1433. writeUInt32BE(buf, buf.length - 4, 0);
  1434. buf[4] = RESPONSE.DATA;
  1435. writeUInt32BE(buf, reqid, 5);
  1436. writeUInt32BE(buf, dataLen, p);
  1437. if (dataLen) {
  1438. if (isBuffer)
  1439. buf.set(data, p += 4);
  1440. else if (isUTF8)
  1441. buf.utf8Write(data, p += 4, dataLen);
  1442. else
  1443. buf.write(data, p += 4, dataLen, encoding);
  1444. }
  1445. const isBuffered = sendOrBuffer(this, buf);
  1446. this._debug && this._debug(
  1447. `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} DATA`
  1448. );
  1449. }
  1450. name(reqid, names) {
  1451. if (!this.server)
  1452. throw new Error('Server-only method called in client mode');
  1453. if (!Array.isArray(names)) {
  1454. if (typeof names !== 'object' || names === null)
  1455. throw new Error('names is not an object or array');
  1456. names = [ names ];
  1457. }
  1458. const count = names.length;
  1459. let namesLen = 0;
  1460. let nameAttrs;
  1461. const attrs = [];
  1462. for (let i = 0; i < count; ++i) {
  1463. const name = names[i];
  1464. const filename = (
  1465. !name || !name.filename || typeof name.filename !== 'string'
  1466. ? ''
  1467. : name.filename
  1468. );
  1469. namesLen += 4 + Buffer.byteLength(filename);
  1470. const longname = (
  1471. !name || !name.longname || typeof name.longname !== 'string'
  1472. ? ''
  1473. : name.longname
  1474. );
  1475. namesLen += 4 + Buffer.byteLength(longname);
  1476. if (typeof name.attrs === 'object' && name.attrs !== null) {
  1477. nameAttrs = attrsToBytes(name.attrs);
  1478. namesLen += 4 + nameAttrs.nb;
  1479. if (nameAttrs.nb) {
  1480. let bytes;
  1481. if (nameAttrs.nb === ATTRS_BUF.length) {
  1482. bytes = new Uint8Array(ATTRS_BUF);
  1483. } else {
  1484. bytes = new Uint8Array(nameAttrs.nb);
  1485. bufferCopy(ATTRS_BUF, bytes, 0, nameAttrs.nb, 0);
  1486. }
  1487. nameAttrs.bytes = bytes;
  1488. }
  1489. attrs.push(nameAttrs);
  1490. } else {
  1491. namesLen += 4;
  1492. attrs.push(null);
  1493. }
  1494. }
  1495. let p = 9;
  1496. const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + namesLen);
  1497. writeUInt32BE(buf, buf.length - 4, 0);
  1498. buf[4] = RESPONSE.NAME;
  1499. writeUInt32BE(buf, reqid, 5);
  1500. writeUInt32BE(buf, count, p);
  1501. p += 4;
  1502. for (let i = 0; i < count; ++i) {
  1503. const name = names[i];
  1504. {
  1505. const filename = (
  1506. !name || !name.filename || typeof name.filename !== 'string'
  1507. ? ''
  1508. : name.filename
  1509. );
  1510. const len = Buffer.byteLength(filename);
  1511. writeUInt32BE(buf, len, p);
  1512. p += 4;
  1513. if (len) {
  1514. buf.utf8Write(filename, p, len);
  1515. p += len;
  1516. }
  1517. }
  1518. {
  1519. const longname = (
  1520. !name || !name.longname || typeof name.longname !== 'string'
  1521. ? ''
  1522. : name.longname
  1523. );
  1524. const len = Buffer.byteLength(longname);
  1525. writeUInt32BE(buf, len, p);
  1526. p += 4;
  1527. if (len) {
  1528. buf.utf8Write(longname, p, len);
  1529. p += len;
  1530. }
  1531. }
  1532. const attr = attrs[i];
  1533. if (attr) {
  1534. writeUInt32BE(buf, attr.flags, p);
  1535. p += 4;
  1536. if (attr.flags && attr.bytes) {
  1537. buf.set(attr.bytes, p);
  1538. p += attr.nb;
  1539. }
  1540. } else {
  1541. writeUInt32BE(buf, 0, p);
  1542. p += 4;
  1543. }
  1544. }
  1545. const isBuffered = sendOrBuffer(this, buf);
  1546. this._debug && this._debug(
  1547. `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} NAME`
  1548. );
  1549. }
  1550. attrs(reqid, attrs) {
  1551. if (!this.server)
  1552. throw new Error('Server-only method called in client mode');
  1553. if (typeof attrs !== 'object' || attrs === null)
  1554. throw new Error('attrs is not an object');
  1555. attrs = attrsToBytes(attrs);
  1556. const flags = attrs.flags;
  1557. const attrsLen = attrs.nb;
  1558. let p = 9;
  1559. const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + attrsLen);
  1560. writeUInt32BE(buf, buf.length - 4, 0);
  1561. buf[4] = RESPONSE.ATTRS;
  1562. writeUInt32BE(buf, reqid, 5);
  1563. writeUInt32BE(buf, flags, p);
  1564. if (attrsLen) {
  1565. p += 4;
  1566. if (attrsLen === ATTRS_BUF.length)
  1567. buf.set(ATTRS_BUF, p);
  1568. else
  1569. bufferCopy(ATTRS_BUF, buf, 0, attrsLen, p);
  1570. p += attrsLen;
  1571. }
  1572. const isBuffered = sendOrBuffer(this, buf);
  1573. this._debug && this._debug(
  1574. `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} ATTRS`
  1575. );
  1576. }
  1577. }
  1578. function tryCreateBuffer(size) {
  1579. try {
  1580. return Buffer.allocUnsafe(size);
  1581. } catch (ex) {
  1582. return ex;
  1583. }
  1584. }
  1585. function read_(self, handle, buf, off, len, position, cb, req_) {
  1586. const maxDataLen = self._maxReadLen;
  1587. const overflow = Math.max(len - maxDataLen, 0);
  1588. if (overflow)
  1589. len = maxDataLen;
  1590. /*
  1591. uint32 id
  1592. string handle
  1593. uint64 offset
  1594. uint32 len
  1595. */
  1596. const handleLen = handle.length;
  1597. let p = 9;
  1598. let pos = position;
  1599. const out = Buffer.allocUnsafe(4 + 1 + 4 + 4 + handleLen + 8 + 4);
  1600. writeUInt32BE(out, out.length - 4, 0);
  1601. out[4] = REQUEST.READ;
  1602. const reqid = self._writeReqid = (self._writeReqid + 1) & MAX_REQID;
  1603. writeUInt32BE(out, reqid, 5);
  1604. writeUInt32BE(out, handleLen, p);
  1605. out.set(handle, p += 4);
  1606. p += handleLen;
  1607. for (let i = 7; i >= 0; --i) {
  1608. out[p + i] = pos & 0xFF;
  1609. pos /= 256;
  1610. }
  1611. writeUInt32BE(out, len, p += 8);
  1612. if (typeof cb !== 'function')
  1613. cb = noop;
  1614. const req = (req_ || {
  1615. nb: 0,
  1616. position,
  1617. off,
  1618. origOff: off,
  1619. len: undefined,
  1620. overflow: undefined,
  1621. cb: (err, data, nb) => {
  1622. const len = req.len;
  1623. const overflow = req.overflow;
  1624. if (err) {
  1625. if (cb._wantEOFError || err.code !== STATUS_CODE.EOF)
  1626. return cb(err);
  1627. } else if (nb > len) {
  1628. return cb(new Error('Received more data than requested'));
  1629. } else if (nb === len && overflow) {
  1630. req.nb += nb;
  1631. req.position += nb;
  1632. req.off += nb;
  1633. read_(self, handle, buf, req.off, overflow, req.position, cb, req);
  1634. return;
  1635. }
  1636. if (req.origOff === 0 && buf.length === req.nb)
  1637. data = buf;
  1638. else
  1639. data = bufferSlice(buf, req.origOff, req.origOff + req.nb);
  1640. cb(undefined, req.nb + (nb || 0), data, req.position);
  1641. },
  1642. buffer: undefined,
  1643. });
  1644. req.len = len;
  1645. req.overflow = overflow;
  1646. // TODO: avoid creating multiple buffer slices when we need to re-call read_()
  1647. // because of overflow
  1648. req.buffer = bufferSlice(buf, off, off + len);
  1649. self._requests[reqid] = req;
  1650. const isBuffered = sendOrBuffer(self, out);
  1651. self._debug && self._debug(
  1652. `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} READ`
  1653. );
  1654. }
  1655. function fastXfer(src, dst, srcPath, dstPath, opts, cb) {
  1656. let concurrency = 64;
  1657. let chunkSize = 32768;
  1658. let onstep;
  1659. let mode;
  1660. let fileSize;
  1661. if (typeof opts === 'function') {
  1662. cb = opts;
  1663. } else if (typeof opts === 'object' && opts !== null) {
  1664. if (typeof opts.concurrency === 'number'
  1665. && opts.concurrency > 0
  1666. && !isNaN(opts.concurrency)) {
  1667. concurrency = opts.concurrency;
  1668. }
  1669. if (typeof opts.chunkSize === 'number'
  1670. && opts.chunkSize > 0
  1671. && !isNaN(opts.chunkSize)) {
  1672. chunkSize = opts.chunkSize;
  1673. }
  1674. if (typeof opts.fileSize === 'number'
  1675. && opts.fileSize > 0
  1676. && !isNaN(opts.fileSize)) {
  1677. fileSize = opts.fileSize;
  1678. }
  1679. if (typeof opts.step === 'function')
  1680. onstep = opts.step;
  1681. if (typeof opts.mode === 'string' || typeof opts.mode === 'number')
  1682. mode = modeNum(opts.mode);
  1683. }
  1684. // Internal state variables
  1685. let fsize;
  1686. let pdst = 0;
  1687. let total = 0;
  1688. let hadError = false;
  1689. let srcHandle;
  1690. let dstHandle;
  1691. let readbuf;
  1692. let bufsize = chunkSize * concurrency;
  1693. function onerror(err) {
  1694. if (hadError)
  1695. return;
  1696. hadError = true;
  1697. let left = 0;
  1698. let cbfinal;
  1699. if (srcHandle || dstHandle) {
  1700. cbfinal = () => {
  1701. if (--left === 0)
  1702. cb(err);
  1703. };
  1704. if (srcHandle && (src === fs || src.outgoing.state === 'open'))
  1705. ++left;
  1706. if (dstHandle && (dst === fs || dst.outgoing.state === 'open'))
  1707. ++left;
  1708. if (srcHandle && (src === fs || src.outgoing.state === 'open'))
  1709. src.close(srcHandle, cbfinal);
  1710. if (dstHandle && (dst === fs || dst.outgoing.state === 'open'))
  1711. dst.close(dstHandle, cbfinal);
  1712. } else {
  1713. cb(err);
  1714. }
  1715. }
  1716. src.open(srcPath, 'r', (err, sourceHandle) => {
  1717. if (err)
  1718. return onerror(err);
  1719. srcHandle = sourceHandle;
  1720. if (fileSize === undefined)
  1721. src.fstat(srcHandle, tryStat);
  1722. else
  1723. tryStat(null, { size: fileSize });
  1724. function tryStat(err, attrs) {
  1725. if (err) {
  1726. if (src !== fs) {
  1727. // Try stat() for sftp servers that may not support fstat() for
  1728. // whatever reason
  1729. src.stat(srcPath, (err_, attrs_) => {
  1730. if (err_)
  1731. return onerror(err);
  1732. tryStat(null, attrs_);
  1733. });
  1734. return;
  1735. }
  1736. return onerror(err);
  1737. }
  1738. fsize = attrs.size;
  1739. dst.open(dstPath, 'w', (err, destHandle) => {
  1740. if (err)
  1741. return onerror(err);
  1742. dstHandle = destHandle;
  1743. if (fsize <= 0)
  1744. return onerror();
  1745. // Use less memory where possible
  1746. while (bufsize > fsize) {
  1747. if (concurrency === 1) {
  1748. bufsize = fsize;
  1749. break;
  1750. }
  1751. bufsize -= chunkSize;
  1752. --concurrency;
  1753. }
  1754. readbuf = tryCreateBuffer(bufsize);
  1755. if (readbuf instanceof Error)
  1756. return onerror(readbuf);
  1757. if (mode !== undefined) {
  1758. dst.fchmod(dstHandle, mode, function tryAgain(err) {
  1759. if (err) {
  1760. // Try chmod() for sftp servers that may not support fchmod()
  1761. // for whatever reason
  1762. dst.chmod(dstPath, mode, (err_) => tryAgain());
  1763. return;
  1764. }
  1765. startReads();
  1766. });
  1767. } else {
  1768. startReads();
  1769. }
  1770. function onread(err, nb, data, dstpos, datapos, origChunkLen) {
  1771. if (err)
  1772. return onerror(err);
  1773. datapos = datapos || 0;
  1774. dst.write(dstHandle, readbuf, datapos, nb, dstpos, writeCb);
  1775. function writeCb(err) {
  1776. if (err)
  1777. return onerror(err);
  1778. total += nb;
  1779. onstep && onstep(total, nb, fsize);
  1780. if (nb < origChunkLen)
  1781. return singleRead(datapos, dstpos + nb, origChunkLen - nb);
  1782. if (total === fsize) {
  1783. dst.close(dstHandle, (err) => {
  1784. dstHandle = undefined;
  1785. if (err)
  1786. return onerror(err);
  1787. src.close(srcHandle, (err) => {
  1788. srcHandle = undefined;
  1789. if (err)
  1790. return onerror(err);
  1791. cb();
  1792. });
  1793. });
  1794. return;
  1795. }
  1796. if (pdst >= fsize)
  1797. return;
  1798. const chunk =
  1799. (pdst + chunkSize > fsize ? fsize - pdst : chunkSize);
  1800. singleRead(datapos, pdst, chunk);
  1801. pdst += chunk;
  1802. }
  1803. }
  1804. function makeCb(psrc, pdst, chunk) {
  1805. return (err, nb, data) => {
  1806. onread(err, nb, data, pdst, psrc, chunk);
  1807. };
  1808. }
  1809. function singleRead(psrc, pdst, chunk) {
  1810. src.read(srcHandle,
  1811. readbuf,
  1812. psrc,
  1813. chunk,
  1814. pdst,
  1815. makeCb(psrc, pdst, chunk));
  1816. }
  1817. function startReads() {
  1818. let reads = 0;
  1819. let psrc = 0;
  1820. while (pdst < fsize && reads < concurrency) {
  1821. const chunk =
  1822. (pdst + chunkSize > fsize ? fsize - pdst : chunkSize);
  1823. singleRead(psrc, pdst, chunk);
  1824. psrc += chunk;
  1825. pdst += chunk;
  1826. ++reads;
  1827. }
  1828. }
  1829. });
  1830. }
  1831. });
  1832. }
  1833. function writeAll(sftp, handle, buffer, offset, length, position, callback_) {
  1834. const callback = (typeof callback_ === 'function' ? callback_ : undefined);
  1835. sftp.write(handle,
  1836. buffer,
  1837. offset,
  1838. length,
  1839. position,
  1840. (writeErr, written) => {
  1841. if (writeErr) {
  1842. return sftp.close(handle, () => {
  1843. callback && callback(writeErr);
  1844. });
  1845. }
  1846. if (written === length) {
  1847. sftp.close(handle, callback);
  1848. } else {
  1849. offset += written;
  1850. length -= written;
  1851. position += written;
  1852. writeAll(sftp, handle, buffer, offset, length, position, callback);
  1853. }
  1854. });
  1855. }
  1856. class Stats {
  1857. constructor(initial) {
  1858. this.mode = (initial && initial.mode);
  1859. this.uid = (initial && initial.uid);
  1860. this.gid = (initial && initial.gid);
  1861. this.size = (initial && initial.size);
  1862. this.atime = (initial && initial.atime);
  1863. this.mtime = (initial && initial.mtime);
  1864. this.extended = (initial && initial.extended);
  1865. }
  1866. isDirectory() {
  1867. return ((this.mode & constants.S_IFMT) === constants.S_IFDIR);
  1868. }
  1869. isFile() {
  1870. return ((this.mode & constants.S_IFMT) === constants.S_IFREG);
  1871. }
  1872. isBlockDevice() {
  1873. return ((this.mode & constants.S_IFMT) === constants.S_IFBLK);
  1874. }
  1875. isCharacterDevice() {
  1876. return ((this.mode & constants.S_IFMT) === constants.S_IFCHR);
  1877. }
  1878. isSymbolicLink() {
  1879. return ((this.mode & constants.S_IFMT) === constants.S_IFLNK);
  1880. }
  1881. isFIFO() {
  1882. return ((this.mode & constants.S_IFMT) === constants.S_IFIFO);
  1883. }
  1884. isSocket() {
  1885. return ((this.mode & constants.S_IFMT) === constants.S_IFSOCK);
  1886. }
  1887. }
  1888. function attrsToBytes(attrs) {
  1889. let flags = 0;
  1890. let nb = 0;
  1891. if (typeof attrs === 'object' && attrs !== null) {
  1892. if (typeof attrs.size === 'number') {
  1893. flags |= ATTR.SIZE;
  1894. const val = attrs.size;
  1895. // Big Endian
  1896. ATTRS_BUF[nb++] = val / 72057594037927940; // 2**56
  1897. ATTRS_BUF[nb++] = val / 281474976710656; // 2**48
  1898. ATTRS_BUF[nb++] = val / 1099511627776; // 2**40
  1899. ATTRS_BUF[nb++] = val / 4294967296; // 2**32
  1900. ATTRS_BUF[nb++] = val / 16777216; // 2**24
  1901. ATTRS_BUF[nb++] = val / 65536; // 2**16
  1902. ATTRS_BUF[nb++] = val / 256; // 2**8
  1903. ATTRS_BUF[nb++] = val;
  1904. }
  1905. if (typeof attrs.uid === 'number' && typeof attrs.gid === 'number') {
  1906. flags |= ATTR.UIDGID;
  1907. const uid = attrs.uid;
  1908. const gid = attrs.gid;
  1909. // Big Endian
  1910. ATTRS_BUF[nb++] = uid >>> 24;
  1911. ATTRS_BUF[nb++] = uid >>> 16;
  1912. ATTRS_BUF[nb++] = uid >>> 8;
  1913. ATTRS_BUF[nb++] = uid;
  1914. ATTRS_BUF[nb++] = gid >>> 24;
  1915. ATTRS_BUF[nb++] = gid >>> 16;
  1916. ATTRS_BUF[nb++] = gid >>> 8;
  1917. ATTRS_BUF[nb++] = gid;
  1918. }
  1919. if (typeof attrs.mode === 'number' || typeof attrs.mode === 'string') {
  1920. const mode = modeNum(attrs.mode);
  1921. flags |= ATTR.PERMISSIONS;
  1922. // Big Endian
  1923. ATTRS_BUF[nb++] = mode >>> 24;
  1924. ATTRS_BUF[nb++] = mode >>> 16;
  1925. ATTRS_BUF[nb++] = mode >>> 8;
  1926. ATTRS_BUF[nb++] = mode;
  1927. }
  1928. if ((typeof attrs.atime === 'number' || isDate(attrs.atime))
  1929. && (typeof attrs.mtime === 'number' || isDate(attrs.mtime))) {
  1930. const atime = toUnixTimestamp(attrs.atime);
  1931. const mtime = toUnixTimestamp(attrs.mtime);
  1932. flags |= ATTR.ACMODTIME;
  1933. // Big Endian
  1934. ATTRS_BUF[nb++] = atime >>> 24;
  1935. ATTRS_BUF[nb++] = atime >>> 16;
  1936. ATTRS_BUF[nb++] = atime >>> 8;
  1937. ATTRS_BUF[nb++] = atime;
  1938. ATTRS_BUF[nb++] = mtime >>> 24;
  1939. ATTRS_BUF[nb++] = mtime >>> 16;
  1940. ATTRS_BUF[nb++] = mtime >>> 8;
  1941. ATTRS_BUF[nb++] = mtime;
  1942. }
  1943. // TODO: extended attributes
  1944. }
  1945. return { flags, nb };
  1946. }
  1947. function toUnixTimestamp(time) {
  1948. // eslint-disable-next-line no-self-compare
  1949. if (typeof time === 'number' && time === time) // Valid, non-NaN number
  1950. return time;
  1951. if (isDate(time))
  1952. return parseInt(time.getTime() / 1000, 10);
  1953. throw new Error(`Cannot parse time: ${time}`);
  1954. }
  1955. function modeNum(mode) {
  1956. // eslint-disable-next-line no-self-compare
  1957. if (typeof mode === 'number' && mode === mode) // Valid, non-NaN number
  1958. return mode;
  1959. if (typeof mode === 'string')
  1960. return modeNum(parseInt(mode, 8));
  1961. throw new Error(`Cannot parse mode: ${mode}`);
  1962. }
  1963. const stringFlagMap = {
  1964. 'r': OPEN_MODE.READ,
  1965. 'r+': OPEN_MODE.READ | OPEN_MODE.WRITE,
  1966. 'w': OPEN_MODE.TRUNC | OPEN_MODE.CREAT | OPEN_MODE.WRITE,
  1967. 'wx': OPEN_MODE.TRUNC | OPEN_MODE.CREAT | OPEN_MODE.WRITE | OPEN_MODE.EXCL,
  1968. 'xw': OPEN_MODE.TRUNC | OPEN_MODE.CREAT | OPEN_MODE.WRITE | OPEN_MODE.EXCL,
  1969. 'w+': OPEN_MODE.TRUNC | OPEN_MODE.CREAT | OPEN_MODE.READ | OPEN_MODE.WRITE,
  1970. 'wx+': OPEN_MODE.TRUNC | OPEN_MODE.CREAT | OPEN_MODE.READ | OPEN_MODE.WRITE
  1971. | OPEN_MODE.EXCL,
  1972. 'xw+': OPEN_MODE.TRUNC | OPEN_MODE.CREAT | OPEN_MODE.READ | OPEN_MODE.WRITE
  1973. | OPEN_MODE.EXCL,
  1974. 'a': OPEN_MODE.APPEND | OPEN_MODE.CREAT | OPEN_MODE.WRITE,
  1975. 'ax': OPEN_MODE.APPEND | OPEN_MODE.CREAT | OPEN_MODE.WRITE | OPEN_MODE.EXCL,
  1976. 'xa': OPEN_MODE.APPEND | OPEN_MODE.CREAT | OPEN_MODE.WRITE | OPEN_MODE.EXCL,
  1977. 'a+': OPEN_MODE.APPEND | OPEN_MODE.CREAT | OPEN_MODE.READ | OPEN_MODE.WRITE,
  1978. 'ax+': OPEN_MODE.APPEND | OPEN_MODE.CREAT | OPEN_MODE.READ | OPEN_MODE.WRITE
  1979. | OPEN_MODE.EXCL,
  1980. 'xa+': OPEN_MODE.APPEND | OPEN_MODE.CREAT | OPEN_MODE.READ | OPEN_MODE.WRITE
  1981. | OPEN_MODE.EXCL
  1982. };
  1983. function stringToFlags(str) {
  1984. const flags = stringFlagMap[str];
  1985. return (flags !== undefined ? flags : null);
  1986. }
  1987. const flagsToString = (() => {
  1988. const stringFlagMapKeys = Object.keys(stringFlagMap);
  1989. return (flags) => {
  1990. for (let i = 0; i < stringFlagMapKeys.length; ++i) {
  1991. const key = stringFlagMapKeys[i];
  1992. if (stringFlagMap[key] === flags)
  1993. return key;
  1994. }
  1995. return null;
  1996. };
  1997. })();
  1998. function readAttrs(biOpt) {
  1999. /*
  2000. uint32 flags
  2001. uint64 size present only if flag SSH_FILEXFER_ATTR_SIZE
  2002. uint32 uid present only if flag SSH_FILEXFER_ATTR_UIDGID
  2003. uint32 gid present only if flag SSH_FILEXFER_ATTR_UIDGID
  2004. uint32 permissions present only if flag SSH_FILEXFER_ATTR_PERMISSIONS
  2005. uint32 atime present only if flag SSH_FILEXFER_ACMODTIME
  2006. uint32 mtime present only if flag SSH_FILEXFER_ACMODTIME
  2007. uint32 extended_count present only if flag SSH_FILEXFER_ATTR_EXTENDED
  2008. string extended_type
  2009. string extended_data
  2010. ... more extended data (extended_type - extended_data pairs),
  2011. so that number of pairs equals extended_count
  2012. */
  2013. const flags = bufferParser.readUInt32BE();
  2014. if (flags === undefined)
  2015. return;
  2016. const attrs = new Stats();
  2017. if (flags & ATTR.SIZE) {
  2018. const size = bufferParser.readUInt64BE(biOpt);
  2019. if (size === undefined)
  2020. return;
  2021. attrs.size = size;
  2022. }
  2023. if (flags & ATTR.UIDGID) {
  2024. const uid = bufferParser.readUInt32BE();
  2025. const gid = bufferParser.readUInt32BE();
  2026. if (gid === undefined)
  2027. return;
  2028. attrs.uid = uid;
  2029. attrs.gid = gid;
  2030. }
  2031. if (flags & ATTR.PERMISSIONS) {
  2032. const mode = bufferParser.readUInt32BE();
  2033. if (mode === undefined)
  2034. return;
  2035. attrs.mode = mode;
  2036. }
  2037. if (flags & ATTR.ACMODTIME) {
  2038. const atime = bufferParser.readUInt32BE();
  2039. const mtime = bufferParser.readUInt32BE();
  2040. if (mtime === undefined)
  2041. return;
  2042. attrs.atime = atime;
  2043. attrs.mtime = mtime;
  2044. }
  2045. if (flags & ATTR.EXTENDED) {
  2046. const count = bufferParser.readUInt32BE();
  2047. if (count === undefined)
  2048. return;
  2049. const extended = {};
  2050. for (let i = 0; i < count; ++i) {
  2051. const type = bufferParser.readString(true);
  2052. const data = bufferParser.readString();
  2053. if (data === undefined)
  2054. return;
  2055. extended[type] = data;
  2056. }
  2057. attrs.extended = extended;
  2058. }
  2059. return attrs;
  2060. }
  2061. function sendOrBuffer(sftp, payload) {
  2062. const ret = tryWritePayload(sftp, payload);
  2063. if (ret !== undefined) {
  2064. sftp._buffer.push(ret);
  2065. return false;
  2066. }
  2067. return true;
  2068. }
  2069. function tryWritePayload(sftp, payload) {
  2070. const outgoing = sftp.outgoing;
  2071. if (outgoing.state !== 'open')
  2072. return;
  2073. if (outgoing.window === 0) {
  2074. sftp._waitWindow = true; // XXX: Unnecessary?
  2075. return payload;
  2076. }
  2077. let ret;
  2078. const len = payload.length;
  2079. let p = 0;
  2080. while (len - p > 0 && outgoing.window > 0) {
  2081. const actualLen = Math.min(len - p, outgoing.window, outgoing.packetSize);
  2082. outgoing.window -= actualLen;
  2083. if (outgoing.window === 0) {
  2084. sftp._waitWindow = true;
  2085. sftp._chunkcb = drainBuffer;
  2086. }
  2087. if (p === 0 && actualLen === len) {
  2088. sftp._protocol.channelData(sftp.outgoing.id, payload);
  2089. } else {
  2090. sftp._protocol.channelData(sftp.outgoing.id,
  2091. bufferSlice(payload, p, p + actualLen));
  2092. }
  2093. p += actualLen;
  2094. }
  2095. if (len - p > 0) {
  2096. if (p > 0)
  2097. ret = bufferSlice(payload, p, len);
  2098. else
  2099. ret = payload; // XXX: should never get here?
  2100. }
  2101. return ret;
  2102. }
  2103. function drainBuffer() {
  2104. this._chunkcb = undefined;
  2105. const buffer = this._buffer;
  2106. let i = 0;
  2107. while (i < buffer.length) {
  2108. const payload = buffer[i];
  2109. const ret = tryWritePayload(this, payload);
  2110. if (ret !== undefined) {
  2111. if (ret !== payload)
  2112. buffer[i] = ret;
  2113. if (i > 0)
  2114. this._buffer = buffer.slice(i);
  2115. return;
  2116. }
  2117. ++i;
  2118. }
  2119. if (i > 0)
  2120. this._buffer = [];
  2121. }
  2122. function doFatalSFTPError(sftp, msg, noDebug) {
  2123. const err = new Error(msg);
  2124. err.level = 'sftp-protocol';
  2125. if (!noDebug && sftp._debug)
  2126. sftp._debug(`SFTP: Inbound: ${msg}`);
  2127. sftp.emit('error', err);
  2128. sftp.destroy();
  2129. cleanupRequests(sftp);
  2130. return false;
  2131. }
  2132. function cleanupRequests(sftp) {
  2133. const keys = Object.keys(sftp._requests);
  2134. if (keys.length === 0)
  2135. return;
  2136. const reqs = sftp._requests;
  2137. sftp._requests = {};
  2138. const err = new Error('No response from server');
  2139. for (let i = 0; i < keys.length; ++i) {
  2140. const req = reqs[keys[i]];
  2141. if (typeof req.cb === 'function')
  2142. req.cb(err);
  2143. }
  2144. }
  2145. function requestLimits(sftp, cb) {
  2146. /*
  2147. uint32 id
  2148. string "limits@openssh.com"
  2149. */
  2150. let p = 9;
  2151. const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + 18);
  2152. writeUInt32BE(buf, buf.length - 4, 0);
  2153. buf[4] = REQUEST.EXTENDED;
  2154. const reqid = sftp._writeReqid = (sftp._writeReqid + 1) & MAX_REQID;
  2155. writeUInt32BE(buf, reqid, 5);
  2156. writeUInt32BE(buf, 18, p);
  2157. buf.utf8Write('limits@openssh.com', p += 4, 18);
  2158. sftp._requests[reqid] = { extended: 'limits@openssh.com', cb };
  2159. const isBuffered = sendOrBuffer(sftp, buf);
  2160. if (sftp._debug) {
  2161. const which = (isBuffered ? 'Buffered' : 'Sending');
  2162. sftp._debug(`SFTP: Outbound: ${which} limits@openssh.com`);
  2163. }
  2164. }
  2165. const CLIENT_HANDLERS = {
  2166. [RESPONSE.VERSION]: (sftp, payload) => {
  2167. if (sftp._version !== -1)
  2168. return doFatalSFTPError(sftp, 'Duplicate VERSION packet');
  2169. const extensions = {};
  2170. /*
  2171. uint32 version
  2172. <extension data>
  2173. */
  2174. bufferParser.init(payload, 1);
  2175. let version = bufferParser.readUInt32BE();
  2176. while (bufferParser.avail()) {
  2177. const extName = bufferParser.readString(true);
  2178. const extData = bufferParser.readString(true);
  2179. if (extData === undefined) {
  2180. version = undefined;
  2181. break;
  2182. }
  2183. extensions[extName] = extData;
  2184. }
  2185. bufferParser.clear();
  2186. if (version === undefined)
  2187. return doFatalSFTPError(sftp, 'Malformed VERSION packet');
  2188. if (sftp._debug) {
  2189. const names = Object.keys(extensions);
  2190. if (names.length) {
  2191. sftp._debug(
  2192. `SFTP: Inbound: Received VERSION (v${version}, exts:${names})`
  2193. );
  2194. } else {
  2195. sftp._debug(`SFTP: Inbound: Received VERSION (v${version})`);
  2196. }
  2197. }
  2198. sftp._version = version;
  2199. sftp._extensions = extensions;
  2200. if (extensions['limits@openssh.com'] === '1') {
  2201. return requestLimits(sftp, (err, limits) => {
  2202. if (!err) {
  2203. if (limits.maxPktLen > 0)
  2204. sftp._maxOutPktLen = limits.maxPktLen;
  2205. if (limits.maxReadLen > 0)
  2206. sftp._maxReadLen = limits.maxReadLen;
  2207. if (limits.maxWriteLen > 0)
  2208. sftp._maxWriteLen = limits.maxWriteLen;
  2209. sftp.maxOpenHandles = (
  2210. limits.maxOpenHandles > 0 ? limits.maxOpenHandles : Infinity
  2211. );
  2212. }
  2213. sftp.emit('ready');
  2214. });
  2215. }
  2216. sftp.emit('ready');
  2217. },
  2218. [RESPONSE.STATUS]: (sftp, payload) => {
  2219. bufferParser.init(payload, 1);
  2220. const reqID = bufferParser.readUInt32BE();
  2221. /*
  2222. uint32 error/status code
  2223. string error message (ISO-10646 UTF-8)
  2224. string language tag
  2225. */
  2226. const errorCode = bufferParser.readUInt32BE();
  2227. const errorMsg = bufferParser.readString(true);
  2228. const lang = bufferParser.skipString();
  2229. bufferParser.clear();
  2230. if (lang === undefined) {
  2231. if (reqID !== undefined)
  2232. delete sftp._requests[reqID];
  2233. return doFatalSFTPError(sftp, 'Malformed STATUS packet');
  2234. }
  2235. if (sftp._debug) {
  2236. const jsonMsg = JSON.stringify(errorMsg);
  2237. sftp._debug(
  2238. `SFTP: Inbound: Received STATUS (id:${reqID}, ${errorCode}, ${jsonMsg})`
  2239. );
  2240. }
  2241. const req = sftp._requests[reqID];
  2242. delete sftp._requests[reqID];
  2243. if (req && typeof req.cb === 'function') {
  2244. if (errorCode === STATUS_CODE.OK) {
  2245. req.cb();
  2246. return;
  2247. }
  2248. const err = new Error(errorMsg
  2249. || STATUS_CODE_STR[errorCode]
  2250. || 'Unknown status');
  2251. err.code = errorCode;
  2252. req.cb(err);
  2253. }
  2254. },
  2255. [RESPONSE.HANDLE]: (sftp, payload) => {
  2256. bufferParser.init(payload, 1);
  2257. const reqID = bufferParser.readUInt32BE();
  2258. /*
  2259. string handle
  2260. */
  2261. const handle = bufferParser.readString();
  2262. bufferParser.clear();
  2263. if (handle === undefined) {
  2264. if (reqID !== undefined)
  2265. delete sftp._requests[reqID];
  2266. return doFatalSFTPError(sftp, 'Malformed HANDLE packet');
  2267. }
  2268. sftp._debug && sftp._debug(`SFTP: Inbound: Received HANDLE (id:${reqID})`);
  2269. const req = sftp._requests[reqID];
  2270. delete sftp._requests[reqID];
  2271. if (req && typeof req.cb === 'function')
  2272. req.cb(undefined, handle);
  2273. },
  2274. [RESPONSE.DATA]: (sftp, payload) => {
  2275. bufferParser.init(payload, 1);
  2276. const reqID = bufferParser.readUInt32BE();
  2277. let req;
  2278. if (reqID !== undefined) {
  2279. req = sftp._requests[reqID];
  2280. delete sftp._requests[reqID];
  2281. }
  2282. /*
  2283. string data
  2284. */
  2285. if (req && typeof req.cb === 'function') {
  2286. if (req.buffer) {
  2287. // We have already pre-allocated space to store the data
  2288. const nb = bufferParser.readString(req.buffer);
  2289. bufferParser.clear();
  2290. if (nb !== undefined) {
  2291. sftp._debug && sftp._debug(
  2292. `SFTP: Inbound: Received DATA (id:${reqID}, ${nb})`
  2293. );
  2294. req.cb(undefined, req.buffer, nb);
  2295. return;
  2296. }
  2297. } else {
  2298. const data = bufferParser.readString();
  2299. bufferParser.clear();
  2300. if (data !== undefined) {
  2301. sftp._debug && sftp._debug(
  2302. `SFTP: Inbound: Received DATA (id:${reqID}, ${data.length})`
  2303. );
  2304. req.cb(undefined, data);
  2305. return;
  2306. }
  2307. }
  2308. } else {
  2309. const nb = bufferParser.skipString();
  2310. bufferParser.clear();
  2311. if (nb !== undefined) {
  2312. sftp._debug && sftp._debug(
  2313. `SFTP: Inbound: Received DATA (id:${reqID}, ${nb})`
  2314. );
  2315. return;
  2316. }
  2317. }
  2318. return doFatalSFTPError(sftp, 'Malformed DATA packet');
  2319. },
  2320. [RESPONSE.NAME]: (sftp, payload) => {
  2321. bufferParser.init(payload, 1);
  2322. const reqID = bufferParser.readUInt32BE();
  2323. let req;
  2324. if (reqID !== undefined) {
  2325. req = sftp._requests[reqID];
  2326. delete sftp._requests[reqID];
  2327. }
  2328. /*
  2329. uint32 count
  2330. repeats count times:
  2331. string filename
  2332. string longname
  2333. ATTRS attrs
  2334. */
  2335. const count = bufferParser.readUInt32BE();
  2336. if (count !== undefined) {
  2337. let names = [];
  2338. for (let i = 0; i < count; ++i) {
  2339. // We are going to assume UTF-8 for filenames despite the SFTPv3
  2340. // spec not specifying an encoding because the specs for newer
  2341. // versions of the protocol all explicitly specify UTF-8 for
  2342. // filenames
  2343. const filename = bufferParser.readString(true);
  2344. // `longname` only exists in SFTPv3 and since it typically will
  2345. // contain the filename, we assume it is also UTF-8
  2346. const longname = bufferParser.readString(true);
  2347. const attrs = readAttrs(sftp._biOpt);
  2348. if (attrs === undefined) {
  2349. names = undefined;
  2350. break;
  2351. }
  2352. names.push({ filename, longname, attrs });
  2353. }
  2354. if (names !== undefined) {
  2355. sftp._debug && sftp._debug(
  2356. `SFTP: Inbound: Received NAME (id:${reqID}, ${names.length})`
  2357. );
  2358. bufferParser.clear();
  2359. if (req && typeof req.cb === 'function')
  2360. req.cb(undefined, names);
  2361. return;
  2362. }
  2363. }
  2364. bufferParser.clear();
  2365. return doFatalSFTPError(sftp, 'Malformed NAME packet');
  2366. },
  2367. [RESPONSE.ATTRS]: (sftp, payload) => {
  2368. bufferParser.init(payload, 1);
  2369. const reqID = bufferParser.readUInt32BE();
  2370. let req;
  2371. if (reqID !== undefined) {
  2372. req = sftp._requests[reqID];
  2373. delete sftp._requests[reqID];
  2374. }
  2375. /*
  2376. ATTRS attrs
  2377. */
  2378. const attrs = readAttrs(sftp._biOpt);
  2379. bufferParser.clear();
  2380. if (attrs !== undefined) {
  2381. sftp._debug && sftp._debug(`SFTP: Inbound: Received ATTRS (id:${reqID})`);
  2382. if (req && typeof req.cb === 'function')
  2383. req.cb(undefined, attrs);
  2384. return;
  2385. }
  2386. return doFatalSFTPError(sftp, 'Malformed ATTRS packet');
  2387. },
  2388. [RESPONSE.EXTENDED]: (sftp, payload) => {
  2389. bufferParser.init(payload, 1);
  2390. const reqID = bufferParser.readUInt32BE();
  2391. if (reqID !== undefined) {
  2392. const req = sftp._requests[reqID];
  2393. if (req) {
  2394. delete sftp._requests[reqID];
  2395. switch (req.extended) {
  2396. case 'statvfs@openssh.com':
  2397. case 'fstatvfs@openssh.com': {
  2398. /*
  2399. uint64 f_bsize // file system block size
  2400. uint64 f_frsize // fundamental fs block size
  2401. uint64 f_blocks // number of blocks (unit f_frsize)
  2402. uint64 f_bfree // free blocks in file system
  2403. uint64 f_bavail // free blocks for non-root
  2404. uint64 f_files // total file inodes
  2405. uint64 f_ffree // free file inodes
  2406. uint64 f_favail // free file inodes for to non-root
  2407. uint64 f_fsid // file system id
  2408. uint64 f_flag // bit mask of f_flag values
  2409. uint64 f_namemax // maximum filename length
  2410. */
  2411. const biOpt = sftp._biOpt;
  2412. const stats = {
  2413. f_bsize: bufferParser.readUInt64BE(biOpt),
  2414. f_frsize: bufferParser.readUInt64BE(biOpt),
  2415. f_blocks: bufferParser.readUInt64BE(biOpt),
  2416. f_bfree: bufferParser.readUInt64BE(biOpt),
  2417. f_bavail: bufferParser.readUInt64BE(biOpt),
  2418. f_files: bufferParser.readUInt64BE(biOpt),
  2419. f_ffree: bufferParser.readUInt64BE(biOpt),
  2420. f_favail: bufferParser.readUInt64BE(biOpt),
  2421. f_sid: bufferParser.readUInt64BE(biOpt),
  2422. f_flag: bufferParser.readUInt64BE(biOpt),
  2423. f_namemax: bufferParser.readUInt64BE(biOpt),
  2424. };
  2425. if (stats.f_namemax === undefined)
  2426. break;
  2427. if (sftp._debug) {
  2428. sftp._debug(
  2429. 'SFTP: Inbound: Received EXTENDED_REPLY '
  2430. + `(id:${reqID}, ${req.extended})`
  2431. );
  2432. }
  2433. bufferParser.clear();
  2434. if (typeof req.cb === 'function')
  2435. req.cb(undefined, stats);
  2436. return;
  2437. }
  2438. case 'limits@openssh.com': {
  2439. /*
  2440. uint64 max-packet-length
  2441. uint64 max-read-length
  2442. uint64 max-write-length
  2443. uint64 max-open-handles
  2444. */
  2445. const limits = {
  2446. maxPktLen: bufferParser.readUInt64BE(),
  2447. maxReadLen: bufferParser.readUInt64BE(),
  2448. maxWriteLen: bufferParser.readUInt64BE(),
  2449. maxOpenHandles: bufferParser.readUInt64BE(),
  2450. };
  2451. if (limits.maxOpenHandles === undefined)
  2452. break;
  2453. if (sftp._debug) {
  2454. sftp._debug(
  2455. 'SFTP: Inbound: Received EXTENDED_REPLY '
  2456. + `(id:${reqID}, ${req.extended})`
  2457. );
  2458. }
  2459. bufferParser.clear();
  2460. if (typeof req.cb === 'function')
  2461. req.cb(undefined, limits);
  2462. return;
  2463. }
  2464. default:
  2465. // Unknown extended request
  2466. sftp._debug && sftp._debug(
  2467. `SFTP: Inbound: Received EXTENDED_REPLY (id:${reqID}, ???)`
  2468. );
  2469. bufferParser.clear();
  2470. if (typeof req.cb === 'function')
  2471. req.cb();
  2472. return;
  2473. }
  2474. } else {
  2475. sftp._debug && sftp._debug(
  2476. `SFTP: Inbound: Received EXTENDED_REPLY (id:${reqID}, ???)`
  2477. );
  2478. bufferParser.clear();
  2479. return;
  2480. }
  2481. }
  2482. bufferParser.clear();
  2483. return doFatalSFTPError(sftp, 'Malformed EXTENDED_REPLY packet');
  2484. },
  2485. };
  2486. const SERVER_HANDLERS = {
  2487. [REQUEST.INIT]: (sftp, payload) => {
  2488. if (sftp._version !== -1)
  2489. return doFatalSFTPError(sftp, 'Duplicate INIT packet');
  2490. const extensions = {};
  2491. /*
  2492. uint32 version
  2493. <extension data>
  2494. */
  2495. bufferParser.init(payload, 1);
  2496. let version = bufferParser.readUInt32BE();
  2497. while (bufferParser.avail()) {
  2498. const extName = bufferParser.readString(true);
  2499. const extData = bufferParser.readString(true);
  2500. if (extData === undefined) {
  2501. version = undefined;
  2502. break;
  2503. }
  2504. extensions[extName] = extData;
  2505. }
  2506. bufferParser.clear();
  2507. if (version === undefined)
  2508. return doFatalSFTPError(sftp, 'Malformed INIT packet');
  2509. if (sftp._debug) {
  2510. const names = Object.keys(extensions);
  2511. if (names.length) {
  2512. sftp._debug(
  2513. `SFTP: Inbound: Received INIT (v${version}, exts:${names})`
  2514. );
  2515. } else {
  2516. sftp._debug(`SFTP: Inbound: Received INIT (v${version})`);
  2517. }
  2518. }
  2519. sendOrBuffer(sftp, SERVER_VERSION_BUFFER);
  2520. sftp._version = version;
  2521. sftp._extensions = extensions;
  2522. sftp.emit('ready');
  2523. },
  2524. [REQUEST.OPEN]: (sftp, payload) => {
  2525. bufferParser.init(payload, 1);
  2526. const reqID = bufferParser.readUInt32BE();
  2527. /*
  2528. string filename
  2529. uint32 pflags
  2530. ATTRS attrs
  2531. */
  2532. const filename = bufferParser.readString(true);
  2533. const pflags = bufferParser.readUInt32BE();
  2534. const attrs = readAttrs(sftp._biOpt);
  2535. bufferParser.clear();
  2536. if (attrs === undefined)
  2537. return doFatalSFTPError(sftp, 'Malformed OPEN packet');
  2538. sftp._debug && sftp._debug(`SFTP: Inbound: Received OPEN (id:${reqID})`);
  2539. if (!sftp.emit('OPEN', reqID, filename, pflags, attrs)) {
  2540. // Automatically reject request if no handler for request type
  2541. sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED);
  2542. }
  2543. },
  2544. [REQUEST.CLOSE]: (sftp, payload) => {
  2545. bufferParser.init(payload, 1);
  2546. const reqID = bufferParser.readUInt32BE();
  2547. /*
  2548. string handle
  2549. */
  2550. const handle = bufferParser.readString();
  2551. bufferParser.clear();
  2552. if (handle === undefined || handle.length > 256)
  2553. return doFatalSFTPError(sftp, 'Malformed CLOSE packet');
  2554. sftp._debug && sftp._debug(`SFTP: Inbound: Received CLOSE (id:${reqID})`);
  2555. if (!sftp.emit('CLOSE', reqID, handle)) {
  2556. // Automatically reject request if no handler for request type
  2557. sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED);
  2558. }
  2559. },
  2560. [REQUEST.READ]: (sftp, payload) => {
  2561. bufferParser.init(payload, 1);
  2562. const reqID = bufferParser.readUInt32BE();
  2563. /*
  2564. string handle
  2565. uint64 offset
  2566. uint32 len
  2567. */
  2568. const handle = bufferParser.readString();
  2569. const offset = bufferParser.readUInt64BE(sftp._biOpt);
  2570. const len = bufferParser.readUInt32BE();
  2571. bufferParser.clear();
  2572. if (len === undefined || handle.length > 256)
  2573. return doFatalSFTPError(sftp, 'Malformed READ packet');
  2574. sftp._debug && sftp._debug(`SFTP: Inbound: Received READ (id:${reqID})`);
  2575. if (!sftp.emit('READ', reqID, handle, offset, len)) {
  2576. // Automatically reject request if no handler for request type
  2577. sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED);
  2578. }
  2579. },
  2580. [REQUEST.WRITE]: (sftp, payload) => {
  2581. bufferParser.init(payload, 1);
  2582. const reqID = bufferParser.readUInt32BE();
  2583. /*
  2584. string handle
  2585. uint64 offset
  2586. string data
  2587. */
  2588. const handle = bufferParser.readString();
  2589. const offset = bufferParser.readUInt64BE(sftp._biOpt);
  2590. const data = bufferParser.readString();
  2591. bufferParser.clear();
  2592. if (data === undefined || handle.length > 256)
  2593. return doFatalSFTPError(sftp, 'Malformed WRITE packet');
  2594. sftp._debug && sftp._debug(`SFTP: Inbound: Received WRITE (id:${reqID})`);
  2595. if (!sftp.emit('WRITE', reqID, handle, offset, data)) {
  2596. // Automatically reject request if no handler for request type
  2597. sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED);
  2598. }
  2599. },
  2600. [REQUEST.LSTAT]: (sftp, payload) => {
  2601. bufferParser.init(payload, 1);
  2602. const reqID = bufferParser.readUInt32BE();
  2603. /*
  2604. string path
  2605. */
  2606. const path = bufferParser.readString(true);
  2607. bufferParser.clear();
  2608. if (path === undefined)
  2609. return doFatalSFTPError(sftp, 'Malformed LSTAT packet');
  2610. sftp._debug && sftp._debug(`SFTP: Inbound: Received LSTAT (id:${reqID})`);
  2611. if (!sftp.emit('LSTAT', reqID, path)) {
  2612. // Automatically reject request if no handler for request type
  2613. sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED);
  2614. }
  2615. },
  2616. [REQUEST.FSTAT]: (sftp, payload) => {
  2617. bufferParser.init(payload, 1);
  2618. const reqID = bufferParser.readUInt32BE();
  2619. /*
  2620. string handle
  2621. */
  2622. const handle = bufferParser.readString();
  2623. bufferParser.clear();
  2624. if (handle === undefined || handle.length > 256)
  2625. return doFatalSFTPError(sftp, 'Malformed FSTAT packet');
  2626. sftp._debug && sftp._debug(`SFTP: Inbound: Received FSTAT (id:${reqID})`);
  2627. if (!sftp.emit('FSTAT', reqID, handle)) {
  2628. // Automatically reject request if no handler for request type
  2629. sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED);
  2630. }
  2631. },
  2632. [REQUEST.SETSTAT]: (sftp, payload) => {
  2633. bufferParser.init(payload, 1);
  2634. const reqID = bufferParser.readUInt32BE();
  2635. /*
  2636. string path
  2637. ATTRS attrs
  2638. */
  2639. const path = bufferParser.readString(true);
  2640. const attrs = readAttrs(sftp._biOpt);
  2641. bufferParser.clear();
  2642. if (attrs === undefined)
  2643. return doFatalSFTPError(sftp, 'Malformed SETSTAT packet');
  2644. sftp._debug && sftp._debug(`SFTP: Inbound: Received SETSTAT (id:${reqID})`);
  2645. if (!sftp.emit('SETSTAT', reqID, path, attrs)) {
  2646. // Automatically reject request if no handler for request type
  2647. sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED);
  2648. }
  2649. },
  2650. [REQUEST.FSETSTAT]: (sftp, payload) => {
  2651. bufferParser.init(payload, 1);
  2652. const reqID = bufferParser.readUInt32BE();
  2653. /*
  2654. string handle
  2655. ATTRS attrs
  2656. */
  2657. const handle = bufferParser.readString();
  2658. const attrs = readAttrs(sftp._biOpt);
  2659. bufferParser.clear();
  2660. if (attrs === undefined || handle.length > 256)
  2661. return doFatalSFTPError(sftp, 'Malformed FSETSTAT packet');
  2662. sftp._debug && sftp._debug(
  2663. `SFTP: Inbound: Received FSETSTAT (id:${reqID})`
  2664. );
  2665. if (!sftp.emit('FSETSTAT', reqID, handle, attrs)) {
  2666. // Automatically reject request if no handler for request type
  2667. sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED);
  2668. }
  2669. },
  2670. [REQUEST.OPENDIR]: (sftp, payload) => {
  2671. bufferParser.init(payload, 1);
  2672. const reqID = bufferParser.readUInt32BE();
  2673. /*
  2674. string path
  2675. */
  2676. const path = bufferParser.readString(true);
  2677. bufferParser.clear();
  2678. if (path === undefined)
  2679. return doFatalSFTPError(sftp, 'Malformed OPENDIR packet');
  2680. sftp._debug && sftp._debug(`SFTP: Inbound: Received OPENDIR (id:${reqID})`);
  2681. if (!sftp.emit('OPENDIR', reqID, path)) {
  2682. // Automatically reject request if no handler for request type
  2683. sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED);
  2684. }
  2685. },
  2686. [REQUEST.READDIR]: (sftp, payload) => {
  2687. bufferParser.init(payload, 1);
  2688. const reqID = bufferParser.readUInt32BE();
  2689. /*
  2690. string handle
  2691. */
  2692. const handle = bufferParser.readString();
  2693. bufferParser.clear();
  2694. if (handle === undefined || handle.length > 256)
  2695. return doFatalSFTPError(sftp, 'Malformed READDIR packet');
  2696. sftp._debug && sftp._debug(`SFTP: Inbound: Received READDIR (id:${reqID})`);
  2697. if (!sftp.emit('READDIR', reqID, handle)) {
  2698. // Automatically reject request if no handler for request type
  2699. sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED);
  2700. }
  2701. },
  2702. [REQUEST.REMOVE]: (sftp, payload) => {
  2703. bufferParser.init(payload, 1);
  2704. const reqID = bufferParser.readUInt32BE();
  2705. /*
  2706. string path
  2707. */
  2708. const path = bufferParser.readString(true);
  2709. bufferParser.clear();
  2710. if (path === undefined)
  2711. return doFatalSFTPError(sftp, 'Malformed REMOVE packet');
  2712. sftp._debug && sftp._debug(`SFTP: Inbound: Received REMOVE (id:${reqID})`);
  2713. if (!sftp.emit('REMOVE', reqID, path)) {
  2714. // Automatically reject request if no handler for request type
  2715. sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED);
  2716. }
  2717. },
  2718. [REQUEST.MKDIR]: (sftp, payload) => {
  2719. bufferParser.init(payload, 1);
  2720. const reqID = bufferParser.readUInt32BE();
  2721. /*
  2722. string path
  2723. ATTRS attrs
  2724. */
  2725. const path = bufferParser.readString(true);
  2726. const attrs = readAttrs(sftp._biOpt);
  2727. bufferParser.clear();
  2728. if (attrs === undefined)
  2729. return doFatalSFTPError(sftp, 'Malformed MKDIR packet');
  2730. sftp._debug && sftp._debug(`SFTP: Inbound: Received MKDIR (id:${reqID})`);
  2731. if (!sftp.emit('MKDIR', reqID, path, attrs)) {
  2732. // Automatically reject request if no handler for request type
  2733. sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED);
  2734. }
  2735. },
  2736. [REQUEST.RMDIR]: (sftp, payload) => {
  2737. bufferParser.init(payload, 1);
  2738. const reqID = bufferParser.readUInt32BE();
  2739. /*
  2740. string path
  2741. */
  2742. const path = bufferParser.readString(true);
  2743. bufferParser.clear();
  2744. if (path === undefined)
  2745. return doFatalSFTPError(sftp, 'Malformed RMDIR packet');
  2746. sftp._debug && sftp._debug(`SFTP: Inbound: Received RMDIR (id:${reqID})`);
  2747. if (!sftp.emit('RMDIR', reqID, path)) {
  2748. // Automatically reject request if no handler for request type
  2749. sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED);
  2750. }
  2751. },
  2752. [REQUEST.REALPATH]: (sftp, payload) => {
  2753. bufferParser.init(payload, 1);
  2754. const reqID = bufferParser.readUInt32BE();
  2755. /*
  2756. string path
  2757. */
  2758. const path = bufferParser.readString(true);
  2759. bufferParser.clear();
  2760. if (path === undefined)
  2761. return doFatalSFTPError(sftp, 'Malformed REALPATH packet');
  2762. sftp._debug && sftp._debug(
  2763. `SFTP: Inbound: Received REALPATH (id:${reqID})`
  2764. );
  2765. if (!sftp.emit('REALPATH', reqID, path)) {
  2766. // Automatically reject request if no handler for request type
  2767. sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED);
  2768. }
  2769. },
  2770. [REQUEST.STAT]: (sftp, payload) => {
  2771. bufferParser.init(payload, 1);
  2772. const reqID = bufferParser.readUInt32BE();
  2773. /*
  2774. string path
  2775. */
  2776. const path = bufferParser.readString(true);
  2777. bufferParser.clear();
  2778. if (path === undefined)
  2779. return doFatalSFTPError(sftp, 'Malformed STAT packet');
  2780. sftp._debug && sftp._debug(`SFTP: Inbound: Received STAT (id:${reqID})`);
  2781. if (!sftp.emit('STAT', reqID, path)) {
  2782. // Automatically reject request if no handler for request type
  2783. sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED);
  2784. }
  2785. },
  2786. [REQUEST.RENAME]: (sftp, payload) => {
  2787. bufferParser.init(payload, 1);
  2788. const reqID = bufferParser.readUInt32BE();
  2789. /*
  2790. string oldpath
  2791. string newpath
  2792. */
  2793. const oldPath = bufferParser.readString(true);
  2794. const newPath = bufferParser.readString(true);
  2795. bufferParser.clear();
  2796. if (newPath === undefined)
  2797. return doFatalSFTPError(sftp, 'Malformed RENAME packet');
  2798. sftp._debug && sftp._debug(`SFTP: Inbound: Received RENAME (id:${reqID})`);
  2799. if (!sftp.emit('RENAME', reqID, oldPath, newPath)) {
  2800. // Automatically reject request if no handler for request type
  2801. sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED);
  2802. }
  2803. },
  2804. [REQUEST.READLINK]: (sftp, payload) => {
  2805. bufferParser.init(payload, 1);
  2806. const reqID = bufferParser.readUInt32BE();
  2807. /*
  2808. string path
  2809. */
  2810. const path = bufferParser.readString(true);
  2811. bufferParser.clear();
  2812. if (path === undefined)
  2813. return doFatalSFTPError(sftp, 'Malformed READLINK packet');
  2814. sftp._debug && sftp._debug(
  2815. `SFTP: Inbound: Received READLINK (id:${reqID})`
  2816. );
  2817. if (!sftp.emit('READLINK', reqID, path)) {
  2818. // Automatically reject request if no handler for request type
  2819. sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED);
  2820. }
  2821. },
  2822. [REQUEST.SYMLINK]: (sftp, payload) => {
  2823. bufferParser.init(payload, 1);
  2824. const reqID = bufferParser.readUInt32BE();
  2825. /*
  2826. string linkpath
  2827. string targetpath
  2828. */
  2829. const linkPath = bufferParser.readString(true);
  2830. const targetPath = bufferParser.readString(true);
  2831. bufferParser.clear();
  2832. if (targetPath === undefined)
  2833. return doFatalSFTPError(sftp, 'Malformed SYMLINK packet');
  2834. sftp._debug && sftp._debug(`SFTP: Inbound: Received SYMLINK (id:${reqID})`);
  2835. let handled;
  2836. if (sftp._isOpenSSH) {
  2837. // OpenSSH has linkpath and targetpath positions switched
  2838. handled = sftp.emit('SYMLINK', reqID, targetPath, linkPath);
  2839. } else {
  2840. handled = sftp.emit('SYMLINK', reqID, linkPath, targetPath);
  2841. }
  2842. if (!handled) {
  2843. // Automatically reject request if no handler for request type
  2844. sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED);
  2845. }
  2846. },
  2847. [REQUEST.EXTENDED]: (sftp, payload) => {
  2848. bufferParser.init(payload, 1);
  2849. const reqID = bufferParser.readUInt32BE();
  2850. /*
  2851. string extended-request
  2852. ... any request-specific data ...
  2853. */
  2854. const extName = bufferParser.readString(true);
  2855. if (extName === undefined) {
  2856. bufferParser.clear();
  2857. return doFatalSFTPError(sftp, 'Malformed EXTENDED packet');
  2858. }
  2859. let extData;
  2860. if (bufferParser.avail())
  2861. extData = bufferParser.readRaw();
  2862. bufferParser.clear();
  2863. sftp._debug && sftp._debug(
  2864. `SFTP: Inbound: Received EXTENDED (id:${reqID})`
  2865. );
  2866. if (!sftp.emit('EXTENDED', reqID, extName, extData)) {
  2867. // Automatically reject request if no handler for request type
  2868. sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED);
  2869. }
  2870. },
  2871. };
  2872. // =============================================================================
  2873. // ReadStream/WriteStream-related ==============================================
  2874. // =============================================================================
  2875. const {
  2876. ERR_INVALID_ARG_TYPE,
  2877. ERR_OUT_OF_RANGE,
  2878. validateNumber
  2879. } = require('./node-fs-compat');
  2880. const kMinPoolSpace = 128;
  2881. let pool;
  2882. // It can happen that we expect to read a large chunk of data, and reserve
  2883. // a large chunk of the pool accordingly, but the read() call only filled
  2884. // a portion of it. If a concurrently executing read() then uses the same pool,
  2885. // the "reserved" portion cannot be used, so we allow it to be re-used as a
  2886. // new pool later.
  2887. const poolFragments = [];
  2888. function allocNewPool(poolSize) {
  2889. if (poolFragments.length > 0)
  2890. pool = poolFragments.pop();
  2891. else
  2892. pool = Buffer.allocUnsafe(poolSize);
  2893. pool.used = 0;
  2894. }
  2895. // Check the `this.start` and `this.end` of stream.
  2896. function checkPosition(pos, name) {
  2897. if (!Number.isSafeInteger(pos)) {
  2898. validateNumber(pos, name);
  2899. if (!Number.isInteger(pos))
  2900. throw new ERR_OUT_OF_RANGE(name, 'an integer', pos);
  2901. throw new ERR_OUT_OF_RANGE(name, '>= 0 and <= 2 ** 53 - 1', pos);
  2902. }
  2903. if (pos < 0)
  2904. throw new ERR_OUT_OF_RANGE(name, '>= 0 and <= 2 ** 53 - 1', pos);
  2905. }
  2906. function roundUpToMultipleOf8(n) {
  2907. return (n + 7) & ~7; // Align to 8 byte boundary.
  2908. }
  2909. function ReadStream(sftp, path, options) {
  2910. if (options === undefined)
  2911. options = {};
  2912. else if (typeof options === 'string')
  2913. options = { encoding: options };
  2914. else if (options === null || typeof options !== 'object')
  2915. throw new TypeError('"options" argument must be a string or an object');
  2916. else
  2917. options = Object.create(options);
  2918. // A little bit bigger buffer and water marks by default
  2919. if (options.highWaterMark === undefined)
  2920. options.highWaterMark = 64 * 1024;
  2921. // For backwards compat do not emit close on destroy.
  2922. options.emitClose = false;
  2923. options.autoDestroy = false; // Node 14 major change.
  2924. ReadableStream.call(this, options);
  2925. this.path = path;
  2926. this.flags = options.flags === undefined ? 'r' : options.flags;
  2927. this.mode = options.mode === undefined ? 0o666 : options.mode;
  2928. this.start = options.start;
  2929. this.end = options.end;
  2930. this.autoClose = options.autoClose === undefined ? true : options.autoClose;
  2931. this.pos = 0;
  2932. this.bytesRead = 0;
  2933. this.closed = false;
  2934. this.handle = options.handle === undefined ? null : options.handle;
  2935. this.sftp = sftp;
  2936. this._opening = false;
  2937. if (this.start !== undefined) {
  2938. checkPosition(this.start, 'start');
  2939. this.pos = this.start;
  2940. }
  2941. if (this.end === undefined) {
  2942. this.end = Infinity;
  2943. } else if (this.end !== Infinity) {
  2944. checkPosition(this.end, 'end');
  2945. if (this.start !== undefined && this.start > this.end) {
  2946. throw new ERR_OUT_OF_RANGE(
  2947. 'start',
  2948. `<= "end" (here: ${this.end})`,
  2949. this.start
  2950. );
  2951. }
  2952. }
  2953. this.on('end', function() {
  2954. if (this.autoClose)
  2955. this.destroy();
  2956. });
  2957. if (!Buffer.isBuffer(this.handle))
  2958. this.open();
  2959. }
  2960. inherits(ReadStream, ReadableStream);
  2961. ReadStream.prototype.open = function() {
  2962. if (this._opening)
  2963. return;
  2964. this._opening = true;
  2965. this.sftp.open(this.path, this.flags, this.mode, (er, handle) => {
  2966. this._opening = false;
  2967. if (er) {
  2968. this.emit('error', er);
  2969. if (this.autoClose)
  2970. this.destroy();
  2971. return;
  2972. }
  2973. this.handle = handle;
  2974. this.emit('open', handle);
  2975. this.emit('ready');
  2976. // Start the flow of data.
  2977. this.read();
  2978. });
  2979. };
  2980. ReadStream.prototype._read = function(n) {
  2981. if (!Buffer.isBuffer(this.handle))
  2982. return this.once('open', () => this._read(n));
  2983. // XXX: safe to remove this?
  2984. if (this.destroyed)
  2985. return;
  2986. if (!pool || pool.length - pool.used < kMinPoolSpace) {
  2987. // Discard the old pool.
  2988. allocNewPool(this.readableHighWaterMark
  2989. || this._readableState.highWaterMark);
  2990. }
  2991. // Grab another reference to the pool in the case that while we're
  2992. // in the thread pool another read() finishes up the pool, and
  2993. // allocates a new one.
  2994. const thisPool = pool;
  2995. let toRead = Math.min(pool.length - pool.used, n);
  2996. const start = pool.used;
  2997. if (this.end !== undefined)
  2998. toRead = Math.min(this.end - this.pos + 1, toRead);
  2999. // Already read everything we were supposed to read!
  3000. // treat as EOF.
  3001. if (toRead <= 0)
  3002. return this.push(null);
  3003. // the actual read.
  3004. this.sftp.read(this.handle,
  3005. pool,
  3006. pool.used,
  3007. toRead,
  3008. this.pos,
  3009. (er, bytesRead) => {
  3010. if (er) {
  3011. this.emit('error', er);
  3012. if (this.autoClose)
  3013. this.destroy();
  3014. return;
  3015. }
  3016. let b = null;
  3017. // Now that we know how much data we have actually read, re-wind the
  3018. // 'used' field if we can, and otherwise allow the remainder of our
  3019. // reservation to be used as a new pool later.
  3020. if (start + toRead === thisPool.used && thisPool === pool) {
  3021. thisPool.used = roundUpToMultipleOf8(thisPool.used + bytesRead - toRead);
  3022. } else {
  3023. // Round down to the next lowest multiple of 8 to ensure the new pool
  3024. // fragment start and end positions are aligned to an 8 byte boundary.
  3025. const alignedEnd = (start + toRead) & ~7;
  3026. const alignedStart = roundUpToMultipleOf8(start + bytesRead);
  3027. if (alignedEnd - alignedStart >= kMinPoolSpace)
  3028. poolFragments.push(thisPool.slice(alignedStart, alignedEnd));
  3029. }
  3030. if (bytesRead > 0) {
  3031. this.bytesRead += bytesRead;
  3032. b = thisPool.slice(start, start + bytesRead);
  3033. }
  3034. // Move the pool positions, and internal position for reading.
  3035. this.pos += bytesRead;
  3036. this.push(b);
  3037. });
  3038. pool.used = roundUpToMultipleOf8(pool.used + toRead);
  3039. };
  3040. ReadStream.prototype._destroy = function(err, cb) {
  3041. if (this._opening && !Buffer.isBuffer(this.handle)) {
  3042. this.once('open', closeStream.bind(null, this, cb, err));
  3043. return;
  3044. }
  3045. closeStream(this, cb, err);
  3046. this.handle = null;
  3047. this._opening = false;
  3048. };
  3049. function closeStream(stream, cb, err) {
  3050. if (!stream.handle)
  3051. return onclose();
  3052. stream.sftp.close(stream.handle, onclose);
  3053. function onclose(er) {
  3054. er = er || err;
  3055. cb(er);
  3056. stream.closed = true;
  3057. if (!er)
  3058. stream.emit('close');
  3059. }
  3060. }
  3061. ReadStream.prototype.close = function(cb) {
  3062. this.destroy(null, cb);
  3063. };
  3064. Object.defineProperty(ReadStream.prototype, 'pending', {
  3065. get() {
  3066. return this.handle === null;
  3067. },
  3068. configurable: true
  3069. });
  3070. // TODO: add `concurrency` setting to allow more than one in-flight WRITE
  3071. // request to server to improve throughput
  3072. function WriteStream(sftp, path, options) {
  3073. if (options === undefined)
  3074. options = {};
  3075. else if (typeof options === 'string')
  3076. options = { encoding: options };
  3077. else if (options === null || typeof options !== 'object')
  3078. throw new TypeError('"options" argument must be a string or an object');
  3079. else
  3080. options = Object.create(options);
  3081. // For backwards compat do not emit close on destroy.
  3082. options.emitClose = false;
  3083. options.autoDestroy = false; // Node 14 major change.
  3084. WritableStream.call(this, options);
  3085. this.path = path;
  3086. this.flags = options.flags === undefined ? 'w' : options.flags;
  3087. this.mode = options.mode === undefined ? 0o666 : options.mode;
  3088. this.start = options.start;
  3089. this.autoClose = options.autoClose === undefined ? true : options.autoClose;
  3090. this.pos = 0;
  3091. this.bytesWritten = 0;
  3092. this.closed = false;
  3093. this.handle = options.handle === undefined ? null : options.handle;
  3094. this.sftp = sftp;
  3095. this._opening = false;
  3096. if (this.start !== undefined) {
  3097. checkPosition(this.start, 'start');
  3098. this.pos = this.start;
  3099. }
  3100. if (options.encoding)
  3101. this.setDefaultEncoding(options.encoding);
  3102. // Node v6.x only
  3103. this.on('finish', function() {
  3104. if (this._writableState.finalCalled)
  3105. return;
  3106. if (this.autoClose)
  3107. this.destroy();
  3108. });
  3109. if (!Buffer.isBuffer(this.handle))
  3110. this.open();
  3111. }
  3112. inherits(WriteStream, WritableStream);
  3113. WriteStream.prototype._final = function(cb) {
  3114. if (this.autoClose)
  3115. this.destroy();
  3116. cb();
  3117. };
  3118. WriteStream.prototype.open = function() {
  3119. if (this._opening)
  3120. return;
  3121. this._opening = true;
  3122. this.sftp.open(this.path, this.flags, this.mode, (er, handle) => {
  3123. this._opening = false;
  3124. if (er) {
  3125. this.emit('error', er);
  3126. if (this.autoClose)
  3127. this.destroy();
  3128. return;
  3129. }
  3130. this.handle = handle;
  3131. const tryAgain = (err) => {
  3132. if (err) {
  3133. // Try chmod() for sftp servers that may not support fchmod() for
  3134. // whatever reason
  3135. this.sftp.chmod(this.path, this.mode, (err_) => tryAgain());
  3136. return;
  3137. }
  3138. // SFTPv3 requires absolute offsets, no matter the open flag used
  3139. if (this.flags[0] === 'a') {
  3140. const tryStat = (err, st) => {
  3141. if (err) {
  3142. // Try stat() for sftp servers that may not support fstat() for
  3143. // whatever reason
  3144. this.sftp.stat(this.path, (err_, st_) => {
  3145. if (err_) {
  3146. this.destroy();
  3147. this.emit('error', err);
  3148. return;
  3149. }
  3150. tryStat(null, st_);
  3151. });
  3152. return;
  3153. }
  3154. this.pos = st.size;
  3155. this.emit('open', handle);
  3156. this.emit('ready');
  3157. };
  3158. this.sftp.fstat(handle, tryStat);
  3159. return;
  3160. }
  3161. this.emit('open', handle);
  3162. this.emit('ready');
  3163. };
  3164. this.sftp.fchmod(handle, this.mode, tryAgain);
  3165. });
  3166. };
  3167. WriteStream.prototype._write = function(data, encoding, cb) {
  3168. if (!Buffer.isBuffer(data)) {
  3169. const err = new ERR_INVALID_ARG_TYPE('data', 'Buffer', data);
  3170. return this.emit('error', err);
  3171. }
  3172. if (!Buffer.isBuffer(this.handle)) {
  3173. return this.once('open', function() {
  3174. this._write(data, encoding, cb);
  3175. });
  3176. }
  3177. this.sftp.write(this.handle,
  3178. data,
  3179. 0,
  3180. data.length,
  3181. this.pos,
  3182. (er, bytes) => {
  3183. if (er) {
  3184. if (this.autoClose)
  3185. this.destroy();
  3186. return cb(er);
  3187. }
  3188. this.bytesWritten += bytes;
  3189. cb();
  3190. });
  3191. this.pos += data.length;
  3192. };
  3193. WriteStream.prototype._writev = function(data, cb) {
  3194. if (!Buffer.isBuffer(this.handle)) {
  3195. return this.once('open', function() {
  3196. this._writev(data, cb);
  3197. });
  3198. }
  3199. const sftp = this.sftp;
  3200. const handle = this.handle;
  3201. let writesLeft = data.length;
  3202. const onwrite = (er, bytes) => {
  3203. if (er) {
  3204. this.destroy();
  3205. return cb(er);
  3206. }
  3207. this.bytesWritten += bytes;
  3208. if (--writesLeft === 0)
  3209. cb();
  3210. };
  3211. // TODO: try to combine chunks to reduce number of requests to the server?
  3212. for (let i = 0; i < data.length; ++i) {
  3213. const chunk = data[i].chunk;
  3214. sftp.write(handle, chunk, 0, chunk.length, this.pos, onwrite);
  3215. this.pos += chunk.length;
  3216. }
  3217. };
  3218. if (typeof WritableStream.prototype.destroy !== 'function')
  3219. WriteStream.prototype.destroy = ReadStream.prototype.destroy;
  3220. WriteStream.prototype._destroy = ReadStream.prototype._destroy;
  3221. WriteStream.prototype.close = function(cb) {
  3222. if (cb) {
  3223. if (this.closed) {
  3224. process.nextTick(cb);
  3225. return;
  3226. }
  3227. this.on('close', cb);
  3228. }
  3229. // If we are not autoClosing, we should call
  3230. // destroy on 'finish'.
  3231. if (!this.autoClose)
  3232. this.on('finish', this.destroy.bind(this));
  3233. this.end();
  3234. };
  3235. // There is no shutdown() for files.
  3236. WriteStream.prototype.destroySoon = WriteStream.prototype.end;
  3237. Object.defineProperty(WriteStream.prototype, 'pending', {
  3238. get() {
  3239. return this.handle === null;
  3240. },
  3241. configurable: true
  3242. });
  3243. // =============================================================================
  3244. module.exports = {
  3245. flagsToString,
  3246. OPEN_MODE,
  3247. SFTP,
  3248. Stats,
  3249. STATUS_CODE,
  3250. stringToFlags,
  3251. };