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);
212 return match ? no_error : bad_certificate;
213 } while (!tbuf.error);
215 /* got here, so we should be at EOF, so add this host to trust db */
216 lseek(trustdb, 0, SEEK_END);
218 /* re-use the buffer so we only do one write */
219 /* ignore errors, the cert is fine, we just can't update
220 * the trustdb if there's errors here
223 tls_buffer_append(&tbuf, certhash, 64);
224 tls_buffer_append_byte(&tbuf, ':');
225 tls_buffer_append(&tbuf, context->sni, strlen(context->sni));
226 tls_buffer_append_byte(&tbuf, '\n');
227 write(trustdb, tbuf.buffer, tbuf.len);
229 tls_buffer_free(&tbuf);
234 int verify_roots(struct TLSContext *context, struct TLSCertificate **chain, int
239 for (i = 0; i < len; i++) {
240 struct TLSCertificate *certificate = chain[i];
241 err = tls_certificate_is_valid(certificate);
248 err = tls_certificate_chain_is_valid(chain, len);
253 if (len > 0 && context->sni) {
254 err = tls_certificate_valid_subject(chain[0], context->sni);
260 /* Perform certificate validation against ROOT CA */
261 err = tls_certificate_chain_is_valid_root(context, chain, len);
270 struct tls_buffer response;
271 struct TLSContext *tls;
274 time_t last_modified;
276 size_t content_length;
281 char *months[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul",
282 "Aug", "Sep", "Oct", "Nov", "Dec" };
285 for (i=0; i < 12; i++) {
286 if (!strncasecmp(m, months[i], 3)) {
293 /* Wed, 06 Feb 2019 10:06:05 GMT */
294 time_t parse_date(char *d) {
295 struct tm tm = { 0 };
300 rv = sscanf(d, "%*[a-zA-Z,] %d %s %d %d:%d:%d", &dom, M, &Y, &h, &m, &s);
302 tm.tm_year = Y - 1900;
306 tm.tm_mon = month(M)-1;
314 char *find_header(struct io *io, char *header, size_t *len) {
320 hlen = strlen(header);
321 eoh = strstr(io->response.buffer, "\r\n\r\n");
325 soh = io->response.buffer;
327 soh = strstr(soh, "\r\n");
332 if (!memcmp(soh, header, hlen)) {
340 eoh = strstr(soh, "\r\n");
342 while (soh < eoh && isspace(*soh)) {
349 void parse_header(struct io *io) {
350 char *s = io->response.buffer;
355 while (!isspace(*s)) {
358 while (isspace(*s)) {
361 code = strtol(s, 0, 10);
362 io->status_code = code;
364 hval = find_header(io, "Date:", &hlen);
367 io->date = parse_date(hval);
370 hval = find_header(io, "Last-Modified:", &hlen);
373 io->last_modified = parse_date(hval);
377 hval = find_header(io, "Content-Length:", &hlen);
380 io->content_length = strtoul(hval, 0, 10);
389 hval = find_header(io, "Location:", &hlen);
391 io->redirect = strndup(hval, hlen);
400 ssize_t fill_buffer(struct io *io) {
401 unsigned char buffer[4096];
405 ret = tls_read(io->tls, buffer, sizeof buffer);
407 ret = read(io->socket, buffer, sizeof buffer);
411 tls_buffer_append(&io->response, buffer, ret);
418 char *nextline(struct io *io) {
421 eol = memchr(io->response.buffer, '\n', io.response.size);
424 eol = memchr(io->response.buffer, '\n', io.response.size);
431 void append_header(struct tls_buffer *buf, char *header, char *val) {
432 tls_buffer_append(buf, header, strlen(header));
433 tls_buffer_append(buf, ": ", 2);
434 tls_buffer_append(buf, val, strlen(val));
435 tls_buffer_append(buf, "\r\n", 2);
438 void append_timeheader(struct tls_buffer *buf, char *header, time_t ts) {
444 strftime(timestr, sizeof timestr, "%a, %d %b %Y %H:%M:%S GMT", tm);
445 append_header(buf, header, timestr);
448 static void pdots(int len, int ch, unsigned long was, unsigned long now,
449 unsigned long total) {
450 was = len * was / total;
454 now = len * now / total;
455 while (was++ < now) {
460 static void fake_header(struct io *io, int fd) {
463 char *message, codestr[5], length[32];
464 struct tls_buffer *hdr = &io->response;
468 case EACCES: code = 403; break;
469 case ENOENT: code = 404; break;
470 default: code = 500; break;
479 if (io->last_modified >= st.st_mtime) {
484 case 200: message = "OK"; break;
485 case 304: message = "Not Modified"; break;
486 case 403: message = "Forbidden"; break;
487 case 404: message = "Not Found"; break;
488 case 500: message = "Internal Server Error"; break;
491 sprintf(codestr, "%0.3d ", code);
492 tls_buffer_append(hdr, "HTTP/1.1 ", 9);
493 tls_buffer_append(hdr, codestr, 4);
494 tls_buffer_append_str(hdr, message);
495 tls_buffer_append(hdr, "\r\n", 2);
497 append_timeheader(hdr, "Date", time(NULL));
498 append_header(hdr, "Server", "zpm-fetchurl/0.9");
500 append_timeheader(hdr, "Last-Modified", st.st_mtime);
501 sprintf(length, "%zu", st.st_size);
502 append_header(hdr, "Content-Length", length);
505 append_header(hdr, "Connection", "close");
506 append_header(hdr, "Content-Type", "application/octet-stream");
507 tls_buffer_append(hdr, "\r\n", 2);
510 char *pathlast(char *path) {
518 while (*path == '/') {
525 while (*path && *path != '/') {
529 while (*path == '/') {
538 return strndup(last, len);
541 static time_t file_mtime(char *path) {
545 rv = stat(path, &st);
547 if (errno == ENOENT) {
550 perror("stat failed:");
557 int main(int ac, char *av[]) {
558 int sockfd, port = -1, rv;
562 char msg[] = "GET %s HTTP/1.1\r\nHost: %s:%i\r\nConnection: close\r\n\r\n";
563 char msg2[] = "GET %s HTTP/1.1\r\nHost: %s:%i\r\nLast-Modified: %s\r\nConnection: close\r\n\r\n";
564 char msg_buffer[1024];
568 struct tls_uri uri = { 0 };
570 int raw = 0, head = 0;
571 int out = 1; /* output file descriptor */
573 struct io io = { {0}, 0, -1, 0, 0, 0, 0, 0 };
574 struct TLSContext *clientssl = 0;
578 struct tls_buffer request;
584 int redirs = 0, redirlimit = 50, printstatus = 0;
585 int verifypolicy = 1, calcoutfile = 0, ifnewer = 0;
589 while ((option = getopt(ac, av, "o:OrIfz:np#R:SkK")) != -1) {
591 case 'o': outfile = optarg; break;
592 case 'O': calcoutfile = 1; break;
593 case 'S': printstatus = 1; head = 1; break;
594 case 'k': verifypolicy = 0; break;
595 case 'K': verifypolicy = 2; break;
597 case 'r': raw = 1; break;
598 case 'f': failsilent = 1; break;
599 case 'z': lmfile = optarg; break;
600 case 'n': ifnewer = 1; break;
601 case 'R': redirlimit = strtol(optarg, 0, 10); break;
603 case '#': progressbar = 1; break;
611 fprintf(stderr, "Usage: %s uri\n", av[0]);
615 url = strdup(av[optind]);
620 io.last_modified = 0;
622 if (calcoutfile && !outfile) {
623 tls_parse_uri(url, &uri);
624 outfile = pathlast(uri.path);
625 /* outfile leaks memory here, so if this
626 * were turned into a library function,
627 * we'd need to track it
630 fprintf(stderr, "unable to determine outfile\n");
635 if (ifnewer && outfile && !lmfile) {
643 ts = file_mtime(lmfile);
647 } else if (ts != 0) {
648 io.last_modified = ts;
650 strftime(lmtime, sizeof lmtime, "%a, %d %b %Y %H:%M:%S GMT", mtime);
656 signal(SIGPIPE, SIG_IGN);
658 tls_buffer_init(&io.response, 0);
659 tls_buffer_init(&request, 128);
661 while (redirs++ <= redirlimit) {
667 tls_parse_uri(url, &uri);
669 port = atoi(uri.port);
672 /* construct request */
674 tls_buffer_append(&request, "HEAD ", 5);
676 tls_buffer_append(&request, "GET ", 4);
678 tls_buffer_append(&request, uri.path, strlen(uri.path));
679 tls_buffer_append(&request, " HTTP/1.1\r\n", 11);
681 append_header(&request, "Host", host);
682 append_header(&request, "Connection", "close");
684 append_header(&request, "If-Modified-Since", lmtime);
686 tls_buffer_append(&request, "\r\n", 2);
688 if (!strcmp(uri.scheme, "https")) {
691 clientssl = tls_create_context(TLS_CLIENT, TLS_V12);
693 /* optionally, we can set a certificate validation
694 * callback function if set_verify is not called, and
695 * root ca is set, `tls_default_verify` will be used
696 * (does exactly what `verify` does in this example)
698 if (verifypolicy == 2) {
700 cert_path = getenv("ZPM_CERTFILE");
702 cert_path = "/var/lib/zpm/roots.pem";
704 rv = tls_load_root_file(clientssl, cert_path);
706 fprintf(stderr, "Error loading root certs\n");
709 tls_set_verify(clientssl, verify_roots);
710 } else if (verifypolicy == 1) {
711 tls_set_verify(clientssl, verify_first);
713 tls_set_verify(clientssl, verify_trust);
717 fprintf(stderr, "Error initializing client context\n");
720 tls_sni_set(clientssl, uri.host);
723 sockfd = open_tcp_connection(host, port);
725 perror("can't open connection");
728 tls_set_fd(clientssl, sockfd);
729 if ((rv = tls_connect(clientssl)) != 1) {
730 fprintf(stderr, "Handshake Error %i\n", rv);
733 ret = tls_write(clientssl, request.buffer, request.len);
734 } else if (!strcmp(uri.scheme, "http")) {
735 sockfd = open_tcp_connection(host, port);
737 perror("can't open connection");
740 ret = write(sockfd, request.buffer, request.len);
741 } else if (!strcmp(uri.scheme, "file")) {
742 sockfd = open(uri.path, O_RDONLY);
743 fake_header(&io, sockfd);
746 fprintf(stderr, "scheme %s unknown\n", uri.scheme);
751 fprintf(stderr, "unable to write http request: %s\n", strerror(errno));
758 if (io.response.len >= 4) {
759 eoh = strstr(io.response.buffer, "\r\n\r\n");
762 ret = fill_buffer(&io);
770 /* never got (complet) header */
771 fprintf(stderr, "incomplete response to %s\n", av[optind]);
775 header_len = (size_t)(eoh - io.response.buffer) + 4;
778 switch (io.status_code) {
787 url = strdup(io.redirect);
794 printf("%d\n", io.status_code);
799 tls_buffer_shift(&io.response, header_len);
802 io.response.len -= 2;
806 if (io.content_length) {
807 fprintf(stderr, "(%lu) ", io.content_length);
812 out = open(outfile, O_WRONLY|O_CREAT, 0600);
814 perror("can't open output file:");
820 write(out, io.response.buffer, io.response.len);
821 ret = io.response.len;
825 if (io.content_length) {
826 pdots(50, '.', total, total+ret,
830 fprintf(stderr, "%zu", total+ret);
837 ret = fill_buffer(&io);
841 fprintf(stderr, "%s read error %zd\n", uri.scheme, ret);
843 struct timespec ts[2];
844 ts[0].tv_sec = 0; ts[0].tv_nsec = UTIME_OMIT;
845 ts[1].tv_sec = io.last_modified;
850 tls_buffer_free(&io.response);
855 tls_shutdown(clientssl);
860 if (progressbar && io.status_code == 200) {
861 fprintf(stderr, "(%lu)", total);
865 return io.status_code < 400 ? 0 : EXIT_FAILURE;