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