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

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