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