xref: /freebsd/crypto/openssl/demos/guide/quic-server-non-block.c (revision e7be843b4a162e68651d3911f0357ed464915629)
1*e7be843bSPierre Pronchery /*
2*e7be843bSPierre Pronchery  *  Copyright 2024-2025 The OpenSSL Project Authors. All Rights Reserved.
3*e7be843bSPierre Pronchery  *
4*e7be843bSPierre Pronchery  *  Licensed under the Apache License 2.0 (the "License").  You may not use
5*e7be843bSPierre Pronchery  *  this file except in compliance with the License.  You can obtain a copy
6*e7be843bSPierre Pronchery  *  in the file LICENSE in the source distribution or at
7*e7be843bSPierre Pronchery  *  https://www.openssl.org/source/license.html
8*e7be843bSPierre Pronchery  */
9*e7be843bSPierre Pronchery 
10*e7be843bSPierre Pronchery /*
11*e7be843bSPierre Pronchery  * NB: Changes to this file should also be reflected in
12*e7be843bSPierre Pronchery  * doc/man7/ossl-guide-quic-server-non-block.pod
13*e7be843bSPierre Pronchery  */
14*e7be843bSPierre Pronchery 
15*e7be843bSPierre Pronchery #include <string.h>
16*e7be843bSPierre Pronchery 
17*e7be843bSPierre Pronchery /* Include the appropriate header file for SOCK_STREAM */
18*e7be843bSPierre Pronchery #ifdef _WIN32 /* Windows */
19*e7be843bSPierre Pronchery # include <stdarg.h>
20*e7be843bSPierre Pronchery # include <winsock2.h>
21*e7be843bSPierre Pronchery #else /* Linux/Unix */
22*e7be843bSPierre Pronchery # include <err.h>
23*e7be843bSPierre Pronchery # include <sys/socket.h>
24*e7be843bSPierre Pronchery # include <sys/select.h>
25*e7be843bSPierre Pronchery # include <netinet/in.h>
26*e7be843bSPierre Pronchery # include <unistd.h>
27*e7be843bSPierre Pronchery #endif
28*e7be843bSPierre Pronchery 
29*e7be843bSPierre Pronchery #include <openssl/bio.h>
30*e7be843bSPierre Pronchery #include <openssl/ssl.h>
31*e7be843bSPierre Pronchery #include <openssl/err.h>
32*e7be843bSPierre Pronchery #include <openssl/quic.h>
33*e7be843bSPierre Pronchery 
34*e7be843bSPierre Pronchery #ifdef _WIN32
35*e7be843bSPierre Pronchery static const char *progname;
36*e7be843bSPierre Pronchery 
vwarnx(const char * fmt,va_list ap)37*e7be843bSPierre Pronchery static void vwarnx(const char *fmt, va_list ap)
38*e7be843bSPierre Pronchery {
39*e7be843bSPierre Pronchery     if (progname != NULL)
40*e7be843bSPierre Pronchery         fprintf(stderr, "%s: ", progname);
41*e7be843bSPierre Pronchery     vfprintf(stderr, fmt, ap);
42*e7be843bSPierre Pronchery     putc('\n', stderr);
43*e7be843bSPierre Pronchery }
44*e7be843bSPierre Pronchery 
errx(int status,const char * fmt,...)45*e7be843bSPierre Pronchery static void errx(int status, const char *fmt, ...)
46*e7be843bSPierre Pronchery {
47*e7be843bSPierre Pronchery     va_list ap;
48*e7be843bSPierre Pronchery 
49*e7be843bSPierre Pronchery     va_start(ap, fmt);
50*e7be843bSPierre Pronchery     vwarnx(fmt, ap);
51*e7be843bSPierre Pronchery     va_end(ap);
52*e7be843bSPierre Pronchery     exit(status);
53*e7be843bSPierre Pronchery }
54*e7be843bSPierre Pronchery 
warnx(const char * fmt,...)55*e7be843bSPierre Pronchery static void warnx(const char *fmt, ...)
56*e7be843bSPierre Pronchery {
57*e7be843bSPierre Pronchery     va_list ap;
58*e7be843bSPierre Pronchery 
59*e7be843bSPierre Pronchery     va_start(ap, fmt);
60*e7be843bSPierre Pronchery     vwarnx(fmt, ap);
61*e7be843bSPierre Pronchery     va_end(ap);
62*e7be843bSPierre Pronchery }
63*e7be843bSPierre Pronchery #endif
64*e7be843bSPierre Pronchery 
65*e7be843bSPierre Pronchery /*
66*e7be843bSPierre Pronchery  * ALPN strings for TLS handshake. Only 'http/1.0' and 'hq-interop'
67*e7be843bSPierre Pronchery  * are accepted.
68*e7be843bSPierre Pronchery  */
69*e7be843bSPierre Pronchery static const unsigned char alpn_ossltest[] = {
70*e7be843bSPierre Pronchery     8,  'h', 't', 't', 'p', '/', '1', '.', '0',
71*e7be843bSPierre Pronchery     10, 'h', 'q', '-', 'i', 'n', 't', 'e', 'r', 'o', 'p',
72*e7be843bSPierre Pronchery };
73*e7be843bSPierre Pronchery 
74*e7be843bSPierre Pronchery /*
75*e7be843bSPierre Pronchery  * This callback validates and negotiates the desired ALPN on the server side.
76*e7be843bSPierre Pronchery  */
select_alpn(SSL * ssl,const unsigned char ** out,unsigned char * out_len,const unsigned char * in,unsigned int in_len,void * arg)77*e7be843bSPierre Pronchery static int select_alpn(SSL *ssl, const unsigned char **out,
78*e7be843bSPierre Pronchery                        unsigned char *out_len, const unsigned char *in,
79*e7be843bSPierre Pronchery                        unsigned int in_len, void *arg)
80*e7be843bSPierre Pronchery {
81*e7be843bSPierre Pronchery     if (SSL_select_next_proto((unsigned char **)out, out_len, alpn_ossltest,
82*e7be843bSPierre Pronchery                               sizeof(alpn_ossltest), in,
83*e7be843bSPierre Pronchery                               in_len) == OPENSSL_NPN_NEGOTIATED)
84*e7be843bSPierre Pronchery         return SSL_TLSEXT_ERR_OK;
85*e7be843bSPierre Pronchery     return SSL_TLSEXT_ERR_ALERT_FATAL;
86*e7be843bSPierre Pronchery }
87*e7be843bSPierre Pronchery 
88*e7be843bSPierre Pronchery /* Create SSL_CTX. */
create_ctx(const char * cert_path,const char * key_path)89*e7be843bSPierre Pronchery static SSL_CTX *create_ctx(const char *cert_path, const char *key_path)
90*e7be843bSPierre Pronchery {
91*e7be843bSPierre Pronchery     SSL_CTX *ctx;
92*e7be843bSPierre Pronchery 
93*e7be843bSPierre Pronchery     /*
94*e7be843bSPierre Pronchery      * An SSL_CTX holds shared configuration information for multiple
95*e7be843bSPierre Pronchery      * subsequent per-client connections. We specifically load a QUIC
96*e7be843bSPierre Pronchery      * server method here.
97*e7be843bSPierre Pronchery      */
98*e7be843bSPierre Pronchery     ctx = SSL_CTX_new(OSSL_QUIC_server_method());
99*e7be843bSPierre Pronchery     if (ctx == NULL)
100*e7be843bSPierre Pronchery         goto err;
101*e7be843bSPierre Pronchery 
102*e7be843bSPierre Pronchery     /*
103*e7be843bSPierre Pronchery      * Load the server's certificate *chain* file (PEM format), which includes
104*e7be843bSPierre Pronchery      * not only the leaf (end-entity) server certificate, but also any
105*e7be843bSPierre Pronchery      * intermediate issuer-CA certificates.  The leaf certificate must be the
106*e7be843bSPierre Pronchery      * first certificate in the file.
107*e7be843bSPierre Pronchery      *
108*e7be843bSPierre Pronchery      * In advanced use-cases this can be called multiple times, once per public
109*e7be843bSPierre Pronchery      * key algorithm for which the server has a corresponding certificate.
110*e7be843bSPierre Pronchery      * However, the corresponding private key (see below) must be loaded first,
111*e7be843bSPierre Pronchery      * *before* moving on to the next chain file.
112*e7be843bSPierre Pronchery      *
113*e7be843bSPierre Pronchery      * The requisite files "chain.pem" and "pkey.pem" can be generated by running
114*e7be843bSPierre Pronchery      * "make chain" in this directory.  If the server will be executed from some
115*e7be843bSPierre Pronchery      * other directory, move or copy the files there.
116*e7be843bSPierre Pronchery      */
117*e7be843bSPierre Pronchery     if (SSL_CTX_use_certificate_chain_file(ctx, cert_path) <= 0) {
118*e7be843bSPierre Pronchery         fprintf(stderr, "couldn't load certificate file: %s\n", cert_path);
119*e7be843bSPierre Pronchery         goto err;
120*e7be843bSPierre Pronchery     }
121*e7be843bSPierre Pronchery 
122*e7be843bSPierre Pronchery     /*
123*e7be843bSPierre Pronchery      * Load the corresponding private key, this also checks that the private
124*e7be843bSPierre Pronchery      * key matches the just loaded end-entity certificate.  It does not check
125*e7be843bSPierre Pronchery      * whether the certificate chain is valid, the certificates could be
126*e7be843bSPierre Pronchery      * expired, or may otherwise fail to form a chain that a client can validate.
127*e7be843bSPierre Pronchery      */
128*e7be843bSPierre Pronchery     if (SSL_CTX_use_PrivateKey_file(ctx, key_path, SSL_FILETYPE_PEM) <= 0) {
129*e7be843bSPierre Pronchery         fprintf(stderr, "couldn't load key file: %s\n", key_path);
130*e7be843bSPierre Pronchery         goto err;
131*e7be843bSPierre Pronchery     }
132*e7be843bSPierre Pronchery 
133*e7be843bSPierre Pronchery     /*
134*e7be843bSPierre Pronchery      * Clients rarely employ certificate-based authentication, and so we don't
135*e7be843bSPierre Pronchery      * require "mutual" TLS authentication (indeed there's no way to know
136*e7be843bSPierre Pronchery      * whether or how the client authenticated the server, so the term "mutual"
137*e7be843bSPierre Pronchery      * is potentially misleading).
138*e7be843bSPierre Pronchery      *
139*e7be843bSPierre Pronchery      * Since we're not soliciting or processing client certificates, we don't
140*e7be843bSPierre Pronchery      * need to configure a trusted-certificate store, so no call to
141*e7be843bSPierre Pronchery      * SSL_CTX_set_default_verify_paths() is needed.  The server's own
142*e7be843bSPierre Pronchery      * certificate chain is assumed valid.
143*e7be843bSPierre Pronchery      */
144*e7be843bSPierre Pronchery     SSL_CTX_set_verify(ctx, SSL_VERIFY_NONE, NULL);
145*e7be843bSPierre Pronchery 
146*e7be843bSPierre Pronchery     /* Setup ALPN negotiation callback to decide which ALPN is accepted. */
147*e7be843bSPierre Pronchery     SSL_CTX_set_alpn_select_cb(ctx, select_alpn, NULL);
148*e7be843bSPierre Pronchery 
149*e7be843bSPierre Pronchery     return ctx;
150*e7be843bSPierre Pronchery 
151*e7be843bSPierre Pronchery err:
152*e7be843bSPierre Pronchery     SSL_CTX_free(ctx);
153*e7be843bSPierre Pronchery     return NULL;
154*e7be843bSPierre Pronchery }
155*e7be843bSPierre Pronchery 
156*e7be843bSPierre Pronchery /* Create UDP socket on the given port. */
create_socket(uint16_t port)157*e7be843bSPierre Pronchery static int create_socket(uint16_t port)
158*e7be843bSPierre Pronchery {
159*e7be843bSPierre Pronchery     int fd;
160*e7be843bSPierre Pronchery     struct sockaddr_in sa = {0};
161*e7be843bSPierre Pronchery 
162*e7be843bSPierre Pronchery     /* Retrieve the file descriptor for a new UDP socket */
163*e7be843bSPierre Pronchery     if ((fd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0) {
164*e7be843bSPierre Pronchery         fprintf(stderr, "cannot create socket");
165*e7be843bSPierre Pronchery         return -1;
166*e7be843bSPierre Pronchery     }
167*e7be843bSPierre Pronchery 
168*e7be843bSPierre Pronchery     sa.sin_family = AF_INET;
169*e7be843bSPierre Pronchery     sa.sin_port = htons(port);
170*e7be843bSPierre Pronchery 
171*e7be843bSPierre Pronchery     /* Bind to the new UDP socket on localhost */
172*e7be843bSPierre Pronchery     if (bind(fd, (const struct sockaddr *)&sa, sizeof(sa)) < 0) {
173*e7be843bSPierre Pronchery         fprintf(stderr, "cannot bind to %u\n", port);
174*e7be843bSPierre Pronchery         BIO_closesocket(fd);
175*e7be843bSPierre Pronchery         return -1;
176*e7be843bSPierre Pronchery     }
177*e7be843bSPierre Pronchery 
178*e7be843bSPierre Pronchery     /* Set port to nonblocking mode */
179*e7be843bSPierre Pronchery     if (BIO_socket_nbio(fd, 1) <= 0) {
180*e7be843bSPierre Pronchery         fprintf(stderr, "Unable to set port to nonblocking mode");
181*e7be843bSPierre Pronchery         BIO_closesocket(fd);
182*e7be843bSPierre Pronchery         return -1;
183*e7be843bSPierre Pronchery     }
184*e7be843bSPierre Pronchery 
185*e7be843bSPierre Pronchery     return fd;
186*e7be843bSPierre Pronchery }
187*e7be843bSPierre Pronchery 
188*e7be843bSPierre Pronchery /**
189*e7be843bSPierre Pronchery  * @brief Waits for activity on the SSL socket, either for reading or writing.
190*e7be843bSPierre Pronchery  *
191*e7be843bSPierre Pronchery  * This function monitors the underlying file descriptor of the given SSL
192*e7be843bSPierre Pronchery  * connection to determine when it is ready for reading or writing, or both.
193*e7be843bSPierre Pronchery  * It uses the select function to wait until the socket is either readable
194*e7be843bSPierre Pronchery  * or writable, depending on what the SSL connection requires.
195*e7be843bSPierre Pronchery  *
196*e7be843bSPierre Pronchery  * @param ssl A pointer to the SSL object representing the connection.
197*e7be843bSPierre Pronchery  *
198*e7be843bSPierre Pronchery  * @note This function blocks until there is activity on the socket. In a real
199*e7be843bSPierre Pronchery  * application, you might want to perform other tasks while waiting, such as
200*e7be843bSPierre Pronchery  * updating a GUI or handling other connections.
201*e7be843bSPierre Pronchery  *
202*e7be843bSPierre Pronchery  * @note This function uses select for simplicity and portability. Depending
203*e7be843bSPierre Pronchery  * on your application's requirements, you might consider using other
204*e7be843bSPierre Pronchery  * mechanisms like poll or epoll for handling multiple file descriptors.
205*e7be843bSPierre Pronchery  */
wait_for_activity(SSL * ssl)206*e7be843bSPierre Pronchery static void wait_for_activity(SSL *ssl)
207*e7be843bSPierre Pronchery {
208*e7be843bSPierre Pronchery     int sock, isinfinite;
209*e7be843bSPierre Pronchery     fd_set read_fd, write_fd;
210*e7be843bSPierre Pronchery     struct timeval tv;
211*e7be843bSPierre Pronchery     struct timeval *tvp = NULL;
212*e7be843bSPierre Pronchery 
213*e7be843bSPierre Pronchery     /* Get hold of the underlying file descriptor for the socket */
214*e7be843bSPierre Pronchery     if ((sock = SSL_get_fd(ssl)) == -1) {
215*e7be843bSPierre Pronchery         fprintf(stderr, "Unable to get file descriptor");
216*e7be843bSPierre Pronchery         return;
217*e7be843bSPierre Pronchery     }
218*e7be843bSPierre Pronchery 
219*e7be843bSPierre Pronchery     /* Initialize the fd_set structure */
220*e7be843bSPierre Pronchery     FD_ZERO(&read_fd);
221*e7be843bSPierre Pronchery     FD_ZERO(&write_fd);
222*e7be843bSPierre Pronchery 
223*e7be843bSPierre Pronchery     /*
224*e7be843bSPierre Pronchery      * Determine if we would like to write to the socket, read from it, or both.
225*e7be843bSPierre Pronchery      */
226*e7be843bSPierre Pronchery     if (SSL_net_write_desired(ssl))
227*e7be843bSPierre Pronchery         FD_SET(sock, &write_fd);
228*e7be843bSPierre Pronchery     if (SSL_net_read_desired(ssl))
229*e7be843bSPierre Pronchery         FD_SET(sock, &read_fd);
230*e7be843bSPierre Pronchery 
231*e7be843bSPierre Pronchery     /*
232*e7be843bSPierre Pronchery      * Find out when OpenSSL would next like to be called, regardless of
233*e7be843bSPierre Pronchery      * whether the state of the underlying socket has changed or not.
234*e7be843bSPierre Pronchery      */
235*e7be843bSPierre Pronchery     if (SSL_get_event_timeout(ssl, &tv, &isinfinite) && !isinfinite)
236*e7be843bSPierre Pronchery         tvp = &tv;
237*e7be843bSPierre Pronchery 
238*e7be843bSPierre Pronchery     /*
239*e7be843bSPierre Pronchery      * Wait until the socket is writeable or readable. We use select here
240*e7be843bSPierre Pronchery      * for the sake of simplicity and portability, but you could equally use
241*e7be843bSPierre Pronchery      * poll/epoll or similar functions
242*e7be843bSPierre Pronchery      *
243*e7be843bSPierre Pronchery      * NOTE: For the purposes of this demonstration code this effectively
244*e7be843bSPierre Pronchery      * makes this demo block until it has something more useful to do. In a
245*e7be843bSPierre Pronchery      * real application you probably want to go and do other work here (e.g.
246*e7be843bSPierre Pronchery      * update a GUI, or service other connections).
247*e7be843bSPierre Pronchery      *
248*e7be843bSPierre Pronchery      * Let's say for example that you want to update the progress counter on
249*e7be843bSPierre Pronchery      * a GUI every 100ms. One way to do that would be to use the timeout in
250*e7be843bSPierre Pronchery      * the last parameter to "select" below. If the tvp value is greater
251*e7be843bSPierre Pronchery      * than 100ms then use 100ms instead. Then, when select returns, you
252*e7be843bSPierre Pronchery      * check if it did so because of activity on the file descriptors or
253*e7be843bSPierre Pronchery      * because of the timeout. If the 100ms GUI timeout has expired but the
254*e7be843bSPierre Pronchery      * tvp timeout has not then go and update the GUI and then restart the
255*e7be843bSPierre Pronchery      * "select" (with updated timeouts).
256*e7be843bSPierre Pronchery      */
257*e7be843bSPierre Pronchery 
258*e7be843bSPierre Pronchery     select(sock + 1, &read_fd, &write_fd, NULL, tvp);
259*e7be843bSPierre Pronchery }
260*e7be843bSPierre Pronchery 
261*e7be843bSPierre Pronchery /**
262*e7be843bSPierre Pronchery  * @brief Handles I/O failures on an SSL connection based on the result code.
263*e7be843bSPierre Pronchery  *
264*e7be843bSPierre Pronchery  * This function processes the result of an SSL I/O operation and handles
265*e7be843bSPierre Pronchery  * different types of errors that may occur during the operation. It takes
266*e7be843bSPierre Pronchery  * appropriate actions such as retrying the operation, reporting errors, or
267*e7be843bSPierre Pronchery  * returning specific status codes based on the error type.
268*e7be843bSPierre Pronchery  *
269*e7be843bSPierre Pronchery  * @param ssl A pointer to the SSL object representing the connection.
270*e7be843bSPierre Pronchery  * @param res The result code from the SSL I/O operation.
271*e7be843bSPierre Pronchery  * @return An integer indicating the outcome:
272*e7be843bSPierre Pronchery  *         - 1: Temporary failure, the operation should be retried.
273*e7be843bSPierre Pronchery  *         - 0: EOF, indicating the connection has been closed.
274*e7be843bSPierre Pronchery  *         - -1: A fatal error occurred or the connection has been reset.
275*e7be843bSPierre Pronchery  *
276*e7be843bSPierre Pronchery  * @note This function may block if a temporary failure occurs and
277*e7be843bSPierre Pronchery  * wait_for_activity() is called.
278*e7be843bSPierre Pronchery  *
279*e7be843bSPierre Pronchery  * @note If the failure is due to an SSL verification error, additional
280*e7be843bSPierre Pronchery  * information will be logged to stderr.
281*e7be843bSPierre Pronchery  */
handle_io_failure(SSL * ssl,int res)282*e7be843bSPierre Pronchery static int handle_io_failure(SSL *ssl, int res)
283*e7be843bSPierre Pronchery {
284*e7be843bSPierre Pronchery     switch (SSL_get_error(ssl, res)) {
285*e7be843bSPierre Pronchery     case SSL_ERROR_WANT_READ:
286*e7be843bSPierre Pronchery     case SSL_ERROR_WANT_WRITE:
287*e7be843bSPierre Pronchery         /* Temporary failure. Wait until we can read/write and try again */
288*e7be843bSPierre Pronchery         wait_for_activity(ssl);
289*e7be843bSPierre Pronchery         return 1;
290*e7be843bSPierre Pronchery 
291*e7be843bSPierre Pronchery     case SSL_ERROR_ZERO_RETURN:
292*e7be843bSPierre Pronchery     case SSL_ERROR_NONE:
293*e7be843bSPierre Pronchery         /* EOF */
294*e7be843bSPierre Pronchery         return 0;
295*e7be843bSPierre Pronchery 
296*e7be843bSPierre Pronchery     case SSL_ERROR_SYSCALL:
297*e7be843bSPierre Pronchery         return -1;
298*e7be843bSPierre Pronchery 
299*e7be843bSPierre Pronchery     case SSL_ERROR_SSL:
300*e7be843bSPierre Pronchery         /*
301*e7be843bSPierre Pronchery          * Some stream fatal error occurred. This could be because of a
302*e7be843bSPierre Pronchery          * stream reset - or some failure occurred on the underlying
303*e7be843bSPierre Pronchery          * connection.
304*e7be843bSPierre Pronchery          */
305*e7be843bSPierre Pronchery         switch (SSL_get_stream_read_state(ssl)) {
306*e7be843bSPierre Pronchery         case SSL_STREAM_STATE_RESET_REMOTE:
307*e7be843bSPierre Pronchery             printf("Stream reset occurred\n");
308*e7be843bSPierre Pronchery             /*
309*e7be843bSPierre Pronchery              * The stream has been reset but the connection is still
310*e7be843bSPierre Pronchery              * healthy.
311*e7be843bSPierre Pronchery              */
312*e7be843bSPierre Pronchery             break;
313*e7be843bSPierre Pronchery 
314*e7be843bSPierre Pronchery         case SSL_STREAM_STATE_CONN_CLOSED:
315*e7be843bSPierre Pronchery             printf("Connection closed\n");
316*e7be843bSPierre Pronchery             /* Connection is already closed. */
317*e7be843bSPierre Pronchery             break;
318*e7be843bSPierre Pronchery 
319*e7be843bSPierre Pronchery         default:
320*e7be843bSPierre Pronchery             printf("Unknown stream failure\n");
321*e7be843bSPierre Pronchery             break;
322*e7be843bSPierre Pronchery         }
323*e7be843bSPierre Pronchery         /*
324*e7be843bSPierre Pronchery          * If the failure is due to a verification error we can get more
325*e7be843bSPierre Pronchery          * information about it from SSL_get_verify_result().
326*e7be843bSPierre Pronchery          */
327*e7be843bSPierre Pronchery         if (SSL_get_verify_result(ssl) != X509_V_OK)
328*e7be843bSPierre Pronchery             printf("Verify error: %s\n",
329*e7be843bSPierre Pronchery                    X509_verify_cert_error_string(SSL_get_verify_result(ssl)));
330*e7be843bSPierre Pronchery         return -1;
331*e7be843bSPierre Pronchery 
332*e7be843bSPierre Pronchery     default:
333*e7be843bSPierre Pronchery         return -1;
334*e7be843bSPierre Pronchery     }
335*e7be843bSPierre Pronchery }
336*e7be843bSPierre Pronchery 
337*e7be843bSPierre Pronchery /*
338*e7be843bSPierre Pronchery  * Main loop for server to accept QUIC connections.
339*e7be843bSPierre Pronchery  * Echo every request back to the client.
340*e7be843bSPierre Pronchery  */
run_quic_server(SSL_CTX * ctx,int fd)341*e7be843bSPierre Pronchery static int run_quic_server(SSL_CTX *ctx, int fd)
342*e7be843bSPierre Pronchery {
343*e7be843bSPierre Pronchery     int ok = -1;
344*e7be843bSPierre Pronchery     int ret, eof;
345*e7be843bSPierre Pronchery     SSL *listener, *conn = NULL;
346*e7be843bSPierre Pronchery     unsigned char buf[8192];
347*e7be843bSPierre Pronchery     size_t nread, total_read, total_written;
348*e7be843bSPierre Pronchery 
349*e7be843bSPierre Pronchery     /* Create a new QUIC listener */
350*e7be843bSPierre Pronchery     if ((listener = SSL_new_listener(ctx, 0)) == NULL)
351*e7be843bSPierre Pronchery         goto err;
352*e7be843bSPierre Pronchery 
353*e7be843bSPierre Pronchery     /* Provide the listener with our UDP socket. */
354*e7be843bSPierre Pronchery     if (!SSL_set_fd(listener, fd))
355*e7be843bSPierre Pronchery         goto err;
356*e7be843bSPierre Pronchery 
357*e7be843bSPierre Pronchery     /*
358*e7be843bSPierre Pronchery      * Set the listener mode to non-blocking, which is inherited by
359*e7be843bSPierre Pronchery      * child objects.
360*e7be843bSPierre Pronchery      */
361*e7be843bSPierre Pronchery     if (!SSL_set_blocking_mode(listener, 0))
362*e7be843bSPierre Pronchery         goto err;
363*e7be843bSPierre Pronchery 
364*e7be843bSPierre Pronchery     /*
365*e7be843bSPierre Pronchery      * Begin listening. Note that is not usually needed as SSL_accept_connection
366*e7be843bSPierre Pronchery      * will implicitly start listening. It is only needed if a server wishes to
367*e7be843bSPierre Pronchery      * ensure it has started to accept incoming connections but does not wish to
368*e7be843bSPierre Pronchery      * actually call SSL_accept_connection yet.
369*e7be843bSPierre Pronchery      */
370*e7be843bSPierre Pronchery     if (!SSL_listen(listener))
371*e7be843bSPierre Pronchery         goto err;
372*e7be843bSPierre Pronchery 
373*e7be843bSPierre Pronchery     /*
374*e7be843bSPierre Pronchery      * Begin an infinite loop of listening for connections. We will only
375*e7be843bSPierre Pronchery      * exit this loop if we encounter an error.
376*e7be843bSPierre Pronchery      */
377*e7be843bSPierre Pronchery     for (;;) {
378*e7be843bSPierre Pronchery         eof = 0;
379*e7be843bSPierre Pronchery         total_read = 0;
380*e7be843bSPierre Pronchery         total_written = 0;
381*e7be843bSPierre Pronchery 
382*e7be843bSPierre Pronchery         /* Pristine error stack for each new connection */
383*e7be843bSPierre Pronchery         ERR_clear_error();
384*e7be843bSPierre Pronchery 
385*e7be843bSPierre Pronchery         /* Block while waiting for a client connection */
386*e7be843bSPierre Pronchery         printf("Waiting for connection\n");
387*e7be843bSPierre Pronchery         while ((conn = SSL_accept_connection(listener, 0)) == NULL)
388*e7be843bSPierre Pronchery             wait_for_activity(listener);
389*e7be843bSPierre Pronchery         printf("Accepted new connection\n");
390*e7be843bSPierre Pronchery 
391*e7be843bSPierre Pronchery         /* Read from client until the client sends a end of stream packet */
392*e7be843bSPierre Pronchery         while (!eof) {
393*e7be843bSPierre Pronchery             ret = SSL_read_ex(conn, buf + total_read, sizeof(buf) - total_read,
394*e7be843bSPierre Pronchery                               &nread);
395*e7be843bSPierre Pronchery             total_read += nread;
396*e7be843bSPierre Pronchery             if (total_read >= 8192) {
397*e7be843bSPierre Pronchery                 fprintf(stderr, "Could not fit all data into buffer\n");
398*e7be843bSPierre Pronchery                 goto err;
399*e7be843bSPierre Pronchery             }
400*e7be843bSPierre Pronchery 
401*e7be843bSPierre Pronchery             switch (handle_io_failure(conn, ret)) {
402*e7be843bSPierre Pronchery             case 1:
403*e7be843bSPierre Pronchery                 continue; /* Retry */
404*e7be843bSPierre Pronchery             case 0:
405*e7be843bSPierre Pronchery                 /* Reached end of stream */
406*e7be843bSPierre Pronchery                 if (!SSL_has_pending(conn))
407*e7be843bSPierre Pronchery                     eof = 1;
408*e7be843bSPierre Pronchery                 break;
409*e7be843bSPierre Pronchery             default:
410*e7be843bSPierre Pronchery                 fprintf(stderr, "Failed reading remaining data\n");
411*e7be843bSPierre Pronchery                 goto err;
412*e7be843bSPierre Pronchery             }
413*e7be843bSPierre Pronchery         }
414*e7be843bSPierre Pronchery 
415*e7be843bSPierre Pronchery         /* Echo client input */
416*e7be843bSPierre Pronchery         while (!SSL_write_ex2(conn, buf,
417*e7be843bSPierre Pronchery                               total_read,
418*e7be843bSPierre Pronchery                               SSL_WRITE_FLAG_CONCLUDE, &total_written)) {
419*e7be843bSPierre Pronchery             if (handle_io_failure(conn, 0) == 1)
420*e7be843bSPierre Pronchery                 continue;
421*e7be843bSPierre Pronchery             fprintf(stderr, "Failed to write data\n");
422*e7be843bSPierre Pronchery             goto err;
423*e7be843bSPierre Pronchery         }
424*e7be843bSPierre Pronchery 
425*e7be843bSPierre Pronchery         if (total_read != total_written)
426*e7be843bSPierre Pronchery             fprintf(stderr, "Failed to echo data [read: %lu, written: %lu]\n",
427*e7be843bSPierre Pronchery                     total_read, total_written);
428*e7be843bSPierre Pronchery 
429*e7be843bSPierre Pronchery         /*
430*e7be843bSPierre Pronchery          * Shut down the connection. We may need to call this multiple times
431*e7be843bSPierre Pronchery          * to ensure the connection is shutdown completely.
432*e7be843bSPierre Pronchery          */
433*e7be843bSPierre Pronchery         while ((ret = SSL_shutdown(conn)) != 1) {
434*e7be843bSPierre Pronchery             if (ret < 0 && handle_io_failure(conn, ret) == 1)
435*e7be843bSPierre Pronchery                 continue; /* Retry */
436*e7be843bSPierre Pronchery         }
437*e7be843bSPierre Pronchery 
438*e7be843bSPierre Pronchery         SSL_free(conn);
439*e7be843bSPierre Pronchery     }
440*e7be843bSPierre Pronchery 
441*e7be843bSPierre Pronchery     ok = EXIT_SUCCESS;
442*e7be843bSPierre Pronchery err:
443*e7be843bSPierre Pronchery     SSL_free(listener);
444*e7be843bSPierre Pronchery     return ok;
445*e7be843bSPierre Pronchery }
446*e7be843bSPierre Pronchery 
447*e7be843bSPierre Pronchery /* Minimal QUIC HTTP/1.0 server. */
main(int argc,char * argv[])448*e7be843bSPierre Pronchery int main(int argc, char *argv[])
449*e7be843bSPierre Pronchery {
450*e7be843bSPierre Pronchery     int res = EXIT_FAILURE;
451*e7be843bSPierre Pronchery     SSL_CTX *ctx = NULL;
452*e7be843bSPierre Pronchery     int fd;
453*e7be843bSPierre Pronchery     unsigned long port;
454*e7be843bSPierre Pronchery 
455*e7be843bSPierre Pronchery #ifdef _WIN32
456*e7be843bSPierre Pronchery     progname = argv[0];
457*e7be843bSPierre Pronchery #endif
458*e7be843bSPierre Pronchery 
459*e7be843bSPierre Pronchery     if (argc != 4)
460*e7be843bSPierre Pronchery         errx(res, "usage: %s <port> <server.crt> <server.key>", argv[0]);
461*e7be843bSPierre Pronchery 
462*e7be843bSPierre Pronchery     /* Create SSL_CTX that supports QUIC. */
463*e7be843bSPierre Pronchery     if ((ctx = create_ctx(argv[2], argv[3])) == NULL) {
464*e7be843bSPierre Pronchery         ERR_print_errors_fp(stderr);
465*e7be843bSPierre Pronchery         errx(res, "Failed to create context");
466*e7be843bSPierre Pronchery     }
467*e7be843bSPierre Pronchery 
468*e7be843bSPierre Pronchery     /* Parse port number from command line arguments. */
469*e7be843bSPierre Pronchery     port = strtoul(argv[1], NULL, 0);
470*e7be843bSPierre Pronchery     if (port == 0 || port > UINT16_MAX) {
471*e7be843bSPierre Pronchery         SSL_CTX_free(ctx);
472*e7be843bSPierre Pronchery         errx(res, "Failed to parse port number");
473*e7be843bSPierre Pronchery     }
474*e7be843bSPierre Pronchery 
475*e7be843bSPierre Pronchery     /* Create and bind a UDP socket. */
476*e7be843bSPierre Pronchery     if ((fd = create_socket((uint16_t)port)) < 0) {
477*e7be843bSPierre Pronchery         SSL_CTX_free(ctx);
478*e7be843bSPierre Pronchery         ERR_print_errors_fp(stderr);
479*e7be843bSPierre Pronchery         errx(res, "Failed to create socket");
480*e7be843bSPierre Pronchery     }
481*e7be843bSPierre Pronchery 
482*e7be843bSPierre Pronchery     /* QUIC server connection acceptance loop. */
483*e7be843bSPierre Pronchery     if (run_quic_server(ctx, fd) < 0) {
484*e7be843bSPierre Pronchery         SSL_CTX_free(ctx);
485*e7be843bSPierre Pronchery         BIO_closesocket(fd);
486*e7be843bSPierre Pronchery         ERR_print_errors_fp(stderr);
487*e7be843bSPierre Pronchery         errx(res, "Error in QUIC server loop");
488*e7be843bSPierre Pronchery     }
489*e7be843bSPierre Pronchery 
490*e7be843bSPierre Pronchery     /* Free resources. */
491*e7be843bSPierre Pronchery     SSL_CTX_free(ctx);
492*e7be843bSPierre Pronchery     BIO_closesocket(fd);
493*e7be843bSPierre Pronchery     res = EXIT_SUCCESS;
494*e7be843bSPierre Pronchery     return res;
495*e7be843bSPierre Pronchery }
496