[BACK]Return to fetch.c CVS log [TXT][DIR] Up to [cvs.NetBSD.org] / src / usr.bin / ftp

Annotation of src/usr.bin/ftp/fetch.c, Revision 1.229

1.229   ! christos    1: /*     $NetBSD: fetch.c,v 1.228 2017/02/15 11:52:11 nonaka Exp $       */
1.1       lukem       2:
                      3: /*-
1.207     wiz         4:  * Copyright (c) 1997-2015 The NetBSD Foundation, Inc.
1.1       lukem       5:  * All rights reserved.
                      6:  *
                      7:  * This code is derived from software contributed to The NetBSD Foundation
1.54      lukem       8:  * by Luke Mewburn.
1.1       lukem       9:  *
1.114     lukem      10:  * This code is derived from software contributed to The NetBSD Foundation
                     11:  * by Scott Aaron Bamford.
                     12:  *
1.207     wiz        13:  * This code is derived from software contributed to The NetBSD Foundation
                     14:  * by Thomas Klausner.
                     15:  *
1.1       lukem      16:  * Redistribution and use in source and binary forms, with or without
                     17:  * modification, are permitted provided that the following conditions
                     18:  * are met:
                     19:  * 1. Redistributions of source code must retain the above copyright
                     20:  *    notice, this list of conditions and the following disclaimer.
                     21:  * 2. Redistributions in binary form must reproduce the above copyright
                     22:  *    notice, this list of conditions and the following disclaimer in the
                     23:  *    documentation and/or other materials provided with the distribution.
                     24:  *
                     25:  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
                     26:  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
                     27:  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
1.14      lukem      28:  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
                     29:  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
1.1       lukem      30:  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
                     31:  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
                     32:  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
                     33:  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
                     34:  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
                     35:  * POSSIBILITY OF SUCH DAMAGE.
                     36:  */
                     37:
1.12      lukem      38: #include <sys/cdefs.h>
1.1       lukem      39: #ifndef lint
1.229   ! christos   40: __RCSID("$NetBSD: fetch.c,v 1.228 2017/02/15 11:52:11 nonaka Exp $");
1.1       lukem      41: #endif /* not lint */
                     42:
                     43: /*
                     44:  * FTP User Program -- Command line file retrieval
                     45:  */
                     46:
                     47: #include <sys/types.h>
                     48: #include <sys/param.h>
                     49: #include <sys/socket.h>
1.30      lukem      50: #include <sys/stat.h>
1.32      lukem      51: #include <sys/time.h>
1.1       lukem      52:
                     53: #include <netinet/in.h>
                     54:
1.2       lukem      55: #include <arpa/ftp.h>
1.1       lukem      56: #include <arpa/inet.h>
                     57:
1.195     lukem      58: #include <assert.h>
1.1       lukem      59: #include <ctype.h>
                     60: #include <err.h>
1.22      lukem      61: #include <errno.h>
1.1       lukem      62: #include <netdb.h>
                     63: #include <fcntl.h>
                     64: #include <stdio.h>
                     65: #include <stdlib.h>
                     66: #include <string.h>
                     67: #include <unistd.h>
1.57      christos   68: #include <time.h>
1.1       lukem      69:
1.199     christos   70: #include "ssl.h"
1.1       lukem      71: #include "ftp_var.h"
1.100     lukem      72: #include "version.h"
1.1       lukem      73:
1.27      lukem      74: typedef enum {
                     75:        UNKNOWN_URL_T=-1,
                     76:        HTTP_URL_T,
1.199     christos   77:        HTTPS_URL_T,
1.27      lukem      78:        FTP_URL_T,
1.53      lukem      79:        FILE_URL_T,
                     80:        CLASSIC_URL_T
1.27      lukem      81: } url_t;
                     82:
1.214     christos   83: struct authinfo {
                     84:        char *auth;
                     85:        char *user;
                     86:        char *pass;
                     87: };
                     88:
                     89: struct urlinfo {
                     90:        char *host;
                     91:        char *port;
                     92:        char *path;
                     93:        url_t utype;
                     94:        in_port_t portnum;
                     95: };
                     96:
1.218     christos   97: struct posinfo {
                     98:        off_t rangestart;
                     99:        off_t rangeend;
                    100:        off_t entitylen;
                    101: };
                    102:
1.194     joerg     103: __dead static void     aborthttp(int);
1.203     christos  104: __dead static void     timeouthttp(int);
1.147     christos  105: #ifndef NO_AUTH
1.214     christos  106: static int     auth_url(const char *, char **, const struct authinfo *);
1.154     lukem     107: static void    base64_encode(const unsigned char *, size_t, unsigned char *);
1.147     christos  108: #endif
1.111     lukem     109: static int     go_fetch(const char *);
                    110: static int     fetch_ftp(const char *);
                    111: static int     fetch_url(const char *, const char *, char *, char *);
1.154     lukem     112: static const char *match_token(const char **, const char *);
1.214     christos  113: static int     parse_url(const char *, const char *, struct urlinfo *,
                    114:     struct authinfo *);
1.111     lukem     115: static void    url_decode(char *);
1.214     christos  116: static void    freeauthinfo(struct authinfo *);
                    117: static void    freeurlinfo(struct urlinfo *);
1.12      lukem     118:
1.42      lukem     119: static int     redirect_loop;
                    120:
1.12      lukem     121:
1.150     lukem     122: #define        STRNEQUAL(a,b)  (strncasecmp((a), (b), sizeof((b))-1) == 0)
                    123: #define        ISLWS(x)        ((x)=='\r' || (x)=='\n' || (x)==' ' || (x)=='\t')
                    124: #define        SKIPLWS(x)      do { while (ISLWS((*x))) x++; } while (0)
                    125:
                    126:
1.25      lukem     127: #define        ABOUT_URL       "about:"        /* propaganda */
                    128: #define        FILE_URL        "file://"       /* file URL prefix */
1.1       lukem     129: #define        FTP_URL         "ftp://"        /* ftp URL prefix */
                    130: #define        HTTP_URL        "http://"       /* http URL prefix */
1.199     christos  131: #ifdef WITH_SSL
                    132: #define        HTTPS_URL       "https://"      /* https URL prefix */
1.1       lukem     133:
1.199     christos  134: #define        IS_HTTP_TYPE(urltype) \
                    135:        (((urltype) == HTTP_URL_T) || ((urltype) == HTTPS_URL_T))
                    136: #else
                    137: #define        IS_HTTP_TYPE(urltype) \
                    138:        ((urltype) == HTTP_URL_T)
                    139: #endif
1.1       lukem     140:
1.154     lukem     141: /*
                    142:  * Determine if token is the next word in buf (case insensitive).
                    143:  * If so, advance buf past the token and any trailing LWS, and
                    144:  * return a pointer to the token (in buf).  Otherwise, return NULL.
1.172     christos  145:  * token may be preceded by LWS.
1.154     lukem     146:  * token must be followed by LWS or NUL.  (I.e, don't partial match).
                    147:  */
                    148: static const char *
                    149: match_token(const char **buf, const char *token)
                    150: {
                    151:        const char      *p, *orig;
                    152:        size_t          tlen;
                    153:
                    154:        tlen = strlen(token);
                    155:        p = *buf;
                    156:        SKIPLWS(p);
                    157:        orig = p;
                    158:        if (strncasecmp(p, token, tlen) != 0)
                    159:                return NULL;
                    160:        p += tlen;
                    161:        if (*p != '\0' && !ISLWS(*p))
                    162:                return NULL;
                    163:        SKIPLWS(p);
                    164:        orig = *buf;
                    165:        *buf = p;
                    166:        return orig;
                    167: }
                    168:
1.214     christos  169: static void
1.218     christos  170: initposinfo(struct posinfo *pi)
                    171: {
                    172:        pi->rangestart = pi->rangeend = pi->entitylen = -1;
                    173: }
                    174:
                    175: static void
1.214     christos  176: initauthinfo(struct authinfo *ai, char *auth)
                    177: {
                    178:        ai->auth = auth;
                    179:        ai->user = ai->pass = 0;
                    180: }
                    181:
                    182: static void
                    183: freeauthinfo(struct authinfo *a)
                    184: {
                    185:        FREEPTR(a->user);
                    186:        if (a->pass != NULL)
                    187:                memset(a->pass, 0, strlen(a->pass));
                    188:        FREEPTR(a->pass);
                    189: }
                    190:
                    191: static void
                    192: initurlinfo(struct urlinfo *ui)
                    193: {
                    194:        ui->host = ui->port = ui->path = 0;
                    195:        ui->utype = UNKNOWN_URL_T;
                    196:        ui->portnum = 0;
                    197: }
                    198:
1.215     christos  199: static void
                    200: copyurlinfo(struct urlinfo *dui, struct urlinfo *sui)
                    201: {
                    202:        dui->host = ftp_strdup(sui->host);
                    203:        dui->port = ftp_strdup(sui->port);
                    204:        dui->path = ftp_strdup(sui->path);
                    205:        dui->utype = sui->utype;
                    206:        dui->portnum = sui->portnum;
                    207: }
                    208:
1.214     christos  209: static void
                    210: freeurlinfo(struct urlinfo *ui)
                    211: {
                    212:        FREEPTR(ui->host);
                    213:        FREEPTR(ui->port);
                    214:        FREEPTR(ui->path);
                    215: }
                    216:
1.147     christos  217: #ifndef NO_AUTH
1.27      lukem     218: /*
1.44      lukem     219:  * Generate authorization response based on given authentication challenge.
                    220:  * Returns -1 if an error occurred, otherwise 0.
                    221:  * Sets response to a malloc(3)ed string; caller should free.
                    222:  */
                    223: static int
1.214     christos  224: auth_url(const char *challenge, char **response, const struct authinfo *auth)
1.44      lukem     225: {
1.162     lukem     226:        const char      *cp, *scheme, *errormsg;
1.154     lukem     227:        char            *ep, *clear, *realm;
1.187     lukem     228:        char             uuser[BUFSIZ], *gotpass;
                    229:        const char      *upass;
1.82      lukem     230:        int              rval;
                    231:        size_t           len, clen, rlen;
1.44      lukem     232:
                    233:        *response = NULL;
1.154     lukem     234:        clear = realm = NULL;
1.44      lukem     235:        rval = -1;
1.154     lukem     236:        cp = challenge;
                    237:        scheme = "Basic";       /* only support Basic authentication */
1.187     lukem     238:        gotpass = NULL;
1.44      lukem     239:
1.163     christos  240:        DPRINTF("auth_url: challenge `%s'\n", challenge);
1.44      lukem     241:
1.154     lukem     242:        if (! match_token(&cp, scheme)) {
1.175     lukem     243:                warnx("Unsupported authentication challenge `%s'",
1.44      lukem     244:                    challenge);
                    245:                goto cleanup_auth_url;
                    246:        }
                    247:
1.91      lukem     248: #define        REALM "realm=\""
1.150     lukem     249:        if (STRNEQUAL(cp, REALM))
1.44      lukem     250:                cp += sizeof(REALM) - 1;
                    251:        else {
1.175     lukem     252:                warnx("Unsupported authentication challenge `%s'",
1.44      lukem     253:                    challenge);
                    254:                goto cleanup_auth_url;
                    255:        }
1.154     lukem     256: /* XXX: need to improve quoted-string parsing to support \ quoting, etc. */
1.44      lukem     257:        if ((ep = strchr(cp, '\"')) != NULL) {
1.186     lukem     258:                len = ep - cp;
1.166     christos  259:                realm = (char *)ftp_malloc(len + 1);
1.78      lukem     260:                (void)strlcpy(realm, cp, len + 1);
1.44      lukem     261:        } else {
1.175     lukem     262:                warnx("Unsupported authentication challenge `%s'",
1.44      lukem     263:                    challenge);
                    264:                goto cleanup_auth_url;
                    265:        }
                    266:
1.154     lukem     267:        fprintf(ttyout, "Username for `%s': ", realm);
1.214     christos  268:        if (auth->user != NULL) {
                    269:                (void)strlcpy(uuser, auth->user, sizeof(uuser));
1.186     lukem     270:                fprintf(ttyout, "%s\n", uuser);
1.154     lukem     271:        } else {
1.54      lukem     272:                (void)fflush(ttyout);
1.188     roy       273:                if (get_line(stdin, uuser, sizeof(uuser), &errormsg) < 0) {
1.162     lukem     274:                        warnx("%s; can't authenticate", errormsg);
1.54      lukem     275:                        goto cleanup_auth_url;
1.90      lukem     276:                }
1.54      lukem     277:        }
1.214     christos  278:        if (auth->pass != NULL)
                    279:                upass = auth->pass;
1.174     lukem     280:        else {
1.187     lukem     281:                gotpass = getpass("Password: ");
                    282:                if (gotpass == NULL) {
1.174     lukem     283:                        warnx("Can't read password");
                    284:                        goto cleanup_auth_url;
                    285:                }
1.187     lukem     286:                upass = gotpass;
1.174     lukem     287:        }
1.44      lukem     288:
1.187     lukem     289:        clen = strlen(uuser) + strlen(upass) + 2;       /* user + ":" + pass + "\0" */
1.166     christos  290:        clear = (char *)ftp_malloc(clen);
1.186     lukem     291:        (void)strlcpy(clear, uuser, clen);
1.78      lukem     292:        (void)strlcat(clear, ":", clen);
1.187     lukem     293:        (void)strlcat(clear, upass, clen);
                    294:        if (gotpass)
                    295:                memset(gotpass, 0, strlen(gotpass));
1.44      lukem     296:
1.64      lukem     297:                                                /* scheme + " " + enc + "\0" */
1.74      lukem     298:        rlen = strlen(scheme) + 1 + (clen + 2) * 4 / 3 + 1;
1.214     christos  299:        *response = ftp_malloc(rlen);
1.78      lukem     300:        (void)strlcpy(*response, scheme, rlen);
1.72      lukem     301:        len = strlcat(*response, " ", rlen);
1.152     lukem     302:                        /* use  `clen - 1'  to not encode the trailing NUL */
1.158     lukem     303:        base64_encode((unsigned char *)clear, clen - 1,
                    304:            (unsigned char *)*response + len);
1.80      lukem     305:        memset(clear, 0, clen);
1.44      lukem     306:        rval = 0;
                    307:
1.118     lukem     308:  cleanup_auth_url:
1.44      lukem     309:        FREEPTR(clear);
                    310:        FREEPTR(realm);
                    311:        return (rval);
                    312: }
                    313:
                    314: /*
                    315:  * Encode len bytes starting at clear using base64 encoding into encoded,
                    316:  * which should be at least ((len + 2) * 4 / 3 + 1) in size.
                    317:  */
