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);
467 /* essentially memmem */
468 void *lookfor(const void *buf, size_t buflen, const void *pattern, size_t len) {
469 const char *bf = buf;
470 const char *pt = pattern;
473 while (len <= (buflen - (p - bf))) {
474 if ((p = memchr(p, *pt, buflen - (p - bf))) != 0) {
475 if (memcmp(p, pattern, len) == 0) {
487 /* returns read chunksize, unshifts the line */
488 ssize_t read_chunksize(struct io *io) {
492 //fwrite(io->chunkbuf.buffer, io->chunkbuf.len, 1, stderr);
494 /* there could be up to two leading bytes */
495 if (io->chunkbuf.len >= 2 && io->chunkbuf.buffer[0] == '\r' && io->chunkbuf.buffer[1] == '\n') {
496 tls_buffer_shift(&io->chunkbuf, 2);
499 cr = lookfor(io->chunkbuf.buffer, io->chunkbuf.len, "\r\n", 2);
505 cs = strtol(io->chunkbuf.buffer, 0, 16);
506 tls_buffer_shift(&io->chunkbuf, cr - io->chunkbuf.buffer + 2);
511 /* unchunk's job is to move bytes from the chunk buf to the response buf */
512 /* return bytes from chunk, 0 if unable. once last chunk, changed chunked
515 ssize_t unchunk(struct io *io) {
516 ssize_t bytes_to_move = 0;
519 if (!io || !io->chunked) {
523 if (io->chunkleft == 0) {
524 chunksize = read_chunksize(io);
525 if (chunksize == -1) {
528 io->chunksize = chunksize;
529 if (io->chunksize == 0) {
530 /* end of chunked data */
535 io->chunkleft = io->chunksize;
536 io->chunktotal += io->chunksize;
539 if (io->chunkbuf.len == 0) {
540 /* need more bytes */
544 bytes_to_move = io->chunkbuf.len < io->chunkleft ? io->chunkbuf.len : io->chunkleft;
546 tls_buffer_append(&io->response, io->chunkbuf.buffer, bytes_to_move);
547 io->chunkleft -= bytes_to_move;
548 io->chunkbytesread += bytes_to_move;
550 /* chunk is terminated with a crlf */
551 //tls_buffer_shift(&io->chunkbuf, bytes_to_move + io->chunkleft ? 0 : 2);
552 tls_buffer_shift(&io->chunkbuf, bytes_to_move);
554 return bytes_to_move;
558 char *nextline(struct io *io) {
561 eol = memchr(io->response.buffer, '\n', io.response.size);
564 eol = memchr(io->response.buffer, '\n', io.response.size);
571 void append_header(struct tls_buffer *buf, char *header, char *val) {
572 tls_buffer_append(buf, header, strlen(header));
573 tls_buffer_append(buf, ": ", 2);
574 tls_buffer_append(buf, val, strlen(val));
575 tls_buffer_append(buf, "\r\n", 2);
578 void append_timeheader(struct tls_buffer *buf, char *header, time_t ts) {
584 strftime(timestr, sizeof timestr, "%a, %d %b %Y %H:%M:%S GMT", tm);
585 append_header(buf, header, timestr);
588 static void pdots(int len, int ch, unsigned long was, unsigned long now,
589 unsigned long total) {
590 was = len * was / total;
594 now = len * now / total;
595 while (was++ < now) {
600 static void fake_header(struct io *io, int fd) {
603 char *message, codestr[5], length[32];
604 struct tls_buffer *hdr = &io->response;
608 case EACCES: code = 403; break;
609 case ENOENT: code = 404; break;
610 default: code = 500; break;
619 if (io->last_modified >= st.st_mtime) {
624 case 200: message = "OK"; break;
625 case 304: message = "Not Modified"; break;
626 case 403: message = "Forbidden"; break;
627 case 404: message = "Not Found"; break;
628 case 500: message = "Internal Server Error"; break;
631 sprintf(codestr, "%0.3d ", code);
632 tls_buffer_append(hdr, "HTTP/1.1 ", 9);
633 tls_buffer_append(hdr, codestr, 4);
634 tls_buffer_append_str(hdr, message);
635 tls_buffer_append(hdr, "\r\n", 2);
637 append_timeheader(hdr, "Date", time(NULL));
638 append_header(hdr, "Server", "zpm-fetchurl/0.9");
640 append_timeheader(hdr, "Last-Modified", st.st_mtime);
641 sprintf(length, "%zu", st.st_size);
642 append_header(hdr, "Content-Length", length);
645 append_header(hdr, "Connection", "close");
646 append_header(hdr, "Content-Type", "application/octet-stream");
647 tls_buffer_append(hdr, "\r\n", 2);
650 char *pathlast(char *path) {
658 while (*path == '/') {
665 while (*path && *path != '/') {
669 while (*path == '/') {
678 return strndup(last, len);
681 static time_t file_mtime(char *path) {
685 rv = stat(path, &st);
687 if (errno == ENOENT) {
690 perror("stat failed:");
697 int main(int ac, char *av[]) {
698 int sockfd, port = -1, rv;
702 char msg[] = "GET %s HTTP/1.1\r\nHost: %s:%i\r\nConnection: close\r\n\r\n";
703 char msg2[] = "GET %s HTTP/1.1\r\nHost: %s:%i\r\nLast-Modified: %s\r\nConnection: close\r\n\r\n";
704 char msg_buffer[1024];
708 struct tls_uri uri = { 0 };
710 int raw = 0, head = 0;
711 int out = 1; /* output file descriptor */
713 struct io io = { {0}, {0}, 0, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
714 struct TLSContext *clientssl = 0;
718 struct tls_buffer request;
721 char *user_agent = 0;
725 int redirs = 0, redirlimit = 50, printstatus = 0, showreq = 0;
726 int verifypolicy = 1, calcoutfile = 0, ifnewer = 0;
730 while ((option = getopt(ac, av, "o:OrIfz:np#RL:SkKU:")) != -1) {
732 case 'o': outfile = optarg; break;
733 case 'O': calcoutfile = 1; break;
734 case 'S': printstatus = 1; head = 1; break;
735 case 'k': verifypolicy = 0; break;
736 case 'K': verifypolicy = 2; break;
737 case 'U': user_agent = optarg; break;
739 case 'r': raw = 1; break;
740 case 'R': showreq = 1; break;
741 case 'f': failsilent = 1; break;
742 case 'z': lmfile = optarg; break;
743 case 'n': ifnewer = 1; break;
744 case 'L': redirlimit = strtol(optarg, 0, 10); break;
746 case '#': progressbar = 1; break;
754 fprintf(stderr, "Usage: %s uri\n", av[0]);
758 url = strdup(av[optind]);
763 io.last_modified = 0;
765 if (calcoutfile && !outfile) {
766 tls_parse_uri(url, &uri);
767 outfile = pathlast(uri.path);
768 /* outfile leaks memory here, so if this
769 * were turned into a library function,
770 * we'd need to track it
773 fprintf(stderr, "unable to determine outfile\n");
778 if (ifnewer && outfile && !lmfile) {
786 ts = file_mtime(lmfile);
790 } else if (ts != 0) {
791 io.last_modified = ts;
793 strftime(lmtime, sizeof lmtime, "%a, %d %b %Y %H:%M:%S GMT", mtime);
799 signal(SIGPIPE, SIG_IGN);
801 tls_buffer_init(&io.response, 0);
802 tls_buffer_init(&request, 128);
804 while (redirs++ <= redirlimit) {
811 tls_parse_uri(url, &uri);
813 port = atoi(uri.port);
816 /* construct request */
818 tls_buffer_append(&request, "HEAD ", 5);
820 tls_buffer_append(&request, "GET ", 4);
822 tls_buffer_append(&request, uri.encoded_path, strlen(uri.encoded_path));
823 if (uri.encoded_query) {
824 tls_buffer_append(&request, "?", 1);
825 tls_buffer_append(&request, uri.encoded_query, strlen(uri.encoded_query));
827 tls_buffer_append(&request, " HTTP/1.1\r\n", 11);
829 append_header(&request, "Host", host);
831 append_header(&request, "User-Agent", user_agent);
833 append_header(&request, "Accept", "*/*");
834 //append_header(&request, "Accept-Encoding", "chunked, identity;q=0.5");
835 append_header(&request, "Connection", "close");
837 append_header(&request, "If-Modified-Since", lmtime);
839 tls_buffer_append(&request, "\r\n", 2);
841 if (!strcmp(uri.scheme, "https")) {
844 clientssl = tls_create_context(TLS_CLIENT, TLS_V12);
846 /* optionally, we can set a certificate validation
847 * callback function if set_verify is not called, and
848 * root ca is set, `tls_default_verify` will be used
849 * (does exactly what `verify` does in this example)
851 if (verifypolicy == 2) {
853 cert_path = getenv("ZPM_CERTFILE");
855 cert_path = "/var/lib/zpm/roots.pem";
857 rv = tls_load_root_file(clientssl, cert_path);
859 fprintf(stderr, "Error loading root certs\n");
862 tls_set_verify(clientssl, verify_roots);
863 } else if (verifypolicy == 1) {
864 tls_set_verify(clientssl, verify_first);
866 tls_set_verify(clientssl, verify_trust);
870 fprintf(stderr, "Error initializing client context\n");
873 tls_sni_set(clientssl, uri.host);
876 sockfd = open_tcp_connection(host, port);
878 perror("can't open connection");
881 tls_set_fd(clientssl, sockfd);
882 if ((rv = tls_connect(clientssl)) != 1) {
883 fprintf(stderr, "Handshake Error %i\n", rv);
886 ret = tls_write(clientssl, request.buffer, request.len);
887 } else if (!strcmp(uri.scheme, "http")) {
888 sockfd = open_tcp_connection(host, port);
890 perror("can't open connection");
893 ret = write(sockfd, request.buffer, request.len);
894 } else if (!strcmp(uri.scheme, "file")) {
895 sockfd = open(uri.path, O_RDONLY);
896 fake_header(&io, sockfd);
899 fprintf(stderr, "scheme %s unknown\n", uri.scheme);
904 fprintf(stderr, "unable to write http request: %s\n", strerror(errno));
912 if (io.response.len >= 4) {
913 eoh = strstr(io.response.buffer, "\r\n\r\n");
916 ret = fill_buffer(&io);
924 /* never got (complete) header */
925 fprintf(stderr, "incomplete response (ret = %zd) to %s\n", ret, url);
926 fprintf(stderr, "have:\n");
927 fwrite(io.response.buffer, io.response.len, 1, stderr);
931 header_len = (size_t)(eoh - io.response.buffer) + 4;
935 switch (io.status_code) {
944 url = strdup(io.redirect);
951 printf("%d\n", io.status_code);
955 fwrite(request.buffer, request.len, 1, stderr);
959 io.response.len -= 2;
960 write(out, io.response.buffer, io.response.len);
964 if (io.status_code == 304) {
969 out = open(outfile, O_WRONLY|O_CREAT|O_TRUNC, 0600);
971 perror("can't open output file:");
977 if (io.content_length) {
978 fprintf(stderr, "(%lu) ", io.content_length);
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 size_t before = io.received;
1003 if (io.response.len) {
1004 if (io.content_length && io.response.len + io.received > io.content_length) {
1005 io.response.len = io.content_length - io.received;
1006 /* we just ignore trailing garbage */
1008 write(out, io.response.buffer, io.response.len);
1009 io.received += io.response.len;
1010 ret = io.response.len;
1011 io.response.len = 0;
1015 if (io.content_length) {
1016 pdots(50, '.', before, io.received,
1020 fprintf(stderr, "%zu", io.received);
1027 if (io.content_length && io.received >= io.content_length) {
1030 ret = fill_buffer(&io);
1033 //fprintf(stderr, "total received: %zu/%zu\n", io.received, io.content_length);
1035 fprintf(stderr, "%s read error %zd\n", uri.scheme, ret);
1037 if (io.last_modified != 0) {
1038 struct timespec ts[2];
1039 ts[0].tv_sec = 0; ts[0].tv_nsec = UTIME_OMIT;
1040 ts[1].tv_sec = io.last_modified;
1045 tls_buffer_free(&io.response);
1050 tls_shutdown(clientssl);
1051 tls_free(clientssl);
1055 if (progressbar && io.status_code == 200) {
1056 if (io.received == io.content_length || io.content_length == 0) {
1057 fprintf(stderr, " done\n");
1058 } else if (io.content_length != io.received) {
1059 fprintf(stderr, "failed (%zu bytes read)\n", total);
1060 io.status_code = 531; /* non official code */
1064 return io.status_code < 400 ? 0 : EXIT_FAILURE;