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

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

1.41    ! deraadt     1: /*     $OpenBSD: fetch.c,v 1.40 2002/11/08 03:30:17 fgsch Exp $        */
1.15      millert     2: /*     $NetBSD: fetch.c,v 1.14 1997/08/18 10:20:20 lukem Exp $ */
1.1       millert     3:
                      4: /*-
                      5:  * Copyright (c) 1997 The NetBSD Foundation, Inc.
                      6:  * All rights reserved.
                      7:  *
                      8:  * This code is derived from software contributed to The NetBSD Foundation
                      9:  * by Jason Thorpe and Luke Mewburn.
                     10:  *
                     11:  * Redistribution and use in source and binary forms, with or without
                     12:  * modification, are permitted provided that the following conditions
                     13:  * are met:
                     14:  * 1. Redistributions of source code must retain the above copyright
                     15:  *    notice, this list of conditions and the following disclaimer.
                     16:  * 2. Redistributions in binary form must reproduce the above copyright
                     17:  *    notice, this list of conditions and the following disclaimer in the
                     18:  *    documentation and/or other materials provided with the distribution.
                     19:  * 3. All advertising materials mentioning features or use of this software
                     20:  *    must display the following acknowledgement:
                     21:  *        This product includes software developed by the NetBSD
                     22:  *        Foundation, Inc. and its contributors.
                     23:  * 4. Neither the name of The NetBSD Foundation nor the names of its
                     24:  *    contributors may be used to endorse or promote products derived
                     25:  *    from this software without specific prior written permission.
                     26:  *
                     27:  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
                     28:  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
                     29:  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
1.15      millert    30:  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
                     31:  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
1.1       millert    32:  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
                     33:  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
                     34:  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
                     35:  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
                     36:  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
                     37:  * POSSIBILITY OF SUCH DAMAGE.
                     38:  */
                     39:
                     40: #ifndef lint
1.41    ! deraadt    41: static char rcsid[] = "$OpenBSD: fetch.c,v 1.40 2002/11/08 03:30:17 fgsch Exp $";
1.1       millert    42: #endif /* not lint */
                     43:
                     44: /*
                     45:  * FTP User Program -- Command line file retrieval
                     46:  */
                     47:
                     48: #include <sys/types.h>
                     49: #include <sys/param.h>
                     50: #include <sys/socket.h>
1.22      deraadt    51: #include <sys/stat.h>
1.1       millert    52:
                     53: #include <netinet/in.h>
                     54:
                     55: #include <arpa/ftp.h>
                     56: #include <arpa/inet.h>
                     57:
                     58: #include <ctype.h>
                     59: #include <err.h>
1.17      millert    60: #include <libgen.h>
1.1       millert    61: #include <netdb.h>
                     62: #include <fcntl.h>
1.3       millert    63: #include <signal.h>
1.1       millert    64: #include <stdio.h>
1.19      deraadt    65: #include <errno.h>
1.1       millert    66: #include <stdlib.h>
                     67: #include <string.h>
                     68: #include <unistd.h>
1.40      fgsch      69: #include <util.h>
1.1       millert    70:
                     71: #include "ftp_var.h"
                     72:
1.38      millert    73: static int     url_get(const char *, const char *, const char *);
                     74: void           aborthttp(int);
                     75: void           abortfile(int);
                     76: char           hextochar(const char *);
                     77: char                   *urldecode(const char *);
1.14      millert    78:
1.1       millert    79: #define        FTP_URL         "ftp://"        /* ftp URL prefix */
                     80: #define        HTTP_URL        "http://"       /* http URL prefix */
1.22      deraadt    81: #define        FILE_URL        "file:"         /* file URL prefix */
1.6       millert    82: #define FTP_PROXY      "ftp_proxy"     /* env var with ftp proxy location */
1.1       millert    83: #define HTTP_PROXY     "http_proxy"    /* env var with http proxy location */
                     84:
                     85:
                     86: #define EMPTYSTRING(x) ((x) == NULL || (*(x) == '\0'))
                     87:
1.37      heko       88: static const char *at_encoding_warning =
                     89:    "Extra `@' characters in usernames and passwords should be encoded as %%40";
                     90:
1.1       millert    91: jmp_buf        httpabort;
                     92:
                     93: /*
1.6       millert    94:  * Retrieve URL, via the proxy in $proxyvar if necessary.
1.1       millert    95:  * Modifies the string argument given.
                     96:  * Returns -1 on failure, 0 on success
                     97:  */
1.14      millert    98: static int
1.17      millert    99: url_get(origline, proxyenv, outfile)
1.14      millert   100:        const char *origline;
                    101:        const char *proxyenv;
