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

Annotation of src/usr.bin/ftp/util.c, Revision 1.70

1.70    ! tedu        1: /*     $OpenBSD: util.c,v 1.69 2015/01/30 04:45:45 tedu Exp $  */
1.13      millert     2: /*     $NetBSD: util.c,v 1.12 1997/08/18 10:20:27 lukem Exp $  */
1.1       millert     3:
1.34      millert     4: /*-
                      5:  * Copyright (c) 1997-1999 The NetBSD Foundation, Inc.
                      6:  * All rights reserved.
                      7:  *
                      8:  * This code is derived from software contributed to The NetBSD Foundation
                      9:  * by Luke Mewburn.
                     10:  *
                     11:  * This code is derived from software contributed to The NetBSD Foundation
                     12:  * by Jason R. Thorpe of the Numerical Aerospace Simulation Facility,
                     13:  * NASA Ames Research Center.
                     14:  *
                     15:  * Redistribution and use in source and binary forms, with or without
                     16:  * modification, are permitted provided that the following conditions
                     17:  * are met:
                     18:  * 1. Redistributions of source code must retain the above copyright
                     19:  *    notice, this list of conditions and the following disclaimer.
                     20:  * 2. Redistributions in binary form must reproduce the above copyright
                     21:  *    notice, this list of conditions and the following disclaimer in the
                     22:  *    documentation and/or other materials provided with the distribution.
                     23:  *
                     24:  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
                     25:  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
                     26:  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
                     27:  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
                     28:  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
                     29:  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
                     30:  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
                     31:  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
                     32:  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
                     33:  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
                     34:  * POSSIBILITY OF SUCH DAMAGE.
                     35:  */
                     36:
1.1       millert    37: /*
                     38:  * Copyright (c) 1985, 1989, 1993, 1994
                     39:  *     The Regents of the University of California.  All rights reserved.
                     40:  *
                     41:  * Redistribution and use in source and binary forms, with or without
                     42:  * modification, are permitted provided that the following conditions
                     43:  * are met:
                     44:  * 1. Redistributions of source code must retain the above copyright
                     45:  *    notice, this list of conditions and the following disclaimer.
                     46:  * 2. Redistributions in binary form must reproduce the above copyright
                     47:  *    notice, this list of conditions and the following disclaimer in the
                     48:  *    documentation and/or other materials provided with the distribution.
1.35      millert    49:  * 3. Neither the name of the University nor the names of its contributors
1.1       millert    50:  *    may be used to endorse or promote products derived from this software
                     51:  *    without specific prior written permission.
                     52:  *
                     53:  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
                     54:  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
                     55:  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
                     56:  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
                     57:  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
                     58:  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
                     59:  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
                     60:  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
                     61:  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
                     62:  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
                     63:  * SUCH DAMAGE.
                     64:  */
                     65:
                     66: /*
                     67:  * FTP User Program -- Misc support routines
                     68:  */
                     69: #include <sys/ioctl.h>
                     70: #include <sys/time.h>
                     71: #include <arpa/ftp.h>
                     72:
                     73: #include <ctype.h>
                     74: #include <err.h>
1.3       millert    75: #include <errno.h>
1.1       millert    76: #include <fcntl.h>
1.41      otto       77: #include <libgen.h>
1.1       millert    78: #include <glob.h>
1.6       millert    79: #include <pwd.h>
1.3       millert    80: #include <signal.h>
1.1       millert    81: #include <stdio.h>
1.2       millert    82: #include <stdlib.h>
1.1       millert    83: #include <string.h>
                     84: #include <time.h>
1.17      deraadt    85: #include <tzfile.h>
1.1       millert    86: #include <unistd.h>
                     87:
                     88: #include "ftp_var.h"
                     89: #include "pathnames.h"
                     90:
1.68      deraadt    91: #define MINIMUM(a, b)  (((a) < (b)) ? (a) : (b))
                     92: #define MAXIMUM(a, b)  (((a) > (b)) ? (a) : (b))
                     93:
1.27      millert    94: static void updateprogressmeter(int);
1.20      millert    95:
1.1       millert    96: /*
                     97:  * Connect to peer server and
                     98:  * auto-login, if possible.
                     99:  */
                    100: void
