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

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