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