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

1.90    ! martynas    1: /*     $OpenBSD: fetch.c,v 1.89 2009/06/04 23:37:09 halex Exp $        */
1.15      millert     2: /*     $NetBSD: fetch.c,v 1.14 1997/08/18 10:20:20 lukem Exp $ */
1.1       millert     3:
                      4: /*-
                      5:  * Copyright (c) 1997 The NetBSD Foundation, Inc.
                      6:  * All rights reserved.
                      7:  *
                      8:  * This code is derived from software contributed to The NetBSD Foundation
                      9:  * by Jason Thorpe and Luke Mewburn.
                     10:  *
                     11:  * Redistribution and use in source and binary forms, with or without
                     12:  * modification, are permitted provided that the following conditions
                     13:  * are met:
                     14:  * 1. Redistributions of source code must retain the above copyright
                     15:  *    notice, this list of conditions and the following disclaimer.
                     16:  * 2. Redistributions in binary form must reproduce the above copyright
                     17:  *    notice, this list of conditions and the following disclaimer in the
                     18:  *    documentation and/or other materials provided with the distribution.
                     19:  *
                     20:  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
                     21:  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
                     22:  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
1.15      millert    23:  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
                     24:  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
1.1       millert    25:  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
                     26:  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
                     27:  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
                     28:  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
                     29:  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
                     30:  * POSSIBILITY OF SUCH DAMAGE.
                     31:  */
                     32:
                     33: /*
                     34:  * FTP User Program -- Command line file retrieval
                     35:  */
                     36:
                     37: #include <sys/types.h>
                     38: #include <sys/param.h>
                     39: #include <sys/socket.h>
1.22      deraadt    40: #include <sys/stat.h>
1.1       millert    41:
                     42: #include <netinet/in.h>
                     43:
                     44: #include <arpa/ftp.h>
                     45: #include <arpa/inet.h>
                     46:
                     47: #include <ctype.h>
                     48: #include <err.h>
1.17      millert    49: #include <libgen.h>
1.58      grunk      50: #include <limits.h>
1.1       millert    51: #include <netdb.h>
                     52: #include <fcntl.h>
1.3       millert    53: #include <signal.h>
1.1       millert    54: #include <stdio.h>
1.61      deraadt    55: #include <stdarg.h>
1.19      deraadt    56: #include <errno.h>
1.1       millert    57: #include <stdlib.h>
                     58: #include <string.h>
                     59: #include <unistd.h>
1.40      fgsch      60: #include <util.h>
1.73      drahn      61: #include <resolv.h>
1.1       millert    62:
1.61      deraadt    63: #ifndef SMALL
                     64: #include <openssl/ssl.h>
                     65: #include <openssl/err.h>
1.78      martynas   66: #else /* !SMALL */
1.61      deraadt    67: #define SSL void
1.78      martynas   68: #endif /* !SMALL */
1.61      deraadt    69:
1.1       millert    70: #include "ftp_var.h"
1.86      martynas   71: #include "cmds.h"
1.1       millert    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.61      deraadt    78: int            ftp_printf(FILE *, SSL *, const char *, ...) __attribute__((format(printf, 3, 4)));
                     79: char           *ftp_readline(FILE *, SSL *, size_t *);
1.65      ray        80: size_t         ftp_read(FILE *, SSL *, char *, size_t);
1.61      deraadt    81: #ifndef SMALL
1.81      espie      82: int            proxy_connect(int, char *, char *);
1.61      deraadt    83: int            SSL_vprintf(SSL *, const char *, va_list);
                     84: char           *SSL_readline(SSL *, size_t *);
1.78      martynas   85: #endif /* !SMALL */
1.14      millert    86:
1.1       millert    87: #define        FTP_URL         "ftp://"        /* ftp URL prefix */
                     88: #define        HTTP_URL        "http://"       /* http URL prefix */
1.61      deraadt    89: #define        HTTPS_URL       "https://"      /* https URL prefix */
1.22      deraadt    90: #define        FILE_URL        "file:"         /* file URL prefix */
1.6       millert    91: #define FTP_PROXY      "ftp_proxy"     /* env var with ftp proxy location */
1.1       millert    92: #define HTTP_PROXY     "http_proxy"    /* env var with http proxy location */
                     93:
1.73      drahn      94: #define COOKIE_MAX_LEN 42
1.1       millert    95:
                     96: #define EMPTYSTRING(x) ((x) == NULL || (*(x) == '\0'))
                     97:
1.37      heko       98: static const char *at_encoding_warning =
1.53      deraadt    99:     "Extra `@' characters in usernames and passwords should be encoded as %%40";
1.37      heko      100:
1.1       millert   101: jmp_buf        httpabort;
                    102:
1.54      fgsch     103: static int     redirect_loop;
                    104:
1.1       millert   105: /*
1.6       millert   106:  * Retrieve URL, via the proxy in $proxyvar if necessary.
1.1       millert   107:  * Modifies the string argument given.
                    108:  * Returns -1 on failure, 0 on success
                    109:  */
