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