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

1.186   ! jca         1: /*     $OpenBSD: fetch.c,v 1.185 2019/12/19 00:07:20 jca 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 *);
                     80: static void    ftp_close(FILE **, struct tls **, volatile int *);
                     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.186   ! jca       314:        int error, i, 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.34      millert   317:        const char * volatile savefile;
1.62      ray       318:        char * volatile proxyurl = NULL;
1.123     guenther  319:        char *credentials = NULL;
1.166     procter   320:        volatile 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) {
                    634:                if (proxyenv && sslpath) {
                    635:                        ishttpsurl = 0;
1.62      ray       636:                        proxyurl = NULL;
1.61      deraadt   637:                        path = sslpath;
                    638:                }
1.131     jca       639:                if (sslhost == NULL) {
                    640:                        sslhost = strdup(host);
                    641:                        if (sslhost == NULL)
                    642:                                errx(1, "Can't allocate memory for https host.");
1.116     jca       643:                }
1.134     jsing     644:                if ((tls = tls_client()) == NULL) {
1.126     jsing     645:                        fprintf(ttyout, "failed to create SSL client\n");
1.61      deraadt   646:                        goto cleanup_url_get;
                    647:                }
1.134     jsing     648:                if (tls_configure(tls, tls_config) != 0) {
1.126     jsing     649:                        fprintf(ttyout, "SSL configuration failure: %s\n",
1.134     jsing     650:                            tls_error(tls));
1.61      deraadt   651:                        goto cleanup_url_get;
1.117     jca       652:                }
1.166     procter   653:                if (tls_connect_socket(tls, fd, sslhost) != 0) {
1.134     jsing     654:                        fprintf(ttyout, "SSL failure: %s\n", tls_error(tls));
1.72      ray       655:                        goto cleanup_url_get;
1.118     jca       656:                }
1.176     jca       657:                if (tls_handshake(tls) != 0) {
                    658:                        fprintf(ttyout, "SSL failure: %s\n", tls_error(tls));
                    659:                        goto cleanup_url_get;
                    660:                }
                    661:                fin = funopen(tls, stdio_tls_read_wrapper,
                    662:                    stdio_tls_write_wrapper, NULL, NULL);
1.61      deraadt   663:        } else {
1.166     procter   664:                fin = fdopen(fd, "r+");
                    665:                fd = -1;
1.61      deraadt   666:        }
1.154     deraadt   667: #else /* !NOSSL */
1.166     procter   668:        fin = fdopen(fd, "r+");
                    669:        fd = -1;
1.154     deraadt   670: #endif /* !NOSSL */
1.155     deraadt   671:
1.157     deraadt   672: #ifdef SMALL
                    673:        if (lastfile) {
                    674:                if (pipeout) {
                    675:                        if (pledge("stdio rpath inet dns tty",  NULL) == -1)
                    676:                                err(1, "pledge");
                    677:                } else {
                    678:                        if (pledge("stdio rpath wpath cpath inet dns tty", NULL) == -1)
                    679:                                err(1, "pledge");
                    680:                }
                    681:        }
                    682: #endif
                    683:
1.155     deraadt   684:        if (connect_timeout) {
                    685:                signal(SIGALRM, SIG_DFL);
                    686:                alarmtimer(0);
                    687:        }
1.40      fgsch     688:
1.1       millert   689:        /*
1.40      fgsch     690:         * Construct and send the request. Proxy requests don't want leading /.
1.1       millert   691:         */
1.154     deraadt   692: #ifndef NOSSL
1.74      pyr       693:        cookie_get(host, path, ishttpsurl, &buf);
1.154     deraadt   694: #endif /* !NOSSL */
1.95      martynas  695:
                    696:        epath = url_encode(path);
1.62      ray       697:        if (proxyurl) {
1.151     millert   698:                if (verbose) {
                    699:                        fprintf(ttyout, "Requesting %s (via %s)\n",
                    700:                            origline, proxyurl);
                    701:                }
1.32      itojun    702:                /*
                    703:                 * Host: directive must use the destination host address for
1.136     bluhm     704:                 * the original URI (path).
1.32      itojun    705:                 */
1.123     guenther  706:                if (credentials)
1.184     jca       707:                        ftp_printf(fin, "GET %s HTTP/1.1\r\n"
1.178     jca       708:                            "Connection: close\r\n"
1.136     bluhm     709:                            "Proxy-Authorization: Basic %s\r\n"
                    710:                            "Host: %s\r\n%s%s\r\n\r\n",
                    711:                            epath, credentials,
                    712:                            proxyhost, buf ? buf : "", httpuseragent);
1.73      drahn     713:                else
1.184     jca       714:                        ftp_printf(fin, "GET %s HTTP/1.1\r\n"
1.178     jca       715:                            "Connection: close\r\n"
1.136     bluhm     716:                            "Host: %s\r\n%s%s\r\n\r\n",
                    717:                            epath, proxyhost, buf ? buf : "", httpuseragent);
1.28      itojun    718:        } else {
1.151     millert   719:                if (verbose)
                    720:                        fprintf(ttyout, "Requesting %s\n", origline);
1.90      martynas  721: #ifndef SMALL
                    722:                if (resume) {
                    723:                        struct stat stbuf;
                    724:
                    725:                        if (stat(savefile, &stbuf) == 0)
                    726:                                restart_point = stbuf.st_size;
                    727:                        else
                    728:                                restart_point = 0;
                    729:                }
1.154     deraadt   730: #endif /* SMALL */
                    731: #ifndef NOSSL
1.123     guenther  732:                if (credentials) {
1.184     jca       733:                        ftp_printf(fin,
1.178     jca       734:                            "GET /%s HTTP/1.1\r\n"
                    735:                            "Connection: close\r\n"
                    736:                            "Authorization: Basic %s\r\n"
                    737:                            "Host: ", epath, credentials);
1.123     guenther  738:                        free(credentials);
                    739:                        credentials = NULL;
1.106     haesbaer  740:                } else
1.154     deraadt   741: #endif /* NOSSL */
1.184     jca       742:                        ftp_printf(fin,
1.178     jca       743:                            "GET /%s HTTP/1.1\r\n"
                    744:                            "Connection: close\r\n"
                    745:                            "Host: ", epath);
1.136     bluhm     746:                if (proxyhost) {
1.184     jca       747:                        ftp_printf(fin, "%s", proxyhost);
1.136     bluhm     748:                        port = NULL;
                    749:                } else if (strchr(host, ':')) {
1.55      fgsch     750:                        /*
                    751:                         * strip off scoped address portion, since it's
                    752:                         * local to node
                    753:                         */
1.32      itojun    754:                        h = strdup(host);
                    755:                        if (h == NULL)
                    756:                                errx(1, "Can't allocate memory.");
                    757:                        if ((p = strchr(h, '%')) != NULL)
                    758:                                *p = '\0';
1.184     jca       759:                        ftp_printf(fin, "[%s]", h);
1.32      itojun    760:                        free(h);
1.55      fgsch     761:                } else
1.184     jca       762:                        ftp_printf(fin, "%s", host);
1.55      fgsch     763:
                    764:                /*
                    765:                 * Send port number only if it's specified and does not equal
                    766:                 * 80. Some broken HTTP servers get confused if you explicitly
                    767:                 * send them the port number.
                    768:                 */
1.154     deraadt   769: #ifndef NOSSL
1.61      deraadt   770:                if (port && strcmp(port, (ishttpsurl ? "443" : "80")) != 0)
1.184     jca       771:                        ftp_printf(fin, ":%s", port);
1.90      martynas  772:                if (restart_point)
1.184     jca       773:                        ftp_printf(fin, "\r\nRange: bytes=%lld-",
1.75      martynas  774:                                (long long)restart_point);
1.154     deraadt   775: #else /* !NOSSL */
1.55      fgsch     776:                if (port && strcmp(port, "80") != 0)
1.184     jca       777:                        ftp_printf(fin, ":%s", port);
1.154     deraadt   778: #endif /* !NOSSL */
1.184     jca       779:                ftp_printf(fin, "\r\n%s%s\r\n\r\n",
1.124     lteo      780:                    buf ? buf : "", httpuseragent);
1.28      itojun    781:        }
1.95      martynas  782:        free(epath);
1.74      pyr       783:
1.154     deraadt   784: #ifndef NOSSL
1.74      pyr       785:        free(buf);
1.156     tb        786: #endif /* !NOSSL */
1.74      pyr       787:        buf = NULL;
                    788:
