ossl-guide-quic-client-non-block.7ossl 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599
  1. .\" Automatically generated by Pod::Man 4.14 (Pod::Simple 3.42)
  2. .\"
  3. .\" Standard preamble:
  4. .\" ========================================================================
  5. .de Sp \" Vertical space (when we can't use .PP)
  6. .if t .sp .5v
  7. .if n .sp
  8. ..
  9. .de Vb \" Begin verbatim text
  10. .ft CW
  11. .nf
  12. .ne \\$1
  13. ..
  14. .de Ve \" End verbatim text
  15. .ft R
  16. .fi
  17. ..
  18. .\" Set up some character translations and predefined strings. \*(-- will
  19. .\" give an unbreakable dash, \*(PI will give pi, \*(L" will give a left
  20. .\" double quote, and \*(R" will give a right double quote. \*(C+ will
  21. .\" give a nicer C++. Capital omega is used to do unbreakable dashes and
  22. .\" therefore won't be available. \*(C` and \*(C' expand to `' in nroff,
  23. .\" nothing in troff, for use with C<>.
  24. .tr \(*W-
  25. .ds C+ C\v'-.1v'\h'-1p'\s-2+\h'-1p'+\s0\v'.1v'\h'-1p'
  26. .ie n \{\
  27. . ds -- \(*W-
  28. . ds PI pi
  29. . if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch
  30. . if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\" diablo 12 pitch
  31. . ds L" ""
  32. . ds R" ""
  33. . ds C` ""
  34. . ds C' ""
  35. 'br\}
  36. .el\{\
  37. . ds -- \|\(em\|
  38. . ds PI \(*p
  39. . ds L" ``
  40. . ds R" ''
  41. . ds C`
  42. . ds C'
  43. 'br\}
  44. .\"
  45. .\" Escape single quotes in literal strings from groff's Unicode transform.
  46. .ie \n(.g .ds Aq \(aq
  47. .el .ds Aq '
  48. .\"
  49. .\" If the F register is >0, we'll generate index entries on stderr for
  50. .\" titles (.TH), headers (.SH), subsections (.SS), items (.Ip), and index
  51. .\" entries marked with X<> in POD. Of course, you'll have to process the
  52. .\" output yourself in some meaningful fashion.
  53. .\"
  54. .\" Avoid warning from groff about undefined register 'F'.
  55. .de IX
  56. ..
  57. .nr rF 0
  58. .if \n(.g .if rF .nr rF 1
  59. .if (\n(rF:(\n(.g==0)) \{\
  60. . if \nF \{\
  61. . de IX
  62. . tm Index:\\$1\t\\n%\t"\\$2"
  63. ..
  64. . if !\nF==2 \{\
  65. . nr % 0
  66. . nr F 2
  67. . \}
  68. . \}
  69. .\}
  70. .rr rF
  71. .\"
  72. .\" Accent mark definitions (@(#)ms.acc 1.5 88/02/08 SMI; from UCB 4.2).
  73. .\" Fear. Run. Save yourself. No user-serviceable parts.
  74. . \" fudge factors for nroff and troff
  75. .if n \{\
  76. . ds #H 0
  77. . ds #V .8m
  78. . ds #F .3m
  79. . ds #[ \f1
  80. . ds #] \fP
  81. .\}
  82. .if t \{\
  83. . ds #H ((1u-(\\\\n(.fu%2u))*.13m)
  84. . ds #V .6m
  85. . ds #F 0
  86. . ds #[ \&
  87. . ds #] \&
  88. .\}
  89. . \" simple accents for nroff and troff
  90. .if n \{\
  91. . ds ' \&
  92. . ds ` \&
  93. . ds ^ \&
  94. . ds , \&
  95. . ds ~ ~
  96. . ds /
  97. .\}
  98. .if t \{\
  99. . ds ' \\k:\h'-(\\n(.wu*8/10-\*(#H)'\'\h"|\\n:u"
  100. . ds ` \\k:\h'-(\\n(.wu*8/10-\*(#H)'\`\h'|\\n:u'
  101. . ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'^\h'|\\n:u'
  102. . ds , \\k:\h'-(\\n(.wu*8/10)',\h'|\\n:u'
  103. . ds ~ \\k:\h'-(\\n(.wu-\*(#H-.1m)'~\h'|\\n:u'
  104. . ds / \\k:\h'-(\\n(.wu*8/10-\*(#H)'\z\(sl\h'|\\n:u'
  105. .\}
  106. . \" troff and (daisy-wheel) nroff accents
  107. .ds : \\k:\h'-(\\n(.wu*8/10-\*(#H+.1m+\*(#F)'\v'-\*(#V'\z.\h'.2m+\*(#F'.\h'|\\n:u'\v'\*(#V'
  108. .ds 8 \h'\*(#H'\(*b\h'-\*(#H'
  109. .ds o \\k:\h'-(\\n(.wu+\w'\(de'u-\*(#H)/2u'\v'-.3n'\*(#[\z\(de\v'.3n'\h'|\\n:u'\*(#]
  110. .ds d- \h'\*(#H'\(pd\h'-\w'~'u'\v'-.25m'\f2\(hy\fP\v'.25m'\h'-\*(#H'
  111. .ds D- D\\k:\h'-\w'D'u'\v'-.11m'\z\(hy\v'.11m'\h'|\\n:u'
  112. .ds th \*(#[\v'.3m'\s+1I\s-1\v'-.3m'\h'-(\w'I'u*2/3)'\s-1o\s+1\*(#]
  113. .ds Th \*(#[\s+2I\s-2\h'-\w'I'u*3/5'\v'-.3m'o\v'.3m'\*(#]
  114. .ds ae a\h'-(\w'a'u*4/10)'e
  115. .ds Ae A\h'-(\w'A'u*4/10)'E
  116. . \" corrections for vroff
  117. .if v .ds ~ \\k:\h'-(\\n(.wu*9/10-\*(#H)'\s-2\u~\d\s+2\h'|\\n:u'
  118. .if v .ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'\v'-.4m'^\v'.4m'\h'|\\n:u'
  119. . \" for low resolution devices (crt and lpr)
  120. .if \n(.H>23 .if \n(.V>19 \
  121. \{\
  122. . ds : e
  123. . ds 8 ss
  124. . ds o a
  125. . ds d- d\h'-1'\(ga
  126. . ds D- D\h'-1'\(hy
  127. . ds th \o'bp'
  128. . ds Th \o'LP'
  129. . ds ae ae
  130. . ds Ae AE
  131. .\}
  132. .rm #[ #] #H #V #F C
  133. .\" ========================================================================
  134. .\"
  135. .IX Title "OSSL-GUIDE-QUIC-CLIENT-NON-BLOCK 7ossl"
  136. .TH OSSL-GUIDE-QUIC-CLIENT-NON-BLOCK 7ossl "2024-09-03" "3.3.2" "OpenSSL"
  137. .\" For nroff, turn off justification. Always turn off hyphenation; it makes
  138. .\" way too many mistakes in technical documents.
  139. .if n .ad l
  140. .nh
  141. .SH "NAME"
  142. ossl\-guide\-quic\-client\-non\-block
  143. \&\- OpenSSL Guide: Writing a simple nonblocking QUIC client
  144. .SH "SIMPLE NONBLOCKING QUIC CLIENT EXAMPLE"
  145. .IX Header "SIMPLE NONBLOCKING QUIC CLIENT EXAMPLE"
  146. This page will build on the example developed on the
  147. \&\fBossl\-guide\-quic\-client\-block\fR\|(7) page which demonstrates how to write a simple
  148. blocking \s-1QUIC\s0 client. On this page we will amend that demo code so that it
  149. supports nonblocking functionality.
  150. .PP
  151. The complete source code for this example nonblocking \s-1QUIC\s0 client is available
  152. in the \fBdemos/guide\fR directory of the OpenSSL source distribution in the file
  153. \&\fBquic\-client\-non\-block.c\fR. It is also available online at
  154. <https://github.com/openssl/openssl/blob/master/demos/guide/quic\-client\-non\-block.c>.
  155. .PP
  156. As we saw in the previous example an OpenSSL \s-1QUIC\s0 application always uses a
  157. nonblocking socket. However, despite this, the \fB\s-1SSL\s0\fR object still has blocking
  158. behaviour. When the \fB\s-1SSL\s0\fR object has blocking behaviour then this means that
  159. it waits (blocks) until data is available to read if you attempt to read from
  160. it when there is no data yet. Similarly it waits when writing if the \fB\s-1SSL\s0\fR
  161. object is currently unable to write at the moment. This can simplify the
  162. development of code because you do not have to worry about what to do in these
  163. cases. The execution of the code will simply stop until it is able to continue.
  164. However in many cases you do not want this behaviour. Rather than stopping and
  165. waiting your application may need to go and do other tasks whilst the \fB\s-1SSL\s0\fR
  166. object is unable to read/write, for example updating a \s-1GUI\s0 or performing
  167. operations on some other connection or stream.
  168. .PP
  169. We will see later in this tutorial how to change the \fB\s-1SSL\s0\fR object so that it
  170. has nonblocking behaviour. With a nonblocking \fB\s-1SSL\s0\fR object, functions such as
  171. \&\fBSSL_read_ex\fR\|(3) or \fBSSL_write_ex\fR\|(3) will return immediately with a non-fatal
  172. error if they are currently unable to read or write respectively.
  173. .PP
  174. Since this page is building on the example developed on the
  175. \&\fBossl\-guide\-quic\-client\-block\fR\|(7) page we assume that you are familiar with it
  176. and we only explain how this example differs.
  177. .SS "Performing work while waiting for the socket"
  178. .IX Subsection "Performing work while waiting for the socket"
  179. In a nonblocking application you will need work to perform in the event that
  180. we want to read or write to the \fB\s-1SSL\s0\fR object but we are currently unable to.
  181. In fact this is the whole point of using a nonblocking \fB\s-1SSL\s0\fR object, i.e. to
  182. give the application the opportunity to do something else. Whatever it is that
  183. the application has to do, it must also be prepared to come back and retry the
  184. operation that it previously attempted periodically to see if it can now
  185. complete. Ideally it would only do this in the event that something has changed
  186. such that it might succeed on the retry attempt, but this does not have to be
  187. the case. It can retry at any time.
  188. .PP
  189. Note that it is important that you retry exactly the same operation that you
  190. tried last time. You cannot start something new. For example if you were
  191. attempting to write the text \*(L"Hello World\*(R" and the operation failed because the
  192. \&\fB\s-1SSL\s0\fR object is currently unable to write, then you cannot then attempt to
  193. write some other text when you retry the operation.
  194. .PP
  195. In this demo application we will create a helper function which simulates doing
  196. other work. In fact, for the sake of simplicity, it will do nothing except wait
  197. for the state of the underlying socket to change or until a timeout expires
  198. after which the state of the \fB\s-1SSL\s0\fR object might have changed. We will call our
  199. function \f(CW\*(C`wait_for_activity()\*(C'\fR.
  200. .PP
  201. .Vb 6
  202. \& static void wait_for_activity(SSL *ssl)
  203. \& {
  204. \& fd_set wfds, rfds;
  205. \& int width, sock, isinfinite;
  206. \& struct timeval tv;
  207. \& struct timeval *tvp = NULL;
  208. \&
  209. \& /* Get hold of the underlying file descriptor for the socket */
  210. \& sock = SSL_get_fd(ssl);
  211. \&
  212. \& FD_ZERO(&wfds);
  213. \& FD_ZERO(&rfds);
  214. \&
  215. \& /*
  216. \& * Find out if we would like to write to the socket, or read from it (or
  217. \& * both)
  218. \& */
  219. \& if (SSL_net_write_desired(ssl))
  220. \& FD_SET(sock, &wfds);
  221. \& if (SSL_net_read_desired(ssl))
  222. \& FD_SET(sock, &rfds);
  223. \& width = sock + 1;
  224. \&
  225. \& /*
  226. \& * Find out when OpenSSL would next like to be called, regardless of
  227. \& * whether the state of the underlying socket has changed or not.
  228. \& */
  229. \& if (SSL_get_event_timeout(ssl, &tv, &isinfinite) && !isinfinite)
  230. \& tvp = &tv;
  231. \&
  232. \& /*
  233. \& * Wait until the socket is writeable or readable. We use select here
  234. \& * for the sake of simplicity and portability, but you could equally use
  235. \& * poll/epoll or similar functions
  236. \& *
  237. \& * NOTE: For the purposes of this demonstration code this effectively
  238. \& * makes this demo block until it has something more useful to do. In a
  239. \& * real application you probably want to go and do other work here (e.g.
  240. \& * update a GUI, or service other connections).
  241. \& *
  242. \& * Let\*(Aqs say for example that you want to update the progress counter on
  243. \& * a GUI every 100ms. One way to do that would be to use the timeout in
  244. \& * the last parameter to "select" below. If the tvp value is greater
  245. \& * than 100ms then use 100ms instead. Then, when select returns, you
  246. \& * check if it did so because of activity on the file descriptors or
  247. \& * because of the timeout. If the 100ms GUI timeout has expired but the
  248. \& * tvp timeout has not then go and update the GUI and then restart the
  249. \& * "select" (with updated timeouts).
  250. \& */
  251. \&
  252. \& select(width, &rfds, &wfds, NULL, tvp);
  253. \&}
  254. .Ve
  255. .PP
  256. If you are familiar with how to write nonblocking applications in OpenSSL for
  257. \&\s-1TLS\s0 (see \fBossl\-guide\-tls\-client\-non\-block\fR\|(7)) then you should note that there
  258. is an important difference here between the way a \s-1QUIC\s0 application and a \s-1TLS\s0
  259. application works. With a \s-1TLS\s0 application if we try to read or write something
  260. to the \fB\s-1SSL\s0\fR object and we get a \*(L"retry\*(R" response (\fB\s-1SSL_ERROR_WANT_READ\s0\fR or
  261. \&\fB\s-1SSL_ERROR_WANT_WRITE\s0\fR) then we can assume that is because OpenSSL attempted to
  262. read or write to the underlying socket and the socket signalled the \*(L"retry\*(R".
  263. With \s-1QUIC\s0 that is not the case. OpenSSL may signal retry as a result of an
  264. \&\fBSSL_read_ex\fR\|(3) or \fBSSL_write_ex\fR\|(3) (or similar) call which indicates the
  265. state of the stream. This is entirely independent of whether the underlying
  266. socket needs to retry or not.
  267. .PP
  268. To determine whether OpenSSL currently wants to read or write to the underlying
  269. socket for a \s-1QUIC\s0 application we must call the \fBSSL_net_read_desired\fR\|(3) and
  270. \&\fBSSL_net_write_desired\fR\|(3) functions.
  271. .PP
  272. It is also important with \s-1QUIC\s0 that we periodically call an I/O function (or
  273. otherwise call the \fBSSL_handle_events\fR\|(3) function) to ensure that the \s-1QUIC\s0
  274. connection remains healthy. This is particularly important with a nonblocking
  275. application because you are likely to leave the \fB\s-1SSL\s0\fR object idle for a while
  276. while the application goes off to do other work. The \fBSSL_get_event_timeout\fR\|(3)
  277. function can be used to determine what the deadline is for the next time we need
  278. to call an I/O function (or call \fBSSL_handle_events\fR\|(3)).
  279. .PP
  280. An alternative to using \fBSSL_get_event_timeout\fR\|(3) to find the next deadline
  281. that OpenSSL must be called again by is to use \*(L"thread assisted\*(R" mode. In
  282. \&\*(L"thread assisted\*(R" mode OpenSSL spawns an additional thread which will
  283. periodically call \fBSSL_handle_events\fR\|(3) automatically, meaning that the
  284. application can leave the connection idle safe in the knowledge that the
  285. connection will still be maintained in a healthy state. See
  286. \&\*(L"Creating the \s-1SSL_CTX\s0 and \s-1SSL\s0 objects\*(R" below for further details about this.
  287. .PP
  288. In this example we are using the \f(CW\*(C`select\*(C'\fR function to check the
  289. readability/writeability of the socket because it is very simple to use and is
  290. available on most Operating Systems. However you could use any other similar
  291. function to do the same thing. \f(CW\*(C`select\*(C'\fR waits for the state of the underlying
  292. socket(s) to become readable/writeable or until the timeout has expired before
  293. returning.
  294. .SS "Handling errors from OpenSSL I/O functions"
  295. .IX Subsection "Handling errors from OpenSSL I/O functions"
  296. A \s-1QUIC\s0 application that has been configured for nonblocking behaviour will need
  297. to be prepared to handle errors returned from OpenSSL I/O functions such as
  298. \&\fBSSL_read_ex\fR\|(3) or \fBSSL_write_ex\fR\|(3). Errors may be fatal for the stream (for
  299. example because the stream has been reset or because the underlying connection
  300. has failed), or non-fatal (for example because we are trying to read from the
  301. stream but no data has not yet arrived from the peer for that stream).
  302. .PP
  303. \&\fBSSL_read_ex\fR\|(3) and \fBSSL_write_ex\fR\|(3) will return 0 to indicate an error and
  304. \&\fBSSL_read\fR\|(3) and \fBSSL_write\fR\|(3) will return 0 or a negative value to indicate
  305. an error. \fBSSL_shutdown\fR\|(3) will return a negative value to incidate an error.
  306. .PP
  307. In the event of an error an application should call \fBSSL_get_error\fR\|(3) to find
  308. out what type of error has occurred. If the error is non-fatal and can be
  309. retried then \fBSSL_get_error\fR\|(3) will return \fB\s-1SSL_ERROR_WANT_READ\s0\fR or
  310. \&\fB\s-1SSL_ERROR_WANT_WRITE\s0\fR depending on whether OpenSSL wanted to read to or write
  311. from the stream but was unable to. Note that a call to \fBSSL_read_ex\fR\|(3) or
  312. \&\fBSSL_read\fR\|(3) can still generate \fB\s-1SSL_ERROR_WANT_WRITE\s0\fR. Similarly calls to
  313. \&\fBSSL_write_ex\fR\|(3) or \fBSSL_write\fR\|(3) might generate \fB\s-1SSL_ERROR_WANT_READ\s0\fR.
  314. .PP
  315. Another type of non-fatal error that may occur is \fB\s-1SSL_ERROR_ZERO_RETURN\s0\fR. This
  316. indicates an \s-1EOF\s0 (End-Of-File) which can occur if you attempt to read data from
  317. an \fB\s-1SSL\s0\fR object but the peer has indicated that it will not send any more data
  318. on the stream. In this case you may still want to write data to the stream but
  319. you will not receive any more data.
  320. .PP
  321. Fatal errors that may occur are \fB\s-1SSL_ERROR_SYSCALL\s0\fR and \fB\s-1SSL_ERROR_SSL\s0\fR. These
  322. indicate that the stream is no longer usable. For example, this could be because
  323. the stream has been reset by the peer, or because the underlying connection has
  324. failed. You can consult the OpenSSL error stack for further details (for example
  325. by calling \fBERR_print_errors\fR\|(3) to print out details of errors that have
  326. occurred). You can also consult the return value of
  327. \&\fBSSL_get_stream_read_state\fR\|(3) to determine whether the error is local to the
  328. stream, or whether the underlying connection has also failed. A return value
  329. of \fB\s-1SSL_STREAM_STATE_RESET_REMOTE\s0\fR tells you that the stream has been reset by
  330. the peer and \fB\s-1SSL_STREAM_STATE_CONN_CLOSED\s0\fR tells you that the underlying
  331. connection has closed.
  332. .PP
  333. In our demo application we will write a function to handle these errors from
  334. OpenSSL I/O functions:
  335. .PP
  336. .Vb 8
  337. \& static int handle_io_failure(SSL *ssl, int res)
  338. \& {
  339. \& switch (SSL_get_error(ssl, res)) {
  340. \& case SSL_ERROR_WANT_READ:
  341. \& case SSL_ERROR_WANT_WRITE:
  342. \& /* Temporary failure. Wait until we can read/write and try again */
  343. \& wait_for_activity(ssl);
  344. \& return 1;
  345. \&
  346. \& case SSL_ERROR_ZERO_RETURN:
  347. \& /* EOF */
  348. \& return 0;
  349. \&
  350. \& case SSL_ERROR_SYSCALL:
  351. \& return \-1;
  352. \&
  353. \& case SSL_ERROR_SSL:
  354. \& /*
  355. \& * Some stream fatal error occurred. This could be because of a
  356. \& * stream reset \- or some failure occurred on the underlying
  357. \& * connection.
  358. \& */
  359. \& switch (SSL_get_stream_read_state(ssl)) {
  360. \& case SSL_STREAM_STATE_RESET_REMOTE:
  361. \& printf("Stream reset occurred\en");
  362. \& /*
  363. \& * The stream has been reset but the connection is still
  364. \& * healthy.
  365. \& */
  366. \& break;
  367. \&
  368. \& case SSL_STREAM_STATE_CONN_CLOSED:
  369. \& printf("Connection closed\en");
  370. \& /* Connection is already closed. */
  371. \& break;
  372. \&
  373. \& default:
  374. \& printf("Unknown stream failure\en");
  375. \& break;
  376. \& }
  377. \& /*
  378. \& * If the failure is due to a verification error we can get more
  379. \& * information about it from SSL_get_verify_result().
  380. \& */
  381. \& if (SSL_get_verify_result(ssl) != X509_V_OK)
  382. \& printf("Verify error: %s\en",
  383. \& X509_verify_cert_error_string(SSL_get_verify_result(ssl)));
  384. \& return \-1;
  385. \&
  386. \& default:
  387. \& return \-1;
  388. \& }
  389. \& }
  390. .Ve
  391. .PP
  392. This function takes as arguments the \fB\s-1SSL\s0\fR object that represents the
  393. connection, as well as the return code from the I/O function that failed. In
  394. the event of a non-fatal failure, it waits until a retry of the I/O operation
  395. might succeed (by using the \f(CW\*(C`wait_for_activity()\*(C'\fR function that we developed
  396. in the previous section). It returns 1 in the event of a non-fatal error
  397. (except \s-1EOF\s0), 0 in the event of \s-1EOF,\s0 or \-1 if a fatal error occurred.
  398. .SS "Creating the \s-1SSL_CTX\s0 and \s-1SSL\s0 objects"
  399. .IX Subsection "Creating the SSL_CTX and SSL objects"
  400. In order to connect to a server we must create \fB\s-1SSL_CTX\s0\fR and \fB\s-1SSL\s0\fR objects for
  401. this. Most of the steps to do this are the same as for a blocking client and are
  402. explained on the \fBossl\-guide\-quic\-client\-block\fR\|(7) page. We won't repeat that
  403. information here.
  404. .PP
  405. One key difference is that we must put the \fB\s-1SSL\s0\fR object into nonblocking mode
  406. (the default is blocking mode). To do that we use the
  407. \&\fBSSL_set_blocking_mode\fR\|(3) function:
  408. .PP
  409. .Vb 9
  410. \& /*
  411. \& * The underlying socket is always nonblocking with QUIC, but the default
  412. \& * behaviour of the SSL object is still to block. We set it for nonblocking
  413. \& * mode in this demo.
  414. \& */
  415. \& if (!SSL_set_blocking_mode(ssl, 0)) {
  416. \& printf("Failed to turn off blocking mode\en");
  417. \& goto end;
  418. \& }
  419. .Ve
  420. .PP
  421. Although the demo application that we are developing here does not use it, it is
  422. possible to use \*(L"thread assisted mode\*(R" when developing \s-1QUIC\s0 applications.
  423. Normally, when writing an OpenSSL \s-1QUIC\s0 application, it is important that
  424. \&\fBSSL_handle_events\fR\|(3) (or alternatively any I/O function) is called on the
  425. connection \fB\s-1SSL\s0\fR object periodically to maintain the connection in a healthy
  426. state. See \*(L"Performing work while waiting for the socket\*(R" for more discussion
  427. on this. This is particularly important to keep in mind when writing a
  428. nonblocking \s-1QUIC\s0 application because it is common to leave the \fB\s-1SSL\s0\fR connection
  429. object idle for some time when using nonblocking mode. By using \*(L"thread assisted
  430. mode\*(R" a separate thread is created by OpenSSL to do this automatically which
  431. means that the application developer does not need to handle this aspect. To do
  432. this we must use \fBOSSL_QUIC_client_thread_method\fR\|(3) when we construct the
  433. \&\fB\s-1SSL_CTX\s0\fR as shown below:
  434. .PP
  435. .Vb 5
  436. \& ctx = SSL_CTX_new(OSSL_QUIC_client_thread_method());
  437. \& if (ctx == NULL) {
  438. \& printf("Failed to create the SSL_CTX\en");
  439. \& goto end;
  440. \& }
  441. .Ve
  442. .SS "Performing the handshake"
  443. .IX Subsection "Performing the handshake"
  444. As in the demo for a blocking \s-1QUIC\s0 client we use the \fBSSL_connect\fR\|(3) function
  445. to perform the handshake with the server. Since we are using a nonblocking
  446. \&\fB\s-1SSL\s0\fR object it is very likely that calls to this function will fail with a
  447. non-fatal error while we are waiting for the server to respond to our handshake
  448. messages. In such a case we must retry the same \fBSSL_connect\fR\|(3) call at a
  449. later time. In this demo we do this in a loop:
  450. .PP
  451. .Vb 7
  452. \& /* Do the handshake with the server */
  453. \& while ((ret = SSL_connect(ssl)) != 1) {
  454. \& if (handle_io_failure(ssl, ret) == 1)
  455. \& continue; /* Retry */
  456. \& printf("Failed to connect to server\en");
  457. \& goto end; /* Cannot retry: error */
  458. \& }
  459. .Ve
  460. .PP
  461. We continually call \fBSSL_connect\fR\|(3) until it gives us a success response.
  462. Otherwise we use the \f(CW\*(C`handle_io_failure()\*(C'\fR function that we created earlier to
  463. work out what we should do next. Note that we do not expect an \s-1EOF\s0 to occur at
  464. this stage, so such a response is treated in the same way as a fatal error.
  465. .SS "Sending and receiving data"
  466. .IX Subsection "Sending and receiving data"
  467. As with the blocking \s-1QUIC\s0 client demo we use the \fBSSL_write_ex\fR\|(3) function to
  468. send data to the server. As with \fBSSL_connect\fR\|(3) above, because we are using
  469. a nonblocking \fB\s-1SSL\s0\fR object, this call could fail with a non-fatal error. In
  470. that case we should retry exactly the same \fBSSL_write_ex\fR\|(3) call again. Note
  471. that the parameters must be \fIexactly\fR the same, i.e. the same pointer to the
  472. buffer to write with the same length. You must not attempt to send different
  473. data on a retry. An optional mode does exist
  474. (\fB\s-1SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER\s0\fR) which will configure OpenSSL to allow
  475. the buffer being written to change from one retry to the next. However, in this
  476. case, you must still retry exactly the same data \- even though the buffer that
  477. contains that data may change location. See \fBSSL_CTX_set_mode\fR\|(3) for further
  478. details. As in the \s-1TLS\s0 tutorials (\fBossl\-guide\-tls\-client\-block\fR\|(7)) we write
  479. the request in three chunks.
  480. .PP
  481. .Vb 10
  482. \& /* Write an HTTP GET request to the peer */
  483. \& while (!SSL_write_ex(ssl, request_start, strlen(request_start), &written)) {
  484. \& if (handle_io_failure(ssl, 0) == 1)
  485. \& continue; /* Retry */
  486. \& printf("Failed to write start of HTTP request\en");
  487. \& goto end; /* Cannot retry: error */
  488. \& }
  489. \& while (!SSL_write_ex(ssl, hostname, strlen(hostname), &written)) {
  490. \& if (handle_io_failure(ssl, 0) == 1)
  491. \& continue; /* Retry */
  492. \& printf("Failed to write hostname in HTTP request\en");
  493. \& goto end; /* Cannot retry: error */
  494. \& }
  495. \& while (!SSL_write_ex(ssl, request_end, strlen(request_end), &written)) {
  496. \& if (handle_io_failure(ssl, 0) == 1)
  497. \& continue; /* Retry */
  498. \& printf("Failed to write end of HTTP request\en");
  499. \& goto end; /* Cannot retry: error */
  500. \& }
  501. .Ve
  502. .PP
  503. On a write we do not expect to see an \s-1EOF\s0 response so we treat that case in the
  504. same way as a fatal error.
  505. .PP
  506. Reading a response back from the server is similar:
  507. .PP
  508. .Vb 10
  509. \& do {
  510. \& /*
  511. \& * Get up to sizeof(buf) bytes of the response. We keep reading until
  512. \& * the server closes the connection.
  513. \& */
  514. \& while (!eof && !SSL_read_ex(ssl, buf, sizeof(buf), &readbytes)) {
  515. \& switch (handle_io_failure(ssl, 0)) {
  516. \& case 1:
  517. \& continue; /* Retry */
  518. \& case 0:
  519. \& eof = 1;
  520. \& continue;
  521. \& case \-1:
  522. \& default:
  523. \& printf("Failed reading remaining data\en");
  524. \& goto end; /* Cannot retry: error */
  525. \& }
  526. \& }
  527. \& /*
  528. \& * OpenSSL does not guarantee that the returned data is a string or
  529. \& * that it is NUL terminated so we use fwrite() to write the exact
  530. \& * number of bytes that we read. The data could be non\-printable or
  531. \& * have NUL characters in the middle of it. For this simple example
  532. \& * we\*(Aqre going to print it to stdout anyway.
  533. \& */
  534. \& if (!eof)
  535. \& fwrite(buf, 1, readbytes, stdout);
  536. \& } while (!eof);
  537. \& /* In case the response didn\*(Aqt finish with a newline we add one now */
  538. \& printf("\en");
  539. .Ve
  540. .PP
  541. The main difference this time is that it is valid for us to receive an \s-1EOF\s0
  542. response when trying to read data from the server. This will occur when the
  543. server closes down the connection after sending all the data in its response.
  544. .PP
  545. In this demo we just print out all the data we've received back in the response
  546. from the server. We continue going around the loop until we either encounter a
  547. fatal error, or we receive an \s-1EOF\s0 (indicating a graceful finish).
  548. .SS "Shutting down the connection"
  549. .IX Subsection "Shutting down the connection"
  550. As in the \s-1QUIC\s0 blocking example we must shutdown the connection when we are
  551. finished with it.
  552. .PP
  553. Even though we have received \s-1EOF\s0 on the stream that we were reading from above,
  554. this tell us nothing about the state of the underlying connection. Our demo
  555. application will initiate the connection shutdown process via
  556. \&\fBSSL_shutdown\fR\|(3).
  557. .PP
  558. Since our application is initiating the shutdown then we might expect to see
  559. \&\fBSSL_shutdown\fR\|(3) give a return value of 0, and then we should continue to call
  560. it until we receive a return value of 1 (meaning we have successfully completed
  561. the shutdown). Since we are using a nonblocking \fB\s-1SSL\s0\fR object we might expect to
  562. have to retry this operation several times. If \fBSSL_shutdown\fR\|(3) returns a
  563. negative result then we must call \fBSSL_get_error\fR\|(3) to work out what to do
  564. next. We use our \fBhandle_io_failure()\fR function that we developed earlier for
  565. this:
  566. .PP
  567. .Vb 8
  568. \& /*
  569. \& * Repeatedly call SSL_shutdown() until the connection is fully
  570. \& * closed.
  571. \& */
  572. \& while ((ret = SSL_shutdown(ssl)) != 1) {
  573. \& if (ret < 0 && handle_io_failure(ssl, ret) == 1)
  574. \& continue; /* Retry */
  575. \& }
  576. .Ve
  577. .SS "Final clean up"
  578. .IX Subsection "Final clean up"
  579. As with the blocking \s-1QUIC\s0 client example, once our connection is finished with
  580. we must free it. The steps to do this for this example are the same as for the
  581. blocking example, so we won't repeat it here.
  582. .SH "FURTHER READING"
  583. .IX Header "FURTHER READING"
  584. See \fBossl\-guide\-quic\-client\-block\fR\|(7) to read a tutorial on how to write a
  585. blocking \s-1QUIC\s0 client. See \fBossl\-guide\-quic\-multi\-stream\fR\|(7) to see how to write
  586. a multi-stream \s-1QUIC\s0 client.
  587. .SH "SEE ALSO"
  588. .IX Header "SEE ALSO"
  589. \&\fBossl\-guide\-introduction\fR\|(7), \fBossl\-guide\-libraries\-introduction\fR\|(7),
  590. \&\fBossl\-guide\-libssl\-introduction\fR\|(7), \fBossl\-guide\-quic\-introduction\fR\|(7),
  591. \&\fBossl\-guide\-quic\-client\-block\fR\|(7), \fBossl\-guide\-quic\-multi\-stream\fR\|(7)
  592. .SH "COPYRIGHT"
  593. .IX Header "COPYRIGHT"
  594. Copyright 2023 The OpenSSL Project Authors. All Rights Reserved.
  595. .PP
  596. Licensed under the Apache License 2.0 (the \*(L"License\*(R"). You may not use
  597. this file except in compliance with the License. You can obtain a copy
  598. in the file \s-1LICENSE\s0 in the source distribution or at
  599. <https://www.openssl.org/source/license.html>.