1.38      deraadt   101: setpeer(int argc, char *argv[])
1.1       millert   102: {
1.40      deraadt   103:        char *host, *port;
1.1       millert   104:
                    105:        if (connected) {
1.7       deraadt   106:                fprintf(ttyout, "Already connected to %s, use close first.\n",
1.2       millert   107:                    hostname);
1.1       millert   108:                code = -1;
                    109:                return;
                    110:        }
1.62      martynas  111: #ifndef SMALL
1.1       millert   112:        if (argc < 2)
1.2       millert   113:                (void)another(&argc, &argv, "to");
1.1       millert   114:        if (argc < 2 || argc > 3) {
1.55      sobrado   115:                fprintf(ttyout, "usage: %s host [port]\n", argv[0]);
1.1       millert   116:                code = -1;
                    117:                return;
                    118:        }
1.62      martynas  119: #endif /* !SMALL */
1.13      millert   120:        if (gatemode)
                    121:                port = gateport;
                    122:        else
                    123:                port = ftpport;
1.22      itojun    124:        if (argc > 2)
                    125:                port = argv[2];
1.13      millert   126:
                    127:        if (gatemode) {
                    128:                if (gateserver == NULL || *gateserver == '\0')
                    129:                        errx(1, "gateserver not defined (shouldn't happen)");
                    130:                host = hookup(gateserver, port);
                    131:        } else
                    132:                host = hookup(argv[1], port);
                    133:
1.1       millert   134:        if (host) {
                    135:                int overbose;
                    136:
1.13      millert   137:                if (gatemode) {
                    138:                        if (command("PASSERVE %s", argv[1]) != COMPLETE)
                    139:                                return;
                    140:                        if (verbose)
                    141:                                fprintf(ttyout,
                    142:                                    "Connected via pass-through server %s\n",
                    143:                                    gateserver);
                    144:                }
                    145:
1.1       millert   146:                connected = 1;
                    147:                /*
                    148:                 * Set up defaults for FTP.
                    149:                 */
1.33      deraadt   150:                (void)strlcpy(formname, "non-print", sizeof formname);
                    151:                form = FORM_N;
                    152:                (void)strlcpy(modename, "stream", sizeof modename);
                    153:                mode = MODE_S;
                    154:                (void)strlcpy(structname, "file", sizeof structname);
                    155:                stru = STRU_F;
                    156:                (void)strlcpy(bytename, "8", sizeof bytename);
                    157:                bytesize = 8;
                    158:
1.25      millert   159:                /*
                    160:                 * Set type to 0 (not specified by user),
                    161:                 * meaning binary by default, but don't bother
                    162:                 * telling server.  We can use binary
                    163:                 * for text files unless changed by the user.
                    164:                 */
1.33      deraadt   165:                (void)strlcpy(typename, "binary", sizeof typename);
1.25      millert   166:                curtype = TYPE_A;
                    167:                type = 0;
1.1       millert   168:                if (autologin)
1.31      fgsch     169:                        (void)ftp_login(argv[1], NULL, NULL);
1.1       millert   170:
                    171:                overbose = verbose;
1.54      martynas  172: #ifndef SMALL
                    173:                if (!debug)
                    174: #endif /* !SMALL */
1.1       millert   175:                        verbose = -1;
                    176:                if (command("SYST") == COMPLETE && overbose) {
                    177:                        char *cp, c;
                    178:                        c = 0;
1.4       millert   179:                        cp = strchr(reply_string + 4, ' ');
1.1       millert   180:                        if (cp == NULL)
1.4       millert   181:                                cp = strchr(reply_string + 4, '\r');
1.1       millert   182:                        if (cp) {
                    183:                                if (cp[-1] == '.')
                    184:                                        cp--;
                    185:                                c = *cp;
                    186:                                *cp = '\0';
                    187:                        }
                    188:
1.7       deraadt   189:                        fprintf(ttyout, "Remote system type is %s.\n", reply_string + 4);
1.1       millert   190:                        if (cp)
                    191:                                *cp = c;
                    192:                }
                    193:                if (!strncmp(reply_string, "215 UNIX Type: L8", 17)) {
                    194:                        if (proxy)
                    195:                                unix_proxy = 1;
                    196:                        else
                    197:                                unix_server = 1;
                    198:                        if (overbose)
1.7       deraadt   199:                                fprintf(ttyout, "Using %s mode to transfer files.\n",
                    200:                                    typename);
1.1       millert   201:                } else {
                    202:                        if (proxy)
                    203:                                unix_proxy = 0;
                    204:                        else
                    205:                                unix_server = 0;
                    206:                }
                    207:                verbose = overbose;
                    208:        }
1.6       millert   209: }
                    210:
                    211: /*
                    212:  * login to remote host, using given username & password if supplied
                    213:  */
                    214: int
1.38      deraadt   215: ftp_login(const char *host, char *user, char *pass)
1.6       millert   216: {
1.68      deraadt   217:        char tmp[80], *acctname = NULL, host_name[HOST_NAME_MAX+1];
                    218:        char anonpass[LOGIN_NAME_MAX + 1 + HOST_NAME_MAX+1];    /* "user@hostname" */
1.40      deraadt   219:        int n, aflag = 0, retry = 0;
1.14      millert   220:        struct passwd *pw;
1.6       millert   221:
1.46      pyr       222: #ifndef SMALL
1.6       millert   223:        if (user == NULL) {
1.43      ray       224:                if (ruserpass(host, &user, &pass, &acctname) < 0) {
1.6       millert   225:                        code = -1;
                    226:                        return (0);
                    227:                }
                    228:        }
1.52      martynas  229: #endif /* !SMALL */
1.6       millert   230:
                    231:        /*
                    232:         * Set up arguments for an anonymous FTP session, if necessary.
                    233:         */
                    234:        if ((user == NULL || pass == NULL) && anonftp) {
                    235:                memset(anonpass, 0, sizeof(anonpass));
1.43      ray       236:                memset(host_name, 0, sizeof(host_name));
1.6       millert   237:
                    238:                /*
                    239:                 * Set up anonymous login password.
                    240:                 */
1.14      millert   241:                if ((user = getlogin()) == NULL) {
                    242:                        if ((pw = getpwuid(getuid())) == NULL)
                    243:                                user = "anonymous";
                    244:                        else
                    245:                                user = pw->pw_name;
                    246:                }
1.43      ray       247:                gethostname(host_name, sizeof(host_name));
1.6       millert   248: #ifndef DONT_CHEAT_ANONPASS
                    249:                /*
                    250:                 * Every anonymous FTP server I've encountered
                    251:                 * will accept the string "username@", and will
                    252:                 * append the hostname itself.  We do this by default
                    253:                 * since many servers are picky about not having
                    254:                 * a FQDN in the anonymous password. - thorpej@netbsd.org
                    255:                 */
                    256:                snprintf(anonpass, sizeof(anonpass) - 1, "%s@",
                    257:                    user);
                    258: #else
                    259:                snprintf(anonpass, sizeof(anonpass) - 1, "%s@%s",
                    260:                    user, hp->h_name);
                    261: #endif
                    262:                pass = anonpass;
1.11      millert   263:                user = "anonymous";     /* as per RFC 1635 */
1.8       jkatz     264:        }
                    265:
                    266: tryagain:
1.9       millert   267:        if (retry)
1.11      millert   268:                user = "ftp";           /* some servers only allow "ftp" */
1.8       jkatz     269:
1.6       millert   270:        while (user == NULL) {
                    271:                char *myname = getlogin();
                    272:
1.14      millert   273:                if (myname == NULL && (pw = getpwuid(getuid())) != NULL)
                    274:                        myname = pw->pw_name;
1.6       millert   275:                if (myname)
1.7       deraadt   276:                        fprintf(ttyout, "Name (%s:%s): ", host, myname);
1.6       millert   277:                else
1.7       deraadt   278:                        fprintf(ttyout, "Name (%s): ", host);
1.44      ray       279:                user = myname;
1.45      ray       280:                if (fgets(tmp, sizeof(tmp), stdin) != NULL) {
1.47      gilles    281:                        tmp[strcspn(tmp, "\n")] = '\0';
1.44      ray       282:                        if (tmp[0] != '\0')
                    283:                                user = tmp;
                    284:                }
1.49      martynas  285:                else
                    286:                        exit(0);
1.6       millert   287:        }
                    288:        n = command("USER %s", user);
                    289:        if (n == CONTINUE) {
                    290:                if (pass == NULL)
                    291:                        pass = getpass("Password:");
                    292:                n = command("PASS %s", pass);
                    293:        }
                    294:        if (n == CONTINUE) {
                    295:                aflag++;
1.43      ray       296:                if (acctname == NULL)
                    297:                        acctname = getpass("Account:");
                    298:                n = command("ACCT %s", acctname);
1.6       millert   299:        }
                    300:        if ((n != COMPLETE) ||
1.43      ray       301:            (!aflag && acctname != NULL && command("ACCT %s", acctname) != COMPLETE)) {
1.63      deraadt   302:                warnx("Login %s failed.", user);
1.9       millert   303:                if (retry || !anonftp)
1.8       jkatz     304:                        return (0);
1.9       millert   305:                else
                    306:                        retry = 1;
1.8       jkatz     307:                goto tryagain;
1.6       millert   308:        }
                    309:        if (proxy)
                    310:                return (1);
                    311:        connected = -1;
1.61      martynas  312: #ifndef SMALL
1.6       millert   313:        for (n = 0; n < macnum; ++n) {
                    314:                if (!strcmp("init", macros[n].mac_name)) {
1.33      deraadt   315:                        (void)strlcpy(line, "$init", sizeof line);
1.6       millert   316:                        makeargv();
                    317:                        domacro(margc, margv);
                    318:                        break;
                    319:                }
                    320:        }
1.61      martynas  321: #endif /* SMALL */
1.6       millert   322:        return (1);
1.1       millert   323: }
                    324:
                    325: /*
1.4       millert   326:  * `another' gets another argument, and stores the new argc and argv.
1.1       millert   327:  * It reverts to the top level (via main.c's intr()) on EOF/error.
                    328:  *
                    329:  * Returns false if no new arguments have been added.
                    330:  */
