mux.go 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  1. // Copyright 2018 fatedier, fatedier@gmail.com
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package mux
  15. import (
  16. "fmt"
  17. "io"
  18. "net"
  19. "sort"
  20. "sync"
  21. "time"
  22. "github.com/fatedier/golib/errors"
  23. gnet "github.com/fatedier/golib/net"
  24. )
  25. const (
  26. // DefaultTimeout is the default length of time to wait for bytes we need.
  27. DefaultTimeout = 10 * time.Second
  28. )
  29. type Mux struct {
  30. ln net.Listener
  31. defaultLn *listener
  32. lns []*listener
  33. maxNeedBytesNum uint32
  34. mu sync.RWMutex
  35. }
  36. func NewMux() (mux *Mux) {
  37. mux = &Mux{
  38. lns: make([]*listener, 0),
  39. }
  40. return
  41. }
  42. func (mux *Mux) Listen(priority int, needBytesNum uint32, fn MatchFunc) net.Listener {
  43. ln := &listener{
  44. c: make(chan net.Conn),
  45. mux: mux,
  46. needBytesNum: needBytesNum,
  47. matchFn: fn,
  48. }
  49. mux.mu.Lock()
  50. defer mux.mu.Unlock()
  51. if needBytesNum > mux.maxNeedBytesNum {
  52. mux.maxNeedBytesNum = needBytesNum
  53. }
  54. newlns := append(mux.copyLns(), ln)
  55. sort.Slice(newlns, func(i, j int) bool {
  56. return newlns[i].needBytesNum < newlns[j].needBytesNum
  57. })
  58. mux.lns = newlns
  59. return ln
  60. }
  61. func (mux *Mux) ListenHttp(priority int) net.Listener {
  62. return mux.Listen(priority, HttpNeedBytesNum, HttpMatchFunc)
  63. }
  64. func (mux *Mux) ListenHttps(priority int) net.Listener {
  65. return mux.Listen(priority, HttpsNeedBytesNum, HttpsMatchFunc)
  66. }
  67. func (mux *Mux) DefaultListener() net.Listener {
  68. mux.mu.Lock()
  69. defer mux.mu.Unlock()
  70. if mux.defaultLn == nil {
  71. mux.defaultLn = &listener{
  72. c: make(chan net.Conn),
  73. mux: mux,
  74. }
  75. }
  76. return mux.defaultLn
  77. }
  78. func (mux *Mux) release(ln *listener) bool {
  79. result := false
  80. mux.mu.Lock()
  81. defer mux.mu.Unlock()
  82. lns := mux.copyLns()
  83. for i, l := range lns {
  84. if l == ln {
  85. lns = append(lns[:i], lns[i+1:]...)
  86. result = true
  87. }
  88. }
  89. mux.lns = lns
  90. return result
  91. }
  92. func (mux *Mux) copyLns() []*listener {
  93. lns := make([]*listener, 0, len(mux.lns))
  94. for _, l := range mux.lns {
  95. lns = append(lns, l)
  96. }
  97. return lns
  98. }
  99. // Serve handles connections from ln and multiplexes then across registered listeners.
  100. func (mux *Mux) Serve(ln net.Listener) error {
  101. mux.mu.Lock()
  102. mux.ln = ln
  103. mux.mu.Unlock()
  104. for {
  105. // Wait for the next connection.
  106. // If it returns a temporary error then simply retry.
  107. // If it returns any other error then exit immediately.
  108. conn, err := ln.Accept()
  109. if err, ok := err.(interface {
  110. Temporary() bool
  111. }); ok && err.Temporary() {
  112. continue
  113. }
  114. if err != nil {
  115. return err
  116. }
  117. go mux.handleConn(conn)
  118. }
  119. }
  120. func (mux *Mux) handleConn(conn net.Conn) {
  121. mux.mu.RLock()
  122. maxNeedBytesNum := mux.maxNeedBytesNum
  123. lns := mux.lns
  124. defaultLn := mux.defaultLn
  125. mux.mu.RUnlock()
  126. sharedConn, rd := gnet.NewSharedConnSize(conn, int(maxNeedBytesNum))
  127. data := make([]byte, maxNeedBytesNum)
  128. conn.SetReadDeadline(time.Now().Add(DefaultTimeout))
  129. _, err := io.ReadFull(rd, data)
  130. if err != nil {
  131. conn.Close()
  132. return
  133. }
  134. conn.SetReadDeadline(time.Time{})
  135. for _, ln := range lns {
  136. if match := ln.matchFn(data); match {
  137. err = errors.PanicToError(func() {
  138. ln.c <- sharedConn
  139. })
  140. if err != nil {
  141. conn.Close()
  142. }
  143. return
  144. }
  145. }
  146. // No match listeners
  147. if defaultLn != nil {
  148. err = errors.PanicToError(func() {
  149. defaultLn.c <- sharedConn
  150. })
  151. if err != nil {
  152. conn.Close()
  153. }
  154. return
  155. }
  156. // No listeners for this connection, close it.
  157. conn.Close()
  158. return
  159. }
  160. type listener struct {
  161. mux *Mux
  162. needBytesNum uint32
  163. matchFn MatchFunc
  164. c chan net.Conn
  165. mu sync.RWMutex
  166. }
  167. // Accept waits for and returns the next connection to the listener.
  168. func (ln *listener) Accept() (net.Conn, error) {
  169. conn, ok := <-ln.c
  170. if !ok {
  171. return nil, fmt.Errorf("network connection closed")
  172. }
  173. return conn, nil
  174. }
  175. // Close removes this listener from the parent mux and closes the channel.
  176. func (ln *listener) Close() error {
  177. if ok := ln.mux.release(ln); ok {
  178. // Close done to signal to any RLock holders to release their lock.
  179. close(ln.c)
  180. }
  181. return nil
  182. }
  183. func (ln *listener) Addr() net.Addr {
  184. if ln.mux == nil {
  185. return nil
  186. }
  187. ln.mux.mu.RLock()
  188. defer ln.mux.mu.RUnlock()
  189. if ln.mux.ln == nil {
  190. return nil
  191. }
  192. return ln.mux.ln.Addr()
  193. }