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