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

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