1.14      millert   110: static int
1.50      deraadt   111: url_get(const char *origline, const char *proxyenv, const char *outfile)
1.1       millert   112: {
1.69      jsg       113:        char pbuf[NI_MAXSERV], hbuf[NI_MAXHOST], *cp, *portnum, *path, ststr[4];
1.62      ray       114:        char *hosttail, *cause = "unknown", *newline, *host, *port, *buf = NULL;
1.53      deraadt   115:        int error, i, isftpurl = 0, isfileurl = 0, isredirect = 0, rval = -1;
1.25      itojun    116:        struct addrinfo hints, *res0, *res;
1.34      millert   117:        const char * volatile savefile;
1.62      ray       118:        char * volatile proxyurl = NULL;
1.73      drahn     119:        char *cookie = NULL;
1.53      deraadt   120:        volatile int s = -1, out;
1.14      millert   121:        volatile sig_t oldintr;
1.53      deraadt   122:        FILE *fin = NULL;
1.1       millert   123:        off_t hashbytes;
1.58      grunk     124:        const char *errstr;
1.61      deraadt   125:        size_t len, wlen;
                    126: #ifndef SMALL
                    127:        char *sslpath = NULL, *sslhost = NULL;
1.70      deraadt   128:        int ishttpsurl = 0;
1.61      deraadt   129:        SSL_CTX *ssl_ctx = NULL;
1.78      martynas  130: #endif /* !SMALL */
1.61      deraadt   131:        SSL *ssl = NULL;
1.70      deraadt   132:        int status;
1.14      millert   133:
1.62      ray       134:        newline = strdup(origline);
                    135:        if (newline == NULL)
1.14      millert   136:                errx(1, "Can't allocate memory to parse URL");
1.62      ray       137:        if (strncasecmp(newline, HTTP_URL, sizeof(HTTP_URL) - 1) == 0)
                    138:                host = newline + sizeof(HTTP_URL) - 1;
                    139:        else if (strncasecmp(newline, FTP_URL, sizeof(FTP_URL) - 1) == 0) {
                    140:                host = newline + sizeof(FTP_URL) - 1;
1.14      millert   141:                isftpurl = 1;
1.62      ray       142:        } else if (strncasecmp(newline, FILE_URL, sizeof(FILE_URL) - 1) == 0) {
                    143:                host = newline + sizeof(FILE_URL) - 1;
1.22      deraadt   144:                isfileurl = 1;
1.61      deraadt   145: #ifndef SMALL
1.62      ray       146:        } else if (strncasecmp(newline, HTTPS_URL, sizeof(HTTPS_URL) - 1) == 0) {
                    147:                host = newline + sizeof(HTTPS_URL) - 1;
1.61      deraadt   148:                ishttpsurl = 1;
1.78      martynas  149: #endif /* !SMALL */
1.14      millert   150:        } else
1.62      ray       151:                errx(1, "url_get: Invalid URL '%s'", newline);
1.6       millert   152:
1.22      deraadt   153:        if (isfileurl) {
                    154:                path = host;
                    155:        } else {
                    156:                path = strchr(host, '/');               /* find path */
                    157:                if (EMPTYSTRING(path)) {
                    158:                        if (isftpurl)
                    159:                                goto noftpautologin;
                    160:                        warnx("Invalid URL (no `/' after host): %s", origline);
                    161:                        goto cleanup_url_get;
                    162:                }
                    163:                *path++ = '\0';
                    164:                if (EMPTYSTRING(path)) {
                    165:                        if (isftpurl)
                    166:                                goto noftpautologin;
                    167:                        warnx("Invalid URL (no file after host): %s", origline);
                    168:                        goto cleanup_url_get;
                    169:                }
1.14      millert   170:        }
1.1       millert   171:
1.17      millert   172:        if (outfile)
                    173:                savefile = outfile;
1.1       millert   174:        else
1.17      millert   175:                savefile = basename(path);
                    176:
1.75      martynas  177: #ifndef SMALL
                    178:        if (resume && (strcmp(savefile, "-") == 0)) {
                    179:                warnx("can't append to stdout");
                    180:                goto cleanup_url_get;
                    181:        }
1.78      martynas  182: #endif /* !SMALL */
1.75      martynas  183:
1.14      millert   184:        if (EMPTYSTRING(savefile)) {
                    185:                if (isftpurl)
                    186:                        goto noftpautologin;
                    187:                warnx("Invalid URL (no file after directory): %s", origline);
1.6       millert   188:                goto cleanup_url_get;
1.14      millert   189:        }
1.1       millert   190:
1.59      uwe       191:        if (!isfileurl && proxyenv != NULL) {           /* use proxy */
1.61      deraadt   192: #ifndef SMALL
                    193:                if (ishttpsurl) {
                    194:                        sslpath = strdup(path);
                    195:                        sslhost = strdup(host);
                    196:                        if (! sslpath || ! sslhost)
                    197:                                errx(1, "Can't allocate memory for https path/host.");
                    198:                }
1.78      martynas  199: #endif /* !SMALL */
1.62      ray       200:                proxyurl = strdup(proxyenv);
                    201:                if (proxyurl == NULL)
1.14      millert   202:                        errx(1, "Can't allocate memory for proxy URL.");
1.62      ray       203:                if (strncasecmp(proxyurl, HTTP_URL, sizeof(HTTP_URL) - 1) == 0)
                    204:                        host = proxyurl + sizeof(HTTP_URL) - 1;
                    205:                else if (strncasecmp(proxyurl, FTP_URL, sizeof(FTP_URL) - 1) == 0)
                    206:                        host = proxyurl + sizeof(FTP_URL) - 1;
1.6       millert   207:                else {
1.14      millert   208:                        warnx("Malformed proxy URL: %s", proxyenv);
1.6       millert   209:                        goto cleanup_url_get;
                    210:                }
1.14      millert   211:                if (EMPTYSTRING(host)) {
                    212:                        warnx("Malformed proxy URL: %s", proxyenv);
1.6       millert   213:                        goto cleanup_url_get;
1.14      millert   214:                }
1.1       millert   215:                *--path = '/';                  /* add / back to real path */
                    216:                path = strchr(host, '/');       /* remove trailing / on host */
1.42      deraadt   217:                if (!EMPTYSTRING(path))
1.73      drahn     218:                        *path++ = '\0';         /* i guess this ++ is useless */
                    219:
                    220:                path = strchr(host, '@');       /* look for credentials in proxy */
                    221:                if (!EMPTYSTRING(path)) {
1.81      espie     222:                        *path = '\0';
1.73      drahn     223:                        cookie = strchr(host, ':');
                    224:                        if (EMPTYSTRING(cookie)) {
                    225:                                warnx("Malformed proxy URL: %s", proxyenv);
                    226:                                goto cleanup_url_get;
                    227:                        }
                    228:                        cookie  = malloc(COOKIE_MAX_LEN);
1.81      espie     229:                        if (cookie == NULL)
                    230:                                errx(1, "out of memory");
                    231:                        if (b64_ntop(host, strlen(host), cookie, COOKIE_MAX_LEN) == -1)
                    232:                                errx(1, "error in base64 encoding");
                    233:                        *path = '@'; /* restore @ in proxyurl */
1.73      drahn     234:                        /*
1.81      espie     235:                         * This removes the password from proxyurl,
1.73      drahn     236:                         * filling with stars
                    237:                         */
1.81      espie     238:                        for (host = 1 + strchr(proxyurl + 5, ':');  *host != '@';
1.73      drahn     239:                             host++)
                    240:                                *host = '*';
                    241:
1.81      espie     242:                        host = path + 1;
1.73      drahn     243:                }
1.62      ray       244:                path = newline;
1.1       millert   245:        }
                    246:
1.22      deraadt   247:        if (isfileurl) {
                    248:                struct stat st;
                    249:
                    250:                s = open(path, O_RDONLY);
                    251:                if (s == -1) {
                    252:                        warn("Can't open file %s", path);
                    253:                        goto cleanup_url_get;
                    254:                }
                    255:
                    256:                if (fstat(s, &st) == -1)
                    257:                        filesize = -1;
                    258:                else
                    259:                        filesize = st.st_size;
                    260:
1.83      martynas  261:                /* Open the output file.  */
1.22      deraadt   262:                if (strcmp(savefile, "-") != 0) {
1.75      martynas  263: #ifndef SMALL
                    264:                        if (resume)
1.82      deraadt   265:                                out = open(savefile, O_CREAT | O_WRONLY |
                    266:                                        O_APPEND, 0666);
                    267:
1.75      martynas  268:                        else
1.78      martynas  269: #endif /* !SMALL */
1.75      martynas  270:                                out = open(savefile, O_CREAT | O_WRONLY |
                    271:                                        O_TRUNC, 0666);
1.22      deraadt   272:                        if (out < 0) {
                    273:                                warn("Can't open %s", savefile);
                    274:                                goto cleanup_url_get;
                    275:                        }
                    276:                } else
                    277:                        out = fileno(stdout);
                    278:
1.75      martynas  279: #ifndef SMALL
                    280:                if (resume) {
                    281:                        if (fstat(out, &st) == -1) {
                    282:                                warn("Can't fstat %s", savefile);
                    283:                                goto cleanup_url_get;
                    284:                        }
                    285:                        if (lseek(s, st.st_size, SEEK_SET) == -1) {
                    286:                                warn("Can't lseek %s", path);
                    287:                                goto cleanup_url_get;
                    288:                        }
                    289:                        restart_point = st.st_size;
                    290:                }
1.78      martynas  291: #endif /* !SMALL */
1.75      martynas  292:
1.22      deraadt   293:                /* Trap signals */
                    294:                oldintr = NULL;
                    295:                if (setjmp(httpabort)) {
                    296:                        if (oldintr)
                    297:                                (void)signal(SIGINT, oldintr);
                    298:                        goto cleanup_url_get;
                    299:                }
                    300:                oldintr = signal(SIGINT, abortfile);
1.42      deraadt   301:
1.22      deraadt   302:                bytes = 0;
                    303:                hashbytes = mark;
1.84      martynas  304:                progressmeter(-1, path);
1.40      fgsch     305:
                    306:                if ((buf = malloc(4096)) == NULL)
1.47      deraadt   307:                        errx(1, "Can't allocate memory for transfer buffer");
1.42      deraadt   308:
1.22      deraadt   309:                /* Finally, suck down the file. */
                    310:                i = 0;
1.40      fgsch     311:                while ((len = read(s, buf, 4096)) > 0) {
1.22      deraadt   312:                        bytes += len;
                    313:                        for (cp = buf; len > 0; len -= i, cp += i) {
                    314:                                if ((i = write(out, cp, len)) == -1) {
                    315:                                        warn("Writing %s", savefile);
                    316:                                        goto cleanup_url_get;
                    317:                                }
                    318:                                else if (i == 0)
                    319:                                        break;
                    320:                        }
                    321:                        if (hash && !progress) {
                    322:                                while (bytes >= hashbytes) {
                    323:                                        (void)putc('#', ttyout);
                    324:                                        hashbytes += mark;
                    325:                                }
                    326:                                (void)fflush(ttyout);
                    327:                        }
                    328:                }
                    329:                if (hash && !progress && bytes > 0) {
                    330:                        if (bytes < mark)
                    331:                                (void)putc('#', ttyout);
                    332:                        (void)putc('\n', ttyout);
                    333:                        (void)fflush(ttyout);
                    334:                }
                    335:                if (len != 0) {
                    336:                        warn("Reading from file");
                    337:                        goto cleanup_url_get;
                    338:                }
1.84      martynas  339:                progressmeter(1, NULL);
1.22      deraadt   340:                if (verbose)
                    341:                        fputs("Successfully retrieved file.\n", ttyout);
                    342:                (void)signal(SIGINT, oldintr);
1.42      deraadt   343:
1.40      fgsch     344:                rval = 0;
                    345:                goto cleanup_url_get;
1.22      deraadt   346:        }
                    347:
1.28      itojun    348:        if (*host == '[' && (hosttail = strrchr(host, ']')) != NULL &&
                    349:            (hosttail[1] == '\0' || hosttail[1] == ':')) {
                    350:                host++;
                    351:                *hosttail++ = '\0';
                    352:        } else
                    353:                hosttail = host;
                    354:
                    355:        portnum = strrchr(hosttail, ':');               /* find portnum */
1.1       millert   356:        if (portnum != NULL)
                    357:                *portnum++ = '\0';
                    358:
1.80      martynas  359: #ifndef SMALL
1.1       millert   360:        if (debug)
1.10      deraadt   361:                fprintf(ttyout, "host %s, port %s, path %s, save as %s.\n",
1.1       millert   362:                    host, portnum, path, savefile);
1.80      martynas  363: #endif /* !SMALL */
1.1       millert   364:
1.25      itojun    365:        memset(&hints, 0, sizeof(hints));
1.39      deraadt   366:        hints.ai_family = family;
1.25      itojun    367:        hints.ai_socktype = SOCK_STREAM;
1.61      deraadt   368: #ifndef SMALL
                    369:        port = portnum ? portnum : (ishttpsurl ? httpsport : httpport);
1.78      martynas  370: #else /* !SMALL */
1.25      itojun    371:        port = portnum ? portnum : httpport;
1.78      martynas  372: #endif /* !SMALL */
1.25      itojun    373:        error = getaddrinfo(host, port, &hints, &res0);
1.61      deraadt   374:        /*
                    375:         * If the services file is corrupt/missing, fall back
                    376:         * on our hard-coded defines.
                    377:         */
1.30      deraadt   378:        if (error == EAI_SERVICE && port == httpport) {
                    379:                snprintf(pbuf, sizeof(pbuf), "%d", HTTP_PORT);
                    380:                error = getaddrinfo(host, pbuf, &hints, &res0);
1.61      deraadt   381: #ifndef SMALL
                    382:        } else if (error == EAI_SERVICE && port == httpsport) {
                    383:                snprintf(pbuf, sizeof(pbuf), "%d", HTTPS_PORT);
                    384:                error = getaddrinfo(host, pbuf, &hints, &res0);
1.78      martynas  385: #endif /* !SMALL */
1.30      deraadt   386:        }
1.25      itojun    387:        if (error) {
                    388:                warnx("%s: %s", gai_strerror(error), host);
                    389:                goto cleanup_url_get;
1.1       millert   390:        }
                    391:
1.25      itojun    392:        s = -1;
                    393:        for (res = res0; res; res = res->ai_next) {
1.44      itojun    394:                if (getnameinfo(res->ai_addr, res->ai_addrlen, hbuf,
                    395:                    sizeof(hbuf), NULL, 0, NI_NUMERICHOST) != 0)
                    396:                        strlcpy(hbuf, "(unknown)", sizeof(hbuf));
1.41      deraadt   397:                if (verbose)
1.44      itojun    398:                        fprintf(ttyout, "Trying %s...\n", hbuf);
1.14      millert   399:
1.25      itojun    400:                s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
                    401:                if (s == -1) {
                    402:                        cause = "socket";
                    403:                        continue;
1.1       millert   404:                }
                    405:
1.25      itojun    406: again:
                    407:                if (connect(s, res->ai_addr, res->ai_addrlen) < 0) {
1.57      otto      408:                        int save_errno;
                    409:
1.25      itojun    410:                        if (errno == EINTR)
                    411:                                goto again;
1.57      otto      412:                        save_errno = errno;
1.25      itojun    413:                        close(s);
1.57      otto      414:                        errno = save_errno;
1.25      itojun    415:                        s = -1;
                    416:                        cause = "connect";
1.19      deraadt   417:                        continue;
                    418:                }
1.25      itojun    419:
1.29      itojun    420:                /* get port in numeric */
                    421:                if (getnameinfo(res->ai_addr, res->ai_addrlen, NULL, 0,
                    422:                    pbuf, sizeof(pbuf), NI_NUMERICSERV) == 0)
                    423:                        port = pbuf;
                    424:                else
                    425:                        port = NULL;
                    426:
1.61      deraadt   427: #ifndef SMALL
                    428:                if (proxyenv && sslhost)
1.81      espie     429:                        proxy_connect(s, sslhost, cookie);
1.78      martynas  430: #endif /* !SMALL */
1.25      itojun    431:                break;
                    432:        }
                    433:        freeaddrinfo(res0);
                    434:        if (s < 0) {
1.33      millert   435:                warn("%s", cause);
1.6       millert   436:                goto cleanup_url_get;
1.1       millert   437:        }
                    438:
1.61      deraadt   439: #ifndef SMALL
                    440:        if (ishttpsurl) {
                    441:                if (proxyenv && sslpath) {
                    442:                        ishttpsurl = 0;
1.62      ray       443:                        proxyurl = NULL;
1.61      deraadt   444:                        path = sslpath;
                    445:                }
                    446:                SSL_library_init();
                    447:                SSL_load_error_strings();
                    448:                SSLeay_add_ssl_algorithms();
                    449:                ssl_ctx = SSL_CTX_new(SSLv23_client_method());
                    450:                ssl = SSL_new(ssl_ctx);
                    451:                if (ssl == NULL || ssl_ctx == NULL) {
                    452:                        ERR_print_errors_fp(ttyout);
                    453:                        goto cleanup_url_get;
                    454:                }
                    455:                if (SSL_set_fd(ssl, s) == 0) {
                    456:                        ERR_print_errors_fp(ttyout);
                    457:                        goto cleanup_url_get;
                    458:                }
                    459:                if (SSL_connect(ssl) <= 0) {
                    460:                        ERR_print_errors_fp(ttyout);
1.72      ray       461:                        goto cleanup_url_get;
1.61      deraadt   462:                }
                    463:        } else {
                    464:                fin = fdopen(s, "r+");
                    465:        }
1.78      martynas  466: #else /* !SMALL */
1.40      fgsch     467:        fin = fdopen(s, "r+");
1.78      martynas  468: #endif /* !SMALL */
1.40      fgsch     469:
1.55      fgsch     470:        if (verbose)
                    471:                fprintf(ttyout, "Requesting %s", origline);
1.1       millert   472:        /*
1.40      fgsch     473:         * Construct and send the request. Proxy requests don't want leading /.
1.1       millert   474:         */
1.74      pyr       475: #ifndef SMALL
                    476:        cookie_get(host, path, ishttpsurl, &buf);
1.78      martynas  477: #endif /* !SMALL */
1.62      ray       478:        if (proxyurl) {
1.55      fgsch     479:                if (verbose)
1.81      espie     480:                        fprintf(ttyout, " (via %s)\n", proxyurl);
1.32      itojun    481:                /*
                    482:                 * Host: directive must use the destination host address for
                    483:                 * the original URI (path).  We do not attach it at this moment.
                    484:                 */
1.73      drahn     485:                if (cookie)
                    486:                        ftp_printf(fin, ssl, "GET %s HTTP/1.0\r\n"
1.74      pyr       487:                            "Proxy-Authorization: Basic %s%s\r\n%s\r\n\r\n",
                    488:                            path, cookie, buf ? buf : "", HTTP_USER_AGENT);
1.73      drahn     489:                else
1.74      pyr       490:                        ftp_printf(fin, ssl, "GET %s HTTP/1.0\r\n%s%s\r\n\r\n",
                    491:                            path, buf ? buf : "", HTTP_USER_AGENT);
1.73      drahn     492:
1.28      itojun    493:        } else {
1.90    ! martynas  494: #ifndef SMALL
        !           495:                if (resume) {
        !           496:                        struct stat stbuf;
        !           497:
        !           498:                        if (stat(savefile, &stbuf) == 0)
        !           499:                                restart_point = stbuf.st_size;
        !           500:                        else
        !           501:                                restart_point = 0;
        !           502:                }
        !           503: #endif /* !SMALL */
1.75      martynas  504:                ftp_printf(fin, ssl, "GET /%s %s\r\nHost: ", path,
                    505: #ifndef SMALL
1.90    ! martynas  506:                        restart_point ? "HTTP/1.1" :
1.78      martynas  507: #endif /* !SMALL */
1.75      martynas  508:                        "HTTP/1.0");
1.32      itojun    509:                if (strchr(host, ':')) {
                    510:                        char *h, *p;
                    511:
1.55      fgsch     512:                        /*
                    513:                         * strip off scoped address portion, since it's
                    514:                         * local to node
                    515:                         */
1.32      itojun    516:                        h = strdup(host);
                    517:                        if (h == NULL)
                    518:                                errx(1, "Can't allocate memory.");
                    519:                        if ((p = strchr(h, '%')) != NULL)
                    520:                                *p = '\0';
1.61      deraadt   521:                        ftp_printf(fin, ssl, "[%s]", h);
1.32      itojun    522:                        free(h);
1.55      fgsch     523:                } else
1.61      deraadt   524:                        ftp_printf(fin, ssl, "%s", host);
1.55      fgsch     525:
                    526:                /*
                    527:                 * Send port number only if it's specified and does not equal
                    528:                 * 80. Some broken HTTP servers get confused if you explicitly
                    529:                 * send them the port number.
                    530:                 */
1.61      deraadt   531: #ifndef SMALL
                    532:                if (port && strcmp(port, (ishttpsurl ? "443" : "80")) != 0)
                    533:                        ftp_printf(fin, ssl, ":%s", port);
1.90    ! martynas  534:                if (restart_point)
1.75      martynas  535:                        ftp_printf(fin, ssl, "\r\nRange: bytes=%lld-",
                    536:                                (long long)restart_point);
1.78      martynas  537: #else /* !SMALL */
1.55      fgsch     538:                if (port && strcmp(port, "80") != 0)
1.61      deraadt   539:                        ftp_printf(fin, ssl, ":%s", port);
1.78      martynas  540: #endif /* !SMALL */
1.74      pyr       541:                ftp_printf(fin, ssl, "\r\n%s%s\r\n\r\n",
                    542:                    buf ? buf : "", HTTP_USER_AGENT);
1.55      fgsch     543:                if (verbose)
                    544:                        fprintf(ttyout, "\n");
1.28      itojun    545:        }
1.74      pyr       546:
                    547:
                    548: #ifndef SMALL
                    549:        free(buf);
1.78      martynas  550: #endif /* !SMALL */
1.74      pyr       551:        buf = NULL;
                    552:
1.61      deraadt   553:        if (fin != NULL && fflush(fin) == EOF) {
1.14      millert   554:                warn("Writing HTTP request");
1.6       millert   555:                goto cleanup_url_get;
1.1       millert   556:        }
1.61      deraadt   557:        if ((buf = ftp_readline(fin, ssl, &len)) == NULL) {
1.40      fgsch     558:                warn("Receiving HTTP reply");
                    559:                goto cleanup_url_get;
1.1       millert   560:        }
1.40      fgsch     561:
                    562:        while (len > 0 && (buf[len-1] == '\r' || buf[len-1] == '\n'))
                    563:                buf[--len] = '\0';
1.80      martynas  564: #ifndef SMALL
1.40      fgsch     565:        if (debug)
                    566:                fprintf(ttyout, "received '%s'\n", buf);
1.80      martynas  567: #endif /* !SMALL */
1.40      fgsch     568:
1.1       millert   569:        cp = strchr(buf, ' ');
                    570:        if (cp == NULL)
                    571:                goto improper;
                    572:        else
                    573:                cp++;
1.69      jsg       574:
                    575:        strlcpy(ststr, cp, sizeof(ststr));
1.75      martynas  576:        status = strtonum(ststr, 200, 416, &errstr);
1.69      jsg       577:        if (errstr) {
                    578:                warnx("Error retrieving file: %s", cp);
                    579:                goto cleanup_url_get;
                    580:        }
                    581:
                    582:        switch (status) {
                    583:        case 200:       /* OK */
1.75      martynas  584: #ifndef SMALL
                    585:        case 206:       /* Partial Content */
1.69      jsg       586:                break;
1.78      martynas  587: #endif /* !SMALL */
1.69      jsg       588:        case 301:       /* Moved Permanently */
                    589:        case 302:       /* Found */
                    590:        case 303:       /* See Other */
                    591:        case 307:       /* Temporary Redirect */
1.40      fgsch     592:                isredirect++;
1.54      fgsch     593:                if (redirect_loop++ > 10) {
                    594:                        warnx("Too many redirections requested");
                    595:                        goto cleanup_url_get;
                    596:                }
1.69      jsg       597:                break;
1.75      martynas  598: #ifndef SMALL
                    599:        case 416:       /* Requested Range Not Satisfiable */
                    600:                warnx("File is already fully retrieved.");
                    601:                goto cleanup_url_get;
1.78      martynas  602: #endif /* !SMALL */
1.69      jsg       603:        default:
1.1       millert   604:                warnx("Error retrieving file: %s", cp);
1.6       millert   605:                goto cleanup_url_get;
1.1       millert   606:        }
                    607:
                    608:        /*
                    609:         * Read the rest of the header.
                    610:         */
1.40      fgsch     611:        free(buf);
                    612:        filesize = -1;
                    613:
1.62      ray       614:        for (;;) {
1.61      deraadt   615:                if ((buf = ftp_readline(fin, ssl, &len)) == NULL) {
1.40      fgsch     616:                        warn("Receiving HTTP reply");
                    617:                        goto cleanup_url_get;
                    618:                }
1.61      deraadt   619:
1.40      fgsch     620:                while (len > 0 && (buf[len-1] == '\r' || buf[len-1] == '\n'))
                    621:                        buf[--len] = '\0';
                    622:                if (len == 0)
1.1       millert   623:                        break;
1.80      martynas  624: #ifndef SMALL
1.40      fgsch     625:                if (debug)
                    626:                        fprintf(ttyout, "received '%s'\n", buf);
1.80      martynas  627: #endif /* !SMALL */
1.1       millert   628:
1.40      fgsch     629:                /* Look for some headers */
                    630:                cp = buf;
1.1       millert   631: #define CONTENTLEN "Content-Length: "
1.40      fgsch     632:                if (strncasecmp(cp, CONTENTLEN, sizeof(CONTENTLEN) - 1) == 0) {
                    633:                        cp += sizeof(CONTENTLEN) - 1;
1.58      grunk     634:                        filesize = strtonum(cp, 0, LLONG_MAX, &errstr);
                    635:                        if (errstr != NULL)
1.40      fgsch     636:                                goto improper;
1.75      martynas  637: #ifndef SMALL
1.90    ! martynas  638:                        if (restart_point)
1.75      martynas  639:                                filesize += restart_point;
1.78      martynas  640: #endif /* !SMALL */
1.40      fgsch     641: #define LOCATION "Location: "
                    642:                } else if (isredirect &&
                    643:                    strncasecmp(cp, LOCATION, sizeof(LOCATION) - 1) == 0) {
                    644:                        cp += sizeof(LOCATION) - 1;
                    645:                        if (verbose)
                    646:                                fprintf(ttyout, "Redirected to %s\n", cp);
                    647:                        if (fin != NULL)
                    648:                                fclose(fin);
                    649:                        else if (s != -1)
                    650:                                close(s);
1.67      steven    651:                        free(proxyurl);
1.62      ray       652:                        free(newline);
1.81      espie     653:                        free(cookie);
1.40      fgsch     654:                        rval = url_get(cp, proxyenv, outfile);
1.67      steven    655:                        free(buf);
1.40      fgsch     656:                        return (rval);
                    657:                }
1.1       millert   658:        }
                    659:
1.17      millert   660:        /* Open the output file.  */
                    661:        if (strcmp(savefile, "-") != 0) {
1.75      martynas  662: #ifndef SMALL
                    663:                if (resume)
1.83      martynas  664:                        out = open(savefile, O_CREAT | O_WRONLY | O_APPEND,
                    665:                                0666);
1.75      martynas  666:                else
1.78      martynas  667: #endif /* !SMALL */
1.75      martynas  668:                        out = open(savefile, O_CREAT | O_WRONLY | O_TRUNC,
                    669:                                0666);
1.10      deraadt   670:                if (out < 0) {
                    671:                        warn("Can't open %s", savefile);
                    672:                        goto cleanup_url_get;
                    673:                }
                    674:        } else
1.17      millert   675:                out = fileno(stdout);
1.1       millert   676:
                    677:        /* Trap signals */
                    678:        oldintr = NULL;
                    679:        if (setjmp(httpabort)) {
                    680:                if (oldintr)
1.2       millert   681:                        (void)signal(SIGINT, oldintr);
1.6       millert   682:                goto cleanup_url_get;
1.1       millert   683:        }
                    684:        oldintr = signal(SIGINT, aborthttp);
                    685:
                    686:        bytes = 0;
                    687:        hashbytes = mark;
1.84      martynas  688:        progressmeter(-1, path);
1.43      millert   689:
                    690:        free(buf);
1.1       millert   691:
                    692:        /* Finally, suck down the file. */
1.40      fgsch     693:        if ((buf = malloc(4096)) == NULL)
1.47      deraadt   694:                errx(1, "Can't allocate memory for transfer buffer");
1.1       millert   695:        i = 0;
1.61      deraadt   696:        len = 1;
                    697:        while (len > 0) {
                    698:                len = ftp_read(fin, ssl, buf, 4096);
1.1       millert   699:                bytes += len;
1.61      deraadt   700:                for (cp = buf, wlen = len; wlen > 0; wlen -= i, cp += i) {
                    701:                        if ((i = write(out, cp, wlen)) == -1) {
1.1       millert   702:                                warn("Writing %s", savefile);
1.6       millert   703:                                goto cleanup_url_get;
1.1       millert   704:                        }
                    705:                        else if (i == 0)
                    706:                                break;
                    707:                }
                    708:                if (hash && !progress) {
                    709:                        while (bytes >= hashbytes) {
1.10      deraadt   710:                                (void)putc('#', ttyout);
1.1       millert   711:                                hashbytes += mark;
                    712:                        }
1.10      deraadt   713:                        (void)fflush(ttyout);
1.1       millert   714:                }
                    715:        }
                    716:        if (hash && !progress && bytes > 0) {
                    717:                if (bytes < mark)
1.10      deraadt   718:                        (void)putc('#', ttyout);
                    719:                (void)putc('\n', ttyout);
                    720:                (void)fflush(ttyout);
1.1       millert   721:        }
                    722:        if (len != 0) {
                    723:                warn("Reading from socket");
1.6       millert   724:                goto cleanup_url_get;
1.1       millert   725:        }
1.84      martynas  726:        progressmeter(1, NULL);
1.75      martynas  727:        if (
                    728: #ifndef SMALL
                    729:                !resume &&
1.78      martynas  730: #endif /* !SMALL */
1.75      martynas  731:                filesize != -1 && len == 0 && bytes != filesize) {
1.24      deraadt   732:                if (verbose)
                    733:                        fputs("Read short file.\n", ttyout);
                    734:                goto cleanup_url_get;
                    735:        }
                    736:
1.1       millert   737:        if (verbose)
1.10      deraadt   738:                fputs("Successfully retrieved file.\n", ttyout);
1.2       millert   739:        (void)signal(SIGINT, oldintr);
1.1       millert   740:
1.40      fgsch     741:        rval = 0;
                    742:        goto cleanup_url_get;
1.1       millert   743:
1.14      millert   744: noftpautologin:
                    745:        warnx(
                    746:            "Auto-login using ftp URLs isn't supported when using $ftp_proxy");
                    747:        goto cleanup_url_get;
                    748:
1.1       millert   749: improper:
1.8       millert   750:        warnx("Improper response from %s", host);
1.14      millert   751:
1.6       millert   752: cleanup_url_get:
1.61      deraadt   753: #ifndef SMALL
                    754:        if (ssl) {
                    755:                SSL_shutdown(ssl);
                    756:                SSL_free(ssl);
                    757:        }
1.78      martynas  758: #endif /* !SMALL */
1.40      fgsch     759:        if (fin != NULL)
                    760:                fclose(fin);
                    761:        else if (s != -1)
1.1       millert   762:                close(s);
1.67      steven    763:        free(buf);
                    764:        free(proxyurl);
1.62      ray       765:        free(newline);
1.81      espie     766:        free(cookie);
1.40      fgsch     767:        return (rval);
1.1       millert   768: }
                    769:
                    770: /*
                    771:  * Abort a http retrieval
                    772:  */
