github.com/tumi8/quic-go@v0.37.4-tum/README.md (about) 1 # A QUIC implementation in pure Go 2 3 <img src="docs/quic.png" width=303 height=124> 4 5 [![PkgGoDev](https://pkg.go.dev/badge/github.com/tumi8/quic-go)](https://pkg.go.dev/github.com/tumi8/quic-go) 6 [![Code Coverage](https://img.shields.io/codecov/c/github/quic-go/quic-go/master.svg?style=flat-square)](https://codecov.io/gh/quic-go/quic-go/) 7 8 quic-go is an implementation of the QUIC protocol ([RFC 9000](https://datatracker.ietf.org/doc/html/rfc9000), [RFC 9001](https://datatracker.ietf.org/doc/html/rfc9001), [RFC 9002](https://datatracker.ietf.org/doc/html/rfc9002)) in Go. It has support for HTTP/3 ([RFC 9114](https://datatracker.ietf.org/doc/html/rfc9114)), including QPACK ([RFC 9204](https://datatracker.ietf.org/doc/html/rfc9204)). 9 10 In addition to these base RFCs, it also implements the following RFCs: 11 * Unreliable Datagram Extension ([RFC 9221](https://datatracker.ietf.org/doc/html/rfc9221)) 12 * Datagram Packetization Layer Path MTU Discovery (DPLPMTUD, [RFC 8899](https://datatracker.ietf.org/doc/html/rfc8899)) 13 * QUIC Version 2 ([RFC 9369](https://datatracker.ietf.org/doc/html/rfc9369)) 14 15 ## Using QUIC 16 17 ### Running a Server 18 19 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. 20 21 ```go 22 udpConn, err := net.ListenUDP("udp4", &net.UDPAddr{Port: 1234}) 23 // ... error handling 24 tr := quic.Transport{ 25 Conn: udpConn, 26 } 27 ln, err := tr.Listen(tlsConf, quicConf) 28 // ... error handling 29 go func() { 30 for { 31 conn, err := ln.Accept() 32 // ... error handling 33 // handle the connection, usually in a new Go routine 34 } 35 } 36 ``` 37 38 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`). 39 40 As a shortcut, `quic.Listen` and `quic.ListenAddr` can be used without explicitly initializing a `quic.Transport`: 41 42 ``` 43 ln, err := quic.Listen(udpConn, tlsConf, quicConf) 44 ``` 45 46 When using the shortcut, it's not possible to reuse the same UDP socket for outgoing connections. 47 48 ### Running a Client 49 50 As mentioned above, multiple outgoing connections can share a single UDP socket, since QUIC uses Connection IDs to demultiplex connections. 51 52 ```go 53 ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) // 3s handshake timeout 54 defer cancel() 55 conn, err := tr.Dial(ctx, <server address>, <tls.Config>, <quic.Config>) 56 // ... error handling 57 ``` 58 59 As a shortcut, `quic.Dial` and `quic.DialAddr` can be used without explictly initializing a `quic.Transport`: 60 61 ```go 62 ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) // 3s handshake timeout 63 defer cancel() 64 conn, err := quic.Dial(ctx, conn, <server address>, <tls.Config>, <quic.Config>) 65 ``` 66 67 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. 68 69 ### Using a QUIC Connection 70 71 #### Accepting Streams 72 73 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](#quic-datagrams)), not on the connection itself. The stream state machine is described in detail in [Section 3 of RFC 9000](https://datatracker.ietf.org/doc/html/rfc9000#section-3). 74 75 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. 76 77 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: 78 79 ```go 80 for { 81 str, err := conn.AcceptStream(context.Background()) // for bidirectional streams 82 // ... error handling 83 // handle the stream, usually in a new Go routine 84 } 85 ``` 86 87 These functions return an error when the underlying QUIC connection is closed. 88 89 #### Opening Streams 90 91 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. 92 93 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: 94 95 ```go 96 ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) 97 defer cancel() 98 str, err := conn.OpenStreamSync(ctx) // wait up to 5s to open a new bidirectional stream 99 ``` 100 101 The asynchronous version never blocks. If it's currently not possible to open a new stream, it returns a `net.Error` timeout error: 102 103 ```go 104 str, err := conn.OpenStream() 105 if nerr, ok := err.(net.Error); ok && nerr.Timeout() { 106 // It's currently not possible to open another stream, 107 // but it might be possible later, once the peer allowed us to do so. 108 } 109 ``` 110 111 These functions return an error when the underlying QUIC connection is closed. 112 113 #### Using Streams 114 115 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. 116 117 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. 118 119 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. 120 121 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. 122 123 A bidirectional stream is only closed once both the read and the write side of the stream have been either closed and reset. Only then the peer is granted a new stream according to the maximum number of concurrent streams configured via `quic.Config.MaxIncomingStreams`. 124 125 ### Configuring QUIC 126 127 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. 128 129 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](https://datatracker.ietf.org/doc/html/rfc9000#section-10.3)). 130 131 ### Closing a Connection 132 133 #### When the remote Peer closes the Connection 134 135 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: 136 137 * `quic.VersionNegotiationError`: Happens during the handshake, if there is no overlap between our and the remote's supported QUIC versions. 138 * `quic.HandshakeTimeoutError`: Happens if the QUIC handshake doesn't complete within the time specified in `quic.Config.HandshakeTimeout`. 139 * `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. 140 * `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. 141 * `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. 142 * `quic.ApplicationError`: Happens when the remote decides to close the connection, see below. 143 144 #### Initiated by the Application 145 146 A `quic.Connection` can be closed using `CloseWithError`: 147 148 ```go 149 conn.CloseWithError(0x42, "error 0x42 occurred") 150 ``` 151 152 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. 153 154 On the receiver side, this is surfaced as a `quic.ApplicationError`. 155 156 ### QUIC Datagrams 157 158 Unreliable datagrams are a QUIC extension ([RFC 9221](https://datatracker.ietf.org/doc/html/rfc9221)) 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()`. 159 160 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 automatically retransmitted. 161 162 Datagrams are sent using the `SendMessage` method on the `quic.Connection`: 163 164 ```go 165 conn.SendMessage([]byte("foobar")) 166 ``` 167 168 And received using `ReceiveMessage`: 169 170 ```go 171 msg, err := conn.ReceiveMessage() 172 ``` 173 174 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). 175 176 177 178 ## Using HTTP/3 179 180 ### As a server 181 182 See the [example server](example/main.go). Starting a QUIC server is very similar to the standard library http package in Go: 183 184 ```go 185 http.Handle("/", http.FileServer(http.Dir(wwwDir))) 186 http3.ListenAndServeQUIC("localhost:4242", "/path/to/cert/chain.pem", "/path/to/privkey.pem", nil) 187 ``` 188 189 ### As a client 190 191 See the [example client](example/client/main.go). Use a `http3.RoundTripper` as a `Transport` in a `http.Client`. 192 193 ```go 194 http.Client{ 195 Transport: &http3.RoundTripper{}, 196 } 197 ``` 198 199 ## Projects using quic-go 200 201 | Project | Description | Stars | 202 |-----------------------------------------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------| 203 | [AdGuardHome](https://github.com/AdguardTeam/AdGuardHome) | Free and open source, powerful network-wide ads & trackers blocking DNS server. | ![GitHub Repo stars](https://img.shields.io/github/stars/AdguardTeam/AdGuardHome?style=flat-square) | 204 | [algernon](https://github.com/xyproto/algernon) | Small self-contained pure-Go web server with Lua, Markdown, HTTP/2, QUIC, Redis and PostgreSQL support | ![GitHub Repo stars](https://img.shields.io/github/stars/xyproto/algernon?style=flat-square) | 205 | [caddy](https://github.com/caddyserver/caddy/) | Fast, multi-platform web server with automatic HTTPS | ![GitHub Repo stars](https://img.shields.io/github/stars/caddyserver/caddy?style=flat-square) | 206 | [cloudflared](https://github.com/cloudflare/cloudflared) | A tunneling daemon that proxies traffic from the Cloudflare network to your origins | ![GitHub Repo stars](https://img.shields.io/github/stars/cloudflare/cloudflared?style=flat-square) | 207 | [go-libp2p](https://github.com/libp2p/go-libp2p) | libp2p implementation in Go, powering [Kubo](https://github.com/ipfs/kubo) (IPFS) and [Lotus](https://github.com/filecoin-project/lotus) (Filecoin), among others | ![GitHub Repo stars](https://img.shields.io/github/stars/libp2p/go-libp2p?style=flat-square) | 208 | [Mercure](https://github.com/dunglas/mercure) | An open, easy, fast, reliable and battery-efficient solution for real-time communications | ![GitHub Repo stars](https://img.shields.io/github/stars/dunglas/mercure?style=flat-square) | 209 | [OONI Probe](https://github.com/ooni/probe-cli) | Next generation OONI Probe. Library and CLI tool. | ![GitHub Repo stars](https://img.shields.io/github/stars/ooni/probe-cli?style=flat-square) | 210 | [syncthing](https://github.com/syncthing/syncthing/) | Open Source Continuous File Synchronization | ![GitHub Repo stars](https://img.shields.io/github/stars/syncthing/syncthing?style=flat-square) | 211 | [traefik](https://github.com/traefik/traefik) | The Cloud Native Application Proxy | ![GitHub Repo stars](https://img.shields.io/github/stars/traefik/traefik?style=flat-square) | 212 | [v2ray-core](https://github.com/v2fly/v2ray-core) | A platform for building proxies to bypass network restrictions | ![GitHub Repo stars](https://img.shields.io/github/stars/v2fly/v2ray-core?style=flat-square) | 213 | [YoMo](https://github.com/yomorun/yomo) | Streaming Serverless Framework for Geo-distributed System | ![GitHub Repo stars](https://img.shields.io/github/stars/yomorun/yomo?style=flat-square) | 214 215 If you'd like to see your project added to this list, please send us a PR. 216 217 ## Release Policy 218 219 quic-go always aims to support the latest two Go releases. 220 221 ### Dependency on forked crypto/tls 222 223 Since the standard library didn't provide any QUIC APIs before the Go 1.21 release, we had to fork crypto/tls to add the required APIs ourselves: [qtls for Go 1.20](https://github.com/tumi8/qtls-go1-20). 224 This had led to a lot of pain in the Go ecosystem, and we're happy that we can rely on Go 1.21 going forward. 225 226 ## Contributing 227 228 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](https://github.com/tumi8/quic-go/issues?q=is%3Aissue+is%3Aopen+label%3A%22help+wanted%22). If you have any questions, please feel free to reach out by opening an issue or leaving a comment.