]> pd.if.org Git - zpackage/blob - src/fetchurl.c
print warning if host cert changed
[zpackage] / src / fetchurl.c
1 #define _POSIX_C_SOURCE 200809L
2
3 #include <stdio.h>
4 #include <sys/types.h>
5 #include <sys/socket.h>
6 #include <netinet/in.h>
7 #include <netdb.h>
8 #include <string.h>
9 #include <strings.h>
10 #include <stdlib.h>
11 #include <unistd.h>
12 #include <signal.h>
13 #include <time.h>
14 #include <sys/stat.h>
15 #include <fcntl.h>
16
17 #include "tlse.h"
18
19 struct tls_uri {
20         char *scheme;
21         char *userinfo;
22         char *host;
23         char *port;
24         char *path;
25         char *query;
26         char *fragment;
27 };
28 int tls_parse_uri(char *, struct tls_uri *);
29 void tls_free_uri(struct tls_uri *);
30
31 int open_tcp_connection(char *host, int port);
32
33 /* if trustpolicy is 0, we just accept anything */
34 int verify_trust(struct TLSContext *context, struct TLSCertificate **chain, int
35                 len) {
36         /* suppress unused */
37         if (context || chain || len) {
38                 return 0;
39         }
40
41         return 0;
42 }
43
44 static char hexchars[] = "0123456789abcdefABCDEF";
45
46 static void hex(char *dst, uint8_t *src, size_t len) {
47         while (len--) {
48                 dst[0] = hexchars[(src[0]>>4)&0xf];
49                 dst[1] = hexchars[src[0]&0xf];
50                 dst+=2;
51                 src++;
52         }
53 }
54
55 #if 0
56 static void hexbin(uint8_t *dst, unsigned char *src, size_t len) {
57         size_t i;
58         int x;
59
60         for (i=0; i<len; i+=2) {
61                 sscanf((const char *)src+i, "%02x", &x);
62                 dst[i/2] = x;
63         }
64 }
65 #endif
66
67 char *my_getline(struct tls_buffer *b, int fd, size_t *size) {
68         char *loc = 0;
69         char buf[4096];
70         ssize_t rv = 0;
71
72         while (b->error == 0) {
73                 loc = memchr(b->buffer, '\n', b->len);
74                 if (loc) {
75                         *size = loc - b->buffer + 1;
76                         return b->buffer;
77                 } else {
78                         rv = read(fd, buf, sizeof buf);
79                         if (rv == -1) {
80                                 return 0;
81                         }
82                         if (rv == 0) {
83                                 break;
84                         }
85                         tls_buffer_append(b, buf, rv);
86                 }
87         }
88         if (rv == 0) {
89                 *size = b->len;
90                 return b->buffer;
91         }
92         return 0;
93 }
94
95 /*
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
99  */
100 int verify_first(struct TLSContext *context, struct TLSCertificate **chain, int
101                 certs) {
102         int err;
103         char *trustfile, *homedir = 0, *host, *fp;
104         unsigned char certhash[65];
105         int trustdb;
106         struct tls_buffer tbuf;
107
108         char *line = 0;
109         size_t len = 0;
110
111         if (certs == 0 || chain == 0) {
112                 return 1;
113         }
114
115         err = tls_certificate_is_valid(chain[0]);
116         if (err) {
117                 return err;
118         }
119
120         if (context->sni) {
121                 err = tls_certificate_valid_subject(chain[0], context->sni);
122                 if (err) {
123                         return err;
124                 }
125         }
126
127         hex(certhash, chain[0]->fp, 32);
128         certhash[64] = 0;
129
130         trustfile = getenv("ZPM_KNOWNHOSTS");
131         if (!trustfile) {
132                 if (geteuid() == 0) {
133                         trustfile = "/var/lib/zpm/known_hosts";
134                 } else {
135                         /* we could do this with a series of
136                          * openat() calls instead of building
137                          * up a string 
138                          */
139                         trustfile = getenv("HOME");
140                         if (!trustfile) {
141                                 fprintf(stderr, "home = %s\n", trustfile);
142                                 return 1;
143                         }
144                         len = snprintf(homedir, 0, "%s/.zpm/known_hosts", trustfile);
145                         homedir = malloc(len+1);
146                         if (!homedir) {
147                                 return 1;
148                         }
149                         len = snprintf(homedir, len+1, "%s/.zpm/known_hosts", trustfile);
150                         trustfile = homedir;
151                 }
152         }
153         /* cert is valid on its face, so check against the trust db */
154         trustdb = open(trustfile, O_RDWR|O_CREAT, 0600);
155         if (trustdb == -1) {
156                 fprintf(stderr, "cannot open trustdb %s: %s\n", trustfile, strerror(errno));
157                 if (homedir) {
158                         free(homedir);
159                 }
160                 return 1;
161         }
162
163         if (homedir) {
164                 free(homedir);
165         }
166
167         len = 0;
168         tls_buffer_init(&tbuf, 128);
169         do {
170                 char *off;
171
172                 tls_buffer_shift(&tbuf, len);
173                 line = my_getline(&tbuf, trustdb, &len);
174
175                 if (!line || !len) {
176                         break;
177                 }
178
179                 fp = line;
180                 while (isspace(*fp)) {
181                         fp++;
182                 }
183                 if (*fp == '#') {
184                         continue;
185                 }
186                 off = strchr(line, ':');
187                 if (!off) {
188                         continue;
189                 }
190                 host = off + 1;
191                 *off = 0;
192                 if (line[len-1] == '\n') {
193                         line[len-1] = 0;
194                 }
195
196                 if (strlen(fp) != 64) {
197                         continue;
198                 }
199
200                 if (len && line[len-1] == '\n') {
201                         line[len-1] = 0;
202                 }
203
204                 if (strcmp(context->sni, host) != 0) {
205                         continue;
206                 }
207
208                 int match = (memcmp(certhash, fp, 64) == 0); 
209
210                 close(trustdb);
211                 tls_buffer_free(&tbuf);
212                 if (!match) {
213                         fprintf(stderr, "host %s certificate changed\n", host);
214                 }
215                 return match ? no_error : bad_certificate;
216         } while (!tbuf.error);
217
218         /* got here, so we should be at EOF, so add this host to trust db */
219         lseek(trustdb, 0, SEEK_END);
220
221         /* re-use the buffer so we only do one write */
222         /* ignore errors, the cert is fine, we just can't update
223          * the trustdb if there's errors here
224          */
225         tbuf.len = 0;
226         tls_buffer_append(&tbuf, certhash, 64);
227         tls_buffer_append_byte(&tbuf, ':');
228         tls_buffer_append(&tbuf, context->sni, strlen(context->sni));
229         tls_buffer_append_byte(&tbuf, '\n');
230         write(trustdb, tbuf.buffer, tbuf.len);
231         close(trustdb);
232         tls_buffer_free(&tbuf);
233
234         return no_error;
235 }
236
237 int verify_roots(struct TLSContext *context, struct TLSCertificate **chain, int
238                 len) {
239         int i, err;
240
241         if (chain) {
242                 for (i = 0; i < len; i++) {
243                         struct TLSCertificate *certificate = chain[i];
244                         err = tls_certificate_is_valid(certificate);
245                         if (err) {
246                                 return err;
247                         }
248                 }
249         }
250         
251         err = tls_certificate_chain_is_valid(chain, len);
252         if (err) {
253                 return err;
254         }
255
256         if (len > 0 && context->sni) {
257                 err = tls_certificate_valid_subject(chain[0], context->sni);
258                 if (err) {
259                         return err;
260                 }
261         }
262
263         /* Perform certificate validation against ROOT CA */
264         err = tls_certificate_chain_is_valid_root(context, chain, len);
265         if (err) {
266                 return err;
267         }
268
269         return no_error;
270 }
271
272 struct io {
273         struct tls_buffer response;
274         struct TLSContext *tls;
275         int socket;
276         int status_code;
277         time_t last_modified;
278         time_t date;
279         size_t content_length;
280         char *redirect;
281 };
282
283 int month(char *m) {
284         char *months[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul",
285                 "Aug", "Sep", "Oct", "Nov", "Dec" };
286         int i;
287
288         for (i=0; i < 12; i++) {
289                 if (!strncasecmp(m, months[i], 3)) {
290                         return i+1;
291                 }
292         }
293         return 0;
294 }
295
296 /* Wed, 06 Feb 2019 10:06:05 GMT */
297 time_t parse_date(char *d) {
298         struct tm tm = { 0 };
299         int rv;
300
301         int h, m, s, dom, Y;
302         char M[4];
303         rv = sscanf(d, "%*[a-zA-Z,] %d %s %d %d:%d:%d", &dom, M, &Y, &h, &m, &s);
304         if (rv == 6) {
305                 tm.tm_year = Y - 1900;
306                 tm.tm_hour = h;
307                 tm.tm_min = m;
308                 tm.tm_sec = s;
309                 tm.tm_mon = month(M)-1;
310                 tm.tm_mday = dom;
311
312                 return mktime(&tm);
313         }
314         return -1;
315 }
316
317 char *find_header(struct io *io, char *header, size_t *len) {
318         char *eoh, *soh;
319         size_t hlen;
320
321         *len = 0;
322
323         hlen = strlen(header);
324         eoh = strstr(io->response.buffer, "\r\n\r\n");
325         if (!eoh) {
326                 return 0;
327         }
328         soh = io->response.buffer;
329         do {
330                 soh = strstr(soh, "\r\n");
331                 if (soh == eoh) {
332                         break;
333                 }
334                 soh += 2;
335                 if (!memcmp(soh, header, hlen)) {
336                         break;
337                 }
338         } while (soh < eoh);
339
340         if (soh >= eoh) {
341                 return 0;
342         }
343         eoh = strstr(soh, "\r\n");
344         soh += hlen;
345         while (soh < eoh && isspace(*soh)) {
346                 soh++;
347         }
348         *len = (eoh - soh);
349         return soh;
350 }
351
352 void parse_header(struct io *io) {
353         char *s = io->response.buffer;
354         int code = 0;
355         char *hval;
356         size_t hlen;
357
358         while (!isspace(*s)) {
359                 s++;
360         }
361         while (isspace(*s)) {
362                 s++;
363         }
364         code = strtol(s, 0, 10);
365         io->status_code = code;
366
367         hval = find_header(io, "Date:", &hlen);
368         if (hval) {
369                 hval[hlen] = 0;
370                 io->date = parse_date(hval);
371                 hval[hlen] = '\r';
372         }
373         hval = find_header(io, "Last-Modified:", &hlen);
374         if (hval) {
375                 hval[hlen] = 0;
376                 io->last_modified = parse_date(hval);
377                 hval[hlen] = '\r';
378         }
379
380         hval = find_header(io, "Content-Length:", &hlen);
381         if (hval) {
382                 hval[hlen] = 0;
383                 io->content_length = strtoul(hval, 0, 10);
384                 hval[hlen] = '\r';
385         }
386
387         switch (code) {
388                 case 301:
389                 case 302:
390                 case 303:
391                 case 307:
392                         hval = find_header(io, "Location:", &hlen);
393                         if (hval) {
394                                 io->redirect = strndup(hval, hlen);
395                         }
396                         break;
397                 default:
398                         break;
399         }
400
401 }
402
403 ssize_t fill_buffer(struct io *io) {
404         unsigned char buffer[4096];
405         ssize_t ret;
406
407         if (io->tls) {
408                 ret = tls_read(io->tls, buffer, sizeof buffer);
409         } else {
410                 ret = read(io->socket, buffer, sizeof buffer);
411         }
412
413         if (ret > 0) {
414                 tls_buffer_append(&io->response, buffer, ret);
415         }
416
417         return ret;
418 }
419
420 #if 0
421 char *nextline(struct io *io) {
422         char *eol = 0;;
423
424         eol = memchr(io->response.buffer, '\n', io.response.size);
425         while (eol == 0) {
426                 fill_buffer(io);
427                 eol = memchr(io->response.buffer, '\n', io.response.size);
428         }
429         if (eol) {
430
431 }
432 #endif
433
434 void append_header(struct tls_buffer *buf, char *header, char *val) {
435         tls_buffer_append(buf, header, strlen(header));
436         tls_buffer_append(buf, ": ", 2);
437         tls_buffer_append(buf, val, strlen(val));
438         tls_buffer_append(buf, "\r\n", 2);
439 }
440
441 void append_timeheader(struct tls_buffer *buf, char *header, time_t ts) {
442         char timestr[80];
443         struct tm *tm;
444
445         tm = gmtime(&ts);
446
447         strftime(timestr, sizeof timestr, "%a, %d %b %Y %H:%M:%S GMT", tm);
448         append_header(buf, header, timestr);
449 }
450
451 static void pdots(int len, int ch, unsigned long was, unsigned long now,
452                 unsigned long total) {
453         was = len * was / total;
454         if (now > total) {
455                 now = total;
456         }
457         now = len * now / total;
458         while (was++ < now) {
459                 putc(ch,stderr);
460         }
461 }
462
463 static void fake_header(struct io *io, int fd) {
464         struct stat st;
465         int code = 200, rv;
466         char *message, codestr[5], length[32];
467         struct tls_buffer *hdr = &io->response;
468
469         if (fd == -1) {
470                 switch (errno) {
471                         case EACCES: code = 403; break;
472                         case ENOENT: code = 404; break;
473                         default: code = 500; break;
474                 }
475         } else {
476                 rv = fstat(fd, &st);
477                 if (rv == -1) {
478                         code = 500;
479                 }
480         }
481
482         if (io->last_modified >= st.st_mtime) {
483                 code = 304;
484         }
485
486         switch (code) {
487                 case 200: message = "OK"; break;
488                 case 304: message = "Not Modified"; break;
489                 case 403: message = "Forbidden"; break;
490                 case 404: message = "Not Found"; break;
491                 case 500: message = "Internal Server Error"; break;
492                 default: break;
493         }
494         sprintf(codestr, "%0.3d ", code);
495         tls_buffer_append(hdr, "HTTP/1.1 ", 9);
496         tls_buffer_append(hdr, codestr, 4);
497         tls_buffer_append_str(hdr, message);
498         tls_buffer_append(hdr, "\r\n", 2);
499
500         append_timeheader(hdr, "Date", time(NULL));
501         append_header(hdr, "Server", "zpm-fetchurl/0.9");
502         if (code < 400) {
503                 append_timeheader(hdr, "Last-Modified", st.st_mtime);
504                 sprintf(length, "%zu", st.st_size);
505                 append_header(hdr, "Content-Length", length);
506         }
507
508         append_header(hdr, "Connection", "close");
509         append_header(hdr, "Content-Type", "application/octet-stream");
510         tls_buffer_append(hdr, "\r\n", 2);
511 }
512
513 char *pathlast(char *path) {
514         char *last = 0;
515         size_t len = 0;
516
517         if (path == 0) {
518                 return 0;
519         }
520
521         while (*path == '/') {
522                 path++;
523         }
524
525         do {
526                 last = path;
527                 len = 0;
528                 while (*path && *path != '/') {
529                         path++;
530                         len++;
531                 }
532                 while (*path == '/') {
533                         path++;
534                 }
535         } while (*path);
536
537         if (len == 0) {
538                 return 0;
539         }
540
541         return strndup(last, len);
542 }
543
544 static time_t file_mtime(char *path) {
545         struct stat st;
546         int rv;
547
548         rv = stat(path, &st);
549         if (rv == -1) {
550                 if (errno == ENOENT) {
551                         return 0;
552                 } 
553                 perror("stat failed:");
554                 return -1;
555         }
556
557         return st.st_mtime;
558 }
559
560 int main(int ac, char *av[]) {
561         int sockfd, port = -1, rv;
562         ssize_t ret;
563         int option;
564 #if 0
565         char msg[] = "GET %s HTTP/1.1\r\nHost: %s:%i\r\nConnection: close\r\n\r\n";
566         char msg2[] = "GET %s HTTP/1.1\r\nHost: %s:%i\r\nLast-Modified: %s\r\nConnection: close\r\n\r\n";
567         char msg_buffer[1024];
568 #endif
569         char *req_file = 0;
570         char *host = 0;
571         struct tls_uri uri = { 0 };
572         char *outfile = 0;
573         int raw = 0, head = 0;
574         int out = 1; /* output file descriptor */
575         int use_tls = 0;
576         struct io io = { {0}, 0, -1, 0, 0, 0, 0, 0 };
577         struct TLSContext *clientssl = 0;
578         int failsilent = 0;
579         char *lmfile = 0;
580         int progressbar = 0;
581         struct tls_buffer request;
582         char lmtime[80];
583         char *eoh = 0;
584         size_t total = 0;
585         size_t header_len;
586         char *url = 0;
587         int redirs = 0, redirlimit = 50, printstatus = 0;
588         int verifypolicy = 1, calcoutfile = 0, ifnewer = 0;
589
590         ltc_mp = tfm_desc;
591
592         while ((option = getopt(ac, av, "o:OrIfz:np#R:SkK")) != -1) {
593                 switch (option) {
594                         case 'o': outfile = optarg; break;
595                         case 'O': calcoutfile = 1; break;
596                         case 'S': printstatus = 1; head = 1; break;
597                         case 'k': verifypolicy = 0; break;
598                         case 'K': verifypolicy = 2; break;
599                         case 'I': head = 1;
600                         case 'r': raw = 1; break;
601                         case 'f': failsilent = 1; break;
602                         case 'z': lmfile = optarg; break;
603                         case 'n': ifnewer = 1; break;
604                         case 'R': redirlimit = strtol(optarg, 0, 10); break;
605                         case 'p':
606                         case '#': progressbar = 1; break;
607                         default:
608                                   exit(EXIT_FAILURE);
609                                   break;
610                 }
611         }
612
613         if (ac < optind) {
614                 fprintf(stderr, "Usage: %s uri\n", av[0]);
615                 exit(EXIT_FAILURE);
616         }
617
618         url = strdup(av[optind]);
619         if (!url) {
620                 exit(EXIT_FAILURE);
621         }
622
623         io.last_modified = 0;
624
625         if (calcoutfile && !outfile) {
626                 tls_parse_uri(url, &uri);
627                 outfile = pathlast(uri.path);
628                 /* outfile leaks memory here, so if this
629                  * were turned into a library function,
630                  * we'd need to track it
631                  */
632                 if (!outfile) {
633                         fprintf(stderr, "unable to determine outfile\n");
634                         exit(EXIT_FAILURE);
635                 }
636         }
637
638         if (ifnewer && outfile && !lmfile) {
639                 lmfile = outfile;
640         }
641
642         if (lmfile) {
643                 struct tm *mtime;
644                 time_t ts;
645
646                 ts = file_mtime(lmfile);
647
648                 if (ts == -1) {
649                         exit(EXIT_FAILURE);
650                 } else if (ts != 0) {
651                         io.last_modified = ts;
652                         mtime = gmtime(&ts);
653                         strftime(lmtime, sizeof lmtime, "%a, %d %b %Y %H:%M:%S GMT", mtime);
654                 } else {
655                         lmfile = 0;
656                 }
657         }
658
659         signal(SIGPIPE, SIG_IGN);
660
661         tls_buffer_init(&io.response, 0);
662         tls_buffer_init(&request, 128);
663
664         while (redirs++ <= redirlimit) {
665                 tls_free_uri(&uri);
666                 io.response.len = 0;
667                 request.len = 0;
668                 eoh = 0;
669
670                 tls_parse_uri(url, &uri);
671                 host = uri.host;
672                 port = atoi(uri.port);
673                 req_file = uri.path;
674
675                 /* construct request */
676                 if (head) {
677                         tls_buffer_append(&request, "HEAD ", 5);
678                 } else {
679                         tls_buffer_append(&request, "GET ", 4);
680                 }
681                 tls_buffer_append(&request, uri.path, strlen(uri.path));
682                 tls_buffer_append(&request, " HTTP/1.1\r\n", 11);
683
684                 append_header(&request, "Host", host);
685                 append_header(&request, "Connection", "close");
686                 if (lmfile) {
687                         append_header(&request, "If-Modified-Since", lmtime);
688                 }
689                 tls_buffer_append(&request, "\r\n", 2);
690
691                 if (!strcmp(uri.scheme, "https")) {
692                         use_tls = 1;
693
694                         clientssl = tls_create_context(TLS_CLIENT, TLS_V12);
695
696                         /* optionally, we can set a certificate validation
697                          * callback function if set_verify is not called, and
698                          * root ca is set, `tls_default_verify` will be used
699                          * (does exactly what `verify` does in this example)
700                          */
701                         if (verifypolicy == 2) {
702                                 char *cert_path = 0;
703                                 cert_path = getenv("ZPM_CERTFILE");
704                                 if (!cert_path) {
705                                         cert_path = "/var/lib/zpm/roots.pem";
706                                 }
707                                 rv = tls_load_root_file(clientssl, cert_path);
708                                 if (rv == -1) {
709                                         fprintf(stderr, "Error loading root certs\n");
710                                         return 1;
711                                 }
712                                 tls_set_verify(clientssl, verify_roots);
713                         } else if (verifypolicy == 1) {
714                                 tls_set_verify(clientssl, verify_first);
715                         } else {
716                                 tls_set_verify(clientssl, verify_trust);
717                         }
718
719                         if (!clientssl) {
720                                 fprintf(stderr, "Error initializing client context\n");
721                                 return -1;
722                         }
723                         tls_sni_set(clientssl, uri.host);
724                         clientssl->sync = 1;
725                         io.tls = clientssl;
726                         sockfd = open_tcp_connection(host, port);
727                         if (sockfd < 0) {
728                                 perror("can't open connection");
729                                 exit(EXIT_FAILURE);
730                         }
731                         tls_set_fd(clientssl, sockfd);
732                         if ((rv = tls_connect(clientssl)) != 1) {
733                                 fprintf(stderr, "Handshake Error %i\n", rv);
734                                 return 1;
735                         }
736                         ret = tls_write(clientssl, request.buffer, request.len);
737                 } else if (!strcmp(uri.scheme, "http")) {
738                         sockfd = open_tcp_connection(host, port);
739                         if (sockfd < 0) {
740                                 perror("can't open connection");
741                                 exit(EXIT_FAILURE);
742                         }
743                         ret = write(sockfd, request.buffer, request.len);
744                 } else if (!strcmp(uri.scheme, "file")) {
745                         sockfd = open(uri.path, O_RDONLY);
746                         fake_header(&io, sockfd);
747                         ret = 0;
748                 } else {
749                         fprintf(stderr, "scheme %s unknown\n", uri.scheme);
750                         exit(EXIT_FAILURE);
751                 }
752
753                 if (ret == -1) {
754                         fprintf(stderr, "unable to write http request: %s\n", strerror(errno));
755                         exit(EXIT_FAILURE);
756                 }
757
758                 io.socket = sockfd;
759
760                 do {
761                         if (io.response.len >= 4) {
762                                 eoh = strstr(io.response.buffer, "\r\n\r\n");
763                         }
764                         if (!eoh) {
765                                 ret = fill_buffer(&io);
766                                 if (ret <= 0) {
767                                         break;
768                                 }
769                         }
770                 } while (!eoh);
771
772                 if (!eoh) {
773                         /* never got (complet) header */
774                         fprintf(stderr, "incomplete response to %s\n", av[optind]);
775                         exit(EXIT_FAILURE);
776                 }
777
778                 header_len = (size_t)(eoh - io.response.buffer) + 4;
779                 parse_header(&io);
780
781                 switch (io.status_code) {
782                         case 304:
783                                 progressbar = 0;
784                                 break;
785                         case 301:
786                         case 302:
787                         case 303:
788                         case 307:
789                                 free(url);
790                                 url = strdup(io.redirect);
791                                 close(io.socket);
792                                 continue;
793                                 break;
794                 }
795
796                 if (printstatus) {
797                         printf("%d\n", io.status_code);
798                         break;
799                 }
800
801                 if (!raw) {
802                         tls_buffer_shift(&io.response, header_len);
803                 }
804                 if (head) {
805                         io.response.len -= 2;
806                 }
807
808                 if (progressbar) {
809                         if (io.content_length) {
810                                 fprintf(stderr, "(%lu) ", io.content_length);
811                         }
812                 }
813
814                 if (outfile) {
815                         out = open(outfile, O_WRONLY|O_CREAT, 0600);
816                         if (out == -1) {
817                                 perror("can't open output file:");
818                                 exit(EXIT_FAILURE);
819                         }
820                 }
821
822                 do {
823                         write(out, io.response.buffer, io.response.len);
824                         ret = io.response.len;
825                         io.response.len = 0;
826
827                         if (progressbar) {
828                                 if (io.content_length) {
829                                         pdots(50, '.', total, total+ret,
830                                                         io.content_length);
831                                 } else {
832                                         putc('\r', stderr);
833                                         fprintf(stderr, "%zu", total+ret);
834                                 }
835                                 total += ret;
836                         }
837                         if (head) {
838                                 break;
839                         }
840                         ret = fill_buffer(&io);
841                 } while (ret > 0);
842
843                 if (ret < 0) {
844                         fprintf(stderr, "%s read error %zd\n", uri.scheme, ret);
845                 }
846                 struct timespec ts[2];
847                 ts[0].tv_sec = 0; ts[0].tv_nsec = UTIME_OMIT;
848                 ts[1].tv_sec = io.last_modified;
849                 ts[1].tv_nsec = 0;
850
851                 futimens(out, ts);
852                 close(out);
853                 tls_buffer_free(&io.response);
854                 break;
855         }
856
857         if (use_tls) {
858                 tls_shutdown(clientssl);
859                 tls_free(clientssl);
860         }
861
862         close(sockfd);
863         if (progressbar && io.status_code == 200) {
864                 fprintf(stderr, "(%lu)", total);
865                 putc('\n',stderr);
866         }
867
868         return io.status_code < 400 ? 0 : EXIT_FAILURE;
869 }