quic-multi-stream.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444
  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. int family, 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, family, 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. int write_a_request(SSL *stream, const char *request_start,
  95. const char *hostname)
  96. {
  97. const char *request_end = "\r\n\r\n";
  98. size_t written;
  99. if (!SSL_write_ex(stream, request_start, strlen(request_start),
  100. &written))
  101. return 0;
  102. if (!SSL_write_ex(stream, hostname, strlen(hostname), &written))
  103. return 0;
  104. if (!SSL_write_ex(stream, request_end, strlen(request_end), &written))
  105. return 0;
  106. return 1;
  107. }
  108. /*
  109. * Simple application to send basic HTTP/1.0 requests to a server and print the
  110. * response on the screen. Note that HTTP/1.0 over QUIC is not a real protocol
  111. * and will not be supported by real world servers. This is for demonstration
  112. * purposes only.
  113. */
  114. int main(int argc, char *argv[])
  115. {
  116. SSL_CTX *ctx = NULL;
  117. SSL *ssl = NULL;
  118. SSL *stream1 = NULL, *stream2 = NULL, *stream3 = NULL;
  119. BIO *bio = NULL;
  120. int res = EXIT_FAILURE;
  121. int ret;
  122. unsigned char alpn[] = { 8, 'h', 't', 't', 'p', '/', '1', '.', '0' };
  123. const char *request1_start =
  124. "GET /request1.html HTTP/1.0\r\nConnection: close\r\nHost: ";
  125. const char *request2_start =
  126. "GET /request2.html HTTP/1.0\r\nConnection: close\r\nHost: ";
  127. size_t readbytes;
  128. char buf[160];
  129. BIO_ADDR *peer_addr = NULL;
  130. char *hostname, *port;
  131. int argnext = 1;
  132. int ipv6 = 0;
  133. if (argc < 3) {
  134. printf("Usage: quic-client-non-block [-6] hostname port\n");
  135. goto end;
  136. }
  137. if (!strcmp(argv[argnext], "-6")) {
  138. if (argc < 4) {
  139. printf("Usage: quic-client-non-block [-6] hostname port\n");
  140. goto end;
  141. }
  142. ipv6 = 1;
  143. argnext++;
  144. }
  145. hostname = argv[argnext++];
  146. port = argv[argnext];
  147. /*
  148. * Create an SSL_CTX which we can use to create SSL objects from. We
  149. * want an SSL_CTX for creating clients so we use
  150. * OSSL_QUIC_client_method() here.
  151. */
  152. ctx = SSL_CTX_new(OSSL_QUIC_client_method());
  153. if (ctx == NULL) {
  154. printf("Failed to create the SSL_CTX\n");
  155. goto end;
  156. }
  157. /*
  158. * Configure the client to abort the handshake if certificate
  159. * verification fails. Virtually all clients should do this unless you
  160. * really know what you are doing.
  161. */
  162. SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, NULL);
  163. /* Use the default trusted certificate store */
  164. if (!SSL_CTX_set_default_verify_paths(ctx)) {
  165. printf("Failed to set the default trusted certificate store\n");
  166. goto end;
  167. }
  168. /* Create an SSL object to represent the TLS connection */
  169. ssl = SSL_new(ctx);
  170. if (ssl == NULL) {
  171. printf("Failed to create the SSL object\n");
  172. goto end;
  173. }
  174. /*
  175. * We will use multiple streams so we will disable the default stream mode.
  176. * This is not a requirement for using multiple streams but is recommended.
  177. */
  178. if (!SSL_set_default_stream_mode(ssl, SSL_DEFAULT_STREAM_MODE_NONE)) {
  179. printf("Failed to disable the default stream mode\n");
  180. goto end;
  181. }
  182. /*
  183. * Create the underlying transport socket/BIO and associate it with the
  184. * connection.
  185. */
  186. bio = create_socket_bio(hostname, port, ipv6 ? AF_INET6 : AF_INET, &peer_addr);
  187. if (bio == NULL) {
  188. printf("Failed to crete the BIO\n");
  189. goto end;
  190. }
  191. SSL_set_bio(ssl, bio, bio);
  192. /*
  193. * Tell the server during the handshake which hostname we are attempting
  194. * to connect to in case the server supports multiple hosts.
  195. */
  196. if (!SSL_set_tlsext_host_name(ssl, hostname)) {
  197. printf("Failed to set the SNI hostname\n");
  198. goto end;
  199. }
  200. /*
  201. * Ensure we check during certificate verification that the server has
  202. * supplied a certificate for the hostname that we were expecting.
  203. * Virtually all clients should do this unless you really know what you
  204. * are doing.
  205. */
  206. if (!SSL_set1_host(ssl, hostname)) {
  207. printf("Failed to set the certificate verification hostname");
  208. goto end;
  209. }
  210. /* SSL_set_alpn_protos returns 0 for success! */
  211. if (SSL_set_alpn_protos(ssl, alpn, sizeof(alpn)) != 0) {
  212. printf("Failed to set the ALPN for the connection\n");
  213. goto end;
  214. }
  215. /* Set the IP address of the remote peer */
  216. if (!SSL_set1_initial_peer_addr(ssl, peer_addr)) {
  217. printf("Failed to set the initial peer address\n");
  218. goto end;
  219. }
  220. /* Do the handshake with the server */
  221. if (SSL_connect(ssl) < 1) {
  222. printf("Failed to connect to the server\n");
  223. /*
  224. * If the failure is due to a verification error we can get more
  225. * information about it from SSL_get_verify_result().
  226. */
  227. if (SSL_get_verify_result(ssl) != X509_V_OK)
  228. printf("Verify error: %s\n",
  229. X509_verify_cert_error_string(SSL_get_verify_result(ssl)));
  230. goto end;
  231. }
  232. /*
  233. * We create two new client initiated streams. The first will be
  234. * bi-directional, and the second will be uni-directional.
  235. */
  236. stream1 = SSL_new_stream(ssl, 0);
  237. stream2 = SSL_new_stream(ssl, SSL_STREAM_FLAG_UNI);
  238. if (stream1 == NULL || stream2 == NULL) {
  239. printf("Failed to create streams\n");
  240. goto end;
  241. }
  242. /* Write an HTTP GET request on each of our streams to the peer */
  243. if (!write_a_request(stream1, request1_start, hostname)) {
  244. printf("Failed to write HTTP request on stream 1\n");
  245. goto end;
  246. }
  247. if (!write_a_request(stream2, request2_start, hostname)) {
  248. printf("Failed to write HTTP request on stream 2\n");
  249. goto end;
  250. }
  251. /*
  252. * In this demo we read all the data from one stream before reading all the
  253. * data from the next stream for simplicity. In practice there is no need to
  254. * do this. We can interleave IO on the different streams if we wish, or
  255. * manage the streams entirely separately on different threads.
  256. */
  257. printf("Stream 1 data:\n");
  258. /*
  259. * Get up to sizeof(buf) bytes of the response from stream 1 (which is a
  260. * bidirectional stream). We keep reading until the server closes the
  261. * connection.
  262. */
  263. while (SSL_read_ex(stream1, buf, sizeof(buf), &readbytes)) {
  264. /*
  265. * OpenSSL does not guarantee that the returned data is a string or
  266. * that it is NUL terminated so we use fwrite() to write the exact
  267. * number of bytes that we read. The data could be non-printable or
  268. * have NUL characters in the middle of it. For this simple example
  269. * we're going to print it to stdout anyway.
  270. */
  271. fwrite(buf, 1, readbytes, stdout);
  272. }
  273. /* In case the response didn't finish with a newline we add one now */
  274. printf("\n");
  275. /*
  276. * Check whether we finished the while loop above normally or as the
  277. * result of an error. The 0 argument to SSL_get_error() is the return
  278. * code we received from the SSL_read_ex() call. It must be 0 in order
  279. * to get here. Normal completion is indicated by SSL_ERROR_ZERO_RETURN. In
  280. * QUIC terms this means that the peer has sent FIN on the stream to
  281. * indicate that no further data will be sent.
  282. */
  283. switch (SSL_get_error(stream1, 0)) {
  284. case SSL_ERROR_ZERO_RETURN:
  285. /* Normal completion of the stream */
  286. break;
  287. case SSL_ERROR_SSL:
  288. /*
  289. * Some stream fatal error occurred. This could be because of a stream
  290. * reset - or some failure occurred on the underlying connection.
  291. */
  292. switch (SSL_get_stream_read_state(stream1)) {
  293. case SSL_STREAM_STATE_RESET_REMOTE:
  294. printf("Stream reset occurred\n");
  295. /* The stream has been reset but the connection is still healthy. */
  296. break;
  297. case SSL_STREAM_STATE_CONN_CLOSED:
  298. printf("Connection closed\n");
  299. /* Connection is already closed. Skip SSL_shutdown() */
  300. goto end;
  301. default:
  302. printf("Unknown stream failure\n");
  303. break;
  304. }
  305. break;
  306. default:
  307. /* Some other unexpected error occurred */
  308. printf ("Failed reading remaining data\n");
  309. break;
  310. }
  311. /*
  312. * In our hypothetical HTTP/1.0 over QUIC protocol that we are using we
  313. * assume that the server will respond with a server initiated stream
  314. * containing the data requested in our uni-directional stream. This doesn't
  315. * really make sense to do in a real protocol, but its just for
  316. * demonstration purposes.
  317. *
  318. * We're using blocking mode so this will block until a stream becomes
  319. * available. We could override this behaviour if we wanted to by setting
  320. * the SSL_ACCEPT_STREAM_NO_BLOCK flag in the second argument below.
  321. */
  322. stream3 = SSL_accept_stream(ssl, 0);
  323. if (stream3 == NULL) {
  324. printf("Failed to accept a new stream\n");
  325. goto end;
  326. }
  327. printf("Stream 3 data:\n");
  328. /*
  329. * Read the data from stream 3 like we did for stream 1 above. Note that
  330. * stream 2 was uni-directional so there is no data to be read from that
  331. * one.
  332. */
  333. while (SSL_read_ex(stream3, buf, sizeof(buf), &readbytes))
  334. fwrite(buf, 1, readbytes, stdout);
  335. printf("\n");
  336. /* Check for errors on the stream */
  337. switch (SSL_get_error(stream3, 0)) {
  338. case SSL_ERROR_ZERO_RETURN:
  339. /* Normal completion of the stream */
  340. break;
  341. case SSL_ERROR_SSL:
  342. switch (SSL_get_stream_read_state(stream3)) {
  343. case SSL_STREAM_STATE_RESET_REMOTE:
  344. printf("Stream reset occurred\n");
  345. break;
  346. case SSL_STREAM_STATE_CONN_CLOSED:
  347. printf("Connection closed\n");
  348. goto end;
  349. default:
  350. printf("Unknown stream failure\n");
  351. break;
  352. }
  353. break;
  354. default:
  355. printf ("Failed reading remaining data\n");
  356. break;
  357. }
  358. /*
  359. * Repeatedly call SSL_shutdown() until the connection is fully
  360. * closed.
  361. */
  362. do {
  363. ret = SSL_shutdown(ssl);
  364. if (ret < 0) {
  365. printf("Error shutting down: %d\n", ret);
  366. goto end;
  367. }
  368. } while (ret != 1);
  369. /* Success! */
  370. res = EXIT_SUCCESS;
  371. end:
  372. /*
  373. * If something bad happened then we will dump the contents of the
  374. * OpenSSL error stack to stderr. There might be some useful diagnostic
  375. * information there.
  376. */
  377. if (res == EXIT_FAILURE)
  378. ERR_print_errors_fp(stderr);
  379. /*
  380. * Free the resources we allocated. We do not free the BIO object here
  381. * because ownership of it was immediately transferred to the SSL object
  382. * via SSL_set_bio(). The BIO will be freed when we free the SSL object.
  383. */
  384. SSL_free(ssl);
  385. SSL_free(stream1);
  386. SSL_free(stream2);
  387. SSL_free(stream3);
  388. SSL_CTX_free(ctx);
  389. BIO_ADDR_free(peer_addr);
  390. return res;
  391. }