1.62      martynas  331: #ifndef SMALL
1.1       millert   332: int
1.38      deraadt   333: another(int *pargc, char ***pargv, const char *prompt)
1.1       millert   334: {
                    335:        int len = strlen(line), ret;
                    336:
                    337:        if (len >= sizeof(line) - 3) {
1.7       deraadt   338:                fputs("sorry, arguments too long.\n", ttyout);
1.1       millert   339:                intr();
                    340:        }
1.7       deraadt   341:        fprintf(ttyout, "(%s) ", prompt);
1.1       millert   342:        line[len++] = ' ';
1.49      martynas  343:        if (fgets(&line[len], (int)(sizeof(line) - len), stdin) == NULL) {
                    344:                clearerr(stdin);
1.1       millert   345:                intr();
1.49      martynas  346:        }
1.1       millert   347:        len += strlen(&line[len]);
                    348:        if (len > 0 && line[len - 1] == '\n')
                    349:                line[len - 1] = '\0';
                    350:        makeargv();
                    351:        ret = margc > *pargc;
                    352:        *pargc = margc;
                    353:        *pargv = margv;
                    354:        return (ret);
                    355: }
1.62      martynas  356: #endif /* !SMALL */
1.1       millert   357:
1.4       millert   358: /*
                    359:  * glob files given in argv[] from the remote server.
                    360:  * if errbuf isn't NULL, store error messages there instead
                    361:  * of writing to the screen.
1.54      martynas  362:  * if type isn't NULL, use LIST instead of NLST, and store filetype.
                    363:  * 'd' means directory, 's' means symbolic link, '-' means plain
                    364:  * file.
1.4       millert   365:  */
1.1       millert   366: char *
1.54      martynas  367: remglob2(char *argv[], int doswitch, char **errbuf, FILE **ftemp, char *type)
1.1       millert   368: {
1.68      deraadt   369:        char temp[PATH_MAX], *bufp, *cp, *lmode;
                    370:        static char buf[PATH_MAX], **args;
1.40      deraadt   371:        int oldverbose, oldhash, fd;
                    372:
                    373:        if (!mflag) {
                    374:                if (!doglob)
                    375:                        args = NULL;
                    376:                else {
1.54      martynas  377:                        if (*ftemp) {
                    378:                                (void)fclose(*ftemp);
                    379:                                *ftemp = NULL;
1.40      deraadt   380:                        }
                    381:                }
                    382:                return (NULL);
                    383:        }
                    384:        if (!doglob) {
                    385:                if (args == NULL)
                    386:                        args = argv;
                    387:                if ((cp = *++args) == NULL)
                    388:                        args = NULL;
                    389:                return (cp);
                    390:        }
1.54      martynas  391:        if (*ftemp == NULL) {
1.3       millert   392:                int len;
                    393:
1.32      millert   394:                if ((cp = getenv("TMPDIR")) == NULL || *cp == '\0')
1.3       millert   395:                    cp = _PATH_TMP;
                    396:                len = strlen(cp);
                    397:                if (len + sizeof(TMPFILE) + (cp[len-1] != '/') > sizeof(temp)) {
                    398:                        warnx("unable to create temporary file: %s",
                    399:                            strerror(ENAMETOOLONG));
                    400:                        return (NULL);
                    401:                }
                    402:
1.33      deraadt   403:                (void)strlcpy(temp, cp, sizeof temp);
1.3       millert   404:                if (temp[len-1] != '/')
                    405:                        temp[len++] = '/';
1.33      deraadt   406:                (void)strlcpy(&temp[len], TMPFILE, sizeof temp - len);
1.40      deraadt   407:                if ((fd = mkstemp(temp)) < 0) {
1.58      sthen     408:                        warn("unable to create temporary file: %s", temp);
1.40      deraadt   409:                        return (NULL);
                    410:                }
                    411:                close(fd);
1.4       millert   412:                oldverbose = verbose;
                    413:                verbose = (errbuf != NULL) ? -1 : 0;
                    414:                oldhash = hash;
                    415:                hash = 0;
1.40      deraadt   416:                if (doswitch)
                    417:                        pswitch(!proxy);
1.43      ray       418:                for (lmode = "w"; *++argv != NULL; lmode = "a")
1.54      martynas  419:                        recvrequest(type ? "LIST" : "NLST", temp, *argv, lmode,
                    420:                            0, 0);
1.4       millert   421:                if ((code / 100) != COMPLETE) {
                    422:                        if (errbuf != NULL)
                    423:                                *errbuf = reply_string;
                    424:                }
                    425:                if (doswitch)
                    426:                        pswitch(!proxy);
1.40      deraadt   427:                verbose = oldverbose;
1.4       millert   428:                hash = oldhash;
1.54      martynas  429:                *ftemp = fopen(temp, "r");
1.40      deraadt   430:                (void)unlink(temp);
1.54      martynas  431:                if (*ftemp == NULL) {
1.4       millert   432:                        if (errbuf == NULL)
1.7       deraadt   433:                                fputs("can't find list of remote files, oops.\n",
                    434:                                    ttyout);
1.4       millert   435:                        else
                    436:                                *errbuf =
                    437:                                    "can't find list of remote files, oops.";
1.40      deraadt   438:                        return (NULL);
                    439:                }
                    440:        }
1.54      martynas  441: again:
                    442:        if (fgets(buf, sizeof(buf), *ftemp) == NULL) {
                    443:                (void)fclose(*ftemp);
                    444:                *ftemp = NULL;
1.40      deraadt   445:                return (NULL);
                    446:        }
1.47      gilles    447:
                    448:        buf[strcspn(buf, "\n")] = '\0';
1.54      martynas  449:        bufp = buf;
                    450:
                    451: #ifndef SMALL
                    452:        if (type) {
                    453:                parse_list(&bufp, type);
1.56      martynas  454:                if (!bufp ||
                    455:                    (bufp[0] == '.' &&  /* LIST defaults to -a on some ftp */
                    456:                    (bufp[1] == '\0' || /* servers.  Ignore '.' and '..'. */
                    457:                    (bufp[1] == '.' && bufp[2] == '\0'))))
1.54      martynas  458:                        goto again;
                    459:        }
                    460: #endif /* !SMALL */
                    461:
                    462:        return (bufp);
                    463: }
                    464:
                    465: /*
                    466:  * wrapper for remglob2
                    467:  */
                    468: char *
                    469: remglob(char *argv[], int doswitch, char **errbuf)
                    470: {
                    471:        static FILE *ftemp = NULL;
1.47      gilles    472:
1.54      martynas  473:        return remglob2(argv, doswitch, errbuf, &ftemp, NULL);
1.1       millert   474: }
                    475:
1.62      martynas  476: #ifndef SMALL
1.1       millert   477: int
1.54      martynas  478: confirm(const char *cmd, const char *file)
1.1       millert   479: {
1.43      ray       480:        char str[BUFSIZ];
1.1       millert   481:
1.54      martynas  482:        if (file && (confirmrest || !interactive))
1.1       millert   483:                return (1);
1.16      deraadt   484: top:
1.54      martynas  485:        if (file)
                    486:                fprintf(ttyout, "%s %s? ", cmd, file);
                    487:        else
                    488:                fprintf(ttyout, "Continue with %s? ", cmd);
1.7       deraadt   489:        (void)fflush(ttyout);
1.51      martynas  490:        if (fgets(str, sizeof(str), stdin) == NULL)
                    491:                goto quit;
1.43      ray       492:        switch (tolower(*str)) {
1.51      martynas  493:                case '?':
                    494:                        fprintf(ttyout,
                    495:                            "?  help\n"
                    496:                            "a  answer yes to all\n"
                    497:                            "n  answer no\n"
                    498:                            "p  turn off prompt mode\n"
                    499:                            "q  answer no to all\n"
                    500:                            "y  answer yes\n");
                    501:                        goto top;
                    502:                case 'a':
                    503:                        confirmrest = 1;
                    504:                        fprintf(ttyout, "Prompting off for duration of %s.\n",
                    505:                            cmd);
                    506:                        break;
1.1       millert   507:                case 'n':
                    508:                        return (0);
                    509:                case 'p':
                    510:                        interactive = 0;
1.7       deraadt   511:                        fputs("Interactive mode: off.\n", ttyout);
1.1       millert   512:                        break;
1.51      martynas  513:                case 'q':
                    514: quit:
                    515:                        mflag = 0;
                    516:                        clearerr(stdin);
                    517:                        return (0);
1.12      jkatz     518:                case 'y':
                    519:                        return(1);
                    520:                        break;
                    521:                default:
1.51      martynas  522:                        fprintf(ttyout, "?, a, n, p, q, y "
                    523:                            "are the only acceptable commands!\n");
1.16      deraadt   524:                        goto top;
1.1       millert   525:                        break;
                    526:        }
                    527:        return (1);
                    528: }
1.62      martynas  529: #endif /* !SMALL */
1.1       millert   530:
                    531: /*
                    532:  * Glob a local file name specification with
                    533:  * the expectation of a single return value.
                    534:  * Can't control multiple values being expanded
                    535:  * from the expression, we return only the first.
                    536:  */
                    537: int
