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

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