1.124     lukem     318: static void
1.154     lukem     319: base64_encode(const unsigned char *clear, size_t len, unsigned char *encoded)
1.44      lukem     320: {
1.154     lukem     321:        static const unsigned char enc[] =
1.44      lukem     322:            "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
1.154     lukem     323:        unsigned char   *cp;
1.187     lukem     324:        size_t   i;
1.44      lukem     325:
                    326:        cp = encoded;
                    327:        for (i = 0; i < len; i += 3) {
                    328:                *(cp++) = enc[((clear[i + 0] >> 2))];
                    329:                *(cp++) = enc[((clear[i + 0] << 4) & 0x30)
                    330:                            | ((clear[i + 1] >> 4) & 0x0f)];
                    331:                *(cp++) = enc[((clear[i + 1] << 2) & 0x3c)
                    332:                            | ((clear[i + 2] >> 6) & 0x03)];
                    333:                *(cp++) = enc[((clear[i + 2]     ) & 0x3f)];
                    334:        }
                    335:        *cp = '\0';
                    336:        while (i-- > len)
                    337:                *(--cp) = '=';
                    338: }
1.147     christos  339: #endif
1.44      lukem     340:
1.50      lukem     341: /*
                    342:  * Decode %xx escapes in given string, `in-place'.
                    343:  */
                    344: static void
1.111     lukem     345: url_decode(char *url)
1.50      lukem     346: {
                    347:        unsigned char *p, *q;
                    348:
                    349:        if (EMPTYSTRING(url))
                    350:                return;
1.75      lukem     351:        p = q = (unsigned char *)url;
1.50      lukem     352:
1.91      lukem     353: #define        HEXTOINT(x) (x - (isdigit(x) ? '0' : (islower(x) ? 'a' : 'A') - 10))
1.50      lukem     354:        while (*p) {
                    355:                if (p[0] == '%'
                    356:                    && p[1] && isxdigit((unsigned char)p[1])
                    357:                    && p[2] && isxdigit((unsigned char)p[2])) {
                    358:                        *q++ = HEXTOINT(p[1]) * 16 + HEXTOINT(p[2]);
                    359:                        p+=3;
                    360:                } else
                    361:                        *q++ = *p++;
                    362:        }
                    363:        *q = '\0';
                    364: }
                    365:
1.44      lukem     366:
                    367: /*
1.193     lukem     368:  * Parse URL of form (per RFC 3986):
1.145     lukem     369:  *     <type>://[<user>[:<password>]@]<host>[:<port>][/<path>]
1.27      lukem     370:  * Returns -1 if a parse error occurred, otherwise 0.
1.50      lukem     371:  * It's the caller's responsibility to url_decode() the returned
                    372:  * user, pass and path.
1.63      lukem     373:  *
1.27      lukem     374:  * Sets type to url_t, each of the given char ** pointers to a
                    375:  * malloc(3)ed strings of the relevant section, and port to
1.41      lukem     376:  * the number given, or ftpport if ftp://, or httpport if http://.
1.52      lukem     377:  *
1.193     lukem     378:  * XXX: this is not totally RFC 3986 compliant; <path> will have the
1.53      lukem     379:  * leading `/' unless it's an ftp:// URL, as this makes things easier
1.177     lukem     380:  * for file:// and http:// URLs.  ftp:// URLs have the `/' between the
1.141     wiz       381:  * host and the URL-path removed, but any additional leading slashes
                    382:  * in the URL-path are retained (because they imply that we should
1.53      lukem     383:  * later do "CWD" with a null argument).
                    384:  *
                    385:  * Examples:
1.141     wiz       386:  *      input URL                       output path
1.53      lukem     387:  *      ---------                       -----------
1.177     lukem     388:  *     "http://host"                   "/"
                    389:  *     "http://host/"                  "/"
                    390:  *     "http://host/path"              "/path"
1.63      lukem     391:  *     "file://host/dir/file"          "dir/file"
1.177     lukem     392:  *     "ftp://host"                    ""
1.63      lukem     393:  *     "ftp://host/"                   ""
1.177     lukem     394:  *     "ftp://host//"                  "/"
                    395:  *     "ftp://host/dir/file"           "dir/file"
1.53      lukem     396:  *     "ftp://host//dir/file"          "/dir/file"
1.27      lukem     397:  */
1.214     christos  398:
1.27      lukem     399: static int
1.214     christos  400: parse_url(const char *url, const char *desc, struct urlinfo *ui,
                    401:     struct authinfo *auth)
1.27      lukem     402: {
1.187     lukem     403:        const char      *origurl, *tport;
                    404:        char            *cp, *ep, *thost;
1.82      lukem     405:        size_t           len;
1.27      lukem     406:
1.214     christos  407:        if (url == NULL || desc == NULL || ui == NULL || auth == NULL)
1.27      lukem     408:                errx(1, "parse_url: invoked with NULL argument!");
1.183     lukem     409:        DPRINTF("parse_url: %s `%s'\n", desc, url);
1.27      lukem     410:
1.82      lukem     411:        origurl = url;
1.63      lukem     412:        tport = NULL;
1.27      lukem     413:
1.150     lukem     414:        if (STRNEQUAL(url, HTTP_URL)) {
1.27      lukem     415:                url += sizeof(HTTP_URL) - 1;
1.214     christos  416:                ui->utype = HTTP_URL_T;
                    417:                ui->portnum = HTTP_PORT;
1.63      lukem     418:                tport = httpport;
1.150     lukem     419:        } else if (STRNEQUAL(url, FTP_URL)) {
1.27      lukem     420:                url += sizeof(FTP_URL) - 1;
1.214     christos  421:                ui->utype = FTP_URL_T;
                    422:                ui->portnum = FTP_PORT;
1.63      lukem     423:                tport = ftpport;
1.150     lukem     424:        } else if (STRNEQUAL(url, FILE_URL)) {
1.27      lukem     425:                url += sizeof(FILE_URL) - 1;
1.214     christos  426:                ui->utype = FILE_URL_T;
1.220     wiz       427:                tport = "";
1.199     christos  428: #ifdef WITH_SSL
                    429:        } else if (STRNEQUAL(url, HTTPS_URL)) {
                    430:                url += sizeof(HTTPS_URL) - 1;
1.214     christos  431:                ui->utype = HTTPS_URL_T;
                    432:                ui->portnum = HTTPS_PORT;
1.199     christos  433:                tport = httpsport;
                    434: #endif
1.27      lukem     435:        } else {
                    436:                warnx("Invalid %s `%s'", desc, url);
1.118     lukem     437:  cleanup_parse_url:
1.214     christos  438:                freeauthinfo(auth);
                    439:                freeurlinfo(ui);
1.27      lukem     440:                return (-1);
                    441:        }
                    442:
                    443:        if (*url == '\0')
                    444:                return (0);
                    445:
                    446:                        /* find [user[:pass]@]host[:port] */
                    447:        ep = strchr(url, '/');
                    448:        if (ep == NULL)
1.166     christos  449:                thost = ftp_strdup(url);
1.27      lukem     450:        else {
1.50      lukem     451:                len = ep - url;
1.166     christos  452:                thost = (char *)ftp_malloc(len + 1);
1.78      lukem     453:                (void)strlcpy(thost, url, len + 1);
1.214     christos  454:                if (ui->utype == FTP_URL_T)     /* skip first / for ftp URLs */
1.53      lukem     455:                        ep++;
1.214     christos  456:                ui->path = ftp_strdup(ep);
1.27      lukem     457:        }
                    458:
1.191     christos  459:        cp = strchr(thost, '@');        /* look for user[:pass]@ in URLs */
1.54      lukem     460:        if (cp != NULL) {
1.214     christos  461:                if (ui->utype == FTP_URL_T)
1.54      lukem     462:                        anonftp = 0;    /* disable anonftp */
1.214     christos  463:                auth->user = thost;
1.27      lukem     464:                *cp = '\0';
1.166     christos  465:                thost = ftp_strdup(cp + 1);
1.214     christos  466:                cp = strchr(auth->user, ':');
1.27      lukem     467:                if (cp != NULL) {
                    468:                        *cp = '\0';
1.214     christos  469:                        auth->pass = ftp_strdup(cp + 1);
1.27      lukem     470:                }
1.214     christos  471:                url_decode(auth->user);
                    472:                if (auth->pass)
                    473:                        url_decode(auth->pass);
1.63      lukem     474:        }
                    475:
                    476: #ifdef INET6
                    477:                        /*
                    478:                         * Check if thost is an encoded IPv6 address, as per
1.193     lukem     479:                         * RFC 3986:
1.63      lukem     480:                         *      `[' ipv6-address ']'
                    481:                         */
                    482:        if (*thost == '[') {
                    483:                cp = thost + 1;
                    484:                if ((ep = strchr(cp, ']')) == NULL ||
1.106     itojun    485:                    (ep[1] != '\0' && ep[1] != ':')) {
1.63      lukem     486:                        warnx("Invalid address `%s' in %s `%s'",
1.82      lukem     487:                            thost, desc, origurl);
1.63      lukem     488:                        goto cleanup_parse_url;
                    489:                }
1.103     lukem     490:                len = ep - cp;          /* change `[xyz]' -> `xyz' */
1.63      lukem     491:                memmove(thost, thost + 1, len);
                    492:                thost[len] = '\0';
                    493:                if (! isipv6addr(thost)) {
                    494:                        warnx("Invalid IPv6 address `%s' in %s `%s'",
1.82      lukem     495:                            thost, desc, origurl);
1.63      lukem     496:                        goto cleanup_parse_url;
                    497:                }
                    498:                cp = ep + 1;
                    499:                if (*cp == ':')
                    500:                        cp++;
                    501:                else
                    502:                        cp = NULL;
1.27      lukem     503:        } else
1.63      lukem     504: #endif /* INET6 */
1.177     lukem     505:                if ((cp = strchr(thost, ':')) != NULL)
1.184     lukem     506:                        *cp++ = '\0';
1.214     christos  507:        ui->host = thost;
1.60      itojun    508:
1.27      lukem     509:                        /* look for [:port] */
                    510:        if (cp != NULL) {
1.184     lukem     511:                unsigned long   nport;
1.27      lukem     512:
1.184     lukem     513:                nport = strtoul(cp, &ep, 10);
                    514:                if (*cp == '\0' || *ep != '\0' ||
                    515:                    nport < 1 || nport > MAX_IN_PORT_T) {
1.122     lukem     516:                        warnx("Unknown port `%s' in %s `%s'",
                    517:                            cp, desc, origurl);
1.27      lukem     518:                        goto cleanup_parse_url;
                    519:                }
1.214     christos  520:                ui->portnum = nport;
1.63      lukem     521:                tport = cp;
1.27      lukem     522:        }
1.82      lukem     523:
1.95      lukem     524:        if (tport != NULL)
1.214     christos  525:                ui->port = ftp_strdup(tport);
                    526:        if (ui->path == NULL) {
1.177     lukem     527:                const char *emptypath = "/";
1.214     christos  528:                if (ui->utype == FTP_URL_T)     /* skip first / for ftp URLs */
1.177     lukem     529:                        emptypath++;
1.214     christos  530:                ui->path = ftp_strdup(emptypath);
1.177     lukem     531:        }
1.27      lukem     532:
1.163     christos  533:        DPRINTF("parse_url: user `%s' pass `%s' host %s port %s(%d) "
                    534:            "path `%s'\n",
1.214     christos  535:            STRorNULL(auth->user), STRorNULL(auth->pass),
                    536:            STRorNULL(ui->host), STRorNULL(ui->port),
                    537:            ui->portnum ? ui->portnum : -1, STRorNULL(ui->path));
1.27      lukem     538:
                    539:        return (0);
                    540: }
                    541:
1.89      lukem     542: sigjmp_buf     httpabort;
1.2       lukem     543:
1.210     christos  544: static int
1.214     christos  545: ftp_socket(const struct urlinfo *ui, void **ssl)
1.210     christos  546: {
                    547:        struct addrinfo hints, *res, *res0 = NULL;
                    548:        int error;
                    549:        int s;
1.214     christos  550:        const char *host = ui->host;
                    551:        const char *port = ui->port;
                    552:
                    553:        if (ui->utype != HTTPS_URL_T)
                    554:                ssl = NULL;
1.210     christos  555:
                    556:        memset(&hints, 0, sizeof(hints));
                    557:        hints.ai_flags = 0;
                    558:        hints.ai_family = family;
                    559:        hints.ai_socktype = SOCK_STREAM;
                    560:        hints.ai_protocol = 0;
                    561:
                    562:        error = getaddrinfo(host, port, &hints, &res0);
                    563:        if (error) {
                    564:                warnx("Can't LOOKUP `%s:%s': %s", host, port,
                    565:                    (error == EAI_SYSTEM) ? strerror(errno)
                    566:                                          : gai_strerror(error));
                    567:                return -1;
                    568:        }
                    569:
                    570:        if (res0->ai_canonname)
                    571:                host = res0->ai_canonname;
                    572:
                    573:        s = -1;
                    574:        if (ssl)
                    575:                *ssl = NULL;
                    576:        for (res = res0; res; res = res->ai_next) {
                    577:                char    hname[NI_MAXHOST], sname[NI_MAXSERV];
                    578:
                    579:                ai_unmapped(res);
                    580:                if (getnameinfo(res->ai_addr, res->ai_addrlen,
                    581:                    hname, sizeof(hname), sname, sizeof(sname),
                    582:                    NI_NUMERICHOST | NI_NUMERICSERV) != 0) {
                    583:                        strlcpy(hname, "?", sizeof(hname));
                    584:                        strlcpy(sname, "?", sizeof(sname));
                    585:                }
                    586:
                    587:                if (verbose && res0->ai_next) {
                    588: #ifdef INET6
                    589:                        if(res->ai_family == AF_INET6) {
                    590:                                fprintf(ttyout, "Trying [%s]:%s ...\n",
                    591:                                    hname, sname);
                    592:                        } else {
                    593: #endif
                    594:                                fprintf(ttyout, "Trying %s:%s ...\n",
                    595:                                    hname, sname);
                    596: #ifdef INET6
                    597:                        }
                    598: #endif
                    599:                }
                    600:
                    601:                s = socket(res->ai_family, SOCK_STREAM, res->ai_protocol);
                    602:                if (s < 0) {
                    603:                        warn(
                    604:                            "Can't create socket for connection to "
                    605:                            "`%s:%s'", hname, sname);
                    606:                        continue;
                    607:                }
                    608:
                    609:                if (ftp_connect(s, res->ai_addr, res->ai_addrlen,
                    610:                    verbose || !res->ai_next) < 0) {
                    611:                        close(s);
                    612:                        s = -1;
                    613:                        continue;
                    614:                }
                    615:
                    616: #ifdef WITH_SSL
                    617:                if (ssl) {
                    618:                        if ((*ssl = fetch_start_ssl(s, host)) == NULL) {
                    619:                                close(s);
                    620:                                s = -1;
                    621:                                continue;
                    622:                        }
                    623:                }
                    624: #endif
                    625:                break;
                    626:        }
                    627:        if (res0)
                    628:                freeaddrinfo(res0);
                    629:        return s;
                    630: }
                    631:
1.211     christos  632: static int
                    633: handle_noproxy(const char *host, in_port_t portnum)
                    634: {
                    635:
                    636:        char *cp, *ep, *np, *np_copy, *np_iter, *no_proxy;
                    637:        unsigned long np_port;
                    638:        size_t hlen, plen;
                    639:        int isproxy = 1;
                    640:
                    641:        /* check URL against list of no_proxied sites */
                    642:        no_proxy = getoptionvalue("no_proxy");
                    643:        if (EMPTYSTRING(no_proxy))
                    644:                return isproxy;
                    645:
                    646:        np_iter = np_copy = ftp_strdup(no_proxy);
                    647:        hlen = strlen(host);
                    648:        while ((cp = strsep(&np_iter, " ,")) != NULL) {
                    649:                if (*cp == '\0')
                    650:                        continue;
                    651:                if ((np = strrchr(cp, ':')) != NULL) {
                    652:                        *np++ =  '\0';
                    653:                        np_port = strtoul(np, &ep, 10);
                    654:                        if (*np == '\0' || *ep != '\0')
                    655:                                continue;
                    656:                        if (np_port != portnum)
                    657:                                continue;
                    658:                }
                    659:                plen = strlen(cp);
                    660:                if (hlen < plen)
                    661:                        continue;
                    662:                if (strncasecmp(host + hlen - plen, cp, plen) == 0) {
                    663:                        isproxy = 0;
                    664:                        break;
                    665:                }
                    666:        }
                    667:        FREEPTR(np_copy);
                    668:        return isproxy;
                    669: }
                    670:
1.212     christos  671: static int
1.214     christos  672: handle_proxy(const char *url, const char *penv, struct urlinfo *ui,
                    673:     struct authinfo *pauth)
1.212     christos  674: {
1.214     christos  675:        struct urlinfo pui;
1.212     christos  676:
1.214     christos  677:        if (isipv6addr(ui->host) && strchr(ui->host, '%') != NULL) {
1.212     christos  678:                warnx("Scoped address notation `%s' disallowed via web proxy",
1.214     christos  679:                    ui->host);
1.212     christos  680:                return -1;
                    681:        }
                    682:
1.214     christos  683:        initurlinfo(&pui);
                    684:        if (parse_url(penv, "proxy URL", &pui, pauth) == -1)
1.212     christos  685:                return -1;
                    686:
1.214     christos  687:        if ((!IS_HTTP_TYPE(pui.utype) && pui.utype != FTP_URL_T) ||
                    688:            EMPTYSTRING(pui.host) ||
                    689:            (! EMPTYSTRING(pui.path) && strcmp(pui.path, "/") != 0)) {
1.212     christos  690:                warnx("Malformed proxy URL `%s'", penv);
1.214     christos  691:                freeurlinfo(&pui);
1.212     christos  692:                return -1;
                    693:        }
                    694:
1.214     christos  695:        FREEPTR(pui.path);
                    696:        pui.path = ftp_strdup(url);
1.212     christos  697:
1.214     christos  698:        freeurlinfo(ui);
                    699:        *ui = pui;
1.212     christos  700:
                    701:        return 0;
                    702: }
                    703:
1.214     christos  704: static void
1.216     nonaka    705: print_host(FETCH *fin, const struct urlinfo *ui)
1.214     christos  706: {
                    707:        char *h, *p;
                    708:
1.216     nonaka    709:        if (strchr(ui->host, ':') == NULL) {
                    710:                fetch_printf(fin, "Host: %s", ui->host);
                    711:        } else {
                    712:                /*
                    713:                 * strip off IPv6 scope identifier, since it is
                    714:                 * local to the node
                    715:                 */
                    716:                h = ftp_strdup(ui->host);
                    717:                if (isipv6addr(h) && (p = strchr(h, '%')) != NULL)
                    718:                        *p = '\0';
                    719:
                    720:                fetch_printf(fin, "Host: [%s]", h);
                    721:                free(h);
1.214     christos  722:        }
                    723:
1.216     nonaka    724:        if ((ui->utype == HTTP_URL_T && ui->portnum != HTTP_PORT) ||
                    725:            (ui->utype == HTTPS_URL_T && ui->portnum != HTTPS_PORT))
                    726:                fetch_printf(fin, ":%u", ui->portnum);
                    727:        fetch_printf(fin, "\r\n");
1.214     christos  728: }
                    729:
                    730: static void
                    731: print_agent(FETCH *fin)
                    732: {
                    733:        const char *useragent;
                    734:        if ((useragent = getenv("FTPUSERAGENT")) != NULL) {
                    735:                fetch_printf(fin, "User-Agent: %s\r\n", useragent);
                    736:        } else {
                    737:                fetch_printf(fin, "User-Agent: %s/%s\r\n",
                    738:                    FTP_PRODUCT, FTP_VERSION);
                    739:        }
                    740: }
                    741:
                    742: static void
                    743: print_cache(FETCH *fin, int isproxy)
                    744: {
                    745:        fetch_printf(fin, isproxy ?
                    746:            "Pragma: no-cache\r\n" :
                    747:            "Cache-Control: no-cache\r\n");
                    748: }
                    749:
                    750: static int
1.216     nonaka    751: print_get(FETCH *fin, int hasleading, int isproxy, const struct urlinfo *oui,
                    752:     const struct urlinfo *ui)
1.214     christos  753: {
1.215     christos  754:        const char *leading = hasleading ? ", " : "  (";
1.214     christos  755:
                    756:        if (isproxy) {
                    757:                if (verbose) {
                    758:                        fprintf(ttyout, "%svia %s:%u", leading,
                    759:                            ui->host, ui->portnum);
                    760:                        leading = ", ";
                    761:                        hasleading++;
                    762:                }
                    763:                fetch_printf(fin, "GET %s HTTP/1.0\r\n", ui->path);
1.216     nonaka    764:                print_host(fin, oui);
1.214     christos  765:                return hasleading;
                    766:        }
                    767:
                    768:        fetch_printf(fin, "GET %s HTTP/1.1\r\n", ui->path);
1.216     nonaka    769:        print_host(fin, ui);
1.214     christos  770:        fetch_printf(fin, "Accept: */*\r\n");
                    771:        fetch_printf(fin, "Connection: close\r\n");
                    772:        if (restart_point) {
                    773:                fputs(leading, ttyout);
                    774:                fetch_printf(fin, "Range: bytes=" LLF "-\r\n",
                    775:                    (LLT)restart_point);
                    776:                fprintf(ttyout, "restarting at " LLF, (LLT)restart_point);
                    777:                hasleading++;
                    778:        }
                    779:        return hasleading;
                    780: }
                    781:
                    782: static void
                    783: getmtime(const char *cp, time_t *mtime)
                    784: {
                    785:        struct tm parsed;
                    786:        const char *t;
                    787:
                    788:        memset(&parsed, 0, sizeof(parsed));
                    789:        t = parse_rfc2616time(&parsed, cp);
                    790:
                    791:        if (t == NULL)
                    792:                return;
                    793:
                    794:        parsed.tm_isdst = -1;
                    795:        if (*t == '\0')
                    796:                *mtime = timegm(&parsed);
                    797:
                    798: #ifndef NO_DEBUG
                    799:        if (ftp_debug && *mtime != -1) {
                    800:                fprintf(ttyout, "parsed time as: %s",
                    801:                    rfc2822time(localtime(mtime)));
                    802:        }
                    803: #endif
                    804: }
                    805:
                    806: static int
1.216     nonaka    807: print_proxy(FETCH *fin, int hasleading, const char *wwwauth,
                    808:     const char *proxyauth)
1.214     christos  809: {
1.216     nonaka    810:        const char *leading = hasleading ? ", " : "  (";
1.214     christos  811:
                    812:        if (wwwauth) {
                    813:                if (verbose) {
                    814:                        fprintf(ttyout, "%swith authorization", leading);
                    815:                        hasleading++;
                    816:                }
                    817:                fetch_printf(fin, "Authorization: %s\r\n", wwwauth);
                    818:        }
                    819:        if (proxyauth) {
                    820:                if (verbose) {
                    821:                        fprintf(ttyout, "%swith proxy authorization", leading);
                    822:                        hasleading++;
                    823:                }
                    824:                fetch_printf(fin, "Proxy-Authorization: %s\r\n", proxyauth);
                    825:        }
                    826:        return hasleading;
                    827: }
                    828:
1.219     christos  829: #ifdef WITH_SSL
1.217     christos  830: static void
                    831: print_connect(FETCH *fin, const struct urlinfo *ui)
                    832: {
                    833:        char hname[NI_MAXHOST], *p;
                    834:        const char *h;
                    835:
                    836:        if (isipv6addr(ui->host)) {
                    837:                /*
                    838:                 * strip off IPv6 scope identifier,
                    839:                 * since it is local to the node
                    840:                 */
                    841:                if ((p = strchr(ui->host, '%')) == NULL)
                    842:                        snprintf(hname, sizeof(hname), "[%s]", ui->host);
                    843:                else
                    844:                        snprintf(hname, sizeof(hname), "[%.*s]",
                    845:                            (int)(p - ui->host), ui->host);
                    846:                h = hname;
                    847:        } else
                    848:                h = ui->host;
                    849:
1.223     christos  850:        fetch_printf(fin, "CONNECT %s:%d HTTP/1.1\r\n", h, ui->portnum);
                    851:        fetch_printf(fin, "Host: %s:%d\r\n", h, ui->portnum);
1.217     christos  852: }
1.219     christos  853: #endif
1.217     christos  854:
1.214     christos  855: #define C_OK 0
                    856: #define C_CLEANUP 1
                    857: #define C_IMPROPER 2
                    858:
                    859: static int
1.215     christos  860: getresponseline(FETCH *fin, char *buf, size_t buflen, int *len)
1.214     christos  861: {
1.215     christos  862:        const char *errormsg;
1.214     christos  863:
                    864:        alarmtimer(quit_time ? quit_time : 60);
1.215     christos  865:        *len = fetch_getline(fin, buf, buflen, &errormsg);
1.214     christos  866:        alarmtimer(0);
1.215     christos  867:        if (*len < 0) {
1.214     christos  868:                if (*errormsg == '\n')
                    869:                        errormsg++;
                    870:                warnx("Receiving HTTP reply: %s", errormsg);
1.215     christos  871:                return C_CLEANUP;
1.214     christos  872:        }
1.215     christos  873:        while (*len > 0 && (ISLWS(buf[*len-1])))
                    874:                buf[--*len] = '\0';
1.214     christos  875:
1.215     christos  876:        if (*len)
                    877:                DPRINTF("%s: received `%s'\n", __func__, buf);
                    878:        return C_OK;
                    879: }
                    880:
                    881: static int
                    882: getresponse(FETCH *fin, char **cp, size_t buflen, int *hcode)
                    883: {
                    884:        int len, rv;
                    885:        char *ep, *buf = *cp;
                    886:
                    887:        *hcode = 0;
                    888:        if ((rv = getresponseline(fin, buf, buflen, &len)) != C_OK)
                    889:                return rv;
1.214     christos  890:
                    891:        /* Determine HTTP response code */
1.215     christos  892:        *cp = strchr(buf, ' ');
                    893:        if (*cp == NULL)
                    894:                return C_IMPROPER;
                    895:
                    896:        (*cp)++;
1.214     christos  897:
1.215     christos  898:        *hcode = strtol(*cp, &ep, 10);
1.214     christos  899:        if (*ep != '\0' && !isspace((unsigned char)*ep))
1.215     christos  900:                return C_IMPROPER;
                    901:
                    902:        return C_OK;
                    903: }
                    904:
                    905: static int
1.218     christos  906: parse_posinfo(const char **cp, struct posinfo *pi)
                    907: {
                    908:        char *ep;
                    909:        if (!match_token(cp, "bytes"))
                    910:                return -1;
                    911:
                    912:        if (**cp == '*')
                    913:                (*cp)++;
                    914:        else {
                    915:                pi->rangestart = STRTOLL(*cp, &ep, 10);
                    916:                if (pi->rangestart < 0 || *ep != '-')
                    917:                        return -1;
                    918:                *cp = ep + 1;
                    919:                pi->rangeend = STRTOLL(*cp, &ep, 10);
                    920:                if (pi->rangeend < 0 || pi->rangeend < pi->rangestart)
                    921:                        return -1;
                    922:                *cp = ep;
                    923:        }
                    924:        if (**cp != '/')
                    925:                return -1;
                    926:        (*cp)++;
                    927:        if (**cp == '*')
                    928:                (*cp)++;
                    929:        else {
                    930:                pi->entitylen = STRTOLL(*cp, &ep, 10);
                    931:                if (pi->entitylen < 0)
                    932:                        return -1;
                    933:                *cp = ep;
                    934:        }
                    935:        if (**cp != '\0')
                    936:                return -1;
                    937:
                    938: #ifndef NO_DEBUG
                    939:        if (ftp_debug) {
                    940:                fprintf(ttyout, "parsed range as: ");
                    941:                if (pi->rangestart == -1)
                    942:                        fprintf(ttyout, "*");
                    943:                else
                    944:                        fprintf(ttyout, LLF "-" LLF, (LLT)pi->rangestart,
                    945:                            (LLT)pi->rangeend);
                    946:                fprintf(ttyout, "/" LLF "\n", (LLT)pi->entitylen);
                    947:        }
                    948: #endif
                    949:        return 0;
                    950: }
                    951:
