Annotation of src/usr.bin/ftp/util.c, Revision 1.50
1.50 ! martynas 1: /* $OpenBSD: util.c,v 1.49 2008/06/15 03:09:13 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.50 ! martynas 74: static const char rcsid[] = "$OpenBSD: util.c,v 1.49 2008/06/15 03:09:13 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.50 ! martynas 466:
! 467: if (force)
! 468: goto top;
! 469:
! 470: if (confirmrest == -1)
1.49 martynas 471: return (0);
472:
1.50 ! martynas 473: if (confirmrest || !interactive)
1.1 millert 474: return (1);
1.16 deraadt 475: top:
1.7 deraadt 476: fprintf(ttyout, "%s %s? ", cmd, file);
477: (void)fflush(ttyout);
1.49 martynas 478: if (fgets(str, sizeof(str), stdin) == NULL) {
1.50 ! martynas 479: if (!force)
! 480: confirmrest = -1;
1.49 martynas 481: clearerr(stdin);
1.1 millert 482: return (0);
1.49 martynas 483: }
1.43 ray 484: switch (tolower(*str)) {
1.1 millert 485: case 'n':
486: return (0);
487: case 'p':
488: interactive = 0;
1.7 deraadt 489: fputs("Interactive mode: off.\n", ttyout);
1.1 millert 490: break;
491: case 'a':
492: confirmrest = 1;
1.7 deraadt 493: fprintf(ttyout, "Prompting off for duration of %s.\n", cmd);
1.12 jkatz 494: break;
495: case 'y':
496: return(1);
497: break;
498: default:
499: fprintf(ttyout, "n, y, p, a, are the only acceptable commands!\n");
1.16 deraadt 500: goto top;
1.1 millert 501: break;
502: }
503: return (1);
504: }
505:
506: /*
507: * Glob a local file name specification with
508: * the expectation of a single return value.
509: * Can't control multiple values being expanded
510: * from the expression, we return only the first.
511: */
512: int
1.38 deraadt 513: globulize(char **cpp)
1.1 millert 514: {
515: glob_t gl;
516: int flags;
517:
518: if (!doglob)
519: return (1);
520:
521: flags = GLOB_BRACE|GLOB_NOCHECK|GLOB_QUOTE|GLOB_TILDE;
522: memset(&gl, 0, sizeof(gl));
523: if (glob(*cpp, flags, NULL, &gl) ||
524: gl.gl_pathc == 0) {
525: warnx("%s: not found", *cpp);
526: globfree(&gl);
527: return (0);
528: }
1.13 millert 529: /* XXX: caller should check if *cpp changed, and
530: * free(*cpp) if that is the case
531: */
532: *cpp = strdup(gl.gl_pathv[0]);
1.30 deraadt 533: if (*cpp == NULL)
534: err(1, NULL);
1.1 millert 535: globfree(&gl);
536: return (1);
537: }
538:
539: /*
540: * determine size of remote file
541: */
542: off_t
1.38 deraadt 543: remotesize(const char *file, int noisy)
1.1 millert 544: {
545: int overbose;
546: off_t size;
547:
548: overbose = verbose;
549: size = -1;
550: if (debug == 0)
551: verbose = -1;
1.11 millert 552: if (command("SIZE %s", file) == COMPLETE) {
553: char *cp, *ep;
554:
555: cp = strchr(reply_string, ' ');
556: if (cp != NULL) {
557: cp++;
558: size = strtoq(cp, &ep, 10);
559: if (*ep != '\0' && !isspace(*ep))
560: size = -1;
561: }
562: } else if (noisy && debug == 0) {
1.7 deraadt 563: fputs(reply_string, ttyout);
1.11 millert 564: fputc('\n', ttyout);
1.7 deraadt 565: }
1.1 millert 566: verbose = overbose;
567: return (size);
568: }
569:
570: /*
571: * determine last modification time (in GMT) of remote file
572: */
573: time_t
1.38 deraadt 574: remotemodtime(const char *file, int noisy)
1.1 millert 575: {
576: int overbose;
577: time_t rtime;
1.15 millert 578: int ocode;
1.1 millert 579:
580: overbose = verbose;
1.15 millert 581: ocode = code;
1.1 millert 582: rtime = -1;
583: if (debug == 0)
584: verbose = -1;
585: if (command("MDTM %s", file) == COMPLETE) {
586: struct tm timebuf;
587: int yy, mo, day, hour, min, sec;
1.23 espie 588: /*
589: * time-val = 14DIGIT [ "." 1*DIGIT ]
590: * YYYYMMDDHHMMSS[.sss]
591: * mdtm-response = "213" SP time-val CRLF / error-response
592: */
593: /* TODO: parse .sss as well, use timespecs. */
594: char *timestr = reply_string;
595:
596: /* Repair `19%02d' bug on server side */
597: while (!isspace(*timestr))
598: timestr++;
599: while (isspace(*timestr))
600: timestr++;
601: if (strncmp(timestr, "191", 3) == 0) {
602: fprintf(ttyout,
603: "Y2K warning! Fixed incorrect time-val received from server.\n");
604: timestr[0] = ' ';
605: timestr[1] = '2';
606: timestr[2] = '0';
607: }
1.1 millert 608: sscanf(reply_string, "%*s %04d%02d%02d%02d%02d%02d", &yy, &mo,
609: &day, &hour, &min, &sec);
610: memset(&timebuf, 0, sizeof(timebuf));
611: timebuf.tm_sec = sec;
612: timebuf.tm_min = min;
613: timebuf.tm_hour = hour;
614: timebuf.tm_mday = day;
615: timebuf.tm_mon = mo - 1;
1.17 deraadt 616: timebuf.tm_year = yy - TM_YEAR_BASE;
1.1 millert 617: timebuf.tm_isdst = -1;
618: rtime = mktime(&timebuf);
619: if (rtime == -1 && (noisy || debug != 0))
1.7 deraadt 620: fprintf(ttyout, "Can't convert %s to a time.\n", reply_string);
1.1 millert 621: else
622: rtime += timebuf.tm_gmtoff; /* conv. local -> GMT */
1.7 deraadt 623: } else if (noisy && debug == 0) {
624: fputs(reply_string, ttyout);
1.11 millert 625: fputc('\n', ttyout);
1.7 deraadt 626: }
1.1 millert 627: verbose = overbose;
1.15 millert 628: if (rtime == -1)
629: code = ocode;
1.1 millert 630: return (rtime);
631: }
1.41 otto 632:
633: /*
634: * Ensure file is in or under dir.
635: * Returns 1 if so, 0 if not (or an error occurred).
636: */
637: int
638: fileindir(const char *file, const char *dir)
639: {
640: char parentdirbuf[MAXPATHLEN], *parentdir;
641: char realdir[MAXPATHLEN];
642: size_t dirlen;
643:
644: /* determine parent directory of file */
645: (void)strlcpy(parentdirbuf, file, sizeof(parentdirbuf));
646: parentdir = dirname(parentdirbuf);
647: if (strcmp(parentdir, ".") == 0)
648: return 1; /* current directory is ok */
649:
650: /* find the directory */
651: if (realpath(parentdir, realdir) == NULL) {
652: warn("Unable to determine real path of `%s'", parentdir);
653: return 0;
654: }
655: if (realdir[0] != '/') /* relative result is ok */
656: return 1;
657:
658: dirlen = strlen(dir);
659: if (strncmp(realdir, dir, dirlen) == 0 &&
660: (realdir[dirlen] == '/' || realdir[dirlen] == '\0'))
661: return 1;
662: return 0;
663: }
664:
1.1 millert 665:
1.10 millert 666: /*
667: * Returns true if this is the controlling/foreground process, else false.
668: */
669: int
1.38 deraadt 670: foregroundproc(void)
1.10 millert 671: {
672: static pid_t pgrp = -1;
673: int ctty_pgrp;
674:
675: if (pgrp == -1)
676: pgrp = getpgrp();
677:
678: return((ioctl(STDOUT_FILENO, TIOCGPGRP, &ctty_pgrp) != -1 &&
679: ctty_pgrp == pgrp));
680: }
681:
1.39 deraadt 682: /* ARGSUSED */
1.20 millert 683: static void
1.39 deraadt 684: updateprogressmeter(int signo)
1.1 millert 685: {
1.19 deraadt 686: int save_errno = errno;
1.1 millert 687:
1.20 millert 688: /* update progressmeter if foreground process or in -m mode */
689: if (foregroundproc() || progress == -1)
1.10 millert 690: progressmeter(0);
1.19 deraadt 691: errno = save_errno;
1.1 millert 692: }
693:
694: /*
695: * Display a transfer progress bar if progress is non-zero.
696: * SIGALRM is hijacked for use by this function.
697: * - Before the transfer, set filesize to size of file (or -1 if unknown),
698: * and call with flag = -1. This starts the once per second timer,
699: * and a call to updateprogressmeter() upon SIGALRM.
700: * - During the transfer, updateprogressmeter will call progressmeter
701: * with flag = 0
702: * - After the transfer, call with flag = 1
703: */
704: static struct timeval start;
705:
706: void
1.38 deraadt 707: progressmeter(int flag)
1.1 millert 708: {
709: /*
710: * List of order of magnitude prefixes.
711: * The last is `P', as 2^64 = 16384 Petabytes
712: */
713: static const char prefixes[] = " KMGTP";
714:
715: static struct timeval lastupdate;
716: static off_t lastsize;
717: struct timeval now, td, wait;
718: off_t cursize, abbrevsize;
719: double elapsed;
720: int ratio, barlength, i, remaining;
1.29 deraadt 721: char buf[512];
1.1 millert 722:
723: if (flag == -1) {
1.2 millert 724: (void)gettimeofday(&start, (struct timezone *)0);
1.1 millert 725: lastupdate = start;
726: lastsize = restart_point;
727: }
1.2 millert 728: (void)gettimeofday(&now, (struct timezone *)0);
1.24 deraadt 729: if (!progress || filesize < 0)
1.1 millert 730: return;
731: cursize = bytes + restart_point;
732:
1.24 deraadt 733: if (filesize)
734: ratio = cursize * 100 / filesize;
735: else
736: ratio = 100;
1.1 millert 737: ratio = MAX(ratio, 0);
738: ratio = MIN(ratio, 100);
739: snprintf(buf, sizeof(buf), "\r%3d%% ", ratio);
740:
741: barlength = ttywidth - 30;
742: if (barlength > 0) {
743: i = barlength * ratio / 100;
744: snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
745: "|%.*s%*s|", i,
1.29 deraadt 746: "*******************************************************"
747: "*******************************************************"
748: "*******************************************************"
749: "*******************************************************"
750: "*******************************************************"
751: "*******************************************************"
752: "*******************************************************",
1.1 millert 753: barlength - i, "");
754: }
755:
756: i = 0;
757: abbrevsize = cursize;
758: while (abbrevsize >= 100000 && i < sizeof(prefixes)) {
759: i++;
760: abbrevsize >>= 10;
761: }
762: snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
1.26 deraadt 763: " %5lld %c%c ", (long long)abbrevsize, prefixes[i],
1.1 millert 764: prefixes[i] == ' ' ? ' ' : 'B');
765:
766: timersub(&now, &lastupdate, &wait);
767: if (cursize > lastsize) {
768: lastupdate = now;
769: lastsize = cursize;
770: if (wait.tv_sec >= STALLTIME) { /* fudge out stalled time */
771: start.tv_sec += wait.tv_sec;
772: start.tv_usec += wait.tv_usec;
773: }
774: wait.tv_sec = 0;
775: }
776:
777: timersub(&now, &start, &td);
778: elapsed = td.tv_sec + (td.tv_usec / 1000000.0);
779:
1.24 deraadt 780: if (flag == 1) {
781: i = (int)elapsed / 3600;
782: if (i)
783: snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
784: "%2d:", i);
785: else
786: snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
787: " ");
788: i = (int)elapsed % 3600;
789: snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
790: "%02d:%02d ", i / 60, i % 60);
791: } else if (bytes <= 0 || elapsed <= 0.0 || cursize > filesize) {
1.1 millert 792: snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
793: " --:-- ETA");
794: } else if (wait.tv_sec >= STALLTIME) {
795: snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
796: " - stalled -");
797: } else {
798: remaining = (int)((filesize - restart_point) /
799: (bytes / elapsed) - elapsed);
800: i = remaining / 3600;
801: if (i)
802: snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
803: "%2d:", i);
804: else
805: snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
806: " ");
807: i = remaining % 3600;
808: snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
809: "%02d:%02d ETA", i / 60, i % 60);
810: }
1.7 deraadt 811: (void)write(fileno(ttyout), buf, strlen(buf));
1.1 millert 812:
813: if (flag == -1) {
1.2 millert 814: (void)signal(SIGALRM, updateprogressmeter);
1.1 millert 815: alarmtimer(1); /* set alarm timer for 1 Hz */
816: } else if (flag == 1) {
817: alarmtimer(0);
1.7 deraadt 818: (void)putc('\n', ttyout);
1.1 millert 819: }
1.7 deraadt 820: fflush(ttyout);
1.1 millert 821: }
822:
823: /*
824: * Display transfer statistics.
825: * Requires start to be initialised by progressmeter(-1),
826: * direction to be defined by xfer routines, and filesize and bytes
827: * to be updated by xfer routines
828: * If siginfo is nonzero, an ETA is displayed, and the output goes to STDERR
1.7 deraadt 829: * instead of TTYOUT.
1.1 millert 830: */
831: void
1.38 deraadt 832: ptransfer(int siginfo)
1.1 millert 833: {
834: struct timeval now, td;
835: double elapsed;
836: off_t bs;
837: int meg, remaining, hh;
838: char buf[100];
839:
840: if (!verbose && !siginfo)
841: return;
842:
1.2 millert 843: (void)gettimeofday(&now, (struct timezone *)0);
1.1 millert 844: timersub(&now, &start, &td);
845: elapsed = td.tv_sec + (td.tv_usec / 1000000.0);
846: bs = bytes / (elapsed == 0.0 ? 1 : elapsed);
847: meg = 0;
848: if (bs > (1024 * 1024))
849: meg = 1;
850: (void)snprintf(buf, sizeof(buf),
1.26 deraadt 851: "%lld byte%s %s in %.2f seconds (%.2f %sB/s)\n",
852: (long long)bytes, bytes == 1 ? "" : "s", direction, elapsed,
1.1 millert 853: bs / (1024.0 * (meg ? 1024.0 : 1.0)), meg ? "M" : "K");
1.11 millert 854: if (siginfo && bytes > 0 && elapsed > 0.0 && filesize >= 0
855: && bytes + restart_point <= filesize) {
1.1 millert 856: remaining = (int)((filesize - restart_point) /
857: (bytes / elapsed) - elapsed);
858: hh = remaining / 3600;
859: remaining %= 3600;
1.11 millert 860: /* "buf+len(buf) -1" to overwrite \n */
1.1 millert 861: snprintf(buf + strlen(buf) - 1, sizeof(buf) - strlen(buf),
862: " ETA: %02d:%02d:%02d\n", hh, remaining / 60,
863: remaining % 60);
864: }
1.7 deraadt 865: (void)write(siginfo ? STDERR_FILENO : fileno(ttyout), buf, strlen(buf));
1.1 millert 866: }
867:
868: /*
869: * List words in stringlist, vertically arranged
870: */
871: void
1.38 deraadt 872: list_vertical(StringList *sl)
1.1 millert 873: {
874: int i, j, w;
1.39 deraadt 875: int columns, width, lines;
1.1 millert 876: char *p;
877:
1.39 deraadt 878: width = 0;
1.1 millert 879:
880: for (i = 0 ; i < sl->sl_cur ; i++) {
881: w = strlen(sl->sl_str[i]);
882: if (w > width)
883: width = w;
884: }
885: width = (width + 8) &~ 7;
886:
887: columns = ttywidth / width;
888: if (columns == 0)
889: columns = 1;
890: lines = (sl->sl_cur + columns - 1) / columns;
891: for (i = 0; i < lines; i++) {
892: for (j = 0; j < columns; j++) {
893: p = sl->sl_str[j * lines + i];
894: if (p)
1.7 deraadt 895: fputs(p, ttyout);
1.1 millert 896: if (j * lines + i + lines >= sl->sl_cur) {
1.7 deraadt 897: putc('\n', ttyout);
1.1 millert 898: break;
899: }
900: w = strlen(p);
901: while (w < width) {
902: w = (w + 8) &~ 7;
1.7 deraadt 903: (void)putc('\t', ttyout);
1.1 millert 904: }
905: }
906: }
907: }
908:
909: /*
910: * Update the global ttywidth value, using TIOCGWINSZ.
911: */
1.39 deraadt 912: /* ARGSUSED */
1.1 millert 913: void
1.39 deraadt 914: setttywidth(int signo)
1.1 millert 915: {
1.19 deraadt 916: int save_errno = errno;
1.1 millert 917: struct winsize winsize;
918:
1.7 deraadt 919: if (ioctl(fileno(ttyout), TIOCGWINSZ, &winsize) != -1)
1.21 deraadt 920: ttywidth = winsize.ws_col ? winsize.ws_col : 80;
1.1 millert 921: else
922: ttywidth = 80;
1.19 deraadt 923: errno = save_errno;
1.1 millert 924: }
925:
926: /*
927: * Set the SIGALRM interval timer for wait seconds, 0 to disable.
928: */
929: void
1.38 deraadt 930: alarmtimer(int wait)
1.1 millert 931: {
932: struct itimerval itv;
933:
934: itv.it_value.tv_sec = wait;
935: itv.it_value.tv_usec = 0;
936: itv.it_interval = itv.it_value;
937: setitimer(ITIMER_REAL, &itv, NULL);
938: }
1.5 millert 939:
940: /*
941: * Setup or cleanup EditLine structures
942: */
943: #ifndef SMALL
944: void
1.38 deraadt 945: controlediting(void)
1.5 millert 946: {
1.36 otto 947: HistEvent hev;
948:
1.5 millert 949: if (editing && el == NULL && hist == NULL) {
1.36 otto 950: el = el_init(__progname, stdin, ttyout, stderr); /* init editline */
1.5 millert 951: hist = history_init(); /* init the builtin history */
1.36 otto 952: history(hist, &hev, H_SETSIZE, 100); /* remember 100 events */
1.5 millert 953: el_set(el, EL_HIST, history, hist); /* use history */
954:
955: el_set(el, EL_EDITOR, "emacs"); /* default editor is emacs */
956: el_set(el, EL_PROMPT, prompt); /* set the prompt function */
957:
958: /* add local file completion, bind to TAB */
959: el_set(el, EL_ADDFN, "ftp-complete",
960: "Context sensitive argument completion",
961: complete);
962: el_set(el, EL_BIND, "^I", "ftp-complete", NULL);
963:
964: el_source(el, NULL); /* read ~/.editrc */
965: el_set(el, EL_SIGNAL, 1);
966: } else if (!editing) {
967: if (hist) {
968: history_end(hist);
969: hist = NULL;
970: }
971: if (el) {
972: el_end(el);
973: el = NULL;
974: }
975: }
976: }
977: #endif /* !SMALL */