Categorygithub.com/daeuniverse/quic-go
modulepackage
0.0.0-20240413031024-943f218e0810
Repository: https://github.com/daeuniverse/quic-go.git
Documentation: pkg.go.dev

# README

A QUIC implementation in pure Go

PkgGoDev Code Coverage Fuzzing Status

quic-go is an implementation of the QUIC protocol (RFC 9000, RFC 9001, RFC 9002) in Go. It has support for HTTP/3 (RFC 9114), including QPACK (RFC 9204).

In addition to these base RFCs, it also implements the following RFCs:

Support for WebTransport over HTTP/3 (draft-ietf-webtrans-http3) is implemented in webtransport-go.

Using QUIC

Running a Server

The central entry point is the quic.Transport. A transport manages QUIC connections running on a single UDP socket. Since QUIC uses Connection IDs, it can demultiplex a listener (accepting incoming connections) and an arbitrary number of outgoing QUIC connections on the same UDP socket.

udpConn, err := net.ListenUDP("udp4", &net.UDPAddr{Port: 1234})
// ... error handling
tr := quic.Transport{
  Conn: udpConn,
}
ln, err := tr.Listen(tlsConf, quicConf)
// ... error handling
go func() {
  for {
    conn, err := ln.Accept()
    // ... error handling
    // handle the connection, usually in a new Go routine
  }
}()

The listener ln can now be used to accept incoming QUIC connections by (repeatedly) calling the Accept method (see below for more information on the quic.Connection).

As a shortcut, quic.Listen and quic.ListenAddr can be used without explicitly initializing a quic.Transport:

ln, err := quic.Listen(udpConn, tlsConf, quicConf)

When using the shortcut, it's not possible to reuse the same UDP socket for outgoing connections.

Running a Client

As mentioned above, multiple outgoing connections can share a single UDP socket, since QUIC uses Connection IDs to demultiplex connections.

ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) // 3s handshake timeout
defer cancel()
conn, err := tr.Dial(ctx, <server address>, <tls.Config>, <quic.Config>)
// ... error handling

As a shortcut, quic.Dial and quic.DialAddr can be used without explictly initializing a quic.Transport:

ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) // 3s handshake timeout
defer cancel()
conn, err := quic.Dial(ctx, conn, <server address>, <tls.Config>, <quic.Config>)

Just as we saw before when used a similar shortcut to run a server, it's also not possible to reuse the same UDP socket for other outgoing connections, or to listen for incoming connections.

Using a QUIC Connection

Accepting Streams

QUIC is a stream-multiplexed transport. A quic.Connection fundamentally differs from the net.Conn and the net.PacketConn interface defined in the standard library. Data is sent and received on (unidirectional and bidirectional) streams (and, if supported, in datagrams), not on the connection itself. The stream state machine is described in detail in Section 3 of RFC 9000.

Note: A unidirectional stream is a stream that the initiator can only write to (quic.SendStream), and the receiver can only read from (quic.ReceiveStream). A bidirectional stream (quic.Stream) allows reading from and writing to for both sides.

On the receiver side, streams are accepted using the AcceptStream (for bidirectional) and AcceptUniStream functions. For most user cases, it makes sense to call these functions in a loop:

for {
  str, err := conn.AcceptStream(context.Background()) // for bidirectional streams
  // ... error handling
  // handle the stream, usually in a new Go routine
}

These functions return an error when the underlying QUIC connection is closed.

Opening Streams

There are two slightly different ways to open streams, one synchronous and one (potentially) asynchronous. This API is necessary since the receiver grants us a certain number of streams that we're allowed to open. It may grant us additional streams later on (typically when existing streams are closed), but it means that at the time we want to open a new stream, we might not be able to do so.

Using the synchronous method OpenStreamSync for bidirectional streams, and OpenUniStreamSync for unidirectional streams, an application can block until the peer allows opening additional streams. In case that we're allowed to open a new stream, these methods return right away:

ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
str, err := conn.OpenStreamSync(ctx) // wait up to 5s to open a new bidirectional stream