1.51      deraadt   773: /* ARGSUSED */
1.1       millert   774: void
1.51      deraadt   775: aborthttp(int signo)
1.1       millert   776: {
                    777:
                    778:        alarmtimer(0);
1.10      deraadt   779:        fputs("\nhttp fetch aborted.\n", ttyout);
                    780:        (void)fflush(ttyout);
1.1       millert   781:        longjmp(httpabort, 1);
                    782: }
                    783:
                    784: /*
1.22      deraadt   785:  * Abort a http retrieval
                    786:  */
1.51      deraadt   787: /* ARGSUSED */
1.22      deraadt   788: void
1.51      deraadt   789: abortfile(int signo)
1.22      deraadt   790: {
                    791:
                    792:        alarmtimer(0);
                    793:        fputs("\nfile fetch aborted.\n", ttyout);
                    794:        (void)fflush(ttyout);
                    795:        longjmp(httpabort, 1);
                    796: }
                    797:
                    798: /*
1.1       millert   799:  * Retrieve multiple files from the command line, transferring
                    800:  * files of the form "host:path", "ftp://host/path" using the
                    801:  * ftp protocol, and files of the form "http://host/path" using
                    802:  * the http protocol.
1.2       millert   803:  * If path has a trailing "/", then return (-1);
1.1       millert   804:  * the path will be cd-ed into and the connection remains open,
                    805:  * and the function will return -1 (to indicate the connection
                    806:  * is alive).
                    807:  * If an error occurs the return value will be the offset+1 in
                    808:  * argv[] of the file that caused a problem (i.e, argv[x]
                    809:  * returns x+1)
                    810:  * Otherwise, 0 is returned if all files retrieved successfully.
                    811:  */
                    812: int
