ossl-guide-tls-client-non-block.pod 17 KB

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