Debian Codegraph @

upstream/debian-unstable/man7/ossl-guide-quic-server-non-block.7ssl

raw
1 .\" -*- mode: troff; coding: utf-8 -*-
2 .\" Automatically generated by Pod::Man 5.0102 (Pod::Simple 3.45)
3 .\"
4 .\" Standard preamble:
5 .\" ========================================================================
6 .de Sp \" Vertical space (when we can't use .PP)
7 .if t .sp .5v
8 .if n .sp
9 ..
10 .de Vb \" Begin verbatim text
11 .ft CW
12 .nf
13 .ne \\$1
14 ..
15 .de Ve \" End verbatim text
16 .ft R
17 .fi
18 ..
19 .\" \*(C` and \*(C' are quotes in nroff, nothing in troff, for use with C<>.
20 .ie n \{\
21 . ds C` ""
22 . ds C' ""
23 'br\}
24 .el\{\
25 . ds C`
26 . ds C'
27 'br\}
28 .\"
29 .\" Escape single quotes in literal strings from groff's Unicode transform.
30 .ie \n(.g .ds Aq \(aq
31 .el .ds Aq '
32 .\"
33 .\" If the F register is >0, we'll generate index entries on stderr for
34 .\" titles (.TH), headers (.SH), subsections (.SS), items (.Ip), and index
35 .\" entries marked with X<> in POD. Of course, you'll have to process the
36 .\" output yourself in some meaningful fashion.
37 .\"
38 .\" Avoid warning from groff about undefined register 'F'.
39 .de IX
40 ..
41 .nr rF 0
42 .if \n(.g .if rF .nr rF 1
43 .if (\n(rF:(\n(.g==0)) \{\
44 . if \nF \{\
45 . de IX
46 . tm Index:\\$1\t\\n%\t"\\$2"
47 ..
48 . if !\nF==2 \{\
49 . nr % 0
50 . nr F 2
51 . \}
52 . \}
53 .\}
54 .rr rF
55 .\" ========================================================================
56 .\"
57 .IX Title "OSSL-GUIDE-QUIC-SERVER-NON-BLOCK 7SSL"
58 .TH OSSL-GUIDE-QUIC-SERVER-NON-BLOCK 7SSL 2026-04-07 3.6.2 OpenSSL
59 .\" For nroff, turn off justification. Always turn off hyphenation; it makes
60 .\" way too many mistakes in technical documents.
61 .if n .ad l
62 .nh
63 .SH NAME
64 ossl\-guide\-quic\-server\-non\-block
65 \&\- OpenSSL Guide: Writing a simple nonblocking QUIC server
66 .SH "SIMPLE NONBLOCKING QUIC SERVER EXAMPLE"
67 .IX Header "SIMPLE NONBLOCKING QUIC SERVER EXAMPLE"
68 This page presents various source code samples demonstrating how to write a
69 simple, non-concurrent, QUIC "echo" server application which accepts one client
70 connection at a time, echoing input from the client back to the same client.
71 Once the current client disconnects, the next client connection is accepted.
72 .PP
73 The server only accepts \f(CW\*(C`http/1.0\*(C'\fR and \f(CW\*(C`hq\-interop\*(C'\fR ALPN's and doesn't actually
74 implement HTTP but only does a simple echo. This is non-standard and will not
75 be supported by real world servers. This is for demonstration purposes only.
76 .PP
77 There are various methods to test this server: \fBquic\-client\-block.c\fR and
78 \&\fBquic\-client\-non\-block.c\fR will send a basic HTTP/1.0 request, which the server
79 will echo back. You can also test this server by running
80 \&\f(CW\*(C`openssl s_client \-connect localhost:4443 \-4 \-quic \-alpn http/1.0\*(C'\fR and entering
81 text that will be echoed back by the server.
82 .PP
83 Both the listening socket and connected socket are "nonblocking". However,
84 we use \fBselect()\fR to make the listening socket block when it cannot read/write.
85 Rather than stopping and waiting, your application may need to go and do other
86 tasks whilst the \fBSSL\fR object is unable to read/write. For example: updating a
87 GUI or performing operations on some other connection or stream.
88 .PP
89 The complete source code for this example nonblocking QUIC server is available
90 in the \fBdemos/guide\fR directory of the OpenSSL source distribution in the file
91 \&\fBquic\-server\-non\-block.c\fR. It is also available online at
92 <https://github.com/openssl/openssl/blob/master/demos/guide/quic\-server\-non\-block.c>.
93 .PP
94 We assume that you already have OpenSSL installed on your system; that you
95 already have some fundamental understanding of OpenSSL concepts and QUIC (see
96 \&\fBossl\-guide\-libraries\-introduction\fR\|(7) and \fBossl\-guide\-quic\-introduction\fR\|(7));
97 and that you know how to write and build C code and link it against the
98 libcrypto and libssl libraries that are provided by OpenSSL. It also assumes
99 that you have a basic understanding of UDP/IP and sockets.
100 .SS "Creating the SSL_CTX and SSL objects"
101 .IX Subsection "Creating the SSL_CTX and SSL objects"
102 The first step is to create an \fBSSL_CTX\fR object for our server. We use the
103 \&\fBSSL_CTX_new\fR\|(3) function for this purpose. We pass as an argument the return
104 value of the function \fBOSSL_QUIC_server_method\fR\|(3). You should use this method
105 whenever you are writing a QUIC server.
106 .PP
107 .Vb 8
108 \& /*
109 \& * An SSL_CTX holds shared configuration information for multiple
110 \& * subsequent per\-client SSL connections. We specifically load a QUIC
111 \& * server method here.
112 \& */
113 \& ctx = SSL_CTX_new(OSSL_QUIC_server_method());
114 \& if (ctx == NULL)
115 \& goto err;
116 .Ve
117 .PP
118 Servers need a private key and certificate. Intermediate issuer CA
119 certificates are often required, and both the server (end-entity or EE)
120 certificate and the issuer ("chain") certificates are most easily configured in
121 a single "chain file". Below we load such a chain file (the EE certificate
122 must appear first), and then load the corresponding private key, checking that
123 it matches the server certificate. No checks are performed to check the
124 integrity of the chain (CA signatures or certificate expiration dates, for
125 example), but we do verify the consistency of the private key with the
126 corresponding certificate.
127 .PP
128 .Vb 10
129 \& /*
130 \& * Load the server\*(Aqs certificate *chain* file (PEM format), which includes
131 \& * not only the leaf (end\-entity) server certificate, but also any
132 \& * intermediate issuer\-CA certificates. The leaf certificate must be the
133 \& * first certificate in the file.
134 \& *
135 \& * In advanced use\-cases this can be called multiple times, once per public
136 \& * key algorithm for which the server has a corresponding certificate.
137 \& * However, the corresponding private key (see below) must be loaded first,
138 \& * *before* moving on to the next chain file.
139 \& */
140 \& if (SSL_CTX_use_certificate_chain_file(ctx, cert_path) <= 0) {
141 \& fprintf(stderr, "couldn\*(Aqt load certificate file: %s\en", cert_path);
142 \& goto err;
143 \& }
144 \&
145 \& /*
146 \& * Load the corresponding private key, this also checks that the private
147 \& * key matches the just loaded end\-entity certificate. It does not check
148 \& * whether the certificate chain is valid, the certificates could be
149 \& * expired, or may otherwise fail to form a chain that a client can
150 \& * validate.
151 \& */
152 \& if (SSL_CTX_use_PrivateKey_file(ctx, key_path, SSL_FILETYPE_PEM) <= 0) {
153 \& fprintf(stderr, "couldn\*(Aqt load key file: %s\en", key_path);
154 \& goto err;
155 \& }
156 .Ve
157 .PP
158 Most servers, including this one, do not solicit client certificates. We
159 therefore do not need a "trust store" and allow the handshake to complete even
160 when the client does not present a certificate. Note: Even if a client did
161 present a trusted certificate, for it to be useful, the server application
162 would still need custom code to use the verified identity to grant nondefault
163 access to that particular client. Some servers grant access to all clients
164 with certificates from a private CA, this then requires processing of
165 certificate revocation lists to deauthorise a client. It is often simpler and
166 more secure to instead keep a list of authorised public keys.
167 .PP
168 Though this is the default setting, we explicitly call the
169 \&\fBSSL_CTX_set_verify\fR\|(3) function and pass the \fBSSL_VERIFY_NONE\fR value to it.
170 The final argument to this function is a callback that you can optionally
171 supply to override the default handling for certificate verification. Most
172 applications do not need to do this so this can safely be set to NULL to get
173 the default handling.
174 .PP
175 .Vb 12
176 \& /*
177 \& * Clients rarely employ certificate\-based authentication, and so we don\*(Aqt
178 \& * require "mutual" TLS authentication (indeed there\*(Aqs no way to know
179 \& * whether or how the client authenticated the server, so the term "mutual"
180 \& * is potentially misleading).
181 \& *
182 \& * Since we\*(Aqre not soliciting or processing client certificates, we don\*(Aqt
183 \& * need to configure a trusted\-certificate store, so no call to
184 \& * SSL_CTX_set_default_verify_paths() is needed. The server\*(Aqs own
185 \& * certificate chain is assumed valid.
186 \& */
187 \& SSL_CTX_set_verify(ctx, SSL_VERIFY_NONE, NULL);
188 .Ve
189 .PP
190 QUIC also dictates using Application-Layer Protocol Negotiation (ALPN) to select
191 an application protocol. We use \fBSSL_CTX_set_alpn_select_cb\fR\|(3) for this
192 purpose. We can pass a callback which will be called for each connection to
193 select an ALPN the server considers acceptable.
194 .PP
195 .Vb 2
196 \& /* Setup ALPN negotiation callback to decide which ALPN is accepted. */
197 \& SSL_CTX_set_alpn_select_cb(ctx, select_alpn, NULL);
198 .Ve
199 .PP
200 In this case, we only accept "http/1.0" and "hq-interop".
201 .PP
202 .Vb 8
203 \& /*
204 \& * ALPN strings for TLS handshake. Only \*(Aqhttp/1.0\*(Aq and \*(Aqhq\-interop\*(Aq
205 \& * are accepted.
206 \& */
207 \& static const unsigned char alpn_ossltest[] = {
208 \& 8, \*(Aqh\*(Aq, \*(Aqt\*(Aq, \*(Aqt\*(Aq, \*(Aqp\*(Aq, \*(Aq/\*(Aq, \*(Aq1\*(Aq, \*(Aq.\*(Aq, \*(Aq0\*(Aq,
209 \& 10, \*(Aqh\*(Aq, \*(Aqq\*(Aq, \*(Aq\-\*(Aq, \*(Aqi\*(Aq, \*(Aqn\*(Aq, \*(Aqt\*(Aq, \*(Aqe\*(Aq, \*(Aqr\*(Aq, \*(Aqo\*(Aq, \*(Aqp\*(Aq,
210 \& };
211 \&
212 \& static int select_alpn(SSL *ssl, const unsigned char **out,
213 \& unsigned char *out_len, const unsigned char *in,
214 \& unsigned int in_len, void *arg)
215 \& {
216 \& if (SSL_select_next_proto((unsigned char **)out, out_len, alpn_ossltest,
217 \& sizeof(alpn_ossltest), in,
218 \& in_len) == OPENSSL_NPN_NEGOTIATED)
219 \& return SSL_TLSEXT_ERR_OK;
220 \& return SSL_TLSEXT_ERR_ALERT_FATAL;
221 \& }
222 .Ve
223 .PP
224 That is all the setup that we need to do for the \fBSSL_CTX\fR. Next, we create a
225 UDP socket and bind to it on localhost.
226 .PP
227 .Vb 5
228 \& /* Retrieve the file descriptor for a new UDP socket */
229 \& if ((fd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0) {
230 \& fprintf(stderr, "cannot create socket");
231 \& return \-1;
232 \& }
233 \&
234 \& sa.sin_family = AF_INET;
235 \& sa.sin_port = htons(port);
236 \&
237 \& /* Bind to the new UDP socket on localhost */
238 \& if (bind(fd, (const struct sockaddr *)&sa, sizeof(sa)) < 0) {
239 \& fprintf(stderr, "cannot bind to %u\en", port);
240 \& BIO_closesocket(fd);
241 \& return \-1;
242 \& }
243 \&
244 \& /* Set port to nonblocking mode */
245 \& if (BIO_socket_nbio(fd, 1) <= 0) {
246 \& fprintf(stderr, "Unable to set port to nonblocking mode");
247 \& BIO_closesocket(fd);
248 \& return \-1;
249 \& }
250 .Ve
251 .PP
252 To run the QUIC server, we create an \fBSSL_LISTENER\fR to listen for incoming
253 connections. We provide it with the bound UDP port to then explicitly begin
254 listening for new connections.
255 .PP
256 .Vb 3
257 \& /* Create a new QUIC listener */
258 \& if ((listener = SSL_new_listener(ctx, 0)) == NULL)
259 \& goto err;
260 \&
261 \& /* Provide the listener with our UDP socket. */
262 \& if (!SSL_set_fd(listener, fd))
263 \& goto err;
264 \&
265 \& /* Set the listener mode to nonblocking, which is inherited by
266 \& * child objects.
267 \& */
268 \& if (!SSL_set_blocking_mode(listener, 0))
269 \& goto err;
270 \&
271 \& /*
272 \& * Begin listening. Note that is not usually needed as SSL_accept_connection
273 \& * will implicitly start listening. It is only needed if a server wishes to
274 \& * ensure it has started to accept incoming connections but does not wish to
275 \& * actually call SSL_accept_connection yet.
276 \& */
277 \& if (!SSL_listen(listener))
278 \& goto err;
279 .Ve
280 .SS "Server loop"
281 .IX Subsection "Server loop"
282 The server now enters a "forever" loop, handling one client connection at a
283 time. Before each connection, we clear the OpenSSL error stack so that any
284 error reports are related to just the new connection.
285 .PP
286 .Vb 2
287 \& /* Pristine error stack for each new connection */
288 \& ERR_clear_error();
289 .Ve
290 .PP
291 We then wait until a connection is ready for reading.
292 It uses the select function to wait until the socket is either readable
293 or writable, depending on what the SSL connection requires.
294 .PP
295 We then accept a new connection in which the handshake will have already
296 occurred. However, since we are in nonblocking mode, \fBSSL_accept_connection\fR\|(3)
297 will return immediately. Therefore, we use a helper function to essentially
298 block until a connection is established.
299 .PP
300 .Vb 5
301 \& printf("Waiting for connection\en");
302 \& while ((conn = SSL_accept_connection(listener, 0)) == NULL) {
303 \& wait_for_activity(listener);
304 \& }
305 \& printf("Accepted new connection\en");
306 .Ve
307 .PP
308 The helper function wait_for_activity uses \fBselect()\fR to block until the file
309 descriptor belonging to the passed SSL object is readable. As mentioned earlier,
310 a more real-world application would likely use this time to perform other tasks.
311 .PP
312 .Vb 3
313 \& /* Initialize the fd_set structure */
314 \& FD_ZERO(&read_fd);
315 \& FD_ZERO(&write_fd);
316 \&
317 \& /*
318 \& * Determine if we would like to write to the socket, read from it, or both.
319 \& */
320 \& if (SSL_net_write_desired(ssl))
321 \& FD_SET(sock, &write_fd);
322 \& if (SSL_net_read_desired(ssl))
323 \& FD_SET(sock, &read_fd);
324 \&
325 \& /*
326 \& * Find out when OpenSSL would next like to be called, regardless of
327 \& * whether the state of the underlying socket has changed or not.
328 \& */
329 \& if (SSL_get_event_timeout(ssl, &tv, &isinfinite) && !isinfinite)
330 \& tvp = &tv;
331 \&
332 \& /*
333 \& * Wait until the socket is writeable or readable. We use select here
334 \& * for the sake of simplicity and portability, but you could equally use
335 \& * poll/epoll or similar functions
336 \& *
337 \& * NOTE: For the purposes of this demonstration code this effectively
338 \& * makes this demo block until it has something more useful to do. In a
339 \& * real application you probably want to go and do other work here (e.g.
340 \& * update a GUI, or service other connections).
341 \& *
342 \& * Let\*(Aqs say for example that you want to update the progress counter on
343 \& * a GUI every 100ms. One way to do that would be to use the timeout in
344 \& * the last parameter to "select" below. If the tvp value is greater
345 \& * than 100ms then use 100ms instead. Then, when select returns, you
346 \& * check if it did so because of activity on the file descriptors or
347 \& * because of the timeout. If the 100ms GUI timeout has expired but the
348 \& * tvp timeout has not then go and update the GUI and then restart the
349 \& * "select" (with updated timeouts).
350 \& */
351 \&
352 \& select(sock + 1, &read_fd, &write_fd, NULL, tvp);
353 .Ve
354 .PP
355 With the handshake complete, the server reads all the client input.
356 .PP
357 .Vb 10
358 \& /* Read from client until the client sends a end of stream packet */
359 \& while (!eof) {
360 \& ret = SSL_read_ex(conn, buf + total_read, sizeof(buf) \- total_read,
361 \& &nread);
362 \& total_read += nread;
363 \& if (total_read >= 8192) {
364 \& fprintf(stderr, "Could not fit all data into buffer\en");
365 \& goto err;
366 \& }
367 \& switch (handle_io_failure(conn, ret)) {
368 \& case 1:
369 \& continue; /* Retry */
370 \& case 0:
371 \& /* Reached end of stream */
372 \& if (!SSL_has_pending(conn))
373 \& eof = 1;
374 \& break;
375 \& default:
376 \& fprintf(stderr, "Failed reading remaining data\en");
377 \& goto err;
378 \& }
379 \& }
380 .Ve
381 .PP
382 Finally, we echo the received data back to the client. We can use
383 \&\fBSSL_write_ex2\fR\|(3) to pass in a special flag SSL_WRITE_FLAG_CONCLUDE that will
384 send a FIN packet once the write has successfully finished writing all the data
385 to the peer.
386 .PP
387 .Vb 9
388 \& /* Echo client input */
389 \& while (!SSL_write_ex2(conn, buf,
390 \& total_read,
391 \& SSL_WRITE_FLAG_CONCLUDE, &total_written)) {
392 \& if (handle_io_failure(conn, 0) == 1)
393 \& continue;
394 \& fprintf(stderr, "Failed to write data\en");
395 \& goto err;
396 \& }
397 .Ve
398 .PP
399 We then shut down the connection with \fBSSL_shutdown\fR\|(3), which may need
400 to be called multiple times to ensure the connection is shutdown completely.
401 .PP
402 .Vb 8
403 \& /*
404 \& * Shut down the connection. We may need to call this multiple times
405 \& * to ensure the connection is shutdown completely.
406 \& */
407 \& while ((ret = SSL_shutdown(conn)) != 1) {
408 \& if (ret < 0 && handle_io_failure(conn, ret) == 1)
409 \& continue; /* Retry */
410 \& }
411 .Ve
412 .PP
413 Finally, we free the SSL connection, and the server is now ready to accept the
414 next client connection.
415 .PP
416 .Vb 1
417 \& SSL_free(conn);
418 .Ve
419 .SS "Final clean up"
420 .IX Subsection "Final clean up"
421 If the server somehow manages to break out of the infinite loop and
422 be ready to exit, it would deallocate the constructed \fBSSL\fR.
423 .PP
424 .Vb 1
425 \& SSL_free(listener);
426 .Ve
427 .PP
428 And in the main function, it would deallocate the constructed \fBSSL_CTX\fR.
429 .PP
430 .Vb 2
431 \& SSL_CTX_free(ctx);
432 \& BIO_closesocket(fd);
433 .Ve
434 .SH "SEE ALSO"
435 .IX Header "SEE ALSO"
436 \&\fBossl\-guide\-introduction\fR\|(7), \fBossl\-guide\-libraries\-introduction\fR\|(7),
437 \&\fBossl\-guide\-libssl\-introduction\fR\|(7), \fBossl\-guide\-quic\-introduction\fR\|(7),
438 \&\fBossl\-guide\-quic\-client\-non\-block\fR\|(7), \fBossl\-guide\-quic\-client\-block\fR\|(7),
439 \&\fBossl\-guide\-tls\-server\-block\fR\|(7), \fBossl\-guide\-quic\-server\-block\fR\|(7)
440 .SH COPYRIGHT
441 .IX Header "COPYRIGHT"
442 Copyright 2024\-2025 The OpenSSL Project Authors. All Rights Reserved.
443 .PP
444 Licensed under the Apache License 2.0 (the "License"). You may not use
445 this file except in compliance with the License. You can obtain a copy
446 in the file LICENSE in the source distribution or at
447 <https://www.openssl.org/source/license.html>.