util.c revision 1.41 1 /* $NetBSD: util.c,v 1.41 1999/01/24 02:39:30 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.41 1999/01/24 02:39:30 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) ||
503 gl.gl_pathc == 0) {
504 warnx("%s: not found", *cpp);
505 globfree(&gl);
506 return (0);
507 }
508 /* XXX: caller should check if *cpp changed, and
509 * free(*cpp) if that is the case
510 */
511 *cpp = xstrdup(gl.gl_pathv[0]);
512 globfree(&gl);
513 return (1);
514 }
515
516 /*
517 * determine size of remote file
518 */
519 off_t
520 remotesize(file, noisy)
521 const char *file;
522 int noisy;
523 {
524 int overbose;
525 off_t size;
526
527 overbose = verbose;
528 size = -1;
529 if (debug == 0)
530 verbose = -1;
531 if (command("SIZE %s", file) == COMPLETE) {
532 char *cp, *ep;
533
534 cp = strchr(reply_string, ' ');
535 if (cp != NULL) {
536 cp++;
537 #ifndef NO_QUAD
538 size = strtoq(cp, &ep, 10);
539 #else
540 size = strtol(cp, &ep, 10);
541 #endif
542 if (*ep != '\0' && !isspace((unsigned char)*ep))
543 size = -1;
544 }
545 } else if (noisy && debug == 0) {
546 fputs(reply_string, ttyout);
547 putc('\n', ttyout);
548 }
549 verbose = overbose;
550 return (size);
551 }
552
553 /*
554 * determine last modification time (in GMT) of remote file
555 */
556 time_t
557 remotemodtime(file, noisy)
558 const char *file;
559 int noisy;
560 {
561 int overbose;
562 time_t rtime;
563 int ocode;
564
565 overbose = verbose;
566 ocode = code;
567 rtime = -1;
568 if (debug == 0)
569 verbose = -1;
570 if (command("MDTM %s", file) == COMPLETE) {
571 struct tm timebuf;
572 int yy, mo, day, hour, min, sec;
573 sscanf(reply_string, "%*s %04d%02d%02d%02d%02d%02d", &yy, &mo,
574 &day, &hour, &min, &sec);
575 memset(&timebuf, 0, sizeof(timebuf));
576 timebuf.tm_sec = sec;
577 timebuf.tm_min = min;
578 timebuf.tm_hour = hour;
579 timebuf.tm_mday = day;
580 timebuf.tm_mon = mo - 1;
581 timebuf.tm_year = yy - TM_YEAR_BASE;
582 timebuf.tm_isdst = -1;
583 rtime = mkgmtime(&timebuf);
584 if (rtime == -1 && (noisy || debug != 0))
585 fprintf(ttyout, "Can't convert %s to a time.\n",
586 reply_string);
587 } else if (noisy && debug == 0) {
588 fputs(reply_string, ttyout);
589 putc('\n', ttyout);
590 }
591 verbose = overbose;
592 if (rtime == -1)
593 code = ocode;
594 return (rtime);
595 }
596
597 /*
598 * UTC version of mktime(3)
599 */
600 #ifdef HAVE_TIMEGM
601 time_t
602 mkgmtime(tm)
603 struct tm *tm;
604 {
605
606 /* This is very clean, but not portable at all. */
607 return (timegm(tm));
608 }
609
610 #else /* not HAVE_TIMEGM */
611
612 /*
613 * This code is not portable, but works on most Unix-like systems.
614 * If the local timezone has no summer time, using mktime(3) function
615 * and adjusting offset would be usable (adjusting leap seconds
616 * is still required, though), but the assumption is not always true.
617 *
618 * Anyway, no portable and correct implementation of UTC to time_t
619 * conversion exists....
620 */
621
622 static time_t
623 sub_mkgmt(tm)
624 struct tm *tm;
625 {
626 int y, nleapdays;
627 time_t t;
628 /* days before the month */
629 static const unsigned short moff[12] = {
630 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334
631 };
632
633 /*
634 * XXX This code assumes the given time to be normalized.
635 * Normalizing here is impossible in case the given time is a leap
636 * second but the local time library is ignorant of leap seconds.
637 */
638
639 /* minimal sanity checking not to access outside of the array */
640 if ((unsigned) tm->tm_mon >= 12)
641 return (time_t) -1;
642 if (tm->tm_year < EPOCH_YEAR - TM_YEAR_BASE)
643 return (time_t) -1;
644
645 y = tm->tm_year + TM_YEAR_BASE - (tm->tm_mon < 2);
646 nleapdays = y / 4 - y / 100 + y / 400 -
647 ((EPOCH_YEAR-1) / 4 - (EPOCH_YEAR-1) / 100 + (EPOCH_YEAR-1) / 400);
648 t = ((((time_t) (tm->tm_year - (EPOCH_YEAR - TM_YEAR_BASE)) * 365 +
649 moff[tm->tm_mon] + tm->tm_mday - 1 + nleapdays) * 24 +
650 tm->tm_hour) * 60 + tm->tm_min) * 60 + tm->tm_sec;
651
652 return (t < 0 ? (time_t) -1 : t);
653 }
654
655 time_t
656 mkgmtime(tm)
657 struct tm *tm;
658 {
659 time_t t, t2;
660 struct tm *tm2;
661 int sec;
662
663 /* Do the first guess. */
664 if ((t = sub_mkgmt(tm)) == (time_t) -1)
665 return (time_t) -1;
666
667 /* save value in case *tm is overwritten by gmtime() */
668 sec = tm->tm_sec;
669
670 tm2 = gmtime(&t);
671 if ((t2 = sub_mkgmt(tm2)) == (time_t) -1)
672 return (time_t) -1;
673
674 if (t2 < t || tm2->tm_sec != sec) {
675 /*
676 * Adjust for leap seconds.
677 *
678 * real time_t time
679 * |
680 * tm
681 * / ... (a) first sub_mkgmt() conversion
682 * t
683 * |
684 * tm2
685 * / ... (b) second sub_mkgmt() conversion
686 * t2
687 * --->time
688 */
689 /*
690 * Do the second guess, assuming (a) and (b) are almost equal.
691 */
692 t += t - t2;
693 tm2 = gmtime(&t);
694
695 /*
696 * Either (a) or (b), may include one or two extra
697 * leap seconds. Try t, t + 2, t - 2, t + 1, and t - 1.
698 */
699 if (tm2->tm_sec == sec
700 || (t += 2, tm2 = gmtime(&t), tm2->tm_sec == sec)
701 || (t -= 4, tm2 = gmtime(&t), tm2->tm_sec == sec)
702 || (t += 3, tm2 = gmtime(&t), tm2->tm_sec == sec)
703 || (t -= 2, tm2 = gmtime(&t), tm2->tm_sec == sec))
704 ; /* found */
705 else {
706 /*
707 * Not found.
708 */
709 if (sec >= 60)
710 /*
711 * The given time is a leap second
712 * (sec 60 or 61), but the time library
713 * is ignorant of the leap second.
714 */
715 ; /* treat sec 60 as 59,
716 sec 61 as 0 of the next minute */
717 else
718 /* The given time may not be normalized. */
719 t++; /* restore t */
720 }
721 }
722
723 return (t < 0 ? (time_t) -1 : t);
724 }
725 #endif /* not HAVE_TIMEGM */
726
727 #ifndef SMALL
728
729 /*
730 * return non-zero if we're the current foreground process
731 */
732 int
733 foregroundproc()
734 {
735 static pid_t pgrp = -1;
736 int ctty_pgrp;
737
738 if (pgrp == -1)
739 pgrp = getpgrp();
740
741 return ((ioctl(fileno(ttyout), TIOCGPGRP, &ctty_pgrp) != -1 &&
742 ctty_pgrp == (int)pgrp));
743 }
744
745
746 static void updateprogressmeter __P((int));
747
748 static void
749 updateprogressmeter(dummy)
750 int dummy;
751 {
752
753 /*
754 * print progress bar only if we are foreground process.
755 */
756 if (foregroundproc())
757 progressmeter(0);
758 }
759 #endif /* SMALL */
760
761
762 /*
763 * List of order of magnitude prefixes.
764 * The last is `P', as 2^64 = 16384 Petabytes
765 */
766 static const char prefixes[] = " KMGTP";
767
768 /*
769 * Display a transfer progress bar if progress is non-zero.
770 * SIGALRM is hijacked for use by this function.
771 * - Before the transfer, set filesize to size of file (or -1 if unknown),
772 * and call with flag = -1. This starts the once per second timer,
773 * and a call to updateprogressmeter() upon SIGALRM.
774 * - During the transfer, updateprogressmeter will call progressmeter
775 * with flag = 0
776 * - After the transfer, call with flag = 1
777 */
778 static struct timeval start;
779 static struct timeval lastupdate;
780
781 void
782 progressmeter(flag)
783 int flag;
784 {
785 #ifndef SMALL
786 static off_t lastsize;
787 struct timeval now, td, wait;
788 off_t cursize, abbrevsize, bytespersec;
789 double elapsed;
790 int ratio, barlength, i, len, remaining;
791 char buf[256];
792
793 len = 0;
794
795 if (flag == -1) {
796 (void)gettimeofday(&start, NULL);
797 lastupdate = start;
798 lastsize = restart_point;
799 }
800 (void)gettimeofday(&now, NULL);
801 if (!progress || filesize <= 0)
802 return;
803 cursize = bytes + restart_point;
804
805 ratio = (int)((double)cursize * 100.0 / (double)filesize);
806 ratio = MAX(ratio, 0);
807 ratio = MIN(ratio, 100);
808 len += snprintf(buf + len, sizeof(buf) - len, "\r%3d%% ", ratio);
809
810 barlength = ttywidth - 43;
811 if (barlength > 0) {
812 i = barlength * ratio / 100;
813 len += snprintf(buf + len, sizeof(buf) - len,
814 "|%.*s%*s|", i,
815 "*****************************************************************************"
816 "*****************************************************************************",
817 barlength - i, "");
818 }
819
820 abbrevsize = cursize;
821 for (i = 0; abbrevsize >= 100000 && i < sizeof(prefixes); i++)
822 abbrevsize >>= 10;
823 len += snprintf(buf + len, sizeof(buf) - len,
824 #ifndef NO_QUAD
825 " %5qd %c%c ", (long long)abbrevsize,
826 #else
827 " %5ld %c%c ", (long)abbrevsize,
828 #endif
829 prefixes[i],
830 i == 0 ? ' ' : 'B');
831
832 timersub(&now, &lastupdate, &wait);
833 if (cursize > lastsize) {
834 lastupdate = now;
835 lastsize = cursize;
836 if (wait.tv_sec >= STALLTIME) { /* fudge out stalled time */
837 start.tv_sec += wait.tv_sec;
838 start.tv_usec += wait.tv_usec;
839 }
840 wait.tv_sec = 0;
841 }
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)fwrite(buf, sizeof(char), len, ttyout);
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)fwrite(buf, sizeof(char), len, siginfo ? stderr : ttyout);
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 /*
1192 * Internal version of connect(2); sets socket buffer sizes first.
1193 */
1194 int
1195 xconnect(sock, name, namelen)
1196 int sock;
1197 const struct sockaddr *name;
1198 int namelen;
1199 {
1200
1201 setupsockbufsize(sock);
1202 return (connect(sock, name, namelen));
1203 }
1204
1205 /*
1206 * Internal version of listen(2); sets socket buffer sizes first.
1207 */
1208 int
1209 xlisten(sock, backlog)
1210 int sock, backlog;
1211 {
1212
1213 setupsockbufsize(sock);
1214 return (listen(sock, backlog));
1215 }
1216
1217 void *
1218 xmalloc(size)
1219 size_t size;
1220 {
1221 void *p;
1222
1223 p = malloc(size);
1224 if (p == NULL)
1225 err(1, "Unable to allocate %ld bytes of memory", (long)size);
1226 return (p);
1227 }
1228
1229 char *
1230 xstrdup(str)
1231 const char *str;
1232 {
1233 char *s;
1234
1235 if (str == NULL)
1236 errx(1, "xstrdup() called with NULL argument");
1237 s = strdup(str);
1238 if (s == NULL)
1239 err(1, "Unable to allocate memory for string copy");
1240 return (s);
1241 }
1242
1243 sig_t
1244 xsignal(sig, func)
1245 int sig;
1246 void (*func) __P((int));
1247 {
1248 struct sigaction act, oact;
1249
1250 act.sa_handler = func;
1251 sigemptyset(&act.sa_mask);
1252 act.sa_flags = SA_RESTART;
1253 if (sigaction(sig, &act, &oact) < 0)
1254 return (SIG_ERR);
1255 return (oact.sa_handler);
1256 }
1257