1.50      deraadt   813: auto_fetch(int argc, char *argv[], char *outfile)
1.1       millert   814: {
                    815:        char *xargv[5];
1.62      ray       816:        char *cp, *url, *host, *dir, *file, *portnum;
                    817:        char *username, *pass, *pathstart;
1.6       millert   818:        char *ftpproxy, *httpproxy;
1.14      millert   819:        int rval, xargc;
                    820:        volatile int argpos;
1.49      krw       821:        int dirhasglob, filehasglob, oautologin;
1.14      millert   822:        char rempath[MAXPATHLEN];
1.1       millert   823:
                    824:        argpos = 0;
                    825:
                    826:        if (setjmp(toplevel)) {
                    827:                if (connected)
                    828:                        disconnect(0, NULL);
1.2       millert   829:                return (argpos + 1);
1.1       millert   830:        }
1.3       millert   831:        (void)signal(SIGINT, (sig_t)intr);
                    832:        (void)signal(SIGPIPE, (sig_t)lostpeer);
1.1       millert   833:
1.45      millert   834:        if ((ftpproxy = getenv(FTP_PROXY)) != NULL && *ftpproxy == '\0')
                    835:                ftpproxy = NULL;
                    836:        if ((httpproxy = getenv(HTTP_PROXY)) != NULL && *httpproxy == '\0')
                    837:                httpproxy = NULL;
1.6       millert   838:
1.1       millert   839:        /*
                    840:         * Loop through as long as there's files to fetch.
                    841:         */
1.62      ray       842:        for (rval = 0; (rval == 0) && (argpos < argc); free(url), argpos++) {
1.1       millert   843:                if (strchr(argv[argpos], ':') == NULL)
                    844:                        break;
1.62      ray       845:                host = dir = file = portnum = username = pass = NULL;
1.1       millert   846:
                    847:                /*
                    848:                 * We muck with the string, so we make a copy.
                    849:                 */
1.62      ray       850:                url = strdup(argv[argpos]);
                    851:                if (url == NULL)
1.1       millert   852:                        errx(1, "Can't allocate memory for auto-fetch.");
                    853:
                    854:                /*
                    855:                 * Try HTTP URL-style arguments first.
                    856:                 */
1.62      ray       857:                if (strncasecmp(url, HTTP_URL, sizeof(HTTP_URL) - 1) == 0 ||
1.61      deraadt   858: #ifndef SMALL
                    859:                    /* even if we compiled without SSL, url_get will check */
1.62      ray       860:                    strncasecmp(url, HTTPS_URL, sizeof(HTTPS_URL) -1) == 0 ||
1.78      martynas  861: #endif /* !SMALL */
1.62      ray       862:                    strncasecmp(url, FILE_URL, sizeof(FILE_URL) - 1) == 0) {
1.54      fgsch     863:                        redirect_loop = 0;
1.62      ray       864:                        if (url_get(url, httpproxy, outfile) == -1)
1.1       millert   865:                                rval = argpos + 1;
                    866:                        continue;
                    867:                }
                    868:
                    869:                /*
1.6       millert   870:                 * Try FTP URL-style arguments next. If ftpproxy is
                    871:                 * set, use url_get() instead of standard ftp.
                    872:                 * Finally, try host:file.
1.1       millert   873:                 */
1.62      ray       874:                host = url;
                    875:                if (strncasecmp(url, FTP_URL, sizeof(FTP_URL) - 1) == 0) {
1.37      heko      876:                        char *passend, *passagain, *userend;
1.31      itojun    877:
1.6       millert   878:                        if (ftpproxy) {
1.62      ray       879:                                if (url_get(url, ftpproxy, outfile) == -1)
1.6       millert   880:                                        rval = argpos + 1;
                    881:                                continue;
                    882:                        }
1.1       millert   883:                        host += sizeof(FTP_URL) - 1;
1.8       millert   884:                        dir = strchr(host, '/');
1.1       millert   885:
1.8       millert   886:                        /* Look for [user:pass@]host[:port] */
1.31      itojun    887:
                    888:                        /* check if we have "user:pass@" */
1.37      heko      889:                        userend = strchr(host, ':');
1.31      itojun    890:                        passend = strchr(host, '@');
                    891:                        if (passend && userend && userend < passend &&
                    892:                            (!dir || passend < dir)) {
1.62      ray       893:                                username = host;
1.31      itojun    894:                                pass = userend + 1;
                    895:                                host = passend + 1;
                    896:                                *userend = *passend = '\0';
1.37      heko      897:                                passagain = strchr(host, '@');
1.42      deraadt   898:                                if (strchr(pass, '@') != NULL ||
1.37      heko      899:                                    (passagain != NULL && passagain < dir)) {
                    900:                                        warnx(at_encoding_warning);
                    901:                                        goto bad_ftp_url;
1.42      deraadt   902:                                }
1.31      itojun    903:
1.77      martynas  904:                                if (EMPTYSTRING(username)) {
1.11      millert   905: bad_ftp_url:
1.31      itojun    906:                                        warnx("Invalid URL: %s", argv[argpos]);
                    907:                                        rval = argpos + 1;
                    908:                                        continue;
                    909:                                }
1.62      ray       910:                                username = urldecode(username);
1.37      heko      911:                                pass = urldecode(pass);
1.8       millert   912:                        }
1.31      itojun    913:
                    914: #ifdef INET6
                    915:                        /* check [host]:port, or [host] */
                    916:                        if (host[0] == '[') {
                    917:                                cp = strchr(host, ']');
                    918:                                if (cp && (!dir || cp < dir)) {
                    919:                                        if (cp + 1 == dir || cp[1] == ':') {
                    920:                                                host++;
                    921:                                                *cp++ = '\0';
                    922:                                        } else
                    923:                                                cp = NULL;
                    924:                                } else
                    925:                                        cp = host;
1.25      itojun    926:                        } else
                    927:                                cp = host;
1.31      itojun    928: #else
                    929:                        cp = host;
1.25      itojun    930: #endif
1.31      itojun    931:
                    932:                        /* split off host[:port] if there is */
                    933:                        if (cp) {
                    934:                                portnum = strchr(cp, ':');
1.52      henning   935:                                pathstart = strchr(cp, '/');
                    936:                                /* : in path is not a port # indicator */
                    937:                                if (portnum && pathstart &&
                    938:                                    pathstart < portnum)
                    939:                                        portnum = NULL;
                    940:
1.31      itojun    941:                                if (!portnum)
                    942:                                        ;
                    943:                                else {
                    944:                                        if (!dir)
                    945:                                                ;
                    946:                                        else if (portnum + 1 < dir) {
                    947:                                                *portnum++ = '\0';
                    948:                                                /*
                    949:                                                 * XXX should check if portnum
                    950:                                                 * is decimal number
                    951:                                                 */
                    952:                                        } else {
                    953:                                                /* empty portnum */
                    954:                                                goto bad_ftp_url;
                    955:                                        }
                    956:                                }
                    957:                        } else
                    958:                                portnum = NULL;
1.8       millert   959:                } else {                        /* classic style `host:file' */
                    960:                        dir = strchr(host, ':');
                    961:                }
1.1       millert   962:                if (EMPTYSTRING(host)) {
                    963:                        rval = argpos + 1;
                    964:                        continue;
                    965:                }
                    966:
                    967:                /*
1.9       millert   968:                 * If dir is NULL, the file wasn't specified
1.1       millert   969:                 * (URL looked something like ftp://host)
                    970:                 */
1.8       millert   971:                if (dir != NULL)
                    972:                        *dir++ = '\0';
1.1       millert   973:
                    974:                /*
                    975:                 * Extract the file and (if present) directory name.
                    976:                 */
1.42      deraadt   977:                if (!EMPTYSTRING(dir)) {
1.8       millert   978:                        cp = strrchr(dir, '/');
1.1       millert   979:                        if (cp != NULL) {
                    980:                                *cp++ = '\0';
                    981:                                file = cp;
                    982:                        } else {
                    983:                                file = dir;
                    984:                                dir = NULL;
                    985:                        }
                    986:                }
1.80      martynas  987: #ifndef SMALL
1.1       millert   988:                if (debug)
1.42      deraadt   989:                        fprintf(ttyout,
                    990:                            "user %s:%s host %s port %s dir %s file %s\n",
1.76      martynas  991:                            username, pass ? "XXXX" : NULL, host, portnum,
                    992:                            dir, file);
1.80      martynas  993: #endif /* !SMALL */
1.1       millert   994:
                    995:                /*
1.49      krw       996:                 * Set up the connection.
1.1       millert   997:                 */
1.49      krw       998:                if (connected)
                    999:                        disconnect(0, NULL);
                   1000:                xargv[0] = __progname;
                   1001:                xargv[1] = host;
1.8       millert  1002:                xargv[2] = NULL;
1.49      krw      1003:                xargc = 2;
                   1004:                if (!EMPTYSTRING(portnum)) {
                   1005:                        xargv[2] = portnum;
                   1006:                        xargv[3] = NULL;
                   1007:                        xargc = 3;
                   1008:                }
                   1009:                oautologin = autologin;
1.88      martynas 1010:                if (username == NULL)
1.89      halex    1011:                        anonftp = 1;
                   1012:                else {
                   1013:                        anonftp = 0;
1.49      krw      1014:                        autologin = 0;
1.89      halex    1015:                }
1.49      krw      1016:                setpeer(xargc, xargv);
                   1017:                autologin = oautologin;
1.87      martynas 1018:                if (connected == 0 ||
                   1019:                    (connected == 1 && autologin && (username == NULL ||
                   1020:                    !ftp_login(host, username, pass)))) {
1.49      krw      1021:                        warnx("Can't connect or login to host `%s'", host);
1.8       millert  1022:                        rval = argpos + 1;
                   1023:                        continue;
1.1       millert  1024:                }
1.49      krw      1025:
                   1026:                /* Always use binary transfers. */
                   1027:                setbinary(0, NULL);
1.1       millert  1028:
1.4       millert  1029:                dirhasglob = filehasglob = 0;
                   1030:                if (doglob) {
1.42      deraadt  1031:                        if (!EMPTYSTRING(dir) &&
1.4       millert  1032:                            strpbrk(dir, "*?[]{}") != NULL)
                   1033:                                dirhasglob = 1;
1.42      deraadt  1034:                        if (!EMPTYSTRING(file) &&
1.4       millert  1035:                            strpbrk(file, "*?[]{}") != NULL)
                   1036:                                filehasglob = 1;
                   1037:                }
                   1038:
1.1       millert  1039:                /* Change directories, if necessary. */
1.42      deraadt  1040:                if (!EMPTYSTRING(dir) && !dirhasglob) {
1.1       millert  1041:                        xargv[0] = "cd";
                   1042:                        xargv[1] = dir;
                   1043:                        xargv[2] = NULL;
                   1044:                        cd(2, xargv);
1.42      deraadt  1045:                        if (!dirchange) {
1.1       millert  1046:                                rval = argpos + 1;
                   1047:                                continue;
                   1048:                        }
                   1049:                }
                   1050:
                   1051:                if (EMPTYSTRING(file)) {
1.86      martynas 1052: #ifndef SMALL
1.1       millert  1053:                        rval = -1;
1.86      martynas 1054: #else /* !SMALL */
                   1055:                        recvrequest("NLST", "-", NULL, "w", 0, 0);
                   1056:                        rval = 0;
                   1057: #endif /* !SMALL */
1.1       millert  1058:                        continue;
                   1059:                }
                   1060:
1.21      marc     1061:                if (verbose)
1.10      deraadt  1062:                        fprintf(ttyout, "Retrieving %s/%s\n", dir ? dir : "", file);
1.1       millert  1063:
1.4       millert  1064:                if (dirhasglob) {
                   1065:                        snprintf(rempath, sizeof(rempath), "%s/%s", dir, file);
                   1066:                        file = rempath;
                   1067:                }
                   1068:
                   1069:                /* Fetch the file(s). */
1.10      deraadt  1070:                xargc = 2;
1.1       millert  1071:                xargv[0] = "get";
                   1072:                xargv[1] = file;
                   1073:                xargv[2] = NULL;
1.4       millert  1074:                if (dirhasglob || filehasglob) {
                   1075:                        int ointeractive;
                   1076:
                   1077:                        ointeractive = interactive;
                   1078:                        interactive = 0;
                   1079:                        xargv[0] = "mget";
1.78      martynas 1080: #ifndef SMALL
                   1081:                        if (resume) {
                   1082:                                xargc = 3;
                   1083:                                xargv[1] = "-c";
                   1084:                                xargv[2] = file;
                   1085:                                xargv[3] = NULL;
                   1086:                        }
                   1087: #endif /* !SMALL */
1.10      deraadt  1088:                        mget(xargc, xargv);
1.5       millert  1089:                        interactive = ointeractive;
1.10      deraadt  1090:                } else {
1.17      millert  1091:                        if (outfile != NULL) {
                   1092:                                xargv[2] = outfile;
                   1093:                                xargv[3] = NULL;
1.10      deraadt  1094:                                xargc++;
                   1095:                        }
1.75      martynas 1096: #ifndef SMALL
                   1097:                        if (resume)
                   1098:                                reget(xargc, xargv);
                   1099:                        else
1.78      martynas 1100: #endif /* !SMALL */
1.75      martynas 1101:                                get(xargc, xargv);
1.10      deraadt  1102:                }
1.1       millert  1103:
1.4       millert  1104:                if ((code / 100) != COMPLETE)
1.1       millert  1105:                        rval = argpos + 1;
                   1106:        }
                   1107:        if (connected && rval != -1)
                   1108:                disconnect(0, NULL);
                   1109:        return (rval);
1.37      heko     1110: }
                   1111:
                   1112: char *
