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