Debian Codegraph @

vendor/github.com/soheilhy/cmux/cmux.go

raw
1 // Copyright 2016 The CMux Authors. All rights reserved.
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
12 // implied. See the License for the specific language governing
13 // permissions and limitations under the License.
14
15 package cmux
16
17 import (
18 "fmt"
19 "io"
20 "net"
21 "sync"
22 "time"
23 )
24
25 // Matcher matches a connection based on its content.
26 type Matcher func(io.Reader) bool
27
28 // MatchWriter is a match that can also write response (say to do handshake).
29 type MatchWriter func(io.Writer, io.Reader) bool
30
31 // ErrorHandler handles an error and returns whether
32 // the mux should continue serving the listener.
33 type ErrorHandler func(error) bool
34
35 var _ net.Error = ErrNotMatched{}
36
37 // ErrNotMatched is returned whenever a connection is not matched by any of
38 // the matchers registered in the multiplexer.
39 type ErrNotMatched struct {
40 c net.Conn
41 }
42
43 func (e ErrNotMatched) Error() string {
44 return fmt.Sprintf("mux: connection %v not matched by an matcher",
45 e.c.RemoteAddr())
46 }
47
48 // Temporary implements the net.Error interface.
49 func (e ErrNotMatched) Temporary() bool { return true }
50
51 // Timeout implements the net.Error interface.
52 func (e ErrNotMatched) Timeout() bool { return false }
53
54 type errListenerClosed string
55
56 func (e errListenerClosed) Error() string { return string(e) }
57 func (e errListenerClosed) Temporary() bool { return false }
58 func (e errListenerClosed) Timeout() bool { return false }
59
60 // ErrListenerClosed is returned from muxListener.Accept when the underlying
61 // listener is closed.
62 var ErrListenerClosed = errListenerClosed("mux: listener closed")
63
64 // for readability of readTimeout
65 var noTimeout time.Duration
66
67 // New instantiates a new connection multiplexer.
68 func New(l net.Listener) CMux {
69 return &cMux{
70 root: l,
71 bufLen: 1024,
72 errh: func(_ error) bool { return true },
73 donec: make(chan struct{}),
74 readTimeout: noTimeout,
75 }
76 }
77
78 // CMux is a multiplexer for network connections.
79 type CMux interface {
80 // Match returns a net.Listener that sees (i.e., accepts) only
81 // the connections matched by at least one of the matcher.
82 //
83 // The order used to call Match determines the priority of matchers.
84 Match(...Matcher) net.Listener
85 // MatchWithWriters returns a net.Listener that accepts only the
86 // connections that matched by at least of the matcher writers.
87 //
88 // Prefer Matchers over MatchWriters, since the latter can write on the
89 // connection before the actual handler.
90 //
91 // The order used to call Match determines the priority of matchers.
92 MatchWithWriters(...MatchWriter) net.Listener
93 // Serve starts multiplexing the listener. Serve blocks and perhaps
94 // should be invoked concurrently within a go routine.
95 Serve() error
96 // HandleError registers an error handler that handles listener errors.
97 HandleError(ErrorHandler)
98 // sets a timeout for the read of matchers
99 SetReadTimeout(time.Duration)
100 }
101
102 type matchersListener struct {
103 ss []MatchWriter
104 l muxListener
105 }
106
107 type cMux struct {
108 root net.Listener
109 bufLen int
110 errh ErrorHandler
111 donec chan struct{}
112 sls []matchersListener
113 readTimeout time.Duration
114 }
115
116 func matchersToMatchWriters(matchers []Matcher) []MatchWriter {
117 mws := make([]MatchWriter, 0, len(matchers))
118 for _, m := range matchers {
119 mws = append(mws, func(w io.Writer, r io.Reader) bool {
120 return m(r)
121 })
122 }
123 return mws
124 }
125
126 func (m *cMux) Match(matchers ...Matcher) net.Listener {
127 mws := matchersToMatchWriters(matchers)
128 return m.MatchWithWriters(mws...)
129 }
130
131 func (m *cMux) MatchWithWriters(matchers ...MatchWriter) net.Listener {
132 ml := muxListener{
133 Listener: m.root,
134 connc: make(chan net.Conn, m.bufLen),
135 }
136 m.sls = append(m.sls, matchersListener{ss: matchers, l: ml})
137 return ml
138 }
139
140 func (m *cMux) SetReadTimeout(t time.Duration) {
141 m.readTimeout = t
142 }
143
144 func (m *cMux) Serve() error {
145 var wg sync.WaitGroup
146
147 defer func() {
148 close(m.donec)
149 wg.Wait()
150
151 for _, sl := range m.sls {
152 close(sl.l.connc)
153 // Drain the connections enqueued for the listener.
154 for c := range sl.l.connc {
155 _ = c.Close()
156 }
157 }
158 }()
159
160 for {
161 c, err := m.root.Accept()
162 if err != nil {
163 if !m.handleErr(err) {
164 return err
165 }
166 continue
167 }
168
169 wg.Add(1)
170 go m.serve(c, m.donec, &wg)
171 }
172 }
173
174 func (m *cMux) serve(c net.Conn, donec <-chan struct{}, wg *sync.WaitGroup) {
175 defer wg.Done()
176
177 muc := newMuxConn(c)
178 if m.readTimeout > noTimeout {
179 _ = c.SetReadDeadline(time.Now().Add(m.readTimeout))
180 }
181 for _, sl := range m.sls {
182 for _, s := range sl.ss {
183 matched := s(muc.Conn, muc.startSniffing())
184 if matched {
185 muc.doneSniffing()
186 if m.readTimeout > noTimeout {
187 _ = c.SetReadDeadline(time.Time{})
188 }
189 select {
190 case sl.l.connc <- muc:
191 case <-donec:
192 _ = c.Close()
193 }
194 return
195 }
196 }
197 }
198
199 _ = c.Close()
200 err := ErrNotMatched{c: c}
201 if !m.handleErr(err) {
202 _ = m.root.Close()
203 }
204 }
205
206 func (m *cMux) HandleError(h ErrorHandler) {
207 m.errh = h
208 }
209
210 func (m *cMux) handleErr(err error) bool {
211 if !m.errh(err) {
212 return false
213 }
214
215 if ne, ok := err.(net.Error); ok {
216 return ne.Temporary()
217 }
218
219 return false
220 }
221
222 type muxListener struct {
223 net.Listener
224 connc chan net.Conn
225 }
226
227 func (l muxListener) Accept() (net.Conn, error) {
228 c, ok := <-l.connc
229 if !ok {
230 return nil, ErrListenerClosed
231 }
232 return c, nil
233 }
234
235 // MuxConn wraps a net.Conn and provides transparent sniffing of connection data.
236 type MuxConn struct {
237 net.Conn
238 buf bufferedReader
239 }
240
241 func newMuxConn(c net.Conn) *MuxConn {
242 return &MuxConn{
243 Conn: c,
244 buf: bufferedReader{source: c},
245 }
246 }
247
248 // From the io.Reader documentation:
249 //
250 // When Read encounters an error or end-of-file condition after
251 // successfully reading n > 0 bytes, it returns the number of
252 // bytes read. It may return the (non-nil) error from the same call
253 // or return the error (and n == 0) from a subsequent call.
254 // An instance of this general case is that a Reader returning
255 // a non-zero number of bytes at the end of the input stream may
256 // return either err == EOF or err == nil. The next Read should
257 // return 0, EOF.
258 func (m *MuxConn) Read(p []byte) (int, error) {
259 return m.buf.Read(p)
260 }
261
262 func (m *MuxConn) startSniffing() io.Reader {
263 m.buf.reset(true)
264 return &m.buf
265 }
266
267 func (m *MuxConn) doneSniffing() {
268 m.buf.reset(false)
269 }