Annotation of src/usr.bin/ftp/fetch.c, Revision 1.192
1.192 ! yasuoka 1: /* $OpenBSD: fetch.c,v 1.191 2020/02/19 12:39: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 *);
1.189 jca 80: static void ftp_close(FILE **, struct tls **, int *);
1.177 jca 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.189 jca 314: int error, 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.189 jca 317: const char *savefile;
318: char *proxyurl = NULL;
1.190 yasuoka 319: char *credentials = NULL, *proxy_credentials = NULL;
1.189 jca 320: 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 */
1.191 jca 376:
377: #ifndef NOSSL
378: /*
379: * Look for auth header in host.
380: * Basic auth from RFC 2617, valid characters for path are in
381: * RFC 3986 section 3.3.
382: */
383: if (ishttpurl || ishttpsurl) {
384: p = strchr(host, '@');
385: if (p != NULL && (path == NULL || p < path)) {
386: *p++ = '\0';
387: credentials = recode_credentials(host);
388:
389: /* Overwrite userinfo */
390: memmove(host, p, strlen(p) + 1);
391: path = strchr(host, '/');
392: }
393: }
394: #endif /* !NOSSL */
395:
1.186 jca 396: if (EMPTYSTRING(path)) {
397: if (outfile) { /* No slash, but */
398: path = strchr(host,'\0'); /* we have outfile. */
399: goto noslash;
1.22 deraadt 400: }
1.186 jca 401: if (isftpurl)
402: goto noftpautologin;
403: warnx("No `/' after host (use -o): %s", origline);
404: goto cleanup_url_get;
405: }
406: *path++ = '\0';
407: if (EMPTYSTRING(path) && !outfile) {
408: if (isftpurl)
409: goto noftpautologin;
410: warnx("No filename after host (use -o): %s", origline);
411: goto cleanup_url_get;
1.14 millert 412: }
1.1 millert 413:
1.93 martynas 414: noslash:
1.17 millert 415: if (outfile)
416: savefile = outfile;
1.93 martynas 417: else {
418: if (path[strlen(path) - 1] == '/') /* Consider no file */
419: savefile = NULL; /* after dir invalid. */
420: else
421: savefile = basename(path);
1.75 martynas 422: }
423:
1.14 millert 424: if (EMPTYSTRING(savefile)) {
425: if (isftpurl)
426: goto noftpautologin;
1.94 martynas 427: warnx("No filename after directory (use -o): %s", origline);
1.6 millert 428: goto cleanup_url_get;
1.14 millert 429: }
1.1 millert 430:
1.93 martynas 431: #ifndef SMALL
1.100 halex 432: if (resume && pipeout) {
1.93 martynas 433: warnx("can't append to stdout");
434: goto cleanup_url_get;
435: }
436: #endif /* !SMALL */
437:
1.186 jca 438: if (proxyenv != NULL) { /* use proxy */
1.154 deraadt 439: #ifndef NOSSL
1.61 deraadt 440: if (ishttpsurl) {
441: sslpath = strdup(path);
442: sslhost = strdup(host);
443: if (! sslpath || ! sslhost)
444: errx(1, "Can't allocate memory for https path/host.");
445: }
1.154 deraadt 446: #endif /* !NOSSL */
1.136 bluhm 447: proxyhost = strdup(host);
448: if (proxyhost == NULL)
449: errx(1, "Can't allocate memory for proxy host.");
1.62 ray 450: proxyurl = strdup(proxyenv);
451: if (proxyurl == NULL)
1.14 millert 452: errx(1, "Can't allocate memory for proxy URL.");
1.62 ray 453: if (strncasecmp(proxyurl, HTTP_URL, sizeof(HTTP_URL) - 1) == 0)
454: host = proxyurl + sizeof(HTTP_URL) - 1;
455: else if (strncasecmp(proxyurl, FTP_URL, sizeof(FTP_URL) - 1) == 0)
456: host = proxyurl + sizeof(FTP_URL) - 1;
1.6 millert 457: else {
1.14 millert 458: warnx("Malformed proxy URL: %s", proxyenv);
1.6 millert 459: goto cleanup_url_get;
460: }
1.14 millert 461: if (EMPTYSTRING(host)) {
462: warnx("Malformed proxy URL: %s", proxyenv);
1.6 millert 463: goto cleanup_url_get;
1.14 millert 464: }
1.93 martynas 465: if (*--path == '\0')
466: *path = '/'; /* add / back to real path */
1.1 millert 467: path = strchr(host, '/'); /* remove trailing / on host */
1.42 deraadt 468: if (!EMPTYSTRING(path))
1.73 drahn 469: *path++ = '\0'; /* i guess this ++ is useless */
470:
471: path = strchr(host, '@'); /* look for credentials in proxy */
472: if (!EMPTYSTRING(path)) {
1.81 espie 473: *path = '\0';
1.123 guenther 474: if (strchr(host, ':') == NULL) {
1.73 drahn 475: warnx("Malformed proxy URL: %s", proxyenv);
476: goto cleanup_url_get;
477: }
1.190 yasuoka 478: proxy_credentials = recode_credentials(host);
1.81 espie 479: *path = '@'; /* restore @ in proxyurl */
1.123 guenther 480:
1.73 drahn 481: /*
1.81 espie 482: * This removes the password from proxyurl,
1.73 drahn 483: * filling with stars
484: */
1.81 espie 485: for (host = 1 + strchr(proxyurl + 5, ':'); *host != '@';
1.179 deraadt 486: host++)
1.73 drahn 487: *host = '*';
488:
1.81 espie 489: host = path + 1;
1.73 drahn 490: }
1.123 guenther 491:
1.62 ray 492: path = newline;
1.1 millert 493: }
494:
1.28 itojun 495: if (*host == '[' && (hosttail = strrchr(host, ']')) != NULL &&
496: (hosttail[1] == '\0' || hosttail[1] == ':')) {
497: host++;
498: *hosttail++ = '\0';
1.102 halex 499: #ifndef SMALL
500: if (asprintf(&full_host, "[%s]", host) == -1)
501: errx(1, "Cannot allocate memory for hostname");
502: #endif /* !SMALL */
1.28 itojun 503: } else
504: hosttail = host;
505:
506: portnum = strrchr(hosttail, ':'); /* find portnum */
1.1 millert 507: if (portnum != NULL)
508: *portnum++ = '\0';
1.154 deraadt 509: #ifndef NOSSL
1.150 millert 510: port = portnum ? portnum : (ishttpsurl ? httpsport : httpport);
1.154 deraadt 511: #else /* !NOSSL */
1.150 millert 512: port = portnum ? portnum : httpport;
1.154 deraadt 513: #endif /* !NOSSL */
1.1 millert 514:
1.80 martynas 515: #ifndef SMALL
1.102 halex 516: if (full_host == NULL)
517: if ((full_host = strdup(host)) == NULL)
518: errx(1, "Cannot allocate memory for hostname");
1.1 millert 519: if (debug)
1.106 haesbaer 520: fprintf(ttyout, "host %s, port %s, path %s, "
1.150 millert 521: "save as %s, auth %s.\n", host, port, path,
522: savefile, credentials ? credentials : "none");
1.80 martynas 523: #endif /* !SMALL */
1.1 millert 524:
1.25 itojun 525: memset(&hints, 0, sizeof(hints));
1.39 deraadt 526: hints.ai_family = family;
1.25 itojun 527: hints.ai_socktype = SOCK_STREAM;
528: error = getaddrinfo(host, port, &hints, &res0);
1.61 deraadt 529: /*
530: * If the services file is corrupt/missing, fall back
531: * on our hard-coded defines.
532: */
1.30 deraadt 533: if (error == EAI_SERVICE && port == httpport) {
534: snprintf(pbuf, sizeof(pbuf), "%d", HTTP_PORT);
535: error = getaddrinfo(host, pbuf, &hints, &res0);
1.154 deraadt 536: #ifndef NOSSL
1.61 deraadt 537: } else if (error == EAI_SERVICE && port == httpsport) {
538: snprintf(pbuf, sizeof(pbuf), "%d", HTTPS_PORT);
539: error = getaddrinfo(host, pbuf, &hints, &res0);
1.154 deraadt 540: #endif /* !NOSSL */
1.30 deraadt 541: }
1.25 itojun 542: if (error) {
1.122 guenther 543: warnx("%s: %s", host, gai_strerror(error));
1.25 itojun 544: goto cleanup_url_get;
1.1 millert 545: }
546:
1.105 haesbaer 547: #ifndef SMALL
548: if (srcaddr) {
549: hints.ai_flags |= AI_NUMERICHOST;
550: error = getaddrinfo(srcaddr, NULL, &hints, &ares);
551: if (error) {
1.122 guenther 552: warnx("%s: %s", srcaddr, gai_strerror(error));
1.105 haesbaer 553: goto cleanup_url_get;
554: }
555: }
556: #endif /* !SMALL */
1.135 deraadt 557:
558: /* ensure consistent order of the output */
559: if (verbose)
560: setvbuf(ttyout, NULL, _IOLBF, 0);
1.105 haesbaer 561:
1.166 procter 562: fd = -1;
1.25 itojun 563: for (res = res0; res; res = res->ai_next) {
1.44 itojun 564: if (getnameinfo(res->ai_addr, res->ai_addrlen, hbuf,
565: sizeof(hbuf), NULL, 0, NI_NUMERICHOST) != 0)
566: strlcpy(hbuf, "(unknown)", sizeof(hbuf));
1.41 deraadt 567: if (verbose)
1.44 itojun 568: fprintf(ttyout, "Trying %s...\n", hbuf);
1.14 millert 569:
1.166 procter 570: fd = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
571: if (fd == -1) {
1.25 itojun 572: cause = "socket";
573: continue;
1.1 millert 574: }
575:
1.105 haesbaer 576: #ifndef SMALL
577: if (srcaddr) {
578: if (ares->ai_family != res->ai_family) {
1.166 procter 579: close(fd);
580: fd = -1;
1.105 haesbaer 581: errno = EINVAL;
582: cause = "bind";
583: continue;
584: }
1.170 deraadt 585: if (bind(fd, ares->ai_addr, ares->ai_addrlen) == -1) {
1.105 haesbaer 586: save_errno = errno;
1.166 procter 587: close(fd);
1.105 haesbaer 588: errno = save_errno;
1.166 procter 589: fd = -1;
1.105 haesbaer 590: cause = "bind";
591: continue;
592: }
593: }
594: #endif /* !SMALL */
595:
1.155 deraadt 596: if (connect_timeout) {
597: (void)signal(SIGALRM, tooslow);
598: alarmtimer(connect_timeout);
599: }
600:
1.166 procter 601: for (error = connect(fd, res->ai_addr, res->ai_addrlen);
602: error != 0 && errno == EINTR; error = connect_wait(fd))
1.149 millert 603: continue;
604: if (error != 0) {
1.57 otto 605: save_errno = errno;
1.166 procter 606: close(fd);
1.57 otto 607: errno = save_errno;
1.166 procter 608: fd = -1;
1.25 itojun 609: cause = "connect";
1.19 deraadt 610: continue;
611: }
1.25 itojun 612:
1.29 itojun 613: /* get port in numeric */
614: if (getnameinfo(res->ai_addr, res->ai_addrlen, NULL, 0,
615: pbuf, sizeof(pbuf), NI_NUMERICSERV) == 0)
616: port = pbuf;
617: else
618: port = NULL;
619:
1.158 jca 620: #ifndef NOSSL
1.61 deraadt 621: if (proxyenv && sslhost)
1.190 yasuoka 622: proxy_connect(fd, sslhost, proxy_credentials);
1.158 jca 623: #endif /* !NOSSL */
1.25 itojun 624: break;
625: }
626: freeaddrinfo(res0);
1.105 haesbaer 627: #ifndef SMALL
628: if (srcaddr)
629: freeaddrinfo(ares);
630: #endif /* !SMALL */
1.166 procter 631: if (fd < 0) {
1.33 millert 632: warn("%s", cause);
1.6 millert 633: goto cleanup_url_get;
1.1 millert 634: }
635:
1.154 deraadt 636: #ifndef NOSSL
1.61 deraadt 637: if (ishttpsurl) {
1.187 beck 638: ssize_t ret;
1.61 deraadt 639: if (proxyenv && sslpath) {
640: ishttpsurl = 0;
1.62 ray 641: proxyurl = NULL;
1.61 deraadt 642: path = sslpath;
643: }
1.131 jca 644: if (sslhost == NULL) {
645: sslhost = strdup(host);
646: if (sslhost == NULL)
647: errx(1, "Can't allocate memory for https host.");
1.116 jca 648: }
1.134 jsing 649: if ((tls = tls_client()) == NULL) {
1.126 jsing 650: fprintf(ttyout, "failed to create SSL client\n");
1.61 deraadt 651: goto cleanup_url_get;
652: }
1.134 jsing 653: if (tls_configure(tls, tls_config) != 0) {
1.187 beck 654: fprintf(ttyout, "TLS configuration failure: %s\n",
1.134 jsing 655: tls_error(tls));
1.61 deraadt 656: goto cleanup_url_get;
1.117 jca 657: }
1.166 procter 658: if (tls_connect_socket(tls, fd, sslhost) != 0) {
1.187 beck 659: fprintf(ttyout, "TLS connect failure: %s\n", tls_error(tls));
1.72 ray 660: goto cleanup_url_get;
1.118 jca 661: }
1.187 beck 662: do {
663: ret = tls_handshake(tls);
664: } while (ret == TLS_WANT_POLLIN || ret == TLS_WANT_POLLOUT);
665: if (ret != 0) {
666: fprintf(ttyout, "TLS handshake failure: %s\n", tls_error(tls));
1.176 jca 667: goto cleanup_url_get;
668: }
669: fin = funopen(tls, stdio_tls_read_wrapper,
670: stdio_tls_write_wrapper, NULL, NULL);
1.61 deraadt 671: } else {
1.166 procter 672: fin = fdopen(fd, "r+");
673: fd = -1;
1.61 deraadt 674: }
1.154 deraadt 675: #else /* !NOSSL */
1.166 procter 676: fin = fdopen(fd, "r+");
677: fd = -1;
1.154 deraadt 678: #endif /* !NOSSL */
1.155 deraadt 679:
1.157 deraadt 680: #ifdef SMALL
681: if (lastfile) {
682: if (pipeout) {
683: if (pledge("stdio rpath inet dns tty", NULL) == -1)
684: err(1, "pledge");
685: } else {
686: if (pledge("stdio rpath wpath cpath inet dns tty", NULL) == -1)
687: err(1, "pledge");
688: }
689: }
690: #endif
691:
1.155 deraadt 692: if (connect_timeout) {
693: signal(SIGALRM, SIG_DFL);
694: alarmtimer(0);
695: }
1.40 fgsch 696:
1.1 millert 697: /*
1.40 fgsch 698: * Construct and send the request. Proxy requests don't want leading /.
1.1 millert 699: */
1.154 deraadt 700: #ifndef NOSSL
1.74 pyr 701: cookie_get(host, path, ishttpsurl, &buf);
1.154 deraadt 702: #endif /* !NOSSL */
1.95 martynas 703:
704: epath = url_encode(path);
1.62 ray 705: if (proxyurl) {
1.151 millert 706: if (verbose) {
707: fprintf(ttyout, "Requesting %s (via %s)\n",
708: origline, proxyurl);
709: }
1.32 itojun 710: /*
711: * Host: directive must use the destination host address for
1.136 bluhm 712: * the original URI (path).
1.32 itojun 713: */
1.190 yasuoka 714: ftp_printf(fin, "GET %s HTTP/1.1\r\n"
715: "Connection: close\r\n"
716: "Host: %s\r\n%s%s\r\n",
717: epath, proxyhost, buf ? buf : "", httpuseragent);
1.123 guenther 718: if (credentials)
1.190 yasuoka 719: ftp_printf(fin, "Authorization: Basic %s\r\n",
720: credentials);
721: if (proxy_credentials)
722: ftp_printf(fin, "Proxy-Authorization: Basic %s\r\n",
723: proxy_credentials);
724: ftp_printf(fin, "\r\n");
1.28 itojun 725: } else {
1.151 millert 726: if (verbose)
727: fprintf(ttyout, "Requesting %s\n", origline);
1.90 martynas 728: #ifndef SMALL
729: if (resume) {
730: struct stat stbuf;
731:
732: if (stat(savefile, &stbuf) == 0)
733: restart_point = stbuf.st_size;
734: else
735: restart_point = 0;
736: }
1.154 deraadt 737: #endif /* SMALL */
738: #ifndef NOSSL
1.123 guenther 739: if (credentials) {
1.184 jca 740: ftp_printf(fin,
1.178 jca 741: "GET /%s HTTP/1.1\r\n"
742: "Connection: close\r\n"
743: "Authorization: Basic %s\r\n"
744: "Host: ", epath, credentials);
1.123 guenther 745: free(credentials);
746: credentials = NULL;
1.106 haesbaer 747: } else
1.154 deraadt 748: #endif /* NOSSL */
1.184 jca 749: ftp_printf(fin,
1.178 jca 750: "GET /%s HTTP/1.1\r\n"
751: "Connection: close\r\n"
752: "Host: ", epath);
1.136 bluhm 753: if (proxyhost) {
1.184 jca 754: ftp_printf(fin, "%s", proxyhost);
1.136 bluhm 755: port = NULL;
756: } else if (strchr(host, ':')) {
1.55 fgsch 757: /*
758: * strip off scoped address portion, since it's
759: * local to node
760: */
1.32 itojun 761: h = strdup(host);
762: if (h == NULL)
763: errx(1, "Can't allocate memory.");
764: if ((p = strchr(h, '%')) != NULL)
765: *p = '\0';
1.184 jca 766: ftp_printf(fin, "[%s]", h);
1.32 itojun 767: free(h);
1.55 fgsch 768: } else
1.184 jca 769: ftp_printf(fin, "%s", host);
1.55 fgsch 770:
771: /*
772: * Send port number only if it's specified and does not equal
773: * 80. Some broken HTTP servers get confused if you explicitly
774: * send them the port number.
775: */
1.154 deraadt 776: #ifndef NOSSL
1.61 deraadt 777: if (port && strcmp(port, (ishttpsurl ? "443" : "80")) != 0)
1.184 jca 778: ftp_printf(fin, ":%s", port);
1.90 martynas 779: if (restart_point)
1.184 jca 780: ftp_printf(fin, "\r\nRange: bytes=%lld-",
1.75 martynas 781: (long long)restart_point);
1.154 deraadt 782: #else /* !NOSSL */
1.55 fgsch 783: if (port && strcmp(port, "80") != 0)
1.184 jca 784: ftp_printf(fin, ":%s", port);
1.154 deraadt 785: #endif /* !NOSSL */
1.184 jca 786: ftp_printf(fin, "\r\n%s%s\r\n\r\n",
1.124 lteo 787: buf ? buf : "", httpuseragent);
1.28 itojun 788: }
1.95 martynas 789: free(epath);
1.74 pyr 790:
1.154 deraadt 791: #ifndef NOSSL
1.74 pyr 792: free(buf);
1.156 tb 793: #endif /* !NOSSL */
1.74 pyr 794: buf = NULL;
795:
1.176 jca 796: if (fflush(fin) == EOF) {
797: warnx("Writing HTTP request: %s", sockerror(tls));
1.6 millert 798: goto cleanup_url_get;
1.1 millert 799: }
1.176 jca 800: if ((buf = ftp_readline(fin, &len)) == NULL) {
801: warnx("Receiving HTTP reply: %s", sockerror(tls));
1.40 fgsch 802: goto cleanup_url_get;
1.1 millert 803: }
1.40 fgsch 804:
805: while (len > 0 && (buf[len-1] == '\r' || buf[len-1] == '\n'))
806: buf[--len] = '\0';
1.80 martynas 807: #ifndef SMALL
1.40 fgsch 808: if (debug)
809: fprintf(ttyout, "received '%s'\n", buf);
1.80 martynas 810: #endif /* !SMALL */
1.40 fgsch 811:
1.1 millert 812: cp = strchr(buf, ' ');
813: if (cp == NULL)
814: goto improper;
815: else
816: cp++;
1.69 jsg 817:
818: strlcpy(ststr, cp, sizeof(ststr));
1.171 jca 819: status = strtonum(ststr, 200, 503, &errstr);
1.69 jsg 820: if (errstr) {
1.175 deraadt 821: strnvis(gerror, cp, sizeof gerror, VIS_SAFE);
822: warnx("Error retrieving %s: %s", origline, gerror);
1.69 jsg 823: goto cleanup_url_get;
824: }
825:
826: switch (status) {
827: case 200: /* OK */
1.75 martynas 828: #ifndef SMALL
1.109 sthen 829: /*
1.98 phessler 830: * When we request a partial file, and we receive an HTTP 200
831: * it is a good indication that the server doesn't support
832: * range requests, and is about to send us the entire file.
833: * If the restart_point == 0, then we are not actually
834: * requesting a partial file, and an HTTP 200 is appropriate.
835: */
836: if (resume && restart_point != 0) {
837: warnx("Server does not support resume.");
838: restart_point = resume = 0;
839: }
1.101 halex 840: /* FALLTHROUGH */
1.75 martynas 841: case 206: /* Partial Content */
1.91 halex 842: #endif /* !SMALL */
1.69 jsg 843: break;
844: case 301: /* Moved Permanently */
845: case 302: /* Found */
846: case 303: /* See Other */
847: case 307: /* Temporary Redirect */
1.40 fgsch 848: isredirect++;
1.54 fgsch 849: if (redirect_loop++ > 10) {
850: warnx("Too many redirections requested");
851: goto cleanup_url_get;
852: }
1.69 jsg 853: break;
1.75 martynas 854: #ifndef SMALL
855: case 416: /* Requested Range Not Satisfiable */
856: warnx("File is already fully retrieved.");
857: goto cleanup_url_get;
1.78 martynas 858: #endif /* !SMALL */
1.171 jca 859: case 503:
1.172 jca 860: isunavail = 1;
861: break;
1.69 jsg 862: default:
1.175 deraadt 863: strnvis(gerror, cp, sizeof gerror, VIS_SAFE);
864: warnx("Error retrieving %s: %s", origline, gerror);
1.6 millert 865: goto cleanup_url_get;
1.1 millert 866: }
867:
868: /*
869: * Read the rest of the header.
870: */
1.40 fgsch 871: free(buf);
872: filesize = -1;
873:
1.62 ray 874: for (;;) {
1.176 jca 875: if ((buf = ftp_readline(fin, &len)) == NULL) {
876: warnx("Receiving HTTP reply: %s", sockerror(tls));
1.40 fgsch 877: goto cleanup_url_get;
878: }
1.61 deraadt 879:
1.40 fgsch 880: while (len > 0 && (buf[len-1] == '\r' || buf[len-1] == '\n'))
881: buf[--len] = '\0';
882: if (len == 0)
1.1 millert 883: break;
1.80 martynas 884: #ifndef SMALL
1.40 fgsch 885: if (debug)
886: fprintf(ttyout, "received '%s'\n", buf);
1.80 martynas 887: #endif /* !SMALL */
1.1 millert 888:
1.40 fgsch 889: /* Look for some headers */
890: cp = buf;
1.1 millert 891: #define CONTENTLEN "Content-Length: "
1.40 fgsch 892: if (strncasecmp(cp, CONTENTLEN, sizeof(CONTENTLEN) - 1) == 0) {
1.104 sthen 893: size_t s;
1.40 fgsch 894: cp += sizeof(CONTENTLEN) - 1;
1.111 deraadt 895: if ((s = strcspn(cp, " \t")))
1.104 sthen 896: *(cp+s) = 0;
1.58 grunk 897: filesize = strtonum(cp, 0, LLONG_MAX, &errstr);
898: if (errstr != NULL)
1.40 fgsch 899: goto improper;
1.75 martynas 900: #ifndef SMALL
1.90 martynas 901: if (restart_point)
1.75 martynas 902: filesize += restart_point;
1.78 martynas 903: #endif /* !SMALL */
1.40 fgsch 904: #define LOCATION "Location: "
905: } else if (isredirect &&
906: strncasecmp(cp, LOCATION, sizeof(LOCATION) - 1) == 0) {
907: cp += sizeof(LOCATION) - 1;
1.144 sthen 908: /*
909: * If there is a colon before the first slash, this URI
910: * is not relative. RFC 3986 4.2
911: */
912: if (cp[strcspn(cp, ":/")] != ':') {
1.102 halex 913: #ifdef SMALL
914: errx(1, "Relative redirect not supported");
915: #else /* SMALL */
1.144 sthen 916: /* XXX doesn't handle protocol-relative URIs */
1.102 halex 917: if (*cp == '/') {
918: locbase = NULL;
919: cp++;
920: } else {
921: locbase = strdup(path);
922: if (locbase == NULL)
923: errx(1, "Can't allocate memory"
924: " for location base");
925: loctail = strchr(locbase, '#');
926: if (loctail != NULL)
927: *loctail = '\0';
928: loctail = strchr(locbase, '?');
929: if (loctail != NULL)
930: *loctail = '\0';
931: loctail = strrchr(locbase, '/');
932: if (loctail == NULL) {
933: free(locbase);
934: locbase = NULL;
935: } else
936: loctail[1] = '\0';
937: }
938: /* Contruct URL from relative redirect */
939: if (asprintf(&redirurl, "%s%s%s%s/%s%s",
940: scheme, full_host,
941: portnum ? ":" : "",
942: portnum ? portnum : "",
943: locbase ? locbase : "",
944: cp) == -1)
945: errx(1, "Cannot build "
946: "redirect URL");
947: free(locbase);
948: #endif /* SMALL */
949: } else if ((redirurl = strdup(cp)) == NULL)
950: errx(1, "Cannot allocate memory for URL");
951: loctail = strchr(redirurl, '#');
952: if (loctail != NULL)
953: *loctail = '\0';
1.40 fgsch 954: if (verbose)
1.102 halex 955: fprintf(ttyout, "Redirected to %s\n", redirurl);
1.173 jca 956: ftp_close(&fin, &tls, &fd);
1.157 deraadt 957: rval = url_get(redirurl, proxyenv, savefile, lastfile);
1.102 halex 958: free(redirurl);
959: goto cleanup_url_get;
1.172 jca 960: #define RETRYAFTER "Retry-After: "
961: } else if (isunavail &&
962: strncasecmp(cp, RETRYAFTER, sizeof(RETRYAFTER) - 1) == 0) {
963: size_t s;
964: cp += sizeof(RETRYAFTER) - 1;
965: if ((s = strcspn(cp, " \t")))
966: cp[s] = '\0';
967: retryafter = strtonum(cp, 0, 0, &errstr);
968: if (errstr != NULL)
969: retryafter = -1;
1.178 jca 970: #define TRANSFER_ENCODING "Transfer-Encoding: "
971: } else if (strncasecmp(cp, TRANSFER_ENCODING,
972: sizeof(TRANSFER_ENCODING) - 1) == 0) {
973: cp += sizeof(TRANSFER_ENCODING) - 1;
974: cp[strcspn(cp, " \t")] = '\0';
975: if (strcasecmp(cp, "chunked") == 0)
976: chunked = 1;
1.40 fgsch 977: }
1.108 tobias 978: free(buf);
1.172 jca 979: }
980:
1.178 jca 981: /* Content-Length should be ignored for Transfer-Encoding: chunked */
982: if (chunked)
983: filesize = -1;
984:
1.172 jca 985: if (isunavail) {
986: if (retried || retryafter != 0)
1.175 deraadt 987: warnx("Error retrieving %s: 503 Service Unavailable",
988: origline);
1.172 jca 989: else {
990: if (verbose)
991: fprintf(ttyout, "Retrying %s\n", origline);
992: retried = 1;
1.174 jca 993: ftp_close(&fin, &tls, &fd);
1.172 jca 994: rval = url_get(origline, proxyenv, savefile, lastfile);
995: }
996: goto cleanup_url_get;
1.1 millert 997: }
998:
1.17 millert 999: /* Open the output file. */
1.100 halex 1000: if (!pipeout) {
1.75 martynas 1001: #ifndef SMALL
1002: if (resume)
1.83 martynas 1003: out = open(savefile, O_CREAT | O_WRONLY | O_APPEND,
1004: 0666);
1.75 martynas 1005: else
1.78 martynas 1006: #endif /* !SMALL */
1.75 martynas 1007: out = open(savefile, O_CREAT | O_WRONLY | O_TRUNC,
1008: 0666);
1.170 deraadt 1009: if (out == -1) {
1.10 deraadt 1010: warn("Can't open %s", savefile);
1011: goto cleanup_url_get;
1012: }
1.157 deraadt 1013: } else {
1.17 millert 1014: out = fileno(stdout);
1.157 deraadt 1015: #ifdef SMALL
1016: if (lastfile) {
1017: if (pledge("stdio tty", NULL) == -1)
1018: err(1, "pledge");
1019: }
1020: #endif
1021: }
1.1 millert 1022:
1.189 jca 1023: free(buf);
1024: if ((buf = malloc(buflen)) == NULL)
1025: errx(1, "Can't allocate memory for transfer buffer");
1026:
1.1 millert 1027: /* Trap signals */
1028: oldintr = NULL;
1.97 martynas 1029: oldinti = NULL;
1.1 millert 1030: if (setjmp(httpabort)) {
1031: if (oldintr)
1.2 millert 1032: (void)signal(SIGINT, oldintr);
1.97 martynas 1033: if (oldinti)
1034: (void)signal(SIGINFO, oldinti);
1.6 millert 1035: goto cleanup_url_get;
1.1 millert 1036: }
1037: oldintr = signal(SIGINT, aborthttp);
1038:
1039: bytes = 0;
1040: hashbytes = mark;
1.84 martynas 1041: progressmeter(-1, path);
1.43 millert 1042:
1.1 millert 1043: /* Finally, suck down the file. */
1.97 martynas 1044: oldinti = signal(SIGINFO, psummary);
1.178 jca 1045: if (chunked) {
1.182 jca 1046: error = save_chunked(fin, tls, out, buf, buflen);
1047: signal(SIGINFO, oldinti);
1048: if (error == -1)
1.178 jca 1049: goto cleanup_url_get;
1050: } else {
1.188 jca 1051: while ((len = fread(buf, 1, buflen, fin)) > 0) {
1.178 jca 1052: bytes += len;
1.188 jca 1053: for (cp = buf; len > 0; len -= wlen, cp += wlen) {
1054: if ((wlen = write(out, cp, len)) == -1) {
1.178 jca 1055: warn("Writing %s", savefile);
1056: signal(SIGINFO, oldinti);
1057: goto cleanup_url_get;
1.188 jca 1058: }
1.178 jca 1059: }
1060: if (hash && !progress) {
1061: while (bytes >= hashbytes) {
1062: (void)putc('#', ttyout);
1063: hashbytes += mark;
1064: }
1065: (void)fflush(ttyout);
1.1 millert 1066: }
1067: }
1.188 jca 1068: save_errno = errno;
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.188 jca 1076: if (len == 0 && ferror(fin)) {
1077: errno = save_errno;
1.178 jca 1078: warnx("Reading from socket: %s", sockerror(tls));
1079: goto cleanup_url_get;
1080: }
1.1 millert 1081: }
1.84 martynas 1082: progressmeter(1, NULL);
1.75 martynas 1083: if (
1084: #ifndef SMALL
1085: !resume &&
1.78 martynas 1086: #endif /* !SMALL */
1.75 martynas 1087: filesize != -1 && len == 0 && bytes != filesize) {
1.24 deraadt 1088: if (verbose)
1089: fputs("Read short file.\n", ttyout);
1090: goto cleanup_url_get;
1091: }
1092:
1.1 millert 1093: if (verbose)
1.97 martynas 1094: ptransfer(0);
1.2 millert 1095: (void)signal(SIGINT, oldintr);
1.1 millert 1096:
1.40 fgsch 1097: rval = 0;
1098: goto cleanup_url_get;
1.1 millert 1099:
1.14 millert 1100: noftpautologin:
1101: warnx(
1102: "Auto-login using ftp URLs isn't supported when using $ftp_proxy");
1103: goto cleanup_url_get;
1104:
1.1 millert 1105: improper:
1.8 millert 1106: warnx("Improper response from %s", host);
1.14 millert 1107:
1.6 millert 1108: cleanup_url_get:
1.181 jca 1109: #ifndef SMALL
1110: free(full_host);
1111: #endif /* !SMALL */
1.154 deraadt 1112: #ifndef NOSSL
1.128 jca 1113: free(sslhost);
1.154 deraadt 1114: #endif /* !NOSSL */
1.173 jca 1115: ftp_close(&fin, &tls, &fd);
1.162 sthen 1116: if (out >= 0 && out != fileno(stdout))
1117: close(out);
1.67 steven 1118: free(buf);
1.136 bluhm 1119: free(proxyhost);
1.67 steven 1120: free(proxyurl);
1.62 ray 1121: free(newline);
1.123 guenther 1122: free(credentials);
1.190 yasuoka 1123: free(proxy_credentials);
1.40 fgsch 1124: return (rval);
1.178 jca 1125: }
1126:
1127: static int
1128: save_chunked(FILE *fin, struct tls *tls, int out, char *buf, size_t buflen)
1129: {
1130:
1131: char *header, *end, *cp;
1132: unsigned long chunksize;
1133: size_t hlen, rlen, wlen;
1134: ssize_t written;
1135: char cr, lf;
1136:
1137: for (;;) {
1138: header = ftp_readline(fin, &hlen);
1139: if (header == NULL)
1140: break;
1141: /* strip CRLF and any optional chunk extension */
1142: header[strcspn(header, ";\r\n")] = '\0';
1143: errno = 0;
1144: chunksize = strtoul(header, &end, 16);
1145: if (errno || header[0] == '\0' || *end != '\0' ||
1146: chunksize > INT_MAX) {
1147: warnx("Invalid chunk size '%s'", header);
1148: free(header);
1149: return -1;
1150: }
1151: free(header);
1152:
1153: if (chunksize == 0) {
1154: /* We're done. Ignore optional trailer. */
1155: return 0;
1156: }
1157:
1158: for (written = 0; chunksize != 0; chunksize -= rlen) {
1159: rlen = (chunksize < buflen) ? chunksize : buflen;
1160: rlen = fread(buf, 1, rlen, fin);
1161: if (rlen == 0)
1162: break;
1163: bytes += rlen;
1164: for (cp = buf, wlen = rlen; wlen > 0;
1.179 deraadt 1165: wlen -= written, cp += written) {
1.178 jca 1166: if ((written = write(out, cp, wlen)) == -1) {
1167: warn("Writing output file");
1168: return -1;
1169: }
1170: }
1171: }
1172:
1173: if (rlen == 0 ||
1174: fread(&cr, 1, 1, fin) != 1 ||
1175: fread(&lf, 1, 1, fin) != 1)
1176: break;
1177:
1178: if (cr != '\r' || lf != '\n') {
1179: warnx("Invalid chunked encoding");
1180: return -1;
1181: }
1182: }
1183:
1184: if (ferror(fin))
1185: warnx("Error while reading from socket: %s", sockerror(tls));
1186: else
1187: warnx("Invalid chunked encoding: short read");
1188:
1189: return -1;
1.1 millert 1190: }
1191:
1192: /*
1193: * Abort a http retrieval
1194: */
1.51 deraadt 1195: /* ARGSUSED */
1.177 jca 1196: static void
1.51 deraadt 1197: aborthttp(int signo)
1.1 millert 1198: {
1199:
1200: alarmtimer(0);
1.10 deraadt 1201: fputs("\nhttp fetch aborted.\n", ttyout);
1202: (void)fflush(ttyout);
1.1 millert 1203: longjmp(httpabort, 1);
1204: }
1205:
1206: /*
1.22 deraadt 1207: * Abort a http retrieval
1208: */
1.51 deraadt 1209: /* ARGSUSED */
1.177 jca 1210: static void
1.51 deraadt 1211: abortfile(int signo)
1.22 deraadt 1212: {
1213:
1214: alarmtimer(0);
1215: fputs("\nfile fetch aborted.\n", ttyout);
1216: (void)fflush(ttyout);
1217: longjmp(httpabort, 1);
1218: }
1219:
1220: /*
1.1 millert 1221: * Retrieve multiple files from the command line, transferring
1222: * files of the form "host:path", "ftp://host/path" using the
1223: * ftp protocol, and files of the form "http://host/path" using
1224: * the http protocol.
1.2 millert 1225: * If path has a trailing "/", then return (-1);
1.1 millert 1226: * the path will be cd-ed into and the connection remains open,
1227: * and the function will return -1 (to indicate the connection
1228: * is alive).
1229: * If an error occurs the return value will be the offset+1 in
1230: * argv[] of the file that caused a problem (i.e, argv[x]
1231: * returns x+1)
1232: * Otherwise, 0 is returned if all files retrieved successfully.
1233: */
1234: int
1.50 deraadt 1235: auto_fetch(int argc, char *argv[], char *outfile)
1.1 millert 1236: {
1237: char *xargv[5];
1.62 ray 1238: char *cp, *url, *host, *dir, *file, *portnum;
1239: char *username, *pass, *pathstart;
1.6 millert 1240: char *ftpproxy, *httpproxy;
1.157 deraadt 1241: int rval, xargc, lastfile;
1.14 millert 1242: volatile int argpos;
1.49 krw 1243: int dirhasglob, filehasglob, oautologin;
1.137 deraadt 1244: char rempath[PATH_MAX];
1.1 millert 1245:
1246: argpos = 0;
1247:
1248: if (setjmp(toplevel)) {
1249: if (connected)
1250: disconnect(0, NULL);
1.2 millert 1251: return (argpos + 1);
1.1 millert 1252: }
1.3 millert 1253: (void)signal(SIGINT, (sig_t)intr);
1254: (void)signal(SIGPIPE, (sig_t)lostpeer);
1.1 millert 1255:
1.45 millert 1256: if ((ftpproxy = getenv(FTP_PROXY)) != NULL && *ftpproxy == '\0')
1257: ftpproxy = NULL;
1258: if ((httpproxy = getenv(HTTP_PROXY)) != NULL && *httpproxy == '\0')
1259: httpproxy = NULL;
1.6 millert 1260:
1.1 millert 1261: /*
1262: * Loop through as long as there's files to fetch.
1263: */
1.123 guenther 1264: username = pass = NULL;
1.62 ray 1265: for (rval = 0; (rval == 0) && (argpos < argc); free(url), argpos++) {
1.1 millert 1266: if (strchr(argv[argpos], ':') == NULL)
1267: break;
1.123 guenther 1268:
1269: free(username);
1270: free(pass);
1.62 ray 1271: host = dir = file = portnum = username = pass = NULL;
1.1 millert 1272:
1.157 deraadt 1273: lastfile = (argv[argpos+1] == NULL);
1274:
1.1 millert 1275: /*
1276: * We muck with the string, so we make a copy.
1277: */
1.62 ray 1278: url = strdup(argv[argpos]);
1279: if (url == NULL)
1.1 millert 1280: errx(1, "Can't allocate memory for auto-fetch.");
1281:
1.186 jca 1282: if (strncasecmp(url, FILE_URL, sizeof(FILE_URL) - 1) == 0) {
1283: if (file_get(url + sizeof(FILE_URL) - 1, outfile) == -1)
1284: rval = argpos + 1;
1285: continue;
1286: }
1287:
1.1 millert 1288: /*
1.186 jca 1289: * Try HTTP URL-style arguments next.
1.1 millert 1290: */
1.62 ray 1291: if (strncasecmp(url, HTTP_URL, sizeof(HTTP_URL) - 1) == 0 ||
1.186 jca 1292: strncasecmp(url, HTTPS_URL, sizeof(HTTPS_URL) -1) == 0) {
1.54 fgsch 1293: redirect_loop = 0;
1.171 jca 1294: retried = 0;
1.157 deraadt 1295: if (url_get(url, httpproxy, outfile, lastfile) == -1)
1.1 millert 1296: rval = argpos + 1;
1297: continue;
1298: }
1299:
1300: /*
1.6 millert 1301: * Try FTP URL-style arguments next. If ftpproxy is
1302: * set, use url_get() instead of standard ftp.
1303: * Finally, try host:file.
1.1 millert 1304: */
1.62 ray 1305: host = url;
1306: if (strncasecmp(url, FTP_URL, sizeof(FTP_URL) - 1) == 0) {
1.37 heko 1307: char *passend, *passagain, *userend;
1.31 itojun 1308:
1.6 millert 1309: if (ftpproxy) {
1.157 deraadt 1310: if (url_get(url, ftpproxy, outfile, lastfile) == -1)
1.6 millert 1311: rval = argpos + 1;
1312: continue;
1313: }
1.1 millert 1314: host += sizeof(FTP_URL) - 1;
1.8 millert 1315: dir = strchr(host, '/');
1.1 millert 1316:
1.8 millert 1317: /* Look for [user:pass@]host[:port] */
1.31 itojun 1318:
1319: /* check if we have "user:pass@" */
1.37 heko 1320: userend = strchr(host, ':');
1.31 itojun 1321: passend = strchr(host, '@');
1322: if (passend && userend && userend < passend &&
1323: (!dir || passend < dir)) {
1.62 ray 1324: username = host;
1.31 itojun 1325: pass = userend + 1;
1326: host = passend + 1;
1327: *userend = *passend = '\0';
1.37 heko 1328: passagain = strchr(host, '@');
1.42 deraadt 1329: if (strchr(pass, '@') != NULL ||
1.37 heko 1330: (passagain != NULL && passagain < dir)) {
1331: warnx(at_encoding_warning);
1.123 guenther 1332: username = pass = NULL;
1.37 heko 1333: goto bad_ftp_url;
1.42 deraadt 1334: }
1.31 itojun 1335:
1.77 martynas 1336: if (EMPTYSTRING(username)) {
1.11 millert 1337: bad_ftp_url:
1.31 itojun 1338: warnx("Invalid URL: %s", argv[argpos]);
1339: rval = argpos + 1;
1.123 guenther 1340: username = pass = NULL;
1.31 itojun 1341: continue;
1342: }
1.62 ray 1343: username = urldecode(username);
1.37 heko 1344: pass = urldecode(pass);
1.8 millert 1345: }
1.31 itojun 1346:
1347: /* check [host]:port, or [host] */
1348: if (host[0] == '[') {
1349: cp = strchr(host, ']');
1350: if (cp && (!dir || cp < dir)) {
1351: if (cp + 1 == dir || cp[1] == ':') {
1352: host++;
1353: *cp++ = '\0';
1354: } else
1355: cp = NULL;
1356: } else
1357: cp = host;
1.25 itojun 1358: } else
1359: cp = host;
1.31 itojun 1360:
1361: /* split off host[:port] if there is */
1362: if (cp) {
1363: portnum = strchr(cp, ':');
1.52 henning 1364: pathstart = strchr(cp, '/');
1365: /* : in path is not a port # indicator */
1366: if (portnum && pathstart &&
1367: pathstart < portnum)
1368: portnum = NULL;
1369:
1.31 itojun 1370: if (!portnum)
1371: ;
1372: else {
1373: if (!dir)
1374: ;
1375: else if (portnum + 1 < dir) {
1376: *portnum++ = '\0';
1377: /*
1378: * XXX should check if portnum
1379: * is decimal number
1380: */
1381: } else {
1382: /* empty portnum */
1383: goto bad_ftp_url;
1384: }
1385: }
1386: } else
1387: portnum = NULL;
1.8 millert 1388: } else { /* classic style `host:file' */
1389: dir = strchr(host, ':');
1390: }
1.1 millert 1391: if (EMPTYSTRING(host)) {
1392: rval = argpos + 1;
1393: continue;
1394: }
1395:
1396: /*
1.9 millert 1397: * If dir is NULL, the file wasn't specified
1.1 millert 1398: * (URL looked something like ftp://host)
1399: */
1.8 millert 1400: if (dir != NULL)
1401: *dir++ = '\0';
1.1 millert 1402:
1403: /*
1404: * Extract the file and (if present) directory name.
1405: */
1.42 deraadt 1406: if (!EMPTYSTRING(dir)) {
1.8 millert 1407: cp = strrchr(dir, '/');
1.1 millert 1408: if (cp != NULL) {
1409: *cp++ = '\0';
1410: file = cp;
1411: } else {
1412: file = dir;
1413: dir = NULL;
1414: }
1415: }
1.80 martynas 1416: #ifndef SMALL
1.1 millert 1417: if (debug)
1.42 deraadt 1418: fprintf(ttyout,
1419: "user %s:%s host %s port %s dir %s file %s\n",
1.76 martynas 1420: username, pass ? "XXXX" : NULL, host, portnum,
1421: dir, file);
1.80 martynas 1422: #endif /* !SMALL */
1.1 millert 1423:
1424: /*
1.49 krw 1425: * Set up the connection.
1.1 millert 1426: */
1.49 krw 1427: if (connected)
1428: disconnect(0, NULL);
1429: xargv[0] = __progname;
1430: xargv[1] = host;
1.8 millert 1431: xargv[2] = NULL;
1.49 krw 1432: xargc = 2;
1433: if (!EMPTYSTRING(portnum)) {
1434: xargv[2] = portnum;
1435: xargv[3] = NULL;
1436: xargc = 3;
1437: }
1438: oautologin = autologin;
1.88 martynas 1439: if (username == NULL)
1.89 halex 1440: anonftp = 1;
1441: else {
1442: anonftp = 0;
1.49 krw 1443: autologin = 0;
1.89 halex 1444: }
1.49 krw 1445: setpeer(xargc, xargv);
1446: autologin = oautologin;
1.87 martynas 1447: if (connected == 0 ||
1448: (connected == 1 && autologin && (username == NULL ||
1449: !ftp_login(host, username, pass)))) {
1.49 krw 1450: warnx("Can't connect or login to host `%s'", host);
1.8 millert 1451: rval = argpos + 1;
1452: continue;
1.1 millert 1453: }
1.49 krw 1454:
1455: /* Always use binary transfers. */
1456: setbinary(0, NULL);
1.1 millert 1457:
1.4 millert 1458: dirhasglob = filehasglob = 0;
1459: if (doglob) {
1.42 deraadt 1460: if (!EMPTYSTRING(dir) &&
1.4 millert 1461: strpbrk(dir, "*?[]{}") != NULL)
1462: dirhasglob = 1;
1.42 deraadt 1463: if (!EMPTYSTRING(file) &&
1.4 millert 1464: strpbrk(file, "*?[]{}") != NULL)
1465: filehasglob = 1;
1466: }
1467:
1.1 millert 1468: /* Change directories, if necessary. */
1.42 deraadt 1469: if (!EMPTYSTRING(dir) && !dirhasglob) {
1.1 millert 1470: xargv[0] = "cd";
1471: xargv[1] = dir;
1472: xargv[2] = NULL;
1473: cd(2, xargv);
1.42 deraadt 1474: if (!dirchange) {
1.1 millert 1475: rval = argpos + 1;
1476: continue;
1477: }
1478: }
1479:
1480: if (EMPTYSTRING(file)) {
1.86 martynas 1481: #ifndef SMALL
1.1 millert 1482: rval = -1;
1.86 martynas 1483: #else /* !SMALL */
1484: recvrequest("NLST", "-", NULL, "w", 0, 0);
1485: rval = 0;
1486: #endif /* !SMALL */
1.1 millert 1487: continue;
1488: }
1489:
1.21 marc 1490: if (verbose)
1.10 deraadt 1491: fprintf(ttyout, "Retrieving %s/%s\n", dir ? dir : "", file);
1.1 millert 1492:
1.4 millert 1493: if (dirhasglob) {
1494: snprintf(rempath, sizeof(rempath), "%s/%s", dir, file);
1495: file = rempath;
1496: }
1497:
1498: /* Fetch the file(s). */
1.10 deraadt 1499: xargc = 2;
1.1 millert 1500: xargv[0] = "get";
1501: xargv[1] = file;
1502: xargv[2] = NULL;
1.4 millert 1503: if (dirhasglob || filehasglob) {
1504: int ointeractive;
1505:
1506: ointeractive = interactive;
1507: interactive = 0;
1508: xargv[0] = "mget";
1.78 martynas 1509: #ifndef SMALL
1510: if (resume) {
1511: xargc = 3;
1512: xargv[1] = "-c";
1513: xargv[2] = file;
1514: xargv[3] = NULL;
1515: }
1516: #endif /* !SMALL */
1.10 deraadt 1517: mget(xargc, xargv);
1.5 millert 1518: interactive = ointeractive;
1.10 deraadt 1519: } else {
1.17 millert 1520: if (outfile != NULL) {
1521: xargv[2] = outfile;
1522: xargv[3] = NULL;
1.10 deraadt 1523: xargc++;
1524: }
1.75 martynas 1525: #ifndef SMALL
1526: if (resume)
1527: reget(xargc, xargv);
1528: else
1.78 martynas 1529: #endif /* !SMALL */
1.75 martynas 1530: get(xargc, xargv);
1.10 deraadt 1531: }
1.1 millert 1532:
1.4 millert 1533: if ((code / 100) != COMPLETE)
1.1 millert 1534: rval = argpos + 1;
1535: }
1536: if (connected && rval != -1)
1537: disconnect(0, NULL);
1538: return (rval);
1.37 heko 1539: }
1540:
1541: char *
1.50 deraadt 1542: urldecode(const char *str)
1.37 heko 1543: {
1.53 deraadt 1544: char *ret, c;
1545: int i, reallen;
1.37 heko 1546:
1.53 deraadt 1547: if (str == NULL)
1548: return NULL;
1549: if ((ret = malloc(strlen(str)+1)) == NULL)
1550: err(1, "Can't allocate memory for URL decoding");
1551: for (i = 0, reallen = 0; str[i] != '\0'; i++, reallen++, ret++) {
1552: c = str[i];
1553: if (c == '+') {
1554: *ret = ' ';
1555: continue;
1556: }
1.61 deraadt 1557:
1558: /* Cannot use strtol here because next char
1559: * after %xx may be a digit.
1560: */
1.143 guenther 1561: if (c == '%' && isxdigit((unsigned char)str[i+1]) &&
1562: isxdigit((unsigned char)str[i+2])) {
1.53 deraadt 1563: *ret = hextochar(&str[i+1]);
1564: i+=2;
1565: continue;
1566: }
1567: *ret = c;
1568: }
1569: *ret = '\0';
1570:
1571: return ret-reallen;
1.123 guenther 1572: }
1573:
1.177 jca 1574: static char *
1.123 guenther 1575: recode_credentials(const char *userinfo)
1576: {
1577: char *ui, *creds;
1578: size_t ulen, credsize;
1579:
1580: /* url-decode the user and pass */
1581: ui = urldecode(userinfo);
1582:
1583: ulen = strlen(ui);
1584: credsize = (ulen + 2) / 3 * 4 + 1;
1585: creds = malloc(credsize);
1586: if (creds == NULL)
1587: errx(1, "out of memory");
1588: if (b64_ntop(ui, ulen, creds, credsize) == -1)
1589: errx(1, "error in base64 encoding");
1590: free(ui);
1591: return (creds);
1.37 heko 1592: }
1593:
1.177 jca 1594: static char
1.50 deraadt 1595: hextochar(const char *str)
1.37 heko 1596: {
1.143 guenther 1597: unsigned char c, ret;
1.37 heko 1598:
1.53 deraadt 1599: c = str[0];
1600: ret = c;
1601: if (isalpha(c))
1602: ret -= isupper(c) ? 'A' - 10 : 'a' - 10;
1603: else
1604: ret -= '0';
1605: ret *= 16;
1606:
1607: c = str[1];
1608: ret += c;
1609: if (isalpha(c))
1610: ret -= isupper(c) ? 'A' - 10 : 'a' - 10;
1611: else
1612: ret -= '0';
1613: return ret;
1.25 itojun 1614: }
1615:
1616: int
1.50 deraadt 1617: isurl(const char *p)
1.25 itojun 1618: {
1.27 millert 1619:
1.26 deraadt 1620: if (strncasecmp(p, FTP_URL, sizeof(FTP_URL) - 1) == 0 ||
1621: strncasecmp(p, HTTP_URL, sizeof(HTTP_URL) - 1) == 0 ||
1.154 deraadt 1622: #ifndef NOSSL
1.61 deraadt 1623: strncasecmp(p, HTTPS_URL, sizeof(HTTPS_URL) - 1) == 0 ||
1.154 deraadt 1624: #endif /* !NOSSL */
1.27 millert 1625: strncasecmp(p, FILE_URL, sizeof(FILE_URL) - 1) == 0 ||
1626: strstr(p, ":/"))
1627: return (1);
1628: return (0);
1.1 millert 1629: }
1.61 deraadt 1630:
1.177 jca 1631: static char *
1.176 jca 1632: ftp_readline(FILE *fp, size_t *lenp)
1.61 deraadt 1633: {
1.176 jca 1634: return fparseln(fp, lenp, NULL, "\0\0\0", 0);
1.173 jca 1635: }
1.184 jca 1636:
1637: #ifndef SMALL
1638: static int
1639: ftp_printf(FILE *fp, const char *fmt, ...)
1640: {
1641: va_list ap;
1642: int ret;
1643:
1644: va_start(ap, fmt);
1645: ret = vfprintf(fp, fmt, ap);
1646: va_end(ap);
1647:
1648: if (debug) {
1649: va_start(ap, fmt);
1650: vfprintf(ttyout, fmt, ap);
1651: va_end(ap);
1652: }
1653:
1654: return ret;
1655: }
1656: #endif /* !SMALL */
1.173 jca 1657:
1.177 jca 1658: static void
1.189 jca 1659: ftp_close(FILE **fin, struct tls **tls, int *fd)
1.173 jca 1660: {
1661: #ifndef NOSSL
1662: int ret;
1663:
1664: if (*tls != NULL) {
1665: if (tls_session_fd != -1)
1666: dprintf(STDERR_FILENO, "tls session resumed: %s\n",
1667: tls_conn_session_resumed(*tls) ? "yes" : "no");
1668: do {
1669: ret = tls_close(*tls);
1670: } while (ret == TLS_WANT_POLLIN || ret == TLS_WANT_POLLOUT);
1671: tls_free(*tls);
1672: *tls = NULL;
1673: }
1.176 jca 1674: if (*fd != -1) {
1675: close(*fd);
1676: *fd = -1;
1677: }
1.173 jca 1678: #endif
1679: if (*fin != NULL) {
1680: fclose(*fin);
1681: *fin = NULL;
1682: }
1.61 deraadt 1683: }
1684:
1.177 jca 1685: static const char *
1.176 jca 1686: sockerror(struct tls *tls)
1687: {
1688: int save_errno = errno;
1.154 deraadt 1689: #ifndef NOSSL
1.176 jca 1690: if (tls != NULL) {
1691: const char *tlserr = tls_error(tls);
1692: if (tlserr != NULL)
1693: return tlserr;
1.139 bluhm 1694: }
1.176 jca 1695: #endif
1696: return strerror(save_errno);
1.61 deraadt 1697: }
1698:
1.176 jca 1699: #ifndef NOSSL
1.177 jca 1700: static int
1.81 espie 1701: proxy_connect(int socket, char *host, char *cookie)
1.61 deraadt 1702: {
1.66 ray 1703: int l;
1.61 deraadt 1704: char buf[1024];
1.192 ! yasuoka 1705: char *connstr, *hosttail, *port;
1.61 deraadt 1706:
1707: if (*host == '[' && (hosttail = strrchr(host, ']')) != NULL &&
1708: (hosttail[1] == '\0' || hosttail[1] == ':')) {
1709: host++;
1710: *hosttail++ = '\0';
1711: } else
1712: hosttail = host;
1713:
1.179 deraadt 1714: port = strrchr(hosttail, ':'); /* find portnum */
1.61 deraadt 1715: if (port != NULL)
1716: *port++ = '\0';
1717: if (!port)
1718: port = "443";
1719:
1.81 espie 1720: if (cookie) {
1721: l = asprintf(&connstr, "CONNECT %s:%s HTTP/1.1\r\n"
1722: "Proxy-Authorization: Basic %s\r\n%s\r\n\r\n",
1723: host, port, cookie, HTTP_USER_AGENT);
1724: } else {
1725: l = asprintf(&connstr, "CONNECT %s:%s HTTP/1.1\r\n%s\r\n\r\n",
1726: host, port, HTTP_USER_AGENT);
1727: }
1728:
1.66 ray 1729: if (l == -1)
1.61 deraadt 1730: errx(1, "Could not allocate memory to assemble connect string!");
1.80 martynas 1731: #ifndef SMALL
1.68 ray 1732: if (debug)
1733: printf("%s", connstr);
1.80 martynas 1734: #endif /* !SMALL */
1.66 ray 1735: if (write(socket, connstr, l) != l)
1.68 ray 1736: err(1, "Could not send connect string");
1.192 ! yasuoka 1737: read(socket, &buf, sizeof(buf)); /* only proxy header XXX: error handling? */
1.71 ray 1738: free(connstr);
1.61 deraadt 1739: return(200);
1.176 jca 1740: }
1741:
1.177 jca 1742: static int
1.176 jca 1743: stdio_tls_write_wrapper(void *arg, const char *buf, int len)
1744: {
1745: struct tls *tls = arg;
1746: ssize_t ret;
1747:
1748: do {
1749: ret = tls_write(tls, buf, len);
1750: } while (ret == TLS_WANT_POLLIN || ret == TLS_WANT_POLLOUT);
1751:
1752: return ret;
1753: }
1754:
1.177 jca 1755: static int
1.176 jca 1756: stdio_tls_read_wrapper(void *arg, char *buf, int len)
1757: {
1758: struct tls *tls = arg;
1759: ssize_t ret;
1760:
1761: do {
1762: ret = tls_read(tls, buf, len);
1763: } while (ret == TLS_WANT_POLLIN || ret == TLS_WANT_POLLOUT);
1764:
1765: return ret;
1.61 deraadt 1766: }
1.158 jca 1767: #endif /* !NOSSL */