]> pd.if.org Git - zpackage/blob - src/fetchurl.c
remove stray debug output
[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 tls_buffer chunkbuf;
280         struct TLSContext *tls;
281         int socket;
282         int chunked;
283         int chunknum;
284         size_t chunksize;
285         size_t chunkleft;
286         size_t chunktotal;
287         size_t chunkbytesread;
288         int status_code;
289         time_t last_modified;
290         time_t date;
291         size_t content_length;
292         size_t received;
293         char *redirect;
294 };
295 ssize_t unchunk(struct io *io);
296
297 int month(char *m) {
298         char *months[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul",
299                 "Aug", "Sep", "Oct", "Nov", "Dec" };
300         int i;
301
302         for (i=0; i < 12; i++) {
303                 if (!strncasecmp(m, months[i], 3)) {
304                         return i+1;
305                 }
306         }
307         return 0;
308 }
309
310 /* Wed, 06 Feb 2019 10:06:05 GMT */
311 time_t parse_date(char *d) {
312         struct tm tm = { 0 };
313         int rv;
314
315         int h, m, s, dom, Y;
316         char M[4];
317         rv = sscanf(d, "%*[a-zA-Z,] %d %s %d %d:%d:%d", &dom, M, &Y, &h, &m, &s);
318         if (rv == 6) {
319                 tm.tm_year = Y - 1900;
320                 tm.tm_hour = h;
321                 tm.tm_min = m;
322                 tm.tm_sec = s;
323                 tm.tm_mon = month(M)-1;
324                 tm.tm_mday = dom;
325
326                 return mktime(&tm);
327         }
328         return -1;
329 }
330
331 char *find_header(struct io *io, char *header, size_t *len) {
332         char *eoh, *soh;
333         size_t hlen;
334
335         *len = 0;
336
337         hlen = strlen(header);
338         eoh = strstr(io->response.buffer, "\r\n\r\n");
339         if (!eoh) {
340                 return 0;
341         }
342         soh = io->response.buffer;
343         do {
344                 soh = strstr(soh, "\r\n");
345                 if (soh == eoh) {
346                         break;
347                 }
348                 soh += 2;
349                 if (!memcmp(soh, header, hlen)) {
350                         break;
351                 }
352         } while (soh < eoh);
353
354         if (soh >= eoh) {
355                 return 0;
356         }
357         eoh = strstr(soh, "\r\n");
358         soh += hlen;
359         while (soh < eoh && isspace(*soh)) {
360                 soh++;
361         }
362         *len = (eoh - soh);
363         return soh;
364 }
365
366 void parse_header(struct io *io) {
367         char *s = io->response.buffer;
368         int code = 0;
369         char *hval;
370         size_t hlen;
371
372         while (!isspace(*s)) {
373                 s++;
374         }
375         while (isspace(*s)) {
376                 s++;
377         }
378         code = strtol(s, 0, 10);
379         io->status_code = code;
380
381         hval = find_header(io, "Date:", &hlen);
382         if (hval) {
383                 hval[hlen] = 0;
384                 io->date = parse_date(hval);
385                 hval[hlen] = '\r';
386         }
387         hval = find_header(io, "Last-Modified:", &hlen);
388         if (hval) {
389                 hval[hlen] = 0;
390                 io->last_modified = parse_date(hval);
391                 hval[hlen] = '\r';
392         }
393
394         hval = find_header(io, "Content-Length:", &hlen);
395         if (hval) {
396                 hval[hlen] = 0;
397                 io->content_length = strtoul(hval, 0, 10);
398                 hval[hlen] = '\r';
399         }
400
401         hval = find_header(io, "Transfer-Encoding:", &hlen);
402         if (hval) {
403                 hval[hlen] = 0;
404                 io->content_length = strtoul(hval, 0, 10);
405                 if (!strcmp(hval, "chunked")) {
406                         io->chunked = 1;
407                 }
408                 hval[hlen] = '\r';
409         }
410
411         switch (code) {
412                 case 301:
413                 case 302:
414                 case 303:
415                 case 307:
416                         hval = find_header(io, "Location:", &hlen);
417                         if (hval) {
418                                 io->redirect = strndup(hval, hlen);
419                         }
420                         break;
421                 default:
422                         break;
423         }
424
425 }
426
427 /* fill buffer needs to put bytes into the response buffer
428  * if the transfer encoding is chunked, it will need to
429  * put the bytes into the chunkbuf first, then call
430  * unchunk.  if unchunk return 0, then it needs more data,
431  * otherwise unchunk returns the number of bytes transferred
432  */
433
434 ssize_t fill_buffer(struct io *io) {
435         unsigned char buffer[4096];
436         ssize_t ret = 0;
437
438         ret = unchunk(io);
439
440         while (ret == 0) {
441                 if (io->tls) {
442                         ret = tls_read(io->tls, buffer, sizeof buffer);
443                 } else {
444                         ret = read(io->socket, buffer, sizeof buffer);
445                 }
446
447                 if (ret <= 0) {
448                         break;
449                 }
450
451                 if (io->chunked) {
452                         tls_buffer_append(&io->chunkbuf, buffer, ret);
453                         //fwrite(buffer, ret, 1, stderr);
454                         ret = unchunk(io);
455                         if (ret != 0 || io->chunksize == 0) {
456                                 break;
457                         }
458                 } else {
459                         tls_buffer_append(&io->response, buffer, ret);
460                         break;
461                 }
462         }
463
464         return ret;
465 }
466
467 /* essentially memmem */
468 void *lookfor(const void *buf, size_t buflen, const void *pattern, size_t len) {
469       const char *bf = buf;
470       const char *pt = pattern;
471       const char *p = bf;
472
473       while (len <= (buflen - (p - bf))) {
474             if ((p = memchr(p, *pt, buflen - (p - bf))) != 0) {
475                   if (memcmp(p, pattern, len) == 0) {
476                         return (void *)p;
477                   } else {
478                           p++;
479                   }
480             } else {
481                     break;
482             }
483       }
484       return NULL;
485 }
486
487 /* returns read chunksize, unshifts the line */
488 ssize_t read_chunksize(struct io *io) {
489         char *cr;
490         ssize_t cs;
491
492         //fwrite(io->chunkbuf.buffer, io->chunkbuf.len, 1, stderr);
493         
494         /* there could be up to two leading bytes */
495         if (io->chunkbuf.len >= 2 && io->chunkbuf.buffer[0] == '\r' && io->chunkbuf.buffer[1] == '\n') {
496                 tls_buffer_shift(&io->chunkbuf, 2);
497         }
498
499         cr = lookfor(io->chunkbuf.buffer, io->chunkbuf.len, "\r\n", 2);
500
501         if (cr == 0) {
502                 return -1;
503         }
504
505         cs = strtol(io->chunkbuf.buffer, 0, 16);
506         tls_buffer_shift(&io->chunkbuf, cr - io->chunkbuf.buffer + 2);
507
508         return cs;
509 }
510
511 /* unchunk's job is to move bytes from the chunk buf to the response buf */
512 /* return bytes from chunk, 0 if unable.  once last chunk, changed chunked
513  * to 0?
514  */
515 ssize_t unchunk(struct io *io) {
516         ssize_t bytes_to_move = 0;
517         ssize_t chunksize;
518
519         if (!io || !io->chunked) {
520                 return 0;
521         }
522
523         if (io->chunkleft == 0) {
524                 chunksize = read_chunksize(io);
525                 if (chunksize == -1) {
526                         return 0;
527                 }
528                 io->chunksize = chunksize;
529                 if (io->chunksize == 0) {
530                         /* end of chunked data */
531                         io->chunked = 0;
532                         return 0;
533                 }
534                 io->chunknum++;
535                 io->chunkleft = io->chunksize;
536                 io->chunktotal += io->chunksize;
537         }
538
539         if (io->chunkbuf.len == 0) {
540                 /* need more bytes */
541                 return 0;
542         }
543
544         bytes_to_move = io->chunkbuf.len < io->chunkleft ? io->chunkbuf.len : io->chunkleft;
545
546         tls_buffer_append(&io->response, io->chunkbuf.buffer, bytes_to_move);
547         io->chunkleft -= bytes_to_move;
548         io->chunkbytesread += bytes_to_move;
549
550         /* chunk is terminated with a crlf */
551         //tls_buffer_shift(&io->chunkbuf, bytes_to_move + io->chunkleft ? 0 : 2);
552         tls_buffer_shift(&io->chunkbuf, bytes_to_move);
553
554         return bytes_to_move;
555 }
556
557 #if 0
558 char *nextline(struct io *io) {
559         char *eol = 0;;
560
561         eol = memchr(io->response.buffer, '\n', io.response.size);
562         while (eol == 0) {
563                 fill_buffer(io);
564                 eol = memchr(io->response.buffer, '\n', io.response.size);
565         }
566         if (eol) {
567
568 }
569 #endif
570
571 void append_header(struct tls_buffer *buf, char *header, char *val) {
572         tls_buffer_append(buf, header, strlen(header));
573         tls_buffer_append(buf, ": ", 2);
574         tls_buffer_append(buf, val, strlen(val));
575         tls_buffer_append(buf, "\r\n", 2);
576 }
577
578 void append_timeheader(struct tls_buffer *buf, char *header, time_t ts) {
579         char timestr[80];
580         struct tm *tm;
581
582         tm = gmtime(&ts);
583
584         strftime(timestr, sizeof timestr, "%a, %d %b %Y %H:%M:%S GMT", tm);
585         append_header(buf, header, timestr);
586 }
587
588 static void pdots(int len, int ch, unsigned long was, unsigned long now,
589                 unsigned long total) {
590         was = len * was / total;
591         if (now > total) {
592                 now = total;
593         }
594         now = len * now / total;
595         while (was++ < now) {
596                 putc(ch,stderr);
597         }
598 }
599
600 static void fake_header(struct io *io, int fd) {
601         struct stat st;
602         int code = 200, rv;
603         char *message, codestr[5], length[32];
604         struct tls_buffer *hdr = &io->response;
605
606         if (fd == -1) {
607                 switch (errno) {
608                         case EACCES: code = 403; break;
609                         case ENOENT: code = 404; break;
610                         default: code = 500; break;
611                 }
612         } else {
613                 rv = fstat(fd, &st);
614                 if (rv == -1) {
615                         code = 500;
616                 }
617         }
618
619         if (io->last_modified >= st.st_mtime) {
620                 code = 304;
621         }
622
623         switch (code) {
624                 case 200: message = "OK"; break;
625                 case 304: message = "Not Modified"; break;
626                 case 403: message = "Forbidden"; break;
627                 case 404: message = "Not Found"; break;
628                 case 500: message = "Internal Server Error"; break;
629                 default: break;
630         }
631         sprintf(codestr, "%0.3d ", code);
632         tls_buffer_append(hdr, "HTTP/1.1 ", 9);
633         tls_buffer_append(hdr, codestr, 4);
634         tls_buffer_append_str(hdr, message);
635         tls_buffer_append(hdr, "\r\n", 2);
636
637         append_timeheader(hdr, "Date", time(NULL));
638         append_header(hdr, "Server", "zpm-fetchurl/0.9");
639         if (code < 400) {
640                 append_timeheader(hdr, "Last-Modified", st.st_mtime);
641                 sprintf(length, "%zu", st.st_size);
642                 append_header(hdr, "Content-Length", length);
643         }
644
645         append_header(hdr, "Connection", "close");
646         append_header(hdr, "Content-Type", "application/octet-stream");
647         tls_buffer_append(hdr, "\r\n", 2);
648 }
649
650 char *pathlast(char *path) {
651         char *last = 0;
652         size_t len = 0;
653
654         if (path == 0) {
655                 return 0;
656         }
657
658         while (*path == '/') {
659                 path++;
660         }
661
662         do {
663                 last = path;
664                 len = 0;
665                 while (*path && *path != '/') {
666                         path++;
667                         len++;
668                 }
669                 while (*path == '/') {
670                         path++;
671                 }
672         } while (*path);
673
674         if (len == 0) {
675                 return 0;
676         }
677
678         return strndup(last, len);
679 }
680
681 static time_t file_mtime(char *path) {
682         struct stat st;
683         int rv;
684
685         rv = stat(path, &st);
686         if (rv == -1) {
687                 if (errno == ENOENT) {
688                         return 0;
689                 } 
690                 perror("stat failed:");
691                 return -1;
692         }
693
694         return st.st_mtime;
695 }
696
697 int main(int ac, char *av[]) {
698         int sockfd, port = -1, rv;
699         ssize_t ret;
700         int option;
701 #if 0
702         char msg[] = "GET %s HTTP/1.1\r\nHost: %s:%i\r\nConnection: close\r\n\r\n";
703         char msg2[] = "GET %s HTTP/1.1\r\nHost: %s:%i\r\nLast-Modified: %s\r\nConnection: close\r\n\r\n";
704         char msg_buffer[1024];
705 #endif
706         char *req_file = 0;
707         char *host = 0;
708         struct tls_uri uri = { 0 };
709         char *outfile = 0;
710         int raw = 0, head = 0;
711         int out = 1; /* output file descriptor */
712         int use_tls = 0;
713         struct io io = { {0}, {0}, 0, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
714         struct TLSContext *clientssl = 0;
715         int failsilent = 0;
716         char *lmfile = 0;
717         int progressbar = 0;
718         struct tls_buffer request;
719         char lmtime[80];
720         char *eoh = 0;
721         char *user_agent = 0;
722         size_t total = 0;
723         size_t header_len;
724         char *url = 0;
725         int redirs = 0, redirlimit = 50, printstatus = 0, showreq = 0;
726         int verifypolicy = 1, calcoutfile = 0, ifnewer = 0;
727
728         ltc_mp = tfm_desc;
729
730         while ((option = getopt(ac, av, "o:OrIfz:np#RL:SkKU:")) != -1) {
731                 switch (option) {
732                         case 'o': outfile = optarg; break;
733                         case 'O': calcoutfile = 1; break;
734                         case 'S': printstatus = 1; head = 1; break;
735                         case 'k': verifypolicy = 0; break;
736                         case 'K': verifypolicy = 2; break;
737                         case 'U': user_agent = optarg; break;
738                         case 'I': head = 1;
739                         case 'r': raw = 1; break;
740                         case 'R': showreq = 1; break;
741                         case 'f': failsilent = 1; break;
742                         case 'z': lmfile = optarg; break;
743                         case 'n': ifnewer = 1; break;
744                         case 'L': redirlimit = strtol(optarg, 0, 10); break;
745                         case 'p':
746                         case '#': progressbar = 1; break;
747                         default:
748                                   exit(EXIT_FAILURE);
749                                   break;
750                 }
751         }
752
753         if (ac < optind) {
754                 fprintf(stderr, "Usage: %s uri\n", av[0]);
755                 exit(EXIT_FAILURE);
756         }
757
758         url = strdup(av[optind]);
759         if (!url) {
760                 exit(EXIT_FAILURE);
761         }
762
763         io.last_modified = 0;
764
765         if (calcoutfile && !outfile) {
766                 tls_parse_uri(url, &uri);
767                 outfile = pathlast(uri.path);
768                 /* outfile leaks memory here, so if this
769                  * were turned into a library function,
770                  * we'd need to track it
771                  */
772                 if (!outfile) {
773                         fprintf(stderr, "unable to determine outfile\n");
774                         exit(EXIT_FAILURE);
775                 }
776         }
777
778         if (ifnewer && outfile && !lmfile) {
779                 lmfile = outfile;
780         }
781
782         if (lmfile) {
783                 struct tm *mtime;
784                 time_t ts;
785
786                 ts = file_mtime(lmfile);
787
788                 if (ts == -1) {
789                         exit(EXIT_FAILURE);
790                 } else if (ts != 0) {
791                         io.last_modified = ts;
792                         mtime = gmtime(&ts);
793                         strftime(lmtime, sizeof lmtime, "%a, %d %b %Y %H:%M:%S GMT", mtime);
794                 } else {
795                         lmfile = 0;
796                 }
797         }
798
799         signal(SIGPIPE, SIG_IGN);
800
801         tls_buffer_init(&io.response, 0);
802         tls_buffer_init(&request, 128);
803
804         while (redirs++ <= redirlimit) {
805                 tls_free_uri(&uri);
806                 io.response.len = 0;
807                 io.chunked = 0;
808                 request.len = 0;
809                 eoh = 0;
810
811                 tls_parse_uri(url, &uri);
812                 host = uri.host;
813                 port = atoi(uri.port);
814                 req_file = uri.path;
815
816                 /* construct request */
817                 if (head) {
818                         tls_buffer_append(&request, "HEAD ", 5);
819                 } else {
820                         tls_buffer_append(&request, "GET ", 4);
821                 }
822                 tls_buffer_append(&request, uri.encoded_path, strlen(uri.encoded_path));
823                 if (uri.encoded_query) {
824                         tls_buffer_append(&request, "?", 1);
825                         tls_buffer_append(&request, uri.encoded_query, strlen(uri.encoded_query));
826                 }
827                 tls_buffer_append(&request, " HTTP/1.1\r\n", 11);
828
829                 append_header(&request, "Host", host);
830                 if (user_agent) {
831                         append_header(&request, "User-Agent", user_agent);
832                 }
833                 append_header(&request, "Accept", "*/*");
834                 //append_header(&request, "Accept-Encoding", "chunked, identity;q=0.5");
835                 append_header(&request, "Connection", "close");
836                 if (lmfile) {
837                         append_header(&request, "If-Modified-Since", lmtime);
838                 }
839                 tls_buffer_append(&request, "\r\n", 2);
840
841                 if (!strcmp(uri.scheme, "https")) {
842                         use_tls = 1;
843
844                         clientssl = tls_create_context(TLS_CLIENT, TLS_V12);
845
846                         /* optionally, we can set a certificate validation
847                          * callback function if set_verify is not called, and
848                          * root ca is set, `tls_default_verify` will be used
849                          * (does exactly what `verify` does in this example)
850                          */
851                         if (verifypolicy == 2) {
852                                 char *cert_path = 0;
853                                 cert_path = getenv("ZPM_CERTFILE");
854                                 if (!cert_path) {
855                                         cert_path = "/var/lib/zpm/roots.pem";
856                                 }
857                                 rv = tls_load_root_file(clientssl, cert_path);
858                                 if (rv == -1) {
859                                         fprintf(stderr, "Error loading root certs\n");
860                                         return 1;
861                                 }
862                                 tls_set_verify(clientssl, verify_roots);
863                         } else if (verifypolicy == 1) {
864                                 tls_set_verify(clientssl, verify_first);
865                         } else {
866                                 tls_set_verify(clientssl, verify_trust);
867                         }
868
869                         if (!clientssl) {
870                                 fprintf(stderr, "Error initializing client context\n");
871                                 return -1;
872                         }
873                         tls_sni_set(clientssl, uri.host);
874                         clientssl->sync = 1;
875                         io.tls = clientssl;
876                         sockfd = open_tcp_connection(host, port);
877                         if (sockfd < 0) {
878                                 perror("can't open connection");
879                                 exit(EXIT_FAILURE);
880                         }
881                         tls_set_fd(clientssl, sockfd);
882                         if ((rv = tls_connect(clientssl)) != 1) {
883                                 fprintf(stderr, "Handshake Error %i\n", rv);
884                                 return 1;
885                         }
886                         ret = tls_write(clientssl, request.buffer, request.len);
887                 } else if (!strcmp(uri.scheme, "http")) {
888                         sockfd = open_tcp_connection(host, port);
889                         if (sockfd < 0) {
890                                 perror("can't open connection");
891                                 exit(EXIT_FAILURE);
892                         }
893                         ret = write(sockfd, request.buffer, request.len);
894                 } else if (!strcmp(uri.scheme, "file")) {
895                         sockfd = open(uri.path, O_RDONLY);
896                         fake_header(&io, sockfd);
897                         ret = 0;
898                 } else {
899                         fprintf(stderr, "scheme %s unknown\n", uri.scheme);
900                         exit(EXIT_FAILURE);
901                 }
902
903                 if (ret == -1) {
904                         fprintf(stderr, "unable to write http request: %s\n", strerror(errno));
905                         exit(EXIT_FAILURE);
906                 }
907
908                 io.socket = sockfd;
909
910                 eoh = 0;
911                 do {
912                         if (io.response.len >= 4) {
913                                 eoh = strstr(io.response.buffer, "\r\n\r\n");
914                         }
915                         if (!eoh) {
916                                 ret = fill_buffer(&io);
917                                 if (ret <= 0) {
918                                         break;
919                                 }
920                         }
921                 } while (!eoh);
922
923                 if (!eoh) {
924                         /* never got (complete) header */
925                         fprintf(stderr, "incomplete response (ret = %zd) to %s\n", ret, url);
926                         fprintf(stderr, "have:\n");
927                         fwrite(io.response.buffer, io.response.len, 1, stderr);
928                         exit(EXIT_FAILURE);
929                 }
930
931                 header_len = (size_t)(eoh - io.response.buffer) + 4;
932
933                 parse_header(&io);
934
935                 switch (io.status_code) {
936                         case 304:
937                                 progressbar = 0;
938                                 break;
939                         case 301:
940                         case 302:
941                         case 303:
942                         case 307:
943                                 free(url);
944                                 url = strdup(io.redirect);
945                                 close(io.socket);
946                                 continue;
947                                 break;
948                 }
949
950                 if (printstatus) {
951                         printf("%d\n", io.status_code);
952                         break;
953                 }
954                 if (showreq) {
955                         fwrite(request.buffer, request.len, 1, stderr);
956                 }
957
958                 if (head) {
959                         io.response.len -= 2;
960                 }
961
962                 if (outfile) {
963                         out = open(outfile, O_WRONLY|O_CREAT|O_TRUNC, 0600);
964                         if (out == -1) {
965                                 perror("can't open output file:");
966                                 exit(EXIT_FAILURE);
967                         }
968                 }
969
970                 if (progressbar) {
971                         if (io.content_length) {
972                                 fprintf(stderr, "(%lu) ", io.content_length);
973                         }
974                 }
975
976                 if (head) {
977                         write(out, io.response.buffer, io.response.len);
978                         break;
979                 }
980
981                 if (raw) {
982                         write(out, io.response.buffer, header_len);
983                 }
984                 tls_buffer_shift(&io.response, header_len);
985
986                 if (io.chunked) {
987                         /* we've written out the head if needed, so
988                          * what's in the response buffer is the
989                          * chunked encoding, so just reassign that
990                          * to the chunkbuf and reinit */
991                         io.chunkbuf = io.response;
992                         tls_buffer_init(&io.response, 0);
993                         /* and put whatever we've got into the response
994                          * buffer, may not be needed, fill buffer
995                          * can handle it.
996                          */ 
997                         //unchunk(&io);
998                 }
999
1000                 do {
1001                         if (io.response.len) {
1002                                 if (io.content_length && io.response.len + io.received > io.content_length) {
1003                                         io.response.len = io.content_length - io.received;
1004                                         /* we just ignore trailing garbage */
1005                                 }
1006                                 write(out, io.response.buffer, io.response.len);
1007                                 io.received += io.response.len;
1008                                 ret = io.response.len;
1009                                 io.response.len = 0;
1010                         }
1011
1012                         if (progressbar) {
1013                                 if (io.content_length) {
1014                                         pdots(50, '.', total, total+ret,
1015                                                         io.content_length);
1016                                 } else {
1017                                         putc('\r', stderr);
1018                                         fprintf(stderr, "%zu", io.received);
1019                                 }
1020                                 total += ret;
1021                         }
1022                         if (head) {
1023                                 break;
1024                         }
1025                         if (io.content_length && io.received >= io.content_length) {
1026                                 break;
1027                         }
1028                         ret = fill_buffer(&io);
1029                 } while (ret > 0);
1030
1031                 //fprintf(stderr, "total received: %zu/%zu\n", io.received, io.content_length);
1032                 if (ret < 0) {
1033                         fprintf(stderr, "%s read error %zd\n", uri.scheme, ret);
1034                 }
1035                 if (io.last_modified != 0) {
1036                         struct timespec ts[2];
1037                         ts[0].tv_sec = 0; ts[0].tv_nsec = UTIME_OMIT;
1038                         ts[1].tv_sec = io.last_modified;
1039                         ts[1].tv_nsec = 0;
1040                         futimens(out, ts);
1041                 }
1042                 close(out);
1043                 tls_buffer_free(&io.response);
1044                 break;
1045         }
1046
1047         if (use_tls) {
1048                 tls_shutdown(clientssl);
1049                 tls_free(clientssl);
1050         }
1051
1052         close(sockfd);
1053         if (progressbar && io.status_code == 200) {
1054                 if (total == io.content_length || io.content_length == 0) {
1055                         fprintf(stderr, " done\n");
1056                 } else if (io.content_length != total) {
1057                         fprintf(stderr, "failed (%zu bytes read)\n", total);
1058                         io.status_code = 531; /* non official code */
1059                 }
1060         }
1061
1062         return io.status_code < 400 ? 0 : EXIT_FAILURE;
1063 }