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

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