channel.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566
  1. // Copyright 2011 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package ssh
  5. import (
  6. "errors"
  7. "fmt"
  8. "io"
  9. "sync"
  10. "sync/atomic"
  11. )
  12. // extendedDataTypeCode identifies an OpenSSL extended data type. See RFC 4254,
  13. // section 5.2.
  14. type extendedDataTypeCode uint32
  15. const (
  16. // extendedDataStderr is the extended data type that is used for stderr.
  17. extendedDataStderr extendedDataTypeCode = 1
  18. // minPacketLength defines the smallest valid packet
  19. minPacketLength = 9
  20. )
  21. // A Channel is an ordered, reliable, duplex stream that is multiplexed over an
  22. // SSH connection. Channel.Read can return a ChannelRequest as an error.
  23. type Channel interface {
  24. // Accept accepts the channel creation request.
  25. Accept() error
  26. // Reject rejects the channel creation request. After calling this, no
  27. // other methods on the Channel may be called. If they are then the
  28. // peer is likely to signal a protocol error and drop the connection.
  29. Reject(reason RejectionReason, message string) error
  30. // Read may return a ChannelRequest as an error.
  31. Read(data []byte) (int, error)
  32. Write(data []byte) (int, error)
  33. Close() error
  34. // Stderr returns an io.Writer that writes to this channel with the
  35. // extended data type set to stderr.
  36. Stderr() io.Writer
  37. // AckRequest either sends an ack or nack to the channel request.
  38. AckRequest(ok bool) error
  39. // ChannelType returns the type of the channel, as supplied by the
  40. // client.
  41. ChannelType() string
  42. // ExtraData returns the arbitary payload for this channel, as supplied
  43. // by the client. This data is specific to the channel type.
  44. ExtraData() []byte
  45. }
  46. // ChannelRequest represents a request sent on a channel, outside of the normal
  47. // stream of bytes. It may result from calling Read on a Channel.
  48. type ChannelRequest struct {
  49. Request string
  50. WantReply bool
  51. Payload []byte
  52. }
  53. func (c ChannelRequest) Error() string {
  54. return "ssh: channel request received"
  55. }
  56. // RejectionReason is an enumeration used when rejecting channel creation
  57. // requests. See RFC 4254, section 5.1.
  58. type RejectionReason uint32
  59. const (
  60. Prohibited RejectionReason = iota + 1
  61. ConnectionFailed
  62. UnknownChannelType
  63. ResourceShortage
  64. )
  65. type channel struct {
  66. conn // the underlying transport
  67. localId, remoteId uint32
  68. remoteWin window
  69. maxPacket uint32
  70. isClosed uint32 // atomic bool, non zero if true
  71. }
  72. func (c *channel) sendWindowAdj(n int) error {
  73. msg := windowAdjustMsg{
  74. PeersId: c.remoteId,
  75. AdditionalBytes: uint32(n),
  76. }
  77. return c.writePacket(marshal(msgChannelWindowAdjust, msg))
  78. }
  79. // sendEOF sends EOF to the remote side. RFC 4254 Section 5.3
  80. func (c *channel) sendEOF() error {
  81. return c.writePacket(marshal(msgChannelEOF, channelEOFMsg{
  82. PeersId: c.remoteId,
  83. }))
  84. }
  85. // sendClose informs the remote side of our intent to close the channel.
  86. func (c *channel) sendClose() error {
  87. return c.conn.writePacket(marshal(msgChannelClose, channelCloseMsg{
  88. PeersId: c.remoteId,
  89. }))
  90. }
  91. func (c *channel) sendChannelOpenFailure(reason RejectionReason, message string) error {
  92. reject := channelOpenFailureMsg{
  93. PeersId: c.remoteId,
  94. Reason: reason,
  95. Message: message,
  96. Language: "en",
  97. }
  98. return c.writePacket(marshal(msgChannelOpenFailure, reject))
  99. }
  100. func (c *channel) writePacket(b []byte) error {
  101. if c.closed() {
  102. return io.EOF
  103. }
  104. if uint32(len(b)) > c.maxPacket {
  105. return fmt.Errorf("ssh: cannot write %d bytes, maxPacket is %d bytes", len(b), c.maxPacket)
  106. }
  107. return c.conn.writePacket(b)
  108. }
  109. func (c *channel) closed() bool {
  110. return atomic.LoadUint32(&c.isClosed) > 0
  111. }
  112. func (c *channel) setClosed() bool {
  113. return atomic.CompareAndSwapUint32(&c.isClosed, 0, 1)
  114. }
  115. type serverChan struct {
  116. channel
  117. // immutable once created
  118. chanType string
  119. extraData []byte
  120. serverConn *ServerConn
  121. myWindow uint32
  122. theyClosed bool // indicates the close msg has been received from the remote side
  123. theySentEOF bool
  124. isDead uint32
  125. err error
  126. pendingRequests []ChannelRequest
  127. pendingData []byte
  128. head, length int
  129. // This lock is inferior to serverConn.lock
  130. cond *sync.Cond
  131. }
  132. func (c *serverChan) Accept() error {
  133. c.serverConn.lock.Lock()
  134. defer c.serverConn.lock.Unlock()
  135. if c.serverConn.err != nil {
  136. return c.serverConn.err
  137. }
  138. confirm := channelOpenConfirmMsg{
  139. PeersId: c.remoteId,
  140. MyId: c.localId,
  141. MyWindow: c.myWindow,
  142. MaxPacketSize: c.maxPacket,
  143. }
  144. return c.writePacket(marshal(msgChannelOpenConfirm, confirm))
  145. }
  146. func (c *serverChan) Reject(reason RejectionReason, message string) error {
  147. c.serverConn.lock.Lock()
  148. defer c.serverConn.lock.Unlock()
  149. if c.serverConn.err != nil {
  150. return c.serverConn.err
  151. }
  152. return c.sendChannelOpenFailure(reason, message)
  153. }
  154. func (c *serverChan) handlePacket(packet interface{}) {
  155. c.cond.L.Lock()
  156. defer c.cond.L.Unlock()
  157. switch packet := packet.(type) {
  158. case *channelRequestMsg:
  159. req := ChannelRequest{
  160. Request: packet.Request,
  161. WantReply: packet.WantReply,
  162. Payload: packet.RequestSpecificData,
  163. }
  164. c.pendingRequests = append(c.pendingRequests, req)
  165. c.cond.Signal()
  166. case *channelCloseMsg:
  167. c.theyClosed = true
  168. c.cond.Signal()
  169. case *channelEOFMsg:
  170. c.theySentEOF = true
  171. c.cond.Signal()
  172. case *windowAdjustMsg:
  173. if !c.remoteWin.add(packet.AdditionalBytes) {
  174. panic("illegal window update")
  175. }
  176. default:
  177. panic("unknown packet type")
  178. }
  179. }
  180. func (c *serverChan) handleData(data []byte) {
  181. c.cond.L.Lock()
  182. defer c.cond.L.Unlock()
  183. // The other side should never send us more than our window.
  184. if len(data)+c.length > len(c.pendingData) {
  185. // TODO(agl): we should tear down the channel with a protocol
  186. // error.
  187. return
  188. }
  189. c.myWindow -= uint32(len(data))
  190. for i := 0; i < 2; i++ {
  191. tail := c.head + c.length
  192. if tail >= len(c.pendingData) {
  193. tail -= len(c.pendingData)
  194. }
  195. n := copy(c.pendingData[tail:], data)
  196. data = data[n:]
  197. c.length += n
  198. }
  199. c.cond.Signal()
  200. }
  201. func (c *serverChan) Stderr() io.Writer {
  202. return extendedDataChannel{c: c, t: extendedDataStderr}
  203. }
  204. // extendedDataChannel is an io.Writer that writes any data to c as extended
  205. // data of the given type.
  206. type extendedDataChannel struct {
  207. t extendedDataTypeCode
  208. c *serverChan
  209. }
  210. func (edc extendedDataChannel) Write(data []byte) (n int, err error) {
  211. const headerLength = 13 // 1 byte message type, 4 bytes remoteId, 4 bytes extended message type, 4 bytes data length
  212. c := edc.c
  213. for len(data) > 0 {
  214. space := min(c.maxPacket-headerLength, len(data))
  215. if space, err = c.getWindowSpace(space); err != nil {
  216. return 0, err
  217. }
  218. todo := data
  219. if uint32(len(todo)) > space {
  220. todo = todo[:space]
  221. }
  222. packet := make([]byte, headerLength+len(todo))
  223. packet[0] = msgChannelExtendedData
  224. marshalUint32(packet[1:], c.remoteId)
  225. marshalUint32(packet[5:], uint32(edc.t))
  226. marshalUint32(packet[9:], uint32(len(todo)))
  227. copy(packet[13:], todo)
  228. if err = c.writePacket(packet); err != nil {
  229. return
  230. }
  231. n += len(todo)
  232. data = data[len(todo):]
  233. }
  234. return
  235. }
  236. func (c *serverChan) Read(data []byte) (n int, err error) {
  237. n, err, windowAdjustment := c.read(data)
  238. if windowAdjustment > 0 {
  239. packet := marshal(msgChannelWindowAdjust, windowAdjustMsg{
  240. PeersId: c.remoteId,
  241. AdditionalBytes: windowAdjustment,
  242. })
  243. err = c.writePacket(packet)
  244. }
  245. return
  246. }
  247. func (c *serverChan) read(data []byte) (n int, err error, windowAdjustment uint32) {
  248. c.cond.L.Lock()
  249. defer c.cond.L.Unlock()
  250. if c.err != nil {
  251. return 0, c.err, 0
  252. }
  253. for {
  254. if c.theySentEOF || c.theyClosed || c.dead() {
  255. return 0, io.EOF, 0
  256. }
  257. if len(c.pendingRequests) > 0 {
  258. req := c.pendingRequests[0]
  259. if len(c.pendingRequests) == 1 {
  260. c.pendingRequests = nil
  261. } else {
  262. oldPendingRequests := c.pendingRequests
  263. c.pendingRequests = make([]ChannelRequest, len(oldPendingRequests)-1)
  264. copy(c.pendingRequests, oldPendingRequests[1:])
  265. }
  266. return 0, req, 0
  267. }
  268. if c.length > 0 {
  269. tail := min(uint32(c.head+c.length), len(c.pendingData))
  270. n = copy(data, c.pendingData[c.head:tail])
  271. c.head += n
  272. c.length -= n
  273. if c.head == len(c.pendingData) {
  274. c.head = 0
  275. }
  276. windowAdjustment = uint32(len(c.pendingData)-c.length) - c.myWindow
  277. if windowAdjustment < uint32(len(c.pendingData)/2) {
  278. windowAdjustment = 0
  279. }
  280. c.myWindow += windowAdjustment
  281. return
  282. }
  283. c.cond.Wait()
  284. }
  285. panic("unreachable")
  286. }
  287. // getWindowSpace takes, at most, max bytes of space from the peer's window. It
  288. // returns the number of bytes actually reserved.
  289. func (c *serverChan) getWindowSpace(max uint32) (uint32, error) {
  290. if c.dead() || c.closed() {
  291. return 0, io.EOF
  292. }
  293. return c.remoteWin.reserve(max), nil
  294. }
  295. func (c *serverChan) dead() bool {
  296. return atomic.LoadUint32(&c.isDead) > 0
  297. }
  298. func (c *serverChan) setDead() {
  299. atomic.StoreUint32(&c.isDead, 1)
  300. }
  301. func (c *serverChan) Write(data []byte) (n int, err error) {
  302. const headerLength = 9 // 1 byte message type, 4 bytes remoteId, 4 bytes data length
  303. for len(data) > 0 {
  304. space := min(c.maxPacket-headerLength, len(data))
  305. if space, err = c.getWindowSpace(space); err != nil {
  306. return 0, err
  307. }
  308. todo := data
  309. if uint32(len(todo)) > space {
  310. todo = todo[:space]
  311. }
  312. packet := make([]byte, headerLength+len(todo))
  313. packet[0] = msgChannelData
  314. marshalUint32(packet[1:], c.remoteId)
  315. marshalUint32(packet[5:], uint32(len(todo)))
  316. copy(packet[9:], todo)
  317. if err = c.writePacket(packet); err != nil {
  318. return
  319. }
  320. n += len(todo)
  321. data = data[len(todo):]
  322. }
  323. return
  324. }
  325. // Close signals the intent to close the channel.
  326. func (c *serverChan) Close() error {
  327. c.serverConn.lock.Lock()
  328. defer c.serverConn.lock.Unlock()
  329. if c.serverConn.err != nil {
  330. return c.serverConn.err
  331. }
  332. if !c.setClosed() {
  333. return errors.New("ssh: channel already closed")
  334. }
  335. return c.sendClose()
  336. }
  337. func (c *serverChan) AckRequest(ok bool) error {
  338. c.serverConn.lock.Lock()
  339. defer c.serverConn.lock.Unlock()
  340. if c.serverConn.err != nil {
  341. return c.serverConn.err
  342. }
  343. if !ok {
  344. ack := channelRequestFailureMsg{
  345. PeersId: c.remoteId,
  346. }
  347. return c.writePacket(marshal(msgChannelFailure, ack))
  348. }
  349. ack := channelRequestSuccessMsg{
  350. PeersId: c.remoteId,
  351. }
  352. return c.writePacket(marshal(msgChannelSuccess, ack))
  353. }
  354. func (c *serverChan) ChannelType() string {
  355. return c.chanType
  356. }
  357. func (c *serverChan) ExtraData() []byte {
  358. return c.extraData
  359. }
  360. // A clientChan represents a single RFC 4254 channel multiplexed
  361. // over a SSH connection.
  362. type clientChan struct {
  363. channel
  364. stdin *chanWriter
  365. stdout *chanReader
  366. stderr *chanReader
  367. msg chan interface{}
  368. }
  369. // newClientChan returns a partially constructed *clientChan
  370. // using the local id provided. To be usable clientChan.remoteId
  371. // needs to be assigned once known.
  372. func newClientChan(cc conn, id uint32) *clientChan {
  373. c := &clientChan{
  374. channel: channel{
  375. conn: cc,
  376. localId: id,
  377. remoteWin: window{Cond: newCond()},
  378. },
  379. msg: make(chan interface{}, 16),
  380. }
  381. c.stdin = &chanWriter{
  382. channel: &c.channel,
  383. }
  384. c.stdout = &chanReader{
  385. channel: &c.channel,
  386. buffer: newBuffer(),
  387. }
  388. c.stderr = &chanReader{
  389. channel: &c.channel,
  390. buffer: newBuffer(),
  391. }
  392. return c
  393. }
  394. // waitForChannelOpenResponse, if successful, fills out
  395. // the remoteId and records any initial window advertisement.
  396. func (c *clientChan) waitForChannelOpenResponse() error {
  397. switch msg := (<-c.msg).(type) {
  398. case *channelOpenConfirmMsg:
  399. if msg.MaxPacketSize < minPacketLength || msg.MaxPacketSize > 1<<31 {
  400. return errors.New("ssh: invalid MaxPacketSize from peer")
  401. }
  402. // fixup remoteId field
  403. c.remoteId = msg.MyId
  404. c.maxPacket = msg.MaxPacketSize
  405. c.remoteWin.add(msg.MyWindow)
  406. return nil
  407. case *channelOpenFailureMsg:
  408. return errors.New(safeString(msg.Message))
  409. }
  410. return errors.New("ssh: unexpected packet")
  411. }
  412. // Close signals the intent to close the channel.
  413. func (c *clientChan) Close() error {
  414. if !c.setClosed() {
  415. return errors.New("ssh: channel already closed")
  416. }
  417. c.stdout.eof()
  418. c.stderr.eof()
  419. return c.sendClose()
  420. }
  421. // A chanWriter represents the stdin of a remote process.
  422. type chanWriter struct {
  423. *channel
  424. // indicates the writer has been closed. eof is owned by the
  425. // caller of Write/Close.
  426. eof bool
  427. }
  428. // Write writes data to the remote process's standard input.
  429. func (w *chanWriter) Write(data []byte) (written int, err error) {
  430. const headerLength = 9 // 1 byte message type, 4 bytes remoteId, 4 bytes data length
  431. for len(data) > 0 {
  432. if w.eof || w.closed() {
  433. err = io.EOF
  434. return
  435. }
  436. // never send more data than maxPacket even if
  437. // there is sufficent window.
  438. n := min(w.maxPacket-headerLength, len(data))
  439. r := w.remoteWin.reserve(n)
  440. n = r
  441. remoteId := w.remoteId
  442. packet := []byte{
  443. msgChannelData,
  444. byte(remoteId >> 24), byte(remoteId >> 16), byte(remoteId >> 8), byte(remoteId),
  445. byte(n >> 24), byte(n >> 16), byte(n >> 8), byte(n),
  446. }
  447. if err = w.writePacket(append(packet, data[:n]...)); err != nil {
  448. break
  449. }
  450. data = data[n:]
  451. written += int(n)
  452. }
  453. return
  454. }
  455. func min(a uint32, b int) uint32 {
  456. if a < uint32(b) {
  457. return a
  458. }
  459. return uint32(b)
  460. }
  461. func (w *chanWriter) Close() error {
  462. w.eof = true
  463. return w.sendEOF()
  464. }
  465. // A chanReader represents stdout or stderr of a remote process.
  466. type chanReader struct {
  467. *channel // the channel backing this reader
  468. *buffer
  469. }
  470. // Read reads data from the remote process's stdout or stderr.
  471. func (r *chanReader) Read(buf []byte) (int, error) {
  472. n, err := r.buffer.Read(buf)
  473. if err != nil {
  474. if err == io.EOF {
  475. return n, err
  476. }
  477. return 0, err
  478. }
  479. return n, r.sendWindowAdj(n)
  480. }