util.c revision 1.29 1 /* $NetBSD: util.c,v 1.29 1998/07/26 21:47:48 mycroft Exp $ */
2
3 /*-
4 * Copyright (c) 1998 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 * Redistribution and use in source and binary forms, with or without
12 * modification, are permitted provided that the following conditions
13 * are met:
14 * 1. Redistributions of source code must retain the above copyright
15 * notice, this list of conditions and the following disclaimer.
16 * 2. Redistributions in binary form must reproduce the above copyright
17 * notice, this list of conditions and the following disclaimer in the
18 * documentation and/or other materials provided with the distribution.
19 * 3. All advertising materials mentioning features or use of this software
20 * must display the following acknowledgement:
21 * This product includes software developed by the NetBSD
22 * Foundation, Inc. and its contributors.
23 * 4. Neither the name of The NetBSD Foundation nor the names of its
24 * contributors may be used to endorse or promote products derived
25 * from this software without specific prior written permission.
26 *
27 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
28 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
29 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
30 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
31 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
32 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
33 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
34 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
35 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
36 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
37 * POSSIBILITY OF SUCH DAMAGE.
38 */
39
40 /*
41 * Copyright (c) 1985, 1989, 1993, 1994
42 * The Regents of the University of California. All rights reserved.
43 *
44 * Redistribution and use in source and binary forms, with or without
45 * modification, are permitted provided that the following conditions
46 * are met:
47 * 1. Redistributions of source code must retain the above copyright
48 * notice, this list of conditions and the following disclaimer.
49 * 2. Redistributions in binary form must reproduce the above copyright
50 * notice, this list of conditions and the following disclaimer in the
51 * documentation and/or other materials provided with the distribution.
52 * 3. All advertising materials mentioning features or use of this software
53 * must display the following acknowledgement:
54 * This product includes software developed by the University of
55 * California, Berkeley and its contributors.
56 * 4. Neither the name of the University nor the names of its contributors
57 * may be used to endorse or promote products derived from this software
58 * without specific prior written permission.
59 *
60 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
61 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
62 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
63 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
64 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
65 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
66 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
67 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
68 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
69 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
70 * SUCH DAMAGE.
71 */
72
73 #include <sys/cdefs.h>
74 #ifndef lint
75 __RCSID("$NetBSD: util.c,v 1.29 1998/07/26 21:47:48 mycroft Exp $");
76 #endif /* not lint */
77
78 /*
79 * FTP User Program -- Misc support routines
80 */
81 #include <sys/types.h>
82 #include <sys/socket.h>
83 #include <sys/ioctl.h>
84 #include <sys/time.h>
85 #include <arpa/ftp.h>
86
87 #include <ctype.h>
88 #include <err.h>
89 #include <fcntl.h>
90 #include <glob.h>
91 #include <termios.h>
92 #include <signal.h>
93 #include <limits.h>
94 #include <pwd.h>
95 #include <stdio.h>
96 #include <stdlib.h>
97 #include <string.h>
98 #include <time.h>
99 #include <tzfile.h>
100 #include <unistd.h>
101
102 #include "ftp_var.h"
103 #include "pathnames.h"
104
105 /*
106 * Connect to peer server and
107 * auto-login, if possible.
108 */
109 void
110 setpeer(argc, argv)
111 int argc;
112 char *argv[];
113 {
114 char *host;
115 in_port_t port;
116
117 if (connected) {
118 fprintf(ttyout, "Already connected to %s, use close first.\n",
119 hostname);
120 code = -1;
121 return;
122 }
123 if (argc < 2)
124 (void)another(&argc, &argv, "to");
125 if (argc < 2 || argc > 3) {
126 fprintf(ttyout, "usage: %s host-name [port]\n", argv[0]);
127 code = -1;
128 return;
129 }
130 if (gatemode)
131 port = gateport;
132 else
133 port = ftpport;
134 if (argc > 2) {
135 char *ep;
136 long nport;
137
138 nport = strtol(argv[2], &ep, 10);
139 if (nport < 1 || nport > MAX_IN_PORT_T || *ep != '\0') {
140 fprintf(ttyout, "%s: bad port number '%s'.\n",
141 argv[1], argv[2]);
142 fprintf(ttyout, "usage: %s host-name [port]\n",
143 argv[0]);
144 code = -1;
145 return;
146 }
147 port = htons((in_port_t)nport);
148 }
149
150 if (gatemode) {
151 if (gateserver == NULL || *gateserver == '\0')
152 errx(1, "gateserver not defined (shouldn't happen)");
153 host = hookup(gateserver, port);
154 } else
155 host = hookup(argv[1], port);
156
157 if (host) {
158 int overbose;
159
160 if (gatemode) {
161 if (command("PASSERVE %s", argv[1]) != COMPLETE)
162 return;
163 if (verbose)
164 fprintf(ttyout,
165 "Connected via pass-through server %s\n",
166 gateserver);
167 }
168
169 connected = 1;
170 /*
171 * Set up defaults for FTP.
172 */
173 (void)strcpy(typename, "ascii"), type = TYPE_A;
174 curtype = TYPE_A;
175 (void)strcpy(formname, "non-print"), form = FORM_N;
176 (void)strcpy(modename, "stream"), mode = MODE_S;
177 (void)strcpy(structname, "file"), stru = STRU_F;
178 (void)strcpy(bytename, "8"), bytesize = 8;
179 if (autologin)
180 (void)ftp_login(argv[1], NULL, NULL);
181
182 overbose = verbose;
183 if (debug == 0)
184 verbose = -1;
185 if (command("SYST") == COMPLETE && overbose) {
186 char *cp, c;
187 c = 0;
188 cp = strchr(reply_string + 4, ' ');
189 if (cp == NULL)
190 cp = strchr(reply_string + 4, '\r');
191 if (cp) {
192 if (cp[-1] == '.')
193 cp--;
194 c = *cp;
195 *cp = '\0';
196 }
197
198 fprintf(ttyout, "Remote system type is %s.\n",
199 reply_string + 4);
200 if (cp)
201 *cp = c;
202 }
203 if (!strncmp(reply_string, "215 UNIX Type: L8", 17)) {
204 if (proxy)
205 unix_proxy = 1;
206 else
207 unix_server = 1;
208 /*
209 * Set type to 0 (not specified by user),
210 * meaning binary by default, but don't bother
211 * telling server. We can use binary
212 * for text files unless changed by the user.
213 */
214 type = 0;
215 (void)strcpy(typename, "binary");
216 if (overbose)
217 fprintf(ttyout,
218 "Using %s mode to transfer files.\n",
219 typename);
220 } else {
221 if (proxy)
222 unix_proxy = 0;
223 else
224 unix_server = 0;
225 if (overbose &&
226 !strncmp(reply_string, "215 TOPS20", 10))
227 fputs(
228 "Remember to set tenex mode when transferring binary files from this machine.\n",
229 ttyout);
230 }
231 verbose = overbose;
232 }
233 }
234
235 /*
236 * login to remote host, using given username & password if supplied
237 */
238 int
239 ftp_login(host, user, pass)
240 const char *host;
241 const char *user, *pass;
242 {
243 char tmp[80];
244 const char *acct;
245 char anonpass[MAXLOGNAME + 1 + MAXHOSTNAMELEN + 1]; /* user@hostname */
246 char hostname[MAXHOSTNAMELEN + 1];
247 struct passwd *pw;
248 int n, aflag = 0;
249
250 acct = NULL;
251 if (user == NULL) {
252 if (ruserpass(host, &user, &pass, &acct) < 0) {
253 code = -1;
254 return (0);
255 }
256 }
257
258 /*
259 * Set up arguments for an anonymous FTP session, if necessary.
260 */
261 if ((user == NULL || pass == NULL) && anonftp) {
262 memset(anonpass, 0, sizeof(anonpass));
263 memset(hostname, 0, sizeof(hostname));
264
265 /*
266 * Set up anonymous login password.
267 */
268 if ((user = getlogin()) == NULL) {
269 if ((pw = getpwuid(getuid())) == NULL)
270 user = "anonymous";
271 else
272 user = pw->pw_name;
273 }
274 gethostname(hostname, MAXHOSTNAMELEN);
275 hostname[sizeof(hostname) - 1] = '\0';
276 #ifndef DONT_CHEAT_ANONPASS
277 /*
278 * Every anonymous FTP server I've encountered
279 * will accept the string "username@", and will
280 * append the hostname itself. We do this by default
281 * since many servers are picky about not having
282 * a FQDN in the anonymous password. - thorpej (at) netbsd.org
283 */
284 snprintf(anonpass, sizeof(anonpass) - 1, "%s@",
285 user);
286 #else
287 snprintf(anonpass, sizeof(anonpass) - 1, "%s@%s",
288 user, hp->h_name);
289 #endif
290 pass = anonpass;
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 = strdup(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 #ifdef NO_QUAD
538 size = strtol(cp, &ep, 10);
539 #else
540 size = strtoq(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 = mktime(&timebuf);
584 if (rtime == -1 && (noisy || debug != 0))
585 fprintf(ttyout, "Can't convert %s to a time.\n",
586 reply_string);
587 else
588 #ifndef __SVR4
589 rtime += timebuf.tm_gmtoff; /* conv. local -> GMT */
590 #else
591 rtime -= timezone;
592 #endif
593 } else if (noisy && debug == 0) {
594 fputs(reply_string, ttyout);
595 putc('\n', ttyout);
596 }
597 verbose = overbose;
598 if (rtime == -1)
599 code = ocode;
600 return (rtime);
601 }
602
603 #ifndef SMALL
604
605 /*
606 * return non-zero if we're the current foreground process
607 */
608 int
609 foregroundproc()
610 {
611 static pid_t pgrp = -1;
612 int ctty_pgrp;
613
614 if (pgrp == -1)
615 pgrp = getpgrp();
616
617 return ((ioctl(fileno(ttyout), TIOCGPGRP, &ctty_pgrp) != -1 &&
618 ctty_pgrp == (int)pgrp));
619 }
620
621
622 static void updateprogressmeter __P((int));
623
624 static void
625 updateprogressmeter(dummy)
626 int dummy;
627 {
628
629 /*
630 * print progress bar only if we are foreground process.
631 */
632 if (foregroundproc())
633 progressmeter(0);
634 }
635 #endif /* SMALL */
636
637 /*
638 * Display a transfer progress bar if progress is non-zero.
639 * SIGALRM is hijacked for use by this function.
640 * - Before the transfer, set filesize to size of file (or -1 if unknown),
641 * and call with flag = -1. This starts the once per second timer,
642 * and a call to updateprogressmeter() upon SIGALRM.
643 * - During the transfer, updateprogressmeter will call progressmeter
644 * with flag = 0
645 * - After the transfer, call with flag = 1
646 */
647 static struct timeval start;
648 static struct timeval lastupdate;
649
650 void
651 progressmeter(flag)
652 int flag;
653 {
654 #ifndef SMALL
655 /*
656 * List of order of magnitude prefixes.
657 * The last is `P', as 2^64 = 16384 Petabytes
658 */
659 static const char prefixes[] = " KMGTP";
660
661 static off_t lastsize;
662 struct timeval now, td, wait;
663 off_t cursize, abbrevsize;
664 double elapsed;
665 int ratio, barlength, i, len, remaining;
666 char buf[256];
667
668 len = 0;
669
670 if (flag == -1) {
671 (void)gettimeofday(&start, NULL);
672 lastupdate = start;
673 lastsize = restart_point;
674 }
675 (void)gettimeofday(&now, NULL);
676 if (!progress || filesize <= 0)
677 return;
678 cursize = bytes + restart_point;
679
680 ratio = cursize * 100 / filesize;
681 ratio = MAX(ratio, 0);
682 ratio = MIN(ratio, 100);
683 len += snprintf(buf + len, sizeof(buf) - len, "\r%3d%% ", ratio);
684
685 barlength = ttywidth - 30;
686 if (barlength > 0) {
687 i = barlength * ratio / 100;
688 len += snprintf(buf + len, sizeof(buf) - len,
689 "|%.*s%*s|", i,
690 "*****************************************************************************"
691 "*****************************************************************************",
692 barlength - i, "");
693 }
694
695 i = 0;
696 abbrevsize = cursize;
697 while (abbrevsize >= 100000 && i < sizeof(prefixes)) {
698 i++;
699 abbrevsize >>= 10;
700 }
701 len += snprintf(buf + len, sizeof(buf) - len,
702 " %5qd %c%c ", (long long)abbrevsize, prefixes[i],
703 prefixes[i] == ' ' ? ' ' : 'B');
704
705 timersub(&now, &lastupdate, &wait);
706 if (cursize > lastsize) {
707 lastupdate = now;
708 lastsize = cursize;
709 if (wait.tv_sec >= STALLTIME) { /* fudge out stalled time */
710 start.tv_sec += wait.tv_sec;
711 start.tv_usec += wait.tv_usec;
712 }
713 wait.tv_sec = 0;
714 }
715
716 timersub(&now, &start, &td);
717 elapsed = td.tv_sec + (td.tv_usec / 1000000.0);
718
719 if (bytes <= 0 || elapsed <= 0.0 || cursize > filesize) {
720 len += snprintf(buf + len, sizeof(buf) - len,
721 " --:-- ETA");
722 } else if (wait.tv_sec >= STALLTIME) {
723 len += snprintf(buf + len, sizeof(buf) - len,
724 " - stalled -");
725 } else {
726 remaining = (int)
727 ((filesize - restart_point) / (bytes / elapsed) - elapsed);
728 if (remaining >= 100 * SECSPERHOUR)
729 len += snprintf(buf + len, sizeof(buf) - len,
730 " --:-- ETA");
731 else {
732 i = remaining / SECSPERHOUR;
733 if (i)
734 len += snprintf(buf + len, sizeof(buf) - len,
735 "%2d:", i);
736 else
737 len += snprintf(buf + len, sizeof(buf) - len,
738 " ");
739 i = remaining % SECSPERHOUR;
740 len += snprintf(buf + len, sizeof(buf) - len,
741 "%02d:%02d ETA", i / 60, i % 60);
742 }
743 }
744 (void)write(fileno(ttyout), buf, len);
745
746 if (flag == -1) {
747 (void)signal(SIGALRM, updateprogressmeter);
748 alarmtimer(1); /* set alarm timer for 1 Hz */
749 } else if (flag == 1) {
750 alarmtimer(0);
751 (void)putc('\n', ttyout);
752 }
753 fflush(ttyout);
754 #endif /* SMALL */
755 }
756
757 /*
758 * Display transfer statistics.
759 * Requires start to be initialised by progressmeter(-1),
760 * direction to be defined by xfer routines, and filesize and bytes
761 * to be updated by xfer routines
762 * If siginfo is nonzero, an ETA is displayed, and the output goes to stderr
763 * instead of ttyout.
764 */
765 void
766 ptransfer(siginfo)
767 int siginfo;
768 {
769 #ifndef SMALL
770 struct timeval now, td, wait;
771 double elapsed;
772 off_t bs;
773 int meg, remaining, hh, len;
774 char buf[100];
775
776 if (!verbose && !siginfo)
777 return;
778
779 (void)gettimeofday(&now, NULL);
780 timersub(&now, &start, &td);
781 elapsed = td.tv_sec + (td.tv_usec / 1000000.0);
782 bs = bytes / (elapsed == 0.0 ? 1 : elapsed);
783 meg = 0;
784 if (bs > (1024 * 1024))
785 meg = 1;
786 len = 0;
787 len += snprintf(buf + len, sizeof(buf) - len,
788 #ifndef NO_QUAD
789 "%qd byte%s %s in ", (long long)bytes,
790 #else
791 "%ld byte%s %s in ", (long)bytes,
792 #endif
793 bytes == 1 ? "" : "s", direction);
794 remaining = (int)elapsed;
795 if (remaining > SECSPERDAY) {
796 int days;
797
798 days = remaining / SECSPERDAY;
799 remaining %= SECSPERDAY;
800 len += snprintf(buf + len, sizeof(buf) - len,
801 "%d day%s ", days, days == 1 ? "" : "s");
802 }
803 hh = remaining / SECSPERHOUR;
804 remaining %= SECSPERHOUR;
805 if (hh)
806 len += snprintf(buf + len, sizeof(buf) - len, "%2d:", hh);
807 len += snprintf(buf + len, sizeof(buf) - len,
808 "%02d:%02d (%.2f %sB/s)", remaining / 60, remaining % 60,
809 bs / (1024.0 * (meg ? 1024.0 : 1.0)),
810 meg ? "M" : "K");
811
812 if (siginfo && bytes > 0 && elapsed > 0.0 && filesize >= 0
813 && bytes + restart_point <= filesize) {
814 remaining = (int)((filesize - restart_point) /
815 (bytes / elapsed) - elapsed);
816 hh = remaining / SECSPERHOUR;
817 remaining %= SECSPERHOUR;
818 len += snprintf(buf + len, sizeof(buf) - len, " ETA: ");
819 if (hh)
820 len += snprintf(buf + len, sizeof(buf) - len, "%2d:",
821 hh);
822 len += snprintf(buf + len, sizeof(buf) - len,
823 "%02d:%02d", remaining / 60, remaining % 60);
824 timersub(&now, &lastupdate, &wait);
825 if (wait.tv_sec >= STALLTIME)
826 len += snprintf(buf + len, sizeof(buf) - len,
827 " (stalled)");
828 }
829 len += snprintf(buf + len, sizeof(buf) - len, "\n");
830 (void)write(siginfo ? STDERR_FILENO : fileno(ttyout), buf, len);
831 #endif /* SMALL */
832 }
833
834 /*
835 * List words in stringlist, vertically arranged
836 */
837 void
838 list_vertical(sl)
839 StringList *sl;
840 {
841 int i, j, w;
842 int columns, width, lines, items;
843 char *p;
844
845 width = items = 0;
846
847 for (i = 0 ; i < sl->sl_cur ; i++) {
848 w = strlen(sl->sl_str[i]);
849 if (w > width)
850 width = w;
851 }
852 width = (width + 8) &~ 7;
853
854 columns = ttywidth / width;
855 if (columns == 0)
856 columns = 1;
857 lines = (sl->sl_cur + columns - 1) / columns;
858 for (i = 0; i < lines; i++) {
859 for (j = 0; j < columns; j++) {
860 p = sl->sl_str[j * lines + i];
861 if (p)
862 fputs(p, ttyout);
863 if (j * lines + i + lines >= sl->sl_cur) {
864 putc('\n', ttyout);
865 break;
866 }
867 w = strlen(p);
868 while (w < width) {
869 w = (w + 8) &~ 7;
870 (void)putc('\t', ttyout);
871 }
872 }
873 }
874 }
875
876 /*
877 * Update the global ttywidth value, using TIOCGWINSZ.
878 */
879 void
880 setttywidth(a)
881 int a;
882 {
883 struct winsize winsize;
884
885 if (ioctl(fileno(ttyout), TIOCGWINSZ, &winsize) != -1)
886 ttywidth = winsize.ws_col;
887 else
888 ttywidth = 80;
889 }
890
891 /*
892 * Set the SIGALRM interval timer for wait seconds, 0 to disable.
893 */
894 void
895 alarmtimer(wait)
896 int wait;
897 {
898 struct itimerval itv;
899
900 itv.it_value.tv_sec = wait;
901 itv.it_value.tv_usec = 0;
902 itv.it_interval = itv.it_value;
903 setitimer(ITIMER_REAL, &itv, NULL);
904 }
905
906 /*
907 * Setup or cleanup EditLine structures
908 */
909 #ifndef SMALL
910 void
911 controlediting()
912 {
913 if (editing && el == NULL && hist == NULL) {
914 HistEvent ev;
915
916 el = el_init(__progname, stdin, ttyout, stderr);
917 /* init editline */
918 hist = history_init(); /* init the builtin history */
919 history(hist, &ev, H_SETSIZE, 100);/* remember 100 events */
920 el_set(el, EL_HIST, history, hist); /* use history */
921
922 el_set(el, EL_EDITOR, "emacs"); /* default editor is emacs */
923 el_set(el, EL_PROMPT, prompt); /* set the prompt function */
924
925 /* add local file completion, bind to TAB */
926 el_set(el, EL_ADDFN, "ftp-complete",
927 "Context sensitive argument completion",
928 complete);
929 el_set(el, EL_BIND, "^I", "ftp-complete", NULL);
930
931 el_source(el, NULL); /* read ~/.editrc */
932 el_set(el, EL_SIGNAL, 1);
933 } else if (!editing) {
934 if (hist) {
935 history_end(hist);
936 hist = NULL;
937 }
938 if (el) {
939 el_end(el);
940 el = NULL;
941 }
942 }
943 }
944 #endif /* !SMALL */
945
946 /*
947 * Parse the specified socket buffer size.
948 */
949 int
950 getsockbufsize(arg)
951 const char *arg;
952 {
953 char *cp;
954 int val;
955
956 if (!isdigit(arg[0]))
957 return (-1);
958
959 val = strtol(arg, &cp, 10);
960 if (cp != NULL) {
961 if (cp[1] != '\0')
962 return (-1);
963 if (cp[0] == 'k')
964 val *= 1024;
965 if (cp[0] == 'm')
966 val *= 1024 * 1024;
967 }
968
969 if (val < 0)
970 return (-1);
971
972 return (val);
973 }
974
975 /*
976 * Set up socket buffer sizes before a connection is made.
977 */
978 void
979 setupsockbufsize(sock)
980 int sock;
981 {
982 static int sndbuf_default, rcvbuf_default;
983 int len, size;
984
985 /*
986 * Get the default socket buffer sizes if we don't already
987 * have them. It doesn't matter which socket we do this
988 * to, because on the first call no socket buffer sizes
989 * will have been modified, so we are guaranteed to get
990 * the system defaults.
991 */
992 if (sndbuf_default == 0) {
993 len = sizeof(sndbuf_default);
994 if (getsockopt(sock, SOL_SOCKET, SO_SNDBUF, &sndbuf_default,
995 &len) < 0)
996 err(1, "unable to get default sndbuf size");
997 len = sizeof(rcvbuf_default);
998 if (getsockopt(sock, SOL_SOCKET, SO_RCVBUF, &rcvbuf_default,
999 &len) < 0)
1000 err(1, "unable to get default rcvbuf size");
1001
1002 }
1003
1004 size = sndbuf_size ? sndbuf_size : sndbuf_default;
1005 if (setsockopt(sock, SOL_SOCKET, SO_SNDBUF, &size, sizeof(size)) < 0)
1006 warn("unable to set sndbuf size %d", size);
1007
1008 size = rcvbuf_size ? rcvbuf_size : rcvbuf_default;
1009 if (setsockopt(sock, SOL_SOCKET, SO_RCVBUF, &size, sizeof(size)) < 0)
1010 warn("unable to set rcvbuf size %d", size);
1011 }
1012
1013 /*
1014 * If the socket buffer sizes were not set manually (i.e. came from a
1015 * configuration file), reset them so the right thing will happen on
1016 * subsequent connections.
1017 */
1018 void
1019 resetsockbufsize()
1020 {
1021
1022 if (sndbuf_manual == 0)
1023 sndbuf_size = 0;
1024 if (rcvbuf_manual == 0)
1025 rcvbuf_size = 0;
1026 }
1027
1028 /*
1029 * Internal version of connect(2); sets socket buffer sizes first.
1030 */
1031 int
1032 xconnect(sock, name, namelen)
1033 int sock;
1034 const struct sockaddr *name;
1035 int namelen;
1036 {
1037
1038 setupsockbufsize(sock);
1039 return (connect(sock, name, namelen));
1040 }
1041
1042 /*
1043 * Internal version of listen(2); sets socket buffer sizes first.
1044 */
1045 int
1046 xlisten(sock, backlog)
1047 int sock, backlog;
1048 {
1049
1050 setupsockbufsize(sock);
1051 return (listen(sock, backlog));
1052 }
1053