1.38      deraadt   538: globulize(char **cpp)
1.1       millert   539: {
                    540:        glob_t gl;
                    541:        int flags;
                    542:
                    543:        if (!doglob)
                    544:                return (1);
                    545:
                    546:        flags = GLOB_BRACE|GLOB_NOCHECK|GLOB_QUOTE|GLOB_TILDE;
                    547:        memset(&gl, 0, sizeof(gl));
                    548:        if (glob(*cpp, flags, NULL, &gl) ||
                    549:            gl.gl_pathc == 0) {
                    550:                warnx("%s: not found", *cpp);
                    551:                globfree(&gl);
                    552:                return (0);
                    553:        }
1.13      millert   554:                /* XXX: caller should check if *cpp changed, and
                    555:                 *      free(*cpp) if that is the case
                    556:                 */
                    557:        *cpp = strdup(gl.gl_pathv[0]);
1.30      deraadt   558:        if (*cpp == NULL)
                    559:                err(1, NULL);
1.1       millert   560:        globfree(&gl);
                    561:        return (1);
                    562: }
                    563:
                    564: /*
                    565:  * determine size of remote file
                    566:  */
                    567: off_t
1.38      deraadt   568: remotesize(const char *file, int noisy)
1.1       millert   569: {
                    570:        int overbose;
                    571:        off_t size;
                    572:
                    573:        overbose = verbose;
                    574:        size = -1;
1.54      martynas  575: #ifndef SMALL
                    576:        if (!debug)
                    577: #endif /* !SMALL */
1.1       millert   578:                verbose = -1;
1.11      millert   579:        if (command("SIZE %s", file) == COMPLETE) {
                    580:                char *cp, *ep;
                    581:
                    582:                cp = strchr(reply_string, ' ');
                    583:                if (cp != NULL) {
                    584:                        cp++;
                    585:                        size = strtoq(cp, &ep, 10);
                    586:                        if (*ep != '\0' && !isspace(*ep))
                    587:                                size = -1;
                    588:                }
1.54      martynas  589:        } else if (noisy
                    590: #ifndef SMALL
                    591:            && !debug
                    592: #endif /* !SMALL */
                    593:            ) {
1.7       deraadt   594:                fputs(reply_string, ttyout);
1.11      millert   595:                fputc('\n', ttyout);
1.7       deraadt   596:        }
1.1       millert   597:        verbose = overbose;
                    598:        return (size);
                    599: }
                    600:
                    601: /*
                    602:  * determine last modification time (in GMT) of remote file
                    603:  */
                    604: time_t
1.38      deraadt   605: remotemodtime(const char *file, int noisy)
1.1       millert   606: {
                    607:        int overbose;
                    608:        time_t rtime;
1.15      millert   609:        int ocode;
1.1       millert   610:
                    611:        overbose = verbose;
1.15      millert   612:        ocode = code;
1.1       millert   613:        rtime = -1;
1.54      martynas  614: #ifndef SMALL
                    615:        if (!debug)
                    616: #endif /* !SMALL */
1.1       millert   617:                verbose = -1;
                    618:        if (command("MDTM %s", file) == COMPLETE) {
                    619:                struct tm timebuf;
                    620:                int yy, mo, day, hour, min, sec;
1.23      espie     621:                /*
                    622:                 * time-val = 14DIGIT [ "." 1*DIGIT ]
                    623:                 *              YYYYMMDDHHMMSS[.sss]
                    624:                 * mdtm-response = "213" SP time-val CRLF / error-response
                    625:                 */
                    626:                /* TODO: parse .sss as well, use timespecs. */
                    627:                char *timestr = reply_string;
                    628:
                    629:                /* Repair `19%02d' bug on server side */
                    630:                while (!isspace(*timestr))
                    631:                        timestr++;
                    632:                while (isspace(*timestr))
                    633:                        timestr++;
                    634:                if (strncmp(timestr, "191", 3) == 0) {
                    635:                        fprintf(ttyout,
                    636:            "Y2K warning! Fixed incorrect time-val received from server.\n");
                    637:                        timestr[0] = ' ';
                    638:                        timestr[1] = '2';
                    639:                        timestr[2] = '0';
                    640:                }
1.1       millert   641:                sscanf(reply_string, "%*s %04d%02d%02d%02d%02d%02d", &yy, &mo,
                    642:                        &day, &hour, &min, &sec);
                    643:                memset(&timebuf, 0, sizeof(timebuf));
                    644:                timebuf.tm_sec = sec;
                    645:                timebuf.tm_min = min;
                    646:                timebuf.tm_hour = hour;
                    647:                timebuf.tm_mday = day;
                    648:                timebuf.tm_mon = mo - 1;
1.17      deraadt   649:                timebuf.tm_year = yy - TM_YEAR_BASE;
1.1       millert   650:                timebuf.tm_isdst = -1;
                    651:                rtime = mktime(&timebuf);
1.54      martynas  652:                if (rtime == -1 && (noisy
                    653: #ifndef SMALL
                    654:                    || debug
                    655: #endif /* !SMALL */
                    656:                    ))
1.7       deraadt   657:                        fprintf(ttyout, "Can't convert %s to a time.\n", reply_string);
1.1       millert   658:                else
                    659:                        rtime += timebuf.tm_gmtoff;     /* conv. local -> GMT */
1.54      martynas  660:        } else if (noisy
                    661: #ifndef SMALL
                    662:            && !debug
                    663: #endif /* !SMALL */
                    664:            ) {
1.7       deraadt   665:                fputs(reply_string, ttyout);
1.11      millert   666:                fputc('\n', ttyout);
1.7       deraadt   667:        }
1.1       millert   668:        verbose = overbose;
1.15      millert   669:        if (rtime == -1)
                    670:                code = ocode;
1.1       millert   671:        return (rtime);
                    672: }
