mux.go 4.7 KB

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