1.228     nonaka    952: #ifndef NO_AUTH
                    953: static void
                    954: do_auth(int hcode, const char *url, const char *penv, struct authinfo *wauth,
                    955:     struct authinfo *pauth, char **auth, const char *message,
                    956:     volatile int *rval)
                    957: {
                    958:        struct authinfo aauth;
                    959:        char *response;
                    960:
                    961:        if (hcode == 401)
                    962:                aauth = *wauth;
                    963:        else
                    964:                aauth = *pauth;
                    965:
                    966:        if (verbose || aauth.auth == NULL ||
                    967:            aauth.user == NULL || aauth.pass == NULL)
                    968:                fprintf(ttyout, "%s\n", message);
                    969:        if (EMPTYSTRING(*auth)) {
                    970:                warnx("No authentication challenge provided by server");
                    971:                return;
                    972:        }
                    973:
                    974:        if (aauth.auth != NULL) {
                    975:                char reply[10];
                    976:
                    977:                fprintf(ttyout, "Authorization failed. Retry (y/n)? ");
                    978:                if (get_line(stdin, reply, sizeof(reply), NULL) < 0) {
                    979:                        return;
                    980:                }
                    981:                if (tolower((unsigned char)reply[0]) != 'y')
                    982:                        return;
                    983:
                    984:                aauth.user = NULL;
                    985:                aauth.pass = NULL;
                    986:        }
                    987:
                    988:        if (auth_url(*auth, &response, &aauth) == 0) {
                    989:                *rval = fetch_url(url, penv,
                    990:                    hcode == 401 ? pauth->auth : response,
                    991:                    hcode == 401 ? response: wauth->auth);
                    992:                memset(response, 0, strlen(response));
                    993:                FREEPTR(response);
                    994:        }
                    995: }
                    996: #endif
                    997:
1.218     christos  998: static int
1.215     christos  999: negotiate_connection(FETCH *fin, const char *url, const char *penv,
1.218     christos 1000:     struct posinfo *pi, time_t *mtime, struct authinfo *wauth,
1.222     christos 1001:     struct authinfo *pauth, volatile int *rval, volatile int *ischunked,
                   1002:     char **auth)
1.215     christos 1003: {
                   1004:        int                     len, hcode, rv;
                   1005:        char                    buf[FTPBUFLEN], *ep;
                   1006:        const char              *cp, *token;
                   1007:        char                    *location, *message;
                   1008:
                   1009:        *auth = message = location = NULL;
                   1010:
                   1011:        /* Read the response */
                   1012:        ep = buf;
                   1013:        switch (getresponse(fin, &ep, sizeof(buf), &hcode)) {
                   1014:        case C_CLEANUP:
                   1015:                goto cleanup_fetch_url;
                   1016:        case C_IMPROPER:
1.214     christos 1017:                goto improper;
1.215     christos 1018:        case C_OK:
                   1019:                message = ftp_strdup(ep);
                   1020:                break;
                   1021:        }
1.214     christos 1022:
                   1023:        /* Read the rest of the header. */
                   1024:
                   1025:        for (;;) {
1.215     christos 1026:                if ((rv = getresponseline(fin, buf, sizeof(buf), &len)) != C_OK)
1.214     christos 1027:                        goto cleanup_fetch_url;
                   1028:                if (len == 0)
                   1029:                        break;
                   1030:
                   1031:        /*
                   1032:         * Look for some headers
                   1033:         */
                   1034:
                   1035:                cp = buf;
                   1036:
                   1037:                if (match_token(&cp, "Content-Length:")) {
                   1038:                        filesize = STRTOLL(cp, &ep, 10);
                   1039:                        if (filesize < 0 || *ep != '\0')
                   1040:                                goto improper;
                   1041:                        DPRINTF("%s: parsed len as: " LLF "\n",
                   1042:                            __func__, (LLT)filesize);
                   1043:
                   1044:                } else if (match_token(&cp, "Content-Range:")) {
1.218     christos 1045:                        if (parse_posinfo(&cp, pi) == -1)
1.214     christos 1046:                                goto improper;
                   1047:                        if (! restart_point) {
                   1048:                                warnx(
                   1049:                            "Received unexpected Content-Range header");
                   1050:                                goto cleanup_fetch_url;
                   1051:                        }
                   1052:
                   1053:                } else if (match_token(&cp, "Last-Modified:")) {
                   1054:                        getmtime(cp, mtime);
                   1055:
                   1056:                } else if (match_token(&cp, "Location:")) {
                   1057:                        location = ftp_strdup(cp);
                   1058:                        DPRINTF("%s: parsed location as `%s'\n",
                   1059:                            __func__, cp);
                   1060:
                   1061:                } else if (match_token(&cp, "Transfer-Encoding:")) {
                   1062:                        if (match_token(&cp, "binary")) {
                   1063:                                warnx(
                   1064:                "Bogus transfer encoding `binary' (fetching anyway)");
                   1065:                                continue;
                   1066:                        }
                   1067:                        if (! (token = match_token(&cp, "chunked"))) {
                   1068:                                warnx(
                   1069:                            "Unsupported transfer encoding `%s'",
                   1070:                                    token);
                   1071:                                goto cleanup_fetch_url;
                   1072:                        }
                   1073:                        (*ischunked)++;
                   1074:                        DPRINTF("%s: using chunked encoding\n",
                   1075:                            __func__);
                   1076:
                   1077:                } else if (match_token(&cp, "Proxy-Authenticate:")
                   1078:                        || match_token(&cp, "WWW-Authenticate:")) {
                   1079:                        if (! (token = match_token(&cp, "Basic"))) {
                   1080:                                DPRINTF("%s: skipping unknown auth "
                   1081:                                    "scheme `%s'\n", __func__, token);
                   1082:                                continue;
                   1083:                        }
1.215     christos 1084:                        FREEPTR(*auth);
                   1085:                        *auth = ftp_strdup(token);
1.214     christos 1086:                        DPRINTF("%s: parsed auth as `%s'\n",
                   1087:                            __func__, cp);
                   1088:                }
                   1089:
                   1090:        }
                   1091:                        /* finished parsing header */
                   1092:
                   1093:        switch (hcode) {
                   1094:        case 200:
                   1095:                break;
                   1096:        case 206:
                   1097:                if (! restart_point) {
                   1098:                        warnx("Not expecting partial content header");
                   1099:                        goto cleanup_fetch_url;
                   1100:                }
                   1101:                break;
                   1102:        case 300:
                   1103:        case 301:
                   1104:        case 302:
                   1105:        case 303:
                   1106:        case 305:
                   1107:        case 307:
                   1108:                if (EMPTYSTRING(location)) {
                   1109:                        warnx(
                   1110:                        "No redirection Location provided by server");
                   1111:                        goto cleanup_fetch_url;
                   1112:                }
                   1113:                if (redirect_loop++ > 5) {
                   1114:                        warnx("Too many redirections requested");
                   1115:                        goto cleanup_fetch_url;
                   1116:                }
                   1117:                if (hcode == 305) {
                   1118:                        if (verbose)
                   1119:                                fprintf(ttyout, "Redirected via %s\n",
                   1120:                                    location);
                   1121:                        *rval = fetch_url(url, location,
                   1122:                            pauth->auth, wauth->auth);
                   1123:                } else {
                   1124:                        if (verbose)
                   1125:                                fprintf(ttyout, "Redirected to %s\n",
                   1126:                                    location);
                   1127:                        *rval = go_fetch(location);
                   1128:                }
                   1129:                goto cleanup_fetch_url;
                   1130: #ifndef NO_AUTH
                   1131:        case 401:
                   1132:        case 407:
1.228     nonaka   1133:                do_auth(hcode, url, penv, wauth, pauth, auth, message, rval);
1.214     christos 1134:                goto cleanup_fetch_url;
                   1135: #endif
                   1136:        default:
                   1137:                if (message)
                   1138:                        warnx("Error retrieving file `%s'", message);
                   1139:                else
                   1140:                        warnx("Unknown error retrieving file");
                   1141:                goto cleanup_fetch_url;
                   1142:        }
                   1143:        rv = C_OK;
                   1144:        goto out;
                   1145:
                   1146: cleanup_fetch_url:
                   1147:        rv = C_CLEANUP;
                   1148:        goto out;
                   1149: improper:
                   1150:        rv = C_IMPROPER;
                   1151:        goto out;
                   1152: out:
                   1153:        FREEPTR(message);
                   1154:        FREEPTR(location);
                   1155:        return rv;
                   1156: }              /* end of ftp:// or http:// specific setup */
                   1157:
1.215     christos 1158: #ifdef WITH_SSL
                   1159: static int
1.228     nonaka   1160: connectmethod(FETCH *fin, const char *url, const char *penv,
                   1161:     struct urlinfo *oui, struct urlinfo *ui, struct authinfo *wauth,
                   1162:     struct authinfo *pauth, char **auth, int *hasleading, volatile int *rval)
1.215     christos 1163: {
                   1164:        void *ssl;
                   1165:        int hcode, rv;
                   1166:        const char *cp;
                   1167:        char buf[FTPBUFLEN], *ep;
                   1168:        char *message = NULL;
                   1169:
1.217     christos 1170:        print_connect(fin, oui);
1.215     christos 1171:
                   1172:        print_agent(fin);
1.216     nonaka   1173:        *hasleading = print_proxy(fin, *hasleading, NULL, pauth->auth);
1.215     christos 1174:
                   1175:        if (verbose && *hasleading)
                   1176:                fputs(")\n", ttyout);
                   1177:        *hasleading = 0;
                   1178:
                   1179:        fetch_printf(fin, "\r\n");
                   1180:        if (fetch_flush(fin) == EOF) {
                   1181:                warn("Writing HTTP request");
                   1182:                alarmtimer(0);
                   1183:                goto cleanup_fetch_url;
                   1184:        }
                   1185:        alarmtimer(0);
                   1186:
                   1187:        /* Read the response */
                   1188:        ep = buf;
                   1189:        switch (getresponse(fin, &ep, sizeof(buf), &hcode)) {
                   1190:        case C_CLEANUP:
                   1191:                goto cleanup_fetch_url;
                   1192:        case C_IMPROPER:
                   1193:                goto improper;
                   1194:        case C_OK:
                   1195:                message = ftp_strdup(ep);
                   1196:                break;
                   1197:        }
                   1198:
                   1199:        for (;;) {
                   1200:                int len;
                   1201:                if (getresponseline(fin, buf, sizeof(buf), &len) != C_OK)
                   1202:                        goto cleanup_fetch_url;
                   1203:                if (len == 0)
                   1204:                        break;
1.221     nonaka   1205:
                   1206:                cp = buf;
1.215     christos 1207:                if (match_token(&cp, "Proxy-Authenticate:")) {
                   1208:                        const char *token;
                   1209:                        if (!(token = match_token(&cp, "Basic"))) {
                   1210:                                DPRINTF(
                   1211:                                    "%s: skipping unknown auth scheme `%s'\n",
                   1212:                                    __func__, token);
                   1213:                                continue;
                   1214:                        }
                   1215:                        FREEPTR(*auth);
                   1216:                        *auth = ftp_strdup(token);
                   1217:                        DPRINTF("%s: parsed auth as " "`%s'\n", __func__, cp);
                   1218:                }
                   1219:        }
                   1220:
                   1221:        /* finished parsing header */
                   1222:        switch (hcode) {
                   1223:        case 200:
                   1224:                break;
1.226     nonaka   1225: #ifndef NO_AUTH
                   1226:        case 407:
1.228     nonaka   1227:                do_auth(hcode, url, penv, wauth, pauth, auth, message, rval);
1.226     nonaka   1228:                goto cleanup_fetch_url;
                   1229: #endif
1.215     christos 1230:        default:
                   1231:                if (message)
                   1232:                        warnx("Error proxy connect " "`%s'", message);
                   1233:                else
                   1234:                        warnx("Unknown error proxy " "connect");
                   1235:                goto cleanup_fetch_url;
                   1236:        }
                   1237:
1.228     nonaka   1238:        if ((ssl = fetch_start_ssl(fetch_fileno(fin), oui->host)) == NULL)
1.215     christos 1239:                goto cleanup_fetch_url;
                   1240:        fetch_set_ssl(fin, ssl);
                   1241:
                   1242:        rv = C_OK;
                   1243:        goto out;
                   1244: improper:
                   1245:        rv = C_IMPROPER;
                   1246:        goto out;
                   1247: cleanup_fetch_url:
                   1248:        rv = C_CLEANUP;
                   1249:        goto out;
                   1250: out:
                   1251:        FREEPTR(message);
                   1252:        return rv;
                   1253: }
                   1254: #endif
