xref: /freebsd/crypto/openssl/doc/man7/ossl-guide-quic-client-non-block.pod (revision e7be843b4a162e68651d3911f0357ed464915629)
1*e7be843bSPierre Pronchery=pod
2*e7be843bSPierre Pronchery
3*e7be843bSPierre Pronchery=begin comment
4*e7be843bSPierre Pronchery
5*e7be843bSPierre ProncheryNB: Changes to the source code samples in this file should also be reflected in
6*e7be843bSPierre Proncherydemos/guide/quic-client-non-block.c
7*e7be843bSPierre Pronchery
8*e7be843bSPierre Pronchery=end comment
9*e7be843bSPierre Pronchery
10*e7be843bSPierre Pronchery=head1 NAME
11*e7be843bSPierre Pronchery
12*e7be843bSPierre Proncheryossl-guide-quic-client-non-block
13*e7be843bSPierre Pronchery- OpenSSL Guide: Writing a simple nonblocking QUIC client
14*e7be843bSPierre Pronchery
15*e7be843bSPierre Pronchery=head1 SIMPLE NONBLOCKING QUIC CLIENT EXAMPLE
16*e7be843bSPierre Pronchery
17*e7be843bSPierre ProncheryThis page will build on the example developed on the
18*e7be843bSPierre ProncheryL<ossl-guide-quic-client-block(7)> page which demonstrates how to write a simple
19*e7be843bSPierre Proncheryblocking QUIC client. On this page we will amend that demo code so that it
20*e7be843bSPierre Proncherysupports nonblocking functionality.
21*e7be843bSPierre Pronchery
22*e7be843bSPierre ProncheryThe complete source code for this example nonblocking QUIC client is available
23*e7be843bSPierre Proncheryin the B<demos/guide> directory of the OpenSSL source distribution in the file
24*e7be843bSPierre ProncheryB<quic-client-non-block.c>. It is also available online at
25*e7be843bSPierre ProncheryL<https://github.com/openssl/openssl/blob/master/demos/guide/quic-client-non-block.c>.
26*e7be843bSPierre Pronchery
27*e7be843bSPierre ProncheryAs we saw in the previous example an OpenSSL QUIC application always uses a
28*e7be843bSPierre Proncherynonblocking socket. However, despite this, the B<SSL> object still has blocking
29*e7be843bSPierre Proncherybehaviour. When the B<SSL> object has blocking behaviour then this means that
30*e7be843bSPierre Proncheryit waits (blocks) until data is available to read if you attempt to read from
31*e7be843bSPierre Proncheryit when there is no data yet. Similarly it waits when writing if the B<SSL>
32*e7be843bSPierre Proncheryobject is currently unable to write at the moment. This can simplify the
33*e7be843bSPierre Proncherydevelopment of code because you do not have to worry about what to do in these
34*e7be843bSPierre Proncherycases. The execution of the code will simply stop until it is able to continue.
35*e7be843bSPierre ProncheryHowever in many cases you do not want this behaviour. Rather than stopping and
36*e7be843bSPierre Proncherywaiting your application may need to go and do other tasks whilst the B<SSL>
37*e7be843bSPierre Proncheryobject is unable to read/write, for example updating a GUI or performing
38*e7be843bSPierre Proncheryoperations on some other connection or stream.
39*e7be843bSPierre Pronchery
40*e7be843bSPierre ProncheryWe will see later in this tutorial how to change the B<SSL> object so that it
41*e7be843bSPierre Proncheryhas nonblocking behaviour. With a nonblocking B<SSL> object, functions such as
42*e7be843bSPierre ProncheryL<SSL_read_ex(3)> or L<SSL_write_ex(3)> will return immediately with a non-fatal
43*e7be843bSPierre Proncheryerror if they are currently unable to read or write respectively.
44*e7be843bSPierre Pronchery
45*e7be843bSPierre ProncherySince this page is building on the example developed on the
46*e7be843bSPierre ProncheryL<ossl-guide-quic-client-block(7)> page we assume that you are familiar with it
47*e7be843bSPierre Proncheryand we only explain how this example differs.
48*e7be843bSPierre Pronchery
49*e7be843bSPierre Pronchery=head2 Performing work while waiting for the socket
50*e7be843bSPierre Pronchery
51*e7be843bSPierre ProncheryIn a nonblocking application you will need work to perform in the event that
52*e7be843bSPierre Proncherywe want to read or write to the B<SSL> object but we are currently unable to.
53*e7be843bSPierre ProncheryIn fact this is the whole point of using a nonblocking B<SSL> object, i.e. to
54*e7be843bSPierre Proncherygive the application the opportunity to do something else. Whatever it is that
55*e7be843bSPierre Proncherythe application has to do, it must also be prepared to come back and retry the
56*e7be843bSPierre Proncheryoperation that it previously attempted periodically to see if it can now
57*e7be843bSPierre Proncherycomplete. Ideally it would only do this in the event that something has changed
58*e7be843bSPierre Proncherysuch that it might succeed on the retry attempt, but this does not have to be
59*e7be843bSPierre Proncherythe case. It can retry at any time.
60*e7be843bSPierre Pronchery
61*e7be843bSPierre ProncheryNote that it is important that you retry exactly the same operation that you
62*e7be843bSPierre Proncherytried last time. You cannot start something new. For example if you were
63*e7be843bSPierre Proncheryattempting to write the text "Hello World" and the operation failed because the
64*e7be843bSPierre ProncheryB<SSL> object is currently unable to write, then you cannot then attempt to
65*e7be843bSPierre Proncherywrite some other text when you retry the operation.
66*e7be843bSPierre Pronchery
67*e7be843bSPierre ProncheryIn this demo application we will create a helper function which simulates doing
68*e7be843bSPierre Proncheryother work. In fact, for the sake of simplicity, it will do nothing except wait
69*e7be843bSPierre Proncheryfor the state of the underlying socket to change or until a timeout expires
70*e7be843bSPierre Proncheryafter which the state of the B<SSL> object might have changed. We will call our
71*e7be843bSPierre Proncheryfunction C<wait_for_activity()>.
72*e7be843bSPierre Pronchery
73*e7be843bSPierre Pronchery    static void wait_for_activity(SSL *ssl)
74*e7be843bSPierre Pronchery    {
75*e7be843bSPierre Pronchery        fd_set wfds, rfds;
76*e7be843bSPierre Pronchery        int width, sock, isinfinite;
77*e7be843bSPierre Pronchery        struct timeval tv;
78*e7be843bSPierre Pronchery        struct timeval *tvp = NULL;
79*e7be843bSPierre Pronchery
80*e7be843bSPierre Pronchery        /* Get hold of the underlying file descriptor for the socket */
81*e7be843bSPierre Pronchery        sock = SSL_get_fd(ssl);
82*e7be843bSPierre Pronchery
83*e7be843bSPierre Pronchery        FD_ZERO(&wfds);
84*e7be843bSPierre Pronchery        FD_ZERO(&rfds);
85*e7be843bSPierre Pronchery
86*e7be843bSPierre Pronchery        /*
87*e7be843bSPierre Pronchery         * Find out if we would like to write to the socket, or read from it (or
88*e7be843bSPierre Pronchery         * both)
89*e7be843bSPierre Pronchery         */
90*e7be843bSPierre Pronchery        if (SSL_net_write_desired(ssl))
91*e7be843bSPierre Pronchery            FD_SET(sock, &wfds);
92*e7be843bSPierre Pronchery        if (SSL_net_read_desired(ssl))
93*e7be843bSPierre Pronchery            FD_SET(sock, &rfds);
94*e7be843bSPierre Pronchery        width = sock + 1;
95*e7be843bSPierre Pronchery
96*e7be843bSPierre Pronchery        /*
97*e7be843bSPierre Pronchery         * Find out when OpenSSL would next like to be called, regardless of
98*e7be843bSPierre Pronchery         * whether the state of the underlying socket has changed or not.
99*e7be843bSPierre Pronchery         */
100*e7be843bSPierre Pronchery        if (SSL_get_event_timeout(ssl, &tv, &isinfinite) && !isinfinite)
101*e7be843bSPierre Pronchery            tvp = &tv;
102*e7be843bSPierre Pronchery
103*e7be843bSPierre Pronchery        /*
104*e7be843bSPierre Pronchery         * Wait until the socket is writeable or readable. We use select here
105*e7be843bSPierre Pronchery         * for the sake of simplicity and portability, but you could equally use
106*e7be843bSPierre Pronchery         * poll/epoll or similar functions
107*e7be843bSPierre Pronchery         *
108*e7be843bSPierre Pronchery         * NOTE: For the purposes of this demonstration code this effectively
109*e7be843bSPierre Pronchery         * makes this demo block until it has something more useful to do. In a
110*e7be843bSPierre Pronchery         * real application you probably want to go and do other work here (e.g.
111*e7be843bSPierre Pronchery         * update a GUI, or service other connections).
112*e7be843bSPierre Pronchery         *
113*e7be843bSPierre Pronchery         * Let's say for example that you want to update the progress counter on
114*e7be843bSPierre Pronchery         * a GUI every 100ms. One way to do that would be to use the timeout in
115*e7be843bSPierre Pronchery         * the last parameter to "select" below. If the tvp value is greater
116*e7be843bSPierre Pronchery         * than 100ms then use 100ms instead. Then, when select returns, you
117*e7be843bSPierre Pronchery         * check if it did so because of activity on the file descriptors or
118*e7be843bSPierre Pronchery         * because of the timeout. If the 100ms GUI timeout has expired but the
119*e7be843bSPierre Pronchery         * tvp timeout has not then go and update the GUI and then restart the
120*e7be843bSPierre Pronchery         * "select" (with updated timeouts).
121*e7be843bSPierre Pronchery         */
122*e7be843bSPierre Pronchery
123*e7be843bSPierre Pronchery        select(width, &rfds, &wfds, NULL, tvp);
124*e7be843bSPierre Pronchery}
125*e7be843bSPierre Pronchery
126*e7be843bSPierre ProncheryIf you are familiar with how to write nonblocking applications in OpenSSL for
127*e7be843bSPierre ProncheryTLS (see L<ossl-guide-tls-client-non-block(7)>) then you should note that there
128*e7be843bSPierre Proncheryis an important difference here between the way a QUIC application and a TLS
129*e7be843bSPierre Proncheryapplication works. With a TLS application if we try to read or write something
130*e7be843bSPierre Proncheryto the B<SSL> object and we get a "retry" response (B<SSL_ERROR_WANT_READ> or
131*e7be843bSPierre ProncheryB<SSL_ERROR_WANT_WRITE>) then we can assume that is because OpenSSL attempted to
132*e7be843bSPierre Proncheryread or write to the underlying socket and the socket signalled the "retry".
133*e7be843bSPierre ProncheryWith QUIC that is not the case. OpenSSL may signal retry as a result of an
134*e7be843bSPierre ProncheryL<SSL_read_ex(3)> or L<SSL_write_ex(3)> (or similar) call which indicates the
135*e7be843bSPierre Proncherystate of the stream. This is entirely independent of whether the underlying
136*e7be843bSPierre Proncherysocket needs to retry or not.
137*e7be843bSPierre Pronchery
138*e7be843bSPierre ProncheryTo determine whether OpenSSL currently wants to read or write to the underlying
139*e7be843bSPierre Proncherysocket for a QUIC application we must call the L<SSL_net_read_desired(3)> and
140*e7be843bSPierre ProncheryL<SSL_net_write_desired(3)> functions.
141*e7be843bSPierre Pronchery
142*e7be843bSPierre ProncheryIt is also important with QUIC that we periodically call an I/O function (or
143*e7be843bSPierre Proncheryotherwise call the L<SSL_handle_events(3)> function) to ensure that the QUIC
144*e7be843bSPierre Proncheryconnection remains healthy. This is particularly important with a nonblocking
145*e7be843bSPierre Proncheryapplication because you are likely to leave the B<SSL> object idle for a while
146*e7be843bSPierre Proncherywhile the application goes off to do other work. The L<SSL_get_event_timeout(3)>
147*e7be843bSPierre Proncheryfunction can be used to determine what the deadline is for the next time we need
148*e7be843bSPierre Proncheryto call an I/O function (or call L<SSL_handle_events(3)>).
149*e7be843bSPierre Pronchery
150*e7be843bSPierre ProncheryAn alternative to using L<SSL_get_event_timeout(3)> to find the next deadline
151*e7be843bSPierre Proncherythat OpenSSL must be called again by is to use "thread assisted" mode. In
152*e7be843bSPierre Pronchery"thread assisted" mode OpenSSL spawns an additional thread which will
153*e7be843bSPierre Proncheryperiodically call L<SSL_handle_events(3)> automatically, meaning that the
154*e7be843bSPierre Proncheryapplication can leave the connection idle safe in the knowledge that the
155*e7be843bSPierre Proncheryconnection will still be maintained in a healthy state. See
156*e7be843bSPierre ProncheryL</Creating the SSL_CTX and SSL objects> below for further details about this.
157*e7be843bSPierre Pronchery
158*e7be843bSPierre ProncheryIn this example we are using the C<select> function to check the
159*e7be843bSPierre Proncheryreadability/writeability of the socket because it is very simple to use and is
160*e7be843bSPierre Proncheryavailable on most Operating Systems. However you could use any other similar
161*e7be843bSPierre Proncheryfunction to do the same thing. C<select> waits for the state of the underlying
162*e7be843bSPierre Proncherysocket(s) to become readable/writeable or until the timeout has expired before
163*e7be843bSPierre Proncheryreturning.
164*e7be843bSPierre Pronchery
165*e7be843bSPierre Pronchery=head2 Handling errors from OpenSSL I/O functions
166*e7be843bSPierre Pronchery
167*e7be843bSPierre ProncheryA QUIC application that has been configured for nonblocking behaviour will need
168*e7be843bSPierre Proncheryto be prepared to handle errors returned from OpenSSL I/O functions such as
169*e7be843bSPierre ProncheryL<SSL_read_ex(3)> or L<SSL_write_ex(3)>. Errors may be fatal for the stream (for
170*e7be843bSPierre Proncheryexample because the stream has been reset or because the underlying connection
171*e7be843bSPierre Proncheryhas failed), or non-fatal (for example because we are trying to read from the
172*e7be843bSPierre Proncherystream but no data has not yet arrived from the peer for that stream).
173*e7be843bSPierre Pronchery
174*e7be843bSPierre ProncheryL<SSL_read_ex(3)> and L<SSL_write_ex(3)> will return 0 to indicate an error and
175*e7be843bSPierre ProncheryL<SSL_read(3)> and L<SSL_write(3)> will return 0 or a negative value to indicate
176*e7be843bSPierre Proncheryan error. L<SSL_shutdown(3)> will return a negative value to incidate an error.
177*e7be843bSPierre Pronchery
178*e7be843bSPierre ProncheryIn the event of an error an application should call L<SSL_get_error(3)> to find
179*e7be843bSPierre Proncheryout what type of error has occurred. If the error is non-fatal and can be
180*e7be843bSPierre Proncheryretried then L<SSL_get_error(3)> will return B<SSL_ERROR_WANT_READ> or
181*e7be843bSPierre ProncheryB<SSL_ERROR_WANT_WRITE> depending on whether OpenSSL wanted to read to or write
182*e7be843bSPierre Proncheryfrom the stream but was unable to. Note that a call to L<SSL_read_ex(3)> or
183*e7be843bSPierre ProncheryL<SSL_read(3)> can still generate B<SSL_ERROR_WANT_WRITE>. Similarly calls to
184*e7be843bSPierre ProncheryL<SSL_write_ex(3)> or L<SSL_write(3)> might generate B<SSL_ERROR_WANT_READ>.
185*e7be843bSPierre Pronchery
186*e7be843bSPierre ProncheryAnother type of non-fatal error that may occur is B<SSL_ERROR_ZERO_RETURN>. This
187*e7be843bSPierre Proncheryindicates an EOF (End-Of-File) which can occur if you attempt to read data from
188*e7be843bSPierre Proncheryan B<SSL> object but the peer has indicated that it will not send any more data
189*e7be843bSPierre Proncheryon the stream. In this case you may still want to write data to the stream but
190*e7be843bSPierre Proncheryyou will not receive any more data.
191*e7be843bSPierre Pronchery
192*e7be843bSPierre ProncheryFatal errors that may occur are B<SSL_ERROR_SYSCALL> and B<SSL_ERROR_SSL>. These
193*e7be843bSPierre Proncheryindicate that the stream is no longer usable. For example, this could be because
194*e7be843bSPierre Proncherythe stream has been reset by the peer, or because the underlying connection has
195*e7be843bSPierre Proncheryfailed. You can consult the OpenSSL error stack for further details (for example
196*e7be843bSPierre Proncheryby calling L<ERR_print_errors(3)> to print out details of errors that have
197*e7be843bSPierre Proncheryoccurred). You can also consult the return value of
198*e7be843bSPierre ProncheryL<SSL_get_stream_read_state(3)> to determine whether the error is local to the
199*e7be843bSPierre Proncherystream, or whether the underlying connection has also failed. A return value
200*e7be843bSPierre Proncheryof B<SSL_STREAM_STATE_RESET_REMOTE> tells you that the stream has been reset by
201*e7be843bSPierre Proncherythe peer and B<SSL_STREAM_STATE_CONN_CLOSED> tells you that the underlying
202*e7be843bSPierre Proncheryconnection has closed.
203*e7be843bSPierre Pronchery
204*e7be843bSPierre ProncheryIn our demo application we will write a function to handle these errors from
205*e7be843bSPierre ProncheryOpenSSL I/O functions:
206*e7be843bSPierre Pronchery
207*e7be843bSPierre Pronchery    static int handle_io_failure(SSL *ssl, int res)
208*e7be843bSPierre Pronchery    {
209*e7be843bSPierre Pronchery        switch (SSL_get_error(ssl, res)) {
210*e7be843bSPierre Pronchery        case SSL_ERROR_WANT_READ:
211*e7be843bSPierre Pronchery        case SSL_ERROR_WANT_WRITE:
212*e7be843bSPierre Pronchery            /* Temporary failure. Wait until we can read/write and try again */
213*e7be843bSPierre Pronchery            wait_for_activity(ssl);
214*e7be843bSPierre Pronchery            return 1;
215*e7be843bSPierre Pronchery
216*e7be843bSPierre Pronchery        case SSL_ERROR_ZERO_RETURN:
217*e7be843bSPierre Pronchery            /* EOF */
218*e7be843bSPierre Pronchery            return 0;
219*e7be843bSPierre Pronchery
220*e7be843bSPierre Pronchery        case SSL_ERROR_SYSCALL:
221*e7be843bSPierre Pronchery            return -1;
222*e7be843bSPierre Pronchery
223*e7be843bSPierre Pronchery        case SSL_ERROR_SSL:
224*e7be843bSPierre Pronchery            /*
225*e7be843bSPierre Pronchery             * Some stream fatal error occurred. This could be because of a
226*e7be843bSPierre Pronchery             * stream reset - or some failure occurred on the underlying
227*e7be843bSPierre Pronchery             * connection.
228*e7be843bSPierre Pronchery             */
229*e7be843bSPierre Pronchery            switch (SSL_get_stream_read_state(ssl)) {
230*e7be843bSPierre Pronchery            case SSL_STREAM_STATE_RESET_REMOTE:
231*e7be843bSPierre Pronchery                printf("Stream reset occurred\n");
232*e7be843bSPierre Pronchery                /*
233*e7be843bSPierre Pronchery                 * The stream has been reset but the connection is still
234*e7be843bSPierre Pronchery                 * healthy.
235*e7be843bSPierre Pronchery                 */
236*e7be843bSPierre Pronchery                break;
237*e7be843bSPierre Pronchery
238*e7be843bSPierre Pronchery            case SSL_STREAM_STATE_CONN_CLOSED:
239*e7be843bSPierre Pronchery                printf("Connection closed\n");
240*e7be843bSPierre Pronchery                /* Connection is already closed. */
241*e7be843bSPierre Pronchery                break;
242*e7be843bSPierre Pronchery
243*e7be843bSPierre Pronchery            default:
244*e7be843bSPierre Pronchery                printf("Unknown stream failure\n");
245*e7be843bSPierre Pronchery                break;
246*e7be843bSPierre Pronchery            }
247*e7be843bSPierre Pronchery            /*
248*e7be843bSPierre Pronchery             * If the failure is due to a verification error we can get more
249*e7be843bSPierre Pronchery             * information about it from SSL_get_verify_result().
250*e7be843bSPierre Pronchery             */
251*e7be843bSPierre Pronchery            if (SSL_get_verify_result(ssl) != X509_V_OK)
252*e7be843bSPierre Pronchery                printf("Verify error: %s\n",
253*e7be843bSPierre Pronchery                    X509_verify_cert_error_string(SSL_get_verify_result(ssl)));
254*e7be843bSPierre Pronchery            return -1;
255*e7be843bSPierre Pronchery
256*e7be843bSPierre Pronchery        default:
257*e7be843bSPierre Pronchery            return -1;
258*e7be843bSPierre Pronchery        }
259*e7be843bSPierre Pronchery    }
260*e7be843bSPierre Pronchery
261*e7be843bSPierre ProncheryThis function takes as arguments the B<SSL> object that represents the
262*e7be843bSPierre Proncheryconnection, as well as the return code from the I/O function that failed. In
263*e7be843bSPierre Proncherythe event of a non-fatal failure, it waits until a retry of the I/O operation
264*e7be843bSPierre Proncherymight succeed (by using the C<wait_for_activity()> function that we developed
265*e7be843bSPierre Proncheryin the previous section). It returns 1 in the event of a non-fatal error
266*e7be843bSPierre Pronchery(except EOF), 0 in the event of EOF, or -1 if a fatal error occurred.
267*e7be843bSPierre Pronchery
268*e7be843bSPierre Pronchery=head2 Creating the SSL_CTX and SSL objects
269*e7be843bSPierre Pronchery
270*e7be843bSPierre ProncheryIn order to connect to a server we must create B<SSL_CTX> and B<SSL> objects for
271*e7be843bSPierre Proncherythis. Most of the steps to do this are the same as for a blocking client and are
272*e7be843bSPierre Proncheryexplained on the L<ossl-guide-quic-client-block(7)> page. We won't repeat that
273*e7be843bSPierre Proncheryinformation here.
274*e7be843bSPierre Pronchery
275*e7be843bSPierre ProncheryOne key difference is that we must put the B<SSL> object into nonblocking mode
276*e7be843bSPierre Pronchery(the default is blocking mode). To do that we use the
277*e7be843bSPierre ProncheryL<SSL_set_blocking_mode(3)> function:
278*e7be843bSPierre Pronchery
279*e7be843bSPierre Pronchery    /*
280*e7be843bSPierre Pronchery     * The underlying socket is always nonblocking with QUIC, but the default
281*e7be843bSPierre Pronchery     * behaviour of the SSL object is still to block. We set it for nonblocking
282*e7be843bSPierre Pronchery     * mode in this demo.
283*e7be843bSPierre Pronchery     */
284*e7be843bSPierre Pronchery    if (!SSL_set_blocking_mode(ssl, 0)) {
285*e7be843bSPierre Pronchery        printf("Failed to turn off blocking mode\n");
286*e7be843bSPierre Pronchery        goto end;
287*e7be843bSPierre Pronchery    }
288*e7be843bSPierre Pronchery
289*e7be843bSPierre ProncheryAlthough the demo application that we are developing here does not use it, it is
290*e7be843bSPierre Proncherypossible to use "thread assisted mode" when developing QUIC applications.
291*e7be843bSPierre ProncheryNormally, when writing an OpenSSL QUIC application, it is important that
292*e7be843bSPierre ProncheryL<SSL_handle_events(3)> (or alternatively any I/O function) is called on the
293*e7be843bSPierre Proncheryconnection B<SSL> object periodically to maintain the connection in a healthy
294*e7be843bSPierre Proncherystate. See L</Performing work while waiting for the socket> for more discussion
295*e7be843bSPierre Proncheryon this. This is particularly important to keep in mind when writing a
296*e7be843bSPierre Proncherynonblocking QUIC application because it is common to leave the B<SSL> connection
297*e7be843bSPierre Proncheryobject idle for some time when using nonblocking mode. By using "thread assisted
298*e7be843bSPierre Proncherymode" a separate thread is created by OpenSSL to do this automatically which
299*e7be843bSPierre Proncherymeans that the application developer does not need to handle this aspect. To do
300*e7be843bSPierre Proncherythis we must use L<OSSL_QUIC_client_thread_method(3)> when we construct the
301*e7be843bSPierre ProncheryB<SSL_CTX> as shown below:
302*e7be843bSPierre Pronchery
303*e7be843bSPierre Pronchery    ctx = SSL_CTX_new(OSSL_QUIC_client_thread_method());
304*e7be843bSPierre Pronchery    if (ctx == NULL) {
305*e7be843bSPierre Pronchery        printf("Failed to create the SSL_CTX\n");
306*e7be843bSPierre Pronchery        goto end;
307*e7be843bSPierre Pronchery    }
308*e7be843bSPierre Pronchery
309*e7be843bSPierre Pronchery=head2 Performing the handshake
310*e7be843bSPierre Pronchery
311*e7be843bSPierre ProncheryAs in the demo for a blocking QUIC client we use the L<SSL_connect(3)> function
312*e7be843bSPierre Proncheryto perform the handshake with the server. Since we are using a nonblocking
313*e7be843bSPierre ProncheryB<SSL> object it is very likely that calls to this function will fail with a
314*e7be843bSPierre Proncherynon-fatal error while we are waiting for the server to respond to our handshake
315*e7be843bSPierre Proncherymessages. In such a case we must retry the same L<SSL_connect(3)> call at a
316*e7be843bSPierre Proncherylater time. In this demo we do this in a loop:
317*e7be843bSPierre Pronchery
318*e7be843bSPierre Pronchery    /* Do the handshake with the server */
319*e7be843bSPierre Pronchery    while ((ret = SSL_connect(ssl)) != 1) {
320*e7be843bSPierre Pronchery        if (handle_io_failure(ssl, ret) == 1)
321*e7be843bSPierre Pronchery            continue; /* Retry */
322*e7be843bSPierre Pronchery        printf("Failed to connect to server\n");
323*e7be843bSPierre Pronchery        goto end; /* Cannot retry: error */
324*e7be843bSPierre Pronchery    }
325*e7be843bSPierre Pronchery
326*e7be843bSPierre ProncheryWe continually call L<SSL_connect(3)> until it gives us a success response.
327*e7be843bSPierre ProncheryOtherwise we use the C<handle_io_failure()> function that we created earlier to
328*e7be843bSPierre Proncherywork out what we should do next. Note that we do not expect an EOF to occur at
329*e7be843bSPierre Proncherythis stage, so such a response is treated in the same way as a fatal error.
330*e7be843bSPierre Pronchery
331*e7be843bSPierre Pronchery=head2 Sending and receiving data
332*e7be843bSPierre Pronchery
333*e7be843bSPierre ProncheryAs with the blocking QUIC client demo we use the L<SSL_write_ex(3)> function to
334*e7be843bSPierre Proncherysend data to the server. As with L<SSL_connect(3)> above, because we are using
335*e7be843bSPierre Proncherya nonblocking B<SSL> object, this call could fail with a non-fatal error. In
336*e7be843bSPierre Proncherythat case we should retry exactly the same L<SSL_write_ex(3)> call again. Note
337*e7be843bSPierre Proncherythat the parameters must be I<exactly> the same, i.e. the same pointer to the
338*e7be843bSPierre Proncherybuffer to write with the same length. You must not attempt to send different
339*e7be843bSPierre Proncherydata on a retry. An optional mode does exist
340*e7be843bSPierre Pronchery(B<SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER>) which will configure OpenSSL to allow
341*e7be843bSPierre Proncherythe buffer being written to change from one retry to the next. However, in this
342*e7be843bSPierre Proncherycase, you must still retry exactly the same data - even though the buffer that
343*e7be843bSPierre Proncherycontains that data may change location. See L<SSL_CTX_set_mode(3)> for further
344*e7be843bSPierre Proncherydetails. As in the TLS tutorials (L<ossl-guide-tls-client-block(7)>) we write
345*e7be843bSPierre Proncherythe request in three chunks.
346*e7be843bSPierre Pronchery
347*e7be843bSPierre ProncheryFirst, we write the entire request to the stream. We also must make sure to
348*e7be843bSPierre Proncherysignal to the server that we have finished writing. This can be done by passing
349*e7be843bSPierre Proncherythe SSL_WRITE_FLAG_CONCLUDE flag to L<SSL_write_ex2(3)> or by calling
350*e7be843bSPierre ProncheryL<SSL_stream_conclude(3)>. Since the first way is more efficient, we choose to
351*e7be843bSPierre Proncherydo that.
352*e7be843bSPierre Pronchery
353*e7be843bSPierre Pronchery    /* Write an HTTP GET request to the peer */
354*e7be843bSPierre Pronchery    while (!SSL_write_ex(ssl, request_start, strlen(request_start), &written)) {
355*e7be843bSPierre Pronchery        if (handle_io_failure(ssl, 0) == 1)
356*e7be843bSPierre Pronchery            continue; /* Retry */
357*e7be843bSPierre Pronchery        printf("Failed to write start of HTTP request\n");
358*e7be843bSPierre Pronchery        goto end; /* Cannot retry: error */
359*e7be843bSPierre Pronchery    }
360*e7be843bSPierre Pronchery    while (!SSL_write_ex(ssl, hostname, strlen(hostname), &written)) {
361*e7be843bSPierre Pronchery        if (handle_io_failure(ssl, 0) == 1)
362*e7be843bSPierre Pronchery            continue; /* Retry */
363*e7be843bSPierre Pronchery        printf("Failed to write hostname in HTTP request\n");
364*e7be843bSPierre Pronchery        goto end; /* Cannot retry: error */
365*e7be843bSPierre Pronchery    }
366*e7be843bSPierre Pronchery    while (!SSL_write_ex2(ssl, request_end, strlen(request_end),
367*e7be843bSPierre Pronchery           SSL_WRITE_FLAG_CONCLUDE, &written)) {
368*e7be843bSPierre Pronchery        if (handle_io_failure(ssl, 0) == 1)
369*e7be843bSPierre Pronchery            continue; /* Retry */
370*e7be843bSPierre Pronchery        printf("Failed to write end of HTTP request\n");
371*e7be843bSPierre Pronchery        goto end; /* Cannot retry: error */
372*e7be843bSPierre Pronchery    }
373*e7be843bSPierre Pronchery
374*e7be843bSPierre ProncheryOn a write we do not expect to see an EOF response so we treat that case in the
375*e7be843bSPierre Proncherysame way as a fatal error.
376*e7be843bSPierre Pronchery
377*e7be843bSPierre ProncheryReading a response back from the server is similar:
378*e7be843bSPierre Pronchery
379*e7be843bSPierre Pronchery    do {
380*e7be843bSPierre Pronchery        /*
381*e7be843bSPierre Pronchery         * Get up to sizeof(buf) bytes of the response. We keep reading until
382*e7be843bSPierre Pronchery         * the server closes the connection.
383*e7be843bSPierre Pronchery         */
384*e7be843bSPierre Pronchery        while (!eof && !SSL_read_ex(ssl, buf, sizeof(buf), &readbytes)) {
385*e7be843bSPierre Pronchery            switch (handle_io_failure(ssl, 0)) {
386*e7be843bSPierre Pronchery            case 1:
387*e7be843bSPierre Pronchery                continue; /* Retry */
388*e7be843bSPierre Pronchery            case 0:
389*e7be843bSPierre Pronchery                eof = 1;
390*e7be843bSPierre Pronchery                continue;
391*e7be843bSPierre Pronchery            case -1:
392*e7be843bSPierre Pronchery            default:
393*e7be843bSPierre Pronchery                printf("Failed reading remaining data\n");
394*e7be843bSPierre Pronchery                goto end; /* Cannot retry: error */
395*e7be843bSPierre Pronchery            }
396*e7be843bSPierre Pronchery        }
397*e7be843bSPierre Pronchery        /*
398*e7be843bSPierre Pronchery         * OpenSSL does not guarantee that the returned data is a string or
399*e7be843bSPierre Pronchery         * that it is NUL terminated so we use fwrite() to write the exact
400*e7be843bSPierre Pronchery         * number of bytes that we read. The data could be non-printable or
401*e7be843bSPierre Pronchery         * have NUL characters in the middle of it. For this simple example
402*e7be843bSPierre Pronchery         * we're going to print it to stdout anyway.
403*e7be843bSPierre Pronchery         */
404*e7be843bSPierre Pronchery        if (!eof)
405*e7be843bSPierre Pronchery            fwrite(buf, 1, readbytes, stdout);
406*e7be843bSPierre Pronchery    } while (!eof);
407*e7be843bSPierre Pronchery    /* In case the response didn't finish with a newline we add one now */
408*e7be843bSPierre Pronchery    printf("\n");
409*e7be843bSPierre Pronchery
410*e7be843bSPierre ProncheryThe main difference this time is that it is valid for us to receive an EOF
411*e7be843bSPierre Proncheryresponse when trying to read data from the server. This will occur when the
412*e7be843bSPierre Proncheryserver closes down the connection after sending all the data in its response.
413*e7be843bSPierre Pronchery
414*e7be843bSPierre ProncheryIn this demo we just print out all the data we've received back in the response
415*e7be843bSPierre Proncheryfrom the server. We continue going around the loop until we either encounter a
416*e7be843bSPierre Proncheryfatal error, or we receive an EOF (indicating a graceful finish).
417*e7be843bSPierre Pronchery
418*e7be843bSPierre Pronchery=head2 Shutting down the connection
419*e7be843bSPierre Pronchery
420*e7be843bSPierre ProncheryAs in the QUIC blocking example we must shutdown the connection when we are
421*e7be843bSPierre Proncheryfinished with it.
422*e7be843bSPierre Pronchery
423*e7be843bSPierre ProncheryEven though we have received EOF on the stream that we were reading from above,
424*e7be843bSPierre Proncherythis tell us nothing about the state of the underlying connection. Our demo
425*e7be843bSPierre Proncheryapplication will initiate the connection shutdown process via
426*e7be843bSPierre ProncheryL<SSL_shutdown(3)>.
427*e7be843bSPierre Pronchery
428*e7be843bSPierre ProncherySince our application is initiating the shutdown then we might expect to see
429*e7be843bSPierre ProncheryL<SSL_shutdown(3)> give a return value of 0, and then we should continue to call
430*e7be843bSPierre Proncheryit until we receive a return value of 1 (meaning we have successfully completed
431*e7be843bSPierre Proncherythe shutdown). Since we are using a nonblocking B<SSL> object we might expect to
432*e7be843bSPierre Proncheryhave to retry this operation several times. If L<SSL_shutdown(3)> returns a
433*e7be843bSPierre Proncherynegative result then we must call L<SSL_get_error(3)> to work out what to do
434*e7be843bSPierre Proncherynext. We use our handle_io_failure() function that we developed earlier for
435*e7be843bSPierre Proncherythis:
436*e7be843bSPierre Pronchery
437*e7be843bSPierre Pronchery    /*
438*e7be843bSPierre Pronchery     * Repeatedly call SSL_shutdown() until the connection is fully
439*e7be843bSPierre Pronchery     * closed.
440*e7be843bSPierre Pronchery     */
441*e7be843bSPierre Pronchery    while ((ret = SSL_shutdown(ssl)) != 1) {
442*e7be843bSPierre Pronchery        if (ret < 0 && handle_io_failure(ssl, ret) == 1)
443*e7be843bSPierre Pronchery            continue; /* Retry */
444*e7be843bSPierre Pronchery    }
445*e7be843bSPierre Pronchery
446*e7be843bSPierre Pronchery=head2 Final clean up
447*e7be843bSPierre Pronchery
448*e7be843bSPierre ProncheryAs with the blocking QUIC client example, once our connection is finished with
449*e7be843bSPierre Proncherywe must free it. The steps to do this for this example are the same as for the
450*e7be843bSPierre Proncheryblocking example, so we won't repeat it here.
451*e7be843bSPierre Pronchery
452*e7be843bSPierre Pronchery=head1 FURTHER READING
453*e7be843bSPierre Pronchery
454*e7be843bSPierre ProncherySee L<ossl-guide-quic-client-block(7)> to read a tutorial on how to write a
455*e7be843bSPierre Proncheryblocking QUIC client. See L<ossl-guide-quic-multi-stream(7)> to see how to write
456*e7be843bSPierre Proncherya multi-stream QUIC client.
457*e7be843bSPierre Pronchery
458*e7be843bSPierre Pronchery=head1 SEE ALSO
459*e7be843bSPierre Pronchery
460*e7be843bSPierre ProncheryL<ossl-guide-introduction(7)>, L<ossl-guide-libraries-introduction(7)>,
461*e7be843bSPierre ProncheryL<ossl-guide-libssl-introduction(7)>, L<ossl-guide-quic-introduction(7)>,
462*e7be843bSPierre ProncheryL<ossl-guide-quic-client-block(7)>, L<ossl-guide-quic-multi-stream(7)>
463*e7be843bSPierre Pronchery
464*e7be843bSPierre Pronchery=head1 COPYRIGHT
465*e7be843bSPierre Pronchery
466*e7be843bSPierre ProncheryCopyright 2023-2025 The OpenSSL Project Authors. All Rights Reserved.
467*e7be843bSPierre Pronchery
468*e7be843bSPierre ProncheryLicensed under the Apache License 2.0 (the "License").  You may not use
469*e7be843bSPierre Proncherythis file except in compliance with the License.  You can obtain a copy
470*e7be843bSPierre Proncheryin the file LICENSE in the source distribution or at
471*e7be843bSPierre ProncheryL<https://www.openssl.org/source/license.html>.
472*e7be843bSPierre Pronchery
473*e7be843bSPierre Pronchery=cut
474