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 */
385 static void ssl_handshake(SSL *ssl, int fd) {
387 if (SSL_set_fd(ssl, fd) == 0) {
388 dief("SSL_set_fd", ERR_error_string(ERR_get_error(), NULL));
391 rv = SSL_connect(ssl);
393 dief("SSL_connect", ERR_error_string(ERR_get_error(), NULL));
398 * Connects to the host |host| and port |port|. This function returns
399 * the file descriptor of the client socket.
401 static int connect_to(const char *host, uint16_t port) {
402 struct addrinfo hints;
405 char service[NI_MAXSERV];
406 struct addrinfo *res, *rp;
407 snprintf(service, sizeof(service), "%u", port);
408 memset(&hints, 0, sizeof(struct addrinfo));
409 hints.ai_family = AF_UNSPEC;
410 hints.ai_socktype = SOCK_STREAM;
411 rv = getaddrinfo(host, service, &hints, &res);
413 dief("getaddrinfo", gai_strerror(rv));
415 for (rp = res; rp; rp = rp->ai_next) {
416 fd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
420 while ((rv = connect(fd, rp->ai_addr, rp->ai_addrlen)) == -1 &&
433 static void make_non_block(int fd) {
435 while ((flags = fcntl(fd, F_GETFL, 0)) == -1 && errno == EINTR)
438 dief("fcntl", strerror(errno));
440 while ((rv = fcntl(fd, F_SETFL, flags | O_NONBLOCK)) == -1 && errno == EINTR)
443 dief("fcntl", strerror(errno));
447 static void set_tcp_nodelay(int fd) {
450 rv = setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &val, (socklen_t)sizeof(val));
452 dief("setsockopt", strerror(errno));
457 * Update |pollfd| based on the state of |connection|.
459 static void ctl_poll(struct pollfd *pollfd, struct Connection *connection) {
461 if (nghttp2_session_want_read(connection->session) ||
462 connection->want_io == WANT_READ) {
463 pollfd->events |= POLLIN;
465 if (nghttp2_session_want_write(connection->session) ||
466 connection->want_io == WANT_WRITE) {
467 pollfd->events |= POLLOUT;
472 * Submits the request |req| to the connection |connection|. This
473 * function does not send packets; just append the request to the
474 * internal queue in |connection->session|.
476 static void submit_request(struct Connection *connection, struct Request *req) {
478 /* Make sure that the last item is NULL */
479 const nghttp2_nv nva[] = {MAKE_NV(":method", "GET"),
480 MAKE_NV_CS(":path", req->path),
481 MAKE_NV(":scheme", "https"),
482 MAKE_NV_CS(":authority", req->hostport),
483 MAKE_NV("accept", "*/*"),
484 MAKE_NV("user-agent", "nghttp2/" NGHTTP2_VERSION)};
486 stream_id = nghttp2_submit_request(connection->session, NULL, nva,
487 sizeof(nva) / sizeof(nva[0]), NULL, req);
490 diec("nghttp2_submit_request", stream_id);
493 req->stream_id = stream_id;
494 printf("[INFO] Stream ID = %d\n", stream_id);
498 * Performs the network I/O.
500 static void exec_io(struct Connection *connection) {
502 rv = nghttp2_session_recv(connection->session);
504 diec("nghttp2_session_recv", rv);
506 rv = nghttp2_session_send(connection->session);
508 diec("nghttp2_session_send", rv);
512 static void request_init(struct Request *req, const struct URI *uri) {
513 req->host = strcopy(uri->host, uri->hostlen);
514 req->port = uri->port;
515 req->path = strcopy(uri->path, uri->pathlen);
516 req->hostport = strcopy(uri->hostport, uri->hostportlen);
520 static void request_free(struct Request *req) {
527 * Fetches the resource denoted by |uri|.
529 static void fetch_uri(const struct URI *uri) {
530 nghttp2_session_callbacks *callbacks;
535 struct Connection connection;
538 struct pollfd pollfds[1];
540 request_init(&req, uri);
542 /* Establish connection and setup SSL */
543 fd = connect_to(req.host, req.port);
545 die("Could not open file descriptor");
547 ssl_ctx = SSL_CTX_new(SSLv23_client_method());
548 if (ssl_ctx == NULL) {
549 dief("SSL_CTX_new", ERR_error_string(ERR_get_error(), NULL));
551 init_ssl_ctx(ssl_ctx);
552 ssl = SSL_new(ssl_ctx);
554 dief("SSL_new", ERR_error_string(ERR_get_error(), NULL));
556 /* To simplify the program, we perform SSL/TLS handshake in blocking
558 ssl_handshake(ssl, fd);
560 connection.ssl = ssl;
561 connection.want_io = IO_NONE;
563 /* Here make file descriptor non-block */
567 printf("[INFO] SSL/TLS handshake completed\n");
569 rv = nghttp2_session_callbacks_new(&callbacks);
572 diec("nghttp2_session_callbacks_new", rv);
575 setup_nghttp2_callbacks(callbacks);
577 rv = nghttp2_session_client_new(&connection.session, callbacks, &connection);
579 nghttp2_session_callbacks_del(callbacks);
582 diec("nghttp2_session_client_new", rv);
585 rv = nghttp2_submit_settings(connection.session, NGHTTP2_FLAG_NONE, NULL, 0);
588 diec("nghttp2_submit_settings", rv);
591 /* Submit the HTTP request to the outbound queue. */
592 submit_request(&connection, &req);
595 ctl_poll(pollfds, &connection);
598 while (nghttp2_session_want_read(connection.session) ||
599 nghttp2_session_want_write(connection.session)) {
600 int nfds = poll(pollfds, npollfds, -1);
602 dief("poll", strerror(errno));
604 if (pollfds[0].revents & (POLLIN | POLLOUT)) {
605 exec_io(&connection);
607 if ((pollfds[0].revents & POLLHUP) || (pollfds[0].revents & POLLERR)) {
608 die("Connection error");
610 ctl_poll(pollfds, &connection);
613 /* Resource cleanup */
614 nghttp2_session_del(connection.session);
617 SSL_CTX_free(ssl_ctx);
618 shutdown(fd, SHUT_WR);
623 static int parse_uri(struct URI *res, const char *uri) {
624 /* We only interested in https */
625 size_t len, i, offset;
627 memset(res, 0, sizeof(struct URI));
629 if (len < 9 || memcmp("https://", uri, 8) != 0) {
633 res->host = res->hostport = &uri[offset];
635 if (uri[offset] == '[') {
636 /* IPv6 literal address */
640 for (i = offset; i < len; ++i) {
642 res->hostlen = i - offset;
648 const char delims[] = ":/?#";
649 for (i = offset; i < len; ++i) {
650 if (strchr(delims, uri[i]) != NULL) {
654 res->hostlen = i - offset;
657 if (res->hostlen == 0) {
663 if (uri[offset] == ':') {
665 const char delims[] = "/?#";
668 for (i = offset; i < len; ++i) {
669 if (strchr(delims, uri[i]) != NULL) {
672 if ('0' <= uri[i] && uri[i] <= '9') {
674 port += uri[i] - '0';
686 res->port = (uint16_t)port;
689 res->hostportlen = (size_t)(uri + offset + ipv6addr - res->host);
690 for (i = offset; i < len; ++i) {
695 if (i - offset == 0) {
699 res->path = &uri[offset];
700 res->pathlen = i - offset;
705 int main(int argc, char **argv) {
707 struct sigaction act;
711 die("Specify a https URI");
714 memset(&act, 0, sizeof(struct sigaction));
715 act.sa_handler = SIG_IGN;
716 sigaction(SIGPIPE, &act, 0);
718 SSL_load_error_strings();
721 rv = parse_uri(&uri, argv[1]);
723 die("parse_uri failed");