demux.go 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332
  1. /*
  2. * Copyright (c) 2023, Psiphon Inc.
  3. * All rights reserved.
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. *
  18. */
  19. package server
  20. import (
  21. "bytes"
  22. "context"
  23. std_errors "errors"
  24. "net"
  25. "time"
  26. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  27. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/errors"
  28. "github.com/sirupsen/logrus"
  29. )
  30. // protocolDemux enables a single listener to support multiple protocols
  31. // by demultiplexing each conn it accepts into the corresponding protocol
  32. // handler.
  33. type protocolDemux struct {
  34. ctx context.Context
  35. cancelFunc context.CancelFunc
  36. innerListener net.Listener
  37. classifiers []protocolClassifier
  38. connClassificationTimeout time.Duration
  39. conns []chan net.Conn
  40. }
  41. type protocolClassifier struct {
  42. // If set, then the classifier only needs a sample of at least this many
  43. // bytes to determine whether there is a match or not.
  44. minBytesToMatch int
  45. // If set, then the classifier only needs a sample of up to this many bytes
  46. // to determine whether there is a match or not. If match returns false with
  47. // a sample of size greater than or equal to maxBytesToMatch, then match
  48. // will always return false regardless of which bytes are appended to
  49. // the given sample.
  50. maxBytesToMatch int
  51. // Returns true if the sample corresponds to the protocol represented by
  52. // this classifier.
  53. match func(sample []byte) bool
  54. }
  55. // newProtocolDemux returns a newly initialized ProtocolDemux and an
  56. // array of protocol listeners. For each protocol classifier in classifiers
  57. // there will be a corresponding protocol listener at the same index in the
  58. // array of returned protocol listeners. If connClassificationTimeout is >0,
  59. // then any conn not classified in this amount of time will be closed.
  60. //
  61. // Limitation: the conn is also closed after reading maxBytesToMatch and
  62. // failing to find a match, which can be a fingerprint for a raw conn with no
  63. // preceding anti-probing measure, such as TLS passthrough.
  64. func newProtocolDemux(ctx context.Context, listener net.Listener, classifiers []protocolClassifier, connClassificationTimeout time.Duration) (*protocolDemux, []protoListener) {
  65. ctx, cancelFunc := context.WithCancel(ctx)
  66. conns := make([]chan net.Conn, len(classifiers))
  67. for i := range classifiers {
  68. conns[i] = make(chan net.Conn)
  69. }
  70. p := protocolDemux{
  71. ctx: ctx,
  72. cancelFunc: cancelFunc,
  73. innerListener: listener,
  74. conns: conns,
  75. classifiers: classifiers,
  76. connClassificationTimeout: connClassificationTimeout,
  77. }
  78. protoListeners := make([]protoListener, len(classifiers))
  79. for i := range classifiers {
  80. protoListeners[i] = protoListener{
  81. index: i,
  82. mux: &p,
  83. }
  84. }
  85. return &p, protoListeners
  86. }
  87. // run runs the protocol demultiplexer; this function blocks while the
  88. // ProtocolDemux accepts new conns and routes them to the corresponding
  89. // protocol listener returned from NewProtocolDemux.
  90. //
  91. // To stop the protocol demultiplexer and cleanup underlying resources
  92. // call Close().
  93. func (mux *protocolDemux) run() error {
  94. maxBytesToMatch := 0
  95. for _, classifer := range mux.classifiers {
  96. if classifer.maxBytesToMatch == 0 {
  97. maxBytesToMatch = 0
  98. break
  99. } else if classifer.maxBytesToMatch > maxBytesToMatch {
  100. maxBytesToMatch = classifer.maxBytesToMatch
  101. }
  102. }
  103. // Set read buffer to max amount of bytes needed to classify each
  104. // Conn if finite.
  105. readBufferSize := 512 // default size
  106. if maxBytesToMatch > 0 {
  107. readBufferSize = maxBytesToMatch
  108. }
  109. for mux.ctx.Err() == nil {
  110. // Accept new conn and spawn a goroutine where it is read until
  111. // either:
  112. // - It matches one of the configured protocols and is sent downstream
  113. // to the corresponding protocol listener
  114. // - It does not match any of the configured protocols, an error
  115. // occurs, or mux.connClassificationTimeout elapses before the conn
  116. // is classified and the conn is closed
  117. // New conns are accepted, and classified, continuously even if the
  118. // downstream consumers are not ready to process them, which could
  119. // result in spawning many goroutines that become blocked until the
  120. // downstream consumers manage to catch up. Although, this scenario
  121. // should be unlikely because the producer - accepting new conns - is
  122. // bounded by network I/O and the consumer is not. Generally, the
  123. // consumer continuously loops accepting new conns, from its
  124. // corresponding protocol listener, and immediately spawns a goroutine
  125. // to handle each new conn after it is accepted.
  126. conn, err := mux.innerListener.Accept()
  127. if err != nil {
  128. if mux.ctx.Err() == nil {
  129. log.WithTraceFields(LogFields{"error": err}).Debug("accept failed")
  130. }
  131. continue
  132. }
  133. go func() {
  134. type classifiedConnResult struct {
  135. index int
  136. acc bytes.Buffer
  137. err error
  138. errLogLevel logrus.Level
  139. }
  140. resultChannel := make(chan *classifiedConnResult, 2)
  141. var connClassifiedAfterFunc *time.Timer
  142. if mux.connClassificationTimeout > 0 {
  143. connClassifiedAfterFunc = time.AfterFunc(mux.connClassificationTimeout, func() {
  144. resultChannel <- &classifiedConnResult{
  145. err: std_errors.New("conn classification timeout"),
  146. errLogLevel: logrus.DebugLevel,
  147. }
  148. })
  149. }
  150. go func() {
  151. var acc bytes.Buffer
  152. b := make([]byte, readBufferSize)
  153. for mux.ctx.Err() == nil {
  154. n, err := conn.Read(b)
  155. if err != nil {
  156. resultChannel <- &classifiedConnResult{
  157. err: errors.TraceMsg(err, "read conn failed"),
  158. errLogLevel: logrus.DebugLevel,
  159. }
  160. return
  161. }
  162. acc.Write(b[:n])
  163. for i, classifier := range mux.classifiers {
  164. if acc.Len() >= classifier.minBytesToMatch && classifier.match(acc.Bytes()) {
  165. resultChannel <- &classifiedConnResult{
  166. index: i,
  167. acc: acc,
  168. }
  169. return
  170. }
  171. }
  172. if maxBytesToMatch != 0 && acc.Len() > maxBytesToMatch {
  173. // No match. Sample does not match any classifier and is
  174. // longer than required by each.
  175. resultChannel <- &classifiedConnResult{
  176. err: std_errors.New("no classifier match for conn"),
  177. errLogLevel: logrus.WarnLevel,
  178. }
  179. return
  180. }
  181. }
  182. resultChannel <- &classifiedConnResult{
  183. err: mux.ctx.Err(),
  184. errLogLevel: logrus.DebugLevel,
  185. }
  186. }()
  187. result := <-resultChannel
  188. if connClassifiedAfterFunc != nil {
  189. connClassifiedAfterFunc.Stop()
  190. }
  191. if result.err != nil {
  192. log.WithTraceFields(LogFields{"error": result.err}).Log(result.errLogLevel, "conn classification failed")
  193. err := conn.Close()
  194. if err != nil {
  195. log.WithTraceFields(LogFields{"error": err}).Debug("close failed")
  196. }
  197. return
  198. }
  199. // Found a match, replay buffered bytes in new conn and send
  200. // downstream.
  201. // TODO: subtract the time it took to classify the conn from the
  202. // subsequent SSH handshake timeout (sshHandshakeTimeout).
  203. bConn := newBufferedConn(conn, result.acc)
  204. select {
  205. case mux.conns[result.index] <- bConn:
  206. case <-mux.ctx.Done():
  207. bConn.Close()
  208. }
  209. }()
  210. }
  211. return mux.ctx.Err()
  212. }
  213. func (mux *protocolDemux) acceptForIndex(index int) (net.Conn, error) {
  214. // First check pool of accepted and classified conns.
  215. for mux.ctx.Err() == nil {
  216. select {
  217. case conn := <-mux.conns[index]:
  218. return conn, nil
  219. case <-mux.ctx.Done():
  220. return nil, errors.Trace(mux.ctx.Err())
  221. }
  222. }
  223. return nil, mux.ctx.Err()
  224. }
  225. func (mux *protocolDemux) Close() error {
  226. mux.cancelFunc()
  227. err := mux.innerListener.Close()
  228. if err != nil {
  229. return errors.Trace(err)
  230. }
  231. return nil
  232. }
  233. type protoListener struct {
  234. index int
  235. mux *protocolDemux
  236. }
  237. func (p protoListener) Accept() (net.Conn, error) {
  238. return p.mux.acceptForIndex(p.index)
  239. }
  240. func (p protoListener) Close() error {
  241. // Do nothing. Listeners must be shutdown with ProtocolDemux.Close.
  242. return nil
  243. }
  244. func (p protoListener) Addr() net.Addr {
  245. return p.mux.innerListener.Addr()
  246. }
  247. type bufferedConn struct {
  248. buffer *bytes.Buffer
  249. net.Conn
  250. }
  251. func newBufferedConn(conn net.Conn, buffer bytes.Buffer) *bufferedConn {
  252. return &bufferedConn{
  253. Conn: conn,
  254. buffer: &buffer,
  255. }
  256. }
  257. func (conn *bufferedConn) Read(b []byte) (n int, err error) {
  258. if conn.buffer != nil && conn.buffer.Len() > 0 {
  259. n := copy(b, conn.buffer.Bytes())
  260. conn.buffer.Next(n)
  261. return n, err
  262. }
  263. // Allow memory to be reclaimed by gc now because Conn may be long
  264. // lived and otherwise this memory would be held for its duration.
  265. conn.buffer = nil
  266. return conn.Conn.Read(b)
  267. }
  268. // GetMetrics implements the common.MetricsSource interface.
  269. func (conn *bufferedConn) GetMetrics() common.LogFields {
  270. // Relay any metrics from the underlying conn.
  271. m, ok := conn.Conn.(common.MetricsSource)
  272. if ok {
  273. return m.GetMetrics()
  274. }
  275. return nil
  276. }