client.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443
  1. package quic
  2. import (
  3. "context"
  4. "crypto/tls"
  5. "fmt"
  6. "net"
  7. "sync"
  8. "github.com/lucas-clemente/quic-go/internal/handshake"
  9. "github.com/lucas-clemente/quic-go/internal/protocol"
  10. "github.com/lucas-clemente/quic-go/internal/qerr"
  11. "github.com/lucas-clemente/quic-go/internal/utils"
  12. "github.com/lucas-clemente/quic-go/internal/wire"
  13. )
  14. type client struct {
  15. mutex sync.Mutex
  16. conn connection
  17. // If the client is created with DialAddr, we create a packet conn.
  18. // If it is started with Dial, we take a packet conn as a parameter.
  19. createdPacketConn bool
  20. packetHandlers packetHandlerManager
  21. token []byte
  22. versionNegotiated utils.AtomicBool // has the server accepted our version
  23. receivedVersionNegotiationPacket bool
  24. negotiatedVersions []protocol.VersionNumber // the list of versions from the version negotiation packet
  25. tlsConf *tls.Config
  26. config *Config
  27. srcConnID protocol.ConnectionID
  28. destConnID protocol.ConnectionID
  29. origDestConnID protocol.ConnectionID // the destination conn ID used on the first Initial (before a Retry)
  30. initialPacketNumber protocol.PacketNumber
  31. initialVersion protocol.VersionNumber
  32. version protocol.VersionNumber
  33. handshakeChan chan struct{}
  34. session quicSession
  35. logger utils.Logger
  36. }
  37. var _ packetHandler = &client{}
  38. var (
  39. // make it possible to mock connection ID generation in the tests
  40. generateConnectionID = protocol.GenerateConnectionID
  41. generateConnectionIDForInitial = protocol.GenerateConnectionIDForInitial
  42. )
  43. // DialAddr establishes a new QUIC connection to a server.
  44. // It uses a new UDP connection and closes this connection when the QUIC session is closed.
  45. // The hostname for SNI is taken from the given address.
  46. func DialAddr(
  47. addr string,
  48. tlsConf *tls.Config,
  49. config *Config,
  50. ) (Session, error) {
  51. return DialAddrContext(context.Background(), addr, tlsConf, config)
  52. }
  53. // DialAddrContext establishes a new QUIC connection to a server using the provided context.
  54. // See DialAddr for details.
  55. func DialAddrContext(
  56. ctx context.Context,
  57. addr string,
  58. tlsConf *tls.Config,
  59. config *Config,
  60. ) (Session, error) {
  61. udpAddr, err := net.ResolveUDPAddr("udp", addr)
  62. if err != nil {
  63. return nil, err
  64. }
  65. udpConn, err := net.ListenUDP("udp", &net.UDPAddr{IP: net.IPv4zero, Port: 0})
  66. if err != nil {
  67. return nil, err
  68. }
  69. return dialContext(ctx, udpConn, udpAddr, addr, tlsConf, config, true)
  70. }
  71. // Dial establishes a new QUIC connection to a server using a net.PacketConn.
  72. // The same PacketConn can be used for multiple calls to Dial and Listen,
  73. // QUIC connection IDs are used for demultiplexing the different connections.
  74. // The host parameter is used for SNI.
  75. func Dial(
  76. pconn net.PacketConn,
  77. remoteAddr net.Addr,
  78. host string,
  79. tlsConf *tls.Config,
  80. config *Config,
  81. ) (Session, error) {
  82. return DialContext(context.Background(), pconn, remoteAddr, host, tlsConf, config)
  83. }
  84. // DialContext establishes a new QUIC connection to a server using a net.PacketConn using the provided context.
  85. // See Dial for details.
  86. func DialContext(
  87. ctx context.Context,
  88. pconn net.PacketConn,
  89. remoteAddr net.Addr,
  90. host string,
  91. tlsConf *tls.Config,
  92. config *Config,
  93. ) (Session, error) {
  94. return dialContext(ctx, pconn, remoteAddr, host, tlsConf, config, false)
  95. }
  96. func dialContext(
  97. ctx context.Context,
  98. pconn net.PacketConn,
  99. remoteAddr net.Addr,
  100. host string,
  101. tlsConf *tls.Config,
  102. config *Config,
  103. createdPacketConn bool,
  104. ) (Session, error) {
  105. config = populateClientConfig(config, createdPacketConn)
  106. packetHandlers, err := getMultiplexer().AddConn(pconn, config.ConnectionIDLength)
  107. if err != nil {
  108. return nil, err
  109. }
  110. c, err := newClient(pconn, remoteAddr, config, tlsConf, host, createdPacketConn)
  111. if err != nil {
  112. return nil, err
  113. }
  114. c.packetHandlers = packetHandlers
  115. if err := c.dial(ctx); err != nil {
  116. return nil, err
  117. }
  118. return c.session, nil
  119. }
  120. func newClient(
  121. pconn net.PacketConn,
  122. remoteAddr net.Addr,
  123. config *Config,
  124. tlsConf *tls.Config,
  125. host string,
  126. createdPacketConn bool,
  127. ) (*client, error) {
  128. if tlsConf == nil {
  129. tlsConf = &tls.Config{}
  130. }
  131. if tlsConf.ServerName == "" {
  132. var err error
  133. tlsConf.ServerName, _, err = net.SplitHostPort(host)
  134. if err != nil {
  135. return nil, err
  136. }
  137. }
  138. // check that all versions are actually supported
  139. if config != nil {
  140. for _, v := range config.Versions {
  141. if !protocol.IsValidVersion(v) {
  142. return nil, fmt.Errorf("%s is not a valid QUIC version", v)
  143. }
  144. }
  145. }
  146. srcConnID, err := generateConnectionID(config.ConnectionIDLength)
  147. if err != nil {
  148. return nil, err
  149. }
  150. destConnID, err := generateConnectionIDForInitial()
  151. if err != nil {
  152. return nil, err
  153. }
  154. c := &client{
  155. srcConnID: srcConnID,
  156. destConnID: destConnID,
  157. conn: &conn{pconn: pconn, currentAddr: remoteAddr},
  158. createdPacketConn: createdPacketConn,
  159. tlsConf: tlsConf,
  160. config: config,
  161. version: config.Versions[0],
  162. handshakeChan: make(chan struct{}),
  163. logger: utils.DefaultLogger.WithPrefix("client"),
  164. }
  165. return c, nil
  166. }
  167. // populateClientConfig populates fields in the quic.Config with their default values, if none are set
  168. // it may be called with nil
  169. func populateClientConfig(config *Config, createdPacketConn bool) *Config {
  170. if config == nil {
  171. config = &Config{}
  172. }
  173. versions := config.Versions
  174. if len(versions) == 0 {
  175. versions = protocol.SupportedVersions
  176. }
  177. handshakeTimeout := protocol.DefaultHandshakeTimeout
  178. if config.HandshakeTimeout != 0 {
  179. handshakeTimeout = config.HandshakeTimeout
  180. }
  181. idleTimeout := protocol.DefaultIdleTimeout
  182. if config.IdleTimeout != 0 {
  183. idleTimeout = config.IdleTimeout
  184. }
  185. maxReceiveStreamFlowControlWindow := config.MaxReceiveStreamFlowControlWindow
  186. if maxReceiveStreamFlowControlWindow == 0 {
  187. maxReceiveStreamFlowControlWindow = protocol.DefaultMaxReceiveStreamFlowControlWindow
  188. }
  189. maxReceiveConnectionFlowControlWindow := config.MaxReceiveConnectionFlowControlWindow
  190. if maxReceiveConnectionFlowControlWindow == 0 {
  191. maxReceiveConnectionFlowControlWindow = protocol.DefaultMaxReceiveConnectionFlowControlWindow
  192. }
  193. maxIncomingStreams := config.MaxIncomingStreams
  194. if maxIncomingStreams == 0 {
  195. maxIncomingStreams = protocol.DefaultMaxIncomingStreams
  196. } else if maxIncomingStreams < 0 {
  197. maxIncomingStreams = 0
  198. }
  199. maxIncomingUniStreams := config.MaxIncomingUniStreams
  200. if maxIncomingUniStreams == 0 {
  201. maxIncomingUniStreams = protocol.DefaultMaxIncomingUniStreams
  202. } else if maxIncomingUniStreams < 0 {
  203. maxIncomingUniStreams = 0
  204. }
  205. connIDLen := config.ConnectionIDLength
  206. if connIDLen == 0 && !createdPacketConn {
  207. connIDLen = protocol.DefaultConnectionIDLength
  208. }
  209. return &Config{
  210. Versions: versions,
  211. HandshakeTimeout: handshakeTimeout,
  212. IdleTimeout: idleTimeout,
  213. ConnectionIDLength: connIDLen,
  214. MaxReceiveStreamFlowControlWindow: maxReceiveStreamFlowControlWindow,
  215. MaxReceiveConnectionFlowControlWindow: maxReceiveConnectionFlowControlWindow,
  216. MaxIncomingStreams: maxIncomingStreams,
  217. MaxIncomingUniStreams: maxIncomingUniStreams,
  218. KeepAlive: config.KeepAlive,
  219. }
  220. }
  221. func (c *client) dial(ctx context.Context) error {
  222. c.logger.Infof("Starting new connection to %s (%s -> %s), source connection ID %s, destination connection ID %s, version %s", c.tlsConf.ServerName, c.conn.LocalAddr(), c.conn.RemoteAddr(), c.srcConnID, c.destConnID, c.version)
  223. if err := c.createNewTLSSession(c.version); err != nil {
  224. return err
  225. }
  226. err := c.establishSecureConnection(ctx)
  227. if err == errCloseForRecreating {
  228. return c.dial(ctx)
  229. }
  230. return err
  231. }
  232. // establishSecureConnection runs the session, and tries to establish a secure connection
  233. // It returns:
  234. // - errCloseSessionRecreating when the server sends a version negotiation packet, or a stateless retry is performed
  235. // - any other error that might occur
  236. // - when the connection is forward-secure
  237. func (c *client) establishSecureConnection(ctx context.Context) error {
  238. errorChan := make(chan error, 1)
  239. go func() {
  240. err := c.session.run() // returns as soon as the session is closed
  241. if err != errCloseForRecreating && c.createdPacketConn {
  242. c.conn.Close()
  243. }
  244. errorChan <- err
  245. }()
  246. select {
  247. case <-ctx.Done():
  248. // The session will send a PeerGoingAway error to the server.
  249. c.session.Close()
  250. return ctx.Err()
  251. case err := <-errorChan:
  252. return err
  253. case <-c.handshakeChan:
  254. // handshake successfully completed
  255. return nil
  256. }
  257. }
  258. func (c *client) handlePacket(p *receivedPacket) {
  259. if p.hdr.IsVersionNegotiation() {
  260. go c.handleVersionNegotiationPacket(p.hdr)
  261. return
  262. }
  263. if p.hdr.Type == protocol.PacketTypeRetry {
  264. go c.handleRetryPacket(p.hdr)
  265. return
  266. }
  267. // this is the first packet we are receiving
  268. // since it is not a Version Negotiation Packet, this means the server supports the suggested version
  269. if !c.versionNegotiated.Get() {
  270. c.versionNegotiated.Set(true)
  271. }
  272. c.session.handlePacket(p)
  273. }
  274. func (c *client) handleVersionNegotiationPacket(hdr *wire.Header) {
  275. c.mutex.Lock()
  276. defer c.mutex.Unlock()
  277. // ignore delayed / duplicated version negotiation packets
  278. if c.receivedVersionNegotiationPacket || c.versionNegotiated.Get() {
  279. c.logger.Debugf("Received a delayed Version Negotiation packet.")
  280. return
  281. }
  282. for _, v := range hdr.SupportedVersions {
  283. if v == c.version {
  284. // The Version Negotiation packet contains the version that we offered.
  285. // This might be a packet sent by an attacker (or by a terribly broken server implementation).
  286. return
  287. }
  288. }
  289. c.logger.Infof("Received a Version Negotiation packet. Supported Versions: %s", hdr.SupportedVersions)
  290. newVersion, ok := protocol.ChooseSupportedVersion(c.config.Versions, hdr.SupportedVersions)
  291. if !ok {
  292. c.session.destroy(qerr.InvalidVersion)
  293. c.logger.Debugf("No compatible version found.")
  294. return
  295. }
  296. c.receivedVersionNegotiationPacket = true
  297. c.negotiatedVersions = hdr.SupportedVersions
  298. // switch to negotiated version
  299. c.initialVersion = c.version
  300. c.version = newVersion
  301. c.logger.Infof("Switching to QUIC version %s. New connection ID: %s", newVersion, c.destConnID)
  302. c.initialPacketNumber = c.session.closeForRecreating()
  303. }
  304. func (c *client) handleRetryPacket(hdr *wire.Header) {
  305. c.mutex.Lock()
  306. defer c.mutex.Unlock()
  307. c.logger.Debugf("<- Received Retry")
  308. (&wire.ExtendedHeader{Header: *hdr}).Log(c.logger)
  309. if !hdr.OrigDestConnectionID.Equal(c.destConnID) {
  310. c.logger.Debugf("Ignoring spoofed Retry. Original Destination Connection ID: %s, expected: %s", hdr.OrigDestConnectionID, c.destConnID)
  311. return
  312. }
  313. if hdr.SrcConnectionID.Equal(c.destConnID) {
  314. c.logger.Debugf("Ignoring Retry, since the server didn't change the Source Connection ID.")
  315. return
  316. }
  317. // If a token is already set, this means that we already received a Retry from the server.
  318. // Ignore this Retry packet.
  319. if len(c.token) > 0 {
  320. c.logger.Debugf("Ignoring Retry, since a Retry was already received.")
  321. return
  322. }
  323. c.origDestConnID = c.destConnID
  324. c.destConnID = hdr.SrcConnectionID
  325. c.token = hdr.Token
  326. c.initialPacketNumber = c.session.closeForRecreating()
  327. }
  328. func (c *client) createNewTLSSession(version protocol.VersionNumber) error {
  329. params := &handshake.TransportParameters{
  330. InitialMaxStreamDataBidiRemote: protocol.InitialMaxStreamData,
  331. InitialMaxStreamDataBidiLocal: protocol.InitialMaxStreamData,
  332. InitialMaxStreamDataUni: protocol.InitialMaxStreamData,
  333. InitialMaxData: protocol.InitialMaxData,
  334. IdleTimeout: c.config.IdleTimeout,
  335. MaxBidiStreams: uint64(c.config.MaxIncomingStreams),
  336. MaxUniStreams: uint64(c.config.MaxIncomingUniStreams),
  337. DisableMigration: true,
  338. }
  339. c.mutex.Lock()
  340. defer c.mutex.Unlock()
  341. runner := &runner{
  342. onHandshakeCompleteImpl: func(_ Session) { close(c.handshakeChan) },
  343. retireConnectionIDImpl: c.packetHandlers.Retire,
  344. removeConnectionIDImpl: c.packetHandlers.Remove,
  345. }
  346. sess, err := newClientSession(
  347. c.conn,
  348. runner,
  349. c.token,
  350. c.origDestConnID,
  351. c.destConnID,
  352. c.srcConnID,
  353. c.config,
  354. c.tlsConf,
  355. c.initialPacketNumber,
  356. params,
  357. c.initialVersion,
  358. c.logger,
  359. c.version,
  360. )
  361. if err != nil {
  362. return err
  363. }
  364. c.session = sess
  365. c.packetHandlers.Add(c.srcConnID, c)
  366. return nil
  367. }
  368. func (c *client) Close() error {
  369. c.mutex.Lock()
  370. defer c.mutex.Unlock()
  371. if c.session == nil {
  372. return nil
  373. }
  374. return c.session.Close()
  375. }
  376. func (c *client) destroy(e error) {
  377. c.mutex.Lock()
  378. defer c.mutex.Unlock()
  379. if c.session == nil {
  380. return
  381. }
  382. c.session.destroy(e)
  383. }
  384. func (c *client) GetVersion() protocol.VersionNumber {
  385. c.mutex.Lock()
  386. v := c.version
  387. c.mutex.Unlock()
  388. return v
  389. }
  390. func (c *client) GetPerspective() protocol.Perspective {
  391. return protocol.PerspectiveClient
  392. }