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

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