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

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