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