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

1.49    ! krw         1: /*     $OpenBSD: fetch.c,v 1.48 2003/12/16 21:46:22 deraadt 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:
1.48      deraadt    40: #if !defined(lint) && !defined(SMALL)
1.49    ! krw        41: static char rcsid[] = "$OpenBSD: fetch.c,v 1.48 2003/12/16 21:46:22 deraadt Exp $";
1.48      deraadt    42: #endif /* not lint and not SMALL */
1.1       millert    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);
1.42      deraadt    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.44      itojun    110:        char pbuf[NI_MAXSERV], hbuf[NI_MAXHOST];
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 */
1.42      deraadt   193:                if (!EMPTYSTRING(path))
1.1       millert   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);
1.42      deraadt   230:
1.22      deraadt   231:                bytes = 0;
                    232:                hashbytes = mark;
                    233:                progressmeter(-1);
1.40      fgsch     234:
                    235:                if ((buf = malloc(4096)) == NULL)
1.47      deraadt   236:                        errx(1, "Can't allocate memory for transfer buffer");
1.42      deraadt   237:
1.22      deraadt   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);
1.42      deraadt   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.44      itojun    312:                if (getnameinfo(res->ai_addr, res->ai_addrlen, hbuf,
                    313:                    sizeof(hbuf), NULL, 0, NI_NUMERICHOST) != 0)
                    314:                        strlcpy(hbuf, "(unknown)", sizeof(hbuf));
1.41      deraadt   315:                if (verbose)
1.44      itojun    316:                        fprintf(ttyout, "Trying %s...\n", hbuf);
1.14      millert   317:
1.25      itojun    318:                s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
                    319:                if (s == -1) {
                    320:                        cause = "socket";
                    321:                        continue;
1.1       millert   322:                }
                    323:
1.25      itojun    324: again:
                    325:                if (connect(s, res->ai_addr, res->ai_addrlen) < 0) {
                    326:                        if (errno == EINTR)
                    327:                                goto again;
                    328:                        close(s);
                    329:                        s = -1;
                    330:                        cause = "connect";
1.19      deraadt   331:                        continue;
                    332:                }
1.25      itojun    333:
1.29      itojun    334:                /* get port in numeric */
                    335:                if (getnameinfo(res->ai_addr, res->ai_addrlen, NULL, 0,
                    336:                    pbuf, sizeof(pbuf), NI_NUMERICSERV) == 0)
                    337:                        port = pbuf;
                    338:                else
                    339:                        port = NULL;
                    340:
1.25      itojun    341:                break;
                    342:        }
                    343:        freeaddrinfo(res0);
                    344:        if (s < 0) {
1.33      millert   345:                warn("%s", cause);
1.6       millert   346:                goto cleanup_url_get;
1.1       millert   347:        }
                    348:
1.40      fgsch     349:        fin = fdopen(s, "r+");
                    350:
1.1       millert   351:        /*
1.40      fgsch     352:         * Construct and send the request. Proxy requests don't want leading /.
1.1       millert   353:         */
1.32      itojun    354:        if (proxy) {
                    355:                /*
                    356:                 * Host: directive must use the destination host address for
                    357:                 * the original URI (path).  We do not attach it at this moment.
                    358:                 */
                    359:                if (verbose)
1.23      deraadt   360:                        fprintf(ttyout, "Requesting %s (via %s)\n",
                    361:                            origline, proxyenv);
1.40      fgsch     362:                fprintf(fin, "GET %s HTTP/1.0\r\n%s\r\n\r\n", path, HTTP_USER_AGENT);
1.28      itojun    363:        } else {
1.32      itojun    364:                if (verbose)
                    365:                        fprintf(ttyout, "Requesting %s\n", origline);
                    366:                if (strchr(host, ':')) {
                    367:                        char *h, *p;
                    368:
                    369:                        /* strip off scoped address portion, since it's local to node */
                    370:                        h = strdup(host);
                    371:                        if (h == NULL)
                    372:                                errx(1, "Can't allocate memory.");
                    373:                        if ((p = strchr(h, '%')) != NULL)
                    374:                                *p = '\0';
1.35      heko      375:                        /*
                    376:                         * Send port number only if it's specified and does not equal
                    377:                         * 80. Some broken HTTP servers get confused if you explicitly
                    378:                         * send them the port number.
                    379:                         */
                    380:                        if (port && strcmp(port, "80") != 0)
1.42      deraadt   381:                                fprintf(fin,
                    382:                                    "GET /%s HTTP/1.0\r\nHost: [%s]:%s\r\n%s\r\n\r\n",
1.36      heko      383:                                    path, h, port, HTTP_USER_AGENT);
1.35      heko      384:                        else
1.42      deraadt   385:                                fprintf(fin,
                    386:                                    "GET /%s HTTP/1.0\r\nHost: [%s]\r\n%s\r\n\r\n",
1.36      heko      387:                                    path, h, HTTP_USER_AGENT);
1.32      itojun    388:                        free(h);
                    389:                } else {
1.35      heko      390:                        if (port && strcmp(port, "80") != 0)
1.42      deraadt   391:                                fprintf(fin,
                    392:                                    "GET /%s HTTP/1.0\r\nHost: %s:%s\r\n%s\r\n\r\n",
1.36      heko      393:                                    path, host, port, HTTP_USER_AGENT);
1.35      heko      394:                        else
1.42      deraadt   395:                                fprintf(fin,
                    396:                                    "GET /%s HTTP/1.0\r\nHost: %s\r\n%s\r\n\r\n",
1.36      heko      397:                                    path, host, HTTP_USER_AGENT);
1.32      itojun    398:                }
1.28      itojun    399:        }
1.40      fgsch     400:        if (fflush(fin) == EOF) {
1.14      millert   401:                warn("Writing HTTP request");
1.6       millert   402:                goto cleanup_url_get;
1.1       millert   403:        }
1.40      fgsch     404:
                    405:        if ((buf = fparseln(fin, &len, NULL, "\0\0\0", 0)) == NULL) {
                    406:                warn("Receiving HTTP reply");
                    407:                goto cleanup_url_get;
1.1       millert   408:        }
1.40      fgsch     409:
                    410:        while (len > 0 && (buf[len-1] == '\r' || buf[len-1] == '\n'))
                    411:                buf[--len] = '\0';
                    412:        if (debug)
                    413:                fprintf(ttyout, "received '%s'\n", buf);
                    414:
1.1       millert   415:        cp = strchr(buf, ' ');
                    416:        if (cp == NULL)
                    417:                goto improper;
                    418:        else
                    419:                cp++;
1.40      fgsch     420:        if (strncmp(cp, "301", 3) == 0 || strncmp(cp, "302", 3) == 0) {
                    421:                isredirect++;
                    422:        } else if (strncmp(cp, "200", 3)) {
1.1       millert   423:                warnx("Error retrieving file: %s", cp);
1.6       millert   424:                goto cleanup_url_get;
1.1       millert   425:        }
                    426:
                    427:        /*
                    428:         * Read the rest of the header.
                    429:         */
1.40      fgsch     430:        free(buf);
                    431:        filesize = -1;
                    432:
                    433:        while (1) {
                    434:                if ((buf = fparseln(fin, &len, NULL, "\0\0\0", 0)) == NULL) {
                    435:                        warn("Receiving HTTP reply");
                    436:                        goto cleanup_url_get;
                    437:                }
                    438:                while (len > 0 && (buf[len-1] == '\r' || buf[len-1] == '\n'))
                    439:                        buf[--len] = '\0';
                    440:                if (len == 0)
1.1       millert   441:                        break;
1.40      fgsch     442:                if (debug)
                    443:                        fprintf(ttyout, "received '%s'\n", buf);
1.1       millert   444:
1.40      fgsch     445:                /* Look for some headers */
                    446:                cp = buf;
1.1       millert   447: #define CONTENTLEN "Content-Length: "
1.40      fgsch     448:                if (strncasecmp(cp, CONTENTLEN, sizeof(CONTENTLEN) - 1) == 0) {
                    449:                        cp += sizeof(CONTENTLEN) - 1;
                    450:                        filesize = strtol(cp, &ep, 10);
                    451:                        if (filesize < 1 || *ep != '\0')
                    452:                                goto improper;
                    453: #define LOCATION "Location: "
                    454:                } else if (isredirect &&
                    455:                    strncasecmp(cp, LOCATION, sizeof(LOCATION) - 1) == 0) {
                    456:                        cp += sizeof(LOCATION) - 1;
                    457:                        if (verbose)
                    458:                                fprintf(ttyout, "Redirected to %s\n", cp);
                    459:                        if (fin != NULL)
                    460:                                fclose(fin);
                    461:                        else if (s != -1)
                    462:                                close(s);
                    463:                        if (proxy)
                    464:                                free(proxy);
                    465:                        free(line);
                    466:                        rval = url_get(cp, proxyenv, outfile);
                    467:                        if (buf)
                    468:                                free(buf);
                    469:                        return (rval);
                    470:                }
1.1       millert   471:        }
                    472:
1.17      millert   473:        /* Open the output file.  */
                    474:        if (strcmp(savefile, "-") != 0) {
1.10      deraadt   475:                out = open(savefile, O_CREAT | O_WRONLY | O_TRUNC, 0666);
                    476:                if (out < 0) {
                    477:                        warn("Can't open %s", savefile);
                    478:                        goto cleanup_url_get;
                    479:                }
                    480:        } else
1.17      millert   481:                out = fileno(stdout);
1.1       millert   482:
                    483:        /* Trap signals */
                    484:        oldintr = NULL;
                    485:        if (setjmp(httpabort)) {
                    486:                if (oldintr)
1.2       millert   487:                        (void)signal(SIGINT, oldintr);
1.6       millert   488:                goto cleanup_url_get;
1.1       millert   489:        }
                    490:        oldintr = signal(SIGINT, aborthttp);
                    491:
                    492:        bytes = 0;
                    493:        hashbytes = mark;
                    494:        progressmeter(-1);
1.43      millert   495:
                    496:        free(buf);
1.1       millert   497:
                    498:        /* Finally, suck down the file. */
1.40      fgsch     499:        if ((buf = malloc(4096)) == NULL)
1.47      deraadt   500:                errx(1, "Can't allocate memory for transfer buffer");
1.1       millert   501:        i = 0;
1.40      fgsch     502:        while ((len = fread(buf, sizeof(char), 4096, fin)) > 0) {
1.1       millert   503:                bytes += len;
                    504:                for (cp = buf; len > 0; len -= i, cp += i) {
                    505:                        if ((i = write(out, cp, len)) == -1) {
                    506:                                warn("Writing %s", savefile);
1.6       millert   507:                                goto cleanup_url_get;
1.1       millert   508:                        }
                    509:                        else if (i == 0)
                    510:                                break;
                    511:                }
                    512:                if (hash && !progress) {
                    513:                        while (bytes >= hashbytes) {
1.10      deraadt   514:                                (void)putc('#', ttyout);
1.1       millert   515:                                hashbytes += mark;
                    516:                        }
1.10      deraadt   517:                        (void)fflush(ttyout);
1.1       millert   518:                }
                    519:        }
                    520:        if (hash && !progress && bytes > 0) {
                    521:                if (bytes < mark)
1.10      deraadt   522:                        (void)putc('#', ttyout);
                    523:                (void)putc('\n', ttyout);
                    524:                (void)fflush(ttyout);
1.1       millert   525:        }
                    526:        if (len != 0) {
                    527:                warn("Reading from socket");
1.6       millert   528:                goto cleanup_url_get;
1.1       millert   529:        }
                    530:        progressmeter(1);
1.24      deraadt   531:        if (filesize != -1 && len == 0 && bytes != filesize) {
                    532:                if (verbose)
                    533:                        fputs("Read short file.\n", ttyout);
                    534:                goto cleanup_url_get;
                    535:        }
                    536:
1.1       millert   537:        if (verbose)
1.10      deraadt   538:                fputs("Successfully retrieved file.\n", ttyout);
1.2       millert   539:        (void)signal(SIGINT, oldintr);
1.1       millert   540:
1.40      fgsch     541:        rval = 0;
                    542:        goto cleanup_url_get;
1.1       millert   543:
1.14      millert   544: noftpautologin:
                    545:        warnx(
                    546:            "Auto-login using ftp URLs isn't supported when using $ftp_proxy");
                    547:        goto cleanup_url_get;
                    548:
1.1       millert   549: improper:
1.8       millert   550:        warnx("Improper response from %s", host);
1.14      millert   551:
1.6       millert   552: cleanup_url_get:
1.40      fgsch     553:        if (fin != NULL)
                    554:                fclose(fin);
                    555:        else if (s != -1)
1.1       millert   556:                close(s);
1.40      fgsch     557:        if (buf)
                    558:                free(buf);
1.1       millert   559:        if (proxy)
                    560:                free(proxy);
1.14      millert   561:        free(line);
1.40      fgsch     562:        return (rval);
1.1       millert   563: }
                    564:
                    565: /*
                    566:  * Abort a http retrieval
                    567:  */
                    568: void
1.3       millert   569: aborthttp(notused)
                    570:        int notused;
1.1       millert   571: {
                    572:
                    573:        alarmtimer(0);
1.10      deraadt   574:        fputs("\nhttp fetch aborted.\n", ttyout);
                    575:        (void)fflush(ttyout);
1.1       millert   576:        longjmp(httpabort, 1);
                    577: }
                    578:
                    579: /*
1.22      deraadt   580:  * Abort a http retrieval
                    581:  */
                    582: void
                    583: abortfile(notused)
                    584:        int notused;
                    585: {
                    586:
                    587:        alarmtimer(0);
                    588:        fputs("\nfile fetch aborted.\n", ttyout);
                    589:        (void)fflush(ttyout);
                    590:        longjmp(httpabort, 1);
                    591: }
                    592:
                    593: /*
1.1       millert   594:  * Retrieve multiple files from the command line, transferring
                    595:  * files of the form "host:path", "ftp://host/path" using the
                    596:  * ftp protocol, and files of the form "http://host/path" using
                    597:  * the http protocol.
1.2       millert   598:  * If path has a trailing "/", then return (-1);
1.1       millert   599:  * the path will be cd-ed into and the connection remains open,
                    600:  * and the function will return -1 (to indicate the connection
                    601:  * is alive).
                    602:  * If an error occurs the return value will be the offset+1 in
                    603:  * argv[] of the file that caused a problem (i.e, argv[x]
                    604:  * returns x+1)
                    605:  * Otherwise, 0 is returned if all files retrieved successfully.
                    606:  */
                    607: int
1.17      millert   608: auto_fetch(argc, argv, outfile)
1.1       millert   609:        int argc;
                    610:        char *argv[];
