util.c revision 1.43 1 /* $NetBSD: util.c,v 1.43 1999/02/07 13:14:07 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.43 1999/02/07 13:14:07 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 /*
753 * print progress bar only if we are foreground process.
754 */
755 if (foregroundproc())
756 progressmeter(0);
757 }
758 #endif /* SMALL */
759
760
761 /*
762 * List of order of magnitude prefixes.
763 * The last is `P', as 2^64 = 16384 Petabytes
764 */
765 static const char prefixes[] = " KMGTP";
766
767 /*
768 * Display a transfer progress bar if progress is non-zero.
769 * SIGALRM is hijacked for use by this function.
770 * - Before the transfer, set filesize to size of file (or -1 if unknown),
771 * and call with flag = -1. This starts the once per second timer,
772 * and a call to updateprogressmeter() upon SIGALRM.
773 * - During the transfer, updateprogressmeter will call progressmeter
774 * with flag = 0
775 * - After the transfer, call with flag = 1
776 */
777 static struct timeval start;
778 static struct timeval lastupdate;
779
780 void
781 progressmeter(flag)
782 int flag;
783 {
784 #ifndef SMALL
785 static off_t lastsize;
786 struct timeval now, td, wait;
787 off_t cursize, abbrevsize, bytespersec;
788 double elapsed;
789 int ratio, barlength, i, len, remaining;
790 char buf[256];
791
792 len = 0;
793
794 if (flag == -1) {
795 (void)gettimeofday(&start, NULL);
796 lastupdate = start;
797 lastsize = restart_point;
798 }
799 (void)gettimeofday(&now, NULL);
800 if (!progress || filesize <= 0)
801 return;
802 cursize = bytes + restart_point;
803
804 ratio = (int)((double)cursize * 100.0 / (double)filesize);
805 ratio = MAX(ratio, 0);
806 ratio = MIN(ratio, 100);
807 len += snprintf(buf + len, sizeof(buf) - len, "\r%3d%% ", ratio);
808
809 barlength = ttywidth - 43;
810 if (barlength > 0) {
811 i = barlength * ratio / 100;
812 len += snprintf(buf + len, sizeof(buf) - len,
813 "|%.*s%*s|", i,
814 "*****************************************************************************"
815 "*****************************************************************************",
816 barlength - i, "");
817 }
818
819 abbrevsize = cursize;
820 for (i = 0; abbrevsize >= 100000 && i < sizeof(prefixes); i++)
821 abbrevsize >>= 10;
822 len += snprintf(buf + len, sizeof(buf) - len,
823 #ifndef NO_QUAD
824 " %5qd %c%c ", (long long)abbrevsize,
825 #else
826 " %5ld %c%c ", (long)abbrevsize,
827 #endif
828 prefixes[i],
829 i == 0 ? ' ' : 'B');
830
831 timersub(&now, &lastupdate, &wait);
832 if (cursize > lastsize) {
833 lastupdate = now;
834 lastsize = cursize;
835 if (wait.tv_sec >= STALLTIME) { /* fudge out stalled time */
836 start.tv_sec += wait.tv_sec;
837 start.tv_usec += wait.tv_usec;
838 }
839 wait.tv_sec = 0;
840 }
841
842 timersub(&now, &start, &td);
843 elapsed = td.tv_sec + (td.tv_usec / 1000000.0);
844
845 bytespersec = 0;
846 if (bytes > 0) {
847 bytespersec = bytes;
848 if (elapsed > 0.0)
849 bytespersec /= elapsed;
850 }
851 for (i = 1; bytespersec >= 1024000 && i < sizeof(prefixes); i++)
852 bytespersec >>= 10;
853 len += snprintf(buf + len, sizeof(buf) - len,
854 #ifndef NO_QUAD
855 " %3qd.%02d %cB/s ", (long long)bytespersec / 1024,
856 #else
857 " %3ld.%02d %cB/s ", (long)bytespersec / 1024,
858 #endif
859 (int)((bytespersec % 1024) * 100 / 1024),
860 prefixes[i]);
861
862 if (bytes <= 0 || elapsed <= 0.0 || cursize > filesize) {
863 len += snprintf(buf + len, sizeof(buf) - len,
864 " --:-- ETA");
865 } else if (wait.tv_sec >= STALLTIME) {
866 len += snprintf(buf + len, sizeof(buf) - len,
867 " - stalled -");
868 } else {
869 remaining = (int)
870 ((filesize - restart_point) / (bytes / elapsed) - elapsed);
871 if (remaining >= 100 * SECSPERHOUR)
872 len += snprintf(buf + len, sizeof(buf) - len,
873 " --:-- ETA");
874 else {
875 i = remaining / SECSPERHOUR;
876 if (i)
877 len += snprintf(buf + len, sizeof(buf) - len,
878 "%2d:", i);
879 else
880 len += snprintf(buf + len, sizeof(buf) - len,
881 " ");
882 i = remaining % SECSPERHOUR;
883 len += snprintf(buf + len, sizeof(buf) - len,
884 "%02d:%02d ETA", i / 60, i % 60);
885 }
886 }
887 (void)write(fileno(ttyout), buf, len);
888
889 if (flag == -1) {
890 (void)xsignal(SIGALRM, updateprogressmeter);
891 alarmtimer(1); /* set alarm timer for 1 Hz */
892 } else if (flag == 1) {
893 (void)xsignal(SIGALRM, SIG_DFL);
894 alarmtimer(0);
895 (void)putc('\n', ttyout);
896 }
897 fflush(ttyout);
898 #endif /* SMALL */
899 }
900
901 /*
902 * Display transfer statistics.
903 * Requires start to be initialised by progressmeter(-1),
904 * direction to be defined by xfer routines, and filesize and bytes
905 * to be updated by xfer routines
906 * If siginfo is nonzero, an ETA is displayed, and the output goes to stderr
907 * instead of ttyout.
908 */
909 void
910 ptransfer(siginfo)
911 int siginfo;
912 {
913 #ifndef SMALL
914 struct timeval now, td, wait;
915 double elapsed;
916 off_t bytespersec;
917 int remaining, hh, i, len;
918 char buf[100];
919
920 if (!verbose && !siginfo)
921 return;
922
923 (void)gettimeofday(&now, NULL);
924 timersub(&now, &start, &td);
925 elapsed = td.tv_sec + (td.tv_usec / 1000000.0);
926 bytespersec = 0;
927 if (bytes > 0) {
928 bytespersec = bytes;
929 if (elapsed > 0.0)
930 bytespersec /= elapsed;
931 }
932 len = 0;
933 len += snprintf(buf + len, sizeof(buf) - len,
934 #ifndef NO_QUAD
935 "%qd byte%s %s in ", (long long)bytes,
936 #else
937 "%ld byte%s %s in ", (long)bytes,
938 #endif
939 bytes == 1 ? "" : "s", direction);
940 remaining = (int)elapsed;
941 if (remaining > SECSPERDAY) {
942 int days;
943
944 days = remaining / SECSPERDAY;
945 remaining %= SECSPERDAY;
946 len += snprintf(buf + len, sizeof(buf) - len,
947 "%d day%s ", days, days == 1 ? "" : "s");
948 }
949 hh = remaining / SECSPERHOUR;
950 remaining %= SECSPERHOUR;
951 if (hh)
952 len += snprintf(buf + len, sizeof(buf) - len, "%2d:", hh);
953 len += snprintf(buf + len, sizeof(buf) - len,
954 "%02d:%02d ", remaining / 60, remaining % 60);
955
956 for (i = 1; bytespersec >= 1024000 && i < sizeof(prefixes); i++)
957 bytespersec >>= 10;
958 len += snprintf(buf + len, sizeof(buf) - len,
959 #ifndef NO_QUAD
960 "(%qd.%02d %cB/s)", (long long)bytespersec / 1024,
961 #else
962 "(%ld.%02d %cB/s)", (long)bytespersec / 1024,
963 #endif
964 (int)((bytespersec % 1024) * 100 / 1024),
965 prefixes[i]);
966
967 if (siginfo && bytes > 0 && elapsed > 0.0 && filesize >= 0
968 && bytes + restart_point <= filesize) {
969 remaining = (int)((filesize - restart_point) /
970 (bytes / elapsed) - elapsed);
971 hh = remaining / SECSPERHOUR;
972 remaining %= SECSPERHOUR;
973 len += snprintf(buf + len, sizeof(buf) - len, " ETA: ");
974 if (hh)
975 len += snprintf(buf + len, sizeof(buf) - len, "%2d:",
976 hh);
977 len += snprintf(buf + len, sizeof(buf) - len,
978 "%02d:%02d", remaining / 60, remaining % 60);
979 timersub(&now, &lastupdate, &wait);
980 if (wait.tv_sec >= STALLTIME)
981 len += snprintf(buf + len, sizeof(buf) - len,
982 " (stalled)");
983 }
984 len += snprintf(buf + len, sizeof(buf) - len, "\n");
985 (void)write(siginfo ? STDERR_FILENO : fileno(ttyout), buf, len);
986 #endif /* SMALL */
987 }
988
989 /*
990 * List words in stringlist, vertically arranged
991 */
992 void
993 list_vertical(sl)
994 StringList *sl;
995 {
996 int i, j, w;
997 int columns, width, lines, items;
998 char *p;
999
1000 width = items = 0;
1001
1002 for (i = 0 ; i < sl->sl_cur ; i++) {
1003 w = strlen(sl->sl_str[i]);
1004 if (w > width)
1005 width = w;
1006 }
1007 width = (width + 8) &~ 7;
1008
1009 columns = ttywidth / width;
1010 if (columns == 0)
1011 columns = 1;
1012 lines = (sl->sl_cur + columns - 1) / columns;
1013 for (i = 0; i < lines; i++) {
1014 for (j = 0; j < columns; j++) {
1015 p = sl->sl_str[j * lines + i];
1016 if (p)
1017 fputs(p, ttyout);
1018 if (j * lines + i + lines >= sl->sl_cur) {
1019 putc('\n', ttyout);
1020 break;
1021 }
1022 w = strlen(p);
1023 while (w < width) {
1024 w = (w + 8) &~ 7;
1025 (void)putc('\t', ttyout);
1026 }
1027 }
1028 }
1029 }
1030
1031 /*
1032 * Update the global ttywidth value, using TIOCGWINSZ.
1033 */
1034 void
1035 setttywidth(a)
1036 int a;
1037 {
1038 struct winsize winsize;
1039
1040 if (ioctl(fileno(ttyout), TIOCGWINSZ, &winsize) != -1 &&
1041 winsize.ws_col != 0)
1042 ttywidth = winsize.ws_col;
1043 else
1044 ttywidth = 80;
1045 }
1046
1047 /*
1048 * Set the SIGALRM interval timer for wait seconds, 0 to disable.
1049 */
1050 void
1051 alarmtimer(wait)
1052 int wait;
1053 {
1054 struct itimerval itv;
1055
1056 itv.it_value.tv_sec = wait;
1057 itv.it_value.tv_usec = 0;
1058 itv.it_interval = itv.it_value;
1059 setitimer(ITIMER_REAL, &itv, NULL);
1060 }
1061
1062 /*
1063 * Setup or cleanup EditLine structures
1064 */
1065 #ifndef SMALL
1066 void
1067 controlediting()
1068 {
1069 if (editing && el == NULL && hist == NULL) {
1070 HistEvent ev;
1071 int editmode;
1072
1073 el = el_init(__progname, stdin, ttyout, stderr);
1074 /* init editline */
1075 hist = history_init(); /* init the builtin history */
1076 history(hist, &ev, H_SETSIZE, 100);/* remember 100 events */
1077 el_set(el, EL_HIST, history, hist); /* use history */
1078
1079 el_set(el, EL_EDITOR, "emacs"); /* default editor is emacs */
1080 el_set(el, EL_PROMPT, prompt); /* set the prompt function */
1081
1082 /* add local file completion, bind to TAB */
1083 el_set(el, EL_ADDFN, "ftp-complete",
1084 "Context sensitive argument completion",
1085 complete);
1086 el_set(el, EL_BIND, "^I", "ftp-complete", NULL);
1087 el_source(el, NULL); /* read ~/.editrc */
1088 if ((el_get(el, EL_EDITMODE, &editmode) != -1) && editmode == 0)
1089 editing = 0; /* the user doesn't want editing,
1090 * so disable, and let statement
1091 * below cleanup */
1092 else
1093 el_set(el, EL_SIGNAL, 1);
1094 }
1095 if (!editing) {
1096 if (hist) {
1097 history_end(hist);
1098 hist = NULL;
1099 }
1100 if (el) {
1101 el_end(el);
1102 el = NULL;
1103 }
1104 }
1105 }
1106 #endif /* !SMALL */
1107
1108 /*
1109 * Parse the specified socket buffer size.
1110 */
1111 int
1112 getsockbufsize(arg)
1113 const char *arg;
1114 {
1115 char *cp;
1116 int val;
1117
1118 if (!isdigit((unsigned char)arg[0]))
1119 return (-1);
1120
1121 val = strtol(arg, &cp, 10);
1122 if (cp != NULL) {
1123 if (cp[1] != '\0')
1124 return (-1);
1125 if (cp[0] == 'k')
1126 val *= 1024;
1127 if (cp[0] == 'm')
1128 val *= 1024 * 1024;
1129 }
1130
1131 if (val < 0)
1132 return (-1);
1133
1134 return (val);
1135 }
1136
1137 /*
1138 * Set up socket buffer sizes before a connection is made.
1139 */
1140 void
1141 setupsockbufsize(sock)
1142 int sock;
1143 {
1144 static int sndbuf_default, rcvbuf_default;
1145 int len, size;
1146
1147 /*
1148 * Get the default socket buffer sizes if we don't already
1149 * have them. It doesn't matter which socket we do this
1150 * to, because on the first call no socket buffer sizes
1151 * will have been modified, so we are guaranteed to get
1152 * the system defaults.
1153 */
1154 if (sndbuf_default == 0) {
1155 len = sizeof(sndbuf_default);
1156 if (getsockopt(sock, SOL_SOCKET, SO_SNDBUF, &sndbuf_default,
1157 &len) < 0)
1158 err(1, "unable to get default sndbuf size");
1159 len = sizeof(rcvbuf_default);
1160 if (getsockopt(sock, SOL_SOCKET, SO_RCVBUF, &rcvbuf_default,
1161 &len) < 0)
1162 err(1, "unable to get default rcvbuf size");
1163
1164 }
1165
1166 size = sndbuf_size ? sndbuf_size : sndbuf_default;
1167 if (setsockopt(sock, SOL_SOCKET, SO_SNDBUF, &size, sizeof(size)) < 0)
1168 warn("unable to set sndbuf size %d", size);
1169
1170 size = rcvbuf_size ? rcvbuf_size : rcvbuf_default;
1171 if (setsockopt(sock, SOL_SOCKET, SO_RCVBUF, &size, sizeof(size)) < 0)
1172 warn("unable to set rcvbuf size %d", size);
1173 }
1174
1175 /*
1176 * If the socket buffer sizes were not set manually (i.e. came from a
1177 * configuration file), reset them so the right thing will happen on
1178 * subsequent connections.
1179 */
1180 void
1181 resetsockbufsize()
1182 {
1183
1184 if (sndbuf_manual == 0)
1185 sndbuf_size = 0;
1186 if (rcvbuf_manual == 0)
1187 rcvbuf_size = 0;
1188 }
1189
1190 void
1191 ftpvis(dst, dstlen, src, srclen)
1192 char *dst;
1193 size_t dstlen;
1194 const char *src;
1195 size_t srclen;
1196 {
1197 int di, si;
1198
1199 for (di = si = 0;
1200 src[si] != '\0' && di < dstlen && si < srclen;
1201 di++, si++) {
1202 switch (src[si]) {
1203 case '\\':
1204 case ' ':
1205 case '\t':
1206 case '\r':
1207 case '"':
1208 dst[di++] = '\\';
1209 if (di >= dstlen)
1210 break;
1211 /* FALLTHROUGH */
1212 default:
1213 dst[di] = src[si];
1214 }
1215 }
1216 dst[di] = '\0';
1217 }
1218
1219 /*
1220 * Internal version of connect(2); sets socket buffer sizes first.
1221 */
1222 int
1223 xconnect(sock, name, namelen)
1224 int sock;
1225 const struct sockaddr *name;
1226 int namelen;
1227 {
1228
1229 setupsockbufsize(sock);
1230 return (connect(sock, name, namelen));
1231 }
1232
1233 /*
1234 * Internal version of listen(2); sets socket buffer sizes first.
1235 */
1236 int
1237 xlisten(sock, backlog)
1238 int sock, backlog;
1239 {
1240
1241 setupsockbufsize(sock);
1242 return (listen(sock, backlog));
1243 }
1244
1245 void *
1246 xmalloc(size)
1247 size_t size;
1248 {
1249 void *p;
1250
1251 p = malloc(size);
1252 if (p == NULL)
1253 err(1, "Unable to allocate %ld bytes of memory", (long)size);
1254 return (p);
1255 }
1256
1257 char *
1258 xstrdup(str)
1259 const char *str;
1260 {
1261 char *s;
1262
1263 if (str == NULL)
1264 errx(1, "xstrdup() called with NULL argument");
1265 s = strdup(str);
1266 if (s == NULL)
1267 err(1, "Unable to allocate memory for string copy");
1268 return (s);
1269 }
1270
1271 sig_t
1272 xsignal(sig, func)
1273 int sig;
1274 void (*func) __P((int));
1275 {
1276 struct sigaction act, oact;
1277
1278 act.sa_handler = func;
1279 sigemptyset(&act.sa_mask);
1280 act.sa_flags = SA_RESTART;
1281 if (sigaction(sig, &act, &oact) < 0)
1282 return (SIG_ERR);
1283 return (oact.sa_handler);
1284 }
1285