1.50      deraadt  1113: urldecode(const char *str)
1.37      heko     1114: {
1.53      deraadt  1115:        char *ret, c;
                   1116:        int i, reallen;
1.37      heko     1117:
1.53      deraadt  1118:        if (str == NULL)
                   1119:                return NULL;
                   1120:        if ((ret = malloc(strlen(str)+1)) == NULL)
                   1121:                err(1, "Can't allocate memory for URL decoding");
                   1122:        for (i = 0, reallen = 0; str[i] != '\0'; i++, reallen++, ret++) {
                   1123:                c = str[i];
                   1124:                if (c == '+') {
                   1125:                        *ret = ' ';
                   1126:                        continue;
                   1127:                }
1.61      deraadt  1128:
                   1129:                /* Cannot use strtol here because next char
                   1130:                 * after %xx may be a digit.
                   1131:                 */
1.53      deraadt  1132:                if (c == '%' && isxdigit(str[i+1]) && isxdigit(str[i+2])) {
                   1133:                        *ret = hextochar(&str[i+1]);
                   1134:                        i+=2;
                   1135:                        continue;
                   1136:                }
                   1137:                *ret = c;
                   1138:        }
                   1139:        *ret = '\0';
                   1140:
                   1141:        return ret-reallen;
1.37      heko     1142: }
                   1143:
                   1144: char