1.41      otto      673:
                    674: /*
                    675:  * Ensure file is in or under dir.
                    676:  * Returns 1 if so, 0 if not (or an error occurred).
                    677:  */
                    678: int
                    679: fileindir(const char *file, const char *dir)
                    680: {
1.68      deraadt   681:        char    parentdirbuf[PATH_MAX], *parentdir;
                    682:        char    realdir[PATH_MAX];
1.41      otto      683:        size_t  dirlen;
                    684:
                    685:                                        /* determine parent directory of file */
                    686:        (void)strlcpy(parentdirbuf, file, sizeof(parentdirbuf));
                    687:        parentdir = dirname(parentdirbuf);
                    688:        if (strcmp(parentdir, ".") == 0)
                    689:                return 1;               /* current directory is ok */
                    690:
                    691:                                        /* find the directory */
                    692:        if (realpath(parentdir, realdir) == NULL) {
                    693:                warn("Unable to determine real path of `%s'", parentdir);
                    694:                return 0;
                    695:        }
                    696:        if (realdir[0] != '/')          /* relative result is ok */
                    697:                return 1;
                    698:
                    699:        dirlen = strlen(dir);
                    700:        if (strncmp(realdir, dir, dirlen) == 0 &&
                    701:            (realdir[dirlen] == '/' || realdir[dirlen] == '\0'))
                    702:                return 1;
                    703:        return 0;
                    704: }
                    705:
1.1       millert   706:
1.10      millert   707: /*
                    708:  * Returns true if this is the controlling/foreground process, else false.
                    709:  */
                    710: int
1.38      deraadt   711: foregroundproc(void)
1.10      millert   712: {
                    713:        static pid_t pgrp = -1;
                    714:        int ctty_pgrp;
                    715:
                    716:        if (pgrp == -1)
                    717:                pgrp = getpgrp();
                    718:
                    719:        return((ioctl(STDOUT_FILENO, TIOCGPGRP, &ctty_pgrp) != -1 &&
                    720:            ctty_pgrp == pgrp));
                    721: }
                    722:
1.39      deraadt   723: /* ARGSUSED */
1.20      millert   724: static void
1.39      deraadt   725: updateprogressmeter(int signo)
1.1       millert   726: {
1.19      deraadt   727:        int save_errno = errno;
1.1       millert   728:
1.20      millert   729:        /* update progressmeter if foreground process or in -m mode */
                    730:        if (foregroundproc() || progress == -1)
1.59      martynas  731:                progressmeter(0, NULL);
1.19      deraadt   732:        errno = save_errno;
1.1       millert   733: }
                    734:
                    735: /*
                    736:  * Display a transfer progress bar if progress is non-zero.
                    737:  * SIGALRM is hijacked for use by this function.
                    738:  * - Before the transfer, set filesize to size of file (or -1 if unknown),
                    739:  *   and call with flag = -1. This starts the once per second timer,
                    740:  *   and a call to updateprogressmeter() upon SIGALRM.
                    741:  * - During the transfer, updateprogressmeter will call progressmeter
                    742:  *   with flag = 0
                    743:  * - After the transfer, call with flag = 1
                    744:  */
                    745: static struct timeval start;
                    746:
1.65      deraadt   747: char *action;
                    748:
1.1       millert   749: void
1.59      martynas  750: progressmeter(int flag, const char *filename)
1.1       millert   751: {
                    752:        /*
                    753:         * List of order of magnitude prefixes.
                    754:         * The last is `P', as 2^64 = 16384 Petabytes
                    755:         */
                    756:        static const char prefixes[] = " KMGTP";
                    757:
                    758:        static struct timeval lastupdate;
                    759:        static off_t lastsize;
1.59      martynas  760:        static char *title = NULL;
1.1       millert   761:        struct timeval now, td, wait;
                    762:        off_t cursize, abbrevsize;
                    763:        double elapsed;
1.57      deraadt   764:        int ratio, barlength, i, remaining, overhead = 30;
1.29      deraadt   765:        char buf[512];
1.1       millert   766:
                    767:        if (flag == -1) {
1.2       millert   768:                (void)gettimeofday(&start, (struct timezone *)0);
1.1       millert   769:                lastupdate = start;
                    770:                lastsize = restart_point;
                    771:        }
1.2       millert   772:        (void)gettimeofday(&now, (struct timezone *)0);
1.24      deraadt   773:        if (!progress || filesize < 0)
1.1       millert   774:                return;
                    775:        cursize = bytes + restart_point;
                    776:
1.24      deraadt   777:        if (filesize)
                    778:                ratio = cursize * 100 / filesize;
                    779:        else
                    780:                ratio = 100;
1.68      deraadt   781:        ratio = MAXIMUM(ratio, 0);
                    782:        ratio = MINIMUM(ratio, 100);
1.59      martynas  783:        if (!verbose && flag == -1) {
                    784:                filename = basename(filename);
                    785:                if (filename != NULL)
                    786:                        title = strdup(filename);
                    787:        }
1.65      deraadt   788:
                    789:        buf[0] = 0;
                    790:        if (!verbose && action != NULL) {
                    791:                int l = strlen(action);
                    792:                char *dotdot = "";
                    793:
                    794:                if (l < 7)
                    795:                        l = 7;
                    796:                else if (l > 12) {
                    797:                        l = 12;
                    798:                        dotdot = "...";
                    799:                        overhead += 3;
                    800:                }
                    801:                snprintf(buf, sizeof(buf), "\r%-*.*s%s ", l, l, action,
                    802:                    dotdot);
                    803:                overhead += l + 1;
                    804:        } else
1.66      dcoppa    805:                snprintf(buf, sizeof(buf), "\r");
1.65      deraadt   806:
1.59      martynas  807:        if (!verbose && title != NULL) {
1.57      deraadt   808:                int l = strlen(title);
                    809:                char *dotdot = "";
                    810:
                    811:                if (l < 12)
                    812:                        l = 12;
                    813:                else if (l > 25) {
                    814:                        l = 22;
                    815:                        dotdot = "...";
                    816:                        overhead += 3;
                    817:                }
1.65      deraadt   818:                snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
                    819:                    "%-*.*s%s %3d%% ", l, l, title,
1.57      deraadt   820:                    dotdot, ratio);
                    821:                overhead += l + 1;
1.59      martynas  822:        } else
1.57      deraadt   823:                snprintf(buf, sizeof(buf), "\r%3d%% ", ratio);
1.1       millert   824:
1.57      deraadt   825:        barlength = ttywidth - overhead;
1.1       millert   826:        if (barlength > 0) {
                    827:                i = barlength * ratio / 100;
                    828:                snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
                    829:                    "|%.*s%*s|", i,
1.29      deraadt   830:                    "*******************************************************"
                    831:                    "*******************************************************"
                    832:                    "*******************************************************"
                    833:                    "*******************************************************"
                    834:                    "*******************************************************"
                    835:                    "*******************************************************"
                    836:                    "*******************************************************",
1.1       millert   837:                    barlength - i, "");
                    838:        }
                    839:
                    840:        i = 0;
                    841:        abbrevsize = cursize;
