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

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