1.176     jca       789:        if (fflush(fin) == EOF) {
                    790:                warnx("Writing HTTP request: %s", sockerror(tls));
1.6       millert   791:                goto cleanup_url_get;
1.1       millert   792:        }
1.176     jca       793:        if ((buf = ftp_readline(fin, &len)) == NULL) {
                    794:                warnx("Receiving HTTP reply: %s", sockerror(tls));
1.40      fgsch     795:                goto cleanup_url_get;
1.1       millert   796:        }
1.40      fgsch     797:
                    798:        while (len > 0 && (buf[len-1] == '\r' || buf[len-1] == '\n'))
                    799:                buf[--len] = '\0';
1.80      martynas  800: #ifndef SMALL
1.40      fgsch     801:        if (debug)
                    802:                fprintf(ttyout, "received '%s'\n", buf);
1.80      martynas  803: #endif /* !SMALL */
1.40      fgsch     804:
1.1       millert   805:        cp = strchr(buf, ' ');
                    806:        if (cp == NULL)
                    807:                goto improper;
                    808:        else
                    809:                cp++;
1.69      jsg       810:
                    811:        strlcpy(ststr, cp, sizeof(ststr));
1.171     jca       812:        status = strtonum(ststr, 200, 503, &errstr);
1.69      jsg       813:        if (errstr) {
1.175     deraadt   814:                strnvis(gerror, cp, sizeof gerror, VIS_SAFE);
                    815:                warnx("Error retrieving %s: %s", origline, gerror);
1.69      jsg       816:                goto cleanup_url_get;
                    817:        }
                    818:
                    819:        switch (status) {
                    820:        case 200:       /* OK */
1.75      martynas  821: #ifndef SMALL
1.109     sthen     822:                /*
1.98      phessler  823:                 * When we request a partial file, and we receive an HTTP 200
                    824:                 * it is a good indication that the server doesn't support
                    825:                 * range requests, and is about to send us the entire file.
                    826:                 * If the restart_point == 0, then we are not actually
                    827:                 * requesting a partial file, and an HTTP 200 is appropriate.
                    828:                 */
                    829:                if (resume && restart_point != 0) {
                    830:                        warnx("Server does not support resume.");
                    831:                        restart_point = resume = 0;
                    832:                }
1.101     halex     833:                /* FALLTHROUGH */
1.75      martynas  834:        case 206:       /* Partial Content */
1.91      halex     835: #endif /* !SMALL */
1.69      jsg       836:                break;
                    837:        case 301:       /* Moved Permanently */
                    838:        case 302:       /* Found */
                    839:        case 303:       /* See Other */
                    840:        case 307:       /* Temporary Redirect */
1.40      fgsch     841:                isredirect++;
1.54      fgsch     842:                if (redirect_loop++ > 10) {
                    843:                        warnx("Too many redirections requested");
                    844:                        goto cleanup_url_get;
                    845:                }
1.69      jsg       846:                break;
1.75      martynas  847: #ifndef SMALL
                    848:        case 416:       /* Requested Range Not Satisfiable */
                    849:                warnx("File is already fully retrieved.");
                    850:                goto cleanup_url_get;
1.78      martynas  851: #endif /* !SMALL */
1.171     jca       852:        case 503:
1.172     jca       853:                isunavail = 1;
                    854:                break;
1.69      jsg       855:        default:
1.175     deraadt   856:                strnvis(gerror, cp, sizeof gerror, VIS_SAFE);
                    857:                warnx("Error retrieving %s: %s", origline, gerror);
1.6       millert   858:                goto cleanup_url_get;
1.1       millert   859:        }
                    860:
                    861:        /*
                    862:         * Read the rest of the header.
                    863:         */
1.40      fgsch     864:        free(buf);
                    865:        filesize = -1;
                    866:
