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