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