The asynchronous version never blocks. If it's currently not possible to open a new stream, it returns a net.Error timeout error:

str, err := conn.OpenStream()
if nerr, ok := err.(net.Error); ok && nerr.Timeout() {
  // It's currently not possible to open another stream,
  // but it might be possible later, once the peer allowed us to do so.
}

These functions return an error when the underlying QUIC connection is closed.

Using Streams

Using QUIC streams is pretty straightforward. The quic.ReceiveStream implements the io.Reader interface, and the quic.SendStream implements the io.Writer interface. A bidirectional stream (quic.Stream) implements both these interfaces. Conceptually, a bidirectional stream can be thought of as the composition of two unidirectional streams in opposite directions.

Calling Close on a quic.SendStream or a quic.Stream closes the send side of the stream. On the receiver side, this will be surfaced as an io.EOF returned from the io.Reader once all data has been consumed. Note that for bidirectional streams, Close only closes the send side of the stream. It is still possible to read from the stream until the peer closes or resets the stream.

In case the application wishes to abort sending on a quic.SendStream or a quic.Stream , it can reset the send side by calling CancelWrite with an application-defined error code (an unsigned 62-bit number). On the receiver side, this surfaced as a quic.StreamError containing that error code on the io.Reader. Note that for bidirectional streams, CancelWrite only resets the send side of the stream. It is still possible to read from the stream until the peer closes or resets the stream.

Conversely, in case the application wishes to abort receiving from a quic.ReceiveStream or a quic.Stream, it can ask the sender to abort data transmission by calling CancelRead with an application-defined error code (an unsigned 62-bit number). On the receiver side, this surfaced as a quic.StreamError containing that error code on the io.Writer. Note that for bidirectional streams, CancelWrite only resets the receive side of the stream. It is still possible to write to the stream.

A bidirectional stream is only closed once both the read and the write side of the stream have been either closed or reset. Only then the peer is granted a new stream according to the maximum number of concurrent streams configured via quic.Config.MaxIncomingStreams.

Configuring QUIC

The quic.Config struct passed to both the listen and dial calls (see above) contains a wide range of configuration options for QUIC connections, incl. the ability to fine-tune flow control limits, the number of streams that the peer is allowed to open concurrently, keep-alives, idle timeouts, and many more. Please refer to the documentation for the quic.Config for details.

The quic.Transport contains a few configuration options that don't apply to any single QUIC connection, but to all connections handled by that transport. It is highly recommend to set the StatelessResetToken, which allows endpoints to quickly recover from crashes / reboots of our node (see Section 10.3 of RFC 9000).

Closing a Connection

When the remote Peer closes the Connection

In case the peer closes the QUIC connection, all calls to open streams, accept streams, as well as all methods on streams immediately return an error. Additionally, it is set as cancellation cause of the connection context. Users can use errors assertions to find out what exactly went wrong:

  • quic.VersionNegotiationError: Happens during the handshake, if there is no overlap between our and the remote's supported QUIC versions.
  • quic.HandshakeTimeoutError: Happens if the QUIC handshake doesn't complete within the time specified in quic.Config.HandshakeTimeout.
  • quic.IdleTimeoutError: Happens after completion of the handshake if the connection is idle for longer than the minimum of both peers idle timeouts (as configured by quic.Config.IdleTimeout). The connection is considered idle when no stream data (and datagrams, if applicable) are exchanged for that period. The QUIC connection can be instructed to regularly send a packet to prevent a connection from going idle by setting quic.Config.KeepAlive. However, this is no guarantee that the peer doesn't suddenly go away (e.g. by abruptly shutting down the node or by crashing), or by a NAT binding expiring, in which case this error might still occur.
  • quic.StatelessResetError: Happens when the remote peer lost the state required to decrypt the packet. This requires the quic.Transport.StatelessResetToken to be configured by the peer.
  • quic.TransportError: Happens if when the QUIC protocol is violated. Unless the error code is APPLICATION_ERROR, this will not happen unless one of the QUIC stacks involved is misbehaving. Please open an issue if you encounter this error.
  • quic.ApplicationError: Happens when the remote decides to close the connection, see below.

