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