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