Home | History | Annotate | Line # | Download | only in man7
      1 =pod
      2 
      3 =begin comment
      4 
      5 NB: Changes to the source code samples in this file should also be reflected in
      6 demos/guide/tls-client-non-block.c
      7 
      8 =end comment
      9 
     10 =head1 NAME
     11 
     12 ossl-guide-tls-client-non-block
     13 - OpenSSL Guide: Writing a simple nonblocking TLS client
     14 
     15 =head1 SIMPLE NONBLOCKING TLS CLIENT EXAMPLE
     16 
     17 This page will build on the example developed on the
     18 L<ossl-guide-tls-client-block(7)> page which demonstrates how to write a simple
     19 blocking TLS client. On this page we will amend that demo code so that it
     20 supports a nonblocking socket.
     21 
     22 The complete source code for this example nonblocking TLS client is available
     23 in the B<demos/guide> directory of the OpenSSL source distribution in the file
     24 B<tls-client-non-block.c>. It is also available online at
     25 L<https://github.com/openssl/openssl/blob/master/demos/guide/tls-client-non-block.c>.
     26 
     27 As we saw in the previous example a blocking socket is one which waits (blocks)
     28 until data is available to read if you attempt to read from it when there is no
     29 data yet. Similarly it waits when writing if the socket is currently unable to
     30 write at the moment. This can simplify the development of code because you do
     31 not have to worry about what to do in these cases. The execution of the code
     32 will simply stop until it is able to continue. However in many cases you do not
     33 want this behaviour. Rather than stopping and waiting your application may need
     34 to go and do other tasks whilst the socket is unable to read/write, for example
     35 updating a GUI or performing operations on some other socket.
     36 
     37 With a nonblocking socket attempting to read or write to a socket that is
     38 currently unable to read or write will return immediately with a non-fatal
     39 error. Although OpenSSL does the reading/writing to the socket this nonblocking
     40 behaviour is propagated up to the application so that OpenSSL I/O functions such
     41 as L<SSL_read_ex(3)> or L<SSL_write_ex(3)> will not block.
     42 
     43 Since this page is building on the example developed on the
     44 L<ossl-guide-tls-client-block(7)> page we assume that you are familiar with it
     45 and we only explain how this example differs.
     46 
     47 =head2 Setting the socket to be nonblocking
     48 
     49 The first step in writing an application that supports nonblocking is to set
     50 the socket into nonblocking mode. A socket will be default be blocking. The
     51 exact details on how to do this can differ from one platform to another.
     52 Fortunately OpenSSL offers a portable function that will do this for you:
     53 
     54     /* Set to nonblocking mode */
     55     if (!BIO_socket_nbio(sock, 1)) {
     56         sock = -1;
     57         continue;
     58     }
     59 
     60 You do not have to use OpenSSL's function for this. You can of course directly
     61 call whatever functions that your Operating System provides for this purpose on
     62 your platform.
     63 
     64 =head2 Performing work while waiting for the socket
     65 
     66 In a nonblocking application you will need work to perform in the event that
     67 we want to read or write to the socket, but we are currently unable to. In fact
     68 this is the whole point of using a nonblocking socket, i.e. to give the
     69 application the opportunity to do something else. Whatever it is that the
     70 application has to do, it must also be prepared to come back and retry the
     71 operation that it previously attempted periodically to see if it can now
     72 complete. Ideally it would only do this in the event that the state of the
     73 underlying socket has actually changed (e.g. become readable where it wasn't
     74 before), but this does not have to be the case. It can retry at any time.
     75 
     76 Note that it is important that you retry exactly the same operation that you
     77 tried last time. You cannot start something new. For example if you were
     78 attempting to write the text "Hello World" and the operation failed because the
     79 socket is currently unable to write, then you cannot then attempt to write
     80 some other text when you retry the operation.
     81 
     82 In this demo application we will create a helper function which simulates doing
     83 other work. In fact, for the sake of simplicity, it will do nothing except wait
     84 for the state of the socket to change.
     85 
     86 We call our function C<wait_for_activity()> because all it does is wait until
     87 the underlying socket has become readable or writeable when it wasn't before.
     88 
     89     static void wait_for_activity(SSL *ssl, int write)
     90     {
     91         fd_set fds;
     92         int width, sock;
     93 
     94         /* Get hold of the underlying file descriptor for the socket */
     95         sock = SSL_get_fd(ssl);
     96 
     97         FD_ZERO(&fds);
     98         FD_SET(sock, &fds);
     99         width = sock + 1;
    100 
    101         /*
    102          * Wait until the socket is writeable or readable. We use select here
    103          * for the sake of simplicity and portability, but you could equally use
    104          * poll/epoll or similar functions
    105          *
    106          * NOTE: For the purposes of this demonstration code this effectively
    107          * makes this demo block until it has something more useful to do. In a
    108          * real application you probably want to go and do other work here (e.g.
    109          * update a GUI, or service other connections).
    110          *
    111          * Let's say for example that you want to update the progress counter on
    112          * a GUI every 100ms. One way to do that would be to add a 100ms timeout
    113          * in the last parameter to "select" below. Then, when select returns,
    114          * you check if it did so because of activity on the file descriptors or
    115          * because of the timeout. If it is due to the timeout then update the
    116          * GUI and then restart the "select".
    117          */
    118         if (write)
    119             select(width, NULL, &fds, NULL, NULL);
    120         else
    121             select(width, &fds, NULL, NULL, NULL);
    122     }
    123 
    124 In this example we are using the C<select> function because it is very simple
    125 to use and is available on most Operating Systems. However you could use any
    126 other similar function to do the same thing. C<select> waits for the state of
    127 the underlying socket(s) to become readable/writeable before returning. It also
    128 supports a "timeout" (as do most other similar functions) so in your own
    129 applications you can make use of this to periodically wake up and perform work
    130 while waiting for the socket state to change. But we don't use that timeout
    131 capability in this example for the sake of simplicity.
    132 
    133 =head2 Handling errors from OpenSSL I/O functions
    134 
    135 An application that uses a nonblocking socket will need to be prepared to
    136 handle errors returned from OpenSSL I/O functions such as L<SSL_read_ex(3)> or
    137 L<SSL_write_ex(3)>. Errors may be fatal (for example because the underlying
    138 connection has failed), or non-fatal (for example because we are trying to read
    139 from the underlying socket but the data has not yet arrived from the peer).
    140 
    141 L<SSL_read_ex(3)> and L<SSL_write_ex(3)> will return 0 to indicate an error and
    142 L<SSL_read(3)> and L<SSL_write(3)> will return 0 or a negative value to indicate
    143 an error. L<SSL_shutdown(3)> will return a negative value to incidate an error.
    144 
    145 In the event of an error an application should call L<SSL_get_error(3)> to find
    146 out what type of error has occurred. If the error is non-fatal and can be
    147 retried then L<SSL_get_error(3)> will return B<SSL_ERROR_WANT_READ> or
    148 B<SSL_ERROR_WANT_WRITE> depending on whether OpenSSL wanted to read to or write
    149 from the socket but was unable to. Note that a call to L<SSL_read_ex(3)> or
    150 L<SSL_read(3)> can still generate B<SSL_ERROR_WANT_WRITE> because OpenSSL
    151 may need to write protocol messages (such as to update cryptographic keys) even
    152 if the application is only trying to read data. Similarly calls to
    153 L<SSL_write_ex(3)> or L<SSL_write(3)> might generate B<SSL_ERROR_WANT_READ>.
    154 
    155 Another type of non-fatal error that may occur is B<SSL_ERROR_ZERO_RETURN>. This
    156 indicates an EOF (End-Of-File) which can occur if you attempt to read data from
    157 an B<SSL> object but the peer has indicated that it will not send any more data
    158 on it. In this case you may still want to write data to the connection but you
    159 will not receive any more data.
    160 
    161 Fatal errors that may occur are B<SSL_ERROR_SYSCALL> and B<SSL_ERROR_SSL>. These
    162 indicate that the underlying connection has failed. You should not attempt to
    163 shut it down with L<SSL_shutdown(3)>. B<SSL_ERROR_SYSCALL> indicates that
    164 OpenSSL attempted to make a syscall that failed. You can consult B<errno> for
    165 further details. B<SSL_ERROR_SSL> indicates that some OpenSSL error occurred. You
    166 can consult the OpenSSL error stack for further details (for example by calling
    167 L<ERR_print_errors(3)> to print out details of errors that have occurred).
    168 
    169 In our demo application we will write a function to handle these errors from
    170 OpenSSL I/O functions:
    171 
    172     static int handle_io_failure(SSL *ssl, int res)
    173     {
    174         switch (SSL_get_error(ssl, res)) {
    175         case SSL_ERROR_WANT_READ:
    176             /* Temporary failure. Wait until we can read and try again */
    177             wait_for_activity(ssl, 0);
    178             return 1;
    179 
    180         case SSL_ERROR_WANT_WRITE:
    181             /* Temporary failure. Wait until we can write and try again */
    182             wait_for_activity(ssl, 1);
    183             return 1;
    184 
    185         case SSL_ERROR_ZERO_RETURN:
    186             /* EOF */
    187             return 0;
    188 
    189         case SSL_ERROR_SYSCALL:
    190             return -1;
    191 
    192         case SSL_ERROR_SSL:
    193             /*
    194             * If the failure is due to a verification error we can get more
    195             * information about it from SSL_get_verify_result().
    196             */
    197             if (SSL_get_verify_result(ssl) != X509_V_OK)
    198                 printf("Verify error: %s\n",
    199                     X509_verify_cert_error_string(SSL_get_verify_result(ssl)));
    200             return -1;
    201 
    202         default:
    203             return -1;
    204         }
    205     }
    206 
    207 This function takes as arguments the B<SSL> object that represents the
    208 connection, as well as the return code from the I/O function that failed. In
    209 the event of a non-fatal failure, it waits until a retry of the I/O operation
    210 might succeed (by using the C<wait_for_activity()> function that we developed
    211 in the previous section). It returns 1 in the event of a non-fatal error
    212 (except EOF), 0 in the event of EOF, or -1 if a fatal error occurred.
    213 
    214 =head2 Creating the SSL_CTX and SSL objects
    215 
    216 In order to connect to a server we must create B<SSL_CTX> and B<SSL> objects for
    217 this. The steps do this are the same as for a blocking client and are explained
    218 on the L<ossl-guide-tls-client-block(7)> page. We won't repeat that information
    219 here.
    220 
    221 =head2 Performing the handshake
    222 
    223 As in the demo for a blocking TLS client we use the L<SSL_connect(3)> function
    224 to perform the TLS handshake with the server. Since we are using a nonblocking
    225 socket it is very likely that calls to this function will fail with a non-fatal
    226 error while we are waiting for the server to respond to our handshake messages.
    227 In such a case we must retry the same L<SSL_connect(3)> call at a later time.
    228 In this demo we this in a loop:
    229 
    230     /* Do the handshake with the server */
    231     while ((ret = SSL_connect(ssl)) != 1) {
    232         if (handle_io_failure(ssl, ret) == 1)
    233             continue; /* Retry */
    234         printf("Failed to connect to server\n");
    235         goto end; /* Cannot retry: error */
    236     }
    237 
    238 We continually call L<SSL_connect(3)> until it gives us a success response.
    239 Otherwise we use the C<handle_io_failure()> function that we created earlier to
    240 work out what we should do next. Note that we do not expect an EOF to occur at
    241 this stage, so such a response is treated in the same way as a fatal error.
    242 
    243 =head2 Sending and receiving data
    244 
    245 As with the blocking TLS client demo we use the L<SSL_write_ex(3)> function to
    246 send data to the server. As with L<SSL_connect(3)> above, because we are using
    247 a nonblocking socket, this call could fail with a non-fatal error. In that case
    248 we should retry exactly the same L<SSL_write_ex(3)> call again. Note that the
    249 parameters must be I<exactly> the same, i.e. the same pointer to the buffer to
    250 write with the same length. You must not attempt to send different data on a
    251 retry. An optional mode does exist (B<SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER>)
    252 which will configure OpenSSL to allow the buffer being written to change from
    253 one retry to the next. However, in this case, you must still retry exactly the
    254 same data - even though the buffer that contains that data may change location.
    255 See L<SSL_CTX_set_mode(3)> for further details. As in the TLS client
    256 blocking tutorial (L<ossl-guide-tls-client-block(7)>) we write the request
    257 in three chunks.
    258 
    259     /* Write an HTTP GET request to the peer */
    260     while (!SSL_write_ex(ssl, request_start, strlen(request_start), &written)) {
    261         if (handle_io_failure(ssl, 0) == 1)
    262             continue; /* Retry */
    263         printf("Failed to write start of HTTP request\n");
    264         goto end; /* Cannot retry: error */
    265     }
    266     while (!SSL_write_ex(ssl, hostname, strlen(hostname), &written)) {
    267         if (handle_io_failure(ssl, 0) == 1)
    268             continue; /* Retry */
    269         printf("Failed to write hostname in HTTP request\n");
    270         goto end; /* Cannot retry: error */
    271     }
    272     while (!SSL_write_ex(ssl, request_end, strlen(request_end), &written)) {
    273         if (handle_io_failure(ssl, 0) == 1)
    274             continue; /* Retry */
    275         printf("Failed to write end of HTTP request\n");
    276         goto end; /* Cannot retry: error */
    277     }
    278 
    279 On a write we do not expect to see an EOF response so we treat that case in the
    280 same way as a fatal error.
    281 
    282 Reading a response back from the server is similar:
    283 
    284     do {
    285         /*
    286          * Get up to sizeof(buf) bytes of the response. We keep reading until
    287          * the server closes the connection.
    288          */
    289         while (!eof && !SSL_read_ex(ssl, buf, sizeof(buf), &readbytes)) {
    290             switch (handle_io_failure(ssl, 0)) {
    291             case 1:
    292                 continue; /* Retry */
    293             case 0:
    294                 eof = 1;
    295                 continue;
    296             case -1:
    297             default:
    298                 printf("Failed reading remaining data\n");
    299                 goto end; /* Cannot retry: error */
    300             }
    301         }
    302         /*
    303          * OpenSSL does not guarantee that the returned data is a string or
    304          * that it is NUL terminated so we use fwrite() to write the exact
    305          * number of bytes that we read. The data could be non-printable or
    306          * have NUL characters in the middle of it. For this simple example
    307          * we're going to print it to stdout anyway.
    308          */
    309         if (!eof)
    310             fwrite(buf, 1, readbytes, stdout);
    311     } while (!eof);
    312     /* In case the response didn't finish with a newline we add one now */
    313     printf("\n");
    314 
    315 The main difference this time is that it is valid for us to receive an EOF
    316 response when trying to read data from the server. This will occur when the
    317 server closes down the connection after sending all the data in its response.
    318 
    319 In this demo we just print out all the data we've received back in the response
    320 from the server. We continue going around the loop until we either encounter a
    321 fatal error, or we receive an EOF (indicating a graceful finish).
    322 
    323 =head2 Shutting down the connection
    324 
    325 As in the TLS blocking example we must shutdown the connection when we are
    326 finished with it.
    327 
    328 If our application was initiating the shutdown then we would expect to see
    329 L<SSL_shutdown(3)> give a return value of 0, and then we would continue to call
    330 it until we received a return value of 1 (meaning we have successfully completed
    331 the shutdown). In this particular example we don't expect SSL_shutdown() to
    332 return 0 because we have already received EOF from the server indicating that it
    333 has shutdown already. So we just keep calling it until SSL_shutdown() returns 1.
    334 Since we are using a nonblocking socket we might expect to have to retry this
    335 operation several times. If L<SSL_shutdown(3)> returns a negative result then we
    336 must call L<SSL_get_error(3)> to work out what to do next. We use our
    337 handle_io_failure() function that we developed earlier for this:
    338 
    339     /*
    340      * The peer already shutdown gracefully (we know this because of the
    341      * SSL_ERROR_ZERO_RETURN (i.e. EOF) above). We should do the same back.
    342      */
    343     while ((ret = SSL_shutdown(ssl)) != 1) {
    344         if (ret < 0 && handle_io_failure(ssl, ret) == 1)
    345             continue; /* Retry */
    346         /*
    347          * ret == 0 is unexpected here because that means "we've sent a
    348          * close_notify and we're waiting for one back". But we already know
    349          * we got one from the peer because of the SSL_ERROR_ZERO_RETURN
    350          * (i.e. EOF) above.
    351          */
    352         printf("Error shutting down\n");
    353         goto end; /* Cannot retry: error */
    354     }
    355 
    356 =head2 Final clean up
    357 
    358 As with the blocking TLS client example, once our connection is finished with we
    359 must free it. The steps to do this for this example are the same as for the
    360 blocking example, so we won't repeat it here.
    361 
    362 =head1 FURTHER READING
    363 
    364 See L<ossl-guide-tls-client-block(7)> to read a tutorial on how to write a
    365 blocking TLS client. See L<ossl-guide-quic-client-block(7)> to see how to do the
    366 same thing for a QUIC client.
    367 
    368 =head1 SEE ALSO
    369 
    370 L<ossl-guide-introduction(7)>, L<ossl-guide-libraries-introduction(7)>,
    371 L<ossl-guide-libssl-introduction(7)>, L<ossl-guide-tls-introduction(7)>,
    372 L<ossl-guide-tls-client-block(7)>, L<ossl-guide-quic-client-block(7)>
    373 
    374 =head1 COPYRIGHT
    375 
    376 Copyright 2023 The OpenSSL Project Authors. All Rights Reserved.
    377 
    378 Licensed under the Apache License 2.0 (the "License").  You may not use
    379 this file except in compliance with the License.  You can obtain a copy
    380 in the file LICENSE in the source distribution or at
    381 L<https://www.openssl.org/source/license.html>.
    382 
    383 =cut
    384