1.64      deraadt   842:        while (abbrevsize >= 100000 && i < sizeof(prefixes)-1) {
1.1       millert   843:                i++;
                    844:                abbrevsize >>= 10;
                    845:        }
                    846:        snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
1.26      deraadt   847:            " %5lld %c%c ", (long long)abbrevsize, prefixes[i],
1.1       millert   848:            prefixes[i] == ' ' ? ' ' : 'B');
                    849:
                    850:        timersub(&now, &lastupdate, &wait);
                    851:        if (cursize > lastsize) {
                    852:                lastupdate = now;
                    853:                lastsize = cursize;
                    854:                if (wait.tv_sec >= STALLTIME) { /* fudge out stalled time */
                    855:                        start.tv_sec += wait.tv_sec;
                    856:                        start.tv_usec += wait.tv_usec;
                    857:                }
                    858:                wait.tv_sec = 0;
                    859:        }
                    860:
                    861:        timersub(&now, &start, &td);
                    862:        elapsed = td.tv_sec + (td.tv_usec / 1000000.0);
                    863:
1.24      deraadt   864:        if (flag == 1) {
                    865:                i = (int)elapsed / 3600;
                    866:                if (i)
                    867:                        snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
                    868:                            "%2d:", i);
                    869:                else
                    870:                        snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
                    871:                            "   ");
                    872:                i = (int)elapsed % 3600;
                    873:                snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
                    874:                    "%02d:%02d    ", i / 60, i % 60);
                    875:        } else if (bytes <= 0 || elapsed <= 0.0 || cursize > filesize) {
1.1       millert   876:                snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
                    877:                    "   --:-- ETA");
                    878:        } else if (wait.tv_sec >= STALLTIME) {
                    879:                snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
                    880:                    " - stalled -");
                    881:        } else {
                    882:                remaining = (int)((filesize - restart_point) /
                    883:                                  (bytes / elapsed) - elapsed);
                    884:                i = remaining / 3600;
                    885:                if (i)
                    886:                        snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
                    887:                            "%2d:", i);
                    888:                else
                    889:                        snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
                    890:                            "   ");
                    891:                i = remaining % 3600;
                    892:                snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
                    893:                    "%02d:%02d ETA", i / 60, i % 60);
                    894:        }
1.7       deraadt   895:        (void)write(fileno(ttyout), buf, strlen(buf));
1.1       millert   896:
                    897:        if (flag == -1) {
1.2       millert   898:                (void)signal(SIGALRM, updateprogressmeter);
1.1       millert   899:                alarmtimer(1);          /* set alarm timer for 1 Hz */
                    900:        } else if (flag == 1) {
                    901:                alarmtimer(0);
1.7       deraadt   902:                (void)putc('\n', ttyout);
1.59      martynas  903:                if (title != NULL) {
                    904:                        free(title);
                    905:                        title = NULL;
                    906:                }
1.1       millert   907:        }
1.7       deraadt   908:        fflush(ttyout);
1.1       millert   909: }
                    910:
                    911: /*
                    912:  * Display transfer statistics.
                    913:  * Requires start to be initialised by progressmeter(-1),
                    914:  * direction to be defined by xfer routines, and filesize and bytes
                    915:  * to be updated by xfer routines
                    916:  * If siginfo is nonzero, an ETA is displayed, and the output goes to STDERR
1.7       deraadt   917:  * instead of TTYOUT.
1.1       millert   918:  */
                    919: void
1.38      deraadt   920: ptransfer(int siginfo)
1.1       millert   921: {
                    922:        struct timeval now, td;
                    923:        double elapsed;
                    924:        off_t bs;
                    925:        int meg, remaining, hh;
                    926:        char buf[100];
                    927:
                    928:        if (!verbose && !siginfo)
                    929:                return;
                    930:
1.2       millert   931:        (void)gettimeofday(&now, (struct timezone *)0);
1.1       millert   932:        timersub(&now, &start, &td);
                    933:        elapsed = td.tv_sec + (td.tv_usec / 1000000.0);
                    934:        bs = bytes / (elapsed == 0.0 ? 1 : elapsed);
                    935:        meg = 0;
                    936:        if (bs > (1024 * 1024))
                    937:                meg = 1;
1.67      deraadt   938:
                    939:        /* XXX floating point printf in signal handler */
1.1       millert   940:        (void)snprintf(buf, sizeof(buf),
1.26      deraadt   941:            "%lld byte%s %s in %.2f seconds (%.2f %sB/s)\n",
                    942:            (long long)bytes, bytes == 1 ? "" : "s", direction, elapsed,
1.1       millert   943:            bs / (1024.0 * (meg ? 1024.0 : 1.0)), meg ? "M" : "K");
1.67      deraadt   944:
                    945:        if (siginfo && bytes > 0 && elapsed > 0.0 && filesize >= 0 &&
                    946:            bytes + restart_point <= filesize) {
1.1       millert   947:                remaining = (int)((filesize - restart_point) /
1.67      deraadt   948:                    (bytes / elapsed) - elapsed);
1.1       millert   949:                hh = remaining / 3600;
                    950:                remaining %= 3600;
1.67      deraadt   951:
                    952:                /* "buf+len(buf) -1" to overwrite \n */
1.1       millert   953:                snprintf(buf + strlen(buf) - 1, sizeof(buf) - strlen(buf),
                    954:                    "  ETA: %02d:%02d:%02d\n", hh, remaining / 60,
                    955:                    remaining % 60);
                    956:        }
1.7       deraadt   957:        (void)write(siginfo ? STDERR_FILENO : fileno(ttyout), buf, strlen(buf));
1.1       millert   958: }
                    959:
                    960: /*
                    961:  * List words in stringlist, vertically arranged
                    962:  */