Initiated by the Application

A quic.Connection can be closed using CloseWithError:

conn.CloseWithError(0x42, "error 0x42 occurred")

Applications can transmit both an error code (an unsigned 62-bit number) as well as a UTF-8 encoded human-readable reason. The error code allows the receiver to learn why the connection was closed, and the reason can be useful for debugging purposes.

On the receiver side, this is surfaced as a quic.ApplicationError.

QUIC Datagrams

Unreliable datagrams are a QUIC extension (RFC 9221) that is negotiated during the handshake. Support can be enabled by setting the quic.Config.EnableDatagram flag. Note that this doesn't guarantee that the peer also supports datagrams. Whether or not the feature negotiation succeeded can be learned from the quic.ConnectionState.SupportsDatagrams obtained from quic.Connection.ConnectionState().

QUIC DATAGRAMs are a new QUIC frame type sent in QUIC 1-RTT packets (i.e. after completion of the handshake). Therefore, they're end-to-end encrypted and congestion-controlled. However, if a DATAGRAM frame is deemed lost by QUIC's loss detection mechanism, they are not retransmitted.

Datagrams are sent using the SendDatagram method on the quic.Connection:

conn.SendDatagram([]byte("foobar"))

And received using ReceiveDatagram:

msg, err := conn.ReceiveDatagram()