1.17      millert   102:        const char *outfile;
1.1       millert   103: {
1.25      itojun    104:        struct addrinfo hints, *res0, *res;
                    105:        int error;
1.40      fgsch     106:        int i, isftpurl, isfileurl, isredirect;
1.34      millert   107:        volatile int s, out;
1.14      millert   108:        size_t len;
1.40      fgsch     109:        char *cp, *ep, *portnum, *path;
1.29      itojun    110:        char pbuf[NI_MAXSERV];
1.34      millert   111:        const char * volatile savefile;
1.40      fgsch     112:        char *line, *host, *port, *buf;
1.34      millert   113:        char * volatile proxy;
1.28      itojun    114:        char *hosttail;
1.14      millert   115:        volatile sig_t oldintr;
1.1       millert   116:        off_t hashbytes;
1.25      itojun    117:        char *cause = "unknown";
1.40      fgsch     118:        FILE *fin;
                    119:        int rval;
1.1       millert   120:
                    121:        s = -1;
                    122:        proxy = NULL;
1.40      fgsch     123:        fin = NULL;
                    124:        buf = NULL;
1.14      millert   125:        isftpurl = 0;
1.22      deraadt   126:        isfileurl = 0;
1.40      fgsch     127:        isredirect = 0;
                    128:        rval = -1;
1.14      millert   129:
                    130:        line = strdup(origline);
                    131:        if (line == NULL)
                    132:                errx(1, "Can't allocate memory to parse URL");
1.7       millert   133:        if (strncasecmp(line, HTTP_URL, sizeof(HTTP_URL) - 1) == 0)
1.6       millert   134:                host = line + sizeof(HTTP_URL) - 1;
1.14      millert   135:        else if (strncasecmp(line, FTP_URL, sizeof(FTP_URL) - 1) == 0) {
1.6       millert   136:                host = line + sizeof(FTP_URL) - 1;
1.14      millert   137:                isftpurl = 1;
1.22      deraadt   138:        } else if (strncasecmp(line, FILE_URL, sizeof(FILE_URL) - 1) == 0) {
                    139:                host = line + sizeof(FILE_URL) - 1;
                    140:                isfileurl = 1;
1.14      millert   141:        } else
                    142:                errx(1, "url_get: Invalid URL '%s'", line);
1.6       millert   143:
1.22      deraadt   144:        if (isfileurl) {
                    145:                path = host;
                    146:        } else {
                    147:                path = strchr(host, '/');               /* find path */
                    148:                if (EMPTYSTRING(path)) {
                    149:                        if (isftpurl)
                    150:                                goto noftpautologin;
                    151:                        warnx("Invalid URL (no `/' after host): %s", origline);
                    152:                        goto cleanup_url_get;
                    153:                }
                    154:                *path++ = '\0';
                    155:                if (EMPTYSTRING(path)) {
                    156:                        if (isftpurl)
                    157:                                goto noftpautologin;
                    158:                        warnx("Invalid URL (no file after host): %s", origline);
                    159:                        goto cleanup_url_get;
                    160:                }
1.14      millert   161:        }
1.1       millert   162:
1.17      millert   163:        if (outfile)
                    164:                savefile = outfile;
1.1       millert   165:        else
1.17      millert   166:                savefile = basename(path);
                    167:
1.14      millert   168:        if (EMPTYSTRING(savefile)) {
                    169:                if (isftpurl)
                    170:                        goto noftpautologin;
                    171:                warnx("Invalid URL (no file after directory): %s", origline);
1.6       millert   172:                goto cleanup_url_get;
1.14      millert   173:        }
1.1       millert   174:
                    175:        if (proxyenv != NULL) {                         /* use proxy */
                    176:                proxy = strdup(proxyenv);
                    177:                if (proxy == NULL)
1.14      millert   178:                        errx(1, "Can't allocate memory for proxy URL.");
1.7       millert   179:                if (strncasecmp(proxy, HTTP_URL, sizeof(HTTP_URL) - 1) == 0)
1.6       millert   180:                        host = proxy + sizeof(HTTP_URL) - 1;
1.7       millert   181:                else if (strncasecmp(proxy, FTP_URL, sizeof(FTP_URL) - 1) == 0)
1.6       millert   182:                        host = proxy + sizeof(FTP_URL) - 1;
                    183:                else {
1.14      millert   184:                        warnx("Malformed proxy URL: %s", proxyenv);
1.6       millert   185:                        goto cleanup_url_get;
                    186:                }
1.14      millert   187:                if (EMPTYSTRING(host)) {
                    188:                        warnx("Malformed proxy URL: %s", proxyenv);
1.6       millert   189:                        goto cleanup_url_get;
1.14      millert   190:                }
1.1       millert   191:                *--path = '/';                  /* add / back to real path */
                    192:                path = strchr(host, '/');       /* remove trailing / on host */
                    193:                if (! EMPTYSTRING(path))
                    194:                        *path++ = '\0';
                    195:                path = line;
                    196:        }
                    197:
1.22      deraadt   198:        if (isfileurl) {
                    199:                struct stat st;
                    200:
                    201:                s = open(path, O_RDONLY);
                    202:                if (s == -1) {
                    203:                        warn("Can't open file %s", path);
                    204:                        goto cleanup_url_get;
                    205:                }
                    206:
                    207:                if (fstat(s, &st) == -1)
                    208:                        filesize = -1;
                    209:                else
                    210:                        filesize = st.st_size;
                    211:
                    212:                /* Open the output file.  */
                    213:                if (strcmp(savefile, "-") != 0) {
                    214:                        out = open(savefile, O_CREAT | O_WRONLY | O_TRUNC, 0666);
                    215:                        if (out < 0) {
                    216:                                warn("Can't open %s", savefile);
                    217:                                goto cleanup_url_get;
                    218:                        }
                    219:                } else
                    220:                        out = fileno(stdout);
                    221:
                    222:                /* Trap signals */
                    223:                oldintr = NULL;
                    224:                if (setjmp(httpabort)) {
                    225:                        if (oldintr)
                    226:                                (void)signal(SIGINT, oldintr);
                    227:                        goto cleanup_url_get;
                    228:                }
                    229:                oldintr = signal(SIGINT, abortfile);
                    230:
                    231:                bytes = 0;
                    232:                hashbytes = mark;
                    233:                progressmeter(-1);
1.40      fgsch     234:
                    235:                if ((buf = malloc(4096)) == NULL)
                    236:                        errx(1, "Can't allocate memory for transfer buffer\n");
1.22      deraadt   237:
                    238:                /* Finally, suck down the file. */
                    239:                i = 0;
1.40      fgsch     240:                while ((len = read(s, buf, 4096)) > 0) {
1.22      deraadt   241:                        bytes += len;
                    242:                        for (cp = buf; len > 0; len -= i, cp += i) {
                    243:                                if ((i = write(out, cp, len)) == -1) {
                    244:                                        warn("Writing %s", savefile);
                    245:                                        goto cleanup_url_get;
                    246:                                }
                    247:                                else if (i == 0)
                    248:                                        break;
                    249:                        }
                    250:                        if (hash && !progress) {
                    251:                                while (bytes >= hashbytes) {
                    252:                                        (void)putc('#', ttyout);
                    253:                                        hashbytes += mark;
                    254:                                }
                    255:                                (void)fflush(ttyout);
                    256:                        }
                    257:                }
                    258:                if (hash && !progress && bytes > 0) {
                    259:                        if (bytes < mark)
                    260:                                (void)putc('#', ttyout);
                    261:                        (void)putc('\n', ttyout);
                    262:                        (void)fflush(ttyout);
                    263:                }
                    264:                if (len != 0) {
                    265:                        warn("Reading from file");
                    266:                        goto cleanup_url_get;
                    267:                }
                    268:                progressmeter(1);
                    269:                if (verbose)
                    270:                        fputs("Successfully retrieved file.\n", ttyout);
                    271:                (void)signal(SIGINT, oldintr);
                    272:
1.40      fgsch     273:                rval = 0;
                    274:                goto cleanup_url_get;
1.22      deraadt   275:        }
                    276:
1.28      itojun    277:        if (*host == '[' && (hosttail = strrchr(host, ']')) != NULL &&
                    278:            (hosttail[1] == '\0' || hosttail[1] == ':')) {
                    279:                host++;
                    280:                *hosttail++ = '\0';
                    281:        } else
                    282:                hosttail = host;
                    283:
                    284:        portnum = strrchr(hosttail, ':');               /* find portnum */
1.1       millert   285:        if (portnum != NULL)
                    286:                *portnum++ = '\0';
                    287:
                    288:        if (debug)
1.10      deraadt   289:                fprintf(ttyout, "host %s, port %s, path %s, save as %s.\n",
1.1       millert   290:                    host, portnum, path, savefile);
                    291:
1.25      itojun    292:        memset(&hints, 0, sizeof(hints));
1.39      deraadt   293:        hints.ai_family = family;
1.25      itojun    294:        hints.ai_socktype = SOCK_STREAM;
                    295:        port = portnum ? portnum : httpport;
                    296:        error = getaddrinfo(host, port, &hints, &res0);
1.30      deraadt   297:        if (error == EAI_SERVICE && port == httpport) {
                    298:                /*
                    299:                 * If the services file is corrupt/missing, fall back
                    300:                 * on our hard-coded defines.
                    301:                 */
                    302:                snprintf(pbuf, sizeof(pbuf), "%d", HTTP_PORT);
                    303:                error = getaddrinfo(host, pbuf, &hints, &res0);
                    304:        }
1.25      itojun    305:        if (error) {
                    306:                warnx("%s: %s", gai_strerror(error), host);
                    307:                goto cleanup_url_get;
1.1       millert   308:        }
                    309:
1.25      itojun    310:        s = -1;
                    311:        for (res = res0; res; res = res->ai_next) {
1.40      fgsch     312:                getnameinfo(res->ai_addr, res->ai_addrlen, pbuf, sizeof(pbuf),
1.41    ! deraadt   313:                    NULL, 0, NI_NUMERICHOST);
        !           314:                if (verbose)
        !           315:                        fprintf(ttyout, "Trying %s...\n", pbuf);
1.14      millert   316:
1.25      itojun    317:                s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
                    318:                if (s == -1) {
                    319:                        cause = "socket";
                    320:                        continue;
1.1       millert   321:                }
                    322:
1.25      itojun    323: again:
                    324:                if (connect(s, res->ai_addr, res->ai_addrlen) < 0) {
                    325:                        if (errno == EINTR)
                    326:                                goto again;
                    327:                        close(s);
                    328:                        s = -1;
                    329:                        cause = "connect";
1.19      deraadt   330:                        continue;
                    331:                }
1.25      itojun    332:
1.29      itojun    333:                /* get port in numeric */
                    334:                if (getnameinfo(res->ai_addr, res->ai_addrlen, NULL, 0,
                    335:                    pbuf, sizeof(pbuf), NI_NUMERICSERV) == 0)
                    336:                        port = pbuf;
                    337:                else
                    338:                        port = NULL;
                    339:
1.25      itojun    340:                break;
                    341:        }
                    342:        freeaddrinfo(res0);
                    343:        if (s < 0) {
1.33      millert   344:                warn("%s", cause);
1.6       millert   345:                goto cleanup_url_get;
1.1       millert   346:        }
                    347:
1.40      fgsch     348:        fin = fdopen(s, "r+");
                    349:
1.1       millert   350:        /*
1.40      fgsch     351:         * Construct and send the request. Proxy requests don't want leading /.
1.1       millert   352:         */
1.32      itojun    353:        if (proxy) {
                    354:                /*
                    355:                 * Host: directive must use the destination host address for
                    356:                 * the original URI (path).  We do not attach it at this moment.
                    357:                 */
                    358:                if (verbose)
1.23      deraadt   359:                        fprintf(ttyout, "Requesting %s (via %s)\n",
                    360:                            origline, proxyenv);
1.40      fgsch     361:                fprintf(fin, "GET %s HTTP/1.0\r\n%s\r\n\r\n", path, HTTP_USER_AGENT);
1.28      itojun    362:        } else {
1.32      itojun    363:                if (verbose)
                    364:                        fprintf(ttyout, "Requesting %s\n", origline);
                    365:                if (strchr(host, ':')) {
                    366:                        char *h, *p;
                    367:
                    368:                        /* strip off scoped address portion, since it's local to node */
                    369:                        h = strdup(host);
                    370:                        if (h == NULL)
                    371:                                errx(1, "Can't allocate memory.");
                    372:                        if ((p = strchr(h, '%')) != NULL)
                    373:                                *p = '\0';
1.35      heko      374:                        /*
                    375:                         * Send port number only if it's specified and does not equal
                    376:                         * 80. Some broken HTTP servers get confused if you explicitly
                    377:                         * send them the port number.
                    378:                         */
                    379:                        if (port && strcmp(port, "80") != 0)
1.40      fgsch     380:                                fprintf(fin, "GET /%s HTTP/1.0\r\nHost: [%s]:%s\r\n%s\r\n\r\n",
1.36      heko      381:                                    path, h, port, HTTP_USER_AGENT);
1.35      heko      382:                        else
1.40      fgsch     383:                                fprintf(fin, "GET /%s HTTP/1.0\r\nHost: [%s]\r\n%s\r\n\r\n",
1.36      heko      384:                                    path, h, HTTP_USER_AGENT);
1.32      itojun    385:                        free(h);
                    386:                } else {
1.35      heko      387:                        if (port && strcmp(port, "80") != 0)
1.40      fgsch     388:                                fprintf(fin, "GET /%s HTTP/1.0\r\nHost: %s:%s\r\n%s\r\n\r\n",
1.36      heko      389:                                    path, host, port, HTTP_USER_AGENT);
1.35      heko      390:                        else
1.40      fgsch     391:                                fprintf(fin, "GET /%s HTTP/1.0\r\nHost: %s\r\n%s\r\n\r\n",
1.36      heko      392:                                    path, host, HTTP_USER_AGENT);
1.32      itojun    393:                }
1.28      itojun    394:        }
1.40      fgsch     395:        if (fflush(fin) == EOF) {
1.14      millert   396:                warn("Writing HTTP request");
1.6       millert   397:                goto cleanup_url_get;
1.1       millert   398:        }
1.40      fgsch     399:
                    400:        if ((buf = fparseln(fin, &len, NULL, "\0\0\0", 0)) == NULL) {
                    401:                warn("Receiving HTTP reply");
                    402:                goto cleanup_url_get;
1.1       millert   403:        }
1.40      fgsch     404:
                    405:        while (len > 0 && (buf[len-1] == '\r' || buf[len-1] == '\n'))
                    406:                buf[--len] = '\0';
                    407:        if (debug)
                    408:                fprintf(ttyout, "received '%s'\n", buf);
                    409:
1.1       millert   410:        cp = strchr(buf, ' ');
                    411:        if (cp == NULL)
                    412:                goto improper;
                    413:        else
                    414:                cp++;
1.40      fgsch     415:        if (strncmp(cp, "301", 3) == 0 || strncmp(cp, "302", 3) == 0) {
                    416:                isredirect++;
                    417:        } else if (strncmp(cp, "200", 3)) {
1.1       millert   418:                warnx("Error retrieving file: %s", cp);
1.6       millert   419:                goto cleanup_url_get;
1.1       millert   420:        }
                    421:
                    422:        /*
                    423:         * Read the rest of the header.
                    424:         */
1.40      fgsch     425:        free(buf);
                    426:        filesize = -1;
                    427:
                    428:        while (1) {
                    429:                if ((buf = fparseln(fin, &len, NULL, "\0\0\0", 0)) == NULL) {
                    430:                        warn("Receiving HTTP reply");
                    431:                        goto cleanup_url_get;
                    432:                }
                    433:                while (len > 0 && (buf[len-1] == '\r' || buf[len-1] == '\n'))
                    434:                        buf[--len] = '\0';
                    435:                if (len == 0)
1.1       millert   436:                        break;
1.40      fgsch     437:                if (debug)
                    438:                        fprintf(ttyout, "received '%s'\n", buf);
1.1       millert   439:
1.40      fgsch     440:                /* Look for some headers */
                    441:                cp = buf;
1.1       millert   442: #define CONTENTLEN "Content-Length: "
1.40      fgsch     443:                if (strncasecmp(cp, CONTENTLEN, sizeof(CONTENTLEN) - 1) == 0) {
                    444:                        cp += sizeof(CONTENTLEN) - 1;
                    445:                        filesize = strtol(cp, &ep, 10);
                    446:                        if (filesize < 1 || *ep != '\0')
                    447:                                goto improper;
                    448: #define LOCATION "Location: "
                    449:                } else if (isredirect &&
                    450:                    strncasecmp(cp, LOCATION, sizeof(LOCATION) - 1) == 0) {
                    451:                        cp += sizeof(LOCATION) - 1;
                    452:                        if (verbose)
                    453:                                fprintf(ttyout, "Redirected to %s\n", cp);
                    454:                        if (fin != NULL)
                    455:                                fclose(fin);
                    456:                        else if (s != -1)
                    457:                                close(s);
                    458:                        if (proxy)
                    459:                                free(proxy);
                    460:                        free(line);
                    461:                        rval = url_get(cp, proxyenv, outfile);
                    462:                        if (buf)
                    463:                                free(buf);
                    464:                        return (rval);
                    465:                }
1.1       millert   466:        }
1.40      fgsch     467:        free(buf);
1.1       millert   468:
1.17      millert   469:        /* Open the output file.  */
                    470:        if (strcmp(savefile, "-") != 0) {
1.10      deraadt   471:                out = open(savefile, O_CREAT | O_WRONLY | O_TRUNC, 0666);
                    472:                if (out < 0) {
                    473:                        warn("Can't open %s", savefile);
                    474:                        goto cleanup_url_get;
                    475:                }
                    476:        } else
1.17      millert   477:                out = fileno(stdout);
1.1       millert   478:
                    479:        /* Trap signals */
                    480:        oldintr = NULL;
                    481:        if (setjmp(httpabort)) {
                    482:                if (oldintr)
1.2       millert   483:                        (void)signal(SIGINT, oldintr);
1.6       millert   484:                goto cleanup_url_get;
1.1       millert   485:        }
                    486:        oldintr = signal(SIGINT, aborthttp);
                    487:
                    488:        bytes = 0;
                    489:        hashbytes = mark;
                    490:        progressmeter(-1);
                    491:
                    492:        /* Finally, suck down the file. */
1.40      fgsch     493:        if ((buf = malloc(4096)) == NULL)
                    494:                errx(1, "Can't allocate memory for transfer buffer\n");
1.1       millert   495:        i = 0;
1.40      fgsch     496:        while ((len = fread(buf, sizeof(char), 4096, fin)) > 0) {
1.1       millert   497:                bytes += len;
                    498:                for (cp = buf; len > 0; len -= i, cp += i) {
                    499:                        if ((i = write(out, cp, len)) == -1) {
                    500:                                warn("Writing %s", savefile);
1.6       millert   501:                                goto cleanup_url_get;
1.1       millert   502:                        }
                    503:                        else if (i == 0)
                    504:                                break;
                    505:                }
                    506:                if (hash && !progress) {
                    507:                        while (bytes >= hashbytes) {
1.10      deraadt   508:                                (void)putc('#', ttyout);
1.1       millert   509:                                hashbytes += mark;
                    510:                        }
1.10      deraadt   511:                        (void)fflush(ttyout);
1.1       millert   512:                }
                    513:        }
                    514:        if (hash && !progress && bytes > 0) {
                    515:                if (bytes < mark)
1.10      deraadt   516:                        (void)putc('#', ttyout);
                    517:                (void)putc('\n', ttyout);
                    518:                (void)fflush(ttyout);
1.1       millert   519:        }
                    520:        if (len != 0) {
                    521:                warn("Reading from socket");
1.6       millert   522:                goto cleanup_url_get;
1.1       millert   523:        }
                    524:        progressmeter(1);
1.24      deraadt   525:        if (filesize != -1 && len == 0 && bytes != filesize) {
                    526:                if (verbose)
                    527:                        fputs("Read short file.\n", ttyout);
                    528:                goto cleanup_url_get;
                    529:        }
                    530:
1.1       millert   531:        if (verbose)
1.10      deraadt   532:                fputs("Successfully retrieved file.\n", ttyout);
1.2       millert   533:        (void)signal(SIGINT, oldintr);
1.1       millert   534:
1.40      fgsch     535:        rval = 0;
                    536:        goto cleanup_url_get;
1.1       millert   537:
1.14      millert   538: noftpautologin:
                    539:        warnx(
                    540:            "Auto-login using ftp URLs isn't supported when using $ftp_proxy");
                    541:        goto cleanup_url_get;
                    542:
1.1       millert   543: improper:
1.8       millert   544:        warnx("Improper response from %s", host);
1.14      millert   545:
1.6       millert   546: cleanup_url_get:
1.40      fgsch     547:        if (fin != NULL)
                    548:                fclose(fin);
                    549:        else if (s != -1)
1.1       millert   550:                close(s);
1.40      fgsch     551:        if (buf)
                    552:                free(buf);
1.1       millert   553:        if (proxy)
                    554:                free(proxy);
1.14      millert   555:        free(line);
1.40      fgsch     556:        return (rval);
1.1       millert   557: }
                    558:
                    559: /*
                    560:  * Abort a http retrieval
                    561:  */
                    562: void