1.17      millert   611:        char *outfile;
1.1       millert   612: {
                    613:        char *xargv[5];
                    614:        char *cp, *line, *host, *dir, *file, *portnum;
1.8       millert   615:        char *user, *pass;
1.6       millert   616:        char *ftpproxy, *httpproxy;
1.14      millert   617:        int rval, xargc;
                    618:        volatile int argpos;
1.49    ! krw       619:        int dirhasglob, filehasglob, oautologin;
1.14      millert   620:        char rempath[MAXPATHLEN];
1.1       millert   621:
                    622:        argpos = 0;
                    623:
                    624:        if (setjmp(toplevel)) {
                    625:                if (connected)
                    626:                        disconnect(0, NULL);
1.2       millert   627:                return (argpos + 1);
1.1       millert   628:        }
1.3       millert   629:        (void)signal(SIGINT, (sig_t)intr);
                    630:        (void)signal(SIGPIPE, (sig_t)lostpeer);
1.1       millert   631:
1.45      millert   632:        if ((ftpproxy = getenv(FTP_PROXY)) != NULL && *ftpproxy == '\0')
                    633:                ftpproxy = NULL;
                    634:        if ((httpproxy = getenv(HTTP_PROXY)) != NULL && *httpproxy == '\0')
                    635:                httpproxy = NULL;
1.6       millert   636:
1.1       millert   637:        /*
                    638:         * Loop through as long as there's files to fetch.
                    639:         */
                    640:        for (rval = 0; (rval == 0) && (argpos < argc); free(line), argpos++) {
                    641:                if (strchr(argv[argpos], ':') == NULL)
                    642:                        break;
1.8       millert   643:                host = dir = file = portnum = user = pass = NULL;
1.1       millert   644:
                    645:                /*
                    646:                 * We muck with the string, so we make a copy.
                    647:                 */
                    648:                line = strdup(argv[argpos]);
                    649:                if (line == NULL)
                    650:                        errx(1, "Can't allocate memory for auto-fetch.");
                    651:
                    652:                /*
                    653:                 * Try HTTP URL-style arguments first.
                    654:                 */
1.22      deraadt   655:                if (strncasecmp(line, HTTP_URL, sizeof(HTTP_URL) - 1) == 0 ||
                    656:                    strncasecmp(line, FILE_URL, sizeof(FILE_URL) - 1) == 0) {
1.17      millert   657:                        if (url_get(line, httpproxy, outfile) == -1)
1.1       millert   658:                                rval = argpos + 1;
                    659:                        continue;
                    660:                }
                    661:
                    662:                /*
1.6       millert   663:                 * Try FTP URL-style arguments next. If ftpproxy is
                    664:                 * set, use url_get() instead of standard ftp.
                    665:                 * Finally, try host:file.
1.1       millert   666:                 */
                    667:                host = line;
1.7       millert   668:                if (strncasecmp(line, FTP_URL, sizeof(FTP_URL) - 1) == 0) {
1.37      heko      669:                        char *passend, *passagain, *userend;
1.31      itojun    670:
1.6       millert   671:                        if (ftpproxy) {
1.17      millert   672:                                if (url_get(line, ftpproxy, outfile) == -1)
1.6       millert   673:                                        rval = argpos + 1;
                    674:                                continue;
                    675:                        }
1.1       millert   676:                        host += sizeof(FTP_URL) - 1;
1.8       millert   677:                        dir = strchr(host, '/');
1.1       millert   678:
1.8       millert   679:                        /* Look for [user:pass@]host[:port] */
1.31      itojun    680:
                    681:                        /* check if we have "user:pass@" */
1.37      heko      682:                        userend = strchr(host, ':');
1.31      itojun    683:                        passend = strchr(host, '@');
                    684:                        if (passend && userend && userend < passend &&
                    685:                            (!dir || passend < dir)) {
                    686:                                user = host;
                    687:                                pass = userend + 1;
                    688:                                host = passend + 1;
                    689:                                *userend = *passend = '\0';
1.37      heko      690:                                passagain = strchr(host, '@');
1.42      deraadt   691:                                if (strchr(pass, '@') != NULL ||
1.37      heko      692:                                    (passagain != NULL && passagain < dir)) {
                    693:                                        warnx(at_encoding_warning);
                    694:                                        goto bad_ftp_url;
1.42      deraadt   695:                                }
1.31      itojun    696:
                    697:                                if (EMPTYSTRING(user) || EMPTYSTRING(pass)) {
1.11      millert   698: bad_ftp_url:
1.31      itojun    699:                                        warnx("Invalid URL: %s", argv[argpos]);
                    700:                                        rval = argpos + 1;
                    701:                                        continue;
                    702:                                }
1.37      heko      703:                                user = urldecode(user);
                    704:                                pass = urldecode(pass);
1.8       millert   705:                        }
1.31      itojun    706:
                    707: #ifdef INET6
                    708:                        /* check [host]:port, or [host] */
                    709:                        if (host[0] == '[') {
                    710:                                cp = strchr(host, ']');
                    711:                                if (cp && (!dir || cp < dir)) {
                    712:                                        if (cp + 1 == dir || cp[1] == ':') {
                    713:                                                host++;
                    714:                                                *cp++ = '\0';
                    715:                                        } else
                    716:                                                cp = NULL;
                    717:                                } else
                    718:                                        cp = host;
1.25      itojun    719:                        } else
                    720:                                cp = host;
1.31      itojun    721: #else
                    722:                        cp = host;
1.25      itojun    723: #endif
1.31      itojun    724:
                    725:                        /* split off host[:port] if there is */
                    726:                        if (cp) {
                    727:                                portnum = strchr(cp, ':');
                    728:                                if (!portnum)
                    729:                                        ;
                    730:                                else {
                    731:                                        if (!dir)
                    732:                                                ;
                    733:                                        else if (portnum + 1 < dir) {
                    734:                                                *portnum++ = '\0';
                    735:                                                /*
                    736:                                                 * XXX should check if portnum
                    737:                                                 * is decimal number
                    738:                                                 */
                    739:                                        } else {
                    740:                                                /* empty portnum */
                    741:                                                goto bad_ftp_url;
                    742:                                        }
                    743:                                }
                    744:                        } else
                    745:                                portnum = NULL;
1.8       millert   746:                } else {                        /* classic style `host:file' */
                    747:                        dir = strchr(host, ':');
                    748:                }
1.1       millert   749:                if (EMPTYSTRING(host)) {
                    750:                        rval = argpos + 1;
                    751:                        continue;
                    752:                }
                    753:
                    754:                /*
1.9       millert   755:                 * If dir is NULL, the file wasn't specified
1.1       millert   756:                 * (URL looked something like ftp://host)
                    757:                 */
1.8       millert   758:                if (dir != NULL)
                    759:                        *dir++ = '\0';
1.1       millert   760:
                    761:                /*
                    762:                 * Extract the file and (if present) directory name.
                    763:                 */
1.42      deraadt   764:                if (!EMPTYSTRING(dir)) {
1.8       millert   765:                        cp = strrchr(dir, '/');
1.1       millert   766:                        if (cp != NULL) {
                    767:                                *cp++ = '\0';
                    768:                                file = cp;
                    769:                        } else {
                    770:                                file = dir;
                    771:                                dir = NULL;
                    772:                        }
                    773:                }
                    774:                if (debug)
1.42      deraadt   775:                        fprintf(ttyout,
                    776:                            "user %s:%s host %s port %s dir %s file %s\n",
1.8       millert   777:                            user, pass, host, portnum, dir, file);
1.1       millert   778:
                    779:                /*
1.49    ! krw       780:                 * Set up the connection.
1.1       millert   781:                 */
1.49    ! krw       782:                if (connected)
        !           783:                        disconnect(0, NULL);
        !           784:                xargv[0] = __progname;
        !           785:                xargv[1] = host;
1.8       millert   786:                xargv[2] = NULL;
1.49    ! krw       787:                xargc = 2;
        !           788:                if (!EMPTYSTRING(portnum)) {
        !           789:                        xargv[2] = portnum;
        !           790:                        xargv[3] = NULL;
        !           791:                        xargc = 3;
        !           792:                }
        !           793:                oautologin = autologin;
        !           794:                if (user != NULL)
        !           795:                        autologin = 0;
        !           796:                setpeer(xargc, xargv);
        !           797:                autologin = oautologin;
        !           798:                if ((connected == 0) ||
        !           799:                    ((connected == 1) && !ftp_login(host, user, pass))) {
        !           800:                        warnx("Can't connect or login to host `%s'", host);
1.8       millert   801:                        rval = argpos + 1;
                    802:                        continue;
1.1       millert   803:                }
1.49    ! krw       804:
        !           805:                /* Always use binary transfers. */
        !           806:                setbinary(0, NULL);
1.1       millert   807:
1.4       millert   808:                dirhasglob = filehasglob = 0;
                    809:                if (doglob) {
1.42      deraadt   810:                        if (!EMPTYSTRING(dir) &&
1.4       millert   811:                            strpbrk(dir, "*?[]{}") != NULL)
                    812:                                dirhasglob = 1;
1.42      deraadt   813:                        if (!EMPTYSTRING(file) &&
1.4       millert   814:                            strpbrk(file, "*?[]{}") != NULL)
                    815:                                filehasglob = 1;
                    816:                }
                    817:
1.1       millert   818:                /* Change directories, if necessary. */
1.42      deraadt   819:                if (!EMPTYSTRING(dir) && !dirhasglob) {
1.1       millert   820:                        xargv[0] = "cd";
                    821:                        xargv[1] = dir;
                    822:                        xargv[2] = NULL;
                    823:                        cd(2, xargv);
1.42      deraadt   824:                        if (!dirchange) {
1.1       millert   825:                                rval = argpos + 1;
                    826:                                continue;
                    827:                        }
                    828:                }
                    829:
                    830:                if (EMPTYSTRING(file)) {
                    831:                        rval = -1;
                    832:                        continue;
                    833:                }
                    834:
1.21      marc      835:                if (verbose)
1.10      deraadt   836:                        fprintf(ttyout, "Retrieving %s/%s\n", dir ? dir : "", file);
1.1       millert   837:
1.4       millert   838:                if (dirhasglob) {
                    839:                        snprintf(rempath, sizeof(rempath), "%s/%s", dir, file);
                    840:                        file = rempath;
                    841:                }
                    842:
                    843:                /* Fetch the file(s). */
1.10      deraadt   844:                xargc = 2;
1.1       millert   845:                xargv[0] = "get";
                    846:                xargv[1] = file;
                    847:                xargv[2] = NULL;
1.4       millert   848:                if (dirhasglob || filehasglob) {
                    849:                        int ointeractive;
                    850:
                    851:                        ointeractive = interactive;
                    852:                        interactive = 0;
                    853:                        xargv[0] = "mget";
1.10      deraadt   854:                        mget(xargc, xargv);
1.5       millert   855:                        interactive = ointeractive;
1.10      deraadt   856:                } else {
1.17      millert   857:                        if (outfile != NULL) {
                    858:                                xargv[2] = outfile;
                    859:                                xargv[3] = NULL;
1.10      deraadt   860:                                xargc++;
                    861:                        }
                    862:                        get(xargc, xargv);
                    863:                }
1.1       millert   864:
1.4       millert   865:                if ((code / 100) != COMPLETE)
1.1       millert   866:                        rval = argpos + 1;
                    867:        }
                    868:        if (connected && rval != -1)
                    869:                disconnect(0, NULL);
                    870:        return (rval);
1.37      heko      871: }
                    872:
                    873: char *