1.62      martynas  963: #ifndef SMALL
1.1       millert   964: void
1.38      deraadt   965: list_vertical(StringList *sl)
1.1       millert   966: {
                    967:        int i, j, w;
1.39      deraadt   968:        int columns, width, lines;
1.1       millert   969:        char *p;
                    970:
1.39      deraadt   971:        width = 0;
1.1       millert   972:
                    973:        for (i = 0 ; i < sl->sl_cur ; i++) {
                    974:                w = strlen(sl->sl_str[i]);
                    975:                if (w > width)
                    976:                        width = w;
                    977:        }
                    978:        width = (width + 8) &~ 7;
                    979:
                    980:        columns = ttywidth / width;
                    981:        if (columns == 0)
                    982:                columns = 1;
                    983:        lines = (sl->sl_cur + columns - 1) / columns;
                    984:        for (i = 0; i < lines; i++) {
                    985:                for (j = 0; j < columns; j++) {
                    986:                        p = sl->sl_str[j * lines + i];
                    987:                        if (p)
1.7       deraadt   988:                                fputs(p, ttyout);
1.1       millert   989:                        if (j * lines + i + lines >= sl->sl_cur) {
1.7       deraadt   990:                                putc('\n', ttyout);
1.1       millert   991:                                break;
                    992:                        }
                    993:                        w = strlen(p);
                    994:                        while (w < width) {
                    995:                                w = (w + 8) &~ 7;
1.7       deraadt   996:                                (void)putc('\t', ttyout);
1.1       millert   997:                        }
                    998:                }
                    999:        }
                   1000: }
1.62      martynas 1001: #endif /* !SMALL */
1.1       millert  1002:
                   1003: /*
                   1004:  * Update the global ttywidth value, using TIOCGWINSZ.
                   1005:  */
1.39      deraadt  1006: /* ARGSUSED */
1.1       millert  1007: void
1.39      deraadt  1008: setttywidth(int signo)
1.1       millert  1009: {
1.19      deraadt  1010:        int save_errno = errno;
1.1       millert  1011:        struct winsize winsize;
                   1012:
1.7       deraadt  1013:        if (ioctl(fileno(ttyout), TIOCGWINSZ, &winsize) != -1)
1.21      deraadt  1014:                ttywidth = winsize.ws_col ? winsize.ws_col : 80;
1.1       millert  1015:        else
                   1016:                ttywidth = 80;
1.19      deraadt  1017:        errno = save_errno;
1.1       millert  1018: }
                   1019:
                   1020: /*
                   1021:  * Set the SIGALRM interval timer for wait seconds, 0 to disable.
                   1022:  */
                   1023: void
1.38      deraadt  1024: alarmtimer(int wait)
1.1       millert  1025: {
1.67      deraadt  1026:        int save_errno = errno;
1.1       millert  1027:        struct itimerval itv;
                   1028:
                   1029:        itv.it_value.tv_sec = wait;
                   1030:        itv.it_value.tv_usec = 0;
                   1031:        itv.it_interval = itv.it_value;
                   1032:        setitimer(ITIMER_REAL, &itv, NULL);
1.67      deraadt  1033:        errno = save_errno;
1.1       millert  1034: }
1.5       millert  1035:
                   1036: /*
                   1037:  * Setup or cleanup EditLine structures
                   1038:  */
                   1039: #ifndef SMALL
                   1040: void
1.38      deraadt  1041: controlediting(void)
1.5       millert  1042: {
1.36      otto     1043:        HistEvent hev;
                   1044:
1.5       millert  1045:        if (editing && el == NULL && hist == NULL) {
1.36      otto     1046:                el = el_init(__progname, stdin, ttyout, stderr); /* init editline */
1.5       millert  1047:                hist = history_init();          /* init the builtin history */
1.36      otto     1048:                history(hist, &hev, H_SETSIZE, 100);    /* remember 100 events */
1.5       millert  1049:                el_set(el, EL_HIST, history, hist);     /* use history */
                   1050:
                   1051:                el_set(el, EL_EDITOR, "emacs"); /* default editor is emacs */
                   1052:                el_set(el, EL_PROMPT, prompt);  /* set the prompt function */
                   1053:
                   1054:                /* add local file completion, bind to TAB */
                   1055:                el_set(el, EL_ADDFN, "ftp-complete",
                   1056:                    "Context sensitive argument completion",
                   1057:                    complete);
                   1058:                el_set(el, EL_BIND, "^I", "ftp-complete", NULL);
                   1059:
                   1060:                el_source(el, NULL);    /* read ~/.editrc */
                   1061:                el_set(el, EL_SIGNAL, 1);
                   1062:        } else if (!editing) {
                   1063:                if (hist) {
                   1064:                        history_end(hist);
                   1065:                        hist = NULL;
                   1066:                }
                   1067:                if (el) {
                   1068:                        el_end(el);
                   1069:                        el = NULL;
                   1070:                }
                   1071:        }
                   1072: }
                   1073: #endif /* !SMALL */
1.62      martynas 1074: