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

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