1.214     christos 1255:
1.1       lukem    1256: /*
1.50      lukem    1257:  * Retrieve URL, via a proxy if necessary, using HTTP.
                   1258:  * If proxyenv is set, use that for the proxy, otherwise try ftp_proxy or
1.200     christos 1259:  * http_proxy/https_proxy as appropriate.
1.50      lukem    1260:  * Supports HTTP redirects.
1.127     tacha    1261:  * Returns 1 on failure, 0 on completed xfer, -1 if ftp connection
1.41      lukem    1262:  * is still open (e.g, ftp xfer with trailing /)
1.1       lukem    1263:  */
1.12      lukem    1264: static int
1.111     lukem    1265: fetch_url(const char *url, const char *proxyenv, char *proxyauth, char *wwwauth)
1.1       lukem    1266: {
1.203     christos 1267:        sigfunc volatile        oldint;
                   1268:        sigfunc volatile        oldpipe;
                   1269:        sigfunc volatile        oldalrm;
                   1270:        sigfunc volatile        oldquit;
1.173     christos 1271:        int volatile            s;
1.95      lukem    1272:        struct stat             sb;
1.173     christos 1273:        int volatile            isproxy;
1.222     christos 1274:        int volatile            rval, ischunked;
1.187     lukem    1275:        size_t                  flen;
1.73      lukem    1276:        static size_t           bufsize;
                   1277:        static char             *xferbuf;
1.214     christos 1278:        const char              *cp;
1.173     christos 1279:        char                    *ep;
1.215     christos 1280:        char                    *auth;
1.173     christos 1281:        char                    *volatile savefile;
                   1282:        char                    *volatile location;
                   1283:        char                    *volatile message;
                   1284:        char                    *volatile decodedpath;
1.214     christos 1285:        struct authinfo         wauth, pauth;
1.218     christos 1286:        struct posinfo          pi;
                   1287:        off_t                   hashbytes;
1.173     christos 1288:        int                     (*volatile closefunc)(FILE *);
1.199     christos 1289:        FETCH                   *volatile fin;
1.173     christos 1290:        FILE                    *volatile fout;
1.203     christos 1291:        const char              *volatile penv = proxyenv;
1.216     nonaka   1292:        struct urlinfo          ui, oui;
1.42      lukem    1293:        time_t                  mtime;
1.210     christos 1294:        void                    *ssl = NULL;
1.1       lukem    1295:
1.203     christos 1296:        DPRINTF("%s: `%s' proxyenv `%s'\n", __func__, url, STRorNULL(penv));
1.183     lukem    1297:
1.203     christos 1298:        oldquit = oldalrm = oldint = oldpipe = NULL;
1.22      lukem    1299:        closefunc = NULL;
1.199     christos 1300:        fin = NULL;
                   1301:        fout = NULL;
1.1       lukem    1302:        s = -1;
1.176     lukem    1303:        savefile = NULL;
1.44      lukem    1304:        auth = location = message = NULL;
1.214     christos 1305:        ischunked = isproxy = 0;
1.42      lukem    1306:        rval = 1;
1.214     christos 1307:
                   1308:        initurlinfo(&ui);
1.225     christos 1309:        initurlinfo(&oui);
1.214     christos 1310:        initauthinfo(&wauth, wwwauth);
                   1311:        initauthinfo(&pauth, proxyauth);
                   1312:
1.215     christos 1313:        decodedpath = NULL;
1.1       lukem    1314:
1.203     christos 1315:        if (sigsetjmp(httpabort, 1))
                   1316:                goto cleanup_fetch_url;
                   1317:
1.214     christos 1318:        if (parse_url(url, "URL", &ui, &wauth) == -1)
1.42      lukem    1319:                goto cleanup_fetch_url;
1.5       lukem    1320:
1.216     nonaka   1321:        copyurlinfo(&oui, &ui);
1.215     christos 1322:
1.214     christos 1323:        if (ui.utype == FILE_URL_T && ! EMPTYSTRING(ui.host)
                   1324:            && strcasecmp(ui.host, "localhost") != 0) {
1.27      lukem    1325:                warnx("No support for non local file URL `%s'", url);
1.42      lukem    1326:                goto cleanup_fetch_url;
1.9       lukem    1327:        }
1.27      lukem    1328:
1.214     christos 1329:        if (EMPTYSTRING(ui.path)) {
                   1330:                if (ui.utype == FTP_URL_T) {
1.52      lukem    1331:                        rval = fetch_ftp(url);
1.42      lukem    1332:                        goto cleanup_fetch_url;
                   1333:                }
1.214     christos 1334:                if (!IS_HTTP_TYPE(ui.utype) || outfile == NULL)  {
1.27      lukem    1335:                        warnx("Invalid URL (no file after host) `%s'", url);
1.42      lukem    1336:                        goto cleanup_fetch_url;
1.27      lukem    1337:                }
1.9       lukem    1338:        }
1.1       lukem    1339:
1.214     christos 1340:        decodedpath = ftp_strdup(ui.path);
1.50      lukem    1341:        url_decode(decodedpath);
                   1342:
1.22      lukem    1343:        if (outfile)
1.206     christos 1344:                savefile = outfile;
1.22      lukem    1345:        else {
1.50      lukem    1346:                cp = strrchr(decodedpath, '/');         /* find savefile */
1.29      lukem    1347:                if (cp != NULL)
1.166     christos 1348:                        savefile = ftp_strdup(cp + 1);
1.22      lukem    1349:                else
1.166     christos 1350:                        savefile = ftp_strdup(decodedpath);
1.227     christos 1351:                /*
                   1352:                 * Use the first URL we requested not the name after a
                   1353:                 * possible redirect, but careful to save it because our
                   1354:                 * "safety" check is the match to outfile.
                   1355:                 */
                   1356:                outfile = ftp_strdup(savefile);
1.22      lukem    1357:        }
1.203     christos 1358:        DPRINTF("%s: savefile `%s'\n", __func__, savefile);
1.9       lukem    1359:        if (EMPTYSTRING(savefile)) {
1.214     christos 1360:                if (ui.utype == FTP_URL_T) {
1.52      lukem    1361:                        rval = fetch_ftp(url);
1.42      lukem    1362:                        goto cleanup_fetch_url;
                   1363:                }
1.175     lukem    1364:                warnx("No file after directory (you must specify an "
1.140     grant    1365:                    "output file) `%s'", url);
1.42      lukem    1366:                goto cleanup_fetch_url;
1.9       lukem    1367:        }
1.1       lukem    1368:
1.95      lukem    1369:        restart_point = 0;
1.25      lukem    1370:        filesize = -1;
1.218     christos 1371:        initposinfo(&pi);
1.25      lukem    1372:        mtime = -1;
1.95      lukem    1373:        if (restartautofetch) {
1.206     christos 1374:                if (stat(savefile, &sb) == 0)
1.95      lukem    1375:                        restart_point = sb.st_size;
                   1376:        }
1.214     christos 1377:        if (ui.utype == FILE_URL_T) {           /* file:// URLs */
1.25      lukem    1378:                direction = "copied";
1.199     christos 1379:                fin = fetch_open(decodedpath, "r");
1.25      lukem    1380:                if (fin == NULL) {
1.175     lukem    1381:                        warn("Can't open `%s'", decodedpath);
1.42      lukem    1382:                        goto cleanup_fetch_url;
1.5       lukem    1383:                }
1.199     christos 1384:                if (fstat(fetch_fileno(fin), &sb) == 0) {
1.25      lukem    1385:                        mtime = sb.st_mtime;
                   1386:                        filesize = sb.st_size;
                   1387:                }
1.95      lukem    1388:                if (restart_point) {
1.199     christos 1389:                        if (lseek(fetch_fileno(fin), restart_point, SEEK_SET) < 0) {
1.175     lukem    1390:                                warn("Can't seek to restart `%s'",
1.95      lukem    1391:                                    decodedpath);
                   1392:                                goto cleanup_fetch_url;
                   1393:                        }
                   1394:                }
                   1395:                if (verbose) {
                   1396:                        fprintf(ttyout, "Copying %s", decodedpath);
                   1397:                        if (restart_point)
1.121     lukem    1398:                                fprintf(ttyout, " (restarting at " LLF ")",
                   1399:                                    (LLT)restart_point);
1.95      lukem    1400:                        fputs("\n", ttyout);
                   1401:                }
1.199     christos 1402:                if (0 == rcvbuf_size) {
                   1403:                        rcvbuf_size = 8 * 1024; /* XXX */
                   1404:                }
1.25      lukem    1405:        } else {                                /* ftp:// or http:// URLs */
1.65      lukem    1406:                int hasleading;
                   1407:
1.203     christos 1408:                if (penv == NULL) {
1.201     christos 1409: #ifdef WITH_SSL
1.214     christos 1410:                        if (ui.utype == HTTPS_URL_T)
1.203     christos 1411:                                penv = getoptionvalue("https_proxy");
1.201     christos 1412: #endif
1.214     christos 1413:                        if (penv == NULL && IS_HTTP_TYPE(ui.utype))
1.203     christos 1414:                                penv = getoptionvalue("http_proxy");
1.214     christos 1415:                        else if (ui.utype == FTP_URL_T)
1.203     christos 1416:                                penv = getoptionvalue("ftp_proxy");
1.42      lukem    1417:                }
1.25      lukem    1418:                direction = "retrieved";
1.203     christos 1419:                if (! EMPTYSTRING(penv)) {                      /* use proxy */
1.27      lukem    1420:
1.214     christos 1421:                        isproxy = handle_noproxy(ui.host, ui.portnum);
1.27      lukem    1422:
1.214     christos 1423:                        if (isproxy == 0 && ui.utype == FTP_URL_T) {
1.211     christos 1424:                                rval = fetch_ftp(url);
                   1425:                                goto cleanup_fetch_url;
1.25      lukem    1426:                        }
1.1       lukem    1427:
1.27      lukem    1428:                        if (isproxy) {
1.180     lukem    1429:                                if (restart_point) {
1.212     christos 1430:                                        warnx(
                   1431:                                            "Can't restart via proxy URL `%s'",
1.203     christos 1432:                                            penv);
1.180     lukem    1433:                                        goto cleanup_fetch_url;
                   1434:                                }
1.214     christos 1435:                                if (handle_proxy(url, penv, &ui, &pauth) < 0)
1.112     itojun   1436:                                        goto cleanup_fetch_url;
1.27      lukem    1437:                        }
1.203     christos 1438:                } /* ! EMPTYSTRING(penv) */
1.25      lukem    1439:
1.214     christos 1440:                s = ftp_socket(&ui, &ssl);
1.98      itojun   1441:                if (s < 0) {
1.214     christos 1442:                        warnx("Can't connect to `%s:%s'", ui.host, ui.port);
1.98      itojun   1443:                        goto cleanup_fetch_url;
                   1444:                }
1.24      lukem    1445:
1.203     christos 1446:                oldalrm = xsignal(SIGALRM, timeouthttp);
                   1447:                alarmtimer(quit_time ? quit_time : 60);
1.199     christos 1448:                fin = fetch_fdopen(s, "r+");
                   1449:                fetch_set_ssl(fin, ssl);
1.203     christos 1450:                alarmtimer(0);
1.199     christos 1451:
1.203     christos 1452:                alarmtimer(quit_time ? quit_time : 60);
1.25      lukem    1453:                /*
1.27      lukem    1454:                 * Construct and send the request.
1.25      lukem    1455:                 */
1.65      lukem    1456:                if (verbose)
                   1457:                        fprintf(ttyout, "Requesting %s\n", url);
1.112     itojun   1458:
1.215     christos 1459:                hasleading = 0;
                   1460: #ifdef WITH_SSL
                   1461:                if (isproxy && oui.utype == HTTPS_URL_T) {
1.228     nonaka   1462:                        switch (connectmethod(fin, url, penv, &oui, &ui,
                   1463:                            &wauth, &pauth, &auth, &hasleading, &rval)) {
1.215     christos 1464:                        case C_CLEANUP:
                   1465:                                goto cleanup_fetch_url;
                   1466:                        case C_IMPROPER:
                   1467:                                goto improper;
                   1468:                        case C_OK:
                   1469:                                break;
                   1470:                        default:
                   1471:                                abort();
                   1472:                        }
                   1473:                }
                   1474: #endif
                   1475:
1.216     nonaka   1476:                hasleading = print_get(fin, hasleading, isproxy, &oui, &ui);
1.214     christos 1477:
                   1478:                if (flushcache)
                   1479:                        print_cache(fin, isproxy);
                   1480:
                   1481:                print_agent(fin);
1.216     nonaka   1482:                hasleading = print_proxy(fin, hasleading, wauth.auth,
1.215     christos 1483:                     auth ? NULL : pauth.auth);
1.214     christos 1484:                if (hasleading) {
1.216     nonaka   1485:                        hasleading = 0;
1.214     christos 1486:                        if (verbose)
                   1487:                                fputs(")\n", ttyout);
1.25      lukem    1488:                }
1.214     christos 1489:
1.199     christos 1490:                fetch_printf(fin, "\r\n");
                   1491:                if (fetch_flush(fin) == EOF) {
1.25      lukem    1492:                        warn("Writing HTTP request");
1.203     christos 1493:                        alarmtimer(0);
1.42      lukem    1494:                        goto cleanup_fetch_url;
1.25      lukem    1495:                }
1.203     christos 1496:                alarmtimer(0);
1.1       lukem    1497:
1.218     christos 1498:                switch (negotiate_connection(fin, url, penv, &pi,
1.215     christos 1499:                    &mtime, &wauth, &pauth, &rval, &ischunked, &auth)) {
1.214     christos 1500:                case C_OK:
                   1501:                        break;
                   1502:                case C_CLEANUP:
1.42      lukem    1503:                        goto cleanup_fetch_url;
1.214     christos 1504:                case C_IMPROPER:
1.42      lukem    1505:                        goto improper;
1.52      lukem    1506:                default:
1.214     christos 1507:                        abort();
1.44      lukem    1508:                }
1.214     christos 1509:        }
1.42      lukem    1510:
1.206     christos 1511:        /* Open the output file. */
                   1512:
                   1513:        /*
                   1514:         * Only trust filenames with special meaning if they came from
                   1515:         * the command line
                   1516:         */
                   1517:        if (outfile == savefile) {
                   1518:                if (strcmp(savefile, "-") == 0) {
                   1519:                        fout = stdout;
                   1520:                } else if (*savefile == '|') {
                   1521:                        oldpipe = xsignal(SIGPIPE, SIG_IGN);
                   1522:                        fout = popen(savefile + 1, "w");
                   1523:                        if (fout == NULL) {
                   1524:                                warn("Can't execute `%s'", savefile + 1);
                   1525:                                goto cleanup_fetch_url;
                   1526:                        }
                   1527:                        closefunc = pclose;
1.22      lukem    1528:                }
1.206     christos 1529:        }
                   1530:        if (fout == NULL) {
1.218     christos 1531:                if ((pi.rangeend != -1 && pi.rangeend <= restart_point) ||
                   1532:                    (pi.rangestart == -1 &&
                   1533:                    filesize != -1 && filesize <= restart_point)) {
1.129     yamt     1534:                        /* already done */
                   1535:                        if (verbose)
                   1536:                                fprintf(ttyout, "already done\n");
                   1537:                        rval = 0;
                   1538:                        goto cleanup_fetch_url;
                   1539:                }
1.218     christos 1540:                if (restart_point && pi.rangestart != -1) {
                   1541:                        if (pi.entitylen != -1)
                   1542:                                filesize = pi.entitylen;
                   1543:                        if (pi.rangestart != restart_point) {
1.95      lukem    1544:                                warnx(
                   1545:                                    "Size of `%s' differs from save file `%s'",
                   1546:                                    url, savefile);
                   1547:                                goto cleanup_fetch_url;
                   1548:                        }
                   1549:                        fout = fopen(savefile, "a");
                   1550:                } else
                   1551:                        fout = fopen(savefile, "w");
1.22      lukem    1552:                if (fout == NULL) {
1.27      lukem    1553:                        warn("Can't open `%s'", savefile);
1.42      lukem    1554:                        goto cleanup_fetch_url;
1.22      lukem    1555:                }
                   1556:                closefunc = fclose;
1.1       lukem    1557:        }
                   1558:
1.22      lukem    1559:                        /* Trap signals */
1.203     christos 1560:        oldquit = xsignal(SIGQUIT, psummary);
                   1561:        oldint = xsignal(SIGINT, aborthttp);
1.2       lukem    1562:
1.195     lukem    1563:        assert(rcvbuf_size > 0);
1.187     lukem    1564:        if ((size_t)rcvbuf_size > bufsize) {
1.73      lukem    1565:                if (xferbuf)
                   1566:                        (void)free(xferbuf);
                   1567:                bufsize = rcvbuf_size;
1.166     christos 1568:                xferbuf = ftp_malloc(bufsize);
1.73      lukem    1569:        }
                   1570:
1.1       lukem    1571:        bytes = 0;
                   1572:        hashbytes = mark;
1.204     christos 1573:        if (oldalrm) {
                   1574:                (void)xsignal(SIGALRM, oldalrm);
                   1575:                oldalrm = NULL;
                   1576:        }
1.1       lukem    1577:        progressmeter(-1);
1.2       lukem    1578:
1.24      lukem    1579:                        /* Finally, suck down the file. */
1.45      lukem    1580:        do {
1.77      lukem    1581:                long chunksize;
1.181     lukem    1582:                short lastchunk;
1.45      lukem    1583:
                   1584:                chunksize = 0;
1.181     lukem    1585:                lastchunk = 0;
                   1586:                                        /* read chunk-size */
1.45      lukem    1587:                if (ischunked) {
1.199     christos 1588:                        if (fetch_getln(xferbuf, bufsize, fin) == NULL) {
1.181     lukem    1589:                                warnx("Unexpected EOF reading chunk-size");
1.45      lukem    1590:                                goto cleanup_fetch_url;
                   1591:                        }
1.181     lukem    1592:                        errno = 0;
1.73      lukem    1593:                        chunksize = strtol(xferbuf, &ep, 16);
1.181     lukem    1594:                        if (ep == xferbuf) {
                   1595:                                warnx("Invalid chunk-size");
                   1596:                                goto cleanup_fetch_url;
                   1597:                        }
                   1598:                        if (errno == ERANGE || chunksize < 0) {
                   1599:                                errno = ERANGE;
                   1600:                                warn("Chunk-size `%.*s'",
1.182     lukem    1601:                                    (int)(ep-xferbuf), xferbuf);
1.181     lukem    1602:                                goto cleanup_fetch_url;
                   1603:                        }
1.103     lukem    1604:
                   1605:                                /*
1.123     lukem    1606:                                 * XXX: Work around bug in Apache 1.3.9 and
                   1607:                                 *      1.3.11, which incorrectly put trailing
1.181     lukem    1608:                                 *      space after the chunk-size.
1.103     lukem    1609:                                 */
1.123     lukem    1610:                        while (*ep == ' ')
1.103     lukem    1611:                                ep++;
                   1612:
1.181     lukem    1613:                                        /* skip [ chunk-ext ] */
                   1614:                        if (*ep == ';') {
                   1615:                                while (*ep && *ep != '\r')
                   1616:                                        ep++;
                   1617:                        }
                   1618:
1.45      lukem    1619:                        if (strcmp(ep, "\r\n") != 0) {
1.181     lukem    1620:                                warnx("Unexpected data following chunk-size");
1.45      lukem    1621:                                goto cleanup_fetch_url;
                   1622:                        }
1.203     christos 1623:                        DPRINTF("%s: got chunk-size of " LLF "\n", __func__,
1.183     lukem    1624:                            (LLT)chunksize);
1.181     lukem    1625:                        if (chunksize == 0) {
                   1626:                                lastchunk = 1;
                   1627:                                goto chunkdone;
                   1628:                        }
1.45      lukem    1629:                }
1.59      lukem    1630:                                        /* transfer file or chunk */
                   1631:                while (1) {
                   1632:                        struct timeval then, now, td;
1.205     christos 1633:                        volatile off_t bufrem;
1.59      lukem    1634:
1.71      lukem    1635:                        if (rate_get)
                   1636:                                (void)gettimeofday(&then, NULL);
1.187     lukem    1637:                        bufrem = rate_get ? rate_get : (off_t)bufsize;
1.101     lukem    1638:                        if (ischunked)
                   1639:                                bufrem = MIN(chunksize, bufrem);
1.59      lukem    1640:                        while (bufrem > 0) {
1.199     christos 1641:                                flen = fetch_read(xferbuf, sizeof(char),
1.187     lukem    1642:                                    MIN((off_t)bufsize, bufrem), fin);
                   1643:                                if (flen <= 0)
1.59      lukem    1644:                                        goto chunkdone;
1.187     lukem    1645:                                bytes += flen;
                   1646:                                bufrem -= flen;
                   1647:                                if (fwrite(xferbuf, sizeof(char), flen, fout)
                   1648:                                    != flen) {
1.59      lukem    1649:                                        warn("Writing `%s'", savefile);
                   1650:                                        goto cleanup_fetch_url;
                   1651:                                }
1.101     lukem    1652:                                if (hash && !progress) {
                   1653:                                        while (bytes >= hashbytes) {
                   1654:                                                (void)putc('#', ttyout);
                   1655:                                                hashbytes += mark;
                   1656:                                        }
                   1657:                                        (void)fflush(ttyout);
                   1658:                                }
                   1659:                                if (ischunked) {
1.187     lukem    1660:                                        chunksize -= flen;
1.101     lukem    1661:                                        if (chunksize <= 0)
                   1662:                                                break;
1.45      lukem    1663:                                }
1.59      lukem    1664:                        }
                   1665:                        if (rate_get) {
                   1666:                                while (1) {
                   1667:                                        (void)gettimeofday(&now, NULL);
                   1668:                                        timersub(&now, &then, &td);
                   1669:                                        if (td.tv_sec > 0)
                   1670:                                                break;
                   1671:                                        usleep(1000000 - td.tv_usec);
                   1672:                                }
                   1673:                        }
1.101     lukem    1674:                        if (ischunked && chunksize <= 0)
                   1675:                                break;
1.1       lukem    1676:                }
1.45      lukem    1677:                                        /* read CRLF after chunk*/
1.59      lukem    1678:  chunkdone:
1.45      lukem    1679:                if (ischunked) {
1.199     christos 1680:                        if (fetch_getln(xferbuf, bufsize, fin) == NULL) {
1.203     christos 1681:                                alarmtimer(0);
1.181     lukem    1682:                                warnx("Unexpected EOF reading chunk CRLF");
                   1683:                                goto cleanup_fetch_url;
                   1684:                        }
1.73      lukem    1685:                        if (strcmp(xferbuf, "\r\n") != 0) {
1.45      lukem    1686:                                warnx("Unexpected data following chunk");
                   1687:                                goto cleanup_fetch_url;
1.1       lukem    1688:                        }
1.181     lukem    1689:                        if (lastchunk)
                   1690:                                break;
1.1       lukem    1691:                }
1.45      lukem    1692:        } while (ischunked);
1.181     lukem    1693:
                   1694: /* XXX: deal with optional trailer & CRLF here? */
                   1695:
1.1       lukem    1696:        if (hash && !progress && bytes > 0) {
                   1697:                if (bytes < mark)
1.22      lukem    1698:                        (void)putc('#', ttyout);
                   1699:                (void)putc('\n', ttyout);
1.1       lukem    1700:        }
1.199     christos 1701:        if (fetch_error(fin)) {
1.25      lukem    1702:                warn("Reading file");
1.42      lukem    1703:                goto cleanup_fetch_url;
1.1       lukem    1704:        }
1.2       lukem    1705:        progressmeter(1);
1.25      lukem    1706:        (void)fflush(fout);
                   1707:        if (closefunc == fclose && mtime != -1) {
                   1708:                struct timeval tval[2];
                   1709:
                   1710:                (void)gettimeofday(&tval[0], NULL);
                   1711:                tval[1].tv_sec = mtime;
                   1712:                tval[1].tv_usec = 0;
1.31      lukem    1713:                (*closefunc)(fout);
                   1714:                fout = NULL;
                   1715:
                   1716:                if (utimes(savefile, tval) == -1) {
1.25      lukem    1717:                        fprintf(ttyout,
                   1718:                            "Can't change modification time to %s",
1.179     lukem    1719:                            rfc2822time(localtime(&mtime)));
1.25      lukem    1720:                }
                   1721:        }
                   1722:        if (bytes > 0)
                   1723:                ptransfer(0);
1.136     lukem    1724:        bytes = 0;
1.1       lukem    1725:
1.42      lukem    1726:        rval = 0;
                   1727:        goto cleanup_fetch_url;
1.11      lukem    1728:
1.118     lukem    1729:  improper:
1.214     christos 1730:        warnx("Improper response from `%s:%s'", ui.host, ui.port);
1.11      lukem    1731:
1.118     lukem    1732:  cleanup_fetch_url:
1.203     christos 1733:        if (oldint)
                   1734:                (void)xsignal(SIGINT, oldint);
                   1735:        if (oldpipe)
                   1736:                (void)xsignal(SIGPIPE, oldpipe);
                   1737:        if (oldalrm)
                   1738:                (void)xsignal(SIGALRM, oldalrm);
                   1739:        if (oldquit)
                   1740:                (void)xsignal(SIGQUIT, oldpipe);
1.24      lukem    1741:        if (fin != NULL)
1.199     christos 1742:                fetch_close(fin);
1.24      lukem    1743:        else if (s != -1)
1.1       lukem    1744:                close(s);
1.22      lukem    1745:        if (closefunc != NULL && fout != NULL)
                   1746:                (*closefunc)(fout);
1.206     christos 1747:        if (savefile != outfile)
                   1748:                FREEPTR(savefile);
1.214     christos 1749:        freeurlinfo(&ui);
1.215     christos 1750:        freeurlinfo(&oui);
1.214     christos 1751:        freeauthinfo(&wauth);
                   1752:        freeauthinfo(&pauth);
1.50      lukem    1753:        FREEPTR(decodedpath);
1.44      lukem    1754:        FREEPTR(auth);
1.42      lukem    1755:        FREEPTR(location);
                   1756:        FREEPTR(message);
                   1757:        return (rval);
1.1       lukem    1758: }
                   1759:
                   1760: /*
1.50      lukem    1761:  * Abort a HTTP retrieval
1.2       lukem    1762:  */
1.194     joerg    1763: static void
1.111     lukem    1764: aborthttp(int notused)
1.2       lukem    1765: {
1.88      lukem    1766:        char msgbuf[100];
1.203     christos 1767:        int len;
1.2       lukem    1768:
1.148     lukem    1769:        sigint_raised = 1;
1.2       lukem    1770:        alarmtimer(0);
1.203     christos 1771:        if (fromatty) {
                   1772:                len = snprintf(msgbuf, sizeof(msgbuf),
                   1773:                    "\n%s: HTTP fetch aborted.\n", getprogname());
                   1774:                if (len > 0)
                   1775:                        write(fileno(ttyout), msgbuf, len);
                   1776:        }
                   1777:        siglongjmp(httpabort, 1);
                   1778: }
                   1779:
                   1780: static void
                   1781: timeouthttp(int notused)
                   1782: {
                   1783:        char msgbuf[100];
                   1784:        int len;
                   1785:
                   1786:        alarmtimer(0);
                   1787:        if (fromatty) {
                   1788:                len = snprintf(msgbuf, sizeof(msgbuf),
                   1789:                    "\n%s: HTTP fetch timeout.\n", getprogname());
                   1790:                if (len > 0)
                   1791:                        write(fileno(ttyout), msgbuf, len);
                   1792:        }
1.88      lukem    1793:        siglongjmp(httpabort, 1);
1.2       lukem    1794: }
                   1795:
                   1796: /*
1.50      lukem    1797:  * Retrieve ftp URL or classic ftp argument using FTP.
1.63      lukem    1798:  * Returns 1 on failure, 0 on completed xfer, -1 if ftp connection
1.42      lukem    1799:  * is still open (e.g, ftp xfer with trailing /)
                   1800:  */
                   1801: static int
