Annotation of src/usr.bin/ftp/fetch.c, Revision 1.187
1.187 ! beck 1: /* $OpenBSD: fetch.c,v 1.186 2020/01/15 14:49:38 jca Exp $ */
1.15 millert 2: /* $NetBSD: fetch.c,v 1.14 1997/08/18 10:20:20 lukem Exp $ */
1.1 millert 3:
4: /*-
5: * Copyright (c) 1997 The NetBSD Foundation, Inc.
6: * All rights reserved.
7: *
8: * This code is derived from software contributed to The NetBSD Foundation
9: * by Jason Thorpe and Luke Mewburn.
10: *
11: * Redistribution and use in source and binary forms, with or without
12: * modification, are permitted provided that the following conditions
13: * are met:
14: * 1. Redistributions of source code must retain the above copyright
15: * notice, this list of conditions and the following disclaimer.
16: * 2. Redistributions in binary form must reproduce the above copyright
17: * notice, this list of conditions and the following disclaimer in the
18: * documentation and/or other materials provided with the distribution.
19: *
20: * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
21: * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
22: * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
1.15 millert 23: * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
24: * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
1.1 millert 25: * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
26: * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
27: * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
28: * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
29: * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
30: * POSSIBILITY OF SUCH DAMAGE.
31: */
32:
33: /*
34: * FTP User Program -- Command line file retrieval
35: */
36:
37: #include <sys/types.h>
38: #include <sys/socket.h>
1.22 deraadt 39: #include <sys/stat.h>
1.1 millert 40:
41: #include <netinet/in.h>
42:
43: #include <arpa/ftp.h>
44: #include <arpa/inet.h>
45:
46: #include <ctype.h>
47: #include <err.h>
1.17 millert 48: #include <libgen.h>
1.1 millert 49: #include <netdb.h>
50: #include <fcntl.h>
1.3 millert 51: #include <signal.h>
1.175 deraadt 52: #include <vis.h>
1.1 millert 53: #include <stdio.h>
1.61 deraadt 54: #include <stdarg.h>
1.19 deraadt 55: #include <errno.h>
1.1 millert 56: #include <stdlib.h>
57: #include <string.h>
58: #include <unistd.h>
1.40 fgsch 59: #include <util.h>
1.73 drahn 60: #include <resolv.h>
1.1 millert 61:
1.154 deraadt 62: #ifndef NOSSL
1.134 jsing 63: #include <tls.h>
1.154 deraadt 64: #else /* !NOSSL */
1.134 jsing 65: struct tls;
1.154 deraadt 66: #endif /* !NOSSL */
1.61 deraadt 67:
1.1 millert 68: #include "ftp_var.h"
1.86 martynas 69: #include "cmds.h"
1.1 millert 70:
1.186 jca 71: static int file_get(const char *, const char *);
1.157 deraadt 72: static int url_get(const char *, const char *, const char *, int);
1.178 jca 73: static int save_chunked(FILE *, struct tls *, int , char *, size_t);
1.177 jca 74: static void aborthttp(int);
75: static void abortfile(int);
76: static char hextochar(const char *);
77: static char *urldecode(const char *);
78: static char *recode_credentials(const char *_userinfo);
79: static char *ftp_readline(FILE *, size_t *);
80: static void ftp_close(FILE **, struct tls **, volatile int *);
81: static const char *sockerror(struct tls *);
1.184 jca 82: #ifdef SMALL
83: #define ftp_printf(fp, ...) fprintf(fp, __VA_ARGS__)
84: #else
85: static int ftp_printf(FILE *, const char *, ...);
86: #endif /* SMALL */
1.158 jca 87: #ifndef NOSSL
1.177 jca 88: static int proxy_connect(int, char *, char *);
89: static int stdio_tls_write_wrapper(void *, const char *, int);
90: static int stdio_tls_read_wrapper(void *, char *, int);
1.158 jca 91: #endif /* !NOSSL */
1.14 millert 92:
1.1 millert 93: #define FTP_URL "ftp://" /* ftp URL prefix */
94: #define HTTP_URL "http://" /* http URL prefix */
1.61 deraadt 95: #define HTTPS_URL "https://" /* https URL prefix */
1.22 deraadt 96: #define FILE_URL "file:" /* file URL prefix */
1.6 millert 97: #define FTP_PROXY "ftp_proxy" /* env var with ftp proxy location */
1.1 millert 98: #define HTTP_PROXY "http_proxy" /* env var with http proxy location */
99:
100: #define EMPTYSTRING(x) ((x) == NULL || (*(x) == '\0'))
101:
1.110 guenther 102: static const char at_encoding_warning[] =
1.53 deraadt 103: "Extra `@' characters in usernames and passwords should be encoded as %%40";
1.37 heko 104:
1.177 jca 105: static jmp_buf httpabort;
1.1 millert 106:
1.54 fgsch 107: static int redirect_loop;
1.171 jca 108: static int retried;
1.54 fgsch 109:
1.1 millert 110: /*
1.95 martynas 111: * Determine whether the character needs encoding, per RFC1738:
1.160 krw 112: * - No corresponding graphic US-ASCII.
113: * - Unsafe characters.
1.95 martynas 114: */
115: static int
1.138 jca 116: unsafe_char(const char *c0)
1.95 martynas 117: {
118: const char *unsafe_chars = " <>\"#{}|\\^~[]`";
1.138 jca 119: const unsigned char *c = (const unsigned char *)c0;
1.95 martynas 120:
121: /*
122: * No corresponding graphic US-ASCII.
123: * Control characters and octets not used in US-ASCII.
124: */
125: return (iscntrl(*c) || !isascii(*c) ||
126:
127: /*
128: * Unsafe characters.
129: * '%' is also unsafe, if is not followed by two
130: * hexadecimal digits.
131: */
132: strchr(unsafe_chars, *c) != NULL ||
133: (*c == '%' && (!isxdigit(*++c) || !isxdigit(*++c))));
134: }
135:
136: /*
137: * Encode given URL, per RFC1738.
138: * Allocate and return string to the caller.
139: */
140: static char *
141: url_encode(const char *path)
142: {
143: size_t i, length, new_length;
144: char *epath, *epathp;
145:
146: length = new_length = strlen(path);
147:
148: /*
149: * First pass:
150: * Count unsafe characters, and determine length of the
151: * final URL.
152: */
153: for (i = 0; i < length; i++)
154: if (unsafe_char(path + i))
155: new_length += 2;
156:
157: epath = epathp = malloc(new_length + 1); /* One more for '\0'. */
158: if (epath == NULL)
1.102 halex 159: err(1, "Can't allocate memory for URL encoding");
1.95 martynas 160:
161: /*
162: * Second pass:
163: * Encode, and copy final URL.
164: */
165: for (i = 0; i < length; i++)
166: if (unsafe_char(path + i)) {
1.138 jca 167: snprintf(epathp, 4, "%%" "%02x",
168: (unsigned char)path[i]);
1.95 martynas 169: epathp += 3;
170: } else
171: *(epathp++) = path[i];
172:
173: *epathp = '\0';
174: return (epath);
175: }
176:
1.155 deraadt 177: /* ARGSUSED */
178: static void
179: tooslow(int signo)
180: {
181: dprintf(STDERR_FILENO, "%s: connect taking too long\n", __progname);
182: _exit(2);
183: }
184:
1.95 martynas 185: /*
1.186 jca 186: * Copy a local file (used by the OpenBSD installer).
187: * Returns -1 on failure, 0 on success
188: */
189: static int
190: file_get(const char *path, const char *outfile)
191: {
192: struct stat st;
193: int fd, out, rval = -1, save_errno;
194: volatile sig_t oldintr, oldinti;
195: const char *savefile;
196: char *buf = NULL, *cp;
197: const size_t buflen = 128 * 1024;
198: off_t hashbytes;
199: ssize_t len, wlen;
200:
201: direction = "received";
202:
203: fd = open(path, O_RDONLY);
204: if (fd == -1) {
205: warn("Can't open file %s", path);
206: return -1;
207: }
208:
209: if (fstat(fd, &st) == -1)
210: filesize = -1;
211: else
212: filesize = st.st_size;
213:
214: if (outfile != NULL)
215: savefile = outfile;
216: else {
217: if (path[strlen(path) - 1] == '/') /* Consider no file */
218: savefile = NULL; /* after dir invalid. */
219: else
220: savefile = basename(path);
221: }
222:
223: if (EMPTYSTRING(savefile)) {
224: warnx("No filename after directory (use -o): %s", path);
225: goto cleanup_copy;
226: }
227:
228: /* Open the output file. */
229: if (!pipeout) {
230: out = open(savefile, O_CREAT | O_WRONLY | O_TRUNC, 0666);
231: if (out == -1) {
232: warn("Can't open %s", savefile);
233: goto cleanup_copy;
234: }
235: } else
236: out = fileno(stdout);
237:
238: if ((buf = malloc(buflen)) == NULL)
239: errx(1, "Can't allocate memory for transfer buffer");
240:
241: /* Trap signals */
242: oldintr = NULL;
243: oldinti = NULL;
244: if (setjmp(httpabort)) {
245: if (oldintr)
246: (void)signal(SIGINT, oldintr);
247: if (oldinti)
248: (void)signal(SIGINFO, oldinti);
249: goto cleanup_copy;
250: }
251: oldintr = signal(SIGINT, abortfile);
252:
253: bytes = 0;
254: hashbytes = mark;
255: progressmeter(-1, path);
256:
257: /* Finally, suck down the file. */
258: oldinti = signal(SIGINFO, psummary);
259: while ((len = read(fd, buf, buflen)) > 0) {
260: bytes += len;
261: for (cp = buf; len > 0; len -= wlen, cp += wlen) {
262: if ((wlen = write(out, cp, len)) == -1) {
263: warn("Writing %s", savefile);
264: signal(SIGINFO, oldinti);
265: goto cleanup_copy;
266: }
267: }
268: if (hash && !progress) {
269: while (bytes >= hashbytes) {
270: (void)putc('#', ttyout);
271: hashbytes += mark;
272: }
273: (void)fflush(ttyout);
274: }
275: }
276: save_errno = errno;
277: signal(SIGINFO, oldinti);
278: if (hash && !progress && bytes > 0) {
279: if (bytes < mark)
280: (void)putc('#', ttyout);
281: (void)putc('\n', ttyout);
282: (void)fflush(ttyout);
283: }
284: if (len == -1) {
285: warnc(save_errno, "Reading from file");
286: goto cleanup_copy;
287: }
288: progressmeter(1, NULL);
289: if (verbose)
290: ptransfer(0);
291: (void)signal(SIGINT, oldintr);
292:
293: rval = 0;
294:
295: cleanup_copy:
296: free(buf);
297: if (out >= 0 && out != fileno(stdout))
298: close(out);
299: close(fd);
300:
301: return rval;
302: }
303:
304: /*
1.6 millert 305: * Retrieve URL, via the proxy in $proxyvar if necessary.
1.1 millert 306: * Returns -1 on failure, 0 on success
307: */
1.14 millert 308: static int
1.157 deraadt 309: url_get(const char *origline, const char *proxyenv, const char *outfile, int lastfile)
1.1 millert 310: {
1.69 jsg 311: char pbuf[NI_MAXSERV], hbuf[NI_MAXHOST], *cp, *portnum, *path, ststr[4];
1.62 ray 312: char *hosttail, *cause = "unknown", *newline, *host, *port, *buf = NULL;
1.175 deraadt 313: char *epath, *redirurl, *loctail, *h, *p, gerror[200];
1.186 jca 314: int error, i, isftpurl = 0, isredirect = 0, rval = -1;
1.172 jca 315: int isunavail = 0, retryafter = -1;
1.152 krw 316: struct addrinfo hints, *res0, *res;
1.34 millert 317: const char * volatile savefile;
1.62 ray 318: char * volatile proxyurl = NULL;
1.123 guenther 319: char *credentials = NULL;
1.166 procter 320: volatile int fd = -1, out = -1;
1.97 martynas 321: volatile sig_t oldintr, oldinti;
1.53 deraadt 322: FILE *fin = NULL;
1.1 millert 323: off_t hashbytes;
1.58 grunk 324: const char *errstr;
1.114 tedu 325: ssize_t len, wlen;
1.136 bluhm 326: char *proxyhost = NULL;
1.154 deraadt 327: #ifndef NOSSL
1.61 deraadt 328: char *sslpath = NULL, *sslhost = NULL;
1.123 guenther 329: int ishttpurl = 0, ishttpsurl = 0;
1.159 krw 330: #endif /* !NOSSL */
331: #ifndef SMALL
1.181 jca 332: char *full_host = NULL;
333: const char *scheme;
1.159 krw 334: char *locbase;
1.152 krw 335: struct addrinfo *ares = NULL;
1.181 jca 336: #endif /* !SMALL */
1.134 jsing 337: struct tls *tls = NULL;
1.70 deraadt 338: int status;
1.105 haesbaer 339: int save_errno;
1.113 tedu 340: const size_t buflen = 128 * 1024;
1.178 jca 341: int chunked = 0;
1.14 millert 342:
1.97 martynas 343: direction = "received";
344:
1.62 ray 345: newline = strdup(origline);
346: if (newline == NULL)
1.14 millert 347: errx(1, "Can't allocate memory to parse URL");
1.102 halex 348: if (strncasecmp(newline, HTTP_URL, sizeof(HTTP_URL) - 1) == 0) {
1.62 ray 349: host = newline + sizeof(HTTP_URL) - 1;
1.181 jca 350: #ifndef NOSSL
351: ishttpurl = 1;
352: #endif /* !NOSSL */
1.102 halex 353: #ifndef SMALL
354: scheme = HTTP_URL;
355: #endif /* !SMALL */
356: } else if (strncasecmp(newline, FTP_URL, sizeof(FTP_URL) - 1) == 0) {
1.62 ray 357: host = newline + sizeof(FTP_URL) - 1;
1.14 millert 358: isftpurl = 1;
1.102 halex 359: #ifndef SMALL
360: scheme = FTP_URL;
361: #endif /* !SMALL */
1.183 jca 362: } else if (strncasecmp(newline, HTTPS_URL, sizeof(HTTPS_URL) - 1) == 0) {
1.154 deraadt 363: #ifndef NOSSL
1.62 ray 364: host = newline + sizeof(HTTPS_URL) - 1;
1.61 deraadt 365: ishttpsurl = 1;
1.183 jca 366: #else
367: errx(1, "%s: No HTTPS support", newline);
368: #endif /* !NOSSL */
1.181 jca 369: #ifndef SMALL
1.102 halex 370: scheme = HTTPS_URL;
1.181 jca 371: #endif /* !SMALL */
1.14 millert 372: } else
1.186 jca 373: errx(1, "%s: URL not permitted", newline);
1.6 millert 374:
1.186 jca 375: path = strchr(host, '/'); /* Find path */
376: if (EMPTYSTRING(path)) {
377: if (outfile) { /* No slash, but */
378: path = strchr(host,'\0'); /* we have outfile. */
379: goto noslash;
1.22 deraadt 380: }
1.186 jca 381: if (isftpurl)
382: goto noftpautologin;
383: warnx("No `/' after host (use -o): %s", origline);
384: goto cleanup_url_get;
385: }
386: *path++ = '\0';
387: if (EMPTYSTRING(path) && !outfile) {
388: if (isftpurl)
389: goto noftpautologin;
390: warnx("No filename after host (use -o): %s", origline);
391: goto cleanup_url_get;
1.14 millert 392: }
1.1 millert 393:
1.93 martynas 394: noslash:
1.106 haesbaer 395:
1.154 deraadt 396: #ifndef NOSSL
1.106 haesbaer 397: /*
398: * Look for auth header in host, since now host does not
399: * contain the path. Basic auth from RFC 2617, valid
400: * characters for path are in RFC 3986 section 3.3.
401: */
1.123 guenther 402: if (proxyenv == NULL && (ishttpurl || ishttpsurl)) {
1.106 haesbaer 403: if ((p = strchr(host, '@')) != NULL) {
1.123 guenther 404: *p = '\0';
405: credentials = recode_credentials(host);
1.106 haesbaer 406: host = p + 1;
407: }
408: }
1.154 deraadt 409: #endif /* NOSSL */
1.106 haesbaer 410:
1.17 millert 411: if (outfile)
412: savefile = outfile;
1.93 martynas 413: else {
414: if (path[strlen(path) - 1] == '/') /* Consider no file */
415: savefile = NULL; /* after dir invalid. */
416: else
417: savefile = basename(path);
1.75 martynas 418: }
419:
1.14 millert 420: if (EMPTYSTRING(savefile)) {
421: if (isftpurl)
422: goto noftpautologin;
1.94 martynas 423: warnx("No filename after directory (use -o): %s", origline);
1.6 millert 424: goto cleanup_url_get;
1.14 millert 425: }
1.1 millert 426:
1.93 martynas 427: #ifndef SMALL
1.100 halex 428: if (resume && pipeout) {
1.93 martynas 429: warnx("can't append to stdout");
430: goto cleanup_url_get;
431: }
432: #endif /* !SMALL */
433:
1.186 jca 434: if (proxyenv != NULL) { /* use proxy */
1.154 deraadt 435: #ifndef NOSSL
1.61 deraadt 436: if (ishttpsurl) {
437: sslpath = strdup(path);
438: sslhost = strdup(host);
439: if (! sslpath || ! sslhost)
440: errx(1, "Can't allocate memory for https path/host.");
441: }
1.154 deraadt 442: #endif /* !NOSSL */
1.136 bluhm 443: proxyhost = strdup(host);
444: if (proxyhost == NULL)
445: errx(1, "Can't allocate memory for proxy host.");
1.62 ray 446: proxyurl = strdup(proxyenv);
447: if (proxyurl == NULL)
1.14 millert 448: errx(1, "Can't allocate memory for proxy URL.");
1.62 ray 449: if (strncasecmp(proxyurl, HTTP_URL, sizeof(HTTP_URL) - 1) == 0)
450: host = proxyurl + sizeof(HTTP_URL) - 1;
451: else if (strncasecmp(proxyurl, FTP_URL, sizeof(FTP_URL) - 1) == 0)
452: host = proxyurl + sizeof(FTP_URL) - 1;
1.6 millert 453: else {
1.14 millert 454: warnx("Malformed proxy URL: %s", proxyenv);
1.6 millert 455: goto cleanup_url_get;
456: }
1.14 millert 457: if (EMPTYSTRING(host)) {
458: warnx("Malformed proxy URL: %s", proxyenv);
1.6 millert 459: goto cleanup_url_get;
1.14 millert 460: }
1.93 martynas 461: if (*--path == '\0')
462: *path = '/'; /* add / back to real path */
1.1 millert 463: path = strchr(host, '/'); /* remove trailing / on host */
1.42 deraadt 464: if (!EMPTYSTRING(path))
1.73 drahn 465: *path++ = '\0'; /* i guess this ++ is useless */
466:
467: path = strchr(host, '@'); /* look for credentials in proxy */
468: if (!EMPTYSTRING(path)) {
1.81 espie 469: *path = '\0';
1.123 guenther 470: if (strchr(host, ':') == NULL) {
1.73 drahn 471: warnx("Malformed proxy URL: %s", proxyenv);
472: goto cleanup_url_get;
473: }
1.123 guenther 474: credentials = recode_credentials(host);
1.81 espie 475: *path = '@'; /* restore @ in proxyurl */
1.123 guenther 476:
1.73 drahn 477: /*
1.81 espie 478: * This removes the password from proxyurl,
1.73 drahn 479: * filling with stars
480: */
1.81 espie 481: for (host = 1 + strchr(proxyurl + 5, ':'); *host != '@';
1.179 deraadt 482: host++)
1.73 drahn 483: *host = '*';
484:
1.81 espie 485: host = path + 1;
1.73 drahn 486: }
1.123 guenther 487:
1.62 ray 488: path = newline;
1.1 millert 489: }
490:
1.28 itojun 491: if (*host == '[' && (hosttail = strrchr(host, ']')) != NULL &&
492: (hosttail[1] == '\0' || hosttail[1] == ':')) {
493: host++;
494: *hosttail++ = '\0';
1.102 halex 495: #ifndef SMALL
496: if (asprintf(&full_host, "[%s]", host) == -1)
497: errx(1, "Cannot allocate memory for hostname");
498: #endif /* !SMALL */
1.28 itojun 499: } else
500: hosttail = host;
501:
502: portnum = strrchr(hosttail, ':'); /* find portnum */
1.1 millert 503: if (portnum != NULL)
504: *portnum++ = '\0';
1.154 deraadt 505: #ifndef NOSSL
1.150 millert 506: port = portnum ? portnum : (ishttpsurl ? httpsport : httpport);
1.154 deraadt 507: #else /* !NOSSL */
1.150 millert 508: port = portnum ? portnum : httpport;
1.154 deraadt 509: #endif /* !NOSSL */
1.1 millert 510:
1.80 martynas 511: #ifndef SMALL
1.102 halex 512: if (full_host == NULL)
513: if ((full_host = strdup(host)) == NULL)
514: errx(1, "Cannot allocate memory for hostname");
1.1 millert 515: if (debug)
1.106 haesbaer 516: fprintf(ttyout, "host %s, port %s, path %s, "
1.150 millert 517: "save as %s, auth %s.\n", host, port, path,
518: savefile, credentials ? credentials : "none");
1.80 martynas 519: #endif /* !SMALL */
1.1 millert 520:
1.25 itojun 521: memset(&hints, 0, sizeof(hints));
1.39 deraadt 522: hints.ai_family = family;
1.25 itojun 523: hints.ai_socktype = SOCK_STREAM;
524: error = getaddrinfo(host, port, &hints, &res0);
1.61 deraadt 525: /*
526: * If the services file is corrupt/missing, fall back
527: * on our hard-coded defines.
528: */
1.30 deraadt 529: if (error == EAI_SERVICE && port == httpport) {
530: snprintf(pbuf, sizeof(pbuf), "%d", HTTP_PORT);
531: error = getaddrinfo(host, pbuf, &hints, &res0);
1.154 deraadt 532: #ifndef NOSSL
1.61 deraadt 533: } else if (error == EAI_SERVICE && port == httpsport) {
534: snprintf(pbuf, sizeof(pbuf), "%d", HTTPS_PORT);
535: error = getaddrinfo(host, pbuf, &hints, &res0);
1.154 deraadt 536: #endif /* !NOSSL */
1.30 deraadt 537: }
1.25 itojun 538: if (error) {
1.122 guenther 539: warnx("%s: %s", host, gai_strerror(error));
1.25 itojun 540: goto cleanup_url_get;
1.1 millert 541: }
542:
1.105 haesbaer 543: #ifndef SMALL
544: if (srcaddr) {
545: hints.ai_flags |= AI_NUMERICHOST;
546: error = getaddrinfo(srcaddr, NULL, &hints, &ares);
547: if (error) {
1.122 guenther 548: warnx("%s: %s", srcaddr, gai_strerror(error));
1.105 haesbaer 549: goto cleanup_url_get;
550: }
551: }
552: #endif /* !SMALL */
1.135 deraadt 553:
554: /* ensure consistent order of the output */
555: if (verbose)
556: setvbuf(ttyout, NULL, _IOLBF, 0);
1.105 haesbaer 557:
1.166 procter 558: fd = -1;
1.25 itojun 559: for (res = res0; res; res = res->ai_next) {
1.44 itojun 560: if (getnameinfo(res->ai_addr, res->ai_addrlen, hbuf,
561: sizeof(hbuf), NULL, 0, NI_NUMERICHOST) != 0)
562: strlcpy(hbuf, "(unknown)", sizeof(hbuf));
1.41 deraadt 563: if (verbose)
1.44 itojun 564: fprintf(ttyout, "Trying %s...\n", hbuf);
1.14 millert 565:
1.166 procter 566: fd = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
567: if (fd == -1) {
1.25 itojun 568: cause = "socket";
569: continue;
1.1 millert 570: }
571:
1.105 haesbaer 572: #ifndef SMALL
573: if (srcaddr) {
574: if (ares->ai_family != res->ai_family) {
1.166 procter 575: close(fd);
576: fd = -1;
1.105 haesbaer 577: errno = EINVAL;
578: cause = "bind";
579: continue;
580: }
1.170 deraadt 581: if (bind(fd, ares->ai_addr, ares->ai_addrlen) == -1) {
1.105 haesbaer 582: save_errno = errno;
1.166 procter 583: close(fd);
1.105 haesbaer 584: errno = save_errno;
1.166 procter 585: fd = -1;
1.105 haesbaer 586: cause = "bind";
587: continue;
588: }
589: }
590: #endif /* !SMALL */
591:
1.155 deraadt 592: if (connect_timeout) {
593: (void)signal(SIGALRM, tooslow);
594: alarmtimer(connect_timeout);
595: }
596:
1.166 procter 597: for (error = connect(fd, res->ai_addr, res->ai_addrlen);
598: error != 0 && errno == EINTR; error = connect_wait(fd))
1.149 millert 599: continue;
600: if (error != 0) {
1.57 otto 601: save_errno = errno;
1.166 procter 602: close(fd);
1.57 otto 603: errno = save_errno;
1.166 procter 604: fd = -1;
1.25 itojun 605: cause = "connect";
1.19 deraadt 606: continue;
607: }
1.25 itojun 608:
1.29 itojun 609: /* get port in numeric */
610: if (getnameinfo(res->ai_addr, res->ai_addrlen, NULL, 0,
611: pbuf, sizeof(pbuf), NI_NUMERICSERV) == 0)
612: port = pbuf;
613: else
614: port = NULL;
615:
1.158 jca 616: #ifndef NOSSL
1.61 deraadt 617: if (proxyenv && sslhost)
1.166 procter 618: proxy_connect(fd, sslhost, credentials);
1.158 jca 619: #endif /* !NOSSL */
1.25 itojun 620: break;
621: }
622: freeaddrinfo(res0);
1.105 haesbaer 623: #ifndef SMALL
624: if (srcaddr)
625: freeaddrinfo(ares);
626: #endif /* !SMALL */
1.166 procter 627: if (fd < 0) {
1.33 millert 628: warn("%s", cause);
1.6 millert 629: goto cleanup_url_get;
1.1 millert 630: }
631:
1.154 deraadt 632: #ifndef NOSSL
1.61 deraadt 633: if (ishttpsurl) {
1.187 ! beck 634: ssize_t ret;
1.61 deraadt 635: if (proxyenv && sslpath) {
636: ishttpsurl = 0;
1.62 ray 637: proxyurl = NULL;
1.61 deraadt 638: path = sslpath;
639: }
1.131 jca 640: if (sslhost == NULL) {
641: sslhost = strdup(host);
642: if (sslhost == NULL)
643: errx(1, "Can't allocate memory for https host.");
1.116 jca 644: }
1.134 jsing 645: if ((tls = tls_client()) == NULL) {
1.126 jsing 646: fprintf(ttyout, "failed to create SSL client\n");
1.61 deraadt 647: goto cleanup_url_get;
648: }
1.134 jsing 649: if (tls_configure(tls, tls_config) != 0) {
1.187 ! beck 650: fprintf(ttyout, "TLS configuration failure: %s\n",
1.134 jsing 651: tls_error(tls));
1.61 deraadt 652: goto cleanup_url_get;
1.117 jca 653: }
1.166 procter 654: if (tls_connect_socket(tls, fd, sslhost) != 0) {
1.187 ! beck 655: fprintf(ttyout, "TLS connect failure: %s\n", tls_error(tls));
1.72 ray 656: goto cleanup_url_get;
1.118 jca 657: }
1.187 ! beck 658: do {
! 659: ret = tls_handshake(tls);
! 660: } while (ret == TLS_WANT_POLLIN || ret == TLS_WANT_POLLOUT);
! 661: if (ret != 0) {
! 662: fprintf(ttyout, "TLS handshake failure: %s\n", tls_error(tls));
1.176 jca 663: goto cleanup_url_get;
664: }
665: fin = funopen(tls, stdio_tls_read_wrapper,
666: stdio_tls_write_wrapper, NULL, NULL);
1.61 deraadt 667: } else {
1.166 procter 668: fin = fdopen(fd, "r+");
669: fd = -1;
1.61 deraadt 670: }
1.154 deraadt 671: #else /* !NOSSL */
1.166 procter 672: fin = fdopen(fd, "r+");
673: fd = -1;
1.154 deraadt 674: #endif /* !NOSSL */
1.155 deraadt 675:
1.157 deraadt 676: #ifdef SMALL
677: if (lastfile) {
678: if (pipeout) {
679: if (pledge("stdio rpath inet dns tty", NULL) == -1)
680: err(1, "pledge");
681: } else {
682: if (pledge("stdio rpath wpath cpath inet dns tty", NULL) == -1)
683: err(1, "pledge");
684: }
685: }
686: #endif
687:
1.155 deraadt 688: if (connect_timeout) {
689: signal(SIGALRM, SIG_DFL);
690: alarmtimer(0);
691: }
1.40 fgsch 692:
1.1 millert 693: /*
1.40 fgsch 694: * Construct and send the request. Proxy requests don't want leading /.
1.1 millert 695: */
1.154 deraadt 696: #ifndef NOSSL
1.74 pyr 697: cookie_get(host, path, ishttpsurl, &buf);
1.154 deraadt 698: #endif /* !NOSSL */
1.95 martynas 699:
700: epath = url_encode(path);
1.62 ray 701: if (proxyurl) {
1.151 millert 702: if (verbose) {
703: fprintf(ttyout, "Requesting %s (via %s)\n",
704: origline, proxyurl);
705: }
1.32 itojun 706: /*
707: * Host: directive must use the destination host address for
1.136 bluhm 708: * the original URI (path).
1.32 itojun 709: */
1.123 guenther 710: if (credentials)
1.184 jca 711: ftp_printf(fin, "GET %s HTTP/1.1\r\n"
1.178 jca 712: "Connection: close\r\n"
1.136 bluhm 713: "Proxy-Authorization: Basic %s\r\n"
714: "Host: %s\r\n%s%s\r\n\r\n",
715: epath, credentials,
716: proxyhost, buf ? buf : "", httpuseragent);
1.73 drahn 717: else
1.184 jca 718: ftp_printf(fin, "GET %s HTTP/1.1\r\n"
1.178 jca 719: "Connection: close\r\n"
1.136 bluhm 720: "Host: %s\r\n%s%s\r\n\r\n",
721: epath, proxyhost, buf ? buf : "", httpuseragent);
1.28 itojun 722: } else {
1.151 millert 723: if (verbose)
724: fprintf(ttyout, "Requesting %s\n", origline);
1.90 martynas 725: #ifndef SMALL
726: if (resume) {
727: struct stat stbuf;
728:
729: if (stat(savefile, &stbuf) == 0)
730: restart_point = stbuf.st_size;
731: else
732: restart_point = 0;
733: }
1.154 deraadt 734: #endif /* SMALL */
735: #ifndef NOSSL
1.123 guenther 736: if (credentials) {
1.184 jca 737: ftp_printf(fin,
1.178 jca 738: "GET /%s HTTP/1.1\r\n"
739: "Connection: close\r\n"
740: "Authorization: Basic %s\r\n"
741: "Host: ", epath, credentials);
1.123 guenther 742: free(credentials);
743: credentials = NULL;
1.106 haesbaer 744: } else
1.154 deraadt 745: #endif /* NOSSL */
1.184 jca 746: ftp_printf(fin,
1.178 jca 747: "GET /%s HTTP/1.1\r\n"
748: "Connection: close\r\n"
749: "Host: ", epath);
1.136 bluhm 750: if (proxyhost) {
1.184 jca 751: ftp_printf(fin, "%s", proxyhost);
1.136 bluhm 752: port = NULL;
753: } else if (strchr(host, ':')) {
1.55 fgsch 754: /*
755: * strip off scoped address portion, since it's
756: * local to node
757: */
1.32 itojun 758: h = strdup(host);
759: if (h == NULL)
760: errx(1, "Can't allocate memory.");
761: if ((p = strchr(h, '%')) != NULL)
762: *p = '\0';
1.184 jca 763: ftp_printf(fin, "[%s]", h);
1.32 itojun 764: free(h);
1.55 fgsch 765: } else
1.184 jca 766: ftp_printf(fin, "%s", host);
1.55 fgsch 767:
768: /*
769: * Send port number only if it's specified and does not equal
770: * 80. Some broken HTTP servers get confused if you explicitly
771: * send them the port number.
772: */
1.154 deraadt 773: #ifndef NOSSL
1.61 deraadt 774: if (port && strcmp(port, (ishttpsurl ? "443" : "80")) != 0)
1.184 jca 775: ftp_printf(fin, ":%s", port);
1.90 martynas 776: if (restart_point)
1.184 jca 777: ftp_printf(fin, "\r\nRange: bytes=%lld-",
1.75 martynas 778: (long long)restart_point);
1.154 deraadt 779: #else /* !NOSSL */
1.55 fgsch 780: if (port && strcmp(port, "80") != 0)
1.184 jca 781: ftp_printf(fin, ":%s", port);
1.154 deraadt 782: #endif /* !NOSSL */
1.184 jca 783: ftp_printf(fin, "\r\n%s%s\r\n\r\n",
1.124 lteo 784: buf ? buf : "", httpuseragent);
1.28 itojun 785: }
1.95 martynas 786: free(epath);
1.74 pyr 787:
1.154 deraadt 788: #ifndef NOSSL
1.74 pyr 789: free(buf);
1.156 tb 790: #endif /* !NOSSL */
1.74 pyr 791: buf = NULL;
792:
1.176 jca 793: if (fflush(fin) == EOF) {
794: warnx("Writing HTTP request: %s", sockerror(tls));
1.6 millert 795: goto cleanup_url_get;
1.1 millert 796: }
1.176 jca 797: if ((buf = ftp_readline(fin, &len)) == NULL) {
798: warnx("Receiving HTTP reply: %s", sockerror(tls));
1.40 fgsch 799: goto cleanup_url_get;
1.1 millert 800: }
1.40 fgsch 801:
802: while (len > 0 && (buf[len-1] == '\r' || buf[len-1] == '\n'))
803: buf[--len] = '\0';
1.80 martynas 804: #ifndef SMALL
1.40 fgsch 805: if (debug)
806: fprintf(ttyout, "received '%s'\n", buf);
1.80 martynas 807: #endif /* !SMALL */
1.40 fgsch 808:
1.1 millert 809: cp = strchr(buf, ' ');
810: if (cp == NULL)
811: goto improper;
812: else
813: cp++;
1.69 jsg 814:
815: strlcpy(ststr, cp, sizeof(ststr));
1.171 jca 816: status = strtonum(ststr, 200, 503, &errstr);
1.69 jsg 817: if (errstr) {
1.175 deraadt 818: strnvis(gerror, cp, sizeof gerror, VIS_SAFE);
819: warnx("Error retrieving %s: %s", origline, gerror);
1.69 jsg 820: goto cleanup_url_get;
821: }
822:
823: switch (status) {
824: case 200: /* OK */
1.75 martynas 825: #ifndef SMALL
1.109 sthen 826: /*
1.98 phessler 827: * When we request a partial file, and we receive an HTTP 200
828: * it is a good indication that the server doesn't support
829: * range requests, and is about to send us the entire file.
830: * If the restart_point == 0, then we are not actually
831: * requesting a partial file, and an HTTP 200 is appropriate.
832: */
833: if (resume && restart_point != 0) {
834: warnx("Server does not support resume.");
835: restart_point = resume = 0;
836: }
1.101 halex 837: /* FALLTHROUGH */
1.75 martynas 838: case 206: /* Partial Content */
1.91 halex 839: #endif /* !SMALL */
1.69 jsg 840: break;
841: case 301: /* Moved Permanently */
842: case 302: /* Found */
843: case 303: /* See Other */
844: case 307: /* Temporary Redirect */
1.40 fgsch 845: isredirect++;
1.54 fgsch 846: if (redirect_loop++ > 10) {
847: warnx("Too many redirections requested");
848: goto cleanup_url_get;
849: }
1.69 jsg 850: break;
1.75 martynas 851: #ifndef SMALL
852: case 416: /* Requested Range Not Satisfiable */
853: warnx("File is already fully retrieved.");
854: goto cleanup_url_get;
1.78 martynas 855: #endif /* !SMALL */
1.171 jca 856: case 503:
1.172 jca 857: isunavail = 1;
858: break;
1.69 jsg 859: default:
1.175 deraadt 860: strnvis(gerror, cp, sizeof gerror, VIS_SAFE);
861: warnx("Error retrieving %s: %s", origline, gerror);
1.6 millert 862: goto cleanup_url_get;
1.1 millert 863: }
864:
865: /*
866: * Read the rest of the header.
867: */
1.40 fgsch 868: free(buf);
869: filesize = -1;
870:
1.62 ray 871: for (;;) {
1.176 jca 872: if ((buf = ftp_readline(fin, &len)) == NULL) {
873: warnx("Receiving HTTP reply: %s", sockerror(tls));
1.40 fgsch 874: goto cleanup_url_get;
875: }
1.61 deraadt 876:
1.40 fgsch 877: while (len > 0 && (buf[len-1] == '\r' || buf[len-1] == '\n'))
878: buf[--len] = '\0';
879: if (len == 0)
1.1 millert 880: break;
1.80 martynas 881: #ifndef SMALL
1.40 fgsch 882: if (debug)
883: fprintf(ttyout, "received '%s'\n", buf);
1.80 martynas 884: #endif /* !SMALL */
1.1 millert 885:
1.40 fgsch 886: /* Look for some headers */
887: cp = buf;
1.1 millert 888: #define CONTENTLEN "Content-Length: "
1.40 fgsch 889: if (strncasecmp(cp, CONTENTLEN, sizeof(CONTENTLEN) - 1) == 0) {
1.104 sthen 890: size_t s;
1.40 fgsch 891: cp += sizeof(CONTENTLEN) - 1;
1.111 deraadt 892: if ((s = strcspn(cp, " \t")))
1.104 sthen 893: *(cp+s) = 0;
1.58 grunk 894: filesize = strtonum(cp, 0, LLONG_MAX, &errstr);
895: if (errstr != NULL)
1.40 fgsch 896: goto improper;
1.75 martynas 897: #ifndef SMALL
1.90 martynas 898: if (restart_point)
1.75 martynas 899: filesize += restart_point;
1.78 martynas 900: #endif /* !SMALL */
1.40 fgsch 901: #define LOCATION "Location: "
902: } else if (isredirect &&
903: strncasecmp(cp, LOCATION, sizeof(LOCATION) - 1) == 0) {
904: cp += sizeof(LOCATION) - 1;
1.144 sthen 905: /*
906: * If there is a colon before the first slash, this URI
907: * is not relative. RFC 3986 4.2
908: */
909: if (cp[strcspn(cp, ":/")] != ':') {
1.102 halex 910: #ifdef SMALL
911: errx(1, "Relative redirect not supported");
912: #else /* SMALL */
1.144 sthen 913: /* XXX doesn't handle protocol-relative URIs */
1.102 halex 914: if (*cp == '/') {
915: locbase = NULL;
916: cp++;
917: } else {
918: locbase = strdup(path);
919: if (locbase == NULL)
920: errx(1, "Can't allocate memory"
921: " for location base");
922: loctail = strchr(locbase, '#');
923: if (loctail != NULL)
924: *loctail = '\0';
925: loctail = strchr(locbase, '?');
926: if (loctail != NULL)
927: *loctail = '\0';
928: loctail = strrchr(locbase, '/');
929: if (loctail == NULL) {
930: free(locbase);
931: locbase = NULL;
932: } else
933: loctail[1] = '\0';
934: }
935: /* Contruct URL from relative redirect */
936: if (asprintf(&redirurl, "%s%s%s%s/%s%s",
937: scheme, full_host,
938: portnum ? ":" : "",
939: portnum ? portnum : "",
940: locbase ? locbase : "",
941: cp) == -1)
942: errx(1, "Cannot build "
943: "redirect URL");
944: free(locbase);
945: #endif /* SMALL */
946: } else if ((redirurl = strdup(cp)) == NULL)
947: errx(1, "Cannot allocate memory for URL");
948: loctail = strchr(redirurl, '#');
949: if (loctail != NULL)
950: *loctail = '\0';
1.40 fgsch 951: if (verbose)
1.102 halex 952: fprintf(ttyout, "Redirected to %s\n", redirurl);
1.173 jca 953: ftp_close(&fin, &tls, &fd);
1.157 deraadt 954: rval = url_get(redirurl, proxyenv, savefile, lastfile);
1.102 halex 955: free(redirurl);
956: goto cleanup_url_get;
1.172 jca 957: #define RETRYAFTER "Retry-After: "
958: } else if (isunavail &&
959: strncasecmp(cp, RETRYAFTER, sizeof(RETRYAFTER) - 1) == 0) {
960: size_t s;
961: cp += sizeof(RETRYAFTER) - 1;
962: if ((s = strcspn(cp, " \t")))
963: cp[s] = '\0';
964: retryafter = strtonum(cp, 0, 0, &errstr);
965: if (errstr != NULL)
966: retryafter = -1;
1.178 jca 967: #define TRANSFER_ENCODING "Transfer-Encoding: "
968: } else if (strncasecmp(cp, TRANSFER_ENCODING,
969: sizeof(TRANSFER_ENCODING) - 1) == 0) {
970: cp += sizeof(TRANSFER_ENCODING) - 1;
971: cp[strcspn(cp, " \t")] = '\0';
972: if (strcasecmp(cp, "chunked") == 0)
973: chunked = 1;
1.40 fgsch 974: }
1.108 tobias 975: free(buf);
1.172 jca 976: }
977:
1.178 jca 978: /* Content-Length should be ignored for Transfer-Encoding: chunked */
979: if (chunked)
980: filesize = -1;
981:
1.172 jca 982: if (isunavail) {
983: if (retried || retryafter != 0)
1.175 deraadt 984: warnx("Error retrieving %s: 503 Service Unavailable",
985: origline);
1.172 jca 986: else {
987: if (verbose)
988: fprintf(ttyout, "Retrying %s\n", origline);
989: retried = 1;
1.174 jca 990: ftp_close(&fin, &tls, &fd);
1.172 jca 991: rval = url_get(origline, proxyenv, savefile, lastfile);
992: }
993: goto cleanup_url_get;
1.1 millert 994: }
995:
1.17 millert 996: /* Open the output file. */
1.100 halex 997: if (!pipeout) {
1.75 martynas 998: #ifndef SMALL
999: if (resume)
1.83 martynas 1000: out = open(savefile, O_CREAT | O_WRONLY | O_APPEND,
1001: 0666);
1.75 martynas 1002: else
1.78 martynas 1003: #endif /* !SMALL */
1.75 martynas 1004: out = open(savefile, O_CREAT | O_WRONLY | O_TRUNC,
1005: 0666);
1.170 deraadt 1006: if (out == -1) {
1.10 deraadt 1007: warn("Can't open %s", savefile);
1008: goto cleanup_url_get;
1009: }
1.157 deraadt 1010: } else {
1.17 millert 1011: out = fileno(stdout);
1.157 deraadt 1012: #ifdef SMALL
1013: if (lastfile) {
1014: if (pledge("stdio tty", NULL) == -1)
1015: err(1, "pledge");
1016: }
1017: #endif
1018: }
1.1 millert 1019:
1020: /* Trap signals */
1021: oldintr = NULL;
1.97 martynas 1022: oldinti = NULL;
1.1 millert 1023: if (setjmp(httpabort)) {
1024: if (oldintr)
1.2 millert 1025: (void)signal(SIGINT, oldintr);
1.97 martynas 1026: if (oldinti)
1027: (void)signal(SIGINFO, oldinti);
1.6 millert 1028: goto cleanup_url_get;
1.1 millert 1029: }
1030: oldintr = signal(SIGINT, aborthttp);
1031:
1032: bytes = 0;
1033: hashbytes = mark;
1.84 martynas 1034: progressmeter(-1, path);
1.43 millert 1035:
1036: free(buf);
1.1 millert 1037:
1038: /* Finally, suck down the file. */
1.113 tedu 1039: if ((buf = malloc(buflen)) == NULL)
1.47 deraadt 1040: errx(1, "Can't allocate memory for transfer buffer");
1.97 martynas 1041: oldinti = signal(SIGINFO, psummary);
1.178 jca 1042: if (chunked) {
1.182 jca 1043: error = save_chunked(fin, tls, out, buf, buflen);
1044: signal(SIGINFO, oldinti);
1045: if (error == -1)
1.178 jca 1046: goto cleanup_url_get;
1047: } else {
1048: i = 0;
1049: len = 1;
1050: while (len > 0) {
1051: len = fread(buf, 1, buflen, fin);
1052: bytes += len;
1053: for (cp = buf, wlen = len; wlen > 0; wlen -= i, cp += i) {
1054: if ((i = write(out, cp, wlen)) == -1) {
1055: warn("Writing %s", savefile);
1056: signal(SIGINFO, oldinti);
1057: goto cleanup_url_get;
1.179 deraadt 1058: } else if (i == 0)
1.178 jca 1059: break;
1060: }
1061: if (hash && !progress) {
1062: while (bytes >= hashbytes) {
1063: (void)putc('#', ttyout);
1064: hashbytes += mark;
1065: }
1066: (void)fflush(ttyout);
1.1 millert 1067: }
1068: }
1.178 jca 1069: signal(SIGINFO, oldinti);
1070: if (hash && !progress && bytes > 0) {
1071: if (bytes < mark)
1.10 deraadt 1072: (void)putc('#', ttyout);
1.178 jca 1073: (void)putc('\n', ttyout);
1.10 deraadt 1074: (void)fflush(ttyout);
1.1 millert 1075: }
1.178 jca 1076: if (len != 0) {
1077: warnx("Reading from socket: %s", sockerror(tls));
1078: goto cleanup_url_get;
1079: }
1.1 millert 1080: }
1.84 martynas 1081: progressmeter(1, NULL);
1.75 martynas 1082: if (
1083: #ifndef SMALL
1084: !resume &&
1.78 martynas 1085: #endif /* !SMALL */
1.75 martynas 1086: filesize != -1 && len == 0 && bytes != filesize) {
1.24 deraadt 1087: if (verbose)
1088: fputs("Read short file.\n", ttyout);
1089: goto cleanup_url_get;
1090: }
1091:
1.1 millert 1092: if (verbose)
1.97 martynas 1093: ptransfer(0);
1.2 millert 1094: (void)signal(SIGINT, oldintr);
1.1 millert 1095:
1.40 fgsch 1096: rval = 0;
1097: goto cleanup_url_get;
1.1 millert 1098:
1.14 millert 1099: noftpautologin:
1100: warnx(
1101: "Auto-login using ftp URLs isn't supported when using $ftp_proxy");
1102: goto cleanup_url_get;
1103:
1.1 millert 1104: improper:
1.8 millert 1105: warnx("Improper response from %s", host);
1.14 millert 1106:
1.6 millert 1107: cleanup_url_get:
1.181 jca 1108: #ifndef SMALL
1109: free(full_host);
1110: #endif /* !SMALL */
1.154 deraadt 1111: #ifndef NOSSL
1.128 jca 1112: free(sslhost);
1.154 deraadt 1113: #endif /* !NOSSL */
1.173 jca 1114: ftp_close(&fin, &tls, &fd);
1.162 sthen 1115: if (out >= 0 && out != fileno(stdout))
1116: close(out);
1.67 steven 1117: free(buf);
1.136 bluhm 1118: free(proxyhost);
1.67 steven 1119: free(proxyurl);
1.62 ray 1120: free(newline);
1.123 guenther 1121: free(credentials);
1.40 fgsch 1122: return (rval);
1.178 jca 1123: }
1124:
1125: static int
1126: save_chunked(FILE *fin, struct tls *tls, int out, char *buf, size_t buflen)
1127: {
1128:
1129: char *header, *end, *cp;
1130: unsigned long chunksize;
1131: size_t hlen, rlen, wlen;
1132: ssize_t written;
1133: char cr, lf;
1134:
1135: for (;;) {
1136: header = ftp_readline(fin, &hlen);
1137: if (header == NULL)
1138: break;
1139: /* strip CRLF and any optional chunk extension */
1140: header[strcspn(header, ";\r\n")] = '\0';
1141: errno = 0;
1142: chunksize = strtoul(header, &end, 16);
1143: if (errno || header[0] == '\0' || *end != '\0' ||
1144: chunksize > INT_MAX) {
1145: warnx("Invalid chunk size '%s'", header);
1146: free(header);
1147: return -1;
1148: }
1149: free(header);
1150:
1151: if (chunksize == 0) {
1152: /* We're done. Ignore optional trailer. */
1153: return 0;
1154: }
1155:
1156: for (written = 0; chunksize != 0; chunksize -= rlen) {
1157: rlen = (chunksize < buflen) ? chunksize : buflen;
1158: rlen = fread(buf, 1, rlen, fin);
1159: if (rlen == 0)
1160: break;
1161: bytes += rlen;
1162: for (cp = buf, wlen = rlen; wlen > 0;
1.179 deraadt 1163: wlen -= written, cp += written) {
1.178 jca 1164: if ((written = write(out, cp, wlen)) == -1) {
1165: warn("Writing output file");
1166: return -1;
1167: }
1168: }
1169: }
1170:
1171: if (rlen == 0 ||
1172: fread(&cr, 1, 1, fin) != 1 ||
1173: fread(&lf, 1, 1, fin) != 1)
1174: break;
1175:
1176: if (cr != '\r' || lf != '\n') {
1177: warnx("Invalid chunked encoding");
1178: return -1;
1179: }
1180: }
1181:
1182: if (ferror(fin))
1183: warnx("Error while reading from socket: %s", sockerror(tls));
1184: else
1185: warnx("Invalid chunked encoding: short read");
1186:
1187: return -1;
1.1 millert 1188: }
1189:
1190: /*
1191: * Abort a http retrieval
1192: */
1.51 deraadt 1193: /* ARGSUSED */
1.177 jca 1194: static void
1.51 deraadt 1195: aborthttp(int signo)
1.1 millert 1196: {
1197:
1198: alarmtimer(0);
1.10 deraadt 1199: fputs("\nhttp fetch aborted.\n", ttyout);
1200: (void)fflush(ttyout);
1.1 millert 1201: longjmp(httpabort, 1);
1202: }
1203:
1204: /*
1.22 deraadt 1205: * Abort a http retrieval
1206: */
1.51 deraadt 1207: /* ARGSUSED */
1.177 jca 1208: static void
1.51 deraadt 1209: abortfile(int signo)
1.22 deraadt 1210: {
1211:
1212: alarmtimer(0);
1213: fputs("\nfile fetch aborted.\n", ttyout);
1214: (void)fflush(ttyout);
1215: longjmp(httpabort, 1);
1216: }
1217:
1218: /*
1.1 millert 1219: * Retrieve multiple files from the command line, transferring
1220: * files of the form "host:path", "ftp://host/path" using the
1221: * ftp protocol, and files of the form "http://host/path" using
1222: * the http protocol.
1.2 millert 1223: * If path has a trailing "/", then return (-1);
1.1 millert 1224: * the path will be cd-ed into and the connection remains open,
1225: * and the function will return -1 (to indicate the connection
1226: * is alive).
1227: * If an error occurs the return value will be the offset+1 in
1228: * argv[] of the file that caused a problem (i.e, argv[x]
1229: * returns x+1)
1230: * Otherwise, 0 is returned if all files retrieved successfully.
1231: */
1232: int
1.50 deraadt 1233: auto_fetch(int argc, char *argv[], char *outfile)
1.1 millert 1234: {
1235: char *xargv[5];
1.62 ray 1236: char *cp, *url, *host, *dir, *file, *portnum;
1237: char *username, *pass, *pathstart;
1.6 millert 1238: char *ftpproxy, *httpproxy;
1.157 deraadt 1239: int rval, xargc, lastfile;
1.14 millert 1240: volatile int argpos;
1.49 krw 1241: int dirhasglob, filehasglob, oautologin;
1.137 deraadt 1242: char rempath[PATH_MAX];
1.1 millert 1243:
1244: argpos = 0;
1245:
1246: if (setjmp(toplevel)) {
1247: if (connected)
1248: disconnect(0, NULL);
1.2 millert 1249: return (argpos + 1);
1.1 millert 1250: }
1.3 millert 1251: (void)signal(SIGINT, (sig_t)intr);
1252: (void)signal(SIGPIPE, (sig_t)lostpeer);
1.1 millert 1253:
1.45 millert 1254: if ((ftpproxy = getenv(FTP_PROXY)) != NULL && *ftpproxy == '\0')
1255: ftpproxy = NULL;
1256: if ((httpproxy = getenv(HTTP_PROXY)) != NULL && *httpproxy == '\0')
1257: httpproxy = NULL;
1.6 millert 1258:
1.1 millert 1259: /*
1260: * Loop through as long as there's files to fetch.
1261: */
1.123 guenther 1262: username = pass = NULL;
1.62 ray 1263: for (rval = 0; (rval == 0) && (argpos < argc); free(url), argpos++) {
1.1 millert 1264: if (strchr(argv[argpos], ':') == NULL)
1265: break;
1.123 guenther 1266:
1267: free(username);
1268: free(pass);
1.62 ray 1269: host = dir = file = portnum = username = pass = NULL;
1.1 millert 1270:
1.157 deraadt 1271: lastfile = (argv[argpos+1] == NULL);
1272:
1.1 millert 1273: /*
1274: * We muck with the string, so we make a copy.
1275: */
1.62 ray 1276: url = strdup(argv[argpos]);
1277: if (url == NULL)
1.1 millert 1278: errx(1, "Can't allocate memory for auto-fetch.");
1279:
1.186 jca 1280: if (strncasecmp(url, FILE_URL, sizeof(FILE_URL) - 1) == 0) {
1281: if (file_get(url + sizeof(FILE_URL) - 1, outfile) == -1)
1282: rval = argpos + 1;
1283: continue;
1284: }
1285:
1.1 millert 1286: /*
1.186 jca 1287: * Try HTTP URL-style arguments next.
1.1 millert 1288: */
1.62 ray 1289: if (strncasecmp(url, HTTP_URL, sizeof(HTTP_URL) - 1) == 0 ||
1.186 jca 1290: strncasecmp(url, HTTPS_URL, sizeof(HTTPS_URL) -1) == 0) {
1.54 fgsch 1291: redirect_loop = 0;
1.171 jca 1292: retried = 0;
1.157 deraadt 1293: if (url_get(url, httpproxy, outfile, lastfile) == -1)
1.1 millert 1294: rval = argpos + 1;
1295: continue;
1296: }
1297:
1298: /*
1.6 millert 1299: * Try FTP URL-style arguments next. If ftpproxy is
1300: * set, use url_get() instead of standard ftp.
1301: * Finally, try host:file.
1.1 millert 1302: */
1.62 ray 1303: host = url;
1304: if (strncasecmp(url, FTP_URL, sizeof(FTP_URL) - 1) == 0) {
1.37 heko 1305: char *passend, *passagain, *userend;
1.31 itojun 1306:
1.6 millert 1307: if (ftpproxy) {
1.157 deraadt 1308: if (url_get(url, ftpproxy, outfile, lastfile) == -1)
1.6 millert 1309: rval = argpos + 1;
1310: continue;
1311: }
1.1 millert 1312: host += sizeof(FTP_URL) - 1;
1.8 millert 1313: dir = strchr(host, '/');
1.1 millert 1314:
1.8 millert 1315: /* Look for [user:pass@]host[:port] */
1.31 itojun 1316:
1317: /* check if we have "user:pass@" */
1.37 heko 1318: userend = strchr(host, ':');
1.31 itojun 1319: passend = strchr(host, '@');
1320: if (passend && userend && userend < passend &&
1321: (!dir || passend < dir)) {
1.62 ray 1322: username = host;
1.31 itojun 1323: pass = userend + 1;
1324: host = passend + 1;
1325: *userend = *passend = '\0';
1.37 heko 1326: passagain = strchr(host, '@');
1.42 deraadt 1327: if (strchr(pass, '@') != NULL ||
1.37 heko 1328: (passagain != NULL && passagain < dir)) {
1329: warnx(at_encoding_warning);
1.123 guenther 1330: username = pass = NULL;
1.37 heko 1331: goto bad_ftp_url;
1.42 deraadt 1332: }
1.31 itojun 1333:
1.77 martynas 1334: if (EMPTYSTRING(username)) {
1.11 millert 1335: bad_ftp_url:
1.31 itojun 1336: warnx("Invalid URL: %s", argv[argpos]);
1337: rval = argpos + 1;
1.123 guenther 1338: username = pass = NULL;
1.31 itojun 1339: continue;
1340: }
1.62 ray 1341: username = urldecode(username);
1.37 heko 1342: pass = urldecode(pass);
1.8 millert 1343: }
1.31 itojun 1344:
1345: /* check [host]:port, or [host] */
1346: if (host[0] == '[') {
1347: cp = strchr(host, ']');
1348: if (cp && (!dir || cp < dir)) {
1349: if (cp + 1 == dir || cp[1] == ':') {
1350: host++;
1351: *cp++ = '\0';
1352: } else
1353: cp = NULL;
1354: } else
1355: cp = host;
1.25 itojun 1356: } else
1357: cp = host;
1.31 itojun 1358:
1359: /* split off host[:port] if there is */
1360: if (cp) {
1361: portnum = strchr(cp, ':');
1.52 henning 1362: pathstart = strchr(cp, '/');
1363: /* : in path is not a port # indicator */
1364: if (portnum && pathstart &&
1365: pathstart < portnum)
1366: portnum = NULL;
1367:
1.31 itojun 1368: if (!portnum)
1369: ;
1370: else {
1371: if (!dir)
1372: ;
1373: else if (portnum + 1 < dir) {
1374: *portnum++ = '\0';
1375: /*
1376: * XXX should check if portnum
1377: * is decimal number
1378: */
1379: } else {
1380: /* empty portnum */
1381: goto bad_ftp_url;
1382: }
1383: }
1384: } else
1385: portnum = NULL;
1.8 millert 1386: } else { /* classic style `host:file' */
1387: dir = strchr(host, ':');
1388: }
1.1 millert 1389: if (EMPTYSTRING(host)) {
1390: rval = argpos + 1;
1391: continue;
1392: }
1393:
1394: /*
1.9 millert 1395: * If dir is NULL, the file wasn't specified
1.1 millert 1396: * (URL looked something like ftp://host)
1397: */
1.8 millert 1398: if (dir != NULL)
1399: *dir++ = '\0';
1.1 millert 1400:
1401: /*
1402: * Extract the file and (if present) directory name.
1403: */
1.42 deraadt 1404: if (!EMPTYSTRING(dir)) {
1.8 millert 1405: cp = strrchr(dir, '/');
1.1 millert 1406: if (cp != NULL) {
1407: *cp++ = '\0';
1408: file = cp;
1409: } else {
1410: file = dir;
1411: dir = NULL;
1412: }
1413: }
1.80 martynas 1414: #ifndef SMALL
1.1 millert 1415: if (debug)
1.42 deraadt 1416: fprintf(ttyout,
1417: "user %s:%s host %s port %s dir %s file %s\n",
1.76 martynas 1418: username, pass ? "XXXX" : NULL, host, portnum,
1419: dir, file);
1.80 martynas 1420: #endif /* !SMALL */
1.1 millert 1421:
1422: /*
1.49 krw 1423: * Set up the connection.
1.1 millert 1424: */
1.49 krw 1425: if (connected)
1426: disconnect(0, NULL);
1427: xargv[0] = __progname;
1428: xargv[1] = host;
1.8 millert 1429: xargv[2] = NULL;
1.49 krw 1430: xargc = 2;
1431: if (!EMPTYSTRING(portnum)) {
1432: xargv[2] = portnum;
1433: xargv[3] = NULL;
1434: xargc = 3;
1435: }
1436: oautologin = autologin;
1.88 martynas 1437: if (username == NULL)
1.89 halex 1438: anonftp = 1;
1439: else {
1440: anonftp = 0;
1.49 krw 1441: autologin = 0;
1.89 halex 1442: }
1.49 krw 1443: setpeer(xargc, xargv);
1444: autologin = oautologin;
1.87 martynas 1445: if (connected == 0 ||
1446: (connected == 1 && autologin && (username == NULL ||
1447: !ftp_login(host, username, pass)))) {
1.49 krw 1448: warnx("Can't connect or login to host `%s'", host);
1.8 millert 1449: rval = argpos + 1;
1450: continue;
1.1 millert 1451: }
1.49 krw 1452:
1453: /* Always use binary transfers. */
1454: setbinary(0, NULL);
1.1 millert 1455:
1.4 millert 1456: dirhasglob = filehasglob = 0;
1457: if (doglob) {
1.42 deraadt 1458: if (!EMPTYSTRING(dir) &&
1.4 millert 1459: strpbrk(dir, "*?[]{}") != NULL)
1460: dirhasglob = 1;
1.42 deraadt 1461: if (!EMPTYSTRING(file) &&
1.4 millert 1462: strpbrk(file, "*?[]{}") != NULL)
1463: filehasglob = 1;
1464: }
1465:
1.1 millert 1466: /* Change directories, if necessary. */
1.42 deraadt 1467: if (!EMPTYSTRING(dir) && !dirhasglob) {
1.1 millert 1468: xargv[0] = "cd";
1469: xargv[1] = dir;
1470: xargv[2] = NULL;
1471: cd(2, xargv);
1.42 deraadt 1472: if (!dirchange) {
1.1 millert 1473: rval = argpos + 1;
1474: continue;
1475: }
1476: }
1477:
1478: if (EMPTYSTRING(file)) {
1.86 martynas 1479: #ifndef SMALL
1.1 millert 1480: rval = -1;
1.86 martynas 1481: #else /* !SMALL */
1482: recvrequest("NLST", "-", NULL, "w", 0, 0);
1483: rval = 0;
1484: #endif /* !SMALL */
1.1 millert 1485: continue;
1486: }
1487:
1.21 marc 1488: if (verbose)
1.10 deraadt 1489: fprintf(ttyout, "Retrieving %s/%s\n", dir ? dir : "", file);
1.1 millert 1490:
1.4 millert 1491: if (dirhasglob) {
1492: snprintf(rempath, sizeof(rempath), "%s/%s", dir, file);
1493: file = rempath;
1494: }
1495:
1496: /* Fetch the file(s). */
1.10 deraadt 1497: xargc = 2;
1.1 millert 1498: xargv[0] = "get";
1499: xargv[1] = file;
1500: xargv[2] = NULL;
1.4 millert 1501: if (dirhasglob || filehasglob) {
1502: int ointeractive;
1503:
1504: ointeractive = interactive;
1505: interactive = 0;
1506: xargv[0] = "mget";
1.78 martynas 1507: #ifndef SMALL
1508: if (resume) {
1509: xargc = 3;
1510: xargv[1] = "-c";
1511: xargv[2] = file;
1512: xargv[3] = NULL;
1513: }
1514: #endif /* !SMALL */
1.10 deraadt 1515: mget(xargc, xargv);
1.5 millert 1516: interactive = ointeractive;
1.10 deraadt 1517: } else {
1.17 millert 1518: if (outfile != NULL) {
1519: xargv[2] = outfile;
1520: xargv[3] = NULL;
1.10 deraadt 1521: xargc++;
1522: }
1.75 martynas 1523: #ifndef SMALL
1524: if (resume)
1525: reget(xargc, xargv);
1526: else
1.78 martynas 1527: #endif /* !SMALL */
1.75 martynas 1528: get(xargc, xargv);
1.10 deraadt 1529: }
1.1 millert 1530:
1.4 millert 1531: if ((code / 100) != COMPLETE)
1.1 millert 1532: rval = argpos + 1;
1533: }
1534: if (connected && rval != -1)
1535: disconnect(0, NULL);
1536: return (rval);
1.37 heko 1537: }
1538:
1539: char *
1.50 deraadt 1540: urldecode(const char *str)
1.37 heko 1541: {
1.53 deraadt 1542: char *ret, c;
1543: int i, reallen;
1.37 heko 1544:
1.53 deraadt 1545: if (str == NULL)
1546: return NULL;
1547: if ((ret = malloc(strlen(str)+1)) == NULL)
1548: err(1, "Can't allocate memory for URL decoding");
1549: for (i = 0, reallen = 0; str[i] != '\0'; i++, reallen++, ret++) {
1550: c = str[i];
1551: if (c == '+') {
1552: *ret = ' ';
1553: continue;
1554: }
1.61 deraadt 1555:
1556: /* Cannot use strtol here because next char
1557: * after %xx may be a digit.
1558: */
1.143 guenther 1559: if (c == '%' && isxdigit((unsigned char)str[i+1]) &&
1560: isxdigit((unsigned char)str[i+2])) {
1.53 deraadt 1561: *ret = hextochar(&str[i+1]);
1562: i+=2;
1563: continue;
1564: }
1565: *ret = c;
1566: }
1567: *ret = '\0';
1568:
1569: return ret-reallen;
1.123 guenther 1570: }
1571:
1.177 jca 1572: static char *
1.123 guenther 1573: recode_credentials(const char *userinfo)
1574: {
1575: char *ui, *creds;
1576: size_t ulen, credsize;
1577:
1578: /* url-decode the user and pass */
1579: ui = urldecode(userinfo);
1580:
1581: ulen = strlen(ui);
1582: credsize = (ulen + 2) / 3 * 4 + 1;
1583: creds = malloc(credsize);
1584: if (creds == NULL)
1585: errx(1, "out of memory");
1586: if (b64_ntop(ui, ulen, creds, credsize) == -1)
1587: errx(1, "error in base64 encoding");
1588: free(ui);
1589: return (creds);
1.37 heko 1590: }
1591:
1.177 jca 1592: static char
1.50 deraadt 1593: hextochar(const char *str)
1.37 heko 1594: {
1.143 guenther 1595: unsigned char c, ret;
1.37 heko 1596:
1.53 deraadt 1597: c = str[0];
1598: ret = c;
1599: if (isalpha(c))
1600: ret -= isupper(c) ? 'A' - 10 : 'a' - 10;
1601: else
1602: ret -= '0';
1603: ret *= 16;
1604:
1605: c = str[1];
1606: ret += c;
1607: if (isalpha(c))
1608: ret -= isupper(c) ? 'A' - 10 : 'a' - 10;
1609: else
1610: ret -= '0';
1611: return ret;
1.25 itojun 1612: }
1613:
1614: int
1.50 deraadt 1615: isurl(const char *p)
1.25 itojun 1616: {
1.27 millert 1617:
1.26 deraadt 1618: if (strncasecmp(p, FTP_URL, sizeof(FTP_URL) - 1) == 0 ||
1619: strncasecmp(p, HTTP_URL, sizeof(HTTP_URL) - 1) == 0 ||
1.154 deraadt 1620: #ifndef NOSSL
1.61 deraadt 1621: strncasecmp(p, HTTPS_URL, sizeof(HTTPS_URL) - 1) == 0 ||
1.154 deraadt 1622: #endif /* !NOSSL */
1.27 millert 1623: strncasecmp(p, FILE_URL, sizeof(FILE_URL) - 1) == 0 ||
1624: strstr(p, ":/"))
1625: return (1);
1626: return (0);
1.1 millert 1627: }
1.61 deraadt 1628:
1.177 jca 1629: static char *
1.176 jca 1630: ftp_readline(FILE *fp, size_t *lenp)
1.61 deraadt 1631: {
1.176 jca 1632: return fparseln(fp, lenp, NULL, "\0\0\0", 0);
1.173 jca 1633: }
1.184 jca 1634:
1635: #ifndef SMALL
1636: static int
1637: ftp_printf(FILE *fp, const char *fmt, ...)
1638: {
1639: va_list ap;
1640: int ret;
1641:
1642: va_start(ap, fmt);
1643: ret = vfprintf(fp, fmt, ap);
1644: va_end(ap);
1645:
1646: if (debug) {
1647: va_start(ap, fmt);
1648: vfprintf(ttyout, fmt, ap);
1649: va_end(ap);
1650: }
1651:
1652: return ret;
1653: }
1654: #endif /* !SMALL */
1.173 jca 1655:
1.177 jca 1656: static void
1.173 jca 1657: ftp_close(FILE **fin, struct tls **tls, volatile int *fd)
1658: {
1659: #ifndef NOSSL
1660: int ret;
1661:
1662: if (*tls != NULL) {
1663: if (tls_session_fd != -1)
1664: dprintf(STDERR_FILENO, "tls session resumed: %s\n",
1665: tls_conn_session_resumed(*tls) ? "yes" : "no");
1666: do {
1667: ret = tls_close(*tls);
1668: } while (ret == TLS_WANT_POLLIN || ret == TLS_WANT_POLLOUT);
1669: tls_free(*tls);
1670: *tls = NULL;
1671: }
1.176 jca 1672: if (*fd != -1) {
1673: close(*fd);
1674: *fd = -1;
1675: }
1.173 jca 1676: #endif
1677: if (*fin != NULL) {
1678: fclose(*fin);
1679: *fin = NULL;
1680: }
1.61 deraadt 1681: }
1682:
1.177 jca 1683: static const char *
1.176 jca 1684: sockerror(struct tls *tls)
1685: {
1686: int save_errno = errno;
1.154 deraadt 1687: #ifndef NOSSL
1.176 jca 1688: if (tls != NULL) {
1689: const char *tlserr = tls_error(tls);
1690: if (tlserr != NULL)
1691: return tlserr;
1.139 bluhm 1692: }
1.176 jca 1693: #endif
1694: return strerror(save_errno);
1.61 deraadt 1695: }
1696:
1.176 jca 1697: #ifndef NOSSL
1.177 jca 1698: static int
1.81 espie 1699: proxy_connect(int socket, char *host, char *cookie)
1.61 deraadt 1700: {
1.66 ray 1701: int l;
1.61 deraadt 1702: char buf[1024];
1703: char *connstr, *hosttail, *port;
1704:
1705: if (*host == '[' && (hosttail = strrchr(host, ']')) != NULL &&
1706: (hosttail[1] == '\0' || hosttail[1] == ':')) {
1707: host++;
1708: *hosttail++ = '\0';
1709: } else
1710: hosttail = host;
1711:
1.179 deraadt 1712: port = strrchr(hosttail, ':'); /* find portnum */
1.61 deraadt 1713: if (port != NULL)
1714: *port++ = '\0';
1715: if (!port)
1716: port = "443";
1717:
1.81 espie 1718: if (cookie) {
1719: l = asprintf(&connstr, "CONNECT %s:%s HTTP/1.1\r\n"
1720: "Proxy-Authorization: Basic %s\r\n%s\r\n\r\n",
1721: host, port, cookie, HTTP_USER_AGENT);
1722: } else {
1723: l = asprintf(&connstr, "CONNECT %s:%s HTTP/1.1\r\n%s\r\n\r\n",
1724: host, port, HTTP_USER_AGENT);
1725: }
1726:
1.66 ray 1727: if (l == -1)
1.61 deraadt 1728: errx(1, "Could not allocate memory to assemble connect string!");
1.80 martynas 1729: #ifndef SMALL
1.68 ray 1730: if (debug)
1731: printf("%s", connstr);
1.80 martynas 1732: #endif /* !SMALL */
1.66 ray 1733: if (write(socket, connstr, l) != l)
1.68 ray 1734: err(1, "Could not send connect string");
1.61 deraadt 1735: read(socket, &buf, sizeof(buf)); /* only proxy header XXX: error handling? */
1.71 ray 1736: free(connstr);
1.61 deraadt 1737: return(200);
1.176 jca 1738: }
1739:
1.177 jca 1740: static int
1.176 jca 1741: stdio_tls_write_wrapper(void *arg, const char *buf, int len)
1742: {
1743: struct tls *tls = arg;
1744: ssize_t ret;
1745:
1746: do {
1747: ret = tls_write(tls, buf, len);
1748: } while (ret == TLS_WANT_POLLIN || ret == TLS_WANT_POLLOUT);
1749:
1750: return ret;
1751: }
1752:
1.177 jca 1753: static int
1.176 jca 1754: stdio_tls_read_wrapper(void *arg, char *buf, int len)
1755: {
1756: struct tls *tls = arg;
1757: ssize_t ret;
1758:
1759: do {
1760: ret = tls_read(tls, buf, len);
1761: } while (ret == TLS_WANT_POLLIN || ret == TLS_WANT_POLLOUT);
1762:
1763: return ret;
1.61 deraadt 1764: }
1.158 jca 1765: #endif /* !NOSSL */