ossl-guide-tls-client-non-block.7ossl 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513
  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-TLS-CLIENT-NON-BLOCK 7ossl"
  136. .TH OSSL-GUIDE-TLS-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\-tls\-client\-non\-block
  143. \&\- OpenSSL Guide: Writing a simple nonblocking TLS client
  144. .SH "SIMPLE NONBLOCKING TLS CLIENT EXAMPLE"
  145. .IX Header "SIMPLE NONBLOCKING TLS CLIENT EXAMPLE"
  146. This page will build on the example developed on the
  147. \&\fBossl\-guide\-tls\-client\-block\fR\|(7) page which demonstrates how to write a simple
  148. blocking \s-1TLS\s0 client. On this page we will amend that demo code so that it
  149. supports a nonblocking socket.
  150. .PP
  151. The complete source code for this example nonblocking \s-1TLS\s0 client is available
  152. in the \fBdemos/guide\fR directory of the OpenSSL source distribution in the file
  153. \&\fBtls\-client\-non\-block.c\fR. It is also available online at
  154. <https://github.com/openssl/openssl/blob/master/demos/guide/tls\-client\-non\-block.c>.
  155. .PP
  156. As we saw in the previous example a blocking socket is one which waits (blocks)
  157. until data is available to read if you attempt to read from it when there is no
  158. data yet. Similarly it waits when writing if the socket is currently unable to
  159. write at the moment. This can simplify the development of code because you do
  160. not have to worry about what to do in these cases. The execution of the code
  161. will simply stop until it is able to continue. However in many cases you do not
  162. want this behaviour. Rather than stopping and waiting your application may need
  163. to go and do other tasks whilst the socket is unable to read/write, for example
  164. updating a \s-1GUI\s0 or performing operations on some other socket.
  165. .PP
  166. With a nonblocking socket attempting to read or write to a socket that is
  167. currently unable to read or write will return immediately with a non-fatal
  168. error. Although OpenSSL does the reading/writing to the socket this nonblocking
  169. behaviour is propagated up to the application so that OpenSSL I/O functions such
  170. as \fBSSL_read_ex\fR\|(3) or \fBSSL_write_ex\fR\|(3) will not block.
  171. .PP
  172. Since this page is building on the example developed on the
  173. \&\fBossl\-guide\-tls\-client\-block\fR\|(7) page we assume that you are familiar with it
  174. and we only explain how this example differs.
  175. .SS "Setting the socket to be nonblocking"
  176. .IX Subsection "Setting the socket to be nonblocking"
  177. The first step in writing an application that supports nonblocking is to set
  178. the socket into nonblocking mode. A socket will be default be blocking. The
  179. exact details on how to do this can differ from one platform to another.
  180. Fortunately OpenSSL offers a portable function that will do this for you:
  181. .PP
  182. .Vb 5
  183. \& /* Set to nonblocking mode */
  184. \& if (!BIO_socket_nbio(sock, 1)) {
  185. \& sock = \-1;
  186. \& continue;
  187. \& }
  188. .Ve
  189. .PP
  190. You do not have to use OpenSSL's function for this. You can of course directly
  191. call whatever functions that your Operating System provides for this purpose on
  192. your platform.
  193. .SS "Performing work while waiting for the socket"
  194. .IX Subsection "Performing work while waiting for the socket"
  195. In a nonblocking application you will need work to perform in the event that
  196. we want to read or write to the socket, but we are currently unable to. In fact
  197. this is the whole point of using a nonblocking socket, i.e. to give the
  198. application the opportunity to do something else. Whatever it is that the
  199. application has to do, it must also be prepared to come back and retry the
  200. operation that it previously attempted periodically to see if it can now
  201. complete. Ideally it would only do this in the event that the state of the
  202. underlying socket has actually changed (e.g. become readable where it wasn't
  203. before), but this does not have to be the case. It can retry at any time.
  204. .PP
  205. Note that it is important that you retry exactly the same operation that you
  206. tried last time. You cannot start something new. For example if you were
  207. attempting to write the text \*(L"Hello World\*(R" and the operation failed because the
  208. socket is currently unable to write, then you cannot then attempt to write
  209. some other text when you retry the operation.
  210. .PP
  211. In this demo application we will create a helper function which simulates doing
  212. other work. In fact, for the sake of simplicity, it will do nothing except wait
  213. for the state of the socket to change.
  214. .PP
  215. We call our function \f(CW\*(C`wait_for_activity()\*(C'\fR because all it does is wait until
  216. the underlying socket has become readable or writeable when it wasn't before.
  217. .PP
  218. .Vb 4
  219. \& static void wait_for_activity(SSL *ssl, int write)
  220. \& {
  221. \& fd_set fds;
  222. \& int width, sock;
  223. \&
  224. \& /* Get hold of the underlying file descriptor for the socket */
  225. \& sock = SSL_get_fd(ssl);
  226. \&
  227. \& FD_ZERO(&fds);
  228. \& FD_SET(sock, &fds);
  229. \& width = sock + 1;
  230. \&
  231. \& /*
  232. \& * Wait until the socket is writeable or readable. We use select here
  233. \& * for the sake of simplicity and portability, but you could equally use
  234. \& * poll/epoll or similar functions
  235. \& *
  236. \& * NOTE: For the purposes of this demonstration code this effectively
  237. \& * makes this demo block until it has something more useful to do. In a
  238. \& * real application you probably want to go and do other work here (e.g.
  239. \& * update a GUI, or service other connections).
  240. \& *
  241. \& * Let\*(Aqs say for example that you want to update the progress counter on
  242. \& * a GUI every 100ms. One way to do that would be to add a 100ms timeout
  243. \& * in the last parameter to "select" below. Then, when select returns,
  244. \& * you check if it did so because of activity on the file descriptors or
  245. \& * because of the timeout. If it is due to the timeout then update the
  246. \& * GUI and then restart the "select".
  247. \& */
  248. \& if (write)
  249. \& select(width, NULL, &fds, NULL, NULL);
  250. \& else
  251. \& select(width, &fds, NULL, NULL, NULL);
  252. \& }
  253. .Ve
  254. .PP
  255. In this example we are using the \f(CW\*(C`select\*(C'\fR function because it is very simple
  256. to use and is available on most Operating Systems. However you could use any
  257. other similar function to do the same thing. \f(CW\*(C`select\*(C'\fR waits for the state of
  258. the underlying socket(s) to become readable/writeable before returning. It also
  259. supports a \*(L"timeout\*(R" (as do most other similar functions) so in your own
  260. applications you can make use of this to periodically wake up and perform work
  261. while waiting for the socket state to change. But we don't use that timeout
  262. capability in this example for the sake of simplicity.
  263. .SS "Handling errors from OpenSSL I/O functions"
  264. .IX Subsection "Handling errors from OpenSSL I/O functions"
  265. An application that uses a nonblocking socket will need to be prepared to
  266. handle errors returned from OpenSSL I/O functions such as \fBSSL_read_ex\fR\|(3) or
  267. \&\fBSSL_write_ex\fR\|(3). Errors may be fatal (for example because the underlying
  268. connection has failed), or non-fatal (for example because we are trying to read
  269. from the underlying socket but the data has not yet arrived from the peer).
  270. .PP
  271. \&\fBSSL_read_ex\fR\|(3) and \fBSSL_write_ex\fR\|(3) will return 0 to indicate an error and
  272. \&\fBSSL_read\fR\|(3) and \fBSSL_write\fR\|(3) will return 0 or a negative value to indicate
  273. an error. \fBSSL_shutdown\fR\|(3) will return a negative value to incidate an error.
  274. .PP
  275. In the event of an error an application should call \fBSSL_get_error\fR\|(3) to find
  276. out what type of error has occurred. If the error is non-fatal and can be
  277. retried then \fBSSL_get_error\fR\|(3) will return \fB\s-1SSL_ERROR_WANT_READ\s0\fR or
  278. \&\fB\s-1SSL_ERROR_WANT_WRITE\s0\fR depending on whether OpenSSL wanted to read to or write
  279. from the socket but was unable to. Note that a call to \fBSSL_read_ex\fR\|(3) or
  280. \&\fBSSL_read\fR\|(3) can still generate \fB\s-1SSL_ERROR_WANT_WRITE\s0\fR because OpenSSL
  281. may need to write protocol messages (such as to update cryptographic keys) even
  282. if the application is only trying to read data. Similarly calls to
  283. \&\fBSSL_write_ex\fR\|(3) or \fBSSL_write\fR\|(3) might generate \fB\s-1SSL_ERROR_WANT_READ\s0\fR.
  284. .PP
  285. Another type of non-fatal error that may occur is \fB\s-1SSL_ERROR_ZERO_RETURN\s0\fR. This
  286. indicates an \s-1EOF\s0 (End-Of-File) which can occur if you attempt to read data from
  287. an \fB\s-1SSL\s0\fR object but the peer has indicated that it will not send any more data
  288. on it. In this case you may still want to write data to the connection but you
  289. will not receive any more data.
  290. .PP
  291. Fatal errors that may occur are \fB\s-1SSL_ERROR_SYSCALL\s0\fR and \fB\s-1SSL_ERROR_SSL\s0\fR. These
  292. indicate that the underlying connection has failed. You should not attempt to
  293. shut it down with \fBSSL_shutdown\fR\|(3). \fB\s-1SSL_ERROR_SYSCALL\s0\fR indicates that
  294. OpenSSL attempted to make a syscall that failed. You can consult \fBerrno\fR for
  295. further details. \fB\s-1SSL_ERROR_SSL\s0\fR indicates that some OpenSSL error occurred. You
  296. can consult the OpenSSL error stack for further details (for example by calling
  297. \&\fBERR_print_errors\fR\|(3) to print out details of errors that have occurred).
  298. .PP
  299. In our demo application we will write a function to handle these errors from
  300. OpenSSL I/O functions:
  301. .PP
  302. .Vb 7
  303. \& static int handle_io_failure(SSL *ssl, int res)
  304. \& {
  305. \& switch (SSL_get_error(ssl, res)) {
  306. \& case SSL_ERROR_WANT_READ:
  307. \& /* Temporary failure. Wait until we can read and try again */
  308. \& wait_for_activity(ssl, 0);
  309. \& return 1;
  310. \&
  311. \& case SSL_ERROR_WANT_WRITE:
  312. \& /* Temporary failure. Wait until we can write and try again */
  313. \& wait_for_activity(ssl, 1);
  314. \& return 1;
  315. \&
  316. \& case SSL_ERROR_ZERO_RETURN:
  317. \& /* EOF */
  318. \& return 0;
  319. \&
  320. \& case SSL_ERROR_SYSCALL:
  321. \& return \-1;
  322. \&
  323. \& case SSL_ERROR_SSL:
  324. \& /*
  325. \& * If the failure is due to a verification error we can get more
  326. \& * information about it from SSL_get_verify_result().
  327. \& */
  328. \& if (SSL_get_verify_result(ssl) != X509_V_OK)
  329. \& printf("Verify error: %s\en",
  330. \& X509_verify_cert_error_string(SSL_get_verify_result(ssl)));
  331. \& return \-1;
  332. \&
  333. \& default:
  334. \& return \-1;
  335. \& }
  336. \& }
  337. .Ve
  338. .PP
  339. This function takes as arguments the \fB\s-1SSL\s0\fR object that represents the
  340. connection, as well as the return code from the I/O function that failed. In
  341. the event of a non-fatal failure, it waits until a retry of the I/O operation
  342. might succeed (by using the \f(CW\*(C`wait_for_activity()\*(C'\fR function that we developed
  343. in the previous section). It returns 1 in the event of a non-fatal error
  344. (except \s-1EOF\s0), 0 in the event of \s-1EOF,\s0 or \-1 if a fatal error occurred.
  345. .SS "Creating the \s-1SSL_CTX\s0 and \s-1SSL\s0 objects"
  346. .IX Subsection "Creating the SSL_CTX and SSL objects"
  347. In order to connect to a server we must create \fB\s-1SSL_CTX\s0\fR and \fB\s-1SSL\s0\fR objects for
  348. this. The steps do this are the same as for a blocking client and are explained
  349. on the \fBossl\-guide\-tls\-client\-block\fR\|(7) page. We won't repeat that information
  350. here.
  351. .SS "Performing the handshake"
  352. .IX Subsection "Performing the handshake"
  353. As in the demo for a blocking \s-1TLS\s0 client we use the \fBSSL_connect\fR\|(3) function
  354. to perform the \s-1TLS\s0 handshake with the server. Since we are using a nonblocking
  355. socket it is very likely that calls to this function will fail with a non-fatal
  356. error while we are waiting for the server to respond to our handshake messages.
  357. In such a case we must retry the same \fBSSL_connect\fR\|(3) call at a later time.
  358. In this demo we this in a loop:
  359. .PP
  360. .Vb 7
  361. \& /* Do the handshake with the server */
  362. \& while ((ret = SSL_connect(ssl)) != 1) {
  363. \& if (handle_io_failure(ssl, ret) == 1)
  364. \& continue; /* Retry */
  365. \& printf("Failed to connect to server\en");
  366. \& goto end; /* Cannot retry: error */
  367. \& }
  368. .Ve
  369. .PP
  370. We continually call \fBSSL_connect\fR\|(3) until it gives us a success response.
  371. Otherwise we use the \f(CW\*(C`handle_io_failure()\*(C'\fR function that we created earlier to
  372. work out what we should do next. Note that we do not expect an \s-1EOF\s0 to occur at
  373. this stage, so such a response is treated in the same way as a fatal error.
  374. .SS "Sending and receiving data"
  375. .IX Subsection "Sending and receiving data"
  376. As with the blocking \s-1TLS\s0 client demo we use the \fBSSL_write_ex\fR\|(3) function to
  377. send data to the server. As with \fBSSL_connect\fR\|(3) above, because we are using
  378. a nonblocking socket, this call could fail with a non-fatal error. In that case
  379. we should retry exactly the same \fBSSL_write_ex\fR\|(3) call again. Note that the
  380. parameters must be \fIexactly\fR the same, i.e. the same pointer to the buffer to
  381. write with the same length. You must not attempt to send different data on a
  382. retry. An optional mode does exist (\fB\s-1SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER\s0\fR)
  383. which will configure OpenSSL to allow the buffer being written to change from
  384. one retry to the next. However, in this case, you must still retry exactly the
  385. same data \- even though the buffer that contains that data may change location.
  386. See \fBSSL_CTX_set_mode\fR\|(3) for further details. As in the \s-1TLS\s0 client
  387. blocking tutorial (\fBossl\-guide\-tls\-client\-block\fR\|(7)) we write the request
  388. in three chunks.
  389. .PP
  390. .Vb 10
  391. \& /* Write an HTTP GET request to the peer */
  392. \& while (!SSL_write_ex(ssl, request_start, strlen(request_start), &written)) {
  393. \& if (handle_io_failure(ssl, 0) == 1)
  394. \& continue; /* Retry */
  395. \& printf("Failed to write start of HTTP request\en");
  396. \& goto end; /* Cannot retry: error */
  397. \& }
  398. \& while (!SSL_write_ex(ssl, hostname, strlen(hostname), &written)) {
  399. \& if (handle_io_failure(ssl, 0) == 1)
  400. \& continue; /* Retry */
  401. \& printf("Failed to write hostname in HTTP request\en");
  402. \& goto end; /* Cannot retry: error */
  403. \& }
  404. \& while (!SSL_write_ex(ssl, request_end, strlen(request_end), &written)) {
  405. \& if (handle_io_failure(ssl, 0) == 1)
  406. \& continue; /* Retry */
  407. \& printf("Failed to write end of HTTP request\en");
  408. \& goto end; /* Cannot retry: error */
  409. \& }
  410. .Ve
  411. .PP
  412. On a write we do not expect to see an \s-1EOF\s0 response so we treat that case in the
  413. same way as a fatal error.
  414. .PP
  415. Reading a response back from the server is similar:
  416. .PP
  417. .Vb 10
  418. \& do {
  419. \& /*
  420. \& * Get up to sizeof(buf) bytes of the response. We keep reading until
  421. \& * the server closes the connection.
  422. \& */
  423. \& while (!eof && !SSL_read_ex(ssl, buf, sizeof(buf), &readbytes)) {
  424. \& switch (handle_io_failure(ssl, 0)) {
  425. \& case 1:
  426. \& continue; /* Retry */
  427. \& case 0:
  428. \& eof = 1;
  429. \& continue;
  430. \& case \-1:
  431. \& default:
  432. \& printf("Failed reading remaining data\en");
  433. \& goto end; /* Cannot retry: error */
  434. \& }
  435. \& }
  436. \& /*
  437. \& * OpenSSL does not guarantee that the returned data is a string or
  438. \& * that it is NUL terminated so we use fwrite() to write the exact
  439. \& * number of bytes that we read. The data could be non\-printable or
  440. \& * have NUL characters in the middle of it. For this simple example
  441. \& * we\*(Aqre going to print it to stdout anyway.
  442. \& */
  443. \& if (!eof)
  444. \& fwrite(buf, 1, readbytes, stdout);
  445. \& } while (!eof);
  446. \& /* In case the response didn\*(Aqt finish with a newline we add one now */
  447. \& printf("\en");
  448. .Ve
  449. .PP
  450. The main difference this time is that it is valid for us to receive an \s-1EOF\s0
  451. response when trying to read data from the server. This will occur when the
  452. server closes down the connection after sending all the data in its response.
  453. .PP
  454. In this demo we just print out all the data we've received back in the response
  455. from the server. We continue going around the loop until we either encounter a
  456. fatal error, or we receive an \s-1EOF\s0 (indicating a graceful finish).
  457. .SS "Shutting down the connection"
  458. .IX Subsection "Shutting down the connection"
  459. As in the \s-1TLS\s0 blocking example we must shutdown the connection when we are
  460. finished with it.
  461. .PP
  462. If our application was initiating the shutdown then we would expect to see
  463. \&\fBSSL_shutdown\fR\|(3) give a return value of 0, and then we would continue to call
  464. it until we received a return value of 1 (meaning we have successfully completed
  465. the shutdown). In this particular example we don't expect \fBSSL_shutdown()\fR to
  466. return 0 because we have already received \s-1EOF\s0 from the server indicating that it
  467. has shutdown already. So we just keep calling it until \fBSSL_shutdown()\fR returns 1.
  468. Since we are using a nonblocking socket we might expect to have to retry this
  469. operation several times. If \fBSSL_shutdown\fR\|(3) returns a negative result then we
  470. must call \fBSSL_get_error\fR\|(3) to work out what to do next. We use our
  471. \&\fBhandle_io_failure()\fR function that we developed earlier for this:
  472. .PP
  473. .Vb 10
  474. \& /*
  475. \& * The peer already shutdown gracefully (we know this because of the
  476. \& * SSL_ERROR_ZERO_RETURN (i.e. EOF) above). We should do the same back.
  477. \& */
  478. \& while ((ret = SSL_shutdown(ssl)) != 1) {
  479. \& if (ret < 0 && handle_io_failure(ssl, ret) == 1)
  480. \& continue; /* Retry */
  481. \& /*
  482. \& * ret == 0 is unexpected here because that means "we\*(Aqve sent a
  483. \& * close_notify and we\*(Aqre waiting for one back". But we already know
  484. \& * we got one from the peer because of the SSL_ERROR_ZERO_RETURN
  485. \& * (i.e. EOF) above.
  486. \& */
  487. \& printf("Error shutting down\en");
  488. \& goto end; /* Cannot retry: error */
  489. \& }
  490. .Ve
  491. .SS "Final clean up"
  492. .IX Subsection "Final clean up"
  493. As with the blocking \s-1TLS\s0 client example, once our connection is finished with we
  494. must free it. The steps to do this for this example are the same as for the
  495. blocking example, so we won't repeat it here.
  496. .SH "FURTHER READING"
  497. .IX Header "FURTHER READING"
  498. See \fBossl\-guide\-tls\-client\-block\fR\|(7) to read a tutorial on how to write a
  499. blocking \s-1TLS\s0 client. See \fBossl\-guide\-quic\-client\-block\fR\|(7) to see how to do the
  500. same thing for a \s-1QUIC\s0 client.
  501. .SH "SEE ALSO"
  502. .IX Header "SEE ALSO"
  503. \&\fBossl\-guide\-introduction\fR\|(7), \fBossl\-guide\-libraries\-introduction\fR\|(7),
  504. \&\fBossl\-guide\-libssl\-introduction\fR\|(7), \fBossl\-guide\-tls\-introduction\fR\|(7),
  505. \&\fBossl\-guide\-tls\-client\-block\fR\|(7), \fBossl\-guide\-quic\-client\-block\fR\|(7)
  506. .SH "COPYRIGHT"
  507. .IX Header "COPYRIGHT"
  508. Copyright 2023 The OpenSSL Project Authors. All Rights Reserved.
  509. .PP
  510. Licensed under the Apache License 2.0 (the \*(L"License\*(R"). You may not use
  511. this file except in compliance with the License. You can obtain a copy
  512. in the file \s-1LICENSE\s0 in the source distribution or at
  513. <https://www.openssl.org/source/license.html>.