1 #define _POSIX_C_SOURCE 200809L
5 #include <sys/socket.h>
6 #include <netinet/in.h>
28 int tls_parse_uri(char *, struct tls_uri *);
29 void tls_free_uri(struct tls_uri *);
31 int open_tcp_connection(char *host, int port);
33 /* if trustpolicy is 0, we just accept anything */
34 int verify_trust(struct TLSContext *context, struct TLSCertificate **chain, int
37 if (context || chain || len) {
44 static char hexchars[] = "0123456789abcdefABCDEF";
46 static void hex(char *dst, uint8_t *src, size_t len) {
48 dst[0] = hexchars[(src[0]>>4)&0xf];
49 dst[1] = hexchars[src[0]&0xf];
56 static void hexbin(uint8_t *dst, unsigned char *src, size_t len) {
60 for (i=0; i<len; i+=2) {
61 sscanf((const char *)src+i, "%02x", &x);
67 char *my_getline(struct tls_buffer *b, int fd, size_t *size) {
72 while (b->error == 0) {
73 loc = memchr(b->buffer, '\n', b->len);
75 *size = loc - b->buffer + 1;
78 rv = read(fd, buf, sizeof buf);
85 tls_buffer_append(b, buf, rv);
96 * We use a trust on first use policy. The trust DB is a simple
97 * file in /var/lib/zpm/known_hosts, or ~/.zpm/known_hosts, or ZPM_KNOWNHOSTS.
98 * if -k is given, no verification is done
100 int verify_first(struct TLSContext *context, struct TLSCertificate **chain, int
103 char *trustfile, *homedir = 0, *host, *fp;
104 unsigned char certhash[65];
106 struct tls_buffer tbuf;
111 if (certs == 0 || chain == 0) {
115 err = tls_certificate_is_valid(chain[0]);
121 err = tls_certificate_valid_subject(chain[0], context->sni);
127 hex(certhash, chain[0]->fp, 32);
130 trustfile = getenv("ZPM_KNOWNHOSTS");
132 if (geteuid() == 0) {
133 trustfile = "/var/lib/zpm/known_hosts";
135 /* we could do this with a series of
136 * openat() calls instead of building
139 trustfile = getenv("HOME");
141 fprintf(stderr, "home = %s\n", trustfile);
144 len = snprintf(homedir, 0, "%s/.zpm/known_hosts", trustfile);
145 homedir = malloc(len+1);
149 len = snprintf(homedir, len+1, "%s/.zpm/known_hosts", trustfile);
153 /* cert is valid on its face, so check against the trust db */
154 trustdb = open(trustfile, O_RDWR|O_CREAT, 0600);
156 fprintf(stderr, "cannot open trustdb %s: %s\n", trustfile, strerror(errno));
168 tls_buffer_init(&tbuf, 128);
172 tls_buffer_shift(&tbuf, len);
173 line = my_getline(&tbuf, trustdb, &len);
180 while (isspace(*fp)) {
186 off = strchr(line, ':');
192 if (line[len-1] == '\n') {
196 if (strlen(fp) != 64) {
200 if (len && line[len-1] == '\n') {
204 if (strcmp(context->sni, host) != 0) {
208 int match = (memcmp(certhash, fp, 64) == 0);
211 tls_buffer_free(&tbuf);
213 fprintf(stderr, "host %s certificate changed\n", host);
215 return match ? no_error : bad_certificate;
216 } while (!tbuf.error);
218 /* got here, so we should be at EOF, so add this host to trust db */
219 lseek(trustdb, 0, SEEK_END);
221 /* re-use the buffer so we only do one write */
222 /* ignore errors, the cert is fine, we just can't update
223 * the trustdb if there's errors here
226 tls_buffer_append(&tbuf, certhash, 64);
227 tls_buffer_append_byte(&tbuf, ':');
228 tls_buffer_append(&tbuf, context->sni, strlen(context->sni));
229 tls_buffer_append_byte(&tbuf, '\n');
230 write(trustdb, tbuf.buffer, tbuf.len);
232 tls_buffer_free(&tbuf);
237 int verify_roots(struct TLSContext *context, struct TLSCertificate **chain, int
242 for (i = 0; i < len; i++) {
243 struct TLSCertificate *certificate = chain[i];
244 err = tls_certificate_is_valid(certificate);
251 err = tls_certificate_chain_is_valid(chain, len);
256 if (len > 0 && context->sni) {
257 err = tls_certificate_valid_subject(chain[0], context->sni);
263 /* Perform certificate validation against ROOT CA */
264 err = tls_certificate_chain_is_valid_root(context, chain, len);
273 struct tls_buffer response;
274 struct TLSContext *tls;
277 time_t last_modified;
279 size_t content_length;
284 char *months[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul",
285 "Aug", "Sep", "Oct", "Nov", "Dec" };
288 for (i=0; i < 12; i++) {
289 if (!strncasecmp(m, months[i], 3)) {
296 /* Wed, 06 Feb 2019 10:06:05 GMT */
297 time_t parse_date(char *d) {
298 struct tm tm = { 0 };
303 rv = sscanf(d, "%*[a-zA-Z,] %d %s %d %d:%d:%d", &dom, M, &Y, &h, &m, &s);
305 tm.tm_year = Y - 1900;
309 tm.tm_mon = month(M)-1;
317 char *find_header(struct io *io, char *header, size_t *len) {
323 hlen = strlen(header);
324 eoh = strstr(io->response.buffer, "\r\n\r\n");
328 soh = io->response.buffer;
330 soh = strstr(soh, "\r\n");
335 if (!memcmp(soh, header, hlen)) {
343 eoh = strstr(soh, "\r\n");
345 while (soh < eoh && isspace(*soh)) {
352 void parse_header(struct io *io) {
353 char *s = io->response.buffer;
358 while (!isspace(*s)) {
361 while (isspace(*s)) {
364 code = strtol(s, 0, 10);
365 io->status_code = code;
367 hval = find_header(io, "Date:", &hlen);
370 io->date = parse_date(hval);
373 hval = find_header(io, "Last-Modified:", &hlen);
376 io->last_modified = parse_date(hval);
380 hval = find_header(io, "Content-Length:", &hlen);
383 io->content_length = strtoul(hval, 0, 10);
392 hval = find_header(io, "Location:", &hlen);
394 io->redirect = strndup(hval, hlen);
403 ssize_t fill_buffer(struct io *io) {
404 unsigned char buffer[4096];
408 ret = tls_read(io->tls, buffer, sizeof buffer);
410 ret = read(io->socket, buffer, sizeof buffer);
414 tls_buffer_append(&io->response, buffer, ret);
421 char *nextline(struct io *io) {
424 eol = memchr(io->response.buffer, '\n', io.response.size);
427 eol = memchr(io->response.buffer, '\n', io.response.size);
434 void append_header(struct tls_buffer *buf, char *header, char *val) {
435 tls_buffer_append(buf, header, strlen(header));
436 tls_buffer_append(buf, ": ", 2);
437 tls_buffer_append(buf, val, strlen(val));
438 tls_buffer_append(buf, "\r\n", 2);
441 void append_timeheader(struct tls_buffer *buf, char *header, time_t ts) {
447 strftime(timestr, sizeof timestr, "%a, %d %b %Y %H:%M:%S GMT", tm);
448 append_header(buf, header, timestr);
451 static void pdots(int len, int ch, unsigned long was, unsigned long now,
452 unsigned long total) {
453 was = len * was / total;
457 now = len * now / total;
458 while (was++ < now) {
463 static void fake_header(struct io *io, int fd) {
466 char *message, codestr[5], length[32];
467 struct tls_buffer *hdr = &io->response;
471 case EACCES: code = 403; break;
472 case ENOENT: code = 404; break;
473 default: code = 500; break;
482 if (io->last_modified >= st.st_mtime) {
487 case 200: message = "OK"; break;
488 case 304: message = "Not Modified"; break;
489 case 403: message = "Forbidden"; break;
490 case 404: message = "Not Found"; break;
491 case 500: message = "Internal Server Error"; break;
494 sprintf(codestr, "%0.3d ", code);
495 tls_buffer_append(hdr, "HTTP/1.1 ", 9);
496 tls_buffer_append(hdr, codestr, 4);
497 tls_buffer_append_str(hdr, message);
498 tls_buffer_append(hdr, "\r\n", 2);
500 append_timeheader(hdr, "Date", time(NULL));
501 append_header(hdr, "Server", "zpm-fetchurl/0.9");
503 append_timeheader(hdr, "Last-Modified", st.st_mtime);
504 sprintf(length, "%zu", st.st_size);
505 append_header(hdr, "Content-Length", length);
508 append_header(hdr, "Connection", "close");
509 append_header(hdr, "Content-Type", "application/octet-stream");
510 tls_buffer_append(hdr, "\r\n", 2);
513 char *pathlast(char *path) {
521 while (*path == '/') {
528 while (*path && *path != '/') {
532 while (*path == '/') {
541 return strndup(last, len);
544 static time_t file_mtime(char *path) {
548 rv = stat(path, &st);
550 if (errno == ENOENT) {
553 perror("stat failed:");
560 int main(int ac, char *av[]) {
561 int sockfd, port = -1, rv;
565 char msg[] = "GET %s HTTP/1.1\r\nHost: %s:%i\r\nConnection: close\r\n\r\n";
566 char msg2[] = "GET %s HTTP/1.1\r\nHost: %s:%i\r\nLast-Modified: %s\r\nConnection: close\r\n\r\n";
567 char msg_buffer[1024];
571 struct tls_uri uri = { 0 };
573 int raw = 0, head = 0;
574 int out = 1; /* output file descriptor */
576 struct io io = { {0}, 0, -1, 0, 0, 0, 0, 0 };
577 struct TLSContext *clientssl = 0;
581 struct tls_buffer request;
587 int redirs = 0, redirlimit = 50, printstatus = 0;
588 int verifypolicy = 1, calcoutfile = 0, ifnewer = 0;
592 while ((option = getopt(ac, av, "o:OrIfz:np#R:SkK")) != -1) {
594 case 'o': outfile = optarg; break;
595 case 'O': calcoutfile = 1; break;
596 case 'S': printstatus = 1; head = 1; break;
597 case 'k': verifypolicy = 0; break;
598 case 'K': verifypolicy = 2; break;
600 case 'r': raw = 1; break;
601 case 'f': failsilent = 1; break;
602 case 'z': lmfile = optarg; break;
603 case 'n': ifnewer = 1; break;
604 case 'R': redirlimit = strtol(optarg, 0, 10); break;
606 case '#': progressbar = 1; break;
614 fprintf(stderr, "Usage: %s uri\n", av[0]);
618 url = strdup(av[optind]);
623 io.last_modified = 0;
625 if (calcoutfile && !outfile) {
626 tls_parse_uri(url, &uri);
627 outfile = pathlast(uri.path);
628 /* outfile leaks memory here, so if this
629 * were turned into a library function,
630 * we'd need to track it
633 fprintf(stderr, "unable to determine outfile\n");
638 if (ifnewer && outfile && !lmfile) {
646 ts = file_mtime(lmfile);
650 } else if (ts != 0) {
651 io.last_modified = ts;
653 strftime(lmtime, sizeof lmtime, "%a, %d %b %Y %H:%M:%S GMT", mtime);
659 signal(SIGPIPE, SIG_IGN);
661 tls_buffer_init(&io.response, 0);
662 tls_buffer_init(&request, 128);
664 while (redirs++ <= redirlimit) {
670 tls_parse_uri(url, &uri);
672 port = atoi(uri.port);
675 /* construct request */
677 tls_buffer_append(&request, "HEAD ", 5);
679 tls_buffer_append(&request, "GET ", 4);
681 tls_buffer_append(&request, uri.path, strlen(uri.path));
682 tls_buffer_append(&request, " HTTP/1.1\r\n", 11);
684 append_header(&request, "Host", host);
685 append_header(&request, "Connection", "close");
687 append_header(&request, "If-Modified-Since", lmtime);
689 tls_buffer_append(&request, "\r\n", 2);
691 if (!strcmp(uri.scheme, "https")) {
694 clientssl = tls_create_context(TLS_CLIENT, TLS_V12);
696 /* optionally, we can set a certificate validation
697 * callback function if set_verify is not called, and
698 * root ca is set, `tls_default_verify` will be used
699 * (does exactly what `verify` does in this example)
701 if (verifypolicy == 2) {
703 cert_path = getenv("ZPM_CERTFILE");
705 cert_path = "/var/lib/zpm/roots.pem";
707 rv = tls_load_root_file(clientssl, cert_path);
709 fprintf(stderr, "Error loading root certs\n");
712 tls_set_verify(clientssl, verify_roots);
713 } else if (verifypolicy == 1) {
714 tls_set_verify(clientssl, verify_first);
716 tls_set_verify(clientssl, verify_trust);
720 fprintf(stderr, "Error initializing client context\n");
723 tls_sni_set(clientssl, uri.host);
726 sockfd = open_tcp_connection(host, port);
728 perror("can't open connection");
731 tls_set_fd(clientssl, sockfd);
732 if ((rv = tls_connect(clientssl)) != 1) {
733 fprintf(stderr, "Handshake Error %i\n", rv);
736 ret = tls_write(clientssl, request.buffer, request.len);
737 } else if (!strcmp(uri.scheme, "http")) {
738 sockfd = open_tcp_connection(host, port);
740 perror("can't open connection");
743 ret = write(sockfd, request.buffer, request.len);
744 } else if (!strcmp(uri.scheme, "file")) {
745 sockfd = open(uri.path, O_RDONLY);
746 fake_header(&io, sockfd);
749 fprintf(stderr, "scheme %s unknown\n", uri.scheme);
754 fprintf(stderr, "unable to write http request: %s\n", strerror(errno));
761 if (io.response.len >= 4) {
762 eoh = strstr(io.response.buffer, "\r\n\r\n");
765 ret = fill_buffer(&io);
773 /* never got (complet) header */
774 fprintf(stderr, "incomplete response to %s\n", av[optind]);
778 header_len = (size_t)(eoh - io.response.buffer) + 4;
781 switch (io.status_code) {
790 url = strdup(io.redirect);
797 printf("%d\n", io.status_code);
802 tls_buffer_shift(&io.response, header_len);
805 io.response.len -= 2;
809 if (io.content_length) {
810 fprintf(stderr, "(%lu) ", io.content_length);
815 out = open(outfile, O_WRONLY|O_CREAT, 0600);
817 perror("can't open output file:");
823 write(out, io.response.buffer, io.response.len);
824 ret = io.response.len;
828 if (io.content_length) {
829 pdots(50, '.', total, total+ret,
833 fprintf(stderr, "%zu", total+ret);
840 ret = fill_buffer(&io);
844 fprintf(stderr, "%s read error %zd\n", uri.scheme, ret);
846 struct timespec ts[2];
847 ts[0].tv_sec = 0; ts[0].tv_nsec = UTIME_OMIT;
848 ts[1].tv_sec = io.last_modified;
853 tls_buffer_free(&io.response);
858 tls_shutdown(clientssl);
863 if (progressbar && io.status_code == 200) {
864 fprintf(stderr, "(%lu)", total);
868 return io.status_code < 400 ? 0 : EXIT_FAILURE;