Annotation of src/usr.bin/ftp/util.c, Revision 1.85
1.85 ! jca 1: /* $OpenBSD: util.c,v 1.84 2017/01/21 08:33:07 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);
1.85 ! jca 787: if (filename != NULL) {
! 788: free(title);
1.59 martynas 789: title = strdup(filename);
1.85 ! jca 790: }
1.59 martynas 791: }
1.65 deraadt 792:
793: buf[0] = 0;
794: if (!verbose && action != NULL) {
795: int l = strlen(action);
796: char *dotdot = "";
797:
798: if (l < 7)
799: l = 7;
800: else if (l > 12) {
801: l = 12;
802: dotdot = "...";
803: overhead += 3;
804: }
805: snprintf(buf, sizeof(buf), "\r%-*.*s%s ", l, l, action,
806: dotdot);
807: overhead += l + 1;
808: } else
1.66 dcoppa 809: snprintf(buf, sizeof(buf), "\r");
1.65 deraadt 810:
1.59 martynas 811: if (!verbose && title != NULL) {
1.57 deraadt 812: int l = strlen(title);
813: char *dotdot = "";
814:
815: if (l < 12)
816: l = 12;
817: else if (l > 25) {
818: l = 22;
819: dotdot = "...";
820: overhead += 3;
821: }
1.65 deraadt 822: snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
823: "%-*.*s%s %3d%% ", l, l, title,
1.57 deraadt 824: dotdot, ratio);
825: overhead += l + 1;
1.59 martynas 826: } else
1.57 deraadt 827: snprintf(buf, sizeof(buf), "\r%3d%% ", ratio);
1.1 millert 828:
1.57 deraadt 829: barlength = ttywidth - overhead;
1.1 millert 830: if (barlength > 0) {
831: i = barlength * ratio / 100;
832: snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
1.84 krw 833: "|%.*s%*s|", i,
1.29 deraadt 834: "*******************************************************"
835: "*******************************************************"
836: "*******************************************************"
837: "*******************************************************"
838: "*******************************************************"
839: "*******************************************************"
840: "*******************************************************",
1.1 millert 841: barlength - i, "");
842: }
843:
844: i = 0;
845: abbrevsize = cursize;
1.64 deraadt 846: while (abbrevsize >= 100000 && i < sizeof(prefixes)-1) {
1.1 millert 847: i++;
848: abbrevsize >>= 10;
849: }
850: snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
1.26 deraadt 851: " %5lld %c%c ", (long long)abbrevsize, prefixes[i],
1.1 millert 852: prefixes[i] == ' ' ? ' ' : 'B');
853:
854: timersub(&now, &lastupdate, &wait);
855: if (cursize > lastsize) {
856: lastupdate = now;
857: lastsize = cursize;
858: if (wait.tv_sec >= STALLTIME) { /* fudge out stalled time */
859: start.tv_sec += wait.tv_sec;
860: start.tv_usec += wait.tv_usec;
861: }
862: wait.tv_sec = 0;
863: }
864:
865: timersub(&now, &start, &td);
866: elapsed = td.tv_sec + (td.tv_usec / 1000000.0);
867:
1.24 deraadt 868: if (flag == 1) {
869: i = (int)elapsed / 3600;
870: if (i)
871: snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
872: "%2d:", i);
873: else
874: snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
875: " ");
876: i = (int)elapsed % 3600;
877: snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
878: "%02d:%02d ", i / 60, i % 60);
879: } else if (bytes <= 0 || elapsed <= 0.0 || cursize > filesize) {
1.1 millert 880: snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
881: " --:-- ETA");
882: } else if (wait.tv_sec >= STALLTIME) {
883: snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
884: " - stalled -");
885: } else {
886: remaining = (int)((filesize - restart_point) /
887: (bytes / elapsed) - elapsed);
888: i = remaining / 3600;
889: if (i)
890: snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
891: "%2d:", i);
892: else
893: snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
894: " ");
895: i = remaining % 3600;
896: snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
897: "%02d:%02d ETA", i / 60, i % 60);
898: }
1.7 deraadt 899: (void)write(fileno(ttyout), buf, strlen(buf));
1.1 millert 900:
901: if (flag == -1) {
1.2 millert 902: (void)signal(SIGALRM, updateprogressmeter);
1.1 millert 903: alarmtimer(1); /* set alarm timer for 1 Hz */
904: } else if (flag == 1) {
905: alarmtimer(0);
1.7 deraadt 906: (void)putc('\n', ttyout);
1.76 mmcc 907: free(title);
908: title = NULL;
1.1 millert 909: }
1.7 deraadt 910: fflush(ttyout);
1.1 millert 911: }
912:
913: /*
914: * Display transfer statistics.
915: * Requires start to be initialised by progressmeter(-1),
916: * direction to be defined by xfer routines, and filesize and bytes
917: * to be updated by xfer routines
918: * If siginfo is nonzero, an ETA is displayed, and the output goes to STDERR
1.7 deraadt 919: * instead of TTYOUT.
1.1 millert 920: */
921: void
1.38 deraadt 922: ptransfer(int siginfo)
1.1 millert 923: {
924: struct timeval now, td;
925: double elapsed;
926: off_t bs;
927: int meg, remaining, hh;
928: char buf[100];
929:
930: if (!verbose && !siginfo)
931: return;
932:
1.77 krw 933: (void)gettimeofday(&now, NULL);
1.1 millert 934: timersub(&now, &start, &td);
935: elapsed = td.tv_sec + (td.tv_usec / 1000000.0);
936: bs = bytes / (elapsed == 0.0 ? 1 : elapsed);
937: meg = 0;
938: if (bs > (1024 * 1024))
939: meg = 1;
1.67 deraadt 940:
941: /* XXX floating point printf in signal handler */
1.1 millert 942: (void)snprintf(buf, sizeof(buf),
1.26 deraadt 943: "%lld byte%s %s in %.2f seconds (%.2f %sB/s)\n",
944: (long long)bytes, bytes == 1 ? "" : "s", direction, elapsed,
1.1 millert 945: bs / (1024.0 * (meg ? 1024.0 : 1.0)), meg ? "M" : "K");
1.67 deraadt 946:
947: if (siginfo && bytes > 0 && elapsed > 0.0 && filesize >= 0 &&
948: bytes + restart_point <= filesize) {
1.1 millert 949: remaining = (int)((filesize - restart_point) /
1.67 deraadt 950: (bytes / elapsed) - elapsed);
1.1 millert 951: hh = remaining / 3600;
952: remaining %= 3600;
1.67 deraadt 953:
954: /* "buf+len(buf) -1" to overwrite \n */
1.1 millert 955: snprintf(buf + strlen(buf) - 1, sizeof(buf) - strlen(buf),
956: " ETA: %02d:%02d:%02d\n", hh, remaining / 60,
957: remaining % 60);
958: }
1.7 deraadt 959: (void)write(siginfo ? STDERR_FILENO : fileno(ttyout), buf, strlen(buf));
1.1 millert 960: }
961:
962: /*
963: * List words in stringlist, vertically arranged
964: */
1.62 martynas 965: #ifndef SMALL
1.1 millert 966: void
1.38 deraadt 967: list_vertical(StringList *sl)
1.1 millert 968: {
969: int i, j, w;
1.39 deraadt 970: int columns, width, lines;
1.1 millert 971: char *p;
972:
1.39 deraadt 973: width = 0;
1.1 millert 974:
975: for (i = 0 ; i < sl->sl_cur ; i++) {
976: w = strlen(sl->sl_str[i]);
977: if (w > width)
978: width = w;
979: }
980: width = (width + 8) &~ 7;
981:
982: columns = ttywidth / width;
983: if (columns == 0)
984: columns = 1;
985: lines = (sl->sl_cur + columns - 1) / columns;
986: for (i = 0; i < lines; i++) {
987: for (j = 0; j < columns; j++) {
988: p = sl->sl_str[j * lines + i];
989: if (p)
1.7 deraadt 990: fputs(p, ttyout);
1.1 millert 991: if (j * lines + i + lines >= sl->sl_cur) {
1.7 deraadt 992: putc('\n', ttyout);
1.1 millert 993: break;
994: }
995: w = strlen(p);
996: while (w < width) {
997: w = (w + 8) &~ 7;
1.7 deraadt 998: (void)putc('\t', ttyout);
1.1 millert 999: }
1000: }
1001: }
1002: }
1.62 martynas 1003: #endif /* !SMALL */
1.1 millert 1004:
1005: /*
1006: * Update the global ttywidth value, using TIOCGWINSZ.
1007: */
1.39 deraadt 1008: /* ARGSUSED */
1.1 millert 1009: void
1.39 deraadt 1010: setttywidth(int signo)
1.1 millert 1011: {
1.19 deraadt 1012: int save_errno = errno;
1.1 millert 1013: struct winsize winsize;
1014:
1.7 deraadt 1015: if (ioctl(fileno(ttyout), TIOCGWINSZ, &winsize) != -1)
1.21 deraadt 1016: ttywidth = winsize.ws_col ? winsize.ws_col : 80;
1.1 millert 1017: else
1018: ttywidth = 80;
1.19 deraadt 1019: errno = save_errno;
1.1 millert 1020: }
1021:
1022: /*
1023: * Set the SIGALRM interval timer for wait seconds, 0 to disable.
1024: */
1025: void
1.38 deraadt 1026: alarmtimer(int wait)
1.1 millert 1027: {
1.67 deraadt 1028: int save_errno = errno;
1.1 millert 1029: struct itimerval itv;
1030:
1031: itv.it_value.tv_sec = wait;
1032: itv.it_value.tv_usec = 0;
1033: itv.it_interval = itv.it_value;
1034: setitimer(ITIMER_REAL, &itv, NULL);
1.67 deraadt 1035: errno = save_errno;
1.1 millert 1036: }
1.5 millert 1037:
1038: /*
1039: * Setup or cleanup EditLine structures
1040: */
1041: #ifndef SMALL
1042: void
1.38 deraadt 1043: controlediting(void)
1.5 millert 1044: {
1.36 otto 1045: HistEvent hev;
1046:
1.5 millert 1047: if (editing && el == NULL && hist == NULL) {
1.36 otto 1048: el = el_init(__progname, stdin, ttyout, stderr); /* init editline */
1.5 millert 1049: hist = history_init(); /* init the builtin history */
1.36 otto 1050: history(hist, &hev, H_SETSIZE, 100); /* remember 100 events */
1.5 millert 1051: el_set(el, EL_HIST, history, hist); /* use history */
1052:
1053: el_set(el, EL_EDITOR, "emacs"); /* default editor is emacs */
1054: el_set(el, EL_PROMPT, prompt); /* set the prompt function */
1055:
1056: /* add local file completion, bind to TAB */
1057: el_set(el, EL_ADDFN, "ftp-complete",
1058: "Context sensitive argument completion",
1059: complete);
1060: el_set(el, EL_BIND, "^I", "ftp-complete", NULL);
1061:
1062: el_source(el, NULL); /* read ~/.editrc */
1063: el_set(el, EL_SIGNAL, 1);
1064: } else if (!editing) {
1065: if (hist) {
1066: history_end(hist);
1067: hist = NULL;
1068: }
1069: if (el) {
1070: el_end(el);
1071: el = NULL;
1072: }
1073: }
1074: }
1075: #endif /* !SMALL */
1.62 martynas 1076:
1.80 millert 1077: /*
1.81 millert 1078: * Wait for an asynchronous connect(2) attempt to finish.
1.80 millert 1079: */
1080: int
1.81 millert 1081: connect_wait(int s)
1.80 millert 1082: {
1083: struct pollfd pfd[1];
1084: int error = 0;
1085: socklen_t len = sizeof(error);
1086:
1087: pfd[0].fd = s;
1088: pfd[0].events = POLLOUT;
1.81 millert 1089:
1090: if (poll(pfd, 1, -1) == -1)
1091: return -1;
1092: if (getsockopt(s, SOL_SOCKET, SO_ERROR, &error, &len) < 0)
1093: return -1;
1094: if (error != 0) {
1095: errno = error;
1096: return -1;
1.80 millert 1097: }
1.81 millert 1098: return 0;
1.80 millert 1099: }