1.50      deraadt  1145: hextochar(const char *str)
1.37      heko     1146: {
1.53      deraadt  1147:        char c, ret;
1.37      heko     1148:
1.53      deraadt  1149:        c = str[0];
                   1150:        ret = c;
                   1151:        if (isalpha(c))
                   1152:                ret -= isupper(c) ? 'A' - 10 : 'a' - 10;
                   1153:        else
                   1154:                ret -= '0';
                   1155:        ret *= 16;
                   1156:
                   1157:        c = str[1];
                   1158:        ret += c;
                   1159:        if (isalpha(c))
                   1160:                ret -= isupper(c) ? 'A' - 10 : 'a' - 10;
                   1161:        else
                   1162:                ret -= '0';
                   1163:        return ret;
1.25      itojun   1164: }
                   1165:
                   1166: int
1.50      deraadt  1167: isurl(const char *p)
1.25      itojun   1168: {
1.27      millert  1169:
1.26      deraadt  1170:        if (strncasecmp(p, FTP_URL, sizeof(FTP_URL) - 1) == 0 ||
                   1171:            strncasecmp(p, HTTP_URL, sizeof(HTTP_URL) - 1) == 0 ||
1.61      deraadt  1172: #ifndef SMALL
                   1173:            strncasecmp(p, HTTPS_URL, sizeof(HTTPS_URL) - 1) == 0 ||
1.78      martynas 1174: #endif /* !SMALL */
1.27      millert  1175:            strncasecmp(p, FILE_URL, sizeof(FILE_URL) - 1) == 0 ||
                   1176:            strstr(p, ":/"))
                   1177:                return (1);
                   1178:        return (0);
1.1       millert  1179: }
1.61      deraadt  1180:
                   1181: char *
                   1182: ftp_readline(FILE *fp, SSL *ssl, size_t *lenp)
                   1183: {
                   1184:        if (fp != NULL)
                   1185:                return fparseln(fp, lenp, NULL, "\0\0\0", 0);
                   1186: #ifndef SMALL
                   1187:        else if (ssl != NULL)
                   1188:                return SSL_readline(ssl, lenp);
1.78      martynas 1189: #endif /* !SMALL */
1.61      deraadt  1190:        else
                   1191:                return NULL;
                   1192: }
                   1193:
1.65      ray      1194: size_t
1.61      deraadt  1195: ftp_read(FILE *fp, SSL *ssl, char *buf, size_t len)
                   1196: {
1.65      ray      1197:        size_t ret;
1.61      deraadt  1198:        if (fp != NULL)
                   1199:                ret = fread(buf, sizeof(char), len, fp);
                   1200: #ifndef SMALL
1.65      ray      1201:        else if (ssl != NULL) {
                   1202:                int nr;
                   1203:
                   1204:                if (len > INT_MAX)
                   1205:                        len = INT_MAX;
                   1206:                if ((nr = SSL_read(ssl, buf, (int)len)) <= 0)
                   1207:                        ret = 0;
                   1208:                else
                   1209:                        ret = nr;
                   1210:        }
1.78      martynas 1211: #endif /* !SMALL */
1.61      deraadt  1212:        else
                   1213:                ret = 0;
                   1214:        return (ret);
                   1215: }
                   1216:
                   1217: int
                   1218: ftp_printf(FILE *fp, SSL *ssl, const char *fmt, ...)
                   1219: {
                   1220:        int ret;
                   1221:        va_list ap;
                   1222:
                   1223:        va_start(ap, fmt);
                   1224:
                   1225:        if (fp != NULL)
                   1226:                ret = vfprintf(fp, fmt, ap);
                   1227: #ifndef SMALL
                   1228:        else if (ssl != NULL)
                   1229:                ret = SSL_vprintf((SSL*)ssl, fmt, ap);
1.78      martynas 1230: #endif /* !SMALL */
1.61      deraadt  1231:        else
                   1232:                ret = NULL;
                   1233:
                   1234:        va_end(ap);
                   1235:        return (ret);
                   1236: }
                   1237:
                   1238: #ifndef SMALL
                   1239: int
                   1240: SSL_vprintf(SSL *ssl, const char *fmt, va_list ap)
                   1241: {
                   1242:        int ret;
                   1243:        char *string;
                   1244:
                   1245:        if ((ret = vasprintf(&string, fmt, ap)) == -1)
                   1246:                return ret;
1.64      ray      1247:        ret = SSL_write(ssl, string, ret);
1.61      deraadt  1248:        free(string);
                   1249:        return ret;
                   1250: }
                   1251:
                   1252: char *
                   1253: SSL_readline(SSL *ssl, size_t *lenp)
                   1254: {
1.63      ray      1255:        size_t i, len;
1.61      deraadt  1256:        char *buf, *q, c;
                   1257:
                   1258:        len = 128;
                   1259:        if ((buf = malloc(len)) == NULL)
                   1260:                errx(1, "Can't allocate memory for transfer buffer");
                   1261:        for (i = 0; ; i++) {
                   1262:                if (i >= len - 1) {
                   1263:                        if ((q = realloc(buf, 2 * len)) == NULL)
                   1264:                                errx(1, "Can't expand transfer buffer");
                   1265:                        buf = q;
                   1266:                        len *= 2;
                   1267:                }
                   1268:                if (SSL_read(ssl, &c, 1) <= 0)
                   1269:                        break;
                   1270:                buf[i] = c;
                   1271:                if (c == '\n')
                   1272:                        break;
                   1273:        }
                   1274:        *lenp = i;
                   1275:        return (buf);
                   1276: }
                   1277:
                   1278: int
