[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.103

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