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

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