[BACK]Return to fetch.c CVS log [TXT][DIR] Up to [local] / src / usr.bin / ftp

Annotation of src/usr.bin/ftp/fetch.c, Revision 1.105

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