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

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