1.3       millert   563: aborthttp(notused)
                    564:        int notused;
1.1       millert   565: {
                    566:
                    567:        alarmtimer(0);
1.10      deraadt   568:        fputs("\nhttp fetch aborted.\n", ttyout);
                    569:        (void)fflush(ttyout);
1.1       millert   570:        longjmp(httpabort, 1);
                    571: }
                    572:
                    573: /*
1.22      deraadt   574:  * Abort a http retrieval
                    575:  */
                    576: void
                    577: abortfile(notused)
                    578:        int notused;
                    579: {
                    580:
                    581:        alarmtimer(0);
                    582:        fputs("\nfile fetch aborted.\n", ttyout);
                    583:        (void)fflush(ttyout);
                    584:        longjmp(httpabort, 1);
                    585: }
                    586:
                    587: /*
1.1       millert   588:  * Retrieve multiple files from the command line, transferring
                    589:  * files of the form "host:path", "ftp://host/path" using the
                    590:  * ftp protocol, and files of the form "http://host/path" using
                    591:  * the http protocol.
1.2       millert   592:  * If path has a trailing "/", then return (-1);
1.1       millert   593:  * the path will be cd-ed into and the connection remains open,
                    594:  * and the function will return -1 (to indicate the connection
                    595:  * is alive).
                    596:  * If an error occurs the return value will be the offset+1 in
                    597:  * argv[] of the file that caused a problem (i.e, argv[x]
                    598:  * returns x+1)
                    599:  * Otherwise, 0 is returned if all files retrieved successfully.
                    600:  */
                    601: int
