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