1.81      espie    1279: proxy_connect(int socket, char *host, char *cookie)
1.61      deraadt  1280: {
1.66      ray      1281:        int l;
1.61      deraadt  1282:        char buf[1024];
                   1283:        char *connstr, *hosttail, *port;
                   1284:
                   1285:        if (*host == '[' && (hosttail = strrchr(host, ']')) != NULL &&
                   1286:                (hosttail[1] == '\0' || hosttail[1] == ':')) {
                   1287:                host++;
                   1288:                *hosttail++ = '\0';
                   1289:        } else
                   1290:                hosttail = host;
                   1291:
                   1292:        port = strrchr(hosttail, ':');               /* find portnum */
                   1293:        if (port != NULL)
                   1294:                *port++ = '\0';
                   1295:        if (!port)
                   1296:                port = "443";
                   1297:
1.81      espie    1298:        if (cookie) {
                   1299:                l = asprintf(&connstr, "CONNECT %s:%s HTTP/1.1\r\n"
                   1300:                        "Proxy-Authorization: Basic %s\r\n%s\r\n\r\n",
                   1301:                        host, port, cookie, HTTP_USER_AGENT);
                   1302:        } else {
                   1303:                l = asprintf(&connstr, "CONNECT %s:%s HTTP/1.1\r\n%s\r\n\r\n",
                   1304:                        host, port, HTTP_USER_AGENT);
                   1305:        }
                   1306:
1.66      ray      1307:        if (l == -1)
1.61      deraadt  1308:                errx(1, "Could not allocate memory to assemble connect string!");
1.80      martynas 1309: #ifndef SMALL
1.68      ray      1310:        if (debug)
                   1311:                printf("%s", connstr);
1.80      martynas 1312: #endif /* !SMALL */
1.66      ray      1313:        if (write(socket, connstr, l) != l)
1.68      ray      1314:                err(1, "Could not send connect string");
1.61      deraadt  1315:        read(socket, &buf, sizeof(buf)); /* only proxy header XXX: error handling? */
1.71      ray      1316:        free(connstr);
1.61      deraadt  1317:        return(200);
                   1318: }
1.78      martynas 1319: #endif /* !SMALL */