channel.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560
  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 server. 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. func (c *channel) sendChannelOpenFailure(reason RejectionReason, message string) error {
  86. reject := channelOpenFailureMsg{
  87. PeersId: c.remoteId,
  88. Reason: reason,
  89. Message: message,
  90. Language: "en",
  91. }
  92. return c.writePacket(marshal(msgChannelOpenFailure, reject))
  93. }
  94. func (c *channel) writePacket(b []byte) error {
  95. if c.closed() {
  96. return io.EOF
  97. }
  98. if uint32(len(b)) > c.maxPacket {
  99. return fmt.Errorf("ssh: cannot write %d bytes, maxPacket is %d bytes", len(b), c.maxPacket)
  100. }
  101. return c.conn.writePacket(b)
  102. }
  103. func (c *channel) closed() bool {
  104. return atomic.LoadUint32(&c.isclosed) > 0
  105. }
  106. func (c *channel) setClosed() bool {
  107. return atomic.CompareAndSwapUint32(&c.isclosed, 0, 1)
  108. }
  109. type serverChan struct {
  110. channel
  111. // immutable once created
  112. chanType string
  113. extraData []byte
  114. serverConn *ServerConn
  115. myWindow uint32
  116. weClosed bool // incidates the close msg has been sent from our side
  117. theyClosed bool // indicates the close msg has been received from the remote side
  118. theySentEOF bool
  119. dead bool
  120. err error
  121. pendingRequests []ChannelRequest
  122. pendingData []byte
  123. head, length int
  124. // This lock is inferior to serverConn.lock
  125. cond *sync.Cond
  126. }
  127. func (c *serverChan) Accept() error {
  128. c.serverConn.lock.Lock()
  129. defer c.serverConn.lock.Unlock()
  130. if c.serverConn.err != nil {
  131. return c.serverConn.err
  132. }
  133. confirm := channelOpenConfirmMsg{
  134. PeersId: c.remoteId,
  135. MyId: c.localId,
  136. MyWindow: c.myWindow,
  137. MaxPacketSize: c.maxPacket,
  138. }
  139. return c.writePacket(marshal(msgChannelOpenConfirm, confirm))
  140. }
  141. func (c *serverChan) Reject(reason RejectionReason, message string) error {
  142. c.serverConn.lock.Lock()
  143. defer c.serverConn.lock.Unlock()
  144. if c.serverConn.err != nil {
  145. return c.serverConn.err
  146. }
  147. return c.sendChannelOpenFailure(reason, message)
  148. }
  149. func (c *serverChan) handlePacket(packet interface{}) {
  150. c.cond.L.Lock()
  151. defer c.cond.L.Unlock()
  152. switch packet := packet.(type) {
  153. case *channelRequestMsg:
  154. req := ChannelRequest{
  155. Request: packet.Request,
  156. WantReply: packet.WantReply,
  157. Payload: packet.RequestSpecificData,
  158. }
  159. c.pendingRequests = append(c.pendingRequests, req)
  160. c.cond.Signal()
  161. case *channelCloseMsg:
  162. c.theyClosed = true
  163. c.cond.Signal()
  164. case *channelEOFMsg:
  165. c.theySentEOF = true
  166. c.cond.Signal()
  167. case *windowAdjustMsg:
  168. if !c.remoteWin.add(packet.AdditionalBytes) {
  169. panic("illegal window update")
  170. }
  171. default:
  172. panic("unknown packet type")
  173. }
  174. }
  175. func (c *serverChan) handleData(data []byte) {
  176. c.cond.L.Lock()
  177. defer c.cond.L.Unlock()
  178. // The other side should never send us more than our window.
  179. if len(data)+c.length > len(c.pendingData) {
  180. // TODO(agl): we should tear down the channel with a protocol
  181. // error.
  182. return
  183. }
  184. c.myWindow -= uint32(len(data))
  185. for i := 0; i < 2; i++ {
  186. tail := c.head + c.length
  187. if tail >= len(c.pendingData) {
  188. tail -= len(c.pendingData)
  189. }
  190. n := copy(c.pendingData[tail:], data)
  191. data = data[n:]
  192. c.length += n
  193. }
  194. c.cond.Signal()
  195. }
  196. func (c *serverChan) Stderr() io.Writer {
  197. return extendedDataChannel{c: c, t: extendedDataStderr}
  198. }
  199. // extendedDataChannel is an io.Writer that writes any data to c as extended
  200. // data of the given type.
  201. type extendedDataChannel struct {
  202. t extendedDataTypeCode
  203. c *serverChan
  204. }
  205. func (edc extendedDataChannel) Write(data []byte) (n int, err error) {
  206. c := edc.c
  207. for len(data) > 0 {
  208. var space uint32
  209. if space, err = c.getWindowSpace(uint32(len(data))); err != nil {
  210. return 0, err
  211. }
  212. todo := data
  213. if uint32(len(todo)) > space {
  214. todo = todo[:space]
  215. }
  216. packet := make([]byte, 1+4+4+4+len(todo))
  217. packet[0] = msgChannelExtendedData
  218. marshalUint32(packet[1:], c.remoteId)
  219. marshalUint32(packet[5:], uint32(edc.t))
  220. marshalUint32(packet[9:], uint32(len(todo)))
  221. copy(packet[13:], todo)
  222. if err = c.writePacket(packet); err != nil {
  223. return
  224. }
  225. n += len(todo)
  226. data = data[len(todo):]
  227. }
  228. return
  229. }
  230. func (c *serverChan) Read(data []byte) (n int, err error) {
  231. n, err, windowAdjustment := c.read(data)
  232. if windowAdjustment > 0 {
  233. packet := marshal(msgChannelWindowAdjust, windowAdjustMsg{
  234. PeersId: c.remoteId,
  235. AdditionalBytes: windowAdjustment,
  236. })
  237. err = c.writePacket(packet)
  238. }
  239. return
  240. }
  241. func (c *serverChan) read(data []byte) (n int, err error, windowAdjustment uint32) {
  242. c.cond.L.Lock()
  243. defer c.cond.L.Unlock()
  244. if c.err != nil {
  245. return 0, c.err, 0
  246. }
  247. for {
  248. if c.theySentEOF || c.theyClosed || c.dead {
  249. return 0, io.EOF, 0
  250. }
  251. if len(c.pendingRequests) > 0 {
  252. req := c.pendingRequests[0]
  253. if len(c.pendingRequests) == 1 {
  254. c.pendingRequests = nil
  255. } else {
  256. oldPendingRequests := c.pendingRequests
  257. c.pendingRequests = make([]ChannelRequest, len(oldPendingRequests)-1)
  258. copy(c.pendingRequests, oldPendingRequests[1:])
  259. }
  260. return 0, req, 0
  261. }
  262. if c.length > 0 {
  263. tail := min(c.head+c.length, len(c.pendingData))
  264. n = copy(data, c.pendingData[c.head:tail])
  265. c.head += n
  266. c.length -= n
  267. if c.head == len(c.pendingData) {
  268. c.head = 0
  269. }
  270. windowAdjustment = uint32(len(c.pendingData)-c.length) - c.myWindow
  271. if windowAdjustment < uint32(len(c.pendingData)/2) {
  272. windowAdjustment = 0
  273. }
  274. c.myWindow += windowAdjustment
  275. return
  276. }
  277. c.cond.Wait()
  278. }
  279. panic("unreachable")
  280. }
  281. // getWindowSpace takes, at most, max bytes of space from the peer's window. It
  282. // returns the number of bytes actually reserved.
  283. func (c *serverChan) getWindowSpace(max uint32) (uint32, error) {
  284. var err error
  285. // TODO(dfc) This lock and check of c.weClosed is necessary because unlike
  286. // clientChan, c.weClosed is observed by more than one goroutine.
  287. c.cond.L.Lock()
  288. if c.dead || c.weClosed {
  289. err = io.EOF
  290. }
  291. c.cond.L.Unlock()
  292. if err != nil {
  293. return 0, err
  294. }
  295. return c.remoteWin.reserve(max), nil
  296. }
  297. func (c *serverChan) Write(data []byte) (n int, err error) {
  298. for len(data) > 0 {
  299. var space uint32
  300. if space, err = c.getWindowSpace(uint32(len(data))); err != nil {
  301. return 0, err
  302. }
  303. todo := data
  304. if uint32(len(todo)) > space {
  305. todo = todo[:space]
  306. }
  307. packet := make([]byte, 1+4+4+len(todo))
  308. packet[0] = msgChannelData
  309. marshalUint32(packet[1:], c.remoteId)
  310. marshalUint32(packet[5:], uint32(len(todo)))
  311. copy(packet[9:], todo)
  312. if err = c.writePacket(packet); err != nil {
  313. return
  314. }
  315. n += len(todo)
  316. data = data[len(todo):]
  317. }
  318. return
  319. }
  320. func (c *serverChan) Close() error {
  321. c.serverConn.lock.Lock()
  322. defer c.serverConn.lock.Unlock()
  323. if c.serverConn.err != nil {
  324. return c.serverConn.err
  325. }
  326. if c.weClosed {
  327. return errors.New("ssh: channel already closed")
  328. }
  329. c.weClosed = true
  330. return c.sendClose()
  331. }
  332. // sendClose signals the intent to close the channel.
  333. func (c *serverChan) sendClose() error {
  334. return c.writePacket(marshal(msgChannelClose, channelCloseMsg{
  335. PeersId: c.remoteId,
  336. }))
  337. }
  338. func (c *serverChan) AckRequest(ok bool) error {
  339. c.serverConn.lock.Lock()
  340. defer c.serverConn.lock.Unlock()
  341. if c.serverConn.err != nil {
  342. return c.serverConn.err
  343. }
  344. if !ok {
  345. ack := channelRequestFailureMsg{
  346. PeersId: c.remoteId,
  347. }
  348. return c.writePacket(marshal(msgChannelFailure, ack))
  349. }
  350. ack := channelRequestSuccessMsg{
  351. PeersId: c.remoteId,
  352. }
  353. return c.writePacket(marshal(msgChannelSuccess, ack))
  354. }
  355. func (c *serverChan) ChannelType() string {
  356. return c.chanType
  357. }
  358. func (c *serverChan) ExtraData() []byte {
  359. return c.extraData
  360. }
  361. // A clientChan represents a single RFC 4254 channel multiplexed
  362. // over a SSH connection.
  363. type clientChan struct {
  364. channel
  365. stdin *chanWriter
  366. stdout *chanReader
  367. stderr *chanReader
  368. msg chan interface{}
  369. }
  370. // newClientChan returns a partially constructed *clientChan
  371. // using the local id provided. To be usable clientChan.remoteId
  372. // needs to be assigned once known.
  373. func newClientChan(cc conn, id uint32) *clientChan {
  374. c := &clientChan{
  375. channel: channel{
  376. conn: cc,
  377. localId: id,
  378. remoteWin: window{Cond: newCond()},
  379. },
  380. msg: make(chan interface{}, 16),
  381. }
  382. c.stdin = &chanWriter{
  383. channel: &c.channel,
  384. }
  385. c.stdout = &chanReader{
  386. channel: &c.channel,
  387. buffer: newBuffer(),
  388. }
  389. c.stderr = &chanReader{
  390. channel: &c.channel,
  391. buffer: newBuffer(),
  392. }
  393. return c
  394. }
  395. // waitForChannelOpenResponse, if successful, fills out
  396. // the remoteId and records any initial window advertisement.
  397. func (c *clientChan) waitForChannelOpenResponse() error {
  398. switch msg := (<-c.msg).(type) {
  399. case *channelOpenConfirmMsg:
  400. if msg.MaxPacketSize < minPacketLength || msg.MaxPacketSize > 1<<31 {
  401. return errors.New("ssh: invalid MaxPacketSize from peer")
  402. }
  403. // fixup remoteId field
  404. c.remoteId = msg.MyId
  405. c.maxPacket = msg.MaxPacketSize
  406. c.remoteWin.add(msg.MyWindow)
  407. return nil
  408. case *channelOpenFailureMsg:
  409. return errors.New(safeString(msg.Message))
  410. }
  411. return errors.New("ssh: unexpected packet")
  412. }
  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. close(c.msg)
  420. // TODO(dfc) step around channel.writePacket() because closed() is now true
  421. return c.channel.conn.writePacket(marshal(msgChannelClose, channelCloseMsg{
  422. PeersId: c.remoteId,
  423. }))
  424. }
  425. // A chanWriter represents the stdin of a remote process.
  426. type chanWriter struct {
  427. *channel
  428. }
  429. // Write writes data to the remote process's standard input.
  430. func (w *chanWriter) Write(data []byte) (written int, err error) {
  431. const headerLength = 9 // 1 byte message type, 4 bytes remoteId, 4 bytes data length
  432. for len(data) > 0 {
  433. // never send more data than maxPacket even if
  434. // there is sufficent window.
  435. n := min(int(w.maxPacket-headerLength), len(data))
  436. n = int(w.remoteWin.reserve(uint32(n)))
  437. remoteId := w.remoteId
  438. packet := []byte{
  439. msgChannelData,
  440. byte(remoteId >> 24), byte(remoteId >> 16), byte(remoteId >> 8), byte(remoteId),
  441. byte(n >> 24), byte(n >> 16), byte(n >> 8), byte(n),
  442. }
  443. if err = w.writePacket(append(packet, data[:n]...)); err != nil {
  444. break
  445. }
  446. data = data[n:]
  447. written += n
  448. }
  449. return
  450. }
  451. func min(a, b int) int {
  452. if a < b {
  453. return a
  454. }
  455. return b
  456. }
  457. func (w *chanWriter) Close() error {
  458. return w.sendEOF()
  459. }
  460. // A chanReader represents stdout or stderr of a remote process.
  461. type chanReader struct {
  462. *channel // the channel backing this reader
  463. *buffer
  464. }
  465. // Read reads data from the remote process's stdout or stderr.
  466. func (r *chanReader) Read(buf []byte) (int, error) {
  467. n, err := r.buffer.Read(buf)
  468. if err != nil {
  469. if err == io.EOF {
  470. return n, err
  471. }
  472. return 0, err
  473. }
  474. return n, r.sendWindowAdj(n)
  475. }