Note that this code path is currently not optimized. It works for datagrams that are sent occasionally, but it doesn't achieve the same throughput as writing data on a stream. Please get in touch on issue #3766 if your use case relies on high datagram throughput, or if you'd like to help fix this issue. There are also some restrictions regarding the maximum message size (see #3599).

QUIC Event Logging using qlog

quic-go logs a wide range of events defined in draft-ietf-quic-qlog-quic-events, providing comprehensive insights in the internals of a QUIC connection.

qlog files can be processed by a number of 3rd-party tools. qviz has proven very useful for debugging all kinds of QUIC connection failures.

qlog can be activated by setting the Tracer callback on the Config. It is called as soon as quic-go decides to start the QUIC handshake on a new connection. qlog.DefaultTracer provides a tracer implementation which writes qlog files to a directory specified by the QLOGDIR environment variable, if set. The default qlog tracer can be used like this:

quic.Config{
  Tracer: qlog.DefaultTracer,
}

This example creates a new qlog file under <QLOGDIR>/<Original Destination Connection ID>_<Vantage Point>.qlog, e.g. qlogs/2e0407da_client.qlog.

For custom qlog behavior, qlog.NewConnectionTracer can be used.

Using HTTP/3

As a server

See the example server. Starting a QUIC server is very similar to the standard library http package in Go:

http.Handle("/", http.FileServer(http.Dir(wwwDir)))
http3.ListenAndServeQUIC("localhost:4242", "/path/to/cert/chain.pem", "/path/to/privkey.pem", nil)

As a client

See the example client. Use a http3.RoundTripper as a Transport in a http.Client.

http.Client{
  Transport: &http3.RoundTripper{},
}

Projects using quic-go

ProjectDescriptionStars
AdGuardHomeFree and open source, powerful network-wide ads & trackers blocking DNS server.GitHub Repo stars
algernonSmall self-contained pure-Go web server with Lua, Markdown, HTTP/2, QUIC, Redis and PostgreSQL supportGitHub Repo stars
caddyFast, multi-platform web server with automatic HTTPSGitHub Repo stars
cloudflaredA tunneling daemon that proxies traffic from the Cloudflare network to your originsGitHub Repo stars
frpA fast reverse proxy to help you expose a local server behind a NAT or firewall to the internetGitHub Repo stars
go-libp2plibp2p implementation in Go, powering Kubo (IPFS) and Lotus (Filecoin), among othersGitHub Repo stars
gostA simple security tunnel written in GoGitHub Repo stars
HysteriaA powerful, lightning fast and censorship resistant proxyGitHub Repo stars
MercureAn open, easy, fast, reliable and battery-efficient solution for real-time communicationsGitHub Repo stars
OONI ProbeNext generation OONI Probe. Library and CLI tool.GitHub Repo stars
RoadRunnerHigh-performance PHP application server, process manager written in Go and powered with pluginsGitHub Repo stars
syncthingOpen Source Continuous File SynchronizationGitHub Repo stars
traefikThe Cloud Native Application ProxyGitHub Repo stars
v2ray-coreA platform for building proxies to bypass network restrictionsGitHub Repo stars
YoMoStreaming Serverless Framework for Geo-distributed SystemGitHub Repo stars

If you'd like to see your project added to this list, please send us a PR.

Release Policy

quic-go always aims to support the latest two Go releases.

Contributing

We are always happy to welcome new contributors! We have a number of self-contained issues that are suitable for first-time contributors, they are tagged with help wanted. If you have any questions, please feel free to reach out by opening an issue or leaving a comment.

# Packages

No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
Package logging defines a logging interface for quic-go.
No description provided by the author
No description provided by the author
Package testutils contains utilities for simulating packet injection and man-in-the-middle (MITM) attacker tests.

# Functions

ConnectionIDFromBytes interprets b as a Connection ID.
Dial establishes a new QUIC connection to a server using a net.PacketConn.
DialAddr establishes a new QUIC connection to a server.
DialAddrEarly establishes a new 0-RTT QUIC connection to a server.
DialEarly establishes a new 0-RTT QUIC connection to a server using a net.PacketConn.
Listen listens for QUIC connections on a given net.PacketConn.
ListenAddr creates a QUIC server listening on a given address.
ListenAddrEarly works like ListenAddr, but it returns connections before the handshake completes.
ListenEarly works like Listen, but it returns connections before the handshake completes.
NewLRUTokenStore creates a new LRU cache for tokens received by the client.

# Constants

No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
Version1 is RFC 9000.
Version2 is RFC 9369.

# Variables

ConnectionTracingKey can be used to associate a ConnectionTracer with a Connection.
Err0RTTRejected is the returned from: * Open{Uni}Stream{Sync} * Accept{Uni}Stream * Stream.Read and Stream.Write when the server rejects a 0-RTT connection attempt.
ErrServerClosed is returned by the Listener or EarlyListener's Accept method after a call to Close.
QUICVersionContextKey can be used to find out the QUIC version of a TLS handshake from the context returned by tls.Config.ClientHelloInfo.Context.

# Structs

ClientHelloInfo contains information about an incoming connection attempt.
A ClientToken is a token received by the client.
Config contains all configuration data needed for a QUIC server or client.
ConnectionState records basic details about a QUIC connection.
DatagramTooLargeError is returned from Connection.SendDatagram if the payload is too large to be sent.
An EarlyListener listens for incoming QUIC connections, and returns them before the handshake completes.
A Listener listens for incoming QUIC connections.
A StreamError is used for Stream.CancelRead and Stream.CancelWrite.
The Transport is the central point to manage incoming and outgoing QUIC connections.

# Interfaces

A Connection is a QUIC connection between two peers.
A ConnectionIDGenerator is an interface that allows clients to implement their own format for the Connection IDs that servers/clients use as SrcConnectionID in QUIC packets.
An EarlyConnection is a connection that is handshaking.
OOBCapablePacketConn is a connection that allows the reading of ECN bits from the IP header.
A ReceiveStream is a unidirectional Receive Stream.
A SendStream is a unidirectional Send Stream.
Stream is the interface implemented by QUIC streams In addition to the errors listed on the Connection, calls to stream functions can return a StreamError if the stream is canceled.
No description provided by the author

# Type aliases

No description provided by the author
No description provided by the author
A ConnectionID is a QUIC Connection ID, as defined in RFC 9000.
No description provided by the author
No description provided by the author
No description provided by the author
StatelessResetKey is a key used to derive stateless reset tokens.
No description provided by the author
The StreamID is the ID of a QUIC stream.
TokenGeneratorKey is a key used to encrypt session resumption tokens.
No description provided by the author
No description provided by the author
A Version is a QUIC version number.
No description provided by the author
A VersionNumber is a QUIC version number.