1.111     lukem    1802: fetch_ftp(const char *url)
1.42      lukem    1803: {
                   1804:        char            *cp, *xargv[5], rempath[MAXPATHLEN];
1.214     christos 1805:        char            *dir, *file;
1.187     lukem    1806:        char             cmdbuf[MAXPATHLEN];
                   1807:        char             dirbuf[4];
1.186     lukem    1808:        int              dirhasglob, filehasglob, rval, transtype, xargc;
1.160     lukem    1809:        int              oanonftp, oautologin;
1.214     christos 1810:        struct authinfo  auth;
                   1811:        struct urlinfo   ui;
1.42      lukem    1812:
1.183     lukem    1813:        DPRINTF("fetch_ftp: `%s'\n", url);
1.214     christos 1814:        dir = file = NULL;
1.42      lukem    1815:        rval = 1;
1.186     lukem    1816:        transtype = TYPE_I;
1.42      lukem    1817:
1.214     christos 1818:        initurlinfo(&ui);
                   1819:        initauthinfo(&auth, NULL);
                   1820:
1.150     lukem    1821:        if (STRNEQUAL(url, FTP_URL)) {
1.214     christos 1822:                if ((parse_url(url, "URL", &ui, &auth) == -1) ||
                   1823:                    (auth.user != NULL && *auth.user == '\0') ||
                   1824:                    EMPTYSTRING(ui.host)) {
1.42      lukem    1825:                        warnx("Invalid URL `%s'", url);
                   1826:                        goto cleanup_fetch_ftp;
                   1827:                }
1.53      lukem    1828:                /*
                   1829:                 * Note: Don't url_decode(path) here.  We need to keep the
                   1830:                 * distinction between "/" and "%2F" until later.
                   1831:                 */
                   1832:
                   1833:                                        /* check for trailing ';type=[aid]' */
1.214     christos 1834:                if (! EMPTYSTRING(ui.path) && (cp = strrchr(ui.path, ';')) != NULL) {
1.53      lukem    1835:                        if (strcasecmp(cp, ";type=a") == 0)
1.186     lukem    1836:                                transtype = TYPE_A;
1.53      lukem    1837:                        else if (strcasecmp(cp, ";type=i") == 0)
1.186     lukem    1838:                                transtype = TYPE_I;
1.53      lukem    1839:                        else if (strcasecmp(cp, ";type=d") == 0) {
                   1840:                                warnx(
                   1841:                            "Directory listing via a URL is not supported");
                   1842:                                goto cleanup_fetch_ftp;
                   1843:                        } else {
                   1844:                                warnx("Invalid suffix `%s' in URL `%s'", cp,
                   1845:                                    url);
                   1846:                                goto cleanup_fetch_ftp;
                   1847:                        }
                   1848:                        *cp = 0;
                   1849:                }
1.97      lukem    1850:        } else {                        /* classic style `[user@]host:[file]' */
1.214     christos 1851:                ui.utype = CLASSIC_URL_T;
                   1852:                ui.host = ftp_strdup(url);
                   1853:                cp = strchr(ui.host, '@');
1.97      lukem    1854:                if (cp != NULL) {
                   1855:                        *cp = '\0';
1.214     christos 1856:                        auth.user = ui.host;
1.97      lukem    1857:                        anonftp = 0;    /* disable anonftp */
1.214     christos 1858:                        ui.host = ftp_strdup(cp + 1);
1.97      lukem    1859:                }
1.214     christos 1860:                cp = strchr(ui.host, ':');
1.42      lukem    1861:                if (cp != NULL) {
                   1862:                        *cp = '\0';
1.214     christos 1863:                        ui.path = ftp_strdup(cp + 1);
1.42      lukem    1864:                }
                   1865:        }
1.214     christos 1866:        if (EMPTYSTRING(ui.host))
1.42      lukem    1867:                goto cleanup_fetch_ftp;
                   1868:
1.50      lukem    1869:                        /* Extract the file and (if present) directory name. */
1.214     christos 1870:        dir = ui.path;
1.42      lukem    1871:        if (! EMPTYSTRING(dir)) {
1.53      lukem    1872:                /*
1.97      lukem    1873:                 * If we are dealing with classic `[user@]host:[path]' syntax,
                   1874:                 * then a path of the form `/file' (resulting from input of the
                   1875:                 * form `host:/file') means that we should do "CWD /" before
                   1876:                 * retrieving the file.  So we set dir="/" and file="file".
1.53      lukem    1877:                 *
1.97      lukem    1878:                 * But if we are dealing with URLs like `ftp://host/path' then
                   1879:                 * a path of the form `/file' (resulting from a URL of the form
                   1880:                 * `ftp://host//file') means that we should do `CWD ' (with an
                   1881:                 * empty argument) before retrieving the file.  So we set
1.53      lukem    1882:                 * dir="" and file="file".
                   1883:                 *
1.97      lukem    1884:                 * If the path does not contain / at all, we set dir=NULL.
                   1885:                 * (We get a path without any slashes if we are dealing with
                   1886:                 * classic `[user@]host:[file]' or URL `ftp://host/file'.)
1.53      lukem    1887:                 *
1.97      lukem    1888:                 * In all other cases, we set dir to a string that does not
                   1889:                 * include the final '/' that separates the dir part from the
                   1890:                 * file part of the path.  (This will be the empty string if
                   1891:                 * and only if we are dealing with a path of the form `/file'
                   1892:                 * resulting from an URL of the form `ftp://host//file'.)
1.53      lukem    1893:                 */
1.42      lukem    1894:                cp = strrchr(dir, '/');
1.214     christos 1895:                if (cp == dir && ui.utype == CLASSIC_URL_T) {
1.50      lukem    1896:                        file = cp + 1;
1.187     lukem    1897:                        (void)strlcpy(dirbuf, "/", sizeof(dirbuf));
                   1898:                        dir = dirbuf;
1.50      lukem    1899:                } else if (cp != NULL) {
1.42      lukem    1900:                        *cp++ = '\0';
                   1901:                        file = cp;
                   1902:                } else {
                   1903:                        file = dir;
                   1904:                        dir = NULL;
                   1905:                }
1.63      lukem    1906:        } else
                   1907:                dir = NULL;
1.214     christos 1908:        if (ui.utype == FTP_URL_T && file != NULL) {
1.157     lukem    1909:                url_decode(file);
1.53      lukem    1910:                /* but still don't url_decode(dir) */
                   1911:        }
1.163     christos 1912:        DPRINTF("fetch_ftp: user `%s' pass `%s' host %s port %s "
                   1913:            "path `%s' dir `%s' file `%s'\n",
1.214     christos 1914:            STRorNULL(auth.user), STRorNULL(auth.pass),
                   1915:            STRorNULL(ui.host), STRorNULL(ui.port),
                   1916:            STRorNULL(ui.path), STRorNULL(dir), STRorNULL(file));
1.42      lukem    1917:
                   1918:        dirhasglob = filehasglob = 0;
1.224     maya     1919:        if (doglob &&
                   1920:            (ui.utype == CLASSIC_URL_T || ui.utype == FTP_URL_T)) {
1.42      lukem    1921:                if (! EMPTYSTRING(dir) && strpbrk(dir, "*?[]{}") != NULL)
                   1922:                        dirhasglob = 1;
                   1923:                if (! EMPTYSTRING(file) && strpbrk(file, "*?[]{}") != NULL)
                   1924:                        filehasglob = 1;
                   1925:        }
                   1926:
1.50      lukem    1927:                        /* Set up the connection */
1.160     lukem    1928:        oanonftp = anonftp;
1.50      lukem    1929:        if (connected)
                   1930:                disconnect(0, NULL);
1.160     lukem    1931:        anonftp = oanonftp;
1.187     lukem    1932:        (void)strlcpy(cmdbuf, getprogname(), sizeof(cmdbuf));
                   1933:        xargv[0] = cmdbuf;
1.214     christos 1934:        xargv[1] = ui.host;
1.50      lukem    1935:        xargv[2] = NULL;
                   1936:        xargc = 2;
1.214     christos 1937:        if (ui.port) {
                   1938:                xargv[2] = ui.port;
1.50      lukem    1939:                xargv[3] = NULL;
                   1940:                xargc = 3;
                   1941:        }
                   1942:        oautologin = autologin;
1.116     lukem    1943:                /* don't autologin in setpeer(), use ftp_login() below */
                   1944:        autologin = 0;
1.50      lukem    1945:        setpeer(xargc, xargv);
                   1946:        autologin = oautologin;
1.116     lukem    1947:        if ((connected == 0) ||
1.214     christos 1948:            (connected == 1 && !ftp_login(ui.host, auth.user, auth.pass))) {
1.189     drochner 1949:                warnx("Can't connect or login to host `%s:%s'",
1.214     christos 1950:                        ui.host, ui.port ? ui.port : "?");
1.50      lukem    1951:                goto cleanup_fetch_ftp;
                   1952:        }
1.42      lukem    1953:
1.186     lukem    1954:        switch (transtype) {
1.53      lukem    1955:        case TYPE_A:
1.118     lukem    1956:                setascii(1, xargv);
1.53      lukem    1957:                break;
                   1958:        case TYPE_I:
1.118     lukem    1959:                setbinary(1, xargv);
1.53      lukem    1960:                break;
                   1961:        default:
1.186     lukem    1962:                errx(1, "fetch_ftp: unknown transfer type %d", transtype);
1.53      lukem    1963:        }
                   1964:
1.63      lukem    1965:                /*
                   1966:                 * Change directories, if necessary.
                   1967:                 *
                   1968:                 * Note: don't use EMPTYSTRING(dir) below, because
                   1969:                 * dir=="" means something different from dir==NULL.
                   1970:                 */
1.53      lukem    1971:        if (dir != NULL && !dirhasglob) {
                   1972:                char *nextpart;
1.42      lukem    1973:
1.53      lukem    1974:                /*
1.97      lukem    1975:                 * If we are dealing with a classic `[user@]host:[path]'
                   1976:                 * (urltype is CLASSIC_URL_T) then we have a raw directory
1.53      lukem    1977:                 * name (not encoded in any way) and we can change
                   1978:                 * directories in one step.
                   1979:                 *
                   1980:                 * If we are dealing with an `ftp://host/path' URL
1.193     lukem    1981:                 * (urltype is FTP_URL_T), then RFC 3986 says we need to
1.53      lukem    1982:                 * send a separate CWD command for each unescaped "/"
                   1983:                 * in the path, and we have to interpret %hex escaping
                   1984:                 * *after* we find the slashes.  It's possible to get
                   1985:                 * empty components here, (from multiple adjacent
1.193     lukem    1986:                 * slashes in the path) and RFC 3986 says that we should
1.53      lukem    1987:                 * still do `CWD ' (with a null argument) in such cases.
                   1988:                 *
1.63      lukem    1989:                 * Many ftp servers don't support `CWD ', so if there's an
                   1990:                 * error performing that command, bail out with a descriptive
                   1991:                 * message.
1.53      lukem    1992:                 *
                   1993:                 * Examples:
                   1994:                 *
1.63      lukem    1995:                 * host:                        dir="", urltype=CLASSIC_URL_T
                   1996:                 *              logged in (to default directory)
1.53      lukem    1997:                 * host:file                    dir=NULL, urltype=CLASSIC_URL_T
                   1998:                 *              "RETR file"
1.63      lukem    1999:                 * host:dir/                    dir="dir", urltype=CLASSIC_URL_T
                   2000:                 *              "CWD dir", logged in
                   2001:                 * ftp://host/                  dir="", urltype=FTP_URL_T
                   2002:                 *              logged in (to default directory)
                   2003:                 * ftp://host/dir/              dir="dir", urltype=FTP_URL_T
                   2004:                 *              "CWD dir", logged in
1.53      lukem    2005:                 * ftp://host/file              dir=NULL, urltype=FTP_URL_T
                   2006:                 *              "RETR file"
                   2007:                 * ftp://host//file             dir="", urltype=FTP_URL_T
1.63      lukem    2008:                 *              "CWD ", "RETR file"
1.53      lukem    2009:                 * host:/file                   dir="/", urltype=CLASSIC_URL_T
                   2010:                 *              "CWD /", "RETR file"
                   2011:                 * ftp://host///file            dir="/", urltype=FTP_URL_T
1.63      lukem    2012:                 *              "CWD ", "CWD ", "RETR file"
1.53      lukem    2013:                 * ftp://host/%2F/file          dir="%2F", urltype=FTP_URL_T
                   2014:                 *              "CWD /", "RETR file"
                   2015:                 * ftp://host/foo/file          dir="foo", urltype=FTP_URL_T
                   2016:                 *              "CWD foo", "RETR file"
                   2017:                 * ftp://host/foo/bar/file      dir="foo/bar"
                   2018:                 *              "CWD foo", "CWD bar", "RETR file"
                   2019:                 * ftp://host//foo/bar/file     dir="/foo/bar"
1.63      lukem    2020:                 *              "CWD ", "CWD foo", "CWD bar", "RETR file"
1.53      lukem    2021:                 * ftp://host/foo//bar/file     dir="foo//bar"
1.63      lukem    2022:                 *              "CWD foo", "CWD ", "CWD bar", "RETR file"
1.53      lukem    2023:                 * ftp://host/%2F/foo/bar/file  dir="%2F/foo/bar"
                   2024:                 *              "CWD /", "CWD foo", "CWD bar", "RETR file"
                   2025:                 * ftp://host/%2Ffoo/bar/file   dir="%2Ffoo/bar"
                   2026:                 *              "CWD /foo", "CWD bar", "RETR file"
                   2027:                 * ftp://host/%2Ffoo%2Fbar/file dir="%2Ffoo%2Fbar"
                   2028:                 *              "CWD /foo/bar", "RETR file"
                   2029:                 * ftp://host/%2Ffoo%2Fbar%2Ffile       dir=NULL
                   2030:                 *              "RETR /foo/bar/file"
                   2031:                 *
                   2032:                 * Note that we don't need `dir' after this point.
                   2033:                 */
                   2034:                do {
1.214     christos 2035:                        if (ui.utype == FTP_URL_T) {
1.53      lukem    2036:                                nextpart = strchr(dir, '/');
                   2037:                                if (nextpart) {
                   2038:                                        *nextpart = '\0';
                   2039:                                        nextpart++;
                   2040:                                }
                   2041:                                url_decode(dir);
                   2042:                        } else
                   2043:                                nextpart = NULL;
1.183     lukem    2044:                        DPRINTF("fetch_ftp: dir `%s', nextpart `%s'\n",
                   2045:                            STRorNULL(dir), STRorNULL(nextpart));
1.214     christos 2046:                        if (ui.utype == FTP_URL_T || *dir != '\0') {
1.187     lukem    2047:                                (void)strlcpy(cmdbuf, "cd", sizeof(cmdbuf));
                   2048:                                xargv[0] = cmdbuf;
1.53      lukem    2049:                                xargv[1] = dir;
                   2050:                                xargv[2] = NULL;
                   2051:                                dirchange = 0;
                   2052:                                cd(2, xargv);
1.63      lukem    2053:                                if (! dirchange) {
                   2054:                                        if (*dir == '\0' && code == 500)
                   2055:                                                fprintf(stderr,
                   2056: "\n"
                   2057: "ftp: The `CWD ' command (without a directory), which is required by\n"
1.193     lukem    2058: "     RFC 3986 to support the empty directory in the URL pathname (`//'),\n"
                   2059: "     conflicts with the server's conformance to RFC 959.\n"
1.63      lukem    2060: "     Try the same URL without the `//' in the URL pathname.\n"
                   2061: "\n");
1.53      lukem    2062:                                        goto cleanup_fetch_ftp;
1.63      lukem    2063:                                }
1.53      lukem    2064:                        }
                   2065:                        dir = nextpart;
                   2066:                } while (dir != NULL);
1.42      lukem    2067:        }
                   2068:
                   2069:        if (EMPTYSTRING(file)) {
                   2070:                rval = -1;
                   2071:                goto cleanup_fetch_ftp;
                   2072:        }
                   2073:
                   2074:        if (dirhasglob) {
1.78      lukem    2075:                (void)strlcpy(rempath, dir,     sizeof(rempath));
                   2076:                (void)strlcat(rempath, "/",     sizeof(rempath));
                   2077:                (void)strlcat(rempath, file,    sizeof(rempath));
1.42      lukem    2078:                file = rempath;
                   2079:        }
                   2080:
                   2081:                        /* Fetch the file(s). */
                   2082:        xargc = 2;
1.187     lukem    2083:        (void)strlcpy(cmdbuf, "get", sizeof(cmdbuf));
                   2084:        xargv[0] = cmdbuf;
1.42      lukem    2085:        xargv[1] = file;
                   2086:        xargv[2] = NULL;
                   2087:        if (dirhasglob || filehasglob) {
                   2088:                int ointeractive;
                   2089:
                   2090:                ointeractive = interactive;
                   2091:                interactive = 0;
1.155     lukem    2092:                if (restartautofetch)
1.187     lukem    2093:                        (void)strlcpy(cmdbuf, "mreget", sizeof(cmdbuf));
1.155     lukem    2094:                else
1.187     lukem    2095:                        (void)strlcpy(cmdbuf, "mget", sizeof(cmdbuf));
                   2096:                xargv[0] = cmdbuf;
1.42      lukem    2097:                mget(xargc, xargv);
                   2098:                interactive = ointeractive;
                   2099:        } else {
1.229   ! christos 2100:                char *destfile = outfile;
        !          2101:                if (destfile == NULL) {
1.53      lukem    2102:                        cp = strrchr(file, '/');        /* find savefile */
                   2103:                        if (cp != NULL)
1.229   ! christos 2104:                                destfile = cp + 1;
1.53      lukem    2105:                        else
1.229   ! christos 2106:                                destfile = file;
1.42      lukem    2107:                }
1.229   ! christos 2108:                xargv[2] = (char *)destfile;
1.53      lukem    2109:                xargv[3] = NULL;
                   2110:                xargc++;
1.52      lukem    2111:                if (restartautofetch)
                   2112:                        reget(xargc, xargv);
                   2113:                else
                   2114:                        get(xargc, xargv);
1.42      lukem    2115:        }
                   2116:
                   2117:        if ((code / 100) == COMPLETE)
                   2118:                rval = 0;
                   2119:
1.118     lukem    2120:  cleanup_fetch_ftp:
1.214     christos 2121:        freeurlinfo(&ui);
                   2122:        freeauthinfo(&auth);
1.42      lukem    2123:        return (rval);
                   2124: }
                   2125:
                   2126: /*
                   2127:  * Retrieve the given file to outfile.
                   2128:  * Supports arguments of the form:
                   2129:  *     "host:path", "ftp://host/path"  if $ftpproxy, call fetch_url() else
                   2130:  *                                     call fetch_ftp()
1.50      lukem    2131:  *     "http://host/path"              call fetch_url() to use HTTP
1.42      lukem    2132:  *     "file:///path"                  call fetch_url() to copy
                   2133:  *     "about:..."                     print a message
                   2134:  *
                   2135:  * Returns 1 on failure, 0 on completed xfer, -1 if ftp connection
                   2136:  * is still open (e.g, ftp xfer with trailing /)
                   2137:  */
                   2138: static int
