client.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689
  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. "crypto"
  7. "crypto/rand"
  8. "errors"
  9. "fmt"
  10. "io"
  11. "math/big"
  12. "net"
  13. "sync"
  14. )
  15. // clientVersion is the fixed identification string that the client will use.
  16. var clientVersion = []byte("SSH-2.0-Go\r\n")
  17. // ClientConn represents the client side of an SSH connection.
  18. type ClientConn struct {
  19. *transport
  20. config *ClientConfig
  21. chanlist // channels associated with this connection
  22. forwardList // forwarded tcpip connections from the remote side
  23. globalRequest
  24. }
  25. type globalRequest struct {
  26. sync.Mutex
  27. response chan interface{}
  28. }
  29. // Client returns a new SSH client connection using c as the underlying transport.
  30. func Client(c net.Conn, config *ClientConfig) (*ClientConn, error) {
  31. conn := &ClientConn{
  32. transport: newTransport(c, config.rand()),
  33. config: config,
  34. globalRequest: globalRequest{response: make(chan interface{}, 1)},
  35. }
  36. if err := conn.handshake(); err != nil {
  37. conn.Close()
  38. return nil, err
  39. }
  40. go conn.mainLoop()
  41. return conn, nil
  42. }
  43. // handshake performs the client side key exchange. See RFC 4253 Section 7.
  44. func (c *ClientConn) handshake() error {
  45. var magics handshakeMagics
  46. if _, err := c.Write(clientVersion); err != nil {
  47. return err
  48. }
  49. if err := c.Flush(); err != nil {
  50. return err
  51. }
  52. magics.clientVersion = clientVersion[:len(clientVersion)-2]
  53. // read remote server version
  54. version, err := readVersion(c)
  55. if err != nil {
  56. return err
  57. }
  58. magics.serverVersion = version
  59. clientKexInit := kexInitMsg{
  60. KexAlgos: supportedKexAlgos,
  61. ServerHostKeyAlgos: supportedHostKeyAlgos,
  62. CiphersClientServer: c.config.Crypto.ciphers(),
  63. CiphersServerClient: c.config.Crypto.ciphers(),
  64. MACsClientServer: c.config.Crypto.macs(),
  65. MACsServerClient: c.config.Crypto.macs(),
  66. CompressionClientServer: supportedCompressions,
  67. CompressionServerClient: supportedCompressions,
  68. }
  69. kexInitPacket := marshal(msgKexInit, clientKexInit)
  70. magics.clientKexInit = kexInitPacket
  71. if err := c.writePacket(kexInitPacket); err != nil {
  72. return err
  73. }
  74. packet, err := c.readPacket()
  75. if err != nil {
  76. return err
  77. }
  78. magics.serverKexInit = packet
  79. var serverKexInit kexInitMsg
  80. if err = unmarshal(&serverKexInit, packet, msgKexInit); err != nil {
  81. return err
  82. }
  83. kexAlgo, hostKeyAlgo, ok := findAgreedAlgorithms(c.transport, &clientKexInit, &serverKexInit)
  84. if !ok {
  85. return errors.New("ssh: no common algorithms")
  86. }
  87. if serverKexInit.FirstKexFollows && kexAlgo != serverKexInit.KexAlgos[0] {
  88. // The server sent a Kex message for the wrong algorithm,
  89. // which we have to ignore.
  90. if _, err := c.readPacket(); err != nil {
  91. return err
  92. }
  93. }
  94. var H, K []byte
  95. var hashFunc crypto.Hash
  96. switch kexAlgo {
  97. case kexAlgoDH14SHA1:
  98. hashFunc = crypto.SHA1
  99. dhGroup14Once.Do(initDHGroup14)
  100. H, K, err = c.kexDH(dhGroup14, hashFunc, &magics, hostKeyAlgo)
  101. case keyAlgoDH1SHA1:
  102. hashFunc = crypto.SHA1
  103. dhGroup1Once.Do(initDHGroup1)
  104. H, K, err = c.kexDH(dhGroup1, hashFunc, &magics, hostKeyAlgo)
  105. default:
  106. err = fmt.Errorf("ssh: unexpected key exchange algorithm %v", kexAlgo)
  107. }
  108. if err != nil {
  109. return err
  110. }
  111. if err = c.writePacket([]byte{msgNewKeys}); err != nil {
  112. return err
  113. }
  114. if err = c.transport.writer.setupKeys(clientKeys, K, H, H, hashFunc); err != nil {
  115. return err
  116. }
  117. if packet, err = c.readPacket(); err != nil {
  118. return err
  119. }
  120. if packet[0] != msgNewKeys {
  121. return UnexpectedMessageError{msgNewKeys, packet[0]}
  122. }
  123. if err := c.transport.reader.setupKeys(serverKeys, K, H, H, hashFunc); err != nil {
  124. return err
  125. }
  126. return c.authenticate(H)
  127. }
  128. // kexDH performs Diffie-Hellman key agreement on a ClientConn. The
  129. // returned values are given the same names as in RFC 4253, section 8.
  130. func (c *ClientConn) kexDH(group *dhGroup, hashFunc crypto.Hash, magics *handshakeMagics, hostKeyAlgo string) ([]byte, []byte, error) {
  131. x, err := rand.Int(c.config.rand(), group.p)
  132. if err != nil {
  133. return nil, nil, err
  134. }
  135. X := new(big.Int).Exp(group.g, x, group.p)
  136. kexDHInit := kexDHInitMsg{
  137. X: X,
  138. }
  139. if err := c.writePacket(marshal(msgKexDHInit, kexDHInit)); err != nil {
  140. return nil, nil, err
  141. }
  142. packet, err := c.readPacket()
  143. if err != nil {
  144. return nil, nil, err
  145. }
  146. var kexDHReply kexDHReplyMsg
  147. if err = unmarshal(&kexDHReply, packet, msgKexDHReply); err != nil {
  148. return nil, nil, err
  149. }
  150. kInt, err := group.diffieHellman(kexDHReply.Y, x)
  151. if err != nil {
  152. return nil, nil, err
  153. }
  154. h := hashFunc.New()
  155. writeString(h, magics.clientVersion)
  156. writeString(h, magics.serverVersion)
  157. writeString(h, magics.clientKexInit)
  158. writeString(h, magics.serverKexInit)
  159. writeString(h, kexDHReply.HostKey)
  160. writeInt(h, X)
  161. writeInt(h, kexDHReply.Y)
  162. K := make([]byte, intLength(kInt))
  163. marshalInt(K, kInt)
  164. h.Write(K)
  165. H := h.Sum(nil)
  166. return H, K, nil
  167. }
  168. // mainLoop reads incoming messages and routes channel messages
  169. // to their respective ClientChans.
  170. func (c *ClientConn) mainLoop() {
  171. defer func() {
  172. // We don't check, for example, that the channel IDs from the
  173. // server are valid before using them. Thus a bad server can
  174. // cause us to panic, but we don't want to crash the program.
  175. recover()
  176. c.Close()
  177. c.closeAll()
  178. }()
  179. for {
  180. packet, err := c.readPacket()
  181. if err != nil {
  182. break
  183. }
  184. // TODO(dfc) A note on blocking channel use.
  185. // The msg, data and dataExt channels of a clientChan can
  186. // cause this loop to block indefinately if the consumer does
  187. // not service them.
  188. switch packet[0] {
  189. case msgChannelData:
  190. if len(packet) < 9 {
  191. // malformed data packet
  192. return
  193. }
  194. peersId := uint32(packet[1])<<24 | uint32(packet[2])<<16 | uint32(packet[3])<<8 | uint32(packet[4])
  195. length := uint32(packet[5])<<24 | uint32(packet[6])<<16 | uint32(packet[7])<<8 | uint32(packet[8])
  196. packet = packet[9:]
  197. if length != uint32(len(packet)) {
  198. return
  199. }
  200. c.getChan(peersId).stdout.handleData(packet)
  201. case msgChannelExtendedData:
  202. if len(packet) < 13 {
  203. // malformed data packet
  204. return
  205. }
  206. peersId := uint32(packet[1])<<24 | uint32(packet[2])<<16 | uint32(packet[3])<<8 | uint32(packet[4])
  207. datatype := uint32(packet[5])<<24 | uint32(packet[6])<<16 | uint32(packet[7])<<8 | uint32(packet[8])
  208. length := uint32(packet[9])<<24 | uint32(packet[10])<<16 | uint32(packet[11])<<8 | uint32(packet[12])
  209. packet = packet[13:]
  210. if length != uint32(len(packet)) {
  211. return
  212. }
  213. // RFC 4254 5.2 defines data_type_code 1 to be data destined
  214. // for stderr on interactive sessions. Other data types are
  215. // silently discarded.
  216. if datatype == 1 {
  217. c.getChan(peersId).stderr.handleData(packet)
  218. }
  219. default:
  220. switch msg := decode(packet).(type) {
  221. case *channelOpenMsg:
  222. c.handleChanOpen(msg)
  223. case *channelOpenConfirmMsg:
  224. c.getChan(msg.PeersId).msg <- msg
  225. case *channelOpenFailureMsg:
  226. c.getChan(msg.PeersId).msg <- msg
  227. case *channelCloseMsg:
  228. ch := c.getChan(msg.PeersId)
  229. ch.theyClosed = true
  230. ch.stdout.eof()
  231. ch.stderr.eof()
  232. close(ch.msg)
  233. if !ch.weClosed {
  234. ch.weClosed = true
  235. ch.sendClose()
  236. }
  237. c.chanlist.remove(msg.PeersId)
  238. case *channelEOFMsg:
  239. ch := c.getChan(msg.PeersId)
  240. ch.stdout.eof()
  241. // RFC 4254 is mute on how EOF affects dataExt messages but
  242. // it is logical to signal EOF at the same time.
  243. ch.stderr.eof()
  244. case *channelRequestSuccessMsg:
  245. c.getChan(msg.PeersId).msg <- msg
  246. case *channelRequestFailureMsg:
  247. c.getChan(msg.PeersId).msg <- msg
  248. case *channelRequestMsg:
  249. c.getChan(msg.PeersId).msg <- msg
  250. case *windowAdjustMsg:
  251. if !c.getChan(msg.PeersId).stdin.win.add(msg.AdditionalBytes) {
  252. // invalid window update
  253. return
  254. }
  255. case *globalRequestSuccessMsg, *globalRequestFailureMsg:
  256. c.globalRequest.response <- msg
  257. case *disconnectMsg:
  258. return
  259. default:
  260. fmt.Printf("mainLoop: unhandled message %T: %v\n", msg, msg)
  261. }
  262. }
  263. }
  264. }
  265. // Handle channel open messages from the remote side.
  266. func (c *ClientConn) handleChanOpen(msg *channelOpenMsg) {
  267. switch msg.ChanType {
  268. case "forwarded-tcpip":
  269. laddr, rest, ok := parseTCPAddr(msg.TypeSpecificData)
  270. if !ok {
  271. // invalid request
  272. c.sendConnectionFailed(msg.PeersId)
  273. return
  274. }
  275. l, ok := c.forwardList.lookup(laddr)
  276. if !ok {
  277. fmt.Println("could not find forward list entry for", laddr)
  278. // Section 7.2, implementations MUST reject suprious incoming
  279. // connections.
  280. c.sendConnectionFailed(msg.PeersId)
  281. return
  282. }
  283. raddr, rest, ok := parseTCPAddr(rest)
  284. if !ok {
  285. // invalid request
  286. c.sendConnectionFailed(msg.PeersId)
  287. return
  288. }
  289. ch := c.newChan(c.transport)
  290. ch.peersId = msg.PeersId
  291. ch.stdin.win.add(msg.PeersWindow)
  292. m := channelOpenConfirmMsg{
  293. PeersId: ch.peersId,
  294. MyId: ch.id,
  295. MyWindow: 1 << 14,
  296. MaxPacketSize: 1 << 15, // RFC 4253 6.1
  297. }
  298. c.writePacket(marshal(msgChannelOpenConfirm, m))
  299. l <- forward{ch, raddr}
  300. default:
  301. // unknown channel type
  302. m := channelOpenFailureMsg{
  303. PeersId: msg.PeersId,
  304. Reason: UnknownChannelType,
  305. Message: fmt.Sprintf("unknown channel type: %v", msg.ChanType),
  306. Language: "en_US.UTF-8",
  307. }
  308. c.writePacket(marshal(msgChannelOpenFailure, m))
  309. }
  310. }
  311. // sendGlobalRequest sends a global request message as specified
  312. // in RFC4254 section 4. To correctly synchronise messages, a lock
  313. // is held internally until a response is returned.
  314. func (c *ClientConn) sendGlobalRequest(m interface{}) (*globalRequestSuccessMsg, error) {
  315. c.globalRequest.Lock()
  316. defer c.globalRequest.Unlock()
  317. if err := c.writePacket(marshal(msgGlobalRequest, m)); err != nil {
  318. return nil, err
  319. }
  320. r := <-c.globalRequest.response
  321. if r, ok := r.(*globalRequestSuccessMsg); ok {
  322. return r, nil
  323. }
  324. return nil, errors.New("request failed")
  325. }
  326. // sendConnectionFailed rejects an incoming channel identified
  327. // by peersId.
  328. func (c *ClientConn) sendConnectionFailed(peersId uint32) error {
  329. m := channelOpenFailureMsg{
  330. PeersId: peersId,
  331. Reason: ConnectionFailed,
  332. Message: "invalid request",
  333. Language: "en_US.UTF-8",
  334. }
  335. return c.writePacket(marshal(msgChannelOpenFailure, m))
  336. }
  337. // parseTCPAddr parses the originating address from the remote into a *net.TCPAddr.
  338. // RFC 4254 section 7.2 is mute on what to do if parsing fails but the forwardlist
  339. // requires a valid *net.TCPAddr to operate, so we enforce that restriction here.
  340. func parseTCPAddr(b []byte) (*net.TCPAddr, []byte, bool) {
  341. addr, b, ok := parseString(b)
  342. if !ok {
  343. return nil, b, false
  344. }
  345. port, b, ok := parseUint32(b)
  346. if !ok {
  347. return nil, b, false
  348. }
  349. ip := net.ParseIP(string(addr))
  350. if ip == nil {
  351. return nil, b, false
  352. }
  353. return &net.TCPAddr{ip, int(port)}, b, true
  354. }
  355. // Dial connects to the given network address using net.Dial and
  356. // then initiates a SSH handshake, returning the resulting client connection.
  357. func Dial(network, addr string, config *ClientConfig) (*ClientConn, error) {
  358. conn, err := net.Dial(network, addr)
  359. if err != nil {
  360. return nil, err
  361. }
  362. return Client(conn, config)
  363. }
  364. // A ClientConfig structure is used to configure a ClientConn. After one has
  365. // been passed to an SSH function it must not be modified.
  366. type ClientConfig struct {
  367. // Rand provides the source of entropy for key exchange. If Rand is
  368. // nil, the cryptographic random reader in package crypto/rand will
  369. // be used.
  370. Rand io.Reader
  371. // The username to authenticate.
  372. User string
  373. // A slice of ClientAuth methods. Only the first instance
  374. // of a particular RFC 4252 method will be used during authentication.
  375. Auth []ClientAuth
  376. // Cryptographic-related configuration.
  377. Crypto CryptoConfig
  378. }
  379. func (c *ClientConfig) rand() io.Reader {
  380. if c.Rand == nil {
  381. return rand.Reader
  382. }
  383. return c.Rand
  384. }
  385. // A clientChan represents a single RFC 4254 channel that is multiplexed
  386. // over a single SSH connection.
  387. type clientChan struct {
  388. packetWriter
  389. id, peersId uint32
  390. stdin *chanWriter // receives window adjustments
  391. stdout *chanReader // receives the payload of channelData messages
  392. stderr *chanReader // receives the payload of channelExtendedData messages
  393. msg chan interface{} // incoming messages
  394. theyClosed bool // indicates the close msg has been received from the remote side
  395. weClosed bool // incidates the close msg has been sent from our side
  396. }
  397. // newClientChan returns a partially constructed *clientChan
  398. // using the local id provided. To be usable clientChan.peersId
  399. // needs to be assigned once known.
  400. func newClientChan(t *transport, id uint32) *clientChan {
  401. c := &clientChan{
  402. packetWriter: t,
  403. id: id,
  404. msg: make(chan interface{}, 16),
  405. }
  406. c.stdin = &chanWriter{
  407. win: &window{Cond: sync.NewCond(new(sync.Mutex))},
  408. clientChan: c,
  409. }
  410. c.stdout = &chanReader{
  411. data: make(chan []byte, 16),
  412. clientChan: c,
  413. }
  414. c.stderr = &chanReader{
  415. data: make(chan []byte, 16),
  416. clientChan: c,
  417. }
  418. return c
  419. }
  420. // waitForChannelOpenResponse, if successful, fills out
  421. // the peerId and records any initial window advertisement.
  422. func (c *clientChan) waitForChannelOpenResponse() error {
  423. switch msg := (<-c.msg).(type) {
  424. case *channelOpenConfirmMsg:
  425. // fixup peersId field
  426. c.peersId = msg.MyId
  427. c.stdin.win.add(msg.MyWindow)
  428. return nil
  429. case *channelOpenFailureMsg:
  430. return errors.New(safeString(msg.Message))
  431. }
  432. return errors.New("ssh: unexpected packet")
  433. }
  434. // sendEOF sends EOF to the server. RFC 4254 Section 5.3
  435. func (c *clientChan) sendEOF() error {
  436. return c.writePacket(marshal(msgChannelEOF, channelEOFMsg{
  437. PeersId: c.peersId,
  438. }))
  439. }
  440. // sendClose signals the intent to close the channel.
  441. func (c *clientChan) sendClose() error {
  442. return c.writePacket(marshal(msgChannelClose, channelCloseMsg{
  443. PeersId: c.peersId,
  444. }))
  445. }
  446. func (c *clientChan) sendWindowAdj(n int) error {
  447. msg := windowAdjustMsg{
  448. PeersId: c.peersId,
  449. AdditionalBytes: uint32(n),
  450. }
  451. return c.writePacket(marshal(msgChannelWindowAdjust, msg))
  452. }
  453. // Close closes the channel. This does not close the underlying connection.
  454. func (c *clientChan) Close() error {
  455. if !c.weClosed {
  456. c.weClosed = true
  457. return c.sendClose()
  458. }
  459. return nil
  460. }
  461. // Thread safe channel list.
  462. type chanlist struct {
  463. // protects concurrent access to chans
  464. sync.Mutex
  465. // chans are indexed by the local id of the channel, clientChan.id.
  466. // The PeersId value of messages received by ClientConn.mainLoop is
  467. // used to locate the right local clientChan in this slice.
  468. chans []*clientChan
  469. }
  470. // Allocate a new ClientChan with the next avail local id.
  471. func (c *chanlist) newChan(t *transport) *clientChan {
  472. c.Lock()
  473. defer c.Unlock()
  474. for i := range c.chans {
  475. if c.chans[i] == nil {
  476. ch := newClientChan(t, uint32(i))
  477. c.chans[i] = ch
  478. return ch
  479. }
  480. }
  481. i := len(c.chans)
  482. ch := newClientChan(t, uint32(i))
  483. c.chans = append(c.chans, ch)
  484. return ch
  485. }
  486. func (c *chanlist) getChan(id uint32) *clientChan {
  487. c.Lock()
  488. defer c.Unlock()
  489. if id >= uint32(len(c.chans)) {
  490. return nil
  491. }
  492. return c.chans[int(id)]
  493. }
  494. func (c *chanlist) remove(id uint32) {
  495. c.Lock()
  496. defer c.Unlock()
  497. c.chans[int(id)] = nil
  498. }
  499. func (c *chanlist) closeAll() {
  500. c.Lock()
  501. defer c.Unlock()
  502. for _, ch := range c.chans {
  503. if ch == nil {
  504. continue
  505. }
  506. ch.theyClosed = true
  507. ch.stdout.eof()
  508. ch.stderr.eof()
  509. close(ch.msg)
  510. }
  511. }
  512. // A chanWriter represents the stdin of a remote process.
  513. type chanWriter struct {
  514. win *window
  515. clientChan *clientChan // the channel backing this writer
  516. }
  517. // Write writes data to the remote process's standard input.
  518. func (w *chanWriter) Write(data []byte) (written int, err error) {
  519. for len(data) > 0 {
  520. // n cannot be larger than 2^31 as len(data) cannot
  521. // be larger than 2^31
  522. n := int(w.win.reserve(uint32(len(data))))
  523. peersId := w.clientChan.peersId
  524. packet := []byte{
  525. msgChannelData,
  526. byte(peersId >> 24), byte(peersId >> 16), byte(peersId >> 8), byte(peersId),
  527. byte(n >> 24), byte(n >> 16), byte(n >> 8), byte(n),
  528. }
  529. if err = w.clientChan.writePacket(append(packet, data[:n]...)); err != nil {
  530. break
  531. }
  532. data = data[n:]
  533. written += n
  534. }
  535. return
  536. }
  537. func min(a, b int) int {
  538. if a < b {
  539. return a
  540. }
  541. return b
  542. }
  543. func (w *chanWriter) Close() error {
  544. return w.clientChan.sendEOF()
  545. }
  546. // A chanReader represents stdout or stderr of a remote process.
  547. type chanReader struct {
  548. // TODO(dfc) a fixed size channel may not be the right data structure.
  549. // If writes to this channel block, they will block mainLoop, making
  550. // it unable to receive new messages from the remote side.
  551. data chan []byte // receives data from remote
  552. dataClosed bool // protects data from being closed twice
  553. clientChan *clientChan // the channel backing this reader
  554. buf []byte
  555. }
  556. // eof signals to the consumer that there is no more data to be received.
  557. func (r *chanReader) eof() {
  558. if !r.dataClosed {
  559. r.dataClosed = true
  560. close(r.data)
  561. }
  562. }
  563. // handleData sends buf to the reader's consumer. If r.data is closed
  564. // the data will be silently discarded
  565. func (r *chanReader) handleData(buf []byte) {
  566. if !r.dataClosed {
  567. r.data <- buf
  568. }
  569. }
  570. // Read reads data from the remote process's stdout or stderr.
  571. func (r *chanReader) Read(data []byte) (int, error) {
  572. var ok bool
  573. for {
  574. if len(r.buf) > 0 {
  575. n := copy(data, r.buf)
  576. r.buf = r.buf[n:]
  577. return n, r.clientChan.sendWindowAdj(n)
  578. }
  579. r.buf, ok = <-r.data
  580. if !ok {
  581. return 0, io.EOF
  582. }
  583. }
  584. panic("unreachable")
  585. }
  586. // window represents the buffer available to clients
  587. // wishing to write to a channel.
  588. type window struct {
  589. *sync.Cond
  590. win uint32 // RFC 4254 5.2 says the window size can grow to 2^32-1
  591. }
  592. // add adds win to the amount of window available
  593. // for consumers.
  594. func (w *window) add(win uint32) bool {
  595. if win == 0 {
  596. return false
  597. }
  598. w.L.Lock()
  599. if w.win+win < win {
  600. w.L.Unlock()
  601. return false
  602. }
  603. w.win += win
  604. // It is unusual that multiple goroutines would be attempting to reserve
  605. // window space, but not guaranteed. Use broadcast to notify all waiters
  606. // that additional window is available.
  607. w.Broadcast()
  608. w.L.Unlock()
  609. return true
  610. }
  611. // reserve reserves win from the available window capacity.
  612. // If no capacity remains, reserve will block. reserve may
  613. // return less than requested.
  614. func (w *window) reserve(win uint32) uint32 {
  615. w.L.Lock()
  616. for w.win == 0 {
  617. w.Wait()
  618. }
  619. if w.win < win {
  620. win = w.win
  621. }
  622. w.win -= win
  623. w.L.Unlock()
  624. return win
  625. }