ossl-guide-quic-client-non-block.pod 21 KB

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