]> pd.if.org Git - zpackage/blob - src/fetchurl.c
cleanups
[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                 return match ? no_error : bad_certificate;
213         } while (!tbuf.error);
214
215         /* got here, so we should be at EOF, so add this host to trust db */
216         lseek(trustdb, 0, SEEK_END);
217
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
221          */
222         tbuf.len = 0;
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);
228         close(trustdb);
229         tls_buffer_free(&tbuf);
230
231         return no_error;
232 }
233
234 int verify_roots(struct TLSContext *context, struct TLSCertificate **chain, int
235                 len) {
236         int i, err;
237
238         if (chain) {
239                 for (i = 0; i < len; i++) {
240                         struct TLSCertificate *certificate = chain[i];
241                         err = tls_certificate_is_valid(certificate);
242                         if (err) {
243                                 return err;
244                         }
245                 }
246         }
247         
248         err = tls_certificate_chain_is_valid(chain, len);
249         if (err) {
250                 return err;
251         }
252
253         if (len > 0 && context->sni) {
254                 err = tls_certificate_valid_subject(chain[0], context->sni);
255                 if (err) {
256                         return err;
257                 }
258         }
259
260         /* Perform certificate validation against ROOT CA */
261         err = tls_certificate_chain_is_valid_root(context, chain, len);
262         if (err) {
263                 return err;
264         }
265
266         return no_error;
267 }
268
269 struct io {
270         struct tls_buffer response;
271         struct TLSContext *tls;
272         int socket;
273         int status_code;
274         time_t last_modified;
275         time_t date;
276         size_t content_length;
277         char *redirect;
278 };
279
280 int month(char *m) {
281         char *months[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul",
282                 "Aug", "Sep", "Oct", "Nov", "Dec" };
283         int i;
284
285         for (i=0; i < 12; i++) {
286                 if (!strncasecmp(m, months[i], 3)) {
287                         return i+1;
288                 }
289         }
290         return 0;
291 }
292
293 /* Wed, 06 Feb 2019 10:06:05 GMT */
294 time_t parse_date(char *d) {
295         struct tm tm = { 0 };
296         int rv;
297
298         int h, m, s, dom, Y;
299         char M[4];
300         rv = sscanf(d, "%*[a-zA-Z,] %d %s %d %d:%d:%d", &dom, M, &Y, &h, &m, &s);
301         if (rv == 6) {
302                 tm.tm_year = Y - 1900;
303                 tm.tm_hour = h;
304                 tm.tm_min = m;
305                 tm.tm_sec = s;
306                 tm.tm_mon = month(M)-1;
307                 tm.tm_mday = dom;
308
309                 return mktime(&tm);
310         }
311         return -1;
312 }
313
314 char *find_header(struct io *io, char *header, size_t *len) {
315         char *eoh, *soh;
316         size_t hlen;
317
318         *len = 0;
319
320         hlen = strlen(header);
321         eoh = strstr(io->response.buffer, "\r\n\r\n");
322         if (!eoh) {
323                 return 0;
324         }
325         soh = io->response.buffer;
326         do {
327                 soh = strstr(soh, "\r\n");
328                 if (soh == eoh) {
329                         break;
330                 }
331                 soh += 2;
332                 if (!memcmp(soh, header, hlen)) {
333                         break;
334                 }
335         } while (soh < eoh);
336
337         if (soh >= eoh) {
338                 return 0;
339         }
340         eoh = strstr(soh, "\r\n");
341         soh += hlen;
342         while (soh < eoh && isspace(*soh)) {
343                 soh++;
344         }
345         *len = (eoh - soh);
346         return soh;
347 }
348
349 void parse_header(struct io *io) {
350         char *s = io->response.buffer;
351         int code = 0;
352         char *hval;
353         size_t hlen;
354
355         while (!isspace(*s)) {
356                 s++;
357         }
358         while (isspace(*s)) {
359                 s++;
360         }
361         code = strtol(s, 0, 10);
362         io->status_code = code;
363
364         hval = find_header(io, "Date:", &hlen);
365         if (hval) {
366                 hval[hlen] = 0;
367                 io->date = parse_date(hval);
368                 hval[hlen] = '\r';
369         }
370         hval = find_header(io, "Last-Modified:", &hlen);
371         if (hval) {
372                 hval[hlen] = 0;
373                 io->last_modified = parse_date(hval);
374                 hval[hlen] = '\r';
375         }
376
377         hval = find_header(io, "Content-Length:", &hlen);
378         if (hval) {
379                 hval[hlen] = 0;
380                 io->content_length = strtoul(hval, 0, 10);
381                 hval[hlen] = '\r';
382         }
383
384         switch (code) {
385                 case 301:
386                 case 302:
387                 case 303:
388                 case 307:
389                         hval = find_header(io, "Location:", &hlen);
390                         if (hval) {
391                                 io->redirect = strndup(hval, hlen);
392                         }
393                         break;
394                 default:
395                         break;
396         }
397
398 }
399
400 ssize_t fill_buffer(struct io *io) {
401         unsigned char buffer[4096];
402         ssize_t ret;
403
404         if (io->tls) {
405                 ret = tls_read(io->tls, buffer, sizeof buffer);
406         } else {
407                 ret = read(io->socket, buffer, sizeof buffer);
408         }
409
410         if (ret > 0) {
411                 tls_buffer_append(&io->response, buffer, ret);
412         }
413
414         return ret;
415 }
416
417 #if 0
418 char *nextline(struct io *io) {
419         char *eol = 0;;
420
421         eol = memchr(io->response.buffer, '\n', io.response.size);
422         while (eol == 0) {
423                 fill_buffer(io);
424                 eol = memchr(io->response.buffer, '\n', io.response.size);
425         }
426         if (eol) {
427
428 }
429 #endif
430
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);
436 }
437
438 void append_timeheader(struct tls_buffer *buf, char *header, time_t ts) {
439         char timestr[80];
440         struct tm *tm;
441
442         tm = gmtime(&ts);
443
444         strftime(timestr, sizeof timestr, "%a, %d %b %Y %H:%M:%S GMT", tm);
445         append_header(buf, header, timestr);
446 }
447
448 static void pdots(int len, int ch, unsigned long was, unsigned long now,
449                 unsigned long total) {
450         was = len * was / total;
451         if (now > total) {
452                 now = total;
453         }
454         now = len * now / total;
455         while (was++ < now) {
456                 putc(ch,stderr);
457         }
458 }
459
460 static void fake_header(struct io *io, int fd) {
461         struct stat st;
462         int code = 200, rv;
463         char *message, codestr[5], length[32];
464         struct tls_buffer *hdr = &io->response;
465
466         if (fd == -1) {
467                 switch (errno) {
468                         case EACCES: code = 403; break;
469                         case ENOENT: code = 404; break;
470                         default: code = 500; break;
471                 }
472         } else {
473                 rv = fstat(fd, &st);
474                 if (rv == -1) {
475                         code = 500;
476                 }
477         }
478
479         if (io->last_modified >= st.st_mtime) {
480                 code = 304;
481         }
482
483         switch (code) {
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;
489                 default: break;
490         }
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);
496
497         append_timeheader(hdr, "Date", time(NULL));
498         append_header(hdr, "Server", "zpm-fetchurl/0.9");
499         if (code < 400) {
500                 append_timeheader(hdr, "Last-Modified", st.st_mtime);
501                 sprintf(length, "%zu", st.st_size);
502                 append_header(hdr, "Content-Length", length);
503         }
504
505         append_header(hdr, "Connection", "close");
506         append_header(hdr, "Content-Type", "application/octet-stream");
507         tls_buffer_append(hdr, "\r\n", 2);
508 }
509
510 char *pathlast(char *path) {
511         char *last = 0;
512         size_t len = 0;
513
514         if (path == 0) {
515                 return 0;
516         }
517
518         while (*path == '/') {
519                 path++;
520         }
521
522         do {
523                 last = path;
524                 len = 0;
525                 while (*path && *path != '/') {
526                         path++;
527                         len++;
528                 }
529                 while (*path == '/') {
530                         path++;
531                 }
532         } while (*path);
533
534         if (len == 0) {
535                 return 0;
536         }
537
538         return strndup(last, len);
539 }
540
541 static time_t file_mtime(char *path) {
542         struct stat st;
543         int rv;
544
545         rv = stat(path, &st);
546         if (rv == -1) {
547                 if (errno == ENOENT) {
548                         return 0;
549                 } 
550                 perror("stat failed:");
551                 return -1;
552         }
553
554         return st.st_mtime;
555 }
556
557 int main(int ac, char *av[]) {
558         int sockfd, port = -1, rv;
559         ssize_t ret;
560         int option;
561 #if 0
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];
565 #endif
566         char *req_file = 0;
567         char *host = 0;
568         struct tls_uri uri = { 0 };
569         char *outfile = 0;
570         int raw = 0, head = 0;
571         int out = 1; /* output file descriptor */
572         int use_tls = 0;
573         struct io io = { {0}, 0, -1, 0, 0, 0, 0, 0 };
574         struct TLSContext *clientssl = 0;
575         int failsilent = 0;
576         char *lmfile = 0;
577         int progressbar = 0;
578         struct tls_buffer request;
579         char lmtime[80];
580         char *eoh = 0;
581         size_t total = 0;
582         size_t header_len;
583         char *url = 0;
584         int redirs = 0, redirlimit = 50, printstatus = 0;
585         int verifypolicy = 1, calcoutfile = 0, ifnewer = 0;
586
587         ltc_mp = tfm_desc;
588
589         while ((option = getopt(ac, av, "o:OrIfz:np#R:SkK")) != -1) {
590                 switch (option) {
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;
596                         case 'I': head = 1;
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;
602                         case 'p':
603                         case '#': progressbar = 1; break;
604                         default:
605                                   exit(EXIT_FAILURE);
606                                   break;
607                 }
608         }
609
610         if (ac < optind) {
611                 fprintf(stderr, "Usage: %s uri\n", av[0]);
612                 exit(EXIT_FAILURE);
613         }
614
615         url = strdup(av[optind]);
616         if (!url) {
617                 exit(EXIT_FAILURE);
618         }
619
620         io.last_modified = 0;
621
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
628                  */
629                 if (!outfile) {
630                         fprintf(stderr, "unable to determine outfile\n");
631                         exit(EXIT_FAILURE);
632                 }
633         }
634
635         if (ifnewer && outfile && !lmfile) {
636                 lmfile = outfile;
637         }
638
639         if (lmfile) {
640                 struct tm *mtime;
641                 time_t ts;
642
643                 ts = file_mtime(lmfile);
644
645                 if (ts == -1) {
646                         exit(EXIT_FAILURE);
647                 } else if (ts != 0) {
648                         io.last_modified = ts;
649                         mtime = gmtime(&ts);
650                         strftime(lmtime, sizeof lmtime, "%a, %d %b %Y %H:%M:%S GMT", mtime);
651                 } else {
652                         lmfile = 0;
653                 }
654         }
655
656         signal(SIGPIPE, SIG_IGN);
657
658         tls_buffer_init(&io.response, 0);
659         tls_buffer_init(&request, 128);
660
661         while (redirs++ <= redirlimit) {
662                 tls_free_uri(&uri);
663                 io.response.len = 0;
664                 request.len = 0;
665                 eoh = 0;
666
667                 tls_parse_uri(url, &uri);
668                 host = uri.host;
669                 port = atoi(uri.port);
670                 req_file = uri.path;
671
672                 /* construct request */
673                 if (head) {
674                         tls_buffer_append(&request, "HEAD ", 5);
675                 } else {
676                         tls_buffer_append(&request, "GET ", 4);
677                 }
678                 tls_buffer_append(&request, uri.path, strlen(uri.path));
679                 tls_buffer_append(&request, " HTTP/1.1\r\n", 11);
680
681                 append_header(&request, "Host", host);
682                 append_header(&request, "Connection", "close");
683                 if (lmfile) {
684                         append_header(&request, "If-Modified-Since", lmtime);
685                 }
686                 tls_buffer_append(&request, "\r\n", 2);
687
688                 if (!strcmp(uri.scheme, "https")) {
689                         use_tls = 1;
690
691                         clientssl = tls_create_context(TLS_CLIENT, TLS_V12);
692
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)
697                          */
698                         if (verifypolicy == 2) {
699                                 char *cert_path = 0;
700                                 cert_path = getenv("ZPM_CERTFILE");
701                                 if (!cert_path) {
702                                         cert_path = "/var/lib/zpm/roots.pem";
703                                 }
704                                 rv = tls_load_root_file(clientssl, cert_path);
705                                 if (rv == -1) {
706                                         fprintf(stderr, "Error loading root certs\n");
707                                         return 1;
708                                 }
709                                 tls_set_verify(clientssl, verify_roots);
710                         } else if (verifypolicy == 1) {
711                                 tls_set_verify(clientssl, verify_first);
712                         } else {
713                                 tls_set_verify(clientssl, verify_trust);
714                         }
715
716                         if (!clientssl) {
717                                 fprintf(stderr, "Error initializing client context\n");
718                                 return -1;
719                         }
720                         tls_sni_set(clientssl, uri.host);
721                         clientssl->sync = 1;
722                         io.tls = clientssl;
723                         sockfd = open_tcp_connection(host, port);
724                         if (sockfd < 0) {
725                                 perror("can't open connection");
726                                 exit(EXIT_FAILURE);
727                         }
728                         tls_set_fd(clientssl, sockfd);
729                         if ((rv = tls_connect(clientssl)) != 1) {
730                                 fprintf(stderr, "Handshake Error %i\n", rv);
731                                 return 1;
732                         }
733                         ret = tls_write(clientssl, request.buffer, request.len);
734                 } else if (!strcmp(uri.scheme, "http")) {
735                         sockfd = open_tcp_connection(host, port);
736                         if (sockfd < 0) {
737                                 perror("can't open connection");
738                                 exit(EXIT_FAILURE);
739                         }
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);
744                         ret = 0;
745                 } else {
746                         fprintf(stderr, "scheme %s unknown\n", uri.scheme);
747                         exit(EXIT_FAILURE);
748                 }
749
750                 if (ret == -1) {
751                         fprintf(stderr, "unable to write http request: %s\n", strerror(errno));
752                         exit(EXIT_FAILURE);
753                 }
754
755                 io.socket = sockfd;
756
757                 do {
758                         if (io.response.len >= 4) {
759                                 eoh = strstr(io.response.buffer, "\r\n\r\n");
760                         }
761                         if (!eoh) {
762                                 ret = fill_buffer(&io);
763                                 if (ret <= 0) {
764                                         break;
765                                 }
766                         }
767                 } while (!eoh);
768
769                 if (!eoh) {
770                         /* never got (complet) header */
771                         fprintf(stderr, "incomplete response to %s\n", av[optind]);
772                         exit(EXIT_FAILURE);
773                 }
774
775                 header_len = (size_t)(eoh - io.response.buffer) + 4;
776                 parse_header(&io);
777
778                 switch (io.status_code) {
779                         case 304:
780                                 progressbar = 0;
781                                 break;
782                         case 301:
783                         case 302:
784                         case 303:
785                         case 307:
786                                 free(url);
787                                 url = strdup(io.redirect);
788                                 close(io.socket);
789                                 continue;
790                                 break;
791                 }
792
793                 if (printstatus) {
794                         printf("%d\n", io.status_code);
795                         break;
796                 }
797
798                 if (!raw) {
799                         tls_buffer_shift(&io.response, header_len);
800                 }
801                 if (head) {
802                         io.response.len -= 2;
803                 }
804
805                 if (progressbar) {
806                         if (io.content_length) {
807                                 fprintf(stderr, "(%lu) ", io.content_length);
808                         }
809                 }
810
811                 if (outfile) {
812                         out = open(outfile, O_WRONLY|O_CREAT, 0600);
813                         if (out == -1) {
814                                 perror("can't open output file:");
815                                 exit(EXIT_FAILURE);
816                         }
817                 }
818
819                 do {
820                         write(out, io.response.buffer, io.response.len);
821                         ret = io.response.len;
822                         io.response.len = 0;
823
824                         if (progressbar) {
825                                 if (io.content_length) {
826                                         pdots(50, '.', total, total+ret,
827                                                         io.content_length);
828                                 } else {
829                                         putc('\r', stderr);
830                                         fprintf(stderr, "%zu", total+ret);
831                                 }
832                                 total += ret;
833                         }
834                         if (head) {
835                                 break;
836                         }
837                         ret = fill_buffer(&io);
838                 } while (ret > 0);
839
840                 if (ret < 0) {
841                         fprintf(stderr, "%s read error %zd\n", uri.scheme, ret);
842                 }
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;
846                 ts[1].tv_nsec = 0;
847
848                 futimens(out, ts);
849                 close(out);
850                 tls_buffer_free(&io.response);
851                 break;
852         }
853
854         if (use_tls) {
855                 tls_shutdown(clientssl);
856                 tls_free(clientssl);
857         }
858
859         close(sockfd);
860         if (progressbar && io.status_code == 200) {
861                 fprintf(stderr, "(%lu)", total);
862                 putc('\n',stderr);
863         }
864
865         return io.status_code < 400 ? 0 : EXIT_FAILURE;
866 }