1.62      ray       867:        for (;;) {
1.176     jca       868:                if ((buf = ftp_readline(fin, &len)) == NULL) {
                    869:                        warnx("Receiving HTTP reply: %s", sockerror(tls));
1.40      fgsch     870:                        goto cleanup_url_get;
                    871:                }
1.61      deraadt   872:
1.40      fgsch     873:                while (len > 0 && (buf[len-1] == '\r' || buf[len-1] == '\n'))
                    874:                        buf[--len] = '\0';
                    875:                if (len == 0)
1.1       millert   876:                        break;
1.80      martynas  877: #ifndef SMALL
1.40      fgsch     878:                if (debug)
                    879:                        fprintf(ttyout, "received '%s'\n", buf);
1.80      martynas  880: #endif /* !SMALL */
1.1       millert   881:
1.40      fgsch     882:                /* Look for some headers */
                    883:                cp = buf;
1.1       millert   884: #define CONTENTLEN "Content-Length: "
1.40      fgsch     885:                if (strncasecmp(cp, CONTENTLEN, sizeof(CONTENTLEN) - 1) == 0) {
1.104     sthen     886:                        size_t s;
1.40      fgsch     887:                        cp += sizeof(CONTENTLEN) - 1;
1.111     deraadt   888:                        if ((s = strcspn(cp, " \t")))
1.104     sthen     889:                                *(cp+s) = 0;
1.58      grunk     890:                        filesize = strtonum(cp, 0, LLONG_MAX, &errstr);
                    891:                        if (errstr != NULL)
1.40      fgsch     892:                                goto improper;
1.75      martynas  893: #ifndef SMALL
1.90      martynas  894:                        if (restart_point)
1.75      martynas  895:                                filesize += restart_point;
1.78      martynas  896: #endif /* !SMALL */
1.40      fgsch     897: #define LOCATION "Location: "
                    898:                } else if (isredirect &&
                    899:                    strncasecmp(cp, LOCATION, sizeof(LOCATION) - 1) == 0) {
                    900:                        cp += sizeof(LOCATION) - 1;
1.144     sthen     901:                        /*
                    902:                         * If there is a colon before the first slash, this URI
                    903:                         * is not relative. RFC 3986 4.2
                    904:                         */
                    905:                        if (cp[strcspn(cp, ":/")] != ':') {
1.102     halex     906: #ifdef SMALL
                    907:                                errx(1, "Relative redirect not supported");
                    908: #else /* SMALL */
1.144     sthen     909:                                /* XXX doesn't handle protocol-relative URIs */
1.102     halex     910:                                if (*cp == '/') {
                    911:                                        locbase = NULL;
                    912:                                        cp++;
                    913:                                } else {
                    914:                                        locbase = strdup(path);
                    915:                                        if (locbase == NULL)
                    916:                                                errx(1, "Can't allocate memory"
                    917:                                                    " for location base");
                    918:                                        loctail = strchr(locbase, '#');
                    919:                                        if (loctail != NULL)
                    920:                                                *loctail = '\0';
                    921:                                        loctail = strchr(locbase, '?');
                    922:                                        if (loctail != NULL)
                    923:                                                *loctail = '\0';
                    924:                                        loctail = strrchr(locbase, '/');
                    925:                                        if (loctail == NULL) {
                    926:                                                free(locbase);
                    927:                                                locbase = NULL;
                    928:                                        } else
                    929:                                                loctail[1] = '\0';
                    930:                                }
                    931:                                /* Contruct URL from relative redirect */
                    932:                                if (asprintf(&redirurl, "%s%s%s%s/%s%s",
                    933:                                    scheme, full_host,
                    934:                                    portnum ? ":" : "",
                    935:                                    portnum ? portnum : "",
                    936:                                    locbase ? locbase : "",
                    937:                                    cp) == -1)
                    938:                                        errx(1, "Cannot build "
                    939:                                            "redirect URL");
                    940:                                free(locbase);
                    941: #endif /* SMALL */
                    942:                        } else if ((redirurl = strdup(cp)) == NULL)
                    943:                                errx(1, "Cannot allocate memory for URL");
                    944:                        loctail = strchr(redirurl, '#');
                    945:                        if (loctail != NULL)
                    946:                                *loctail = '\0';
1.40      fgsch     947:                        if (verbose)
1.102     halex     948:                                fprintf(ttyout, "Redirected to %s\n", redirurl);
1.173     jca       949:                        ftp_close(&fin, &tls, &fd);
1.157     deraadt   950:                        rval = url_get(redirurl, proxyenv, savefile, lastfile);
1.102     halex     951:                        free(redirurl);
                    952:                        goto cleanup_url_get;
1.172     jca       953: #define RETRYAFTER "Retry-After: "
                    954:                } else if (isunavail &&
                    955:                    strncasecmp(cp, RETRYAFTER, sizeof(RETRYAFTER) - 1) == 0) {
                    956:                        size_t s;
                    957:                        cp += sizeof(RETRYAFTER) - 1;
                    958:                        if ((s = strcspn(cp, " \t")))
                    959:                                cp[s] = '\0';
                    960:                        retryafter = strtonum(cp, 0, 0, &errstr);
                    961:                        if (errstr != NULL)
                    962:                                retryafter = -1;
1.178     jca       963: #define TRANSFER_ENCODING "Transfer-Encoding: "
                    964:                } else if (strncasecmp(cp, TRANSFER_ENCODING,
                    965:                            sizeof(TRANSFER_ENCODING) - 1) == 0) {
                    966:                        cp += sizeof(TRANSFER_ENCODING) - 1;
                    967:                        cp[strcspn(cp, " \t")] = '\0';
                    968:                        if (strcasecmp(cp, "chunked") == 0)
                    969:                                chunked = 1;
1.40      fgsch     970:                }
1.108     tobias    971:                free(buf);
1.172     jca       972:        }
                    973:
1.178     jca       974:        /* Content-Length should be ignored for Transfer-Encoding: chunked */
                    975:        if (chunked)
                    976:                filesize = -1;
                    977:
1.172     jca       978:        if (isunavail) {
                    979:                if (retried || retryafter != 0)
1.175     deraadt   980:                        warnx("Error retrieving %s: 503 Service Unavailable",
                    981:                            origline);
1.172     jca       982:                else {
                    983:                        if (verbose)
                    984:                                fprintf(ttyout, "Retrying %s\n", origline);
                    985:                        retried = 1;
1.174     jca       986:                        ftp_close(&fin, &tls, &fd);
1.172     jca       987:                        rval = url_get(origline, proxyenv, savefile, lastfile);
                    988:                }
                    989:                goto cleanup_url_get;
1.1       millert   990:        }
                    991:
1.17      millert   992:        /* Open the output file.  */
1.100     halex     993:        if (!pipeout) {
1.75      martynas  994: #ifndef SMALL
                    995:                if (resume)
1.83      martynas  996:                        out = open(savefile, O_CREAT | O_WRONLY | O_APPEND,
                    997:                                0666);
1.75      martynas  998:                else
1.78      martynas  999: #endif /* !SMALL */
1.75      martynas 1000:                        out = open(savefile, O_CREAT | O_WRONLY | O_TRUNC,
                   1001:                                0666);
1.170     deraadt  1002:                if (out == -1) {
1.10      deraadt  1003:                        warn("Can't open %s", savefile);
                   1004:                        goto cleanup_url_get;
                   1005:                }
1.157     deraadt  1006:        } else {
1.17      millert  1007:                out = fileno(stdout);
1.157     deraadt  1008: #ifdef SMALL
                   1009:                if (lastfile) {
                   1010:                        if (pledge("stdio tty", NULL) == -1)
                   1011:                                err(1, "pledge");
                   1012:                }
                   1013: #endif
                   1014:        }
1.1       millert  1015:
                   1016:        /* Trap signals */
                   1017:        oldintr = NULL;
