quic-multi-stream.c 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416
  1. /*
  2. * Copyright 2023 The OpenSSL Project Authors. All Rights Reserved.
  3. *
  4. * Licensed under the Apache License 2.0 (the "License"). You may not use
  5. * this file except in compliance with the License. You can obtain a copy
  6. * in the file LICENSE in the source distribution or at
  7. * https://www.openssl.org/source/license.html
  8. */
  9. /*
  10. * NB: Changes to this file should also be reflected in
  11. * doc/man7/ossl-guide-quic-multi-stream.pod
  12. */
  13. #include <string.h>
  14. /* Include the appropriate header file for SOCK_DGRAM */
  15. #ifdef _WIN32 /* Windows */
  16. # include <winsock2.h>
  17. #else /* Linux/Unix */
  18. # include <sys/socket.h>
  19. #endif
  20. #include <openssl/bio.h>
  21. #include <openssl/ssl.h>
  22. #include <openssl/err.h>
  23. /* Helper function to create a BIO connected to the server */
  24. static BIO *create_socket_bio(const char *hostname, const char *port,
  25. BIO_ADDR **peer_addr)
  26. {
  27. int sock = -1;
  28. BIO_ADDRINFO *res;
  29. const BIO_ADDRINFO *ai = NULL;
  30. BIO *bio;
  31. /*
  32. * Lookup IP address info for the server.
  33. */
  34. if (!BIO_lookup_ex(hostname, port, BIO_LOOKUP_CLIENT, 0, SOCK_DGRAM, 0,
  35. &res))
  36. return NULL;
  37. /*
  38. * Loop through all the possible addresses for the server and find one
  39. * we can connect to.
  40. */
  41. for (ai = res; ai != NULL; ai = BIO_ADDRINFO_next(ai)) {
  42. /*
  43. * Create a UDP socket. We could equally use non-OpenSSL calls such
  44. * as "socket" here for this and the subsequent connect and close
  45. * functions. But for portability reasons and also so that we get
  46. * errors on the OpenSSL stack in the event of a failure we use
  47. * OpenSSL's versions of these functions.
  48. */
  49. sock = BIO_socket(BIO_ADDRINFO_family(ai), SOCK_DGRAM, 0, 0);
  50. if (sock == -1)
  51. continue;
  52. /* Connect the socket to the server's address */
  53. if (!BIO_connect(sock, BIO_ADDRINFO_address(ai), 0)) {
  54. BIO_closesocket(sock);
  55. sock = -1;
  56. continue;
  57. }
  58. /* Set to nonblocking mode */
  59. if (!BIO_socket_nbio(sock, 1)) {
  60. BIO_closesocket(sock);
  61. sock = -1;
  62. continue;
  63. }
  64. break;
  65. }
  66. if (sock != -1) {
  67. *peer_addr = BIO_ADDR_dup(BIO_ADDRINFO_address(ai));
  68. if (*peer_addr == NULL) {
  69. BIO_closesocket(sock);
  70. return NULL;
  71. }
  72. }
  73. /* Free the address information resources we allocated earlier */
  74. BIO_ADDRINFO_free(res);
  75. /* If sock is -1 then we've been unable to connect to the server */
  76. if (sock == -1)
  77. return NULL;
  78. /* Create a BIO to wrap the socket */
  79. bio = BIO_new(BIO_s_datagram());
  80. if (bio == NULL) {
  81. BIO_closesocket(sock);
  82. return NULL;
  83. }
  84. /*
  85. * Associate the newly created BIO with the underlying socket. By
  86. * passing BIO_CLOSE here the socket will be automatically closed when
  87. * the BIO is freed. Alternatively you can use BIO_NOCLOSE, in which
  88. * case you must close the socket explicitly when it is no longer
  89. * needed.
  90. */
  91. BIO_set_fd(bio, sock, BIO_CLOSE);
  92. return bio;
  93. }
  94. /* Server hostname and port details. Must be in quotes */
  95. #ifndef HOSTNAME
  96. # define HOSTNAME "www.example.com"
  97. #endif
  98. #ifndef PORT
  99. # define PORT "443"
  100. #endif
  101. /*
  102. * Simple application to send basic HTTP/1.0 requests to a server and print the
  103. * response on the screen. Note that HTTP/1.0 over QUIC is not a real protocol
  104. * and will not be supported by real world servers. This is for demonstration
  105. * purposes only.
  106. */
  107. int main(void)
  108. {
  109. SSL_CTX *ctx = NULL;
  110. SSL *ssl = NULL;
  111. SSL *stream1 = NULL, *stream2 = NULL, *stream3 = NULL;
  112. BIO *bio = NULL;
  113. int res = EXIT_FAILURE;
  114. int ret;
  115. unsigned char alpn[] = { 8, 'h', 't', 't', 'p', '/', '1', '.', '0' };
  116. const char *request1 =
  117. "GET /request1.html HTTP/1.0\r\nConnection: close\r\nHost: "HOSTNAME"\r\n\r\n";
  118. const char *request2 =
  119. "GET /request2.html HTTP/1.0\r\nConnection: close\r\nHost: "HOSTNAME"\r\n\r\n";
  120. size_t written, readbytes;
  121. char buf[160];
  122. BIO_ADDR *peer_addr = NULL;
  123. /*
  124. * Create an SSL_CTX which we can use to create SSL objects from. We
  125. * want an SSL_CTX for creating clients so we use
  126. * OSSL_QUIC_client_method() here.
  127. */
  128. ctx = SSL_CTX_new(OSSL_QUIC_client_method());
  129. if (ctx == NULL) {
  130. printf("Failed to create the SSL_CTX\n");
  131. goto end;
  132. }
  133. /*
  134. * Configure the client to abort the handshake if certificate
  135. * verification fails. Virtually all clients should do this unless you
  136. * really know what you are doing.
  137. */
  138. SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, NULL);
  139. /* Use the default trusted certificate store */
  140. if (!SSL_CTX_set_default_verify_paths(ctx)) {
  141. printf("Failed to set the default trusted certificate store\n");
  142. goto end;
  143. }
  144. /* Create an SSL object to represent the TLS connection */
  145. ssl = SSL_new(ctx);
  146. if (ssl == NULL) {
  147. printf("Failed to create the SSL object\n");
  148. goto end;
  149. }
  150. /*
  151. * We will use multiple streams so we will disable the default stream mode.
  152. * This is not a requirement for using multiple streams but is recommended.
  153. */
  154. if (!SSL_set_default_stream_mode(ssl, SSL_DEFAULT_STREAM_MODE_NONE)) {
  155. printf("Failed to disable the default stream mode\n");
  156. goto end;
  157. }
  158. /*
  159. * Create the underlying transport socket/BIO and associate it with the
  160. * connection.
  161. */
  162. bio = create_socket_bio(HOSTNAME, PORT, &peer_addr);
  163. if (bio == NULL) {
  164. printf("Failed to crete the BIO\n");
  165. goto end;
  166. }
  167. SSL_set_bio(ssl, bio, bio);
  168. /*
  169. * Tell the server during the handshake which hostname we are attempting
  170. * to connect to in case the server supports multiple hosts.
  171. */
  172. if (!SSL_set_tlsext_host_name(ssl, HOSTNAME)) {
  173. printf("Failed to set the SNI hostname\n");
  174. goto end;
  175. }
  176. /*
  177. * Ensure we check during certificate verification that the server has
  178. * supplied a certificate for the hostname that we were expecting.
  179. * Virtually all clients should do this unless you really know what you
  180. * are doing.
  181. */
  182. if (!SSL_set1_host(ssl, HOSTNAME)) {
  183. printf("Failed to set the certificate verification hostname");
  184. goto end;
  185. }
  186. /* SSL_set_alpn_protos returns 0 for success! */
  187. if (SSL_set_alpn_protos(ssl, alpn, sizeof(alpn)) != 0) {
  188. printf("Failed to set the ALPN for the connection\n");
  189. goto end;
  190. }
  191. /* Set the IP address of the remote peer */
  192. if (!SSL_set1_initial_peer_addr(ssl, peer_addr)) {
  193. printf("Failed to set the initial peer address\n");
  194. goto end;
  195. }
  196. /* Do the handshake with the server */
  197. if (SSL_connect(ssl) < 1) {
  198. printf("Failed to connect to the server\n");
  199. /*
  200. * If the failure is due to a verification error we can get more
  201. * information about it from SSL_get_verify_result().
  202. */
  203. if (SSL_get_verify_result(ssl) != X509_V_OK)
  204. printf("Verify error: %s\n",
  205. X509_verify_cert_error_string(SSL_get_verify_result(ssl)));
  206. goto end;
  207. }
  208. /*
  209. * We create two new client initiated streams. The first will be
  210. * bi-directional, and the second will be uni-directional.
  211. */
  212. stream1 = SSL_new_stream(ssl, 0);
  213. stream2 = SSL_new_stream(ssl, SSL_STREAM_FLAG_UNI);
  214. if (stream1 == NULL || stream2 == NULL) {
  215. printf("Failed to create streams\n");
  216. goto end;
  217. }
  218. /* Write an HTTP GET request on each of our streams to the peer */
  219. if (!SSL_write_ex(stream1, request1, strlen(request1), &written)) {
  220. printf("Failed to write HTTP request on stream 1\n");
  221. goto end;
  222. }
  223. if (!SSL_write_ex(stream2, request2, strlen(request2), &written)) {
  224. printf("Failed to write HTTP request on stream 2\n");
  225. goto end;
  226. }
  227. /*
  228. * In this demo we read all the data from one stream before reading all the
  229. * data from the next stream for simplicity. In practice there is no need to
  230. * do this. We can interleave IO on the different streams if we wish, or
  231. * manage the streams entirely separately on different threads.
  232. */
  233. printf("Stream 1 data:\n");
  234. /*
  235. * Get up to sizeof(buf) bytes of the response from stream 1 (which is a
  236. * bidirectional stream). We keep reading until the server closes the
  237. * connection.
  238. */
  239. while (SSL_read_ex(stream1, buf, sizeof(buf), &readbytes)) {
  240. /*
  241. * OpenSSL does not guarantee that the returned data is a string or
  242. * that it is NUL terminated so we use fwrite() to write the exact
  243. * number of bytes that we read. The data could be non-printable or
  244. * have NUL characters in the middle of it. For this simple example
  245. * we're going to print it to stdout anyway.
  246. */
  247. fwrite(buf, 1, readbytes, stdout);
  248. }
  249. /* In case the response didn't finish with a newline we add one now */
  250. printf("\n");
  251. /*
  252. * Check whether we finished the while loop above normally or as the
  253. * result of an error. The 0 argument to SSL_get_error() is the return
  254. * code we received from the SSL_read_ex() call. It must be 0 in order
  255. * to get here. Normal completion is indicated by SSL_ERROR_ZERO_RETURN. In
  256. * QUIC terms this means that the peer has sent FIN on the stream to
  257. * indicate that no further data will be sent.
  258. */
  259. switch (SSL_get_error(stream1, 0)) {
  260. case SSL_ERROR_ZERO_RETURN:
  261. /* Normal completion of the stream */
  262. break;
  263. case SSL_ERROR_SSL:
  264. /*
  265. * Some stream fatal error occurred. This could be because of a stream
  266. * reset - or some failure occurred on the underlying connection.
  267. */
  268. switch (SSL_get_stream_read_state(stream1)) {
  269. case SSL_STREAM_STATE_RESET_REMOTE:
  270. printf("Stream reset occurred\n");
  271. /* The stream has been reset but the connection is still healthy. */
  272. break;
  273. case SSL_STREAM_STATE_CONN_CLOSED:
  274. printf("Connection closed\n");
  275. /* Connection is already closed. Skip SSL_shutdown() */
  276. goto end;
  277. default:
  278. printf("Unknown stream failure\n");
  279. break;
  280. }
  281. break;
  282. default:
  283. /* Some other unexpected error occurred */
  284. printf ("Failed reading remaining data\n");
  285. break;
  286. }
  287. /*
  288. * In our hypothetical HTTP/1.0 over QUIC protocol that we are using we
  289. * assume that the server will respond with a server initiated stream
  290. * containing the data requested in our uni-directional stream. This doesn't
  291. * really make sense to do in a real protocol, but its just for
  292. * demonstration purposes.
  293. *
  294. * We're using blocking mode so this will block until a stream becomes
  295. * available. We could override this behaviour if we wanted to by setting
  296. * the SSL_ACCEPT_STREAM_NO_BLOCK flag in the second argument below.
  297. */
  298. stream3 = SSL_accept_stream(ssl, 0);
  299. if (stream3 == NULL) {
  300. printf("Failed to accept a new stream\n");
  301. goto end;
  302. }
  303. printf("Stream 3 data:\n");
  304. /*
  305. * Read the data from stream 3 like we did for stream 1 above. Note that
  306. * stream 2 was uni-directional so there is no data to be read from that
  307. * one.
  308. */
  309. while (SSL_read_ex(stream3, buf, sizeof(buf), &readbytes))
  310. fwrite(buf, 1, readbytes, stdout);
  311. printf("\n");
  312. /* Check for errors on the stream */
  313. switch (SSL_get_error(stream3, 0)) {
  314. case SSL_ERROR_ZERO_RETURN:
  315. /* Normal completion of the stream */
  316. break;
  317. case SSL_ERROR_SSL:
  318. switch (SSL_get_stream_read_state(stream3)) {
  319. case SSL_STREAM_STATE_RESET_REMOTE:
  320. printf("Stream reset occurred\n");
  321. break;
  322. case SSL_STREAM_STATE_CONN_CLOSED:
  323. printf("Connection closed\n");
  324. goto end;
  325. default:
  326. printf("Unknown stream failure\n");
  327. break;
  328. }
  329. break;
  330. default:
  331. printf ("Failed reading remaining data\n");
  332. break;
  333. }
  334. /*
  335. * Repeatedly call SSL_shutdown() until the connection is fully
  336. * closed.
  337. */
  338. do {
  339. ret = SSL_shutdown(ssl);
  340. if (ret < 0) {
  341. printf("Error shutting down: %d\n", ret);
  342. goto end;
  343. }
  344. } while (ret != 1);
  345. /* Success! */
  346. res = EXIT_SUCCESS;
  347. end:
  348. /*
  349. * If something bad happened then we will dump the contents of the
  350. * OpenSSL error stack to stderr. There might be some useful diagnostic
  351. * information there.
  352. */
  353. if (res == EXIT_FAILURE)
  354. ERR_print_errors_fp(stderr);
  355. /*
  356. * Free the resources we allocated. We do not free the BIO object here
  357. * because ownership of it was immediately transferred to the SSL object
  358. * via SSL_set_bio(). The BIO will be freed when we free the SSL object.
  359. */
  360. SSL_free(ssl);
  361. SSL_free(stream1);
  362. SSL_free(stream2);
  363. SSL_free(stream3);
  364. SSL_CTX_free(ctx);
  365. BIO_ADDR_free(peer_addr);
  366. return res;
  367. }