Apply PIE to nghttpx
[platform/upstream/nghttp2.git] / examples / client.c
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  */
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
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
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
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  */
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  */
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
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
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  */
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  */
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  */
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  */
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  */
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
385 static void ssl_handshake(SSL *ssl, int fd) {
386   int rv;
387   if (SSL_set_fd(ssl, fd) == 0) {
388     dief("SSL_set_fd", ERR_error_string(ERR_get_error(), NULL));
389   }
390   ERR_clear_error();
391   rv = SSL_connect(ssl);
392   if (rv <= 0) {
393     dief("SSL_connect", ERR_error_string(ERR_get_error(), NULL));
394   }
395 }
396
397 /*
398  * Connects to the host |host| and port |port|.  This function returns
399  * the file descriptor of the client socket.
400  */
401 static int connect_to(const char *host, uint16_t port) {
402   struct addrinfo hints;
403   int fd = -1;
404   int rv;
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);
412   if (rv != 0) {
413     dief("getaddrinfo", gai_strerror(rv));
414   }
415   for (rp = res; rp; rp = rp->ai_next) {
416     fd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
417     if (fd == -1) {
418       continue;
419     }
420     while ((rv = connect(fd, rp->ai_addr, rp->ai_addrlen)) == -1 &&
421            errno == EINTR)
422       ;
423     if (rv == 0) {
424       break;
425     }
426     close(fd);
427     fd = -1;
428   }
429   freeaddrinfo(res);
430   return fd;
431 }
432
433 static void make_non_block(int fd) {
434   int flags, rv;
435   while ((flags = fcntl(fd, F_GETFL, 0)) == -1 && errno == EINTR)
436     ;
437   if (flags == -1) {
438     dief("fcntl", strerror(errno));
439   }
440   while ((rv = fcntl(fd, F_SETFL, flags | O_NONBLOCK)) == -1 && errno == EINTR)
441     ;
442   if (rv == -1) {
443     dief("fcntl", strerror(errno));
444   }
445 }
446
447 static void set_tcp_nodelay(int fd) {
448   int val = 1;
449   int rv;
450   rv = setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &val, (socklen_t)sizeof(val));
451   if (rv == -1) {
452     dief("setsockopt", strerror(errno));
453   }
454 }
455
456 /*
457  * Update |pollfd| based on the state of |connection|.
458  */
459 static void ctl_poll(struct pollfd *pollfd, struct Connection *connection) {
460   pollfd->events = 0;
461   if (nghttp2_session_want_read(connection->session) ||
462       connection->want_io == WANT_READ) {
463     pollfd->events |= POLLIN;
464   }
465   if (nghttp2_session_want_write(connection->session) ||
466       connection->want_io == WANT_WRITE) {
467     pollfd->events |= POLLOUT;
468   }
469 }
470
471 /*
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|.
475  */
476 static void submit_request(struct Connection *connection, struct Request *req) {
477   int32_t stream_id;
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)};
485
486   stream_id = nghttp2_submit_request(connection->session, NULL, nva,
487                                      sizeof(nva) / sizeof(nva[0]), NULL, req);
488
489   if (stream_id < 0) {
490     diec("nghttp2_submit_request", stream_id);
491   }
492
493   req->stream_id = stream_id;
494   printf("[INFO] Stream ID = %d\n", stream_id);
495 }
496
497 /*
498  * Performs the network I/O.
499  */
500 static void exec_io(struct Connection *connection) {
501   int rv;
502   rv = nghttp2_session_recv(connection->session);
503   if (rv != 0) {
504     diec("nghttp2_session_recv", rv);
505   }
506   rv = nghttp2_session_send(connection->session);
507   if (rv != 0) {
508     diec("nghttp2_session_send", rv);
509   }
510 }
511
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);
517   req->stream_id = -1;
518 }
519
520 static void request_free(struct Request *req) {
521   free(req->host);
522   free(req->path);
523   free(req->hostport);
524 }
525
526 /*
527  * Fetches the resource denoted by |uri|.
528  */
529 static void fetch_uri(const struct URI *uri) {
530   nghttp2_session_callbacks *callbacks;
531   int fd;
532   SSL_CTX *ssl_ctx;
533   SSL *ssl;
534   struct Request req;
535   struct Connection connection;
536   int rv;
537   nfds_t npollfds = 1;
538   struct pollfd pollfds[1];
539
540   request_init(&req, uri);
541
542   /* Establish connection and setup SSL */
543   fd = connect_to(req.host, req.port);
544   if (fd == -1) {
545     die("Could not open file descriptor");
546   }
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));
550   }
551   init_ssl_ctx(ssl_ctx);
552   ssl = SSL_new(ssl_ctx);
553   if (ssl == NULL) {
554     dief("SSL_new", ERR_error_string(ERR_get_error(), NULL));
555   }
556   /* To simplify the program, we perform SSL/TLS handshake in blocking
557      I/O. */
558   ssl_handshake(ssl, fd);
559
560   connection.ssl = ssl;
561   connection.want_io = IO_NONE;
562
563   /* Here make file descriptor non-block */
564   make_non_block(fd);
565   set_tcp_nodelay(fd);
566
567   printf("[INFO] SSL/TLS handshake completed\n");
568
569   rv = nghttp2_session_callbacks_new(&callbacks);
570
571   if (rv != 0) {
572     diec("nghttp2_session_callbacks_new", rv);
573   }
574
575   setup_nghttp2_callbacks(callbacks);
576
577   rv = nghttp2_session_client_new(&connection.session, callbacks, &connection);
578
579   nghttp2_session_callbacks_del(callbacks);
580
581   if (rv != 0) {
582     diec("nghttp2_session_client_new", rv);
583   }
584
585   rv = nghttp2_submit_settings(connection.session, NGHTTP2_FLAG_NONE, NULL, 0);
586
587   if (rv != 0) {
588     diec("nghttp2_submit_settings", rv);
589   }
590
591   /* Submit the HTTP request to the outbound queue. */
592   submit_request(&connection, &req);
593
594   pollfds[0].fd = fd;
595   ctl_poll(pollfds, &connection);
596
597   /* Event loop */
598   while (nghttp2_session_want_read(connection.session) ||
599          nghttp2_session_want_write(connection.session)) {
600     int nfds = poll(pollfds, npollfds, -1);
601     if (nfds == -1) {
602       dief("poll", strerror(errno));
603     }
604     if (pollfds[0].revents & (POLLIN | POLLOUT)) {
605       exec_io(&connection);
606     }
607     if ((pollfds[0].revents & POLLHUP) || (pollfds[0].revents & POLLERR)) {
608       die("Connection error");
609     }
610     ctl_poll(pollfds, &connection);
611   }
612
613   /* Resource cleanup */
614   nghttp2_session_del(connection.session);
615   SSL_shutdown(ssl);
616   SSL_free(ssl);
617   SSL_CTX_free(ssl_ctx);
618   shutdown(fd, SHUT_WR);
619   close(fd);
620   request_free(&req);
621 }
622
623 static int parse_uri(struct URI *res, const char *uri) {
624   /* We only interested in https */
625   size_t len, i, offset;
626   int ipv6addr = 0;
627   memset(res, 0, sizeof(struct URI));
628   len = strlen(uri);
629   if (len < 9 || memcmp("https://", uri, 8) != 0) {
630     return -1;
631   }
632   offset = 8;
633   res->host = res->hostport = &uri[offset];
634   res->hostlen = 0;
635   if (uri[offset] == '[') {
636     /* IPv6 literal address */
637     ++offset;
638     ++res->host;
639     ipv6addr = 1;
640     for (i = offset; i < len; ++i) {
641       if (uri[i] == ']') {
642         res->hostlen = i - offset;
643         offset = i + 1;
644         break;
645       }
646     }
647   } else {
648     const char delims[] = ":/?#";
649     for (i = offset; i < len; ++i) {
650       if (strchr(delims, uri[i]) != NULL) {
651         break;
652       }
653     }
654     res->hostlen = i - offset;
655     offset = i;
656   }
657   if (res->hostlen == 0) {
658     return -1;
659   }
660   /* Assuming https */
661   res->port = 443;
662   if (offset < len) {
663     if (uri[offset] == ':') {
664       /* port */
665       const char delims[] = "/?#";
666       int port = 0;
667       ++offset;
668       for (i = offset; i < len; ++i) {
669         if (strchr(delims, uri[i]) != NULL) {
670           break;
671         }
672         if ('0' <= uri[i] && uri[i] <= '9') {
673           port *= 10;
674           port += uri[i] - '0';
675           if (port > 65535) {
676             return -1;
677           }
678         } else {
679           return -1;
680         }
681       }
682       if (port == 0) {
683         return -1;
684       }
685       offset = i;
686       res->port = (uint16_t)port;
687     }
688   }
689   res->hostportlen = (size_t)(uri + offset + ipv6addr - res->host);
690   for (i = offset; i < len; ++i) {
691     if (uri[i] == '#') {
692       break;
693     }
694   }
695   if (i - offset == 0) {
696     res->path = "/";
697     res->pathlen = 1;
698   } else {
699     res->path = &uri[offset];
700     res->pathlen = i - offset;
701   }
702   return 0;
703 }
704
705 int main(int argc, char **argv) {
706   struct URI uri;
707   struct sigaction act;
708   int rv;
709
710   if (argc < 2) {
711     die("Specify a https URI");
712   }
713
714   memset(&act, 0, sizeof(struct sigaction));
715   act.sa_handler = SIG_IGN;
716   sigaction(SIGPIPE, &act, 0);
717
718   SSL_load_error_strings();
719   SSL_library_init();
720
721   rv = parse_uri(&uri, argv[1]);
722   if (rv != 0) {
723     die("parse_uri failed");
724   }
725   fetch_uri(&uri);
726   return EXIT_SUCCESS;
727 }