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