channel.go 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410
  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. "io"
  8. "sync"
  9. )
  10. // extendedDataTypeCode identifies an OpenSSL extended data type. See RFC 4254,
  11. // section 5.2.
  12. type extendedDataTypeCode uint32
  13. // extendedDataStderr is the extended data type that is used for stderr.
  14. const extendedDataStderr extendedDataTypeCode = 1
  15. // A Channel is an ordered, reliable, duplex stream that is multiplexed over an
  16. // SSH connection. Channel.Read can return a ChannelRequest as an error.
  17. type Channel interface {
  18. // Accept accepts the channel creation request.
  19. Accept() error
  20. // Reject rejects the channel creation request. After calling this, no
  21. // other methods on the Channel may be called. If they are then the
  22. // peer is likely to signal a protocol error and drop the connection.
  23. Reject(reason RejectionReason, message string) error
  24. // Read may return a ChannelRequest as an error.
  25. Read(data []byte) (int, error)
  26. Write(data []byte) (int, error)
  27. Close() error
  28. // Stderr returns an io.Writer that writes to this channel with the
  29. // extended data type set to stderr.
  30. Stderr() io.Writer
  31. // AckRequest either sends an ack or nack to the channel request.
  32. AckRequest(ok bool) error
  33. // ChannelType returns the type of the channel, as supplied by the
  34. // client.
  35. ChannelType() string
  36. // ExtraData returns the arbitary payload for this channel, as supplied
  37. // by the client. This data is specific to the channel type.
  38. ExtraData() []byte
  39. }
  40. // ChannelRequest represents a request sent on a channel, outside of the normal
  41. // stream of bytes. It may result from calling Read on a Channel.
  42. type ChannelRequest struct {
  43. Request string
  44. WantReply bool
  45. Payload []byte
  46. }
  47. func (c ChannelRequest) Error() string {
  48. return "ssh: channel request received"
  49. }
  50. // RejectionReason is an enumeration used when rejecting channel creation
  51. // requests. See RFC 4254, section 5.1.
  52. type RejectionReason int
  53. const (
  54. Prohibited RejectionReason = iota + 1
  55. ConnectionFailed
  56. UnknownChannelType
  57. ResourceShortage
  58. )
  59. type channel struct {
  60. conn // the underlying transport
  61. localId, remoteId uint32
  62. remoteWin window
  63. theyClosed bool // indicates the close msg has been received from the remote side
  64. weClosed bool // incidates the close msg has been sent from our side
  65. theySentEOF bool // used by serverChan
  66. dead bool // used by ServerChan to force close
  67. }
  68. func (c *channel) sendWindowAdj(n int) error {
  69. msg := windowAdjustMsg{
  70. PeersId: c.remoteId,
  71. AdditionalBytes: uint32(n),
  72. }
  73. return c.writePacket(marshal(msgChannelWindowAdjust, msg))
  74. }
  75. // sendClose signals the intent to close the channel.
  76. func (c *channel) sendClose() error {
  77. return c.writePacket(marshal(msgChannelClose, channelCloseMsg{
  78. PeersId: c.remoteId,
  79. }))
  80. }
  81. // sendEOF sends EOF to the server. RFC 4254 Section 5.3
  82. func (c *channel) sendEOF() error {
  83. return c.writePacket(marshal(msgChannelEOF, channelEOFMsg{
  84. PeersId: c.remoteId,
  85. }))
  86. }
  87. func (c *channel) sendChannelOpenFailure(reason RejectionReason, message string) error {
  88. reject := channelOpenFailureMsg{
  89. PeersId: c.remoteId,
  90. Reason: reason,
  91. Message: message,
  92. Language: "en",
  93. }
  94. return c.writePacket(marshal(msgChannelOpenFailure, reject))
  95. }
  96. type serverChan struct {
  97. channel
  98. // immutable once created
  99. chanType string
  100. extraData []byte
  101. serverConn *ServerConn
  102. myWindow uint32
  103. maxPacketSize uint32
  104. err error
  105. pendingRequests []ChannelRequest
  106. pendingData []byte
  107. head, length int
  108. // This lock is inferior to serverConn.lock
  109. cond *sync.Cond
  110. }
  111. func (c *serverChan) Accept() error {
  112. c.serverConn.lock.Lock()
  113. defer c.serverConn.lock.Unlock()
  114. if c.serverConn.err != nil {
  115. return c.serverConn.err
  116. }
  117. confirm := channelOpenConfirmMsg{
  118. PeersId: c.remoteId,
  119. MyId: c.localId,
  120. MyWindow: c.myWindow,
  121. MaxPacketSize: c.maxPacketSize,
  122. }
  123. return c.writePacket(marshal(msgChannelOpenConfirm, confirm))
  124. }
  125. func (c *serverChan) Reject(reason RejectionReason, message string) error {
  126. c.serverConn.lock.Lock()
  127. defer c.serverConn.lock.Unlock()
  128. if c.serverConn.err != nil {
  129. return c.serverConn.err
  130. }
  131. return c.sendChannelOpenFailure(reason, message)
  132. }
  133. func (c *serverChan) handlePacket(packet interface{}) {
  134. c.cond.L.Lock()
  135. defer c.cond.L.Unlock()
  136. switch packet := packet.(type) {
  137. case *channelRequestMsg:
  138. req := ChannelRequest{
  139. Request: packet.Request,
  140. WantReply: packet.WantReply,
  141. Payload: packet.RequestSpecificData,
  142. }
  143. c.pendingRequests = append(c.pendingRequests, req)
  144. c.cond.Signal()
  145. case *channelCloseMsg:
  146. c.theyClosed = true
  147. c.cond.Signal()
  148. case *channelEOFMsg:
  149. c.theySentEOF = true
  150. c.cond.Signal()
  151. case *windowAdjustMsg:
  152. if !c.remoteWin.add(packet.AdditionalBytes) {
  153. panic("illegal window update")
  154. }
  155. default:
  156. panic("unknown packet type")
  157. }
  158. }
  159. func (c *serverChan) handleData(data []byte) {
  160. c.cond.L.Lock()
  161. defer c.cond.L.Unlock()
  162. // The other side should never send us more than our window.
  163. if len(data)+c.length > len(c.pendingData) {
  164. // TODO(agl): we should tear down the channel with a protocol
  165. // error.
  166. return
  167. }
  168. c.myWindow -= uint32(len(data))
  169. for i := 0; i < 2; i++ {
  170. tail := c.head + c.length
  171. if tail >= len(c.pendingData) {
  172. tail -= len(c.pendingData)
  173. }
  174. n := copy(c.pendingData[tail:], data)
  175. data = data[n:]
  176. c.length += n
  177. }
  178. c.cond.Signal()
  179. }
  180. func (c *serverChan) Stderr() io.Writer {
  181. return extendedDataChannel{c: c, t: extendedDataStderr}
  182. }
  183. // extendedDataChannel is an io.Writer that writes any data to c as extended
  184. // data of the given type.
  185. type extendedDataChannel struct {
  186. t extendedDataTypeCode
  187. c *serverChan
  188. }
  189. func (edc extendedDataChannel) Write(data []byte) (n int, err error) {
  190. c := edc.c
  191. for len(data) > 0 {
  192. var space uint32
  193. if space, err = c.getWindowSpace(uint32(len(data))); err != nil {
  194. return 0, err
  195. }
  196. todo := data
  197. if uint32(len(todo)) > space {
  198. todo = todo[:space]
  199. }
  200. packet := make([]byte, 1+4+4+4+len(todo))
  201. packet[0] = msgChannelExtendedData
  202. marshalUint32(packet[1:], c.remoteId)
  203. marshalUint32(packet[5:], uint32(edc.t))
  204. marshalUint32(packet[9:], uint32(len(todo)))
  205. copy(packet[13:], todo)
  206. if err = c.writePacket(packet); err != nil {
  207. return
  208. }
  209. n += len(todo)
  210. data = data[len(todo):]
  211. }
  212. return
  213. }
  214. func (c *serverChan) Read(data []byte) (n int, err error) {
  215. n, err, windowAdjustment := c.read(data)
  216. if windowAdjustment > 0 {
  217. packet := marshal(msgChannelWindowAdjust, windowAdjustMsg{
  218. PeersId: c.remoteId,
  219. AdditionalBytes: windowAdjustment,
  220. })
  221. err = c.writePacket(packet)
  222. }
  223. return
  224. }
  225. func (c *serverChan) read(data []byte) (n int, err error, windowAdjustment uint32) {
  226. c.cond.L.Lock()
  227. defer c.cond.L.Unlock()
  228. if c.err != nil {
  229. return 0, c.err, 0
  230. }
  231. for {
  232. if c.theySentEOF || c.theyClosed || c.dead {
  233. return 0, io.EOF, 0
  234. }
  235. if len(c.pendingRequests) > 0 {
  236. req := c.pendingRequests[0]
  237. if len(c.pendingRequests) == 1 {
  238. c.pendingRequests = nil
  239. } else {
  240. oldPendingRequests := c.pendingRequests
  241. c.pendingRequests = make([]ChannelRequest, len(oldPendingRequests)-1)
  242. copy(c.pendingRequests, oldPendingRequests[1:])
  243. }
  244. return 0, req, 0
  245. }
  246. if c.length > 0 {
  247. tail := min(c.head+c.length, len(c.pendingData))
  248. n = copy(data, c.pendingData[c.head:tail])
  249. c.head += n
  250. c.length -= n
  251. if c.head == len(c.pendingData) {
  252. c.head = 0
  253. }
  254. windowAdjustment = uint32(len(c.pendingData)-c.length) - c.myWindow
  255. if windowAdjustment < uint32(len(c.pendingData)/2) {
  256. windowAdjustment = 0
  257. }
  258. c.myWindow += windowAdjustment
  259. return
  260. }
  261. c.cond.Wait()
  262. }
  263. panic("unreachable")
  264. }
  265. // getWindowSpace takes, at most, max bytes of space from the peer's window. It
  266. // returns the number of bytes actually reserved.
  267. func (c *serverChan) getWindowSpace(max uint32) (uint32, error) {
  268. var err error
  269. // TODO(dfc) This lock and check of c.weClosed is necessary because unlike
  270. // clientChan, c.weClosed is observed by more than one goroutine.
  271. c.cond.L.Lock()
  272. if c.dead || c.weClosed {
  273. err = io.EOF
  274. }
  275. c.cond.L.Unlock()
  276. if err != nil {
  277. return 0, err
  278. }
  279. return c.remoteWin.reserve(max), nil
  280. }
  281. func (c *serverChan) Write(data []byte) (n int, err error) {
  282. for len(data) > 0 {
  283. var space uint32
  284. if space, err = c.getWindowSpace(uint32(len(data))); err != nil {
  285. return 0, err
  286. }
  287. todo := data
  288. if uint32(len(todo)) > space {
  289. todo = todo[:space]
  290. }
  291. packet := make([]byte, 1+4+4+len(todo))
  292. packet[0] = msgChannelData
  293. marshalUint32(packet[1:], c.remoteId)
  294. marshalUint32(packet[5:], uint32(len(todo)))
  295. copy(packet[9:], todo)
  296. if err = c.writePacket(packet); err != nil {
  297. return
  298. }
  299. n += len(todo)
  300. data = data[len(todo):]
  301. }
  302. return
  303. }
  304. func (c *serverChan) Close() error {
  305. c.serverConn.lock.Lock()
  306. defer c.serverConn.lock.Unlock()
  307. if c.serverConn.err != nil {
  308. return c.serverConn.err
  309. }
  310. if c.weClosed {
  311. return errors.New("ssh: channel already closed")
  312. }
  313. c.weClosed = true
  314. return c.sendClose()
  315. }
  316. func (c *serverChan) AckRequest(ok bool) error {
  317. c.serverConn.lock.Lock()
  318. defer c.serverConn.lock.Unlock()
  319. if c.serverConn.err != nil {
  320. return c.serverConn.err
  321. }
  322. if !ok {
  323. ack := channelRequestFailureMsg{
  324. PeersId: c.remoteId,
  325. }
  326. return c.writePacket(marshal(msgChannelFailure, ack))
  327. }
  328. ack := channelRequestSuccessMsg{
  329. PeersId: c.remoteId,
  330. }
  331. return c.writePacket(marshal(msgChannelSuccess, ack))
  332. }
  333. func (c *serverChan) ChannelType() string {
  334. return c.chanType
  335. }
  336. func (c *serverChan) ExtraData() []byte {
  337. return c.extraData
  338. }