• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * nghttp2 - HTTP/2 C Library
3  *
4  * Copyright (c) 2013 Tatsuhiro Tsujikawa
5  *
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:
13  *
14  * The above copyright notice and this permission notice shall be
15  * included in all copies or substantial portions of the Software.
16  *
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.
24  */
25 /*
26  * This program is written to show how to use nghttp2 API in C and
27  * intentionally made simple.
28  */
29 #ifdef HAVE_CONFIG_H
30 #  include <config.h>
31 #endif /* HAVE_CONFIG_H */
32 
33 #include <inttypes.h>
34 #include <stdlib.h>
35 #ifdef HAVE_UNISTD_H
36 #  include <unistd.h>
37 #endif /* HAVE_UNISTD_H */
38 #ifdef HAVE_FCNTL_H
39 #  include <fcntl.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 */
45 #ifdef HAVE_NETDB_H
46 #  include <netdb.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>
52 #include <poll.h>
53 #include <signal.h>
54 #include <stdio.h>
55 #include <assert.h>
56 #include <string.h>
57 #include <errno.h>
58 
59 #include <nghttp2/nghttp2.h>
60 
61 #include <openssl/ssl.h>
62 #include <openssl/err.h>
63 #include <openssl/conf.h>
64 
65 enum { IO_NONE, WANT_READ, WANT_WRITE };
66 
67 #define MAKE_NV(NAME, VALUE)                                                   \
68   {                                                                            \
69     (uint8_t *)NAME, (uint8_t *)VALUE, sizeof(NAME) - 1, sizeof(VALUE) - 1,    \
70         NGHTTP2_NV_FLAG_NONE                                                   \
71   }
72 
73 #define MAKE_NV_CS(NAME, VALUE)                                                \
74   {                                                                            \
75     (uint8_t *)NAME, (uint8_t *)VALUE, sizeof(NAME) - 1, strlen(VALUE),        \
76         NGHTTP2_NV_FLAG_NONE                                                   \
77   }
78 
79 struct Connection {
80   SSL *ssl;
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. */
88   int want_io;
89 };
90 
91 struct Request {
92   char *host;
93   /* In this program, path contains query component as well. */
94   char *path;
95   /* This is the concatenation of host and port with ":" in
96      between. */
97   char *hostport;
98   /* Stream ID for this request. */
99   int32_t stream_id;
100   uint16_t port;
101 };
102 
103 struct URI {
104   const char *host;
105   /* In this program, path contains query component as well. */
106   const char *path;
107   size_t pathlen;
108   const char *hostport;
109   size_t hostlen;
110   size_t hostportlen;
111   uint16_t port;
112 };
113 
114 /*
115  * Returns copy of string |s| with the length |len|. The returned
116  * string is NULL-terminated.
117  */
strcopy(const char * s,size_t len)118 static char *strcopy(const char *s, size_t len) {
119   char *dst;
120   dst = malloc(len + 1);
121   memcpy(dst, s, len);
122   dst[len] = '\0';
123   return dst;
124 }
125 
126 /*
127  * Prints error message |msg| and exit.
128  */
129 NGHTTP2_NORETURN
die(const char * msg)130 static void die(const char *msg) {
131   fprintf(stderr, "FATAL: %s\n", msg);
132   exit(EXIT_FAILURE);
133 }
134 
135 /*
136  * Prints error containing the function name |func| and message |msg|
137  * and exit.
138  */
139 NGHTTP2_NORETURN
dief(const char * func,const char * msg)140 static void dief(const char *func, const char *msg) {
141   fprintf(stderr, "FATAL: %s: %s\n", func, msg);
142   exit(EXIT_FAILURE);
143 }
144 
145 /*
146  * Prints error containing the function name |func| and error code
147  * |error_code| and exit.
148  */
149 NGHTTP2_NORETURN
diec(const char * func,int error_code)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));
153   exit(EXIT_FAILURE);
154 }
155 
156 /*
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.
161  */
send_callback(nghttp2_session * session,const uint8_t * data,size_t length,int flags,void * user_data)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;
165   int rv;
166   (void)session;
167   (void)flags;
168 
169   connection = (struct Connection *)user_data;
170   connection->want_io = IO_NONE;
171   ERR_clear_error();
172   rv = SSL_write(connection->ssl, data, (int)length);
173   if (rv <= 0) {
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;
179     } else {
180       rv = NGHTTP2_ERR_CALLBACK_FAILURE;
181     }
182   }
183   return rv;
184 }
185 
186 /*
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.
191  */
recv_callback(nghttp2_session * session,uint8_t * buf,size_t length,int flags,void * user_data)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;
195   int rv;
196   (void)session;
197   (void)flags;
198 
199   connection = (struct Connection *)user_data;
200   connection->want_io = IO_NONE;
201   ERR_clear_error();
202   rv = SSL_read(connection->ssl, buf, (int)length);
203   if (rv < 0) {
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;
209     } else {
210       rv = NGHTTP2_ERR_CALLBACK_FAILURE;
211     }
212   } else if (rv == 0) {
213     rv = NGHTTP2_ERR_EOF;
214   }
215   return rv;
216 }
217 
on_frame_send_callback(nghttp2_session * session,const nghttp2_frame * frame,void * user_data)218 static int on_frame_send_callback(nghttp2_session *session,
219                                   const nghttp2_frame *frame, void *user_data) {
220   size_t i;
221   (void)user_data;
222 
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);
230         printf(": ");
231         fwrite(nva[i].value, 1, nva[i].valuelen, stdout);
232         printf("\n");
233       }
234     }
235     break;
236   case NGHTTP2_RST_STREAM:
237     printf("[INFO] C ----------------------------> S (RST_STREAM)\n");
238     break;
239   case NGHTTP2_GOAWAY:
240     printf("[INFO] C ----------------------------> S (GOAWAY)\n");
241     break;
242   }
243   return 0;
244 }
245 
on_frame_recv_callback(nghttp2_session * session,const nghttp2_frame * frame,void * user_data)246 static int on_frame_recv_callback(nghttp2_session *session,
247                                   const nghttp2_frame *frame, void *user_data) {
248   size_t i;
249   (void)user_data;
250 
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;
255       struct Request *req;
256       req = nghttp2_session_get_stream_user_data(session, frame->hd.stream_id);
257       if (req) {
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);
261           printf(": ");
262           fwrite(nva[i].value, 1, nva[i].valuelen, stdout);
263           printf("\n");
264         }
265       }
266     }
267     break;
268   case NGHTTP2_RST_STREAM:
269     printf("[INFO] C <---------------------------- S (RST_STREAM)\n");
270     break;
271   case NGHTTP2_GOAWAY:
272     printf("[INFO] C <---------------------------- S (GOAWAY)\n");
273     break;
274   }
275   return 0;
276 }
277 
278 /*
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.
283  */
on_stream_close_callback(nghttp2_session * session,int32_t stream_id,uint32_t error_code,void * user_data)284 static int on_stream_close_callback(nghttp2_session *session, int32_t stream_id,
285                                     uint32_t error_code, void *user_data) {
286   struct Request *req;
287   (void)error_code;
288   (void)user_data;
289 
290   req = nghttp2_session_get_stream_user_data(session, stream_id);
291   if (req) {
292     int rv;
293     rv = nghttp2_session_terminate_session(session, NGHTTP2_NO_ERROR);
294 
295     if (rv != 0) {
296       diec("nghttp2_session_terminate_session", rv);
297     }
298   }
299   return 0;
300 }
301 
302 /*
303  * The implementation of nghttp2_on_data_chunk_recv_callback type. We
304  * use this function to print the received response body.
305  */
on_data_chunk_recv_callback(nghttp2_session * session,uint8_t flags,int32_t stream_id,const uint8_t * data,size_t len,void * user_data)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) {
309   struct Request *req;
310   (void)flags;
311   (void)user_data;
312 
313   req = nghttp2_session_get_stream_user_data(session, stream_id);
314   if (req) {
315     printf("[INFO] C <---------------------------- S (DATA chunk)\n"
316            "%lu bytes\n",
317            (unsigned long int)len);
318     fwrite(data, 1, len, stdout);
319     printf("\n");
320   }
321   return 0;
322 }
323 
324 /*
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.
329  */
setup_nghttp2_callbacks(nghttp2_session_callbacks * callbacks)330 static void setup_nghttp2_callbacks(nghttp2_session_callbacks *callbacks) {
331   nghttp2_session_callbacks_set_send_callback(callbacks, send_callback);
332 
333   nghttp2_session_callbacks_set_recv_callback(callbacks, recv_callback);
334 
335   nghttp2_session_callbacks_set_on_frame_send_callback(callbacks,
336                                                        on_frame_send_callback);
337 
338   nghttp2_session_callbacks_set_on_frame_recv_callback(callbacks,
339                                                        on_frame_recv_callback);
340 
341   nghttp2_session_callbacks_set_on_stream_close_callback(
342       callbacks, on_stream_close_callback);
343 
344   nghttp2_session_callbacks_set_on_data_chunk_recv_callback(
345       callbacks, on_data_chunk_recv_callback);
346 }
347 
348 #ifndef OPENSSL_NO_NEXTPROTONEG
349 /*
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.
353  */
select_next_proto_cb(SSL * ssl,unsigned char ** out,unsigned char * outlen,const unsigned char * in,unsigned int inlen,void * arg)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) {
357   int rv;
358   (void)ssl;
359   (void)arg;
360 
361   /* nghttp2_select_next_protocol() selects HTTP/2 protocol the
362      nghttp2 library supports. */
363   rv = nghttp2_select_next_protocol(out, outlen, in, inlen);
364   if (rv <= 0) {
365     die("Server did not advertise HTTP/2 protocol");
366   }
367   return SSL_TLSEXT_ERR_OK;
368 }
369 #endif /* !OPENSSL_NO_NEXTPROTONEG */
370 
371 /*
372  * Setup SSL/TLS context.
373  */
init_ssl_ctx(SSL_CTX * ssl_ctx)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 */
383 
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 */
387 }
388 
ssl_handshake(SSL * ssl,int fd)389 static void ssl_handshake(SSL *ssl, int fd) {
390   int rv;
391   if (SSL_set_fd(ssl, fd) == 0) {
392     dief("SSL_set_fd", ERR_error_string(ERR_get_error(), NULL));
393   }
394   ERR_clear_error();
395   rv = SSL_connect(ssl);
396   if (rv <= 0) {
397     dief("SSL_connect", ERR_error_string(ERR_get_error(), NULL));
398   }
399 }
400 
401 /*
402  * Connects to the host |host| and port |port|.  This function returns
403  * the file descriptor of the client socket.
404  */
connect_to(const char * host,uint16_t port)405 static int connect_to(const char *host, uint16_t port) {
406   struct addrinfo hints;
407   int fd = -1;
408   int rv;
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);
416   if (rv != 0) {
417     dief("getaddrinfo", gai_strerror(rv));
418   }
419   for (rp = res; rp; rp = rp->ai_next) {
420     fd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
421     if (fd == -1) {
422       continue;
423     }
424     while ((rv = connect(fd, rp->ai_addr, rp->ai_addrlen)) == -1 &&
425            errno == EINTR)
426       ;
427     if (rv == 0) {
428       break;
429     }
430     close(fd);
431     fd = -1;
432   }
433   freeaddrinfo(res);
434   return fd;
435 }
436 
make_non_block(int fd)437 static void make_non_block(int fd) {
438   int flags, rv;
439   while ((flags = fcntl(fd, F_GETFL, 0)) == -1 && errno == EINTR)
440     ;
441   if (flags == -1) {
442     dief("fcntl", strerror(errno));
443   }
444   while ((rv = fcntl(fd, F_SETFL, flags | O_NONBLOCK)) == -1 && errno == EINTR)
445     ;
446   if (rv == -1) {
447     dief("fcntl", strerror(errno));
448   }
449 }
450 
set_tcp_nodelay(int fd)451 static void set_tcp_nodelay(int fd) {
452   int val = 1;
453   int rv;
454   rv = setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &val, (socklen_t)sizeof(val));
455   if (rv == -1) {
456     dief("setsockopt", strerror(errno));
457   }
458 }
459 
460 /*
461  * Update |pollfd| based on the state of |connection|.
462  */
ctl_poll(struct pollfd * pollfd,struct Connection * connection)463 static void ctl_poll(struct pollfd *pollfd, struct Connection *connection) {
464   pollfd->events = 0;
465   if (nghttp2_session_want_read(connection->session) ||
466       connection->want_io == WANT_READ) {
467     pollfd->events |= POLLIN;
468   }
469   if (nghttp2_session_want_write(connection->session) ||
470       connection->want_io == WANT_WRITE) {
471     pollfd->events |= POLLOUT;
472   }
473 }
474 
475 /*
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|.
479  */
submit_request(struct Connection * connection,struct Request * req)480 static void submit_request(struct Connection *connection, struct Request *req) {
481   int32_t stream_id;
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)};
489 
490   stream_id = nghttp2_submit_request(connection->session, NULL, nva,
491                                      sizeof(nva) / sizeof(nva[0]), NULL, req);
492 
493   if (stream_id < 0) {
494     diec("nghttp2_submit_request", stream_id);
495   }
496 
497   req->stream_id = stream_id;
498   printf("[INFO] Stream ID = %d\n", stream_id);
499 }
500 
501 /*
502  * Performs the network I/O.
503  */
exec_io(struct Connection * connection)504 static void exec_io(struct Connection *connection) {
505   int rv;
506   rv = nghttp2_session_recv(connection->session);
507   if (rv != 0) {
508     diec("nghttp2_session_recv", rv);
509   }
510   rv = nghttp2_session_send(connection->session);
511   if (rv != 0) {
512     diec("nghttp2_session_send", rv);
513   }
514 }
515 
request_init(struct Request * req,const struct URI * uri)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);
521   req->stream_id = -1;
522 }
523 
request_free(struct Request * req)524 static void request_free(struct Request *req) {
525   free(req->host);
526   free(req->path);
527   free(req->hostport);
528 }
529 
530 /*
531  * Fetches the resource denoted by |uri|.
532  */
fetch_uri(const struct URI * uri)533 static void fetch_uri(const struct URI *uri) {
534   nghttp2_session_callbacks *callbacks;
535   int fd;
536   SSL_CTX *ssl_ctx;
537   SSL *ssl;
538   struct Request req;
539   struct Connection connection;
540   int rv;
541   nfds_t npollfds = 1;
542   struct pollfd pollfds[1];
543 
544   request_init(&req, uri);
545 
546   /* Establish connection and setup SSL */
547   fd = connect_to(req.host, req.port);
548   if (fd == -1) {
549     die("Could not open file descriptor");
550   }
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));
554   }
555   init_ssl_ctx(ssl_ctx);
556   ssl = SSL_new(ssl_ctx);
557   if (ssl == NULL) {
558     dief("SSL_new", ERR_error_string(ERR_get_error(), NULL));
559   }
560   /* To simplify the program, we perform SSL/TLS handshake in blocking
561      I/O. */
562   ssl_handshake(ssl, fd);
563 
564   connection.ssl = ssl;
565   connection.want_io = IO_NONE;
566 
567   /* Here make file descriptor non-block */
568   make_non_block(fd);
569   set_tcp_nodelay(fd);
570 
571   printf("[INFO] SSL/TLS handshake completed\n");
572 
573   rv = nghttp2_session_callbacks_new(&callbacks);
574 
575   if (rv != 0) {
576     diec("nghttp2_session_callbacks_new", rv);
577   }
578 
579   setup_nghttp2_callbacks(callbacks);
580 
581   rv = nghttp2_session_client_new(&connection.session, callbacks, &connection);
582 
583   nghttp2_session_callbacks_del(callbacks);
584 
585   if (rv != 0) {
586     diec("nghttp2_session_client_new", rv);
587   }
588 
589   rv = nghttp2_submit_settings(connection.session, NGHTTP2_FLAG_NONE, NULL, 0);
590 
591   if (rv != 0) {
592     diec("nghttp2_submit_settings", rv);
593   }
594 
595   /* Submit the HTTP request to the outbound queue. */
596   submit_request(&connection, &req);
597 
598   pollfds[0].fd = fd;
599   ctl_poll(pollfds, &connection);
600 
601   /* Event loop */
602   while (nghttp2_session_want_read(connection.session) ||
603          nghttp2_session_want_write(connection.session)) {
604     int nfds = poll(pollfds, npollfds, -1);
605     if (nfds == -1) {
606       dief("poll", strerror(errno));
607     }
608     if (pollfds[0].revents & (POLLIN | POLLOUT)) {
609       exec_io(&connection);
610     }
611     if ((pollfds[0].revents & POLLHUP) || (pollfds[0].revents & POLLERR)) {
612       die("Connection error");
613     }
614     ctl_poll(pollfds, &connection);
615   }
616 
617   /* Resource cleanup */
618   nghttp2_session_del(connection.session);
619   SSL_shutdown(ssl);
620   SSL_free(ssl);
621   SSL_CTX_free(ssl_ctx);
622   shutdown(fd, SHUT_WR);
623   close(fd);
624   request_free(&req);
625 }
626 
parse_uri(struct URI * res,const char * uri)627 static int parse_uri(struct URI *res, const char *uri) {
628   /* We only interested in https */
629   size_t len, i, offset;
630   int ipv6addr = 0;
631   memset(res, 0, sizeof(struct URI));
632   len = strlen(uri);
633   if (len < 9 || memcmp("https://", uri, 8) != 0) {
634     return -1;
635   }
636   offset = 8;
637   res->host = res->hostport = &uri[offset];
638   res->hostlen = 0;
639   if (uri[offset] == '[') {
640     /* IPv6 literal address */
641     ++offset;
642     ++res->host;
643     ipv6addr = 1;
644     for (i = offset; i < len; ++i) {
645       if (uri[i] == ']') {
646         res->hostlen = i - offset;
647         offset = i + 1;
648         break;
649       }
650     }
651   } else {
652     const char delims[] = ":/?#";
653     for (i = offset; i < len; ++i) {
654       if (strchr(delims, uri[i]) != NULL) {
655         break;
656       }
657     }
658     res->hostlen = i - offset;
659     offset = i;
660   }
661   if (res->hostlen == 0) {
662     return -1;
663   }
664   /* Assuming https */
665   res->port = 443;
666   if (offset < len) {
667     if (uri[offset] == ':') {
668       /* port */
669       const char delims[] = "/?#";
670       int port = 0;
671       ++offset;
672       for (i = offset; i < len; ++i) {
673         if (strchr(delims, uri[i]) != NULL) {
674           break;
675         }
676         if ('0' <= uri[i] && uri[i] <= '9') {
677           port *= 10;
678           port += uri[i] - '0';
679           if (port > 65535) {
680             return -1;
681           }
682         } else {
683           return -1;
684         }
685       }
686       if (port == 0) {
687         return -1;
688       }
689       offset = i;
690       res->port = (uint16_t)port;
691     }
692   }
693   res->hostportlen = (size_t)(uri + offset + ipv6addr - res->host);
694   for (i = offset; i < len; ++i) {
695     if (uri[i] == '#') {
696       break;
697     }
698   }
699   if (i - offset == 0) {
700     res->path = "/";
701     res->pathlen = 1;
702   } else {
703     res->path = &uri[offset];
704     res->pathlen = i - offset;
705   }
706   return 0;
707 }
708 
main(int argc,char ** argv)709 int main(int argc, char **argv) {
710   struct URI uri;
711   struct sigaction act;
712   int rv;
713 
714   if (argc < 2) {
715     die("Specify a https URI");
716   }
717 
718   memset(&act, 0, sizeof(struct sigaction));
719   act.sa_handler = SIG_IGN;
720   sigaction(SIGPIPE, &act, 0);
721 
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();
730   SSL_library_init();
731   OpenSSL_add_all_algorithms();
732 #endif /* !(OPENSSL_VERSION_NUMBER >= 0x1010000fL) &&                          \
733           !defined(OPENSSL_IS_BORINGSSL) */
734 
735   rv = parse_uri(&uri, argv[1]);
736   if (rv != 0) {
737     die("parse_uri failed");
738   }
739   fetch_uri(&uri);
740   return EXIT_SUCCESS;
741 }
742