util.c revision 1.46 1 /* $NetBSD: util.c,v 1.46 1999/03/08 03:09:08 lukem Exp $ */
2
3 /*-
4 * Copyright (c) 1998, 1999 The NetBSD Foundation, Inc.
5 * All rights reserved.
6 *
7 * This code is derived from software contributed to The NetBSD Foundation
8 * by Jason R. Thorpe of the Numerical Aerospace Simulation Facility,
9 * NASA Ames Research Center.
10 *
11 * This code is derived from software contributed to The NetBSD Foundation
12 * by Luke Mewburn.
13 *
14 * Redistribution and use in source and binary forms, with or without
15 * modification, are permitted provided that the following conditions
16 * are met:
17 * 1. Redistributions of source code must retain the above copyright
18 * notice, this list of conditions and the following disclaimer.
19 * 2. Redistributions in binary form must reproduce the above copyright
20 * notice, this list of conditions and the following disclaimer in the
21 * documentation and/or other materials provided with the distribution.
22 * 3. All advertising materials mentioning features or use of this software
23 * must display the following acknowledgement:
24 * This product includes software developed by the NetBSD
25 * Foundation, Inc. and its contributors.
26 * 4. Neither the name of The NetBSD Foundation nor the names of its
27 * contributors may be used to endorse or promote products derived
28 * from this software without specific prior written permission.
29 *
30 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
31 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
32 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
33 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
34 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
35 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
36 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
37 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
38 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
39 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
40 * POSSIBILITY OF SUCH DAMAGE.
41 */
42
43 /*
44 * Copyright (c) 1985, 1989, 1993, 1994
45 * The Regents of the University of California. All rights reserved.
46 *
47 * Redistribution and use in source and binary forms, with or without
48 * modification, are permitted provided that the following conditions
49 * are met:
50 * 1. Redistributions of source code must retain the above copyright
51 * notice, this list of conditions and the following disclaimer.
52 * 2. Redistributions in binary form must reproduce the above copyright
53 * notice, this list of conditions and the following disclaimer in the
54 * documentation and/or other materials provided with the distribution.
55 * 3. All advertising materials mentioning features or use of this software
56 * must display the following acknowledgement:
57 * This product includes software developed by the University of
58 * California, Berkeley and its contributors.
59 * 4. Neither the name of the University nor the names of its contributors
60 * may be used to endorse or promote products derived from this software
61 * without specific prior written permission.
62 *
63 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
64 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
65 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
66 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
67 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
68 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
69 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
70 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
71 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
72 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
73 * SUCH DAMAGE.
74 */
75
76 #include <sys/cdefs.h>
77 #ifndef lint
78 __RCSID("$NetBSD: util.c,v 1.46 1999/03/08 03:09:08 lukem Exp $");
79 #endif /* not lint */
80
81 /*
82 * FTP User Program -- Misc support routines
83 */
84 #include <sys/types.h>
85 #include <sys/socket.h>
86 #include <sys/ioctl.h>
87 #include <sys/time.h>
88 #include <arpa/ftp.h>
89
90 #include <ctype.h>
91 #include <err.h>
92 #include <fcntl.h>
93 #include <glob.h>
94 #include <termios.h>
95 #include <signal.h>
96 #include <limits.h>
97 #include <pwd.h>
98 #include <stdio.h>
99 #include <stdlib.h>
100 #include <string.h>
101 #include <time.h>
102 #include <tzfile.h>
103 #include <unistd.h>
104
105 #include "ftp_var.h"
106 #include "pathnames.h"
107
108 #ifndef HAVE_TIMEGM
109 static time_t sub_mkgmt __P((struct tm *tm));
110 #endif
111
112 /*
113 * Connect to peer server and
114 * auto-login, if possible.
115 */
116 void
117 setpeer(argc, argv)
118 int argc;
119 char *argv[];
120 {
121 char *host;
122 in_port_t port;
123
124 if (connected) {
125 fprintf(ttyout, "Already connected to %s, use close first.\n",
126 hostname);
127 code = -1;
128 return;
129 }
130 if (argc < 2)
131 (void)another(&argc, &argv, "to");
132 if (argc < 2 || argc > 3) {
133 fprintf(ttyout, "usage: %s host-name [port]\n", argv[0]);
134 code = -1;
135 return;
136 }
137 if (gatemode)
138 port = gateport;
139 else
140 port = ftpport;
141 if (argc > 2) {
142 char *ep;
143 long nport;
144
145 nport = strtol(argv[2], &ep, 10);
146 if (nport < 1 || nport > MAX_IN_PORT_T || *ep != '\0') {
147 fprintf(ttyout, "%s: bad port number '%s'.\n",
148 argv[1], argv[2]);
149 fprintf(ttyout, "usage: %s host-name [port]\n",
150 argv[0]);
151 code = -1;
152 return;
153 }
154 port = htons((in_port_t)nport);
155 }
156
157 if (gatemode) {
158 if (gateserver == NULL || *gateserver == '\0')
159 errx(1, "gateserver not defined (shouldn't happen)");
160 host = hookup(gateserver, port);
161 } else
162 host = hookup(argv[1], port);
163
164 if (host) {
165 int overbose;
166
167 if (gatemode) {
168 if (command("PASSERVE %s", argv[1]) != COMPLETE)
169 return;
170 if (verbose)
171 fprintf(ttyout,
172 "Connected via pass-through server %s\n",
173 gateserver);
174 }
175
176 connected = 1;
177 /*
178 * Set up defaults for FTP.
179 */
180 (void)strcpy(typename, "ascii"), type = TYPE_A;
181 curtype = TYPE_A;
182 (void)strcpy(formname, "non-print"), form = FORM_N;
183 (void)strcpy(modename, "stream"), mode = MODE_S;
184 (void)strcpy(structname, "file"), stru = STRU_F;
185 (void)strcpy(bytename, "8"), bytesize = 8;
186 if (autologin)
187 (void)ftp_login(argv[1], NULL, NULL);
188
189 overbose = verbose;
190 if (debug == 0)
191 verbose = -1;
192 if (command("SYST") == COMPLETE && overbose) {
193 char *cp, c;
194 c = 0;
195 cp = strchr(reply_string + 4, ' ');
196 if (cp == NULL)
197 cp = strchr(reply_string + 4, '\r');
198 if (cp) {
199 if (cp[-1] == '.')
200 cp--;
201 c = *cp;
202 *cp = '\0';
203 }
204
205 fprintf(ttyout, "Remote system type is %s.\n",
206 reply_string + 4);
207 if (cp)
208 *cp = c;
209 }
210 if (!strncmp(reply_string, "215 UNIX Type: L8", 17)) {
211 if (proxy)
212 unix_proxy = 1;
213 else
214 unix_server = 1;
215 /*
216 * Set type to 0 (not specified by user),
217 * meaning binary by default, but don't bother
218 * telling server. We can use binary
219 * for text files unless changed by the user.
220 */
221 type = 0;
222 (void)strcpy(typename, "binary");
223 if (overbose)
224 fprintf(ttyout,
225 "Using %s mode to transfer files.\n",
226 typename);
227 } else {
228 if (proxy)
229 unix_proxy = 0;
230 else
231 unix_server = 0;
232 if (overbose &&
233 !strncmp(reply_string, "215 TOPS20", 10))
234 fputs(
235 "Remember to set tenex mode when transferring binary files from this machine.\n",
236 ttyout);
237 }
238 verbose = overbose;
239 }
240 }
241
242 /*
243 * login to remote host, using given username & password if supplied
244 */
245 int
246 ftp_login(host, user, pass)
247 const char *host;
248 const char *user, *pass;
249 {
250 char tmp[80];
251 const char *acct;
252 char anonpass[MAXLOGNAME + 2]; /* "user@" */
253 struct passwd *pw;
254 int n, aflag = 0;
255
256 acct = NULL;
257 if (user == NULL) {
258 if (ruserpass(host, &user, &pass, &acct) < 0) {
259 code = -1;
260 return (0);
261 }
262 }
263
264 /*
265 * Set up arguments for an anonymous FTP session, if necessary.
266 */
267 if ((user == NULL || pass == NULL) && anonftp) {
268 memset(anonpass, 0, sizeof(anonpass));
269
270 /*
271 * Set up anonymous login password.
272 */
273 if ((pass = getenv("FTPANONPASS")) == NULL) {
274 if ((pass = getlogin()) == NULL) {
275 if ((pw = getpwuid(getuid())) == NULL)
276 pass = "anonymous";
277 else
278 pass = pw->pw_name;
279 }
280 /*
281 * Every anonymous FTP server I've encountered
282 * will accept the string "username@", and will
283 * append the hostname itself. We do this by default
284 * since many servers are picky about not having
285 * a FQDN in the anonymous password.
286 * - thorpej (at) netbsd.org
287 */
288 snprintf(anonpass, sizeof(anonpass) - 1, "%s@", pass);
289 pass = anonpass;
290 }
291 user = "anonymous"; /* as per RFC 1635 */
292 }
293
294 while (user == NULL) {
295 const char *myname = getlogin();
296
297 if (myname == NULL && (pw = getpwuid(getuid())) != NULL)
298 myname = pw->pw_name;
299 if (myname)
300 fprintf(ttyout, "Name (%s:%s): ", host, myname);
301 else
302 fprintf(ttyout, "Name (%s): ", host);
303 *tmp = '\0';
304 (void)fgets(tmp, sizeof(tmp) - 1, stdin);
305 tmp[strlen(tmp) - 1] = '\0';
306 if (*tmp == '\0')
307 user = myname;
308 else
309 user = tmp;
310 }
311 n = command("USER %s", user);
312 if (n == CONTINUE) {
313 if (pass == NULL)
314 pass = getpass("Password:");
315 n = command("PASS %s", pass);
316 }
317 if (n == CONTINUE) {
318 aflag++;
319 if (acct == NULL)
320 acct = getpass("Account:");
321 n = command("ACCT %s", acct);
322 }
323 if ((n != COMPLETE) ||
324 (!aflag && acct != NULL && command("ACCT %s", acct) != COMPLETE)) {
325 warnx("Login failed.");
326 return (0);
327 }
328 if (proxy)
329 return (1);
330 connected = -1;
331 for (n = 0; n < macnum; ++n) {
332 if (!strcmp("init", macros[n].mac_name)) {
333 (void)strcpy(line, "$init");
334 makeargv();
335 domacro(margc, margv);
336 break;
337 }
338 }
339 return (1);
340 }
341
342 /*
343 * `another' gets another argument, and stores the new argc and argv.
344 * It reverts to the top level (via main.c's intr()) on EOF/error.
345 *
346 * Returns false if no new arguments have been added.
347 */
348 int
349 another(pargc, pargv, prompt)
350 int *pargc;
351 char ***pargv;
352 const char *prompt;
353 {
354 int len = strlen(line), ret;
355
356 if (len >= sizeof(line) - 3) {
357 fputs("sorry, arguments too long.\n", ttyout);
358 intr();
359 }
360 fprintf(ttyout, "(%s) ", prompt);
361 line[len++] = ' ';
362 if (fgets(&line[len], sizeof(line) - len, stdin) == NULL)
363 intr();
364 len += strlen(&line[len]);
365 if (len > 0 && line[len - 1] == '\n')
366 line[len - 1] = '\0';
367 makeargv();
368 ret = margc > *pargc;
369 *pargc = margc;
370 *pargv = margv;
371 return (ret);
372 }
373
374 /*
375 * glob files given in argv[] from the remote server.
376 * if errbuf isn't NULL, store error messages there instead
377 * of writing to the screen.
378 */
379 char *
380 remglob(argv, doswitch, errbuf)
381 char *argv[];
382 int doswitch;
383 char **errbuf;
384 {
385 char temp[MAXPATHLEN];
386 static char buf[MAXPATHLEN];
387 static FILE *ftemp = NULL;
388 static char **args;
389 int oldverbose, oldhash, fd;
390 char *cp, *mode;
391
392 if (!mflag) {
393 if (!doglob)
394 args = NULL;
395 else {
396 if (ftemp) {
397 (void)fclose(ftemp);
398 ftemp = NULL;
399 }
400 }
401 return (NULL);
402 }
403 if (!doglob) {
404 if (args == NULL)
405 args = argv;
406 if ((cp = *++args) == NULL)
407 args = NULL;
408 return (cp);
409 }
410 if (ftemp == NULL) {
411 (void)snprintf(temp, sizeof(temp), "%s/%s", tmpdir, TMPFILE);
412 if ((fd = mkstemp(temp)) < 0) {
413 warn("unable to create temporary file %s", temp);
414 return (NULL);
415 }
416 close(fd);
417 oldverbose = verbose;
418 verbose = (errbuf != NULL) ? -1 : 0;
419 oldhash = hash;
420 hash = 0;
421 if (doswitch)
422 pswitch(!proxy);
423 for (mode = "w"; *++argv != NULL; mode = "a")
424 recvrequest("NLST", temp, *argv, mode, 0, 0);
425 if ((code / 100) != COMPLETE) {
426 if (errbuf != NULL)
427 *errbuf = reply_string;
428 }
429 if (doswitch)
430 pswitch(!proxy);
431 verbose = oldverbose;
432 hash = oldhash;
433 ftemp = fopen(temp, "r");
434 (void)unlink(temp);
435 if (ftemp == NULL) {
436 if (errbuf == NULL)
437 fputs(
438 "can't find list of remote files, oops.\n",
439 ttyout);
440 else
441 *errbuf =
442 "can't find list of remote files, oops.";
443 return (NULL);
444 }
445 }
446 if (fgets(buf, sizeof(buf), ftemp) == NULL) {
447 (void)fclose(ftemp);
448 ftemp = NULL;
449 return (NULL);
450 }
451 if ((cp = strchr(buf, '\n')) != NULL)
452 *cp = '\0';
453 return (buf);
454 }
455
456 int
457 confirm(cmd, file)
458 const char *cmd, *file;
459 {
460 char line[BUFSIZ];
461
462 if (!interactive || confirmrest)
463 return (1);
464 fprintf(ttyout, "%s %s? ", cmd, file);
465 (void)fflush(ttyout);
466 if (fgets(line, sizeof(line), stdin) == NULL)
467 return (0);
468 switch (tolower(*line)) {
469 case 'n':
470 return (0);
471 case 'p':
472 interactive = 0;
473 fputs("Interactive mode: off.\n", ttyout);
474 break;
475 case 'a':
476 confirmrest = 1;
477 fprintf(ttyout, "Prompting off for duration of %s.\n",
478 cmd);
479 break;
480 }
481 return (1);
482 }
483
484 /*
485 * Glob a local file name specification with
486 * the expectation of a single return value.
487 * Can't control multiple values being expanded
488 * from the expression, we return only the first.
489 */
490 int
491 globulize(cpp)
492 char **cpp;
493 {
494 glob_t gl;
495 int flags;
496
497 if (!doglob)
498 return (1);
499
500 flags = GLOB_BRACE|GLOB_NOCHECK|GLOB_TILDE;
501 memset(&gl, 0, sizeof(gl));
502 if (glob(*cpp, flags, NULL, &gl) || gl.gl_pathc == 0) {
503 warnx("%s: not found", *cpp);
504 globfree(&gl);
505 return (0);
506 }
507 /* XXX: caller should check if *cpp changed, and
508 * free(*cpp) if that is the case
509 */
510 *cpp = xstrdup(gl.gl_pathv[0]);
511 globfree(&gl);
512 return (1);
513 }
514
515 /*
516 * determine size of remote file
517 */
518 off_t
519 remotesize(file, noisy)
520 const char *file;
521 int noisy;
522 {
523 int overbose;
524 off_t size;
525
526 overbose = verbose;
527 size = -1;
528 if (debug == 0)
529 verbose = -1;
530 if (command("SIZE %s", file) == COMPLETE) {
531 char *cp, *ep;
532
533 cp = strchr(reply_string, ' ');
534 if (cp != NULL) {
535 cp++;
536 #ifndef NO_QUAD
537 size = strtoq(cp, &ep, 10);
538 #else
539 size = strtol(cp, &ep, 10);
540 #endif
541 if (*ep != '\0' && !isspace((unsigned char)*ep))
542 size = -1;
543 }
544 } else if (noisy && debug == 0) {
545 fputs(reply_string, ttyout);
546 putc('\n', ttyout);
547 }
548 verbose = overbose;
549 return (size);
550 }
551
552 /*
553 * determine last modification time (in GMT) of remote file
554 */
555 time_t
556 remotemodtime(file, noisy)
557 const char *file;
558 int noisy;
559 {
560 int overbose;
561 time_t rtime;
562 int ocode;
563
564 overbose = verbose;
565 ocode = code;
566 rtime = -1;
567 if (debug == 0)
568 verbose = -1;
569 if (command("MDTM %s", file) == COMPLETE) {
570 struct tm timebuf;
571 int yy, mo, day, hour, min, sec;
572 sscanf(reply_string, "%*s %04d%02d%02d%02d%02d%02d", &yy, &mo,
573 &day, &hour, &min, &sec);
574 memset(&timebuf, 0, sizeof(timebuf));
575 timebuf.tm_sec = sec;
576 timebuf.tm_min = min;
577 timebuf.tm_hour = hour;
578 timebuf.tm_mday = day;
579 timebuf.tm_mon = mo - 1;
580 timebuf.tm_year = yy - TM_YEAR_BASE;
581 timebuf.tm_isdst = -1;
582 rtime = mkgmtime(&timebuf);
583 if (rtime == -1 && (noisy || debug != 0))
584 fprintf(ttyout, "Can't convert %s to a time.\n",
585 reply_string);
586 } else if (noisy && debug == 0) {
587 fputs(reply_string, ttyout);
588 putc('\n', ttyout);
589 }
590 verbose = overbose;
591 if (rtime == -1)
592 code = ocode;
593 return (rtime);
594 }
595
596 /*
597 * UTC version of mktime(3)
598 */
599 #ifdef HAVE_TIMEGM
600 time_t
601 mkgmtime(tm)
602 struct tm *tm;
603 {
604
605 /* This is very clean, but not portable at all. */
606 return (timegm(tm));
607 }
608
609 #else /* not HAVE_TIMEGM */
610
611 /*
612 * This code is not portable, but works on most Unix-like systems.
613 * If the local timezone has no summer time, using mktime(3) function
614 * and adjusting offset would be usable (adjusting leap seconds
615 * is still required, though), but the assumption is not always true.
616 *
617 * Anyway, no portable and correct implementation of UTC to time_t
618 * conversion exists....
619 */
620
621 static time_t
622 sub_mkgmt(tm)
623 struct tm *tm;
624 {
625 int y, nleapdays;
626 time_t t;
627 /* days before the month */
628 static const unsigned short moff[12] = {
629 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334
630 };
631
632 /*
633 * XXX This code assumes the given time to be normalized.
634 * Normalizing here is impossible in case the given time is a leap
635 * second but the local time library is ignorant of leap seconds.
636 */
637
638 /* minimal sanity checking not to access outside of the array */
639 if ((unsigned) tm->tm_mon >= 12)
640 return (time_t) -1;
641 if (tm->tm_year < EPOCH_YEAR - TM_YEAR_BASE)
642 return (time_t) -1;
643
644 y = tm->tm_year + TM_YEAR_BASE - (tm->tm_mon < 2);
645 nleapdays = y / 4 - y / 100 + y / 400 -
646 ((EPOCH_YEAR-1) / 4 - (EPOCH_YEAR-1) / 100 + (EPOCH_YEAR-1) / 400);
647 t = ((((time_t) (tm->tm_year - (EPOCH_YEAR - TM_YEAR_BASE)) * 365 +
648 moff[tm->tm_mon] + tm->tm_mday - 1 + nleapdays) * 24 +
649 tm->tm_hour) * 60 + tm->tm_min) * 60 + tm->tm_sec;
650
651 return (t < 0 ? (time_t) -1 : t);
652 }
653
654 time_t
655 mkgmtime(tm)
656 struct tm *tm;
657 {
658 time_t t, t2;
659 struct tm *tm2;
660 int sec;
661
662 /* Do the first guess. */
663 if ((t = sub_mkgmt(tm)) == (time_t) -1)
664 return (time_t) -1;
665
666 /* save value in case *tm is overwritten by gmtime() */
667 sec = tm->tm_sec;
668
669 tm2 = gmtime(&t);
670 if ((t2 = sub_mkgmt(tm2)) == (time_t) -1)
671 return (time_t) -1;
672
673 if (t2 < t || tm2->tm_sec != sec) {
674 /*
675 * Adjust for leap seconds.
676 *
677 * real time_t time
678 * |
679 * tm
680 * / ... (a) first sub_mkgmt() conversion
681 * t
682 * |
683 * tm2
684 * / ... (b) second sub_mkgmt() conversion
685 * t2
686 * --->time
687 */
688 /*
689 * Do the second guess, assuming (a) and (b) are almost equal.
690 */
691 t += t - t2;
692 tm2 = gmtime(&t);
693
694 /*
695 * Either (a) or (b), may include one or two extra
696 * leap seconds. Try t, t + 2, t - 2, t + 1, and t - 1.
697 */
698 if (tm2->tm_sec == sec
699 || (t += 2, tm2 = gmtime(&t), tm2->tm_sec == sec)
700 || (t -= 4, tm2 = gmtime(&t), tm2->tm_sec == sec)
701 || (t += 3, tm2 = gmtime(&t), tm2->tm_sec == sec)
702 || (t -= 2, tm2 = gmtime(&t), tm2->tm_sec == sec))
703 ; /* found */
704 else {
705 /*
706 * Not found.
707 */
708 if (sec >= 60)
709 /*
710 * The given time is a leap second
711 * (sec 60 or 61), but the time library
712 * is ignorant of the leap second.
713 */
714 ; /* treat sec 60 as 59,
715 sec 61 as 0 of the next minute */
716 else
717 /* The given time may not be normalized. */
718 t++; /* restore t */
719 }
720 }
721
722 return (t < 0 ? (time_t) -1 : t);
723 }
724 #endif /* not HAVE_TIMEGM */
725
726 #ifndef SMALL
727
728 /*
729 * return non-zero if we're the current foreground process
730 */
731 int
732 foregroundproc()
733 {
734 static pid_t pgrp = -1;
735 int ctty_pgrp;
736
737 if (pgrp == -1)
738 pgrp = getpgrp();
739
740 return ((ioctl(fileno(ttyout), TIOCGPGRP, &ctty_pgrp) != -1 &&
741 ctty_pgrp == (int)pgrp));
742 }
743
744
745 static void updateprogressmeter __P((int));
746
747 static void
748 updateprogressmeter(dummy)
749 int dummy;
750 {
751
752 progressmeter(0);
753 }
754 #endif /* SMALL */
755
756
757 /*
758 * List of order of magnitude prefixes.
759 * The last is `P', as 2^64 = 16384 Petabytes
760 */
761 static const char prefixes[] = " KMGTP";
762
763 /*
764 * Display a transfer progress bar if progress is non-zero.
765 * SIGALRM is hijacked for use by this function.
766 * - Before the transfer, set filesize to size of file (or -1 if unknown),
767 * and call with flag = -1. This starts the once per second timer,
768 * and a call to updateprogressmeter() upon SIGALRM.
769 * - During the transfer, updateprogressmeter will call progressmeter
770 * with flag = 0
771 * - After the transfer, call with flag = 1
772 */
773 static struct timeval start;
774 static struct timeval lastupdate;
775
776 void
777 progressmeter(flag)
778 int flag;
779 {
780 #ifndef SMALL
781 static off_t lastsize;
782 struct timeval now, td, wait;
783 off_t cursize, abbrevsize, bytespersec;
784 double elapsed;
785 int ratio, barlength, i, len, remaining;
786 char buf[256];
787
788 len = 0;
789 if (flag == -1) {
790 (void)gettimeofday(&start, NULL);
791 lastupdate = start;
792 lastsize = restart_point;
793 }
794 if (!progress || filesize <= 0)
795 return;
796
797 (void)gettimeofday(&now, NULL);
798 cursize = bytes + restart_point;
799 timersub(&now, &lastupdate, &wait);
800 if (cursize > lastsize) {
801 lastupdate = now;
802 lastsize = cursize;
803 if (wait.tv_sec >= STALLTIME) { /* fudge out stalled time */
804 start.tv_sec += wait.tv_sec;
805 start.tv_usec += wait.tv_usec;
806 }
807 wait.tv_sec = 0;
808 }
809
810 /*
811 * print progress bar only if we are foreground process.
812 */
813 if (! foregroundproc())
814 return;
815
816 ratio = (int)((double)cursize * 100.0 / (double)filesize);
817 ratio = MAX(ratio, 0);
818 ratio = MIN(ratio, 100);
819 len += snprintf(buf + len, sizeof(buf) - len, "\r%3d%% ", ratio);
820
821 barlength = ttywidth - 43;
822 if (barlength > 0) {
823 i = barlength * ratio / 100;
824 len += snprintf(buf + len, sizeof(buf) - len,
825 "|%.*s%*s|", i,
826 "*****************************************************************************"
827 "*****************************************************************************",
828 barlength - i, "");
829 }
830
831 abbrevsize = cursize;
832 for (i = 0; abbrevsize >= 100000 && i < sizeof(prefixes); i++)
833 abbrevsize >>= 10;
834 len += snprintf(buf + len, sizeof(buf) - len,
835 #ifndef NO_QUAD
836 " %5qd %c%c ", (long long)abbrevsize,
837 #else
838 " %5ld %c%c ", (long)abbrevsize,
839 #endif
840 prefixes[i],
841 i == 0 ? ' ' : 'B');
842
843 timersub(&now, &start, &td);
844 elapsed = td.tv_sec + (td.tv_usec / 1000000.0);
845
846 bytespersec = 0;
847 if (bytes > 0) {
848 bytespersec = bytes;
849 if (elapsed > 0.0)
850 bytespersec /= elapsed;
851 }
852 for (i = 1; bytespersec >= 1024000 && i < sizeof(prefixes); i++)
853 bytespersec >>= 10;
854 len += snprintf(buf + len, sizeof(buf) - len,
855 #ifndef NO_QUAD
856 " %3qd.%02d %cB/s ", (long long)bytespersec / 1024,
857 #else
858 " %3ld.%02d %cB/s ", (long)bytespersec / 1024,
859 #endif
860 (int)((bytespersec % 1024) * 100 / 1024),
861 prefixes[i]);
862
863 if (bytes <= 0 || elapsed <= 0.0 || cursize > filesize) {
864 len += snprintf(buf + len, sizeof(buf) - len,
865 " --:-- ETA");
866 } else if (wait.tv_sec >= STALLTIME) {
867 len += snprintf(buf + len, sizeof(buf) - len,
868 " - stalled -");
869 } else {
870 remaining = (int)
871 ((filesize - restart_point) / (bytes / elapsed) - elapsed);
872 if (remaining >= 100 * SECSPERHOUR)
873 len += snprintf(buf + len, sizeof(buf) - len,
874 " --:-- ETA");
875 else {
876 i = remaining / SECSPERHOUR;
877 if (i)
878 len += snprintf(buf + len, sizeof(buf) - len,
879 "%2d:", i);
880 else
881 len += snprintf(buf + len, sizeof(buf) - len,
882 " ");
883 i = remaining % SECSPERHOUR;
884 len += snprintf(buf + len, sizeof(buf) - len,
885 "%02d:%02d ETA", i / 60, i % 60);
886 }
887 }
888 (void)write(fileno(ttyout), buf, len);
889
890 if (flag == -1) {
891 (void)xsignal(SIGALRM, updateprogressmeter);
892 alarmtimer(1); /* set alarm timer for 1 Hz */
893 } else if (flag == 1) {
894 (void)xsignal(SIGALRM, SIG_DFL);
895 alarmtimer(0);
896 (void)putc('\n', ttyout);
897 }
898 fflush(ttyout);
899 #endif /* SMALL */
900 }
901
902 /*
903 * Display transfer statistics.
904 * Requires start to be initialised by progressmeter(-1),
905 * direction to be defined by xfer routines, and filesize and bytes
906 * to be updated by xfer routines
907 * If siginfo is nonzero, an ETA is displayed, and the output goes to stderr
908 * instead of ttyout.
909 */
910 void
911 ptransfer(siginfo)
912 int siginfo;
913 {
914 #ifndef SMALL
915 struct timeval now, td, wait;
916 double elapsed;
917 off_t bytespersec;
918 int remaining, hh, i, len;
919 char buf[100];
920
921 if (!verbose && !siginfo)
922 return;
923
924 (void)gettimeofday(&now, NULL);
925 timersub(&now, &start, &td);
926 elapsed = td.tv_sec + (td.tv_usec / 1000000.0);
927 bytespersec = 0;
928 if (bytes > 0) {
929 bytespersec = bytes;
930 if (elapsed > 0.0)
931 bytespersec /= elapsed;
932 }
933 len = 0;
934 len += snprintf(buf + len, sizeof(buf) - len,
935 #ifndef NO_QUAD
936 "%qd byte%s %s in ", (long long)bytes,
937 #else
938 "%ld byte%s %s in ", (long)bytes,
939 #endif
940 bytes == 1 ? "" : "s", direction);
941 remaining = (int)elapsed;
942 if (remaining > SECSPERDAY) {
943 int days;
944
945 days = remaining / SECSPERDAY;
946 remaining %= SECSPERDAY;
947 len += snprintf(buf + len, sizeof(buf) - len,
948 "%d day%s ", days, days == 1 ? "" : "s");
949 }
950 hh = remaining / SECSPERHOUR;
951 remaining %= SECSPERHOUR;
952 if (hh)
953 len += snprintf(buf + len, sizeof(buf) - len, "%2d:", hh);
954 len += snprintf(buf + len, sizeof(buf) - len,
955 "%02d:%02d ", remaining / 60, remaining % 60);
956
957 for (i = 1; bytespersec >= 1024000 && i < sizeof(prefixes); i++)
958 bytespersec >>= 10;
959 len += snprintf(buf + len, sizeof(buf) - len,
960 #ifndef NO_QUAD
961 "(%qd.%02d %cB/s)", (long long)bytespersec / 1024,
962 #else
963 "(%ld.%02d %cB/s)", (long)bytespersec / 1024,
964 #endif
965 (int)((bytespersec % 1024) * 100 / 1024),
966 prefixes[i]);
967
968 if (siginfo && bytes > 0 && elapsed > 0.0 && filesize >= 0
969 && bytes + restart_point <= filesize) {
970 remaining = (int)((filesize - restart_point) /
971 (bytes / elapsed) - elapsed);
972 hh = remaining / SECSPERHOUR;
973 remaining %= SECSPERHOUR;
974 len += snprintf(buf + len, sizeof(buf) - len, " ETA: ");
975 if (hh)
976 len += snprintf(buf + len, sizeof(buf) - len, "%2d:",
977 hh);
978 len += snprintf(buf + len, sizeof(buf) - len,
979 "%02d:%02d", remaining / 60, remaining % 60);
980 timersub(&now, &lastupdate, &wait);
981 if (wait.tv_sec >= STALLTIME)
982 len += snprintf(buf + len, sizeof(buf) - len,
983 " (stalled)");
984 }
985 len += snprintf(buf + len, sizeof(buf) - len, "\n");
986 (void)write(siginfo ? STDERR_FILENO : fileno(ttyout), buf, len);
987 #endif /* SMALL */
988 }
989
990 /*
991 * List words in stringlist, vertically arranged
992 */
993 void
994 list_vertical(sl)
995 StringList *sl;
996 {
997 int i, j, w;
998 int columns, width, lines, items;
999 char *p;
1000
1001 width = items = 0;
1002
1003 for (i = 0 ; i < sl->sl_cur ; i++) {
1004 w = strlen(sl->sl_str[i]);
1005 if (w > width)
1006 width = w;
1007 }
1008 width = (width + 8) &~ 7;
1009
1010 columns = ttywidth / width;
1011 if (columns == 0)
1012 columns = 1;
1013 lines = (sl->sl_cur + columns - 1) / columns;
1014 for (i = 0; i < lines; i++) {
1015 for (j = 0; j < columns; j++) {
1016 p = sl->sl_str[j * lines + i];
1017 if (p)
1018 fputs(p, ttyout);
1019 if (j * lines + i + lines >= sl->sl_cur) {
1020 putc('\n', ttyout);
1021 break;
1022 }
1023 w = strlen(p);
1024 while (w < width) {
1025 w = (w + 8) &~ 7;
1026 (void)putc('\t', ttyout);
1027 }
1028 }
1029 }
1030 }
1031
1032 /*
1033 * Update the global ttywidth value, using TIOCGWINSZ.
1034 */
1035 void
1036 setttywidth(a)
1037 int a;
1038 {
1039 struct winsize winsize;
1040
1041 if (ioctl(fileno(ttyout), TIOCGWINSZ, &winsize) != -1 &&
1042 winsize.ws_col != 0)
1043 ttywidth = winsize.ws_col;
1044 else
1045 ttywidth = 80;
1046 }
1047
1048 /*
1049 * Set the SIGALRM interval timer for wait seconds, 0 to disable.
1050 */
1051 void
1052 alarmtimer(wait)
1053 int wait;
1054 {
1055 struct itimerval itv;
1056
1057 itv.it_value.tv_sec = wait;
1058 itv.it_value.tv_usec = 0;
1059 itv.it_interval = itv.it_value;
1060 setitimer(ITIMER_REAL, &itv, NULL);
1061 }
1062
1063 /*
1064 * Setup or cleanup EditLine structures
1065 */
1066 #ifndef SMALL
1067 void
1068 controlediting()
1069 {
1070 if (editing && el == NULL && hist == NULL) {
1071 HistEvent ev;
1072 int editmode;
1073
1074 el = el_init(__progname, stdin, ttyout, stderr);
1075 /* init editline */
1076 hist = history_init(); /* init the builtin history */
1077 history(hist, &ev, H_SETSIZE, 100);/* remember 100 events */
1078 el_set(el, EL_HIST, history, hist); /* use history */
1079
1080 el_set(el, EL_EDITOR, "emacs"); /* default editor is emacs */
1081 el_set(el, EL_PROMPT, prompt); /* set the prompt function */
1082
1083 /* add local file completion, bind to TAB */
1084 el_set(el, EL_ADDFN, "ftp-complete",
1085 "Context sensitive argument completion",
1086 complete);
1087 el_set(el, EL_BIND, "^I", "ftp-complete", NULL);
1088 el_source(el, NULL); /* read ~/.editrc */
1089 if ((el_get(el, EL_EDITMODE, &editmode) != -1) && editmode == 0)
1090 editing = 0; /* the user doesn't want editing,
1091 * so disable, and let statement
1092 * below cleanup */
1093 else
1094 el_set(el, EL_SIGNAL, 1);
1095 }
1096 if (!editing) {
1097 if (hist) {
1098 history_end(hist);
1099 hist = NULL;
1100 }
1101 if (el) {
1102 el_end(el);
1103 el = NULL;
1104 }
1105 }
1106 }
1107 #endif /* !SMALL */
1108
1109 /*
1110 * Parse the specified socket buffer size.
1111 */
1112 int
1113 getsockbufsize(arg)
1114 const char *arg;
1115 {
1116 char *cp;
1117 int val;
1118
1119 if (!isdigit((unsigned char)arg[0]))
1120 return (-1);
1121
1122 val = strtol(arg, &cp, 10);
1123 if (cp != NULL) {
1124 if (cp[1] != '\0')
1125 return (-1);
1126 if (cp[0] == 'k')
1127 val *= 1024;
1128 if (cp[0] == 'm')
1129 val *= 1024 * 1024;
1130 }
1131
1132 if (val < 0)
1133 return (-1);
1134
1135 return (val);
1136 }
1137
1138 /*
1139 * Set up socket buffer sizes before a connection is made.
1140 */
1141 void
1142 setupsockbufsize(sock)
1143 int sock;
1144 {
1145 static int sndbuf_default, rcvbuf_default;
1146 int len, size;
1147
1148 /*
1149 * Get the default socket buffer sizes if we don't already
1150 * have them. It doesn't matter which socket we do this
1151 * to, because on the first call no socket buffer sizes
1152 * will have been modified, so we are guaranteed to get
1153 * the system defaults.
1154 */
1155 if (sndbuf_default == 0) {
1156 len = sizeof(sndbuf_default);
1157 if (getsockopt(sock, SOL_SOCKET, SO_SNDBUF, &sndbuf_default,
1158 &len) < 0)
1159 err(1, "unable to get default sndbuf size");
1160 len = sizeof(rcvbuf_default);
1161 if (getsockopt(sock, SOL_SOCKET, SO_RCVBUF, &rcvbuf_default,
1162 &len) < 0)
1163 err(1, "unable to get default rcvbuf size");
1164
1165 }
1166
1167 size = sndbuf_size ? sndbuf_size : sndbuf_default;
1168 if (setsockopt(sock, SOL_SOCKET, SO_SNDBUF, &size, sizeof(size)) < 0)
1169 warn("unable to set sndbuf size %d", size);
1170
1171 size = rcvbuf_size ? rcvbuf_size : rcvbuf_default;
1172 if (setsockopt(sock, SOL_SOCKET, SO_RCVBUF, &size, sizeof(size)) < 0)
1173 warn("unable to set rcvbuf size %d", size);
1174 }
1175
1176 /*
1177 * If the socket buffer sizes were not set manually (i.e. came from a
1178 * configuration file), reset them so the right thing will happen on
1179 * subsequent connections.
1180 */
1181 void
1182 resetsockbufsize()
1183 {
1184
1185 if (sndbuf_manual == 0)
1186 sndbuf_size = 0;
1187 if (rcvbuf_manual == 0)
1188 rcvbuf_size = 0;
1189 }
1190
1191 void
1192 ftpvis(dst, dstlen, src, srclen)
1193 char *dst;
1194 size_t dstlen;
1195 const char *src;
1196 size_t srclen;
1197 {
1198 int di, si;
1199
1200 for (di = si = 0;
1201 src[si] != '\0' && di < dstlen && si < srclen;
1202 di++, si++) {
1203 switch (src[si]) {
1204 case '\\':
1205 case ' ':
1206 case '\t':
1207 case '\r':
1208 case '\n':
1209 case '"':
1210 dst[di++] = '\\';
1211 if (di >= dstlen)
1212 break;
1213 /* FALLTHROUGH */
1214 default:
1215 dst[di] = src[si];
1216 }
1217 }
1218 dst[di] = '\0';
1219 }
1220
1221 /*
1222 * Internal version of connect(2); sets socket buffer sizes first.
1223 */
1224 int
1225 xconnect(sock, name, namelen)
1226 int sock;
1227 const struct sockaddr *name;
1228 int namelen;
1229 {
1230
1231 setupsockbufsize(sock);
1232 return (connect(sock, name, namelen));
1233 }
1234
1235 /*
1236 * Internal version of listen(2); sets socket buffer sizes first.
1237 */
1238 int
1239 xlisten(sock, backlog)
1240 int sock, backlog;
1241 {
1242
1243 setupsockbufsize(sock);
1244 return (listen(sock, backlog));
1245 }
1246
1247 void *
1248 xmalloc(size)
1249 size_t size;
1250 {
1251 void *p;
1252
1253 p = malloc(size);
1254 if (p == NULL)
1255 err(1, "Unable to allocate %ld bytes of memory", (long)size);
1256 return (p);
1257 }
1258
1259 char *
1260 xstrdup(str)
1261 const char *str;
1262 {
1263 char *s;
1264
1265 if (str == NULL)
1266 errx(1, "xstrdup() called with NULL argument");
1267 s = strdup(str);
1268 if (s == NULL)
1269 err(1, "Unable to allocate memory for string copy");
1270 return (s);
1271 }
1272
1273 sig_t
1274 xsignal(sig, func)
1275 int sig;
1276 void (*func) __P((int));
1277 {
1278 struct sigaction act, oact;
1279
1280 act.sa_handler = func;
1281 sigemptyset(&act.sa_mask);
1282 act.sa_flags = SA_RESTART;
1283 if (sigaction(sig, &act, &oact) < 0)
1284 return (SIG_ERR);
1285 return (oact.sa_handler);
1286 }
1287