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 tls_buffer chunkbuf;
280 struct TLSContext *tls;
287 size_t chunkbytesread;
289 time_t last_modified;
291 size_t content_length;
295 ssize_t unchunk(struct io *io);
298 char *months[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul",
299 "Aug", "Sep", "Oct", "Nov", "Dec" };
302 for (i=0; i < 12; i++) {
303 if (!strncasecmp(m, months[i], 3)) {
310 /* Wed, 06 Feb 2019 10:06:05 GMT */
311 time_t parse_date(char *d) {
312 struct tm tm = { 0 };
317 rv = sscanf(d, "%*[a-zA-Z,] %d %s %d %d:%d:%d", &dom, M, &Y, &h, &m, &s);
319 tm.tm_year = Y - 1900;
323 tm.tm_mon = month(M)-1;
331 char *find_header(struct io *io, char *header, size_t *len) {
337 hlen = strlen(header);
338 eoh = strstr(io->response.buffer, "\r\n\r\n");
342 soh = io->response.buffer;
344 soh = strstr(soh, "\r\n");
349 if (!memcmp(soh, header, hlen)) {
357 eoh = strstr(soh, "\r\n");
359 while (soh < eoh && isspace(*soh)) {
366 void parse_header(struct io *io) {
367 char *s = io->response.buffer;
372 while (!isspace(*s)) {
375 while (isspace(*s)) {
378 code = strtol(s, 0, 10);
379 io->status_code = code;
381 hval = find_header(io, "Date:", &hlen);
384 io->date = parse_date(hval);
387 hval = find_header(io, "Last-Modified:", &hlen);
390 io->last_modified = parse_date(hval);
394 hval = find_header(io, "Content-Length:", &hlen);
397 io->content_length = strtoul(hval, 0, 10);
401 hval = find_header(io, "Transfer-Encoding:", &hlen);
404 io->content_length = strtoul(hval, 0, 10);
405 if (!strcmp(hval, "chunked")) {
416 hval = find_header(io, "Location:", &hlen);
418 io->redirect = strndup(hval, hlen);
427 /* fill buffer needs to put bytes into the response buffer
428 * if the transfer encoding is chunked, it will need to
429 * put the bytes into the chunkbuf first, then call
430 * unchunk. if unchunk return 0, then it needs more data,
431 * otherwise unchunk returns the number of bytes transferred
434 ssize_t fill_buffer(struct io *io) {
435 unsigned char buffer[4096];
442 ret = tls_read(io->tls, buffer, sizeof buffer);
444 ret = read(io->socket, buffer, sizeof buffer);
452 tls_buffer_append(&io->chunkbuf, buffer, ret);
453 //fwrite(buffer, ret, 1, stderr);
455 if (ret != 0 || io->chunksize == 0) {
459 tls_buffer_append(&io->response, buffer, ret);
464 fprintf(stderr, "filled %zd bytes\n", ret);
468 /* essentially memmem */
469 void *lookfor(const void *buf, size_t buflen, const void *pattern, size_t len) {
470 const char *bf = buf;
471 const char *pt = pattern;
474 while (len <= (buflen - (p - bf))) {
475 if ((p = memchr(p, *pt, buflen - (p - bf))) != 0) {
476 if (memcmp(p, pattern, len) == 0) {
488 /* returns read chunksize, unshifts the line */
489 ssize_t read_chunksize(struct io *io) {
493 //fwrite(io->chunkbuf.buffer, io->chunkbuf.len, 1, stderr);
495 /* there could be up to two leading bytes */
496 if (io->chunkbuf.len >= 2 && io->chunkbuf.buffer[0] == '\r' && io->chunkbuf.buffer[1] == '\n') {
497 tls_buffer_shift(&io->chunkbuf, 2);
500 cr = lookfor(io->chunkbuf.buffer, io->chunkbuf.len, "\r\n", 2);
506 cs = strtol(io->chunkbuf.buffer, 0, 16);
507 tls_buffer_shift(&io->chunkbuf, cr - io->chunkbuf.buffer + 2);
512 /* unchunk's job is to move bytes from the chunk buf to the response buf */
513 /* return bytes from chunk, 0 if unable. once last chunk, changed chunked
516 ssize_t unchunk(struct io *io) {
517 ssize_t bytes_to_move = 0;
520 if (!io || !io->chunked) {
524 if (io->chunkleft == 0) {
525 chunksize = read_chunksize(io);
526 if (chunksize == -1) {
529 io->chunksize = chunksize;
530 if (io->chunksize == 0) {
531 /* end of chunked data */
536 io->chunkleft = io->chunksize;
537 io->chunktotal += io->chunksize;
540 if (io->chunkbuf.len == 0) {
541 /* need more bytes */
545 bytes_to_move = io->chunkbuf.len < io->chunkleft ? io->chunkbuf.len : io->chunkleft;
547 tls_buffer_append(&io->response, io->chunkbuf.buffer, bytes_to_move);
548 io->chunkleft -= bytes_to_move;
549 io->chunkbytesread += bytes_to_move;
551 /* chunk is terminated with a crlf */
552 //tls_buffer_shift(&io->chunkbuf, bytes_to_move + io->chunkleft ? 0 : 2);
553 tls_buffer_shift(&io->chunkbuf, bytes_to_move);
555 return bytes_to_move;
559 char *nextline(struct io *io) {
562 eol = memchr(io->response.buffer, '\n', io.response.size);
565 eol = memchr(io->response.buffer, '\n', io.response.size);
572 void append_header(struct tls_buffer *buf, char *header, char *val) {
573 tls_buffer_append(buf, header, strlen(header));
574 tls_buffer_append(buf, ": ", 2);
575 tls_buffer_append(buf, val, strlen(val));
576 tls_buffer_append(buf, "\r\n", 2);
579 void append_timeheader(struct tls_buffer *buf, char *header, time_t ts) {
585 strftime(timestr, sizeof timestr, "%a, %d %b %Y %H:%M:%S GMT", tm);
586 append_header(buf, header, timestr);
589 static void pdots(int len, int ch, unsigned long was, unsigned long now,
590 unsigned long total) {
591 was = len * was / total;
595 now = len * now / total;
596 while (was++ < now) {
601 static void fake_header(struct io *io, int fd) {
604 char *message, codestr[5], length[32];
605 struct tls_buffer *hdr = &io->response;
609 case EACCES: code = 403; break;
610 case ENOENT: code = 404; break;
611 default: code = 500; break;
620 if (io->last_modified >= st.st_mtime) {
625 case 200: message = "OK"; break;
626 case 304: message = "Not Modified"; break;
627 case 403: message = "Forbidden"; break;
628 case 404: message = "Not Found"; break;
629 case 500: message = "Internal Server Error"; break;
632 sprintf(codestr, "%0.3d ", code);
633 tls_buffer_append(hdr, "HTTP/1.1 ", 9);
634 tls_buffer_append(hdr, codestr, 4);
635 tls_buffer_append_str(hdr, message);
636 tls_buffer_append(hdr, "\r\n", 2);
638 append_timeheader(hdr, "Date", time(NULL));
639 append_header(hdr, "Server", "zpm-fetchurl/0.9");
641 append_timeheader(hdr, "Last-Modified", st.st_mtime);
642 sprintf(length, "%zu", st.st_size);
643 append_header(hdr, "Content-Length", length);
646 append_header(hdr, "Connection", "close");
647 append_header(hdr, "Content-Type", "application/octet-stream");
648 tls_buffer_append(hdr, "\r\n", 2);
651 char *pathlast(char *path) {
659 while (*path == '/') {
666 while (*path && *path != '/') {
670 while (*path == '/') {
679 return strndup(last, len);
682 static time_t file_mtime(char *path) {
686 rv = stat(path, &st);
688 if (errno == ENOENT) {
691 perror("stat failed:");
698 int main(int ac, char *av[]) {
699 int sockfd, port = -1, rv;
703 char msg[] = "GET %s HTTP/1.1\r\nHost: %s:%i\r\nConnection: close\r\n\r\n";
704 char msg2[] = "GET %s HTTP/1.1\r\nHost: %s:%i\r\nLast-Modified: %s\r\nConnection: close\r\n\r\n";
705 char msg_buffer[1024];
709 struct tls_uri uri = { 0 };
711 int raw = 0, head = 0;
712 int out = 1; /* output file descriptor */
714 struct io io = { {0}, {0}, 0, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
715 struct TLSContext *clientssl = 0;
719 struct tls_buffer request;
722 char *user_agent = 0;
726 int redirs = 0, redirlimit = 50, printstatus = 0, showreq = 0;
727 int verifypolicy = 1, calcoutfile = 0, ifnewer = 0;
731 while ((option = getopt(ac, av, "o:OrIfz:np#RL:SkKU:")) != -1) {
733 case 'o': outfile = optarg; break;
734 case 'O': calcoutfile = 1; break;
735 case 'S': printstatus = 1; head = 1; break;
736 case 'k': verifypolicy = 0; break;
737 case 'K': verifypolicy = 2; break;
738 case 'U': user_agent = optarg; break;
740 case 'r': raw = 1; break;
741 case 'R': showreq = 1; break;
742 case 'f': failsilent = 1; break;
743 case 'z': lmfile = optarg; break;
744 case 'n': ifnewer = 1; break;
745 case 'L': redirlimit = strtol(optarg, 0, 10); break;
747 case '#': progressbar = 1; break;
755 fprintf(stderr, "Usage: %s uri\n", av[0]);
759 url = strdup(av[optind]);
764 io.last_modified = 0;
766 if (calcoutfile && !outfile) {
767 tls_parse_uri(url, &uri);
768 outfile = pathlast(uri.path);
769 /* outfile leaks memory here, so if this
770 * were turned into a library function,
771 * we'd need to track it
774 fprintf(stderr, "unable to determine outfile\n");
779 if (ifnewer && outfile && !lmfile) {
787 ts = file_mtime(lmfile);
791 } else if (ts != 0) {
792 io.last_modified = ts;
794 strftime(lmtime, sizeof lmtime, "%a, %d %b %Y %H:%M:%S GMT", mtime);
800 signal(SIGPIPE, SIG_IGN);
802 tls_buffer_init(&io.response, 0);
803 tls_buffer_init(&request, 128);
805 while (redirs++ <= redirlimit) {
812 tls_parse_uri(url, &uri);
814 port = atoi(uri.port);
817 /* construct request */
819 tls_buffer_append(&request, "HEAD ", 5);
821 tls_buffer_append(&request, "GET ", 4);
823 tls_buffer_append(&request, uri.encoded_path, strlen(uri.encoded_path));
824 if (uri.encoded_query) {
825 tls_buffer_append(&request, "?", 1);
826 tls_buffer_append(&request, uri.encoded_query, strlen(uri.encoded_query));
828 tls_buffer_append(&request, " HTTP/1.1\r\n", 11);
830 append_header(&request, "Host", host);
832 append_header(&request, "User-Agent", user_agent);
834 append_header(&request, "Accept", "*/*");
835 //append_header(&request, "Accept-Encoding", "chunked, identity;q=0.5");
836 append_header(&request, "Connection", "close");
838 append_header(&request, "If-Modified-Since", lmtime);
840 tls_buffer_append(&request, "\r\n", 2);
842 if (!strcmp(uri.scheme, "https")) {
845 clientssl = tls_create_context(TLS_CLIENT, TLS_V12);
847 /* optionally, we can set a certificate validation
848 * callback function if set_verify is not called, and
849 * root ca is set, `tls_default_verify` will be used
850 * (does exactly what `verify` does in this example)
852 if (verifypolicy == 2) {
854 cert_path = getenv("ZPM_CERTFILE");
856 cert_path = "/var/lib/zpm/roots.pem";
858 rv = tls_load_root_file(clientssl, cert_path);
860 fprintf(stderr, "Error loading root certs\n");
863 tls_set_verify(clientssl, verify_roots);
864 } else if (verifypolicy == 1) {
865 tls_set_verify(clientssl, verify_first);
867 tls_set_verify(clientssl, verify_trust);
871 fprintf(stderr, "Error initializing client context\n");
874 tls_sni_set(clientssl, uri.host);
877 sockfd = open_tcp_connection(host, port);
879 perror("can't open connection");
882 tls_set_fd(clientssl, sockfd);
883 if ((rv = tls_connect(clientssl)) != 1) {
884 fprintf(stderr, "Handshake Error %i\n", rv);
887 ret = tls_write(clientssl, request.buffer, request.len);
888 } else if (!strcmp(uri.scheme, "http")) {
889 sockfd = open_tcp_connection(host, port);
891 perror("can't open connection");
894 ret = write(sockfd, request.buffer, request.len);
895 } else if (!strcmp(uri.scheme, "file")) {
896 sockfd = open(uri.path, O_RDONLY);
897 fake_header(&io, sockfd);
900 fprintf(stderr, "scheme %s unknown\n", uri.scheme);
905 fprintf(stderr, "unable to write http request: %s\n", strerror(errno));
913 if (io.response.len >= 4) {
914 eoh = strstr(io.response.buffer, "\r\n\r\n");
917 ret = fill_buffer(&io);
925 /* never got (complete) header */
926 fprintf(stderr, "incomplete response (ret = %zd) to %s\n", ret, url);
927 fprintf(stderr, "have:\n");
928 fwrite(io.response.buffer, io.response.len, 1, stderr);
932 header_len = (size_t)(eoh - io.response.buffer) + 4;
936 switch (io.status_code) {
945 url = strdup(io.redirect);
952 printf("%d\n", io.status_code);
956 fwrite(request.buffer, request.len, 1, stderr);
960 io.response.len -= 2;
964 out = open(outfile, O_WRONLY|O_CREAT|O_TRUNC, 0600);
966 perror("can't open output file:");
972 if (io.content_length) {
973 fprintf(stderr, "(%lu) ", io.content_length);
978 write(out, io.response.buffer, io.response.len);
983 write(out, io.response.buffer, header_len);
985 tls_buffer_shift(&io.response, header_len);
988 /* we've written out the head if needed, so
989 * what's in the response buffer is the
990 * chunked encoding, so just reassign that
991 * to the chunkbuf and reinit */
992 io.chunkbuf = io.response;
993 tls_buffer_init(&io.response, 0);
994 /* and put whatever we've got into the response
995 * buffer, may not be needed, fill buffer
1002 if (io.response.len) {
1003 if (io.content_length && io.response.len + io.received > io.content_length) {
1004 io.response.len = io.content_length - io.received;
1005 /* we just ignore trailing garbage */
1007 write(out, io.response.buffer, io.response.len);
1008 io.received += io.response.len;
1009 ret = io.response.len;
1010 io.response.len = 0;
1014 if (io.content_length) {
1015 pdots(50, '.', total, total+ret,
1019 fprintf(stderr, "%zu", io.received);
1026 if (io.content_length && io.received >= io.content_length) {
1029 ret = fill_buffer(&io);
1032 //fprintf(stderr, "total received: %zu/%zu\n", io.received, io.content_length);
1034 fprintf(stderr, "%s read error %zd\n", uri.scheme, ret);
1036 if (io.last_modified != 0) {
1037 struct timespec ts[2];
1038 ts[0].tv_sec = 0; ts[0].tv_nsec = UTIME_OMIT;
1039 ts[1].tv_sec = io.last_modified;
1044 tls_buffer_free(&io.response);
1049 tls_shutdown(clientssl);
1050 tls_free(clientssl);
1054 if (progressbar && io.status_code == 200) {
1055 if (total == io.content_length || io.content_length == 0) {
1056 fprintf(stderr, " done\n");
1057 } else if (io.content_length != total) {
1058 fprintf(stderr, "failed (%zu bytes read)\n", total);
1059 io.status_code = 531; /* non official code */
1063 return io.status_code < 400 ? 0 : EXIT_FAILURE;