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