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

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