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

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