demux.go 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  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(
  65. ctx context.Context,
  66. listener net.Listener,
  67. classifiers []protocolClassifier,
  68. connClassificationTimeout time.Duration) (*protocolDemux, []protoListener) {
  69. ctx, cancelFunc := context.WithCancel(ctx)
  70. conns := make([]chan net.Conn, len(classifiers))
  71. for i := range classifiers {
  72. conns[i] = make(chan net.Conn)
  73. }
  74. p := protocolDemux{
  75. ctx: ctx,
  76. cancelFunc: cancelFunc,
  77. innerListener: listener,
  78. conns: conns,
  79. classifiers: classifiers,
  80. connClassificationTimeout: connClassificationTimeout,
  81. }
  82. protoListeners := make([]protoListener, len(classifiers))
  83. for i := range classifiers {
  84. protoListeners[i] = protoListener{
  85. index: i,
  86. mux: &p,
  87. }
  88. }
  89. return &p, protoListeners
  90. }
  91. // run runs the protocol demultiplexer; this function blocks while the
  92. // ProtocolDemux accepts new conns and routes them to the corresponding
  93. // protocol listener returned from NewProtocolDemux.
  94. //
  95. // To stop the protocol demultiplexer and cleanup underlying resources
  96. // call Close().
  97. func (mux *protocolDemux) run() error {
  98. maxBytesToMatch := 0
  99. for _, classifer := range mux.classifiers {
  100. if classifer.maxBytesToMatch == 0 {
  101. maxBytesToMatch = 0
  102. break
  103. } else if classifer.maxBytesToMatch > maxBytesToMatch {
  104. maxBytesToMatch = classifer.maxBytesToMatch
  105. }
  106. }
  107. // Set read buffer to max amount of bytes needed to classify each
  108. // Conn if finite.
  109. readBufferSize := 512 // default size
  110. if maxBytesToMatch > 0 {
  111. readBufferSize = maxBytesToMatch
  112. }
  113. for mux.ctx.Err() == nil {
  114. // Accept new conn and spawn a goroutine where it is read until
  115. // either:
  116. // - It matches one of the configured protocols and is sent downstream
  117. // to the corresponding protocol listener
  118. // - It does not match any of the configured protocols, an error
  119. // occurs, or mux.connClassificationTimeout elapses before the conn
  120. // is classified and the conn is closed
  121. // New conns are accepted, and classified, continuously even if the
  122. // downstream consumers are not ready to process them, which could
  123. // result in spawning many goroutines that become blocked until the
  124. // downstream consumers manage to catch up. Although, this scenario
  125. // should be unlikely because the producer - accepting new conns - is
  126. // bounded by network I/O and the consumer is not. Generally, the
  127. // consumer continuously loops accepting new conns, from its
  128. // corresponding protocol listener, and immediately spawns a goroutine
  129. // to handle each new conn after it is accepted.
  130. conn, err := mux.innerListener.Accept()
  131. if err != nil {
  132. if mux.ctx.Err() == nil {
  133. log.WithTraceFields(LogFields{"error": err}).Debug("accept failed")
  134. }
  135. continue
  136. }
  137. go func() {
  138. type classifiedConnResult struct {
  139. index int
  140. acc bytes.Buffer
  141. err error
  142. errLogLevel logrus.Level
  143. }
  144. resultChannel := make(chan *classifiedConnResult, 2)
  145. var connClassifiedAfterFunc *time.Timer
  146. if mux.connClassificationTimeout > 0 {
  147. connClassifiedAfterFunc = time.AfterFunc(mux.connClassificationTimeout, func() {
  148. resultChannel <- &classifiedConnResult{
  149. err: std_errors.New("conn classification timeout"),
  150. errLogLevel: logrus.DebugLevel,
  151. }
  152. })
  153. }
  154. go func() {
  155. var acc bytes.Buffer
  156. b := make([]byte, readBufferSize)
  157. for mux.ctx.Err() == nil {
  158. n, err := conn.Read(b)
  159. if err != nil {
  160. resultChannel <- &classifiedConnResult{
  161. err: errors.TraceMsg(err, "read conn failed"),
  162. errLogLevel: logrus.DebugLevel,
  163. }
  164. return
  165. }
  166. acc.Write(b[:n])
  167. for i, classifier := range mux.classifiers {
  168. if acc.Len() >= classifier.minBytesToMatch && classifier.match(acc.Bytes()) {
  169. resultChannel <- &classifiedConnResult{
  170. index: i,
  171. acc: acc,
  172. }
  173. return
  174. }
  175. }
  176. if maxBytesToMatch != 0 && acc.Len() > maxBytesToMatch {
  177. // No match. Sample does not match any classifier and is
  178. // longer than required by each.
  179. resultChannel <- &classifiedConnResult{
  180. err: std_errors.New("no classifier match for conn"),
  181. errLogLevel: logrus.WarnLevel,
  182. }
  183. return
  184. }
  185. }
  186. resultChannel <- &classifiedConnResult{
  187. err: mux.ctx.Err(),
  188. errLogLevel: logrus.DebugLevel,
  189. }
  190. }()
  191. result := <-resultChannel
  192. if connClassifiedAfterFunc != nil {
  193. connClassifiedAfterFunc.Stop()
  194. }
  195. if result.err != nil {
  196. log.WithTraceFields(LogFields{"error": result.err}).Log(result.errLogLevel, "conn classification failed")
  197. err := conn.Close()
  198. if err != nil {
  199. log.WithTraceFields(LogFields{"error": err}).Debug("close failed")
  200. }
  201. return
  202. }
  203. // Found a match, replay buffered bytes in new conn and send
  204. // downstream.
  205. // TODO: subtract the time it took to classify the conn from the
  206. // subsequent SSH handshake timeout (sshHandshakeTimeout).
  207. bConn := newBufferedConn(conn, result.acc)
  208. select {
  209. case mux.conns[result.index] <- bConn:
  210. case <-mux.ctx.Done():
  211. bConn.Close()
  212. }
  213. }()
  214. }
  215. return mux.ctx.Err()
  216. }
  217. func (mux *protocolDemux) acceptForIndex(index int) (net.Conn, error) {
  218. // First check pool of accepted and classified conns.
  219. for mux.ctx.Err() == nil {
  220. select {
  221. case conn := <-mux.conns[index]:
  222. return conn, nil
  223. case <-mux.ctx.Done():
  224. return nil, errors.Trace(mux.ctx.Err())
  225. }
  226. }
  227. return nil, mux.ctx.Err()
  228. }
  229. func (mux *protocolDemux) Close() error {
  230. mux.cancelFunc()
  231. err := mux.innerListener.Close()
  232. if err != nil {
  233. return errors.Trace(err)
  234. }
  235. return nil
  236. }
  237. type protoListener struct {
  238. index int
  239. mux *protocolDemux
  240. }
  241. func (p protoListener) Accept() (net.Conn, error) {
  242. return p.mux.acceptForIndex(p.index)
  243. }
  244. func (p protoListener) Close() error {
  245. // Do nothing. Listeners must be shutdown with ProtocolDemux.Close.
  246. return nil
  247. }
  248. func (p protoListener) Addr() net.Addr {
  249. return p.mux.innerListener.Addr()
  250. }
  251. type bufferedConn struct {
  252. buffer *bytes.Buffer
  253. net.Conn
  254. }
  255. func newBufferedConn(conn net.Conn, buffer bytes.Buffer) *bufferedConn {
  256. return &bufferedConn{
  257. Conn: conn,
  258. buffer: &buffer,
  259. }
  260. }
  261. func (conn *bufferedConn) Read(b []byte) (n int, err error) {
  262. if conn.buffer != nil && conn.buffer.Len() > 0 {
  263. n := copy(b, conn.buffer.Bytes())
  264. conn.buffer.Next(n)
  265. return n, err
  266. }
  267. // Allow memory to be reclaimed by gc now because Conn may be long
  268. // lived and otherwise this memory would be held for its duration.
  269. conn.buffer = nil
  270. return conn.Conn.Read(b)
  271. }
  272. // GetMetrics implements the common.MetricsSource interface.
  273. func (conn *bufferedConn) GetMetrics() common.LogFields {
  274. // Relay any metrics from the underlying conn.
  275. m, ok := conn.Conn.(common.MetricsSource)
  276. if ok {
  277. return m.GetMetrics()
  278. }
  279. return nil
  280. }