1.111     lukem    2139: go_fetch(const char *url)
1.42      lukem    2140: {
1.186     lukem    2141:        char *proxyenv;
1.196     apb      2142:        char *p;
1.42      lukem    2143:
1.147     christos 2144: #ifndef NO_ABOUT
1.42      lukem    2145:        /*
                   2146:         * Check for about:*
                   2147:         */
1.150     lukem    2148:        if (STRNEQUAL(url, ABOUT_URL)) {
1.42      lukem    2149:                url += sizeof(ABOUT_URL) -1;
1.144     lukem    2150:                if (strcasecmp(url, "ftp") == 0 ||
                   2151:                    strcasecmp(url, "tnftp") == 0) {
1.87      lukem    2152:                        fputs(
1.143     salo     2153: "This version of ftp has been enhanced by Luke Mewburn <lukem@NetBSD.org>\n"
1.87      lukem    2154: "for the NetBSD project.  Execute `man ftp' for more details.\n", ttyout);
                   2155:                } else if (strcasecmp(url, "lukem") == 0) {
                   2156:                        fputs(
                   2157: "Luke Mewburn is the author of most of the enhancements in this ftp client.\n"
1.143     salo     2158: "Please email feedback to <lukem@NetBSD.org>.\n", ttyout);
1.42      lukem    2159:                } else if (strcasecmp(url, "netbsd") == 0) {
1.87      lukem    2160:                        fputs(
                   2161: "NetBSD is a freely available and redistributable UNIX-like operating system.\n"
1.144     lukem    2162: "For more information, see http://www.NetBSD.org/\n", ttyout);
1.92      lukem    2163:                } else if (strcasecmp(url, "version") == 0) {
1.115     lukem    2164:                        fprintf(ttyout, "Version: %s %s%s\n",
                   2165:                            FTP_PRODUCT, FTP_VERSION,
                   2166: #ifdef INET6
                   2167:                            ""
                   2168: #else
                   2169:                            " (-IPv6)"
                   2170: #endif
                   2171:                        );
1.42      lukem    2172:                } else {
                   2173:                        fprintf(ttyout, "`%s' is an interesting topic.\n", url);
                   2174:                }
1.92      lukem    2175:                fputs("\n", ttyout);
1.42      lukem    2176:                return (0);
                   2177:        }
1.147     christos 2178: #endif
1.42      lukem    2179:
                   2180:        /*
                   2181:         * Check for file:// and http:// URLs.
                   2182:         */
1.199     christos 2183:        if (STRNEQUAL(url, HTTP_URL)
                   2184: #ifdef WITH_SSL
                   2185:            || STRNEQUAL(url, HTTPS_URL)
                   2186: #endif
                   2187:            || STRNEQUAL(url, FILE_URL))
1.52      lukem    2188:                return (fetch_url(url, NULL, NULL, NULL));
1.42      lukem    2189:
                   2190:        /*
1.196     apb      2191:         * If it contains "://" but does not begin with ftp://
                   2192:         * or something that was already handled, then it's
                   2193:         * unsupported.
                   2194:         *
                   2195:         * If it contains ":" but not "://" then we assume the
                   2196:         * part before the colon is a host name, not an URL scheme,
                   2197:         * so we don't try to match that here.
                   2198:         */
                   2199:        if ((p = strstr(url, "://")) != NULL && ! STRNEQUAL(url, FTP_URL))
1.197     apb      2200:                errx(1, "Unsupported URL scheme `%.*s'", (int)(p - url), url);
1.196     apb      2201:
                   2202:        /*
1.42      lukem    2203:         * Try FTP URL-style and host:file arguments next.
                   2204:         * If ftpproxy is set with an FTP URL, use fetch_url()
                   2205:         * Othewise, use fetch_ftp().
                   2206:         */
1.186     lukem    2207:        proxyenv = getoptionvalue("ftp_proxy");
                   2208:        if (!EMPTYSTRING(proxyenv) && STRNEQUAL(url, FTP_URL))
1.52      lukem    2209:                return (fetch_url(url, NULL, NULL, NULL));
1.42      lukem    2210:
1.52      lukem    2211:        return (fetch_ftp(url));
1.42      lukem    2212: }
                   2213:
                   2214: /*
                   2215:  * Retrieve multiple files from the command line,
                   2216:  * calling go_fetch() for each file.
                   2217:  *
                   2218:  * If an ftp path has a trailing "/", the path will be cd-ed into and
1.41      lukem    2219:  * the connection remains open, and the function will return -1
                   2220:  * (to indicate the connection is alive).
1.1       lukem    2221:  * If an error occurs the return value will be the offset+1 in
                   2222:  * argv[] of the file that caused a problem (i.e, argv[x]
                   2223:  * returns x+1)
                   2224:  * Otherwise, 0 is returned if all files retrieved successfully.
                   2225:  */
                   2226: int
