Annotation of src/usr.bin/ftp/fetch.c, Revision 1.63
1.63 ! ray 1: /* $OpenBSD: fetch.c,v 1.62 2006/05/16 23:43:16 ray 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: * 3. All advertising materials mentioning features or use of this software
20: * must display the following acknowledgement:
21: * This product includes software developed by the NetBSD
22: * Foundation, Inc. and its contributors.
23: * 4. Neither the name of The NetBSD Foundation nor the names of its
24: * contributors may be used to endorse or promote products derived
25: * from this software without specific prior written permission.
26: *
27: * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
28: * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
29: * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
1.15 millert 30: * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
31: * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
1.1 millert 32: * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
33: * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
34: * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
35: * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
36: * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
37: * POSSIBILITY OF SUCH DAMAGE.
38: */
39:
1.48 deraadt 40: #if !defined(lint) && !defined(SMALL)
1.63 ! ray 41: static const char rcsid[] = "$OpenBSD: fetch.c,v 1.62 2006/05/16 23:43:16 ray Exp $";
1.48 deraadt 42: #endif /* not lint and not SMALL */
1.1 millert 43:
44: /*
45: * FTP User Program -- Command line file retrieval
46: */
47:
48: #include <sys/types.h>
49: #include <sys/param.h>
50: #include <sys/socket.h>
1.22 deraadt 51: #include <sys/stat.h>
1.1 millert 52:
53: #include <netinet/in.h>
54:
55: #include <arpa/ftp.h>
56: #include <arpa/inet.h>
57:
58: #include <ctype.h>
59: #include <err.h>
1.17 millert 60: #include <libgen.h>
1.58 grunk 61: #include <limits.h>
1.1 millert 62: #include <netdb.h>
63: #include <fcntl.h>
1.3 millert 64: #include <signal.h>
1.1 millert 65: #include <stdio.h>
1.61 deraadt 66: #include <stdarg.h>
1.19 deraadt 67: #include <errno.h>
1.1 millert 68: #include <stdlib.h>
69: #include <string.h>
70: #include <unistd.h>
1.40 fgsch 71: #include <util.h>
1.1 millert 72:
1.61 deraadt 73: #ifndef SMALL
74: #include <openssl/ssl.h>
75: #include <openssl/err.h>
76: #else
77: #define SSL void
78: #endif
79:
1.1 millert 80: #include "ftp_var.h"
81:
1.38 millert 82: static int url_get(const char *, const char *, const char *);
83: void aborthttp(int);
84: void abortfile(int);
1.42 deraadt 85: char hextochar(const char *);
86: char *urldecode(const char *);
1.61 deraadt 87: int ftp_printf(FILE *, SSL *, const char *, ...) __attribute__((format(printf, 3, 4)));
88: char *ftp_readline(FILE *, SSL *, size_t *);
89: int ftp_read(FILE *, SSL *, char *, size_t);
90: #ifndef SMALL
91: int proxy_connect(int, char *);
92: int SSL_vprintf(SSL *, const char *, va_list);
93: char *SSL_readline(SSL *, size_t *);
94: #endif
1.14 millert 95:
1.1 millert 96: #define FTP_URL "ftp://" /* ftp URL prefix */
97: #define HTTP_URL "http://" /* http URL prefix */
1.61 deraadt 98: #define HTTPS_URL "https://" /* https URL prefix */
1.22 deraadt 99: #define FILE_URL "file:" /* file URL prefix */
1.6 millert 100: #define FTP_PROXY "ftp_proxy" /* env var with ftp proxy location */
1.1 millert 101: #define HTTP_PROXY "http_proxy" /* env var with http proxy location */
102:
103:
104: #define EMPTYSTRING(x) ((x) == NULL || (*(x) == '\0'))
105:
1.37 heko 106: static const char *at_encoding_warning =
1.53 deraadt 107: "Extra `@' characters in usernames and passwords should be encoded as %%40";
1.37 heko 108:
1.1 millert 109: jmp_buf httpabort;
110:
1.54 fgsch 111: static int redirect_loop;
112:
1.1 millert 113: /*
1.6 millert 114: * Retrieve URL, via the proxy in $proxyvar if necessary.
1.1 millert 115: * Modifies the string argument given.
116: * Returns -1 on failure, 0 on success
117: */
1.14 millert 118: static int
1.50 deraadt 119: url_get(const char *origline, const char *proxyenv, const char *outfile)
1.1 millert 120: {
1.58 grunk 121: char pbuf[NI_MAXSERV], hbuf[NI_MAXHOST], *cp, *portnum, *path;
1.62 ray 122: char *hosttail, *cause = "unknown", *newline, *host, *port, *buf = NULL;
1.53 deraadt 123: int error, i, isftpurl = 0, isfileurl = 0, isredirect = 0, rval = -1;
1.25 itojun 124: struct addrinfo hints, *res0, *res;
1.34 millert 125: const char * volatile savefile;
1.62 ray 126: char * volatile proxyurl = NULL;
1.53 deraadt 127: volatile int s = -1, out;
1.14 millert 128: volatile sig_t oldintr;
1.53 deraadt 129: FILE *fin = NULL;
1.1 millert 130: off_t hashbytes;
1.58 grunk 131: const char *errstr;
1.61 deraadt 132: size_t len, wlen;
133: #ifndef SMALL
134: char *sslpath = NULL, *sslhost = NULL;
135: int ishttpsurl = 0;
136: SSL_CTX *ssl_ctx = NULL;
137: #endif
138: SSL *ssl = NULL;
1.14 millert 139:
1.62 ray 140: newline = strdup(origline);
141: if (newline == NULL)
1.14 millert 142: errx(1, "Can't allocate memory to parse URL");
1.62 ray 143: if (strncasecmp(newline, HTTP_URL, sizeof(HTTP_URL) - 1) == 0)
144: host = newline + sizeof(HTTP_URL) - 1;
145: else if (strncasecmp(newline, FTP_URL, sizeof(FTP_URL) - 1) == 0) {
146: host = newline + sizeof(FTP_URL) - 1;
1.14 millert 147: isftpurl = 1;
1.62 ray 148: } else if (strncasecmp(newline, FILE_URL, sizeof(FILE_URL) - 1) == 0) {
149: host = newline + sizeof(FILE_URL) - 1;
1.22 deraadt 150: isfileurl = 1;
1.61 deraadt 151: #ifndef SMALL
1.62 ray 152: } else if (strncasecmp(newline, HTTPS_URL, sizeof(HTTPS_URL) - 1) == 0) {
153: host = newline + sizeof(HTTPS_URL) - 1;
1.61 deraadt 154: ishttpsurl = 1;
155: #endif
1.14 millert 156: } else
1.62 ray 157: errx(1, "url_get: Invalid URL '%s'", newline);
1.6 millert 158:
1.22 deraadt 159: if (isfileurl) {
160: path = host;
161: } else {
162: path = strchr(host, '/'); /* find path */
163: if (EMPTYSTRING(path)) {
164: if (isftpurl)
165: goto noftpautologin;
166: warnx("Invalid URL (no `/' after host): %s", origline);
167: goto cleanup_url_get;
168: }
169: *path++ = '\0';
170: if (EMPTYSTRING(path)) {
171: if (isftpurl)
172: goto noftpautologin;
173: warnx("Invalid URL (no file after host): %s", origline);
174: goto cleanup_url_get;
175: }
1.14 millert 176: }
1.1 millert 177:
1.17 millert 178: if (outfile)
179: savefile = outfile;
1.1 millert 180: else
1.17 millert 181: savefile = basename(path);
182:
1.14 millert 183: if (EMPTYSTRING(savefile)) {
184: if (isftpurl)
185: goto noftpautologin;
186: warnx("Invalid URL (no file after directory): %s", origline);
1.6 millert 187: goto cleanup_url_get;
1.14 millert 188: }
1.1 millert 189:
1.59 uwe 190: if (!isfileurl && proxyenv != NULL) { /* use proxy */
1.61 deraadt 191: #ifndef SMALL
192: if (ishttpsurl) {
193: sslpath = strdup(path);
194: sslhost = strdup(host);
195: if (! sslpath || ! sslhost)
196: errx(1, "Can't allocate memory for https path/host.");
197: }
198: #endif
1.62 ray 199: proxyurl = strdup(proxyenv);
200: if (proxyurl == NULL)
1.14 millert 201: errx(1, "Can't allocate memory for proxy URL.");
1.62 ray 202: if (strncasecmp(proxyurl, HTTP_URL, sizeof(HTTP_URL) - 1) == 0)
203: host = proxyurl + sizeof(HTTP_URL) - 1;
204: else if (strncasecmp(proxyurl, FTP_URL, sizeof(FTP_URL) - 1) == 0)
205: host = proxyurl + sizeof(FTP_URL) - 1;
1.6 millert 206: else {
1.14 millert 207: warnx("Malformed proxy URL: %s", proxyenv);
1.6 millert 208: goto cleanup_url_get;
209: }
1.14 millert 210: if (EMPTYSTRING(host)) {
211: warnx("Malformed proxy URL: %s", proxyenv);
1.6 millert 212: goto cleanup_url_get;
1.14 millert 213: }
1.1 millert 214: *--path = '/'; /* add / back to real path */
215: path = strchr(host, '/'); /* remove trailing / on host */
1.42 deraadt 216: if (!EMPTYSTRING(path))
1.1 millert 217: *path++ = '\0';
1.62 ray 218: path = newline;
1.1 millert 219: }
220:
1.22 deraadt 221: if (isfileurl) {
222: struct stat st;
223:
224: s = open(path, O_RDONLY);
225: if (s == -1) {
226: warn("Can't open file %s", path);
227: goto cleanup_url_get;
228: }
229:
230: if (fstat(s, &st) == -1)
231: filesize = -1;
232: else
233: filesize = st.st_size;
234:
235: /* Open the output file. */
236: if (strcmp(savefile, "-") != 0) {
1.55 fgsch 237: out = open(savefile, O_CREAT | O_WRONLY | O_TRUNC,
238: 0666);
1.22 deraadt 239: if (out < 0) {
240: warn("Can't open %s", savefile);
241: goto cleanup_url_get;
242: }
243: } else
244: out = fileno(stdout);
245:
246: /* Trap signals */
247: oldintr = NULL;
248: if (setjmp(httpabort)) {
249: if (oldintr)
250: (void)signal(SIGINT, oldintr);
251: goto cleanup_url_get;
252: }
253: oldintr = signal(SIGINT, abortfile);
1.42 deraadt 254:
1.22 deraadt 255: bytes = 0;
256: hashbytes = mark;
257: progressmeter(-1);
1.40 fgsch 258:
259: if ((buf = malloc(4096)) == NULL)
1.47 deraadt 260: errx(1, "Can't allocate memory for transfer buffer");
1.42 deraadt 261:
1.22 deraadt 262: /* Finally, suck down the file. */
263: i = 0;
1.40 fgsch 264: while ((len = read(s, buf, 4096)) > 0) {
1.22 deraadt 265: bytes += len;
266: for (cp = buf; len > 0; len -= i, cp += i) {
267: if ((i = write(out, cp, len)) == -1) {
268: warn("Writing %s", savefile);
269: goto cleanup_url_get;
270: }
271: else if (i == 0)
272: break;
273: }
274: if (hash && !progress) {
275: while (bytes >= hashbytes) {
276: (void)putc('#', ttyout);
277: hashbytes += mark;
278: }
279: (void)fflush(ttyout);
280: }
281: }
282: if (hash && !progress && bytes > 0) {
283: if (bytes < mark)
284: (void)putc('#', ttyout);
285: (void)putc('\n', ttyout);
286: (void)fflush(ttyout);
287: }
288: if (len != 0) {
289: warn("Reading from file");
290: goto cleanup_url_get;
291: }
292: progressmeter(1);
293: if (verbose)
294: fputs("Successfully retrieved file.\n", ttyout);
295: (void)signal(SIGINT, oldintr);
1.42 deraadt 296:
1.40 fgsch 297: rval = 0;
298: goto cleanup_url_get;
1.22 deraadt 299: }
300:
1.28 itojun 301: if (*host == '[' && (hosttail = strrchr(host, ']')) != NULL &&
302: (hosttail[1] == '\0' || hosttail[1] == ':')) {
303: host++;
304: *hosttail++ = '\0';
305: } else
306: hosttail = host;
307:
308: portnum = strrchr(hosttail, ':'); /* find portnum */
1.1 millert 309: if (portnum != NULL)
310: *portnum++ = '\0';
311:
312: if (debug)
1.10 deraadt 313: fprintf(ttyout, "host %s, port %s, path %s, save as %s.\n",
1.1 millert 314: host, portnum, path, savefile);
315:
1.25 itojun 316: memset(&hints, 0, sizeof(hints));
1.39 deraadt 317: hints.ai_family = family;
1.25 itojun 318: hints.ai_socktype = SOCK_STREAM;
1.61 deraadt 319: #ifndef SMALL
320: port = portnum ? portnum : (ishttpsurl ? httpsport : httpport);
321: #else
1.25 itojun 322: port = portnum ? portnum : httpport;
1.61 deraadt 323: #endif
1.25 itojun 324: error = getaddrinfo(host, port, &hints, &res0);
1.61 deraadt 325: /*
326: * If the services file is corrupt/missing, fall back
327: * on our hard-coded defines.
328: */
1.30 deraadt 329: if (error == EAI_SERVICE && port == httpport) {
330: snprintf(pbuf, sizeof(pbuf), "%d", HTTP_PORT);
331: error = getaddrinfo(host, pbuf, &hints, &res0);
1.61 deraadt 332: #ifndef SMALL
333: } else if (error == EAI_SERVICE && port == httpsport) {
334: snprintf(pbuf, sizeof(pbuf), "%d", HTTPS_PORT);
335: error = getaddrinfo(host, pbuf, &hints, &res0);
336: #endif
1.30 deraadt 337: }
1.25 itojun 338: if (error) {
339: warnx("%s: %s", gai_strerror(error), host);
340: goto cleanup_url_get;
1.1 millert 341: }
342:
1.25 itojun 343: s = -1;
344: for (res = res0; res; res = res->ai_next) {
1.44 itojun 345: if (getnameinfo(res->ai_addr, res->ai_addrlen, hbuf,
346: sizeof(hbuf), NULL, 0, NI_NUMERICHOST) != 0)
347: strlcpy(hbuf, "(unknown)", sizeof(hbuf));
1.41 deraadt 348: if (verbose)
1.44 itojun 349: fprintf(ttyout, "Trying %s...\n", hbuf);
1.14 millert 350:
1.25 itojun 351: s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
352: if (s == -1) {
353: cause = "socket";
354: continue;
1.1 millert 355: }
356:
1.25 itojun 357: again:
358: if (connect(s, res->ai_addr, res->ai_addrlen) < 0) {
1.57 otto 359: int save_errno;
360:
1.25 itojun 361: if (errno == EINTR)
362: goto again;
1.57 otto 363: save_errno = errno;
1.25 itojun 364: close(s);
1.57 otto 365: errno = save_errno;
1.25 itojun 366: s = -1;
367: cause = "connect";
1.19 deraadt 368: continue;
369: }
1.25 itojun 370:
1.29 itojun 371: /* get port in numeric */
372: if (getnameinfo(res->ai_addr, res->ai_addrlen, NULL, 0,
373: pbuf, sizeof(pbuf), NI_NUMERICSERV) == 0)
374: port = pbuf;
375: else
376: port = NULL;
377:
1.61 deraadt 378: #ifndef SMALL
379: if (proxyenv && sslhost)
380: proxy_connect(s, sslhost);
381: #endif
1.25 itojun 382: break;
383: }
384: freeaddrinfo(res0);
385: if (s < 0) {
1.33 millert 386: warn("%s", cause);
1.6 millert 387: goto cleanup_url_get;
1.1 millert 388: }
389:
1.61 deraadt 390: #ifndef SMALL
391: if (ishttpsurl) {
392: if (proxyenv && sslpath) {
393: ishttpsurl = 0;
1.62 ray 394: proxyurl = NULL;
1.61 deraadt 395: path = sslpath;
396: }
397: SSL_library_init();
398: SSL_load_error_strings();
399: SSLeay_add_ssl_algorithms();
400: ssl_ctx = SSL_CTX_new(SSLv23_client_method());
401: ssl = SSL_new(ssl_ctx);
402: if (ssl == NULL || ssl_ctx == NULL) {
403: ERR_print_errors_fp(ttyout);
404: goto cleanup_url_get;
405: }
406: if (SSL_set_fd(ssl, s) == 0) {
407: ERR_print_errors_fp(ttyout);
408: goto cleanup_url_get;
409: }
410: if (SSL_connect(ssl) <= 0) {
411: ERR_print_errors_fp(ttyout);
412: goto cleanup_url_get;;
413: }
414: } else {
415: fin = fdopen(s, "r+");
416: }
417: #else
1.40 fgsch 418: fin = fdopen(s, "r+");
1.61 deraadt 419: #endif
1.40 fgsch 420:
1.55 fgsch 421: if (verbose)
422: fprintf(ttyout, "Requesting %s", origline);
1.1 millert 423: /*
1.40 fgsch 424: * Construct and send the request. Proxy requests don't want leading /.
1.1 millert 425: */
1.62 ray 426: if (proxyurl) {
1.55 fgsch 427: if (verbose)
428: fprintf(ttyout, " (via %s)\n", proxyenv);
1.32 itojun 429: /*
430: * Host: directive must use the destination host address for
431: * the original URI (path). We do not attach it at this moment.
432: */
1.61 deraadt 433: ftp_printf(fin, ssl, "GET %s HTTP/1.0\r\n%s\r\n\r\n", path,
1.55 fgsch 434: HTTP_USER_AGENT);
1.28 itojun 435: } else {
1.61 deraadt 436: ftp_printf(fin, ssl, "GET /%s HTTP/1.0\r\nHost: ", path);
1.32 itojun 437: if (strchr(host, ':')) {
438: char *h, *p;
439:
1.55 fgsch 440: /*
441: * strip off scoped address portion, since it's
442: * local to node
443: */
1.32 itojun 444: h = strdup(host);
445: if (h == NULL)
446: errx(1, "Can't allocate memory.");
447: if ((p = strchr(h, '%')) != NULL)
448: *p = '\0';
1.61 deraadt 449: ftp_printf(fin, ssl, "[%s]", h);
1.32 itojun 450: free(h);
1.55 fgsch 451: } else
1.61 deraadt 452: ftp_printf(fin, ssl, "%s", host);
1.55 fgsch 453:
454: /*
455: * Send port number only if it's specified and does not equal
456: * 80. Some broken HTTP servers get confused if you explicitly
457: * send them the port number.
458: */
1.61 deraadt 459: #ifndef SMALL
460: if (port && strcmp(port, (ishttpsurl ? "443" : "80")) != 0)
461: ftp_printf(fin, ssl, ":%s", port);
462: #else
1.55 fgsch 463: if (port && strcmp(port, "80") != 0)
1.61 deraadt 464: ftp_printf(fin, ssl, ":%s", port);
465: #endif
466: ftp_printf(fin, ssl, "\r\n%s\r\n\r\n", HTTP_USER_AGENT);
1.55 fgsch 467: if (verbose)
468: fprintf(ttyout, "\n");
1.28 itojun 469: }
1.61 deraadt 470: if (fin != NULL && fflush(fin) == EOF) {
1.14 millert 471: warn("Writing HTTP request");
1.6 millert 472: goto cleanup_url_get;
1.1 millert 473: }
1.61 deraadt 474: if ((buf = ftp_readline(fin, ssl, &len)) == NULL) {
1.40 fgsch 475: warn("Receiving HTTP reply");
476: goto cleanup_url_get;
1.1 millert 477: }
1.40 fgsch 478:
479: while (len > 0 && (buf[len-1] == '\r' || buf[len-1] == '\n'))
480: buf[--len] = '\0';
481: if (debug)
482: fprintf(ttyout, "received '%s'\n", buf);
483:
1.1 millert 484: cp = strchr(buf, ' ');
485: if (cp == NULL)
486: goto improper;
487: else
488: cp++;
1.40 fgsch 489: if (strncmp(cp, "301", 3) == 0 || strncmp(cp, "302", 3) == 0) {
490: isredirect++;
1.54 fgsch 491: if (redirect_loop++ > 10) {
492: warnx("Too many redirections requested");
493: goto cleanup_url_get;
494: }
1.40 fgsch 495: } else if (strncmp(cp, "200", 3)) {
1.1 millert 496: warnx("Error retrieving file: %s", cp);
1.6 millert 497: goto cleanup_url_get;
1.1 millert 498: }
499:
500: /*
501: * Read the rest of the header.
502: */
1.40 fgsch 503: free(buf);
504: filesize = -1;
505:
1.62 ray 506: for (;;) {
1.61 deraadt 507: if ((buf = ftp_readline(fin, ssl, &len)) == NULL) {
1.40 fgsch 508: warn("Receiving HTTP reply");
509: goto cleanup_url_get;
510: }
1.61 deraadt 511:
1.40 fgsch 512: while (len > 0 && (buf[len-1] == '\r' || buf[len-1] == '\n'))
513: buf[--len] = '\0';
514: if (len == 0)
1.1 millert 515: break;
1.40 fgsch 516: if (debug)
517: fprintf(ttyout, "received '%s'\n", buf);
1.1 millert 518:
1.40 fgsch 519: /* Look for some headers */
520: cp = buf;
1.1 millert 521: #define CONTENTLEN "Content-Length: "
1.40 fgsch 522: if (strncasecmp(cp, CONTENTLEN, sizeof(CONTENTLEN) - 1) == 0) {
523: cp += sizeof(CONTENTLEN) - 1;
1.58 grunk 524: filesize = strtonum(cp, 0, LLONG_MAX, &errstr);
525: if (errstr != NULL)
1.40 fgsch 526: goto improper;
527: #define LOCATION "Location: "
528: } else if (isredirect &&
529: strncasecmp(cp, LOCATION, sizeof(LOCATION) - 1) == 0) {
530: cp += sizeof(LOCATION) - 1;
531: if (verbose)
532: fprintf(ttyout, "Redirected to %s\n", cp);
533: if (fin != NULL)
534: fclose(fin);
535: else if (s != -1)
536: close(s);
1.62 ray 537: if (proxyurl)
538: free(proxyurl);
539: free(newline);
1.40 fgsch 540: rval = url_get(cp, proxyenv, outfile);
541: if (buf)
542: free(buf);
543: return (rval);
544: }
1.1 millert 545: }
546:
1.17 millert 547: /* Open the output file. */
548: if (strcmp(savefile, "-") != 0) {
1.10 deraadt 549: out = open(savefile, O_CREAT | O_WRONLY | O_TRUNC, 0666);
550: if (out < 0) {
551: warn("Can't open %s", savefile);
552: goto cleanup_url_get;
553: }
554: } else
1.17 millert 555: out = fileno(stdout);
1.1 millert 556:
557: /* Trap signals */
558: oldintr = NULL;
559: if (setjmp(httpabort)) {
560: if (oldintr)
1.2 millert 561: (void)signal(SIGINT, oldintr);
1.6 millert 562: goto cleanup_url_get;
1.1 millert 563: }
564: oldintr = signal(SIGINT, aborthttp);
565:
566: bytes = 0;
567: hashbytes = mark;
568: progressmeter(-1);
1.43 millert 569:
570: free(buf);
1.1 millert 571:
572: /* Finally, suck down the file. */
1.40 fgsch 573: if ((buf = malloc(4096)) == NULL)
1.47 deraadt 574: errx(1, "Can't allocate memory for transfer buffer");
1.1 millert 575: i = 0;
1.61 deraadt 576: len = 1;
577: while (len > 0) {
578: len = ftp_read(fin, ssl, buf, 4096);
1.1 millert 579: bytes += len;
1.61 deraadt 580: for (cp = buf, wlen = len; wlen > 0; wlen -= i, cp += i) {
581: if ((i = write(out, cp, wlen)) == -1) {
1.1 millert 582: warn("Writing %s", savefile);
1.6 millert 583: goto cleanup_url_get;
1.1 millert 584: }
585: else if (i == 0)
586: break;
587: }
588: if (hash && !progress) {
589: while (bytes >= hashbytes) {
1.10 deraadt 590: (void)putc('#', ttyout);
1.1 millert 591: hashbytes += mark;
592: }
1.10 deraadt 593: (void)fflush(ttyout);
1.1 millert 594: }
595: }
596: if (hash && !progress && bytes > 0) {
597: if (bytes < mark)
1.10 deraadt 598: (void)putc('#', ttyout);
599: (void)putc('\n', ttyout);
600: (void)fflush(ttyout);
1.1 millert 601: }
602: if (len != 0) {
603: warn("Reading from socket");
1.6 millert 604: goto cleanup_url_get;
1.1 millert 605: }
606: progressmeter(1);
1.24 deraadt 607: if (filesize != -1 && len == 0 && bytes != filesize) {
608: if (verbose)
609: fputs("Read short file.\n", ttyout);
610: goto cleanup_url_get;
611: }
612:
1.1 millert 613: if (verbose)
1.10 deraadt 614: fputs("Successfully retrieved file.\n", ttyout);
1.2 millert 615: (void)signal(SIGINT, oldintr);
1.1 millert 616:
1.40 fgsch 617: rval = 0;
618: goto cleanup_url_get;
1.1 millert 619:
1.14 millert 620: noftpautologin:
621: warnx(
622: "Auto-login using ftp URLs isn't supported when using $ftp_proxy");
623: goto cleanup_url_get;
624:
1.1 millert 625: improper:
1.8 millert 626: warnx("Improper response from %s", host);
1.14 millert 627:
1.6 millert 628: cleanup_url_get:
1.61 deraadt 629: #ifndef SMALL
630: if (ssl) {
631: SSL_shutdown(ssl);
632: SSL_free(ssl);
633: }
634: #endif
1.40 fgsch 635: if (fin != NULL)
636: fclose(fin);
637: else if (s != -1)
1.1 millert 638: close(s);
1.40 fgsch 639: if (buf)
640: free(buf);
1.62 ray 641: if (proxyurl)
642: free(proxyurl);
643: free(newline);
1.40 fgsch 644: return (rval);
1.1 millert 645: }
646:
647: /*
648: * Abort a http retrieval
649: */
1.51 deraadt 650: /* ARGSUSED */
1.1 millert 651: void
1.51 deraadt 652: aborthttp(int signo)
1.1 millert 653: {
654:
655: alarmtimer(0);
1.10 deraadt 656: fputs("\nhttp fetch aborted.\n", ttyout);
657: (void)fflush(ttyout);
1.1 millert 658: longjmp(httpabort, 1);
659: }
660:
661: /*
1.22 deraadt 662: * Abort a http retrieval
663: */
1.51 deraadt 664: /* ARGSUSED */
1.22 deraadt 665: void
1.51 deraadt 666: abortfile(int signo)
1.22 deraadt 667: {
668:
669: alarmtimer(0);
670: fputs("\nfile fetch aborted.\n", ttyout);
671: (void)fflush(ttyout);
672: longjmp(httpabort, 1);
673: }
674:
675: /*
1.1 millert 676: * Retrieve multiple files from the command line, transferring
677: * files of the form "host:path", "ftp://host/path" using the
678: * ftp protocol, and files of the form "http://host/path" using
679: * the http protocol.
1.2 millert 680: * If path has a trailing "/", then return (-1);
1.1 millert 681: * the path will be cd-ed into and the connection remains open,
682: * and the function will return -1 (to indicate the connection
683: * is alive).
684: * If an error occurs the return value will be the offset+1 in
685: * argv[] of the file that caused a problem (i.e, argv[x]
686: * returns x+1)
687: * Otherwise, 0 is returned if all files retrieved successfully.
688: */
689: int
1.50 deraadt 690: auto_fetch(int argc, char *argv[], char *outfile)
1.1 millert 691: {
692: char *xargv[5];
1.62 ray 693: char *cp, *url, *host, *dir, *file, *portnum;
694: char *username, *pass, *pathstart;
1.6 millert 695: char *ftpproxy, *httpproxy;
1.14 millert 696: int rval, xargc;
697: volatile int argpos;
1.49 krw 698: int dirhasglob, filehasglob, oautologin;
1.14 millert 699: char rempath[MAXPATHLEN];
1.1 millert 700:
701: argpos = 0;
702:
703: if (setjmp(toplevel)) {
704: if (connected)
705: disconnect(0, NULL);
1.2 millert 706: return (argpos + 1);
1.1 millert 707: }
1.3 millert 708: (void)signal(SIGINT, (sig_t)intr);
709: (void)signal(SIGPIPE, (sig_t)lostpeer);
1.1 millert 710:
1.45 millert 711: if ((ftpproxy = getenv(FTP_PROXY)) != NULL && *ftpproxy == '\0')
712: ftpproxy = NULL;
713: if ((httpproxy = getenv(HTTP_PROXY)) != NULL && *httpproxy == '\0')
714: httpproxy = NULL;
1.6 millert 715:
1.1 millert 716: /*
717: * Loop through as long as there's files to fetch.
718: */
1.62 ray 719: for (rval = 0; (rval == 0) && (argpos < argc); free(url), argpos++) {
1.1 millert 720: if (strchr(argv[argpos], ':') == NULL)
721: break;
1.62 ray 722: host = dir = file = portnum = username = pass = NULL;
1.1 millert 723:
724: /*
725: * We muck with the string, so we make a copy.
726: */
1.62 ray 727: url = strdup(argv[argpos]);
728: if (url == NULL)
1.1 millert 729: errx(1, "Can't allocate memory for auto-fetch.");
730:
731: /*
732: * Try HTTP URL-style arguments first.
733: */
1.62 ray 734: if (strncasecmp(url, HTTP_URL, sizeof(HTTP_URL) - 1) == 0 ||
1.61 deraadt 735: #ifndef SMALL
736: /* even if we compiled without SSL, url_get will check */
1.62 ray 737: strncasecmp(url, HTTPS_URL, sizeof(HTTPS_URL) -1) == 0 ||
1.61 deraadt 738: #endif
1.62 ray 739: strncasecmp(url, FILE_URL, sizeof(FILE_URL) - 1) == 0) {
1.54 fgsch 740: redirect_loop = 0;
1.62 ray 741: if (url_get(url, httpproxy, outfile) == -1)
1.1 millert 742: rval = argpos + 1;
743: continue;
744: }
745:
746: /*
1.6 millert 747: * Try FTP URL-style arguments next. If ftpproxy is
748: * set, use url_get() instead of standard ftp.
749: * Finally, try host:file.
1.1 millert 750: */
1.62 ray 751: host = url;
752: if (strncasecmp(url, FTP_URL, sizeof(FTP_URL) - 1) == 0) {
1.37 heko 753: char *passend, *passagain, *userend;
1.31 itojun 754:
1.6 millert 755: if (ftpproxy) {
1.62 ray 756: if (url_get(url, ftpproxy, outfile) == -1)
1.6 millert 757: rval = argpos + 1;
758: continue;
759: }
1.1 millert 760: host += sizeof(FTP_URL) - 1;
1.8 millert 761: dir = strchr(host, '/');
1.1 millert 762:
1.8 millert 763: /* Look for [user:pass@]host[:port] */
1.31 itojun 764:
765: /* check if we have "user:pass@" */
1.37 heko 766: userend = strchr(host, ':');
1.31 itojun 767: passend = strchr(host, '@');
768: if (passend && userend && userend < passend &&
769: (!dir || passend < dir)) {
1.62 ray 770: username = host;
1.31 itojun 771: pass = userend + 1;
772: host = passend + 1;
773: *userend = *passend = '\0';
1.37 heko 774: passagain = strchr(host, '@');
1.42 deraadt 775: if (strchr(pass, '@') != NULL ||
1.37 heko 776: (passagain != NULL && passagain < dir)) {
777: warnx(at_encoding_warning);
778: goto bad_ftp_url;
1.42 deraadt 779: }
1.31 itojun 780:
1.62 ray 781: if (EMPTYSTRING(username) || EMPTYSTRING(pass)) {
1.11 millert 782: bad_ftp_url:
1.31 itojun 783: warnx("Invalid URL: %s", argv[argpos]);
784: rval = argpos + 1;
785: continue;
786: }
1.62 ray 787: username = urldecode(username);
1.37 heko 788: pass = urldecode(pass);
1.8 millert 789: }
1.31 itojun 790:
791: #ifdef INET6
792: /* check [host]:port, or [host] */
793: if (host[0] == '[') {
794: cp = strchr(host, ']');
795: if (cp && (!dir || cp < dir)) {
796: if (cp + 1 == dir || cp[1] == ':') {
797: host++;
798: *cp++ = '\0';
799: } else
800: cp = NULL;
801: } else
802: cp = host;
1.25 itojun 803: } else
804: cp = host;
1.31 itojun 805: #else
806: cp = host;
1.25 itojun 807: #endif
1.31 itojun 808:
809: /* split off host[:port] if there is */
810: if (cp) {
811: portnum = strchr(cp, ':');
1.52 henning 812: pathstart = strchr(cp, '/');
813: /* : in path is not a port # indicator */
814: if (portnum && pathstart &&
815: pathstart < portnum)
816: portnum = NULL;
817:
1.31 itojun 818: if (!portnum)
819: ;
820: else {
821: if (!dir)
822: ;
823: else if (portnum + 1 < dir) {
824: *portnum++ = '\0';
825: /*
826: * XXX should check if portnum
827: * is decimal number
828: */
829: } else {
830: /* empty portnum */
831: goto bad_ftp_url;
832: }
833: }
834: } else
835: portnum = NULL;
1.8 millert 836: } else { /* classic style `host:file' */
837: dir = strchr(host, ':');
838: }
1.1 millert 839: if (EMPTYSTRING(host)) {
840: rval = argpos + 1;
841: continue;
842: }
843:
844: /*
1.9 millert 845: * If dir is NULL, the file wasn't specified
1.1 millert 846: * (URL looked something like ftp://host)
847: */
1.8 millert 848: if (dir != NULL)
849: *dir++ = '\0';
1.1 millert 850:
851: /*
852: * Extract the file and (if present) directory name.
853: */
1.42 deraadt 854: if (!EMPTYSTRING(dir)) {
1.8 millert 855: cp = strrchr(dir, '/');
1.1 millert 856: if (cp != NULL) {
857: *cp++ = '\0';
858: file = cp;
859: } else {
860: file = dir;
861: dir = NULL;
862: }
863: }
864: if (debug)
1.42 deraadt 865: fprintf(ttyout,
866: "user %s:%s host %s port %s dir %s file %s\n",
1.62 ray 867: username, pass, host, portnum, dir, file);
1.1 millert 868:
869: /*
1.49 krw 870: * Set up the connection.
1.1 millert 871: */
1.49 krw 872: if (connected)
873: disconnect(0, NULL);
874: xargv[0] = __progname;
875: xargv[1] = host;
1.8 millert 876: xargv[2] = NULL;
1.49 krw 877: xargc = 2;
878: if (!EMPTYSTRING(portnum)) {
879: xargv[2] = portnum;
880: xargv[3] = NULL;
881: xargc = 3;
882: }
883: oautologin = autologin;
1.62 ray 884: if (username != NULL)
1.49 krw 885: autologin = 0;
886: setpeer(xargc, xargv);
887: autologin = oautologin;
888: if ((connected == 0) ||
1.62 ray 889: ((connected == 1) && !ftp_login(host, username, pass))) {
1.49 krw 890: warnx("Can't connect or login to host `%s'", host);
1.8 millert 891: rval = argpos + 1;
892: continue;
1.1 millert 893: }
1.49 krw 894:
895: /* Always use binary transfers. */
896: setbinary(0, NULL);
1.1 millert 897:
1.4 millert 898: dirhasglob = filehasglob = 0;
899: if (doglob) {
1.42 deraadt 900: if (!EMPTYSTRING(dir) &&
1.4 millert 901: strpbrk(dir, "*?[]{}") != NULL)
902: dirhasglob = 1;
1.42 deraadt 903: if (!EMPTYSTRING(file) &&
1.4 millert 904: strpbrk(file, "*?[]{}") != NULL)
905: filehasglob = 1;
906: }
907:
1.1 millert 908: /* Change directories, if necessary. */
1.42 deraadt 909: if (!EMPTYSTRING(dir) && !dirhasglob) {
1.1 millert 910: xargv[0] = "cd";
911: xargv[1] = dir;
912: xargv[2] = NULL;
913: cd(2, xargv);
1.42 deraadt 914: if (!dirchange) {
1.1 millert 915: rval = argpos + 1;
916: continue;
917: }
918: }
919:
920: if (EMPTYSTRING(file)) {
921: rval = -1;
922: continue;
923: }
924:
1.21 marc 925: if (verbose)
1.10 deraadt 926: fprintf(ttyout, "Retrieving %s/%s\n", dir ? dir : "", file);
1.1 millert 927:
1.4 millert 928: if (dirhasglob) {
929: snprintf(rempath, sizeof(rempath), "%s/%s", dir, file);
930: file = rempath;
931: }
932:
933: /* Fetch the file(s). */
1.10 deraadt 934: xargc = 2;
1.1 millert 935: xargv[0] = "get";
936: xargv[1] = file;
937: xargv[2] = NULL;
1.4 millert 938: if (dirhasglob || filehasglob) {
939: int ointeractive;
940:
941: ointeractive = interactive;
942: interactive = 0;
943: xargv[0] = "mget";
1.10 deraadt 944: mget(xargc, xargv);
1.5 millert 945: interactive = ointeractive;
1.10 deraadt 946: } else {
1.17 millert 947: if (outfile != NULL) {
948: xargv[2] = outfile;
949: xargv[3] = NULL;
1.10 deraadt 950: xargc++;
951: }
952: get(xargc, xargv);
953: }
1.1 millert 954:
1.4 millert 955: if ((code / 100) != COMPLETE)
1.1 millert 956: rval = argpos + 1;
957: }
958: if (connected && rval != -1)
959: disconnect(0, NULL);
960: return (rval);
1.37 heko 961: }
962:
963: char *
1.50 deraadt 964: urldecode(const char *str)
1.37 heko 965: {
1.53 deraadt 966: char *ret, c;
967: int i, reallen;
1.37 heko 968:
1.53 deraadt 969: if (str == NULL)
970: return NULL;
971: if ((ret = malloc(strlen(str)+1)) == NULL)
972: err(1, "Can't allocate memory for URL decoding");
973: for (i = 0, reallen = 0; str[i] != '\0'; i++, reallen++, ret++) {
974: c = str[i];
975: if (c == '+') {
976: *ret = ' ';
977: continue;
978: }
1.61 deraadt 979:
980: /* Cannot use strtol here because next char
981: * after %xx may be a digit.
982: */
1.53 deraadt 983: if (c == '%' && isxdigit(str[i+1]) && isxdigit(str[i+2])) {
984: *ret = hextochar(&str[i+1]);
985: i+=2;
986: continue;
987: }
988: *ret = c;
989: }
990: *ret = '\0';
991:
992: return ret-reallen;
1.37 heko 993: }
994:
995: char
1.50 deraadt 996: hextochar(const char *str)
1.37 heko 997: {
1.53 deraadt 998: char c, ret;
1.37 heko 999:
1.53 deraadt 1000: c = str[0];
1001: ret = c;
1002: if (isalpha(c))
1003: ret -= isupper(c) ? 'A' - 10 : 'a' - 10;
1004: else
1005: ret -= '0';
1006: ret *= 16;
1007:
1008: c = str[1];
1009: ret += c;
1010: if (isalpha(c))
1011: ret -= isupper(c) ? 'A' - 10 : 'a' - 10;
1012: else
1013: ret -= '0';
1014: return ret;
1.25 itojun 1015: }
1016:
1017: int
1.50 deraadt 1018: isurl(const char *p)
1.25 itojun 1019: {
1.27 millert 1020:
1.26 deraadt 1021: if (strncasecmp(p, FTP_URL, sizeof(FTP_URL) - 1) == 0 ||
1022: strncasecmp(p, HTTP_URL, sizeof(HTTP_URL) - 1) == 0 ||
1.61 deraadt 1023: #ifndef SMALL
1024: strncasecmp(p, HTTPS_URL, sizeof(HTTPS_URL) - 1) == 0 ||
1025: #endif
1.27 millert 1026: strncasecmp(p, FILE_URL, sizeof(FILE_URL) - 1) == 0 ||
1027: strstr(p, ":/"))
1028: return (1);
1029: return (0);
1.1 millert 1030: }
1.61 deraadt 1031:
1032: char *
1033: ftp_readline(FILE *fp, SSL *ssl, size_t *lenp)
1034: {
1035: if (fp != NULL)
1036: return fparseln(fp, lenp, NULL, "\0\0\0", 0);
1037: #ifndef SMALL
1038: else if (ssl != NULL)
1039: return SSL_readline(ssl, lenp);
1040: #endif
1041: else
1042: return NULL;
1043: }
1044:
1045: int
1046: ftp_read(FILE *fp, SSL *ssl, char *buf, size_t len)
1047: {
1048: int ret;
1049: if (fp != NULL)
1050: ret = fread(buf, sizeof(char), len, fp);
1051: #ifndef SMALL
1052: else if (ssl != NULL)
1053: ret = SSL_read(ssl, buf, (int)len);
1054: #endif
1055: else
1056: ret = 0;
1057: return (ret);
1058: }
1059:
1060: int
1061: ftp_printf(FILE *fp, SSL *ssl, const char *fmt, ...)
1062: {
1063: int ret;
1064: va_list ap;
1065:
1066: va_start(ap, fmt);
1067:
1068: if (fp != NULL)
1069: ret = vfprintf(fp, fmt, ap);
1070: #ifndef SMALL
1071: else if (ssl != NULL)
1072: ret = SSL_vprintf((SSL*)ssl, fmt, ap);
1073: #endif
1074: else
1075: ret = NULL;
1076:
1077: va_end(ap);
1078: return (ret);
1079: }
1080:
1081: #ifndef SMALL
1082: int
1083: SSL_vprintf(SSL *ssl, const char *fmt, va_list ap)
1084: {
1085: int ret;
1086: char *string;
1087:
1088: if ((ret = vasprintf(&string, fmt, ap)) == -1)
1089: return ret;
1090: ret = SSL_write(ssl, (void *)string, (int)strlen(string));
1091: free(string);
1092: return ret;
1093: }
1094:
1095: char *
1096: SSL_readline(SSL *ssl, size_t *lenp)
1097: {
1.63 ! ray 1098: size_t i, len;
1.61 deraadt 1099: char *buf, *q, c;
1100:
1101: len = 128;
1102: if ((buf = malloc(len)) == NULL)
1103: errx(1, "Can't allocate memory for transfer buffer");
1104: for (i = 0; ; i++) {
1105: if (i >= len - 1) {
1106: if ((q = realloc(buf, 2 * len)) == NULL)
1107: errx(1, "Can't expand transfer buffer");
1108: buf = q;
1109: len *= 2;
1110: }
1111: if (SSL_read(ssl, &c, 1) <= 0)
1112: break;
1113: buf[i] = c;
1114: if (c == '\n')
1115: break;
1116: }
1117: *lenp = i;
1118: return (buf);
1119: }
1120:
1121: int
1122: proxy_connect(int socket, char *host)
1123: {
1124: char buf[1024];
1125: char *connstr, *hosttail, *port;
1126:
1127: if (*host == '[' && (hosttail = strrchr(host, ']')) != NULL &&
1128: (hosttail[1] == '\0' || hosttail[1] == ':')) {
1129: host++;
1130: *hosttail++ = '\0';
1131: } else
1132: hosttail = host;
1133:
1134: port = strrchr(hosttail, ':'); /* find portnum */
1135: if (port != NULL)
1136: *port++ = '\0';
1137: if (!port)
1138: port = "443";
1139:
1140: if (debug)
1141: printf("CONNECT %s:%s HTTP/1.1\n\n", host, port);
1142: asprintf(&connstr, "CONNECT %s:%s HTTP/1.1\n\n", host, port);
1143: if (!connstr)
1144: errx(1, "Could not allocate memory to assemble connect string!");
1145: if (write(socket, connstr, strlen(connstr)) != strlen(connstr))
1146: errx(1, "Could not send connect string: %s", strerror(errno));
1147: read(socket, &buf, sizeof(buf)); /* only proxy header XXX: error handling? */
1148: return(200);
1149: }
1150: #endif