2 * nghttp2 - HTTP/2 C Library
4 * Copyright (c) 2013 Tatsuhiro Tsujikawa
6 * Permission is hereby granted, free of charge, to any person obtaining
7 * a copy of this software and associated documentation files (the
8 * "Software"), to deal in the Software without restriction, including
9 * without limitation the rights to use, copy, modify, merge, publish,
10 * distribute, sublicense, and/or sell copies of the Software, and to
11 * permit persons to whom the Software is furnished to do so, subject to
12 * the following conditions:
14 * The above copyright notice and this permission notice shall be
15 * included in all copies or substantial portions of the Software.
17 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
18 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
19 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
20 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
21 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
22 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
23 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
26 * This program is written to show how to use nghttp2 API in C and
27 * intentionally made simple.
31 #endif /* HAVE_CONFIG_H */
37 #endif /* HAVE_UNISTD_H */
40 #endif /* HAVE_FCNTL_H */
41 #include <sys/types.h>
42 #ifdef HAVE_SYS_SOCKET_H
43 # include <sys/socket.h>
44 #endif /* HAVE_SYS_SOCKET_H */
47 #endif /* HAVE_NETDB_H */
48 #ifdef HAVE_NETINET_IN_H
49 # include <netinet/in.h>
50 #endif /* HAVE_NETINET_IN_H */
51 #include <netinet/tcp.h>
59 #include <nghttp2/nghttp2.h>
61 #include <openssl/ssl.h>
62 #include <openssl/err.h>
63 #include <openssl/conf.h>
65 enum { IO_NONE, WANT_READ, WANT_WRITE };
67 #define MAKE_NV(NAME, VALUE) \
69 (uint8_t *)NAME, (uint8_t *)VALUE, sizeof(NAME) - 1, sizeof(VALUE) - 1, \
70 NGHTTP2_NV_FLAG_NONE \
73 #define MAKE_NV_CS(NAME, VALUE) \
75 (uint8_t *)NAME, (uint8_t *)VALUE, sizeof(NAME) - 1, strlen(VALUE), \
76 NGHTTP2_NV_FLAG_NONE \
81 nghttp2_session *session;
82 /* WANT_READ if SSL/TLS connection needs more input; or WANT_WRITE
83 if it needs more output; or IO_NONE. This is necessary because
84 SSL/TLS re-negotiation is possible at any time. nghttp2 API
85 offers similar functions like nghttp2_session_want_read() and
86 nghttp2_session_want_write() but they do not take into account
87 SSL/TSL connection. */
93 /* In this program, path contains query component as well. */
95 /* This is the concatenation of host and port with ":" in
98 /* Stream ID for this request. */
105 /* In this program, path contains query component as well. */
108 const char *hostport;
115 * Returns copy of string |s| with the length |len|. The returned
116 * string is NULL-terminated.
118 static char *strcopy(const char *s, size_t len) {
120 dst = malloc(len + 1);
127 * Prints error message |msg| and exit.
130 static void die(const char *msg) {
131 fprintf(stderr, "FATAL: %s\n", msg);
136 * Prints error containing the function name |func| and message |msg|
140 static void dief(const char *func, const char *msg) {
141 fprintf(stderr, "FATAL: %s: %s\n", func, msg);
146 * Prints error containing the function name |func| and error code
147 * |error_code| and exit.
150 static void diec(const char *func, int error_code) {
151 fprintf(stderr, "FATAL: %s: error_code=%d, msg=%s\n", func, error_code,
152 nghttp2_strerror(error_code));
157 * The implementation of nghttp2_send_callback type. Here we write
158 * |data| with size |length| to the network and return the number of
159 * bytes actually written. See the documentation of
160 * nghttp2_send_callback for the details.
162 static ssize_t send_callback(nghttp2_session *session, const uint8_t *data,
163 size_t length, int flags, void *user_data) {
164 struct Connection *connection;
169 connection = (struct Connection *)user_data;
170 connection->want_io = IO_NONE;
172 rv = SSL_write(connection->ssl, data, (int)length);
174 int err = SSL_get_error(connection->ssl, rv);
175 if (err == SSL_ERROR_WANT_WRITE || err == SSL_ERROR_WANT_READ) {
176 connection->want_io =
177 (err == SSL_ERROR_WANT_READ ? WANT_READ : WANT_WRITE);
178 rv = NGHTTP2_ERR_WOULDBLOCK;
180 rv = NGHTTP2_ERR_CALLBACK_FAILURE;
187 * The implementation of nghttp2_recv_callback type. Here we read data
188 * from the network and write them in |buf|. The capacity of |buf| is
189 * |length| bytes. Returns the number of bytes stored in |buf|. See
190 * the documentation of nghttp2_recv_callback for the details.
192 static ssize_t recv_callback(nghttp2_session *session, uint8_t *buf,
193 size_t length, int flags, void *user_data) {
194 struct Connection *connection;
199 connection = (struct Connection *)user_data;
200 connection->want_io = IO_NONE;
202 rv = SSL_read(connection->ssl, buf, (int)length);
204 int err = SSL_get_error(connection->ssl, rv);
205 if (err == SSL_ERROR_WANT_WRITE || err == SSL_ERROR_WANT_READ) {
206 connection->want_io =
207 (err == SSL_ERROR_WANT_READ ? WANT_READ : WANT_WRITE);
208 rv = NGHTTP2_ERR_WOULDBLOCK;
210 rv = NGHTTP2_ERR_CALLBACK_FAILURE;
212 } else if (rv == 0) {
213 rv = NGHTTP2_ERR_EOF;
218 static int on_frame_send_callback(nghttp2_session *session,
219 const nghttp2_frame *frame, void *user_data) {
223 switch (frame->hd.type) {
224 case NGHTTP2_HEADERS:
225 if (nghttp2_session_get_stream_user_data(session, frame->hd.stream_id)) {
226 const nghttp2_nv *nva = frame->headers.nva;
227 printf("[INFO] C ----------------------------> S (HEADERS)\n");
228 for (i = 0; i < frame->headers.nvlen; ++i) {
229 fwrite(nva[i].name, 1, nva[i].namelen, stdout);
231 fwrite(nva[i].value, 1, nva[i].valuelen, stdout);
236 case NGHTTP2_RST_STREAM:
237 printf("[INFO] C ----------------------------> S (RST_STREAM)\n");
240 printf("[INFO] C ----------------------------> S (GOAWAY)\n");
246 static int on_frame_recv_callback(nghttp2_session *session,
247 const nghttp2_frame *frame, void *user_data) {
251 switch (frame->hd.type) {
252 case NGHTTP2_HEADERS:
253 if (frame->headers.cat == NGHTTP2_HCAT_RESPONSE) {
254 const nghttp2_nv *nva = frame->headers.nva;
256 req = nghttp2_session_get_stream_user_data(session, frame->hd.stream_id);
258 printf("[INFO] C <---------------------------- S (HEADERS)\n");
259 for (i = 0; i < frame->headers.nvlen; ++i) {
260 fwrite(nva[i].name, 1, nva[i].namelen, stdout);
262 fwrite(nva[i].value, 1, nva[i].valuelen, stdout);
268 case NGHTTP2_RST_STREAM:
269 printf("[INFO] C <---------------------------- S (RST_STREAM)\n");
272 printf("[INFO] C <---------------------------- S (GOAWAY)\n");
279 * The implementation of nghttp2_on_stream_close_callback type. We use
280 * this function to know the response is fully received. Since we just
281 * fetch 1 resource in this program, after reception of the response,
282 * we submit GOAWAY and close the session.
284 static int on_stream_close_callback(nghttp2_session *session, int32_t stream_id,
285 uint32_t error_code, void *user_data) {
290 req = nghttp2_session_get_stream_user_data(session, stream_id);
293 rv = nghttp2_session_terminate_session(session, NGHTTP2_NO_ERROR);
296 diec("nghttp2_session_terminate_session", rv);
303 * The implementation of nghttp2_on_data_chunk_recv_callback type. We
304 * use this function to print the received response body.
306 static int on_data_chunk_recv_callback(nghttp2_session *session, uint8_t flags,
307 int32_t stream_id, const uint8_t *data,
308 size_t len, void *user_data) {
313 req = nghttp2_session_get_stream_user_data(session, stream_id);
315 printf("[INFO] C <---------------------------- S (DATA chunk)\n"
317 (unsigned long int)len);
318 fwrite(data, 1, len, stdout);
325 * Setup callback functions. nghttp2 API offers many callback
326 * functions, but most of them are optional. The send_callback is
327 * always required. Since we use nghttp2_session_recv(), the
328 * recv_callback is also required.
330 static void setup_nghttp2_callbacks(nghttp2_session_callbacks *callbacks) {
331 nghttp2_session_callbacks_set_send_callback(callbacks, send_callback);
333 nghttp2_session_callbacks_set_recv_callback(callbacks, recv_callback);
335 nghttp2_session_callbacks_set_on_frame_send_callback(callbacks,
336 on_frame_send_callback);
338 nghttp2_session_callbacks_set_on_frame_recv_callback(callbacks,
339 on_frame_recv_callback);
341 nghttp2_session_callbacks_set_on_stream_close_callback(
342 callbacks, on_stream_close_callback);
344 nghttp2_session_callbacks_set_on_data_chunk_recv_callback(
345 callbacks, on_data_chunk_recv_callback);
348 #ifndef OPENSSL_NO_NEXTPROTONEG
350 * Callback function for TLS NPN. Since this program only supports
351 * HTTP/2 protocol, if server does not offer HTTP/2 the nghttp2
352 * library supports, we terminate program.
354 static int select_next_proto_cb(SSL *ssl, unsigned char **out,
355 unsigned char *outlen, const unsigned char *in,
356 unsigned int inlen, void *arg) {
361 /* nghttp2_select_next_protocol() selects HTTP/2 protocol the
362 nghttp2 library supports. */
363 rv = nghttp2_select_next_protocol(out, outlen, in, inlen);
365 die("Server did not advertise HTTP/2 protocol");
367 return SSL_TLSEXT_ERR_OK;
369 #endif /* !OPENSSL_NO_NEXTPROTONEG */
372 * Setup SSL/TLS context.
374 static void init_ssl_ctx(SSL_CTX *ssl_ctx) {
375 /* Disable SSLv2 and enable all workarounds for buggy servers */
376 SSL_CTX_set_options(ssl_ctx, SSL_OP_ALL | SSL_OP_NO_SSLv2);
377 SSL_CTX_set_mode(ssl_ctx, SSL_MODE_AUTO_RETRY);
378 SSL_CTX_set_mode(ssl_ctx, SSL_MODE_RELEASE_BUFFERS);
379 /* Set NPN callback */
380 #ifndef OPENSSL_NO_NEXTPROTONEG
381 SSL_CTX_set_next_proto_select_cb(ssl_ctx, select_next_proto_cb, NULL);
382 #endif /* !OPENSSL_NO_NEXTPROTONEG */
384 #if OPENSSL_VERSION_NUMBER >= 0x10002000L
385 SSL_CTX_set_alpn_protos(ssl_ctx, (const unsigned char *)"\x02h2", 3);
386 #endif /* OPENSSL_VERSION_NUMBER >= 0x10002000L */
389 static void ssl_handshake(SSL *ssl, int fd) {
391 if (SSL_set_fd(ssl, fd) == 0) {
392 dief("SSL_set_fd", ERR_error_string(ERR_get_error(), NULL));
395 rv = SSL_connect(ssl);
397 dief("SSL_connect", ERR_error_string(ERR_get_error(), NULL));
402 * Connects to the host |host| and port |port|. This function returns
403 * the file descriptor of the client socket.
405 static int connect_to(const char *host, uint16_t port) {
406 struct addrinfo hints;
409 char service[NI_MAXSERV];
410 struct addrinfo *res, *rp;
411 snprintf(service, sizeof(service), "%u", port);
412 memset(&hints, 0, sizeof(struct addrinfo));
413 hints.ai_family = AF_UNSPEC;
414 hints.ai_socktype = SOCK_STREAM;
415 rv = getaddrinfo(host, service, &hints, &res);
417 dief("getaddrinfo", gai_strerror(rv));
419 for (rp = res; rp; rp = rp->ai_next) {
420 fd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
424 while ((rv = connect(fd, rp->ai_addr, rp->ai_addrlen)) == -1 &&
437 static void make_non_block(int fd) {
439 while ((flags = fcntl(fd, F_GETFL, 0)) == -1 && errno == EINTR)
442 dief("fcntl", strerror(errno));
444 while ((rv = fcntl(fd, F_SETFL, flags | O_NONBLOCK)) == -1 && errno == EINTR)
447 dief("fcntl", strerror(errno));
451 static void set_tcp_nodelay(int fd) {
454 rv = setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &val, (socklen_t)sizeof(val));
456 dief("setsockopt", strerror(errno));
461 * Update |pollfd| based on the state of |connection|.
463 static void ctl_poll(struct pollfd *pollfd, struct Connection *connection) {
465 if (nghttp2_session_want_read(connection->session) ||
466 connection->want_io == WANT_READ) {
467 pollfd->events |= POLLIN;
469 if (nghttp2_session_want_write(connection->session) ||
470 connection->want_io == WANT_WRITE) {
471 pollfd->events |= POLLOUT;
476 * Submits the request |req| to the connection |connection|. This
477 * function does not send packets; just append the request to the
478 * internal queue in |connection->session|.
480 static void submit_request(struct Connection *connection, struct Request *req) {
482 /* Make sure that the last item is NULL */
483 const nghttp2_nv nva[] = {MAKE_NV(":method", "GET"),
484 MAKE_NV_CS(":path", req->path),
485 MAKE_NV(":scheme", "https"),
486 MAKE_NV_CS(":authority", req->hostport),
487 MAKE_NV("accept", "*/*"),
488 MAKE_NV("user-agent", "nghttp2/" NGHTTP2_VERSION)};
490 stream_id = nghttp2_submit_request(connection->session, NULL, nva,
491 sizeof(nva) / sizeof(nva[0]), NULL, req);
494 diec("nghttp2_submit_request", stream_id);
497 req->stream_id = stream_id;
498 printf("[INFO] Stream ID = %d\n", stream_id);
502 * Performs the network I/O.
504 static void exec_io(struct Connection *connection) {
506 rv = nghttp2_session_recv(connection->session);
508 diec("nghttp2_session_recv", rv);
510 rv = nghttp2_session_send(connection->session);
512 diec("nghttp2_session_send", rv);
516 static void request_init(struct Request *req, const struct URI *uri) {
517 req->host = strcopy(uri->host, uri->hostlen);
518 req->port = uri->port;
519 req->path = strcopy(uri->path, uri->pathlen);
520 req->hostport = strcopy(uri->hostport, uri->hostportlen);
524 static void request_free(struct Request *req) {
531 * Fetches the resource denoted by |uri|.
533 static void fetch_uri(const struct URI *uri) {
534 nghttp2_session_callbacks *callbacks;
539 struct Connection connection;
542 struct pollfd pollfds[1];
544 request_init(&req, uri);
546 /* Establish connection and setup SSL */
547 fd = connect_to(req.host, req.port);
549 die("Could not open file descriptor");
551 ssl_ctx = SSL_CTX_new(TLS_client_method());
552 if (ssl_ctx == NULL) {
553 dief("SSL_CTX_new", ERR_error_string(ERR_get_error(), NULL));
555 init_ssl_ctx(ssl_ctx);
556 ssl = SSL_new(ssl_ctx);
558 dief("SSL_new", ERR_error_string(ERR_get_error(), NULL));
560 /* To simplify the program, we perform SSL/TLS handshake in blocking
562 ssl_handshake(ssl, fd);
564 connection.ssl = ssl;
565 connection.want_io = IO_NONE;
567 /* Here make file descriptor non-block */
571 printf("[INFO] SSL/TLS handshake completed\n");
573 rv = nghttp2_session_callbacks_new(&callbacks);
576 diec("nghttp2_session_callbacks_new", rv);
579 setup_nghttp2_callbacks(callbacks);
581 rv = nghttp2_session_client_new(&connection.session, callbacks, &connection);
583 nghttp2_session_callbacks_del(callbacks);
586 diec("nghttp2_session_client_new", rv);
589 rv = nghttp2_submit_settings(connection.session, NGHTTP2_FLAG_NONE, NULL, 0);
592 diec("nghttp2_submit_settings", rv);
595 /* Submit the HTTP request to the outbound queue. */
596 submit_request(&connection, &req);
599 ctl_poll(pollfds, &connection);
602 while (nghttp2_session_want_read(connection.session) ||
603 nghttp2_session_want_write(connection.session)) {
604 int nfds = poll(pollfds, npollfds, -1);
606 dief("poll", strerror(errno));
608 if (pollfds[0].revents & (POLLIN | POLLOUT)) {
609 exec_io(&connection);
611 if ((pollfds[0].revents & POLLHUP) || (pollfds[0].revents & POLLERR)) {
612 die("Connection error");
614 ctl_poll(pollfds, &connection);
617 /* Resource cleanup */
618 nghttp2_session_del(connection.session);
621 SSL_CTX_free(ssl_ctx);
622 shutdown(fd, SHUT_WR);
627 static int parse_uri(struct URI *res, const char *uri) {
628 /* We only interested in https */
629 size_t len, i, offset;
631 memset(res, 0, sizeof(struct URI));
633 if (len < 9 || memcmp("https://", uri, 8) != 0) {
637 res->host = res->hostport = &uri[offset];
639 if (uri[offset] == '[') {
640 /* IPv6 literal address */
644 for (i = offset; i < len; ++i) {
646 res->hostlen = i - offset;
652 const char delims[] = ":/?#";
653 for (i = offset; i < len; ++i) {
654 if (strchr(delims, uri[i]) != NULL) {
658 res->hostlen = i - offset;
661 if (res->hostlen == 0) {
667 if (uri[offset] == ':') {
669 const char delims[] = "/?#";
672 for (i = offset; i < len; ++i) {
673 if (strchr(delims, uri[i]) != NULL) {
676 if ('0' <= uri[i] && uri[i] <= '9') {
678 port += uri[i] - '0';
690 res->port = (uint16_t)port;
693 res->hostportlen = (size_t)(uri + offset + ipv6addr - res->host);
694 for (i = offset; i < len; ++i) {
699 if (i - offset == 0) {
703 res->path = &uri[offset];
704 res->pathlen = i - offset;
709 int main(int argc, char **argv) {
711 struct sigaction act;
715 die("Specify a https URI");
718 memset(&act, 0, sizeof(struct sigaction));
719 act.sa_handler = SIG_IGN;
720 sigaction(SIGPIPE, &act, 0);
722 #if OPENSSL_VERSION_NUMBER >= 0x1010000fL
723 /* No explicit initialization is required. */
724 #elif defined(OPENSSL_IS_BORINGSSL)
725 CRYPTO_library_init();
726 #else /* !(OPENSSL_VERSION_NUMBER >= 0x1010000fL) && \
727 !defined(OPENSSL_IS_BORINGSSL) */
728 OPENSSL_config(NULL);
729 SSL_load_error_strings();
731 OpenSSL_add_all_algorithms();
732 #endif /* !(OPENSSL_VERSION_NUMBER >= 0x1010000fL) && \
733 !defined(OPENSSL_IS_BORINGSSL) */
735 rv = parse_uri(&uri, argv[1]);
737 die("parse_uri failed");