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);
210 fprintf(stderr, "host %s certificate changed\n", host);
211 fprintf(stderr, "was %.64s\n", fp);
212 fprintf(stderr, "now %.64s\n", certhash);
216 tls_buffer_free(&tbuf);
217 return match ? no_error : bad_certificate;
218 } while (!tbuf.error);
220 /* got here, so we should be at EOF, so add this host to trust db */
221 lseek(trustdb, 0, SEEK_END);
223 /* re-use the buffer so we only do one write */
224 /* ignore errors, the cert is fine, we just can't update
225 * the trustdb if there's errors here
228 tls_buffer_append(&tbuf, certhash, 64);
229 tls_buffer_append_byte(&tbuf, ':');
230 tls_buffer_append(&tbuf, context->sni, strlen(context->sni));
231 tls_buffer_append_byte(&tbuf, '\n');
232 write(trustdb, tbuf.buffer, tbuf.len);
234 tls_buffer_free(&tbuf);
239 int verify_roots(struct TLSContext *context, struct TLSCertificate **chain, int
244 for (i = 0; i < len; i++) {
245 struct TLSCertificate *certificate = chain[i];
246 err = tls_certificate_is_valid(certificate);
253 err = tls_certificate_chain_is_valid(chain, len);
258 if (len > 0 && context->sni) {
259 err = tls_certificate_valid_subject(chain[0], context->sni);
265 /* Perform certificate validation against ROOT CA */
266 err = tls_certificate_chain_is_valid_root(context, chain, len);
275 struct tls_buffer response;
276 struct TLSContext *tls;
279 time_t last_modified;
281 size_t content_length;
286 char *months[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul",
287 "Aug", "Sep", "Oct", "Nov", "Dec" };
290 for (i=0; i < 12; i++) {
291 if (!strncasecmp(m, months[i], 3)) {
298 /* Wed, 06 Feb 2019 10:06:05 GMT */
299 time_t parse_date(char *d) {
300 struct tm tm = { 0 };
305 rv = sscanf(d, "%*[a-zA-Z,] %d %s %d %d:%d:%d", &dom, M, &Y, &h, &m, &s);
307 tm.tm_year = Y - 1900;
311 tm.tm_mon = month(M)-1;
319 char *find_header(struct io *io, char *header, size_t *len) {
325 hlen = strlen(header);
326 eoh = strstr(io->response.buffer, "\r\n\r\n");
330 soh = io->response.buffer;
332 soh = strstr(soh, "\r\n");
337 if (!memcmp(soh, header, hlen)) {
345 eoh = strstr(soh, "\r\n");
347 while (soh < eoh && isspace(*soh)) {
354 void parse_header(struct io *io) {
355 char *s = io->response.buffer;
360 while (!isspace(*s)) {
363 while (isspace(*s)) {
366 code = strtol(s, 0, 10);
367 io->status_code = code;
369 hval = find_header(io, "Date:", &hlen);
372 io->date = parse_date(hval);
375 hval = find_header(io, "Last-Modified:", &hlen);
378 io->last_modified = parse_date(hval);
382 hval = find_header(io, "Content-Length:", &hlen);
385 io->content_length = strtoul(hval, 0, 10);
394 hval = find_header(io, "Location:", &hlen);
396 io->redirect = strndup(hval, hlen);
405 ssize_t fill_buffer(struct io *io) {
406 unsigned char buffer[4096];
410 ret = tls_read(io->tls, buffer, sizeof buffer);
412 ret = read(io->socket, buffer, sizeof buffer);
416 tls_buffer_append(&io->response, buffer, ret);
423 char *nextline(struct io *io) {
426 eol = memchr(io->response.buffer, '\n', io.response.size);
429 eol = memchr(io->response.buffer, '\n', io.response.size);
436 void append_header(struct tls_buffer *buf, char *header, char *val) {
437 tls_buffer_append(buf, header, strlen(header));
438 tls_buffer_append(buf, ": ", 2);
439 tls_buffer_append(buf, val, strlen(val));
440 tls_buffer_append(buf, "\r\n", 2);
443 void append_timeheader(struct tls_buffer *buf, char *header, time_t ts) {
449 strftime(timestr, sizeof timestr, "%a, %d %b %Y %H:%M:%S GMT", tm);
450 append_header(buf, header, timestr);
453 static void pdots(int len, int ch, unsigned long was, unsigned long now,
454 unsigned long total) {
455 was = len * was / total;
459 now = len * now / total;
460 while (was++ < now) {
465 static void fake_header(struct io *io, int fd) {
468 char *message, codestr[5], length[32];
469 struct tls_buffer *hdr = &io->response;
473 case EACCES: code = 403; break;
474 case ENOENT: code = 404; break;
475 default: code = 500; break;
484 if (io->last_modified >= st.st_mtime) {
489 case 200: message = "OK"; break;
490 case 304: message = "Not Modified"; break;
491 case 403: message = "Forbidden"; break;
492 case 404: message = "Not Found"; break;
493 case 500: message = "Internal Server Error"; break;
496 sprintf(codestr, "%0.3d ", code);
497 tls_buffer_append(hdr, "HTTP/1.1 ", 9);
498 tls_buffer_append(hdr, codestr, 4);
499 tls_buffer_append_str(hdr, message);
500 tls_buffer_append(hdr, "\r\n", 2);
502 append_timeheader(hdr, "Date", time(NULL));
503 append_header(hdr, "Server", "zpm-fetchurl/0.9");
505 append_timeheader(hdr, "Last-Modified", st.st_mtime);
506 sprintf(length, "%zu", st.st_size);
507 append_header(hdr, "Content-Length", length);
510 append_header(hdr, "Connection", "close");
511 append_header(hdr, "Content-Type", "application/octet-stream");
512 tls_buffer_append(hdr, "\r\n", 2);
515 char *pathlast(char *path) {
523 while (*path == '/') {
530 while (*path && *path != '/') {
534 while (*path == '/') {
543 return strndup(last, len);
546 static time_t file_mtime(char *path) {
550 rv = stat(path, &st);
552 if (errno == ENOENT) {
555 perror("stat failed:");
562 int main(int ac, char *av[]) {
563 int sockfd, port = -1, rv;
567 char msg[] = "GET %s HTTP/1.1\r\nHost: %s:%i\r\nConnection: close\r\n\r\n";
568 char msg2[] = "GET %s HTTP/1.1\r\nHost: %s:%i\r\nLast-Modified: %s\r\nConnection: close\r\n\r\n";
569 char msg_buffer[1024];
573 struct tls_uri uri = { 0 };
575 int raw = 0, head = 0;
576 int out = 1; /* output file descriptor */
578 struct io io = { {0}, 0, -1, 0, 0, 0, 0, 0 };
579 struct TLSContext *clientssl = 0;
583 struct tls_buffer request;
589 int redirs = 0, redirlimit = 50, printstatus = 0;
590 int verifypolicy = 1, calcoutfile = 0, ifnewer = 0;
594 while ((option = getopt(ac, av, "o:OrIfz:np#R:SkK")) != -1) {
596 case 'o': outfile = optarg; break;
597 case 'O': calcoutfile = 1; break;
598 case 'S': printstatus = 1; head = 1; break;
599 case 'k': verifypolicy = 0; break;
600 case 'K': verifypolicy = 2; break;
602 case 'r': raw = 1; break;
603 case 'f': failsilent = 1; break;
604 case 'z': lmfile = optarg; break;
605 case 'n': ifnewer = 1; break;
606 case 'R': redirlimit = strtol(optarg, 0, 10); break;
608 case '#': progressbar = 1; break;
616 fprintf(stderr, "Usage: %s uri\n", av[0]);
620 url = strdup(av[optind]);
625 io.last_modified = 0;
627 if (calcoutfile && !outfile) {
628 tls_parse_uri(url, &uri);
629 outfile = pathlast(uri.path);
630 /* outfile leaks memory here, so if this
631 * were turned into a library function,
632 * we'd need to track it
635 fprintf(stderr, "unable to determine outfile\n");
640 if (ifnewer && outfile && !lmfile) {
648 ts = file_mtime(lmfile);
652 } else if (ts != 0) {
653 io.last_modified = ts;
655 strftime(lmtime, sizeof lmtime, "%a, %d %b %Y %H:%M:%S GMT", mtime);
661 signal(SIGPIPE, SIG_IGN);
663 tls_buffer_init(&io.response, 0);
664 tls_buffer_init(&request, 128);
666 while (redirs++ <= redirlimit) {
672 tls_parse_uri(url, &uri);
674 port = atoi(uri.port);
677 /* construct request */
679 tls_buffer_append(&request, "HEAD ", 5);
681 tls_buffer_append(&request, "GET ", 4);
683 tls_buffer_append(&request, uri.path, strlen(uri.path));
684 tls_buffer_append(&request, " HTTP/1.1\r\n", 11);
686 append_header(&request, "Host", host);
687 append_header(&request, "Connection", "close");
689 append_header(&request, "If-Modified-Since", lmtime);
691 tls_buffer_append(&request, "\r\n", 2);
693 if (!strcmp(uri.scheme, "https")) {
696 clientssl = tls_create_context(TLS_CLIENT, TLS_V12);
698 /* optionally, we can set a certificate validation
699 * callback function if set_verify is not called, and
700 * root ca is set, `tls_default_verify` will be used
701 * (does exactly what `verify` does in this example)
703 if (verifypolicy == 2) {
705 cert_path = getenv("ZPM_CERTFILE");
707 cert_path = "/var/lib/zpm/roots.pem";
709 rv = tls_load_root_file(clientssl, cert_path);
711 fprintf(stderr, "Error loading root certs\n");
714 tls_set_verify(clientssl, verify_roots);
715 } else if (verifypolicy == 1) {
716 tls_set_verify(clientssl, verify_first);
718 tls_set_verify(clientssl, verify_trust);
722 fprintf(stderr, "Error initializing client context\n");
725 tls_sni_set(clientssl, uri.host);
728 sockfd = open_tcp_connection(host, port);
730 perror("can't open connection");
733 tls_set_fd(clientssl, sockfd);
734 if ((rv = tls_connect(clientssl)) != 1) {
735 fprintf(stderr, "Handshake Error %i\n", rv);
738 ret = tls_write(clientssl, request.buffer, request.len);
739 } else if (!strcmp(uri.scheme, "http")) {
740 sockfd = open_tcp_connection(host, port);
742 perror("can't open connection");
745 ret = write(sockfd, request.buffer, request.len);
746 } else if (!strcmp(uri.scheme, "file")) {
747 sockfd = open(uri.path, O_RDONLY);
748 fake_header(&io, sockfd);
751 fprintf(stderr, "scheme %s unknown\n", uri.scheme);
756 fprintf(stderr, "unable to write http request: %s\n", strerror(errno));
763 if (io.response.len >= 4) {
764 eoh = strstr(io.response.buffer, "\r\n\r\n");
767 ret = fill_buffer(&io);
775 /* never got (complet) header */
776 fprintf(stderr, "incomplete response to %s\n", av[optind]);
780 header_len = (size_t)(eoh - io.response.buffer) + 4;
783 switch (io.status_code) {
792 url = strdup(io.redirect);
799 printf("%d\n", io.status_code);
804 tls_buffer_shift(&io.response, header_len);
807 io.response.len -= 2;
811 if (io.content_length) {
812 fprintf(stderr, "(%lu) ", io.content_length);
817 out = open(outfile, O_WRONLY|O_CREAT, 0600);
819 perror("can't open output file:");
825 write(out, io.response.buffer, io.response.len);
826 ret = io.response.len;
830 if (io.content_length) {
831 pdots(50, '.', total, total+ret,
835 fprintf(stderr, "%zu", total+ret);
842 ret = fill_buffer(&io);
846 fprintf(stderr, "%s read error %zd\n", uri.scheme, ret);
848 struct timespec ts[2];
849 ts[0].tv_sec = 0; ts[0].tv_nsec = UTIME_OMIT;
850 ts[1].tv_sec = io.last_modified;
855 tls_buffer_free(&io.response);
860 tls_shutdown(clientssl);
865 if (progressbar && io.status_code == 200) {
866 fprintf(stderr, "(%lu)", total);
870 return io.status_code < 400 ? 0 : EXIT_FAILURE;