client.go 17 KB

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