1 #define _POSIX_C_SOURCE 200809L
5 #include <sys/socket.h>
6 #include <netinet/in.h>
31 int tls_parse_uri(char *, struct tls_uri *);
32 void tls_free_uri(struct tls_uri *);
34 int open_tcp_connection(char *host, int port);
36 /* if trustpolicy is 0, we just accept anything */
37 int verify_trust(struct TLSContext *context, struct TLSCertificate **chain, int
40 if (context || chain || len) {
47 static char hexchars[] = "0123456789abcdefABCDEF";
49 static void hex(char *dst, uint8_t *src, size_t len) {
51 dst[0] = hexchars[(src[0]>>4)&0xf];
52 dst[1] = hexchars[src[0]&0xf];
59 static void hexbin(uint8_t *dst, unsigned char *src, size_t len) {
63 for (i=0; i<len; i+=2) {
64 sscanf((const char *)src+i, "%02x", &x);
70 char *my_getline(struct tls_buffer *b, int fd, size_t *size) {
75 while (b->error == 0) {
76 loc = memchr(b->buffer, '\n', b->len);
78 *size = loc - b->buffer + 1;
81 rv = read(fd, buf, sizeof buf);
88 tls_buffer_append(b, buf, rv);
99 * We use a trust on first use policy. The trust DB is a simple
100 * file in /var/lib/zpm/known_hosts, or ~/.zpm/known_hosts, or ZPM_KNOWNHOSTS.
101 * if -k is given, no verification is done
103 int verify_first(struct TLSContext *context, struct TLSCertificate **chain, int
106 char *trustfile, *homedir = 0, *host, *fp;
107 unsigned char certhash[65];
109 struct tls_buffer tbuf;
114 if (certs == 0 || chain == 0) {
118 err = tls_certificate_is_valid(chain[0]);
124 err = tls_certificate_valid_subject(chain[0], context->sni);
130 hex(certhash, chain[0]->fp, 32);
133 trustfile = getenv("ZPM_KNOWNHOSTS");
135 if (geteuid() == 0) {
136 trustfile = "/var/lib/zpm/known_hosts";
138 /* we could do this with a series of
139 * openat() calls instead of building
142 trustfile = getenv("HOME");
144 fprintf(stderr, "home = %s\n", trustfile);
147 len = snprintf(homedir, 0, "%s/.zpm/known_hosts", trustfile);
148 homedir = malloc(len+1);
152 len = snprintf(homedir, len+1, "%s/.zpm/known_hosts", trustfile);
156 /* cert is valid on its face, so check against the trust db */
157 trustdb = open(trustfile, O_RDWR|O_CREAT, 0600);
159 fprintf(stderr, "cannot open trustdb %s: %s\n", trustfile, strerror(errno));
171 tls_buffer_init(&tbuf, 128);
175 tls_buffer_shift(&tbuf, len);
176 line = my_getline(&tbuf, trustdb, &len);
183 while (isspace(*fp)) {
189 off = strchr(line, ':');
195 if (line[len-1] == '\n') {
199 if (strlen(fp) != 64) {
203 if (len && line[len-1] == '\n') {
207 if (strcmp(context->sni, host) != 0) {
211 int match = (memcmp(certhash, fp, 64) == 0);
213 fprintf(stderr, "host %s certificate changed\n", host);
214 fprintf(stderr, "was %.64s\n", fp);
215 fprintf(stderr, "now %.64s\n", certhash);
219 tls_buffer_free(&tbuf);
220 return match ? no_error : bad_certificate;
221 } while (!tbuf.error);
223 /* got here, so we should be at EOF, so add this host to trust db */
224 lseek(trustdb, 0, SEEK_END);
226 /* re-use the buffer so we only do one write */
227 /* ignore errors, the cert is fine, we just can't update
228 * the trustdb if there's errors here
231 tls_buffer_append(&tbuf, certhash, 64);
232 tls_buffer_append_byte(&tbuf, ':');
233 tls_buffer_append(&tbuf, context->sni, strlen(context->sni));
234 tls_buffer_append_byte(&tbuf, '\n');
235 write(trustdb, tbuf.buffer, tbuf.len);
237 tls_buffer_free(&tbuf);
242 int verify_roots(struct TLSContext *context, struct TLSCertificate **chain, int
247 for (i = 0; i < len; i++) {
248 struct TLSCertificate *certificate = chain[i];
249 err = tls_certificate_is_valid(certificate);
256 err = tls_certificate_chain_is_valid(chain, len);
261 if (len > 0 && context->sni) {
262 err = tls_certificate_valid_subject(chain[0], context->sni);
268 /* Perform certificate validation against ROOT CA */
269 err = tls_certificate_chain_is_valid_root(context, chain, len);
278 struct tls_buffer response;
279 struct TLSContext *tls;
282 time_t last_modified;
284 size_t content_length;
289 char *months[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul",
290 "Aug", "Sep", "Oct", "Nov", "Dec" };
293 for (i=0; i < 12; i++) {
294 if (!strncasecmp(m, months[i], 3)) {
301 /* Wed, 06 Feb 2019 10:06:05 GMT */
302 time_t parse_date(char *d) {
303 struct tm tm = { 0 };
308 rv = sscanf(d, "%*[a-zA-Z,] %d %s %d %d:%d:%d", &dom, M, &Y, &h, &m, &s);
310 tm.tm_year = Y - 1900;
314 tm.tm_mon = month(M)-1;
322 char *find_header(struct io *io, char *header, size_t *len) {
328 hlen = strlen(header);
329 eoh = strstr(io->response.buffer, "\r\n\r\n");
333 soh = io->response.buffer;
335 soh = strstr(soh, "\r\n");
340 if (!memcmp(soh, header, hlen)) {
348 eoh = strstr(soh, "\r\n");
350 while (soh < eoh && isspace(*soh)) {
357 void parse_header(struct io *io) {
358 char *s = io->response.buffer;
363 while (!isspace(*s)) {
366 while (isspace(*s)) {
369 code = strtol(s, 0, 10);
370 io->status_code = code;
372 hval = find_header(io, "Date:", &hlen);
375 io->date = parse_date(hval);
378 hval = find_header(io, "Last-Modified:", &hlen);
381 io->last_modified = parse_date(hval);
385 hval = find_header(io, "Content-Length:", &hlen);
388 io->content_length = strtoul(hval, 0, 10);
397 hval = find_header(io, "Location:", &hlen);
399 io->redirect = strndup(hval, hlen);
408 ssize_t fill_buffer(struct io *io) {
409 unsigned char buffer[4096];
413 ret = tls_read(io->tls, buffer, sizeof buffer);
415 ret = read(io->socket, buffer, sizeof buffer);
419 tls_buffer_append(&io->response, buffer, ret);
426 char *nextline(struct io *io) {
429 eol = memchr(io->response.buffer, '\n', io.response.size);
432 eol = memchr(io->response.buffer, '\n', io.response.size);
439 void append_header(struct tls_buffer *buf, char *header, char *val) {
440 tls_buffer_append(buf, header, strlen(header));
441 tls_buffer_append(buf, ": ", 2);
442 tls_buffer_append(buf, val, strlen(val));
443 tls_buffer_append(buf, "\r\n", 2);
446 void append_timeheader(struct tls_buffer *buf, char *header, time_t ts) {
452 strftime(timestr, sizeof timestr, "%a, %d %b %Y %H:%M:%S GMT", tm);
453 append_header(buf, header, timestr);
456 static void pdots(int len, int ch, unsigned long was, unsigned long now,
457 unsigned long total) {
458 was = len * was / total;
462 now = len * now / total;
463 while (was++ < now) {
468 static void fake_header(struct io *io, int fd) {
471 char *message, codestr[5], length[32];
472 struct tls_buffer *hdr = &io->response;
476 case EACCES: code = 403; break;
477 case ENOENT: code = 404; break;
478 default: code = 500; break;
487 if (io->last_modified >= st.st_mtime) {
492 case 200: message = "OK"; break;
493 case 304: message = "Not Modified"; break;
494 case 403: message = "Forbidden"; break;
495 case 404: message = "Not Found"; break;
496 case 500: message = "Internal Server Error"; break;
499 sprintf(codestr, "%0.3d ", code);
500 tls_buffer_append(hdr, "HTTP/1.1 ", 9);
501 tls_buffer_append(hdr, codestr, 4);
502 tls_buffer_append_str(hdr, message);
503 tls_buffer_append(hdr, "\r\n", 2);
505 append_timeheader(hdr, "Date", time(NULL));
506 append_header(hdr, "Server", "zpm-fetchurl/0.9");
508 append_timeheader(hdr, "Last-Modified", st.st_mtime);
509 sprintf(length, "%zu", st.st_size);
510 append_header(hdr, "Content-Length", length);
513 append_header(hdr, "Connection", "close");
514 append_header(hdr, "Content-Type", "application/octet-stream");
515 tls_buffer_append(hdr, "\r\n", 2);
518 char *pathlast(char *path) {
526 while (*path == '/') {
533 while (*path && *path != '/') {
537 while (*path == '/') {
546 return strndup(last, len);
549 static time_t file_mtime(char *path) {
553 rv = stat(path, &st);
555 if (errno == ENOENT) {
558 perror("stat failed:");
565 int main(int ac, char *av[]) {
566 int sockfd, port = -1, rv;
570 char msg[] = "GET %s HTTP/1.1\r\nHost: %s:%i\r\nConnection: close\r\n\r\n";
571 char msg2[] = "GET %s HTTP/1.1\r\nHost: %s:%i\r\nLast-Modified: %s\r\nConnection: close\r\n\r\n";
572 char msg_buffer[1024];
576 struct tls_uri uri = { 0 };
578 int raw = 0, head = 0;
579 int out = 1; /* output file descriptor */
581 struct io io = { {0}, 0, -1, 0, 0, 0, 0, 0 };
582 struct TLSContext *clientssl = 0;
586 struct tls_buffer request;
589 char *user_agent = 0;
593 int redirs = 0, redirlimit = 50, printstatus = 0;
594 int verifypolicy = 1, calcoutfile = 0, ifnewer = 0;
598 while ((option = getopt(ac, av, "o:OrIfz:np#R:SkKU:")) != -1) {
600 case 'o': outfile = optarg; break;
601 case 'O': calcoutfile = 1; break;
602 case 'S': printstatus = 1; head = 1; break;
603 case 'k': verifypolicy = 0; break;
604 case 'K': verifypolicy = 2; break;
605 case 'U': user_agent = optarg; break;
607 case 'r': raw = 1; break;
608 case 'f': failsilent = 1; break;
609 case 'z': lmfile = optarg; break;
610 case 'n': ifnewer = 1; break;
611 case 'R': redirlimit = strtol(optarg, 0, 10); break;
613 case '#': progressbar = 1; break;
621 fprintf(stderr, "Usage: %s uri\n", av[0]);
625 url = strdup(av[optind]);
630 io.last_modified = 0;
632 if (calcoutfile && !outfile) {
633 tls_parse_uri(url, &uri);
634 outfile = pathlast(uri.path);
635 /* outfile leaks memory here, so if this
636 * were turned into a library function,
637 * we'd need to track it
640 fprintf(stderr, "unable to determine outfile\n");
645 if (ifnewer && outfile && !lmfile) {
653 ts = file_mtime(lmfile);
657 } else if (ts != 0) {
658 io.last_modified = ts;
660 strftime(lmtime, sizeof lmtime, "%a, %d %b %Y %H:%M:%S GMT", mtime);
666 signal(SIGPIPE, SIG_IGN);
668 tls_buffer_init(&io.response, 0);
669 tls_buffer_init(&request, 128);
671 while (redirs++ <= redirlimit) {
677 tls_parse_uri(url, &uri);
679 port = atoi(uri.port);
682 /* construct request */
684 tls_buffer_append(&request, "HEAD ", 5);
686 tls_buffer_append(&request, "GET ", 4);
688 tls_buffer_append(&request, uri.encoded_path, strlen(uri.encoded_path));
689 if (uri.encoded_query) {
690 tls_buffer_append(&request, "?", 1);
691 tls_buffer_append(&request, uri.encoded_query, strlen(uri.encoded_query));
693 tls_buffer_append(&request, " HTTP/1.1\r\n", 11);
695 append_header(&request, "Host", host);
697 append_header(&request, "User-Agent", user_agent);
699 append_header(&request, "Accept", "*/*");
700 append_header(&request, "Connection", "close");
702 append_header(&request, "If-Modified-Since", lmtime);
704 tls_buffer_append(&request, "\r\n", 2);
706 if (!strcmp(uri.scheme, "https")) {
709 clientssl = tls_create_context(TLS_CLIENT, TLS_V12);
711 /* optionally, we can set a certificate validation
712 * callback function if set_verify is not called, and
713 * root ca is set, `tls_default_verify` will be used
714 * (does exactly what `verify` does in this example)
716 if (verifypolicy == 2) {
718 cert_path = getenv("ZPM_CERTFILE");
720 cert_path = "/var/lib/zpm/roots.pem";
722 rv = tls_load_root_file(clientssl, cert_path);
724 fprintf(stderr, "Error loading root certs\n");
727 tls_set_verify(clientssl, verify_roots);
728 } else if (verifypolicy == 1) {
729 tls_set_verify(clientssl, verify_first);
731 tls_set_verify(clientssl, verify_trust);
735 fprintf(stderr, "Error initializing client context\n");
738 tls_sni_set(clientssl, uri.host);
741 sockfd = open_tcp_connection(host, port);
743 perror("can't open connection");
746 tls_set_fd(clientssl, sockfd);
747 if ((rv = tls_connect(clientssl)) != 1) {
748 fprintf(stderr, "Handshake Error %i\n", rv);
751 ret = tls_write(clientssl, request.buffer, request.len);
752 } else if (!strcmp(uri.scheme, "http")) {
753 sockfd = open_tcp_connection(host, port);
755 perror("can't open connection");
758 ret = write(sockfd, request.buffer, request.len);
759 } else if (!strcmp(uri.scheme, "file")) {
760 sockfd = open(uri.path, O_RDONLY);
761 fake_header(&io, sockfd);
764 fprintf(stderr, "scheme %s unknown\n", uri.scheme);
769 fprintf(stderr, "unable to write http request: %s\n", strerror(errno));
777 if (io.response.len >= 4) {
778 eoh = strstr(io.response.buffer, "\r\n\r\n");
781 ret = fill_buffer(&io);
789 /* never got (complete) header */
790 fprintf(stderr, "incomplete response (ret = %zd) to %s\n", ret, url);
791 fprintf(stderr, "have:\n");
792 fwrite(io.response.buffer, io.response.len, 1, stderr);
796 header_len = (size_t)(eoh - io.response.buffer) + 4;
799 switch (io.status_code) {
808 url = strdup(io.redirect);
815 printf("%d\n", io.status_code);
820 tls_buffer_shift(&io.response, header_len);
823 io.response.len -= 2;
827 if (io.content_length) {
828 fprintf(stderr, "(%lu) ", io.content_length);
833 out = open(outfile, O_WRONLY|O_CREAT, 0600);
835 perror("can't open output file:");
841 write(out, io.response.buffer, io.response.len);
842 ret = io.response.len;
846 if (io.content_length) {
847 pdots(50, '.', total, total+ret,
851 fprintf(stderr, "%zu", total+ret);
858 ret = fill_buffer(&io);
862 fprintf(stderr, "%s read error %zd\n", uri.scheme, ret);
864 struct timespec ts[2];
865 ts[0].tv_sec = 0; ts[0].tv_nsec = UTIME_OMIT;
866 ts[1].tv_sec = io.last_modified;
871 tls_buffer_free(&io.response);
876 tls_shutdown(clientssl);
881 if (progressbar && io.status_code == 200) {
882 fprintf(stderr, "(%lu)", total);
886 return io.status_code < 400 ? 0 : EXIT_FAILURE;