mux.go 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232
  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. // sorted by priority
  33. lns []*listener
  34. maxNeedBytesNum uint32
  35. mu sync.RWMutex
  36. }
  37. func NewMux(ln net.Listener) (mux *Mux) {
  38. mux = &Mux{
  39. ln: ln,
  40. lns: make([]*listener, 0),
  41. }
  42. return
  43. }
  44. // priority
  45. func (mux *Mux) Listen(priority int, needBytesNum uint32, fn MatchFunc) net.Listener {
  46. ln := &listener{
  47. c: make(chan net.Conn),
  48. mux: mux,
  49. priority: priority,
  50. needBytesNum: needBytesNum,
  51. matchFn: fn,
  52. }
  53. mux.mu.Lock()
  54. defer mux.mu.Unlock()
  55. if needBytesNum > mux.maxNeedBytesNum {
  56. mux.maxNeedBytesNum = needBytesNum
  57. }
  58. newlns := append(mux.copyLns(), ln)
  59. sort.Slice(newlns, func(i, j int) bool {
  60. if newlns[i].priority == newlns[j].priority {
  61. return newlns[i].needBytesNum < newlns[j].needBytesNum
  62. }
  63. return newlns[i].priority < newlns[j].priority
  64. })
  65. mux.lns = newlns
  66. return ln
  67. }
  68. func (mux *Mux) ListenHttp(priority int) net.Listener {
  69. return mux.Listen(priority, HttpNeedBytesNum, HttpMatchFunc)
  70. }
  71. func (mux *Mux) ListenHttps(priority int) net.Listener {
  72. return mux.Listen(priority, HttpsNeedBytesNum, HttpsMatchFunc)
  73. }
  74. func (mux *Mux) DefaultListener() net.Listener {
  75. mux.mu.Lock()
  76. defer mux.mu.Unlock()
  77. if mux.defaultLn == nil {
  78. mux.defaultLn = &listener{
  79. c: make(chan net.Conn),
  80. mux: mux,
  81. }
  82. }
  83. return mux.defaultLn
  84. }
  85. func (mux *Mux) release(ln *listener) bool {
  86. result := false
  87. mux.mu.Lock()
  88. defer mux.mu.Unlock()
  89. lns := mux.copyLns()
  90. for i, l := range lns {
  91. if l == ln {
  92. lns = append(lns[:i], lns[i+1:]...)
  93. result = true
  94. break
  95. }
  96. }
  97. mux.lns = lns
  98. return result
  99. }
  100. func (mux *Mux) copyLns() []*listener {
  101. lns := make([]*listener, 0, len(mux.lns))
  102. for _, l := range mux.lns {
  103. lns = append(lns, l)
  104. }
  105. return lns
  106. }
  107. // Serve handles connections from ln and multiplexes then across registered listeners.
  108. func (mux *Mux) Serve() error {
  109. for {
  110. // Wait for the next connection.
  111. // If it returns a temporary error then simply retry.
  112. // If it returns any other error then exit immediately.
  113. conn, err := mux.ln.Accept()
  114. if err, ok := err.(interface {
  115. Temporary() bool
  116. }); ok && err.Temporary() {
  117. continue
  118. }
  119. if err != nil {
  120. return err
  121. }
  122. go mux.handleConn(conn)
  123. }
  124. }
  125. func (mux *Mux) handleConn(conn net.Conn) {
  126. mux.mu.RLock()
  127. maxNeedBytesNum := mux.maxNeedBytesNum
  128. lns := mux.lns
  129. defaultLn := mux.defaultLn
  130. mux.mu.RUnlock()
  131. sharedConn, rd := gnet.NewSharedConnSize(conn, int(maxNeedBytesNum))
  132. data := make([]byte, maxNeedBytesNum)
  133. conn.SetReadDeadline(time.Now().Add(DefaultTimeout))
  134. _, err := io.ReadFull(rd, data)
  135. if err != nil {
  136. conn.Close()
  137. return
  138. }
  139. conn.SetReadDeadline(time.Time{})
  140. for _, ln := range lns {
  141. if match := ln.matchFn(data); match {
  142. err = errors.PanicToError(func() {
  143. ln.c <- sharedConn
  144. })
  145. if err != nil {
  146. conn.Close()
  147. }
  148. return
  149. }
  150. }
  151. // No match listeners
  152. if defaultLn != nil {
  153. err = errors.PanicToError(func() {
  154. defaultLn.c <- sharedConn
  155. })
  156. if err != nil {
  157. conn.Close()
  158. }
  159. return
  160. }
  161. // No listeners for this connection, close it.
  162. conn.Close()
  163. return
  164. }
  165. type listener struct {
  166. mux *Mux
  167. priority int
  168. needBytesNum uint32
  169. matchFn MatchFunc
  170. c chan net.Conn
  171. mu sync.RWMutex
  172. }
  173. // Accept waits for and returns the next connection to the listener.
  174. func (ln *listener) Accept() (net.Conn, error) {
  175. conn, ok := <-ln.c
  176. if !ok {
  177. return nil, fmt.Errorf("network connection closed")
  178. }
  179. return conn, nil
  180. }
  181. // Close removes this listener from the parent mux and closes the channel.
  182. func (ln *listener) Close() error {
  183. if ok := ln.mux.release(ln); ok {
  184. // Close done to signal to any RLock holders to release their lock.
  185. close(ln.c)
  186. }
  187. return nil
  188. }
  189. func (ln *listener) Addr() net.Addr {
  190. if ln.mux == nil {
  191. return nil
  192. }
  193. ln.mux.mu.RLock()
  194. defer ln.mux.mu.RUnlock()
  195. if ln.mux.ln == nil {
  196. return nil
  197. }
  198. return ln.mux.ln.Addr()
  199. }