1.111     lukem    2227: auto_fetch(int argc, char *argv[])
1.1       lukem    2228: {
1.160     lukem    2229:        volatile int    argpos, rval;
1.22      lukem    2230:
1.160     lukem    2231:        argpos = rval = 0;
1.1       lukem    2232:
1.88      lukem    2233:        if (sigsetjmp(toplevel, 1)) {
1.2       lukem    2234:                if (connected)
                   2235:                        disconnect(0, NULL);
1.148     lukem    2236:                if (rval > 0)
                   2237:                        rval = argpos + 1;
                   2238:                return (rval);
1.2       lukem    2239:        }
1.88      lukem    2240:        (void)xsignal(SIGINT, intr);
1.91      lukem    2241:        (void)xsignal(SIGPIPE, lostpeer);
1.1       lukem    2242:
                   2243:        /*
                   2244:         * Loop through as long as there's files to fetch.
                   2245:         */
1.160     lukem    2246:        for (; (rval == 0) && (argpos < argc); argpos++) {
1.1       lukem    2247:                if (strchr(argv[argpos], ':') == NULL)
                   2248:                        break;
1.42      lukem    2249:                redirect_loop = 0;
1.90      lukem    2250:                if (!anonftp)
                   2251:                        anonftp = 2;    /* Handle "automatic" transfers. */
1.52      lukem    2252:                rval = go_fetch(argv[argpos]);
                   2253:                if (outfile != NULL && strcmp(outfile, "-") != 0
1.229   ! christos 2254:                    && outfile[0] != '|') {
        !          2255:                        FREEPTR(outfile);
        !          2256:                }
1.42      lukem    2257:                if (rval > 0)
1.1       lukem    2258:                        rval = argpos + 1;
1.42      lukem    2259:        }
1.3       lukem    2260:
1.1       lukem    2261:        if (connected && rval != -1)
                   2262:                disconnect(0, NULL);
1.114     lukem    2263:        return (rval);
                   2264: }
                   2265:
                   2266:
1.170     lukem    2267: /*
                   2268:  * Upload multiple files from the command line.
                   2269:  *
                   2270:  * If an error occurs the return value will be the offset+1 in
                   2271:  * argv[] of the file that caused a problem (i.e, argv[x]
                   2272:  * returns x+1)
                   2273:  * Otherwise, 0 is returned if all files uploaded successfully.
                   2274:  */
1.114     lukem    2275: int
                   2276: auto_put(int argc, char **argv, const char *uploadserver)
                   2277: {
                   2278:        char    *uargv[4], *path, *pathsep;
1.170     lukem    2279:        int      uargc, rval, argpos;
1.159     lukem    2280:        size_t   len;
1.187     lukem    2281:        char     cmdbuf[MAX_C_NAME];
1.114     lukem    2282:
1.187     lukem    2283:        (void)strlcpy(cmdbuf, "mput", sizeof(cmdbuf));
                   2284:        uargv[0] = cmdbuf;
                   2285:        uargv[1] = argv[0];
                   2286:        uargc = 2;
1.114     lukem    2287:        uargv[2] = uargv[3] = NULL;
                   2288:        pathsep = NULL;
                   2289:        rval = 1;
                   2290:
1.163     christos 2291:        DPRINTF("auto_put: target `%s'\n", uploadserver);
1.114     lukem    2292:
1.166     christos 2293:        path = ftp_strdup(uploadserver);
1.114     lukem    2294:        len = strlen(path);
                   2295:        if (path[len - 1] != '/' && path[len - 1] != ':') {
                   2296:                        /*
                   2297:                         * make sure we always pass a directory to auto_fetch
                   2298:                         */
                   2299:                if (argc > 1) {         /* more than one file to upload */
                   2300:                        len = strlen(uploadserver) + 2; /* path + "/" + "\0" */
                   2301:                        free(path);
1.166     christos 2302:                        path = (char *)ftp_malloc(len);
1.114     lukem    2303:                        (void)strlcpy(path, uploadserver, len);
                   2304:                        (void)strlcat(path, "/", len);
                   2305:                } else {                /* single file to upload */
1.187     lukem    2306:                        (void)strlcpy(cmdbuf, "put", sizeof(cmdbuf));
                   2307:                        uargv[0] = cmdbuf;
1.114     lukem    2308:                        pathsep = strrchr(path, '/');
                   2309:                        if (pathsep == NULL) {
                   2310:                                pathsep = strrchr(path, ':');
                   2311:                                if (pathsep == NULL) {
                   2312:                                        warnx("Invalid URL `%s'", path);
                   2313:                                        goto cleanup_auto_put;
                   2314:                                }
                   2315:                                pathsep++;
1.166     christos 2316:                                uargv[2] = ftp_strdup(pathsep);
1.114     lukem    2317:                                pathsep[0] = '/';
1.157     lukem    2318:                        } else
1.166     christos 2319:                                uargv[2] = ftp_strdup(pathsep + 1);
1.114     lukem    2320:                        pathsep[1] = '\0';
                   2321:                        uargc++;
                   2322:                }
                   2323:        }
1.163     christos 2324:        DPRINTF("auto_put: URL `%s' argv[2] `%s'\n",
1.183     lukem    2325:            path, STRorNULL(uargv[2]));
1.157     lukem    2326:
                   2327:                        /* connect and cwd */
1.114     lukem    2328:        rval = auto_fetch(1, &path);
                   2329:        if(rval >= 0)
                   2330:                goto cleanup_auto_put;
                   2331:
1.170     lukem    2332:        rval = 0;
                   2333:
                   2334:                        /* target filename provided; upload 1 file */
1.114     lukem    2335:                        /* XXX : is this the best way? */
                   2336:        if (uargc == 3) {
                   2337:                uargv[1] = argv[0];
                   2338:                put(uargc, uargv);
1.170     lukem    2339:                if ((code / 100) != COMPLETE)
                   2340:                        rval = 1;
                   2341:        } else {        /* otherwise a target dir: upload all files to it */
                   2342:                for(argpos = 0; argv[argpos] != NULL; argpos++) {
                   2343:                        uargv[1] = argv[argpos];
                   2344:                        mput(uargc, uargv);
                   2345:                        if ((code / 100) != COMPLETE) {
                   2346:                                rval = argpos + 1;
                   2347:                                break;
                   2348:                        }
                   2349:                }
1.114     lukem    2350:        }
                   2351:
1.118     lukem    2352:  cleanup_auto_put:
1.168     christos 2353:        free(path);
1.114     lukem    2354:        FREEPTR(uargv[2]);
1.1       lukem    2355:        return (rval);
                   2356: }

CVSweb <webmaster@jp.NetBSD.org>