1.42      deraadt   874: urldecode(str)
1.37      heko      875:         const char *str;
                    876: {
                    877:         char *ret;
                    878:         char c;
                    879:         int i, reallen;
                    880:
1.42      deraadt   881:         if (str == NULL)
1.37      heko      882:                 return NULL;
                    883:         if ((ret = malloc(strlen(str)+1)) == NULL)
                    884:                 err(1, "Can't allocate memory for URL decoding");
                    885:         for (i = 0, reallen = 0; str[i] != '\0'; i++, reallen++, ret++) {
                    886:                 c = str[i];
                    887:                 if (c == '+') {
                    888:                         *ret = ' ';
                    889:                         continue;
                    890:                 }
                    891:                 /* Can't use strtol here because next char after %xx may be
                    892:                  * a digit. */
                    893:                 if (c == '%' && isxdigit(str[i+1]) && isxdigit(str[i+2])) {
                    894:                         *ret = hextochar(&str[i+1]);
                    895:                         i+=2;
                    896:                         continue;
                    897:                 }
                    898:                 *ret = c;
                    899:         }
                    900:         *ret = '\0';
                    901:
                    902:         return ret-reallen;
                    903: }
                    904:
                    905: char
                    906: hextochar(str)
                    907:         const char *str;
                    908: {
                    909:         char c, ret;
                    910:
                    911:         c = str[0];
                    912:         ret = c;
                    913:         if (isalpha(c))
                    914:                 ret -= isupper(c) ? 'A' - 10 : 'a' - 10;
                    915:         else
                    916:                 ret -= '0';
                    917:         ret *= 16;
                    918:
                    919:         c = str[1];
                    920:         ret += c;
                    921:         if (isalpha(c))
                    922:                 ret -= isupper(c) ? 'A' - 10 : 'a' - 10;
                    923:         else
                    924:                 ret -= '0';
                    925:         return ret;
1.25      itojun    926: }
                    927:
                    928: int
                    929: isurl(p)
                    930:        const char *p;
                    931: {
1.27      millert   932:
1.26      deraadt   933:        if (strncasecmp(p, FTP_URL, sizeof(FTP_URL) - 1) == 0 ||
                    934:            strncasecmp(p, HTTP_URL, sizeof(HTTP_URL) - 1) == 0 ||
1.27      millert   935:            strncasecmp(p, FILE_URL, sizeof(FILE_URL) - 1) == 0 ||
                    936:            strstr(p, ":/"))
                    937:                return (1);
                    938:        return (0);
1.1       millert   939: }