1.17      millert   602: auto_fetch(argc, argv, outfile)
1.1       millert   603:        int argc;
                    604:        char *argv[];
1.17      millert   605:        char *outfile;
1.1       millert   606: {
                    607:        static char lasthost[MAXHOSTNAMELEN];
                    608:        char *xargv[5];
                    609:        char *cp, *line, *host, *dir, *file, *portnum;
1.8       millert   610:        char *user, *pass;
1.6       millert   611:        char *ftpproxy, *httpproxy;
1.14      millert   612:        int rval, xargc;
                    613:        volatile int argpos;
1.4       millert   614:        int dirhasglob, filehasglob;
1.14      millert   615:        char rempath[MAXPATHLEN];
1.1       millert   616:
                    617:        argpos = 0;
                    618:
                    619:        if (setjmp(toplevel)) {
                    620:                if (connected)
                    621:                        disconnect(0, NULL);
1.2       millert   622:                return (argpos + 1);
1.1       millert   623:        }
1.3       millert   624:        (void)signal(SIGINT, (sig_t)intr);
                    625:        (void)signal(SIGPIPE, (sig_t)lostpeer);
1.1       millert   626:
1.6       millert   627:        ftpproxy = getenv(FTP_PROXY);
                    628:        httpproxy = getenv(HTTP_PROXY);
                    629:
1.1       millert   630:        /*
                    631:         * Loop through as long as there's files to fetch.
                    632:         */
                    633:        for (rval = 0; (rval == 0) && (argpos < argc); free(line), argpos++) {
                    634:                if (strchr(argv[argpos], ':') == NULL)
                    635:                        break;
1.8       millert   636:                host = dir = file = portnum = user = pass = NULL;
1.1       millert   637:
                    638:                /*
                    639:                 * We muck with the string, so we make a copy.
                    640:                 */
                    641:                line = strdup(argv[argpos]);
                    642:                if (line == NULL)
                    643:                        errx(1, "Can't allocate memory for auto-fetch.");
                    644:
                    645:                /*
                    646:                 * Try HTTP URL-style arguments first.
                    647:                 */
1.22      deraadt   648:                if (strncasecmp(line, HTTP_URL, sizeof(HTTP_URL) - 1) == 0 ||
                    649:                    strncasecmp(line, FILE_URL, sizeof(FILE_URL) - 1) == 0) {
1.17      millert   650:                        if (url_get(line, httpproxy, outfile) == -1)
1.1       millert   651:                                rval = argpos + 1;
                    652:                        continue;
                    653:                }
                    654:
                    655:                /*
1.6       millert   656:                 * Try FTP URL-style arguments next. If ftpproxy is
                    657:                 * set, use url_get() instead of standard ftp.
                    658:                 * Finally, try host:file.
1.1       millert   659:                 */
                    660:                host = line;
1.7       millert   661:                if (strncasecmp(line, FTP_URL, sizeof(FTP_URL) - 1) == 0) {
1.37      heko      662:                        char *passend, *passagain, *userend;
1.31      itojun    663:
1.6       millert   664:                        if (ftpproxy) {
1.17      millert   665:                                if (url_get(line, ftpproxy, outfile) == -1)
1.6       millert   666:                                        rval = argpos + 1;
                    667:                                continue;
                    668:                        }
1.1       millert   669:                        host += sizeof(FTP_URL) - 1;
1.8       millert   670:                        dir = strchr(host, '/');
1.1       millert   671:
1.8       millert   672:                        /* Look for [user:pass@]host[:port] */
1.31      itojun    673:
                    674:                        /* check if we have "user:pass@" */
1.37      heko      675:                        userend = strchr(host, ':');
1.31      itojun    676:                        passend = strchr(host, '@');
                    677:                        if (passend && userend && userend < passend &&
                    678:                            (!dir || passend < dir)) {
                    679:                                user = host;
                    680:                                pass = userend + 1;
                    681:                                host = passend + 1;
                    682:                                *userend = *passend = '\0';
1.37      heko      683:                                passagain = strchr(host, '@');
                    684:                                if (strchr(pass, '@') != NULL ||
                    685:                                    (passagain != NULL && passagain < dir)) {
                    686:                                        warnx(at_encoding_warning);
                    687:                                        goto bad_ftp_url;
                    688:                                }
1.31      itojun    689:
                    690:                                if (EMPTYSTRING(user) || EMPTYSTRING(pass)) {
1.11      millert   691: bad_ftp_url:
1.31      itojun    692:                                        warnx("Invalid URL: %s", argv[argpos]);
                    693:                                        rval = argpos + 1;
                    694:                                        continue;
                    695:                                }
1.37      heko      696:                                user = urldecode(user);
                    697:                                pass = urldecode(pass);
1.8       millert   698:                        }
1.31      itojun    699:
                    700: #ifdef INET6
                    701:                        /* check [host]:port, or [host] */
                    702:                        if (host[0] == '[') {
                    703:                                cp = strchr(host, ']');
                    704:                                if (cp && (!dir || cp < dir)) {
                    705:                                        if (cp + 1 == dir || cp[1] == ':') {
                    706:                                                host++;
                    707:                                                *cp++ = '\0';
                    708:                                        } else
                    709:                                                cp = NULL;
                    710:                                } else
                    711:                                        cp = host;
1.25      itojun    712:                        } else
                    713:                                cp = host;
1.31      itojun    714: #else
                    715:                        cp = host;
1.25      itojun    716: #endif
1.31      itojun    717:
                    718:                        /* split off host[:port] if there is */
                    719:                        if (cp) {
                    720:                                portnum = strchr(cp, ':');
                    721:                                if (!portnum)
                    722:                                        ;
                    723:                                else {
                    724:                                        if (!dir)
                    725:                                                ;
                    726:                                        else if (portnum + 1 < dir) {
                    727:                                                *portnum++ = '\0';
                    728:                                                /*
                    729:                                                 * XXX should check if portnum
                    730:                                                 * is decimal number
                    731:                                                 */
                    732:                                        } else {
                    733:                                                /* empty portnum */
                    734:                                                goto bad_ftp_url;
                    735:                                        }
                    736:                                }
                    737:                        } else
                    738:                                portnum = NULL;
1.8       millert   739:                } else {                        /* classic style `host:file' */
                    740:                        dir = strchr(host, ':');
                    741:                }
1.1       millert   742:                if (EMPTYSTRING(host)) {
                    743:                        rval = argpos + 1;
                    744:                        continue;
                    745:                }
                    746:
                    747:                /*
1.9       millert   748:                 * If dir is NULL, the file wasn't specified
1.1       millert   749:                 * (URL looked something like ftp://host)
                    750:                 */
1.8       millert   751:                if (dir != NULL)
                    752:                        *dir++ = '\0';
1.1       millert   753:
                    754:                /*
                    755:                 * Extract the file and (if present) directory name.
                    756:                 */
                    757:                if (! EMPTYSTRING(dir)) {
1.8       millert   758:                        cp = strrchr(dir, '/');
1.1       millert   759:                        if (cp != NULL) {
                    760:                                *cp++ = '\0';
                    761:                                file = cp;
                    762:                        } else {
                    763:                                file = dir;
                    764:                                dir = NULL;
                    765:                        }
                    766:                }
                    767:                if (debug)
1.10      deraadt   768:                        fprintf(ttyout, "user %s:%s host %s port %s dir %s file %s\n",
1.8       millert   769:                            user, pass, host, portnum, dir, file);
1.1       millert   770:
                    771:                /*
                    772:                 * Set up the connection if we don't have one.
                    773:                 */
                    774:                if (strcmp(host, lasthost) != 0) {
1.8       millert   775:                        int oautologin;
                    776:
1.5       millert   777:                        (void)strcpy(lasthost, host);
1.1       millert   778:                        if (connected)
                    779:                                disconnect(0, NULL);
                    780:                        xargv[0] = __progname;
                    781:                        xargv[1] = host;
                    782:                        xargv[2] = NULL;
                    783:                        xargc = 2;
1.8       millert   784:                        if (! EMPTYSTRING(portnum)) {
1.1       millert   785:                                xargv[2] = portnum;
                    786:                                xargv[3] = NULL;
                    787:                                xargc = 3;
                    788:                        }
1.8       millert   789:                        oautologin = autologin;
                    790:                        if (user != NULL)
                    791:                                autologin = 0;
1.1       millert   792:                        setpeer(xargc, xargv);
1.8       millert   793:                        autologin = oautologin;
                    794:                        if ((connected == 0) ||
1.40      fgsch     795:                            ((connected == 1) && !ftp_login(host, user, pass))) {
1.8       millert   796:                                warnx("Can't connect or login to host `%s'",
                    797:                                    host);
1.1       millert   798:                                rval = argpos + 1;
                    799:                                continue;
                    800:                        }
                    801:
                    802:                        /* Always use binary transfers. */
                    803:                        setbinary(0, NULL);
                    804:                }
1.8       millert   805:                /* cd back to '/' */
                    806:                xargv[0] = "cd";
                    807:                xargv[1] = "/";
                    808:                xargv[2] = NULL;
                    809:                cd(2, xargv);
                    810:                if (! dirchange) {
                    811:                        rval = argpos + 1;
                    812:                        continue;
1.1       millert   813:                }
                    814:
1.4       millert   815:                dirhasglob = filehasglob = 0;
                    816:                if (doglob) {
                    817:                        if (! EMPTYSTRING(dir) &&
                    818:                            strpbrk(dir, "*?[]{}") != NULL)
                    819:                                dirhasglob = 1;
                    820:                        if (! EMPTYSTRING(file) &&
                    821:                            strpbrk(file, "*?[]{}") != NULL)
                    822:                                filehasglob = 1;
                    823:                }
                    824:
1.1       millert   825:                /* Change directories, if necessary. */
1.4       millert   826:                if (! EMPTYSTRING(dir) && !dirhasglob) {
1.1       millert   827:                        xargv[0] = "cd";
                    828:                        xargv[1] = dir;
                    829:                        xargv[2] = NULL;
                    830:                        cd(2, xargv);
                    831:                        if (! dirchange) {
                    832:                                rval = argpos + 1;
                    833:                                continue;
                    834:                        }
                    835:                }
                    836:
                    837:                if (EMPTYSTRING(file)) {
                    838:                        rval = -1;
                    839:                        continue;
                    840:                }
                    841:
1.21      marc      842:                if (verbose)
1.10      deraadt   843:                        fprintf(ttyout, "Retrieving %s/%s\n", dir ? dir : "", file);
1.1       millert   844:
1.4       millert   845:                if (dirhasglob) {
                    846:                        snprintf(rempath, sizeof(rempath), "%s/%s", dir, file);
                    847:                        file = rempath;
                    848:                }
                    849:
                    850:                /* Fetch the file(s). */
1.10      deraadt   851:                xargc = 2;
1.1       millert   852:                xargv[0] = "get";
                    853:                xargv[1] = file;
                    854:                xargv[2] = NULL;
1.4       millert   855:                if (dirhasglob || filehasglob) {
                    856:                        int ointeractive;
                    857:
                    858:                        ointeractive = interactive;
                    859:                        interactive = 0;
                    860:                        xargv[0] = "mget";
1.10      deraadt   861:                        mget(xargc, xargv);
1.5       millert   862:                        interactive = ointeractive;
1.10      deraadt   863:                } else {
1.17      millert   864:                        if (outfile != NULL) {
                    865:                                xargv[2] = outfile;
                    866:                                xargv[3] = NULL;
1.10      deraadt   867:                                xargc++;
                    868:                        }
                    869:                        get(xargc, xargv);
                    870:                }
1.1       millert   871:
1.4       millert   872:                if ((code / 100) != COMPLETE)
1.1       millert   873:                        rval = argpos + 1;
                    874:        }
                    875:        if (connected && rval != -1)
                    876:                disconnect(0, NULL);
                    877:        return (rval);
1.37      heko      878: }
                    879:
                    880: char *
                    881: urldecode(str)
                    882:         const char *str;
                    883: {
                    884:         char *ret;
                    885:         char c;
                    886:         int i, reallen;
                    887:
                    888:         if (str == NULL)
                    889:                 return NULL;
                    890:         if ((ret = malloc(strlen(str)+1)) == NULL)
                    891:                 err(1, "Can't allocate memory for URL decoding");
                    892:         for (i = 0, reallen = 0; str[i] != '\0'; i++, reallen++, ret++) {
                    893:                 c = str[i];
                    894:                 if (c == '+') {
                    895:                         *ret = ' ';
                    896:                         continue;
                    897:                 }
                    898:                 /* Can't use strtol here because next char after %xx may be
                    899:                  * a digit. */
                    900:                 if (c == '%' && isxdigit(str[i+1]) && isxdigit(str[i+2])) {
                    901:                         *ret = hextochar(&str[i+1]);
                    902:                         i+=2;
                    903:                         continue;
                    904:                 }
                    905:                 *ret = c;
                    906:         }
                    907:         *ret = '\0';
                    908:
                    909:         return ret-reallen;
                    910: }
                    911:
                    912: char
                    913: hextochar(str)
                    914:         const char *str;
                    915: {
                    916:         char c, ret;
                    917:
                    918:         c = str[0];
                    919:         ret = c;
                    920:         if (isalpha(c))
                    921:                 ret -= isupper(c) ? 'A' - 10 : 'a' - 10;
                    922:         else
                    923:                 ret -= '0';
                    924:         ret *= 16;
                    925:
                    926:         c = str[1];
                    927:         ret += c;
                    928:         if (isalpha(c))
                    929:                 ret -= isupper(c) ? 'A' - 10 : 'a' - 10;
                    930:         else
                    931:                 ret -= '0';
                    932:         return ret;
1.25      itojun    933: }
                    934:
                    935: int
                    936: isurl(p)
                    937:        const char *p;
                    938: {
1.27      millert   939:
1.26      deraadt   940:        if (strncasecmp(p, FTP_URL, sizeof(FTP_URL) - 1) == 0 ||
                    941:            strncasecmp(p, HTTP_URL, sizeof(HTTP_URL) - 1) == 0 ||
1.27      millert   942:            strncasecmp(p, FILE_URL, sizeof(FILE_URL) - 1) == 0 ||
                    943:            strstr(p, ":/"))
                    944:                return (1);
                    945:        return (0);
1.1       millert   946: }