1.97      martynas 1018:        oldinti = NULL;
1.1       millert  1019:        if (setjmp(httpabort)) {
                   1020:                if (oldintr)
1.2       millert  1021:                        (void)signal(SIGINT, oldintr);
1.97      martynas 1022:                if (oldinti)
                   1023:                        (void)signal(SIGINFO, oldinti);
1.6       millert  1024:                goto cleanup_url_get;
1.1       millert  1025:        }
                   1026:        oldintr = signal(SIGINT, aborthttp);
                   1027:
                   1028:        bytes = 0;
                   1029:        hashbytes = mark;
1.84      martynas 1030:        progressmeter(-1, path);
1.43      millert  1031:
                   1032:        free(buf);
1.1       millert  1033:
                   1034:        /* Finally, suck down the file. */
1.113     tedu     1035:        if ((buf = malloc(buflen)) == NULL)
1.47      deraadt  1036:                errx(1, "Can't allocate memory for transfer buffer");
1.97      martynas 1037:        oldinti = signal(SIGINFO, psummary);
1.178     jca      1038:        if (chunked) {
1.182     jca      1039:                error = save_chunked(fin, tls, out, buf, buflen);
                   1040:                signal(SIGINFO, oldinti);
                   1041:                if (error == -1)
1.178     jca      1042:                        goto cleanup_url_get;
                   1043:        } else {
                   1044:                i = 0;
                   1045:                len = 1;
                   1046:                while (len > 0) {
                   1047:                        len = fread(buf, 1, buflen, fin);
                   1048:                        bytes += len;
                   1049:                        for (cp = buf, wlen = len; wlen > 0; wlen -= i, cp += i) {
                   1050:                                if ((i = write(out, cp, wlen)) == -1) {
                   1051:                                        warn("Writing %s", savefile);
                   1052:                                        signal(SIGINFO, oldinti);
                   1053:                                        goto cleanup_url_get;
1.179     deraadt  1054:                                } else if (i == 0)
1.178     jca      1055:                                        break;
                   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.178     jca      1065:                signal(SIGINFO, oldinti);
                   1066:                if (hash && !progress && bytes > 0) {
                   1067:                        if (bytes < mark)
1.10      deraadt  1068:                                (void)putc('#', ttyout);
1.178     jca      1069:                        (void)putc('\n', ttyout);
1.10      deraadt  1070:                        (void)fflush(ttyout);
1.1       millert  1071:                }
1.178     jca      1072:                if (len != 0) {
                   1073:                        warnx("Reading from socket: %s", sockerror(tls));
                   1074:                        goto cleanup_url_get;
                   1075:                }
1.1       millert  1076:        }
1.84      martynas 1077:        progressmeter(1, NULL);
1.75      martynas 1078:        if (
                   1079: #ifndef SMALL
                   1080:                !resume &&
1.78      martynas 1081: #endif /* !SMALL */
1.75      martynas 1082:                filesize != -1 && len == 0 && bytes != filesize) {
1.24      deraadt  1083:                if (verbose)
                   1084:                        fputs("Read short file.\n", ttyout);
                   1085:                goto cleanup_url_get;
                   1086:        }
                   1087:
1.1       millert  1088:        if (verbose)
1.97      martynas 1089:                ptransfer(0);
1.2       millert  1090:        (void)signal(SIGINT, oldintr);
1.1       millert  1091:
1.40      fgsch    1092:        rval = 0;
                   1093:        goto cleanup_url_get;
1.1       millert  1094:
1.14      millert  1095: noftpautologin:
                   1096:        warnx(
                   1097:            "Auto-login using ftp URLs isn't supported when using $ftp_proxy");
                   1098:        goto cleanup_url_get;
                   1099:
1.1       millert  1100: improper:
1.8       millert  1101:        warnx("Improper response from %s", host);
1.14      millert  1102:
1.6       millert  1103: cleanup_url_get:
1.181     jca      1104: #ifndef SMALL
                   1105:        free(full_host);
                   1106: #endif /* !SMALL */
1.154     deraadt  1107: #ifndef NOSSL
1.128     jca      1108:        free(sslhost);
1.154     deraadt  1109: #endif /* !NOSSL */
1.173     jca      1110:        ftp_close(&fin, &tls, &fd);
1.162     sthen    1111:        if (out >= 0 && out != fileno(stdout))
                   1112:                close(out);
1.67      steven   1113:        free(buf);
1.136     bluhm    1114:        free(proxyhost);
1.67      steven   1115:        free(proxyurl);
1.62      ray      1116:        free(newline);
1.123     guenther 1117:        free(credentials);
1.40      fgsch    1118:        return (rval);
1.178     jca      1119: }
                   1120:
                   1121: static int
                   1122: save_chunked(FILE *fin, struct tls *tls, int out, char *buf, size_t buflen)
                   1123: {
                   1124:
                   1125:        char                    *header, *end, *cp;
                   1126:        unsigned long           chunksize;
                   1127:        size_t                  hlen, rlen, wlen;
                   1128:        ssize_t                 written;
                   1129:        char                    cr, lf;
                   1130:
                   1131:        for (;;) {
                   1132:                header = ftp_readline(fin, &hlen);
                   1133:                if (header == NULL)
                   1134:                        break;
                   1135:                /* strip CRLF and any optional chunk extension */
                   1136:                header[strcspn(header, ";\r\n")] = '\0';
                   1137:                errno = 0;
                   1138:                chunksize = strtoul(header, &end, 16);
                   1139:                if (errno || header[0] == '\0' || *end != '\0' ||
                   1140:                    chunksize > INT_MAX) {
                   1141:                        warnx("Invalid chunk size '%s'", header);
                   1142:                        free(header);
                   1143:                        return -1;
                   1144:                }
                   1145:                free(header);
                   1146:
                   1147:                if (chunksize == 0) {
                   1148:                        /* We're done.  Ignore optional trailer. */
                   1149:                        return 0;
                   1150:                }
                   1151:
                   1152:                for (written = 0; chunksize != 0; chunksize -= rlen) {
                   1153:                        rlen = (chunksize < buflen) ? chunksize : buflen;
                   1154:                        rlen = fread(buf, 1, rlen, fin);
                   1155:                        if (rlen == 0)
                   1156:                                break;
                   1157:                        bytes += rlen;
                   1158:                        for (cp = buf, wlen = rlen; wlen > 0;
1.179     deraadt  1159:                            wlen -= written, cp += written) {
1.178     jca      1160:                                if ((written = write(out, cp, wlen)) == -1) {
                   1161:                                        warn("Writing output file");
                   1162:                                        return -1;
                   1163:                                }
                   1164:                        }
                   1165:                }
                   1166:
                   1167:                if (rlen == 0 ||
                   1168:                    fread(&cr, 1, 1, fin) != 1 ||
                   1169:                    fread(&lf, 1, 1, fin) != 1)
                   1170:                        break;
                   1171:
                   1172:                if (cr != '\r' || lf != '\n') {
                   1173:                        warnx("Invalid chunked encoding");
                   1174:                        return -1;
                   1175:                }
                   1176:        }
                   1177:
                   1178:        if (ferror(fin))
                   1179:                warnx("Error while reading from socket: %s", sockerror(tls));
                   1180:        else
                   1181:                warnx("Invalid chunked encoding: short read");
                   1182:
                   1183:        return -1;
1.1       millert  1184: }
                   1185:
                   1186: /*
                   1187:  * Abort a http retrieval
                   1188:  */
1.51      deraadt  1189: /* ARGSUSED */
1.177     jca      1190: static void
1.51      deraadt  1191: aborthttp(int signo)
1.1       millert  1192: {
                   1193:
                   1194:        alarmtimer(0);
1.10      deraadt  1195:        fputs("\nhttp fetch aborted.\n", ttyout);
                   1196:        (void)fflush(ttyout);
1.1       millert  1197:        longjmp(httpabort, 1);
                   1198: }
                   1199:
                   1200: /*
1.22      deraadt  1201:  * Abort a http retrieval
                   1202:  */
1.51      deraadt  1203: /* ARGSUSED */
1.177     jca      1204: static void
1.51      deraadt  1205: abortfile(int signo)
1.22      deraadt  1206: {
                   1207:
                   1208:        alarmtimer(0);
                   1209:        fputs("\nfile fetch aborted.\n", ttyout);
                   1210:        (void)fflush(ttyout);
                   1211:        longjmp(httpabort, 1);
                   1212: }
                   1213:
                   1214: /*
1.1       millert  1215:  * Retrieve multiple files from the command line, transferring
                   1216:  * files of the form "host:path", "ftp://host/path" using the
                   1217:  * ftp protocol, and files of the form "http://host/path" using
                   1218:  * the http protocol.
1.2       millert  1219:  * If path has a trailing "/", then return (-1);
1.1       millert  1220:  * the path will be cd-ed into and the connection remains open,
                   1221:  * and the function will return -1 (to indicate the connection
                   1222:  * is alive).
                   1223:  * If an error occurs the return value will be the offset+1 in
                   1224:  * argv[] of the file that caused a problem (i.e, argv[x]
                   1225:  * returns x+1)
                   1226:  * Otherwise, 0 is returned if all files retrieved successfully.
                   1227:  */
                   1228: int
1.50      deraadt  1229: auto_fetch(int argc, char *argv[], char *outfile)
1.1       millert  1230: {
                   1231:        char *xargv[5];
1.62      ray      1232:        char *cp, *url, *host, *dir, *file, *portnum;
                   1233:        char *username, *pass, *pathstart;
1.6       millert  1234:        char *ftpproxy, *httpproxy;
1.157     deraadt  1235:        int rval, xargc, lastfile;
1.14      millert  1236:        volatile int argpos;
1.49      krw      1237:        int dirhasglob, filehasglob, oautologin;
1.137     deraadt  1238:        char rempath[PATH_MAX];
1.1       millert  1239:
                   1240:        argpos = 0;
                   1241:
                   1242:        if (setjmp(toplevel)) {
                   1243:                if (connected)
                   1244:                        disconnect(0, NULL);
1.2       millert  1245:                return (argpos + 1);
1.1       millert  1246:        }
1.3       millert  1247:        (void)signal(SIGINT, (sig_t)intr);
                   1248:        (void)signal(SIGPIPE, (sig_t)lostpeer);
1.1       millert  1249:
1.45      millert  1250:        if ((ftpproxy = getenv(FTP_PROXY)) != NULL && *ftpproxy == '\0')
                   1251:                ftpproxy = NULL;
                   1252:        if ((httpproxy = getenv(HTTP_PROXY)) != NULL && *httpproxy == '\0')
                   1253:                httpproxy = NULL;
1.6       millert  1254:
1.1       millert  1255:        /*
                   1256:         * Loop through as long as there's files to fetch.
                   1257:         */
1.123     guenther 1258:        username = pass = NULL;
1.62      ray      1259:        for (rval = 0; (rval == 0) && (argpos < argc); free(url), argpos++) {
1.1       millert  1260:                if (strchr(argv[argpos], ':') == NULL)
                   1261:                        break;
1.123     guenther 1262:
                   1263:                free(username);
                   1264:                free(pass);
1.62      ray      1265:                host = dir = file = portnum = username = pass = NULL;
1.1       millert  1266:
1.157     deraadt  1267:                lastfile = (argv[argpos+1] == NULL);
                   1268:
1.1       millert  1269:                /*
                   1270:                 * We muck with the string, so we make a copy.
                   1271:                 */
1.62      ray      1272:                url = strdup(argv[argpos]);
                   1273:                if (url == NULL)
1.1       millert  1274:                        errx(1, "Can't allocate memory for auto-fetch.");
                   1275:
1.186   ! jca      1276:                if (strncasecmp(url, FILE_URL, sizeof(FILE_URL) - 1) == 0) {
        !          1277:                        if (file_get(url + sizeof(FILE_URL) - 1, outfile) == -1)
        !          1278:                                rval = argpos + 1;
        !          1279:                        continue;
        !          1280:                }
        !          1281:
1.1       millert  1282:                /*
1.186   ! jca      1283:                 * Try HTTP URL-style arguments next.
1.1       millert  1284:                 */
1.62      ray      1285:                if (strncasecmp(url, HTTP_URL, sizeof(HTTP_URL) - 1) == 0 ||
1.186   ! jca      1286:                    strncasecmp(url, HTTPS_URL, sizeof(HTTPS_URL) -1) == 0) {
1.54      fgsch    1287:                        redirect_loop = 0;
1.171     jca      1288:                        retried = 0;
1.157     deraadt  1289:                        if (url_get(url, httpproxy, outfile, lastfile) == -1)
1.1       millert  1290:                                rval = argpos + 1;
                   1291:                        continue;
                   1292:                }
                   1293:
                   1294:                /*
1.6       millert  1295:                 * Try FTP URL-style arguments next. If ftpproxy is
                   1296:                 * set, use url_get() instead of standard ftp.
                   1297:                 * Finally, try host:file.
1.1       millert  1298:                 */
1.62      ray      1299:                host = url;
                   1300:                if (strncasecmp(url, FTP_URL, sizeof(FTP_URL) - 1) == 0) {
1.37      heko     1301:                        char *passend, *passagain, *userend;
1.31      itojun   1302:
1.6       millert  1303:                        if (ftpproxy) {
1.157     deraadt  1304:                                if (url_get(url, ftpproxy, outfile, lastfile) == -1)
1.6       millert  1305:                                        rval = argpos + 1;
                   1306:                                continue;
                   1307:                        }
1.1       millert  1308:                        host += sizeof(FTP_URL) - 1;
1.8       millert  1309:                        dir = strchr(host, '/');
1.1       millert  1310:
1.8       millert  1311:                        /* Look for [user:pass@]host[:port] */
1.31      itojun   1312:
                   1313:                        /* check if we have "user:pass@" */
1.37      heko     1314:                        userend = strchr(host, ':');
1.31      itojun   1315:                        passend = strchr(host, '@');
                   1316:                        if (passend && userend && userend < passend &&
                   1317:                            (!dir || passend < dir)) {
1.62      ray      1318:                                username = host;
1.31      itojun   1319:                                pass = userend + 1;
                   1320:                                host = passend + 1;
                   1321:                                *userend = *passend = '\0';
1.37      heko     1322:                                passagain = strchr(host, '@');
1.42      deraadt  1323:                                if (strchr(pass, '@') != NULL ||
1.37      heko     1324:                                    (passagain != NULL && passagain < dir)) {
                   1325:                                        warnx(at_encoding_warning);
1.123     guenther 1326:                                        username = pass = NULL;
1.37      heko     1327:                                        goto bad_ftp_url;
1.42      deraadt  1328:                                }
1.31      itojun   1329:
1.77      martynas 1330:                                if (EMPTYSTRING(username)) {
1.11      millert  1331: bad_ftp_url:
1.31      itojun   1332:                                        warnx("Invalid URL: %s", argv[argpos]);
                   1333:                                        rval = argpos + 1;
1.123     guenther 1334:                                        username = pass = NULL;
1.31      itojun   1335:                                        continue;
                   1336:                                }
1.62      ray      1337:                                username = urldecode(username);
1.37      heko     1338:                                pass = urldecode(pass);
1.8       millert  1339:                        }
1.31      itojun   1340:
                   1341:                        /* check [host]:port, or [host] */
                   1342:                        if (host[0] == '[') {
                   1343:                                cp = strchr(host, ']');
                   1344:                                if (cp && (!dir || cp < dir)) {
                   1345:                                        if (cp + 1 == dir || cp[1] == ':') {
                   1346:                                                host++;
                   1347:                                                *cp++ = '\0';
                   1348:                                        } else
                   1349:                                                cp = NULL;
                   1350:                                } else
                   1351:                                        cp = host;
1.25      itojun   1352:                        } else
                   1353:                                cp = host;
1.31      itojun   1354:
                   1355:                        /* split off host[:port] if there is */
                   1356:                        if (cp) {
                   1357:                                portnum = strchr(cp, ':');
1.52      henning  1358:                                pathstart = strchr(cp, '/');
                   1359:                                /* : in path is not a port # indicator */
                   1360:                                if (portnum && pathstart &&
                   1361:                                    pathstart < portnum)
                   1362:                                        portnum = NULL;
                   1363:
1.31      itojun   1364:                                if (!portnum)
                   1365:                                        ;
                   1366:                                else {
                   1367:                                        if (!dir)
                   1368:                                                ;
                   1369:                                        else if (portnum + 1 < dir) {
                   1370:                                                *portnum++ = '\0';
                   1371:                                                /*
                   1372:                                                 * XXX should check if portnum
                   1373:                                                 * is decimal number
                   1374:                                                 */
                   1375:                                        } else {
                   1376:                                                /* empty portnum */
                   1377:                                                goto bad_ftp_url;
                   1378:                                        }
                   1379:                                }
                   1380:                        } else
                   1381:                                portnum = NULL;
1.8       millert  1382:                } else {                        /* classic style `host:file' */
                   1383:                        dir = strchr(host, ':');
                   1384:                }
1.1       millert  1385:                if (EMPTYSTRING(host)) {
                   1386:                        rval = argpos + 1;
                   1387:                        continue;
                   1388:                }
                   1389:
                   1390:                /*
1.9       millert  1391:                 * If dir is NULL, the file wasn't specified
1.1       millert  1392:                 * (URL looked something like ftp://host)
                   1393:                 */
1.8       millert  1394:                if (dir != NULL)
                   1395:                        *dir++ = '\0';
1.1       millert  1396:
                   1397:                /*
                   1398:                 * Extract the file and (if present) directory name.
                   1399:                 */
1.42      deraadt  1400:                if (!EMPTYSTRING(dir)) {
1.8       millert  1401:                        cp = strrchr(dir, '/');
1.1       millert  1402:                        if (cp != NULL) {
                   1403:                                *cp++ = '\0';
                   1404:                                file = cp;
                   1405:                        } else {
                   1406:                                file = dir;
                   1407:                                dir = NULL;
                   1408:                        }
                   1409:                }
1.80      martynas 1410: #ifndef SMALL
1.1       millert  1411:                if (debug)
1.42      deraadt  1412:                        fprintf(ttyout,
                   1413:                            "user %s:%s host %s port %s dir %s file %s\n",
1.76      martynas 1414:                            username, pass ? "XXXX" : NULL, host, portnum,
                   1415:                            dir, file);
1.80      martynas 1416: #endif /* !SMALL */
1.1       millert  1417:
                   1418:                /*
1.49      krw      1419:                 * Set up the connection.
1.1       millert  1420:                 */
1.49      krw      1421:                if (connected)
                   1422:                        disconnect(0, NULL);
                   1423:                xargv[0] = __progname;
                   1424:                xargv[1] = host;
1.8       millert  1425:                xargv[2] = NULL;
1.49      krw      1426:                xargc = 2;
                   1427:                if (!EMPTYSTRING(portnum)) {
                   1428:                        xargv[2] = portnum;
                   1429:                        xargv[3] = NULL;
                   1430:                        xargc = 3;
                   1431:                }
                   1432:                oautologin = autologin;
1.88      martynas 1433:                if (username == NULL)
1.89      halex    1434:                        anonftp = 1;
                   1435:                else {
                   1436:                        anonftp = 0;
1.49      krw      1437:                        autologin = 0;
1.89      halex    1438:                }
1.49      krw      1439:                setpeer(xargc, xargv);
                   1440:                autologin = oautologin;
1.87      martynas 1441:                if (connected == 0 ||
                   1442:                    (connected == 1 && autologin && (username == NULL ||
                   1443:                    !ftp_login(host, username, pass)))) {
1.49      krw      1444:                        warnx("Can't connect or login to host `%s'", host);
1.8       millert  1445:                        rval = argpos + 1;
                   1446:                        continue;
1.1       millert  1447:                }
1.49      krw      1448:
                   1449:                /* Always use binary transfers. */
                   1450:                setbinary(0, NULL);
1.1       millert  1451:
1.4       millert  1452:                dirhasglob = filehasglob = 0;
                   1453:                if (doglob) {
1.42      deraadt  1454:                        if (!EMPTYSTRING(dir) &&
1.4       millert  1455:                            strpbrk(dir, "*?[]{}") != NULL)
                   1456:                                dirhasglob = 1;
1.42      deraadt  1457:                        if (!EMPTYSTRING(file) &&
1.4       millert  1458:                            strpbrk(file, "*?[]{}") != NULL)
                   1459:                                filehasglob = 1;
                   1460:                }
                   1461:
1.1       millert  1462:                /* Change directories, if necessary. */
1.42      deraadt  1463:                if (!EMPTYSTRING(dir) && !dirhasglob) {
1.1       millert  1464:                        xargv[0] = "cd";
                   1465:                        xargv[1] = dir;
                   1466:                        xargv[2] = NULL;
                   1467:                        cd(2, xargv);
1.42      deraadt  1468:                        if (!dirchange) {
1.1       millert  1469:                                rval = argpos + 1;
                   1470:                                continue;
                   1471:                        }
                   1472:                }
                   1473:
                   1474:                if (EMPTYSTRING(file)) {
1.86      martynas 1475: #ifndef SMALL
1.1       millert  1476:                        rval = -1;
1.86      martynas 1477: #else /* !SMALL */
                   1478:                        recvrequest("NLST", "-", NULL, "w", 0, 0);
                   1479:                        rval = 0;
                   1480: #endif /* !SMALL */
1.1       millert  1481:                        continue;
                   1482:                }
                   1483:
1.21      marc     1484:                if (verbose)
1.10      deraadt  1485:                        fprintf(ttyout, "Retrieving %s/%s\n", dir ? dir : "", file);
1.1       millert  1486:
1.4       millert  1487:                if (dirhasglob) {
                   1488:                        snprintf(rempath, sizeof(rempath), "%s/%s", dir, file);
                   1489:                        file = rempath;
                   1490:                }
                   1491:
                   1492:                /* Fetch the file(s). */
1.10      deraadt  1493:                xargc = 2;
1.1       millert  1494:                xargv[0] = "get";
                   1495:                xargv[1] = file;
                   1496:                xargv[2] = NULL;
1.4       millert  1497:                if (dirhasglob || filehasglob) {
                   1498:                        int ointeractive;
                   1499:
                   1500:                        ointeractive = interactive;
                   1501:                        interactive = 0;
                   1502:                        xargv[0] = "mget";
1.78      martynas 1503: #ifndef SMALL
                   1504:                        if (resume) {
                   1505:                                xargc = 3;
                   1506:                                xargv[1] = "-c";
                   1507:                                xargv[2] = file;
                   1508:                                xargv[3] = NULL;
                   1509:                        }
                   1510: #endif /* !SMALL */
1.10      deraadt  1511:                        mget(xargc, xargv);
1.5       millert  1512:                        interactive = ointeractive;
1.10      deraadt  1513:                } else {
1.17      millert  1514:                        if (outfile != NULL) {
                   1515:                                xargv[2] = outfile;
                   1516:                                xargv[3] = NULL;
1.10      deraadt  1517:                                xargc++;
                   1518:                        }
1.75      martynas 1519: #ifndef SMALL
                   1520:                        if (resume)
                   1521:                                reget(xargc, xargv);
                   1522:                        else
1.78      martynas 1523: #endif /* !SMALL */
1.75      martynas 1524:                                get(xargc, xargv);
1.10      deraadt  1525:                }
1.1       millert  1526:
1.4       millert  1527:                if ((code / 100) != COMPLETE)
1.1       millert  1528:                        rval = argpos + 1;
                   1529:        }
                   1530:        if (connected && rval != -1)
                   1531:                disconnect(0, NULL);
                   1532:        return (rval);
1.37      heko     1533: }
                   1534:
                   1535: char *
1.50      deraadt  1536: urldecode(const char *str)
1.37      heko     1537: {
1.53      deraadt  1538:        char *ret, c;
                   1539:        int i, reallen;
1.37      heko     1540:
1.53      deraadt  1541:        if (str == NULL)
                   1542:                return NULL;
                   1543:        if ((ret = malloc(strlen(str)+1)) == NULL)
                   1544:                err(1, "Can't allocate memory for URL decoding");
                   1545:        for (i = 0, reallen = 0; str[i] != '\0'; i++, reallen++, ret++) {
                   1546:                c = str[i];
                   1547:                if (c == '+') {
                   1548:                        *ret = ' ';
                   1549:                        continue;
                   1550:                }
1.61      deraadt  1551:
                   1552:                /* Cannot use strtol here because next char
                   1553:                 * after %xx may be a digit.
                   1554:                 */
1.143     guenther 1555:                if (c == '%' && isxdigit((unsigned char)str[i+1]) &&
                   1556:                    isxdigit((unsigned char)str[i+2])) {
1.53      deraadt  1557:                        *ret = hextochar(&str[i+1]);
                   1558:                        i+=2;
                   1559:                        continue;
                   1560:                }
                   1561:                *ret = c;
                   1562:        }
                   1563:        *ret = '\0';
                   1564:
                   1565:        return ret-reallen;
1.123     guenther 1566: }
                   1567:
1.177     jca      1568: static char *
1.123     guenther 1569: recode_credentials(const char *userinfo)
                   1570: {
                   1571:        char *ui, *creds;
                   1572:        size_t ulen, credsize;
                   1573:
                   1574:        /* url-decode the user and pass */
                   1575:        ui = urldecode(userinfo);
                   1576:
                   1577:        ulen = strlen(ui);
                   1578:        credsize = (ulen + 2) / 3 * 4 + 1;
                   1579:        creds = malloc(credsize);
                   1580:        if (creds == NULL)
                   1581:                errx(1, "out of memory");
                   1582:        if (b64_ntop(ui, ulen, creds, credsize) == -1)
                   1583:                errx(1, "error in base64 encoding");
                   1584:        free(ui);
                   1585:        return (creds);
1.37      heko     1586: }
                   1587:
1.177     jca      1588: static char
1.50      deraadt  1589: hextochar(const char *str)
1.37      heko     1590: {
1.143     guenther 1591:        unsigned char c, ret;
1.37      heko     1592:
1.53      deraadt  1593:        c = str[0];
                   1594:        ret = c;
                   1595:        if (isalpha(c))
                   1596:                ret -= isupper(c) ? 'A' - 10 : 'a' - 10;
                   1597:        else
                   1598:                ret -= '0';
                   1599:        ret *= 16;
                   1600:
                   1601:        c = str[1];
                   1602:        ret += c;
                   1603:        if (isalpha(c))
                   1604:                ret -= isupper(c) ? 'A' - 10 : 'a' - 10;
                   1605:        else
                   1606:                ret -= '0';
                   1607:        return ret;
1.25      itojun   1608: }
                   1609:
                   1610: int
1.50      deraadt  1611: isurl(const char *p)
1.25      itojun   1612: {
1.27      millert  1613:
1.26      deraadt  1614:        if (strncasecmp(p, FTP_URL, sizeof(FTP_URL) - 1) == 0 ||
                   1615:            strncasecmp(p, HTTP_URL, sizeof(HTTP_URL) - 1) == 0 ||
1.154     deraadt  1616: #ifndef NOSSL
1.61      deraadt  1617:            strncasecmp(p, HTTPS_URL, sizeof(HTTPS_URL) - 1) == 0 ||
1.154     deraadt  1618: #endif /* !NOSSL */
1.27      millert  1619:            strncasecmp(p, FILE_URL, sizeof(FILE_URL) - 1) == 0 ||
                   1620:            strstr(p, ":/"))
                   1621:                return (1);
                   1622:        return (0);
1.1       millert  1623: }
1.61      deraadt  1624:
1.177     jca      1625: static char *
1.176     jca      1626: ftp_readline(FILE *fp, size_t *lenp)
1.61      deraadt  1627: {
1.176     jca      1628:        return fparseln(fp, lenp, NULL, "\0\0\0", 0);
1.173     jca      1629: }
1.184     jca      1630:
                   1631: #ifndef SMALL
                   1632: static int
                   1633: ftp_printf(FILE *fp, const char *fmt, ...)
                   1634: {
                   1635:        va_list ap;
                   1636:        int     ret;
                   1637:
                   1638:        va_start(ap, fmt);
                   1639:        ret = vfprintf(fp, fmt, ap);
                   1640:        va_end(ap);
                   1641:
                   1642:        if (debug) {
                   1643:                va_start(ap, fmt);
                   1644:                vfprintf(ttyout, fmt, ap);
                   1645:                va_end(ap);
                   1646:        }
                   1647:
                   1648:        return ret;
                   1649: }
                   1650: #endif /* !SMALL */
1.173     jca      1651:
1.177     jca      1652: static void
1.173     jca      1653: ftp_close(FILE **fin, struct tls **tls, volatile int *fd)
                   1654: {
                   1655: #ifndef NOSSL
                   1656:        int     ret;
                   1657:
                   1658:        if (*tls != NULL) {
                   1659:                if (tls_session_fd != -1)
                   1660:                        dprintf(STDERR_FILENO, "tls session resumed: %s\n",
                   1661:                            tls_conn_session_resumed(*tls) ? "yes" : "no");
                   1662:                do {
                   1663:                        ret = tls_close(*tls);
                   1664:                } while (ret == TLS_WANT_POLLIN || ret == TLS_WANT_POLLOUT);
                   1665:                tls_free(*tls);
                   1666:                *tls = NULL;
                   1667:        }
1.176     jca      1668:        if (*fd != -1) {
                   1669:                close(*fd);
                   1670:                *fd = -1;
                   1671:        }
1.173     jca      1672: #endif
                   1673:        if (*fin != NULL) {
                   1674:                fclose(*fin);
                   1675:                *fin = NULL;
                   1676:        }
1.61      deraadt  1677: }
                   1678:
1.177     jca      1679: static const char *
1.176     jca      1680: sockerror(struct tls *tls)
                   1681: {
                   1682:        int     save_errno = errno;
1.154     deraadt  1683: #ifndef NOSSL
1.176     jca      1684:        if (tls != NULL) {
                   1685:                const char *tlserr = tls_error(tls);
                   1686:                if (tlserr != NULL)
                   1687:                        return tlserr;
1.139     bluhm    1688:        }
1.176     jca      1689: #endif
                   1690:        return strerror(save_errno);
1.61      deraadt  1691: }
                   1692:
1.176     jca      1693: #ifndef NOSSL
1.177     jca      1694: static int
1.81      espie    1695: proxy_connect(int socket, char *host, char *cookie)
1.61      deraadt  1696: {
1.66      ray      1697:        int l;
1.61      deraadt  1698:        char buf[1024];
                   1699:        char *connstr, *hosttail, *port;
                   1700:
                   1701:        if (*host == '[' && (hosttail = strrchr(host, ']')) != NULL &&
                   1702:                (hosttail[1] == '\0' || hosttail[1] == ':')) {
                   1703:                host++;
                   1704:                *hosttail++ = '\0';
                   1705:        } else
                   1706:                hosttail = host;
                   1707:
1.179     deraadt  1708:        port = strrchr(hosttail, ':');          /* find portnum */
1.61      deraadt  1709:        if (port != NULL)
                   1710:                *port++ = '\0';
                   1711:        if (!port)
                   1712:                port = "443";
                   1713:
1.81      espie    1714:        if (cookie) {
                   1715:                l = asprintf(&connstr, "CONNECT %s:%s HTTP/1.1\r\n"
                   1716:                        "Proxy-Authorization: Basic %s\r\n%s\r\n\r\n",
                   1717:                        host, port, cookie, HTTP_USER_AGENT);
                   1718:        } else {
                   1719:                l = asprintf(&connstr, "CONNECT %s:%s HTTP/1.1\r\n%s\r\n\r\n",
                   1720:                        host, port, HTTP_USER_AGENT);
                   1721:        }
                   1722:
1.66      ray      1723:        if (l == -1)
1.61      deraadt  1724:                errx(1, "Could not allocate memory to assemble connect string!");
1.80      martynas 1725: #ifndef SMALL
1.68      ray      1726:        if (debug)
                   1727:                printf("%s", connstr);
1.80      martynas 1728: #endif /* !SMALL */
1.66      ray      1729:        if (write(socket, connstr, l) != l)
1.68      ray      1730:                err(1, "Could not send connect string");
1.61      deraadt  1731:        read(socket, &buf, sizeof(buf)); /* only proxy header XXX: error handling? */
1.71      ray      1732:        free(connstr);
1.61      deraadt  1733:        return(200);
1.176     jca      1734: }
                   1735:
1.177     jca      1736: static int
1.176     jca      1737: stdio_tls_write_wrapper(void *arg, const char *buf, int len)
                   1738: {
                   1739:        struct tls *tls = arg;
                   1740:        ssize_t ret;
                   1741:
                   1742:        do {
                   1743:                ret = tls_write(tls, buf, len);
                   1744:        } while (ret == TLS_WANT_POLLIN || ret == TLS_WANT_POLLOUT);
                   1745:
                   1746:        return ret;
                   1747: }
                   1748:
1.177     jca      1749: static int
1.176     jca      1750: stdio_tls_read_wrapper(void *arg, char *buf, int len)
                   1751: {
                   1752:        struct tls *tls = arg;
                   1753:        ssize_t ret;
                   1754:
                   1755:        do {
                   1756:                ret = tls_read(tls, buf, len);
                   1757:        } while (ret == TLS_WANT_POLLIN || ret == TLS_WANT_POLLOUT);
                   1758:
                   1759:        return ret;
1.61      deraadt  1760: }
1.158     jca      1761: #endif /* !NOSSL */