util.c revision 1.61 1 /* $NetBSD: util.c,v 1.61 1999/09/26 02:00:12 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.61 1999/09/26 02:00:12 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 <errno.h>
93 #include <fcntl.h>
94 #include <glob.h>
95 #include <termios.h>
96 #include <signal.h>
97 #include <limits.h>
98 #include <pwd.h>
99 #include <stdio.h>
100 #include <stdlib.h>
101 #include <string.h>
102 #include <time.h>
103 #include <tzfile.h>
104 #include <unistd.h>
105
106 #include "ftp_var.h"
107 #include "pathnames.h"
108
109 /*
110 * Connect to peer server and
111 * auto-login, if possible.
112 */
113 void
114 setpeer(argc, argv)
115 int argc;
116 char *argv[];
117 {
118 char *host;
119 char *port;
120
121 if (connected) {
122 fprintf(ttyout, "Already connected to %s, use close first.\n",
123 hostname);
124 code = -1;
125 return;
126 }
127 if (argc < 2)
128 (void)another(&argc, &argv, "to");
129 if (argc < 2 || argc > 3) {
130 fprintf(ttyout, "usage: %s host-name [port]\n", argv[0]);
131 code = -1;
132 return;
133 }
134 if (gatemode)
135 port = gateport;
136 else
137 port = ftpport;
138 if (argc > 2)
139 port = strdup(argv[2]);
140
141 if (gatemode) {
142 if (gateserver == NULL || *gateserver == '\0')
143 errx(1, "gateserver not defined (shouldn't happen)");
144 host = hookup(gateserver, port);
145 } else
146 host = hookup(argv[1], port);
147
148 if (host) {
149 int overbose;
150
151 if (gatemode && verbose) {
152 fprintf(ttyout,
153 "Connecting via pass-through server %s\n",
154 gateserver);
155 }
156
157 connected = 1;
158 /*
159 * Set up defaults for FTP.
160 */
161 (void)strcpy(typename, "ascii"), type = TYPE_A;
162 curtype = TYPE_A;
163 (void)strcpy(formname, "non-print"), form = FORM_N;
164 (void)strcpy(modename, "stream"), mode = MODE_S;
165 (void)strcpy(structname, "file"), stru = STRU_F;
166 (void)strcpy(bytename, "8"), bytesize = 8;
167 if (autologin)
168 (void)ftp_login(argv[1], NULL, NULL);
169
170 overbose = verbose;
171 if (debug == 0)
172 verbose = -1;
173 if (command("SYST") == COMPLETE && overbose) {
174 char *cp, c;
175 c = 0;
176 cp = strchr(reply_string + 4, ' ');
177 if (cp == NULL)
178 cp = strchr(reply_string + 4, '\r');
179 if (cp) {
180 if (cp[-1] == '.')
181 cp--;
182 c = *cp;
183 *cp = '\0';
184 }
185
186 fprintf(ttyout, "Remote system type is %s.\n",
187 reply_string + 4);
188 if (cp)
189 *cp = c;
190 }
191 if (!strncmp(reply_string, "215 UNIX Type: L8", 17)) {
192 if (proxy)
193 unix_proxy = 1;
194 else
195 unix_server = 1;
196 /*
197 * Set type to 0 (not specified by user),
198 * meaning binary by default, but don't bother
199 * telling server. We can use binary
200 * for text files unless changed by the user.
201 */
202 type = 0;
203 (void)strcpy(typename, "binary");
204 if (overbose)
205 fprintf(ttyout,
206 "Using %s mode to transfer files.\n",
207 typename);
208 } else {
209 if (proxy)
210 unix_proxy = 0;
211 else
212 unix_server = 0;
213 if (overbose &&
214 !strncmp(reply_string, "215 TOPS20", 10))
215 fputs(
216 "Remember to set tenex mode when transferring binary files from this machine.\n",
217 ttyout);
218 }
219 verbose = overbose;
220 }
221 }
222
223 /*
224 * login to remote host, using given username & password if supplied
225 */
226 int
227 ftp_login(host, user, pass)
228 const char *host;
229 const char *user, *pass;
230 {
231 char tmp[80];
232 const char *acct;
233 struct passwd *pw;
234 int n, aflag, rval, freeuser, freepass, freeacct, len;
235
236 acct = NULL;
237 aflag = rval = freeuser = freepass = freeacct = 0;
238
239 /*
240 * Set up arguments for an anonymous FTP session, if necessary.
241 */
242 if (anonftp) {
243 /*
244 * Set up anonymous login password.
245 */
246 if ((pass = getenv("FTPANONPASS")) == NULL) {
247 char *anonpass;
248
249 if ((pass = getlogin()) == NULL) {
250 if ((pw = getpwuid(getuid())) == NULL)
251 pass = "anonymous";
252 else
253 pass = pw->pw_name;
254 }
255 /*
256 * Every anonymous FTP server I've encountered
257 * will accept the string "username@", and will
258 * append the hostname itself. We do this by default
259 * since many servers are picky about not having
260 * a FQDN in the anonymous password.
261 * - thorpej (at) netbsd.org
262 */
263 len = strlen(pass) + 2;
264 anonpass = xmalloc(len);
265 strlcpy(anonpass, pass, len);
266 strlcat(anonpass, "@", len);
267 pass = anonpass;
268 freepass = 1;
269 }
270 user = "anonymous"; /* as per RFC 1635 */
271 }
272
273 if (user == NULL)
274 freeuser = 1;
275 if (pass == NULL)
276 freepass = 1;
277 freeacct = 1;
278 if (ruserpass(host, &user, &pass, &acct) < 0) {
279 code = -1;
280 goto cleanup_ftp_login;
281 }
282
283 while (user == NULL) {
284 const char *myname = getlogin();
285
286 if (myname == NULL && (pw = getpwuid(getuid())) != NULL)
287 myname = pw->pw_name;
288 if (myname)
289 fprintf(ttyout, "Name (%s:%s): ", host, myname);
290 else
291 fprintf(ttyout, "Name (%s): ", host);
292 *tmp = '\0';
293 if (fgets(tmp, sizeof(tmp) - 1, stdin) == NULL) {
294 fprintf(ttyout, "\nEOF received; login aborted.\n");
295 code = -1;
296 goto cleanup_ftp_login;
297 }
298 tmp[strlen(tmp) - 1] = '\0';
299 freeuser = 0;
300 if (*tmp == '\0')
301 user = myname;
302 else
303 user = tmp;
304 }
305
306 if (gatemode) {
307 char *nuser;
308 int len;
309
310 len = strlen(user) + 1 + strlen(host) + 1;
311 nuser = xmalloc(len);
312 strlcpy(nuser, user, len);
313 strlcat(nuser, "@", len);
314 strlcat(nuser, host, len);
315 freeuser = 1;
316 user = nuser;
317 }
318
319 n = command("USER %s", user);
320 if (n == CONTINUE) {
321 if (pass == NULL) {
322 freepass = 0;
323 pass = getpass("Password:");
324 }
325 n = command("PASS %s", pass);
326 }
327 if (n == CONTINUE) {
328 aflag++;
329 if (acct == NULL) {
330 freeacct = 0;
331 acct = getpass("Account:");
332 }
333 if (acct[0] == '\0') {
334 warnx("Login failed.");
335 goto cleanup_ftp_login;
336 }
337 n = command("ACCT %s", acct);
338 }
339 if ((n != COMPLETE) ||
340 (!aflag && acct != NULL && command("ACCT %s", acct) != COMPLETE)) {
341 warnx("Login failed.");
342 goto cleanup_ftp_login;
343 }
344 rval = 1;
345 if (proxy)
346 goto cleanup_ftp_login;
347
348 connected = -1;
349 for (n = 0; n < macnum; ++n) {
350 if (!strcmp("init", macros[n].mac_name)) {
351 (void)strcpy(line, "$init");
352 makeargv();
353 domacro(margc, margv);
354 break;
355 }
356 }
357 cleanup_ftp_login:
358 if (user != NULL && freeuser)
359 free((char *)user);
360 if (pass != NULL && freepass)
361 free((char *)pass);
362 if (acct != NULL && freeacct)
363 free((char *)acct);
364 return (rval);
365 }
366
367 /*
368 * `another' gets another argument, and stores the new argc and argv.
369 * It reverts to the top level (via main.c's intr()) on EOF/error.
370 *
371 * Returns false if no new arguments have been added.
372 */
373 int
374 another(pargc, pargv, prompt)
375 int *pargc;
376 char ***pargv;
377 const char *prompt;
378 {
379 int len = strlen(line), ret;
380
381 if (len >= sizeof(line) - 3) {
382 fputs("sorry, arguments too long.\n", ttyout);
383 intr();
384 }
385 fprintf(ttyout, "(%s) ", prompt);
386 line[len++] = ' ';
387 if (fgets(&line[len], sizeof(line) - len, stdin) == NULL)
388 intr();
389 len += strlen(&line[len]);
390 if (len > 0 && line[len - 1] == '\n')
391 line[len - 1] = '\0';
392 makeargv();
393 ret = margc > *pargc;
394 *pargc = margc;
395 *pargv = margv;
396 return (ret);
397 }
398
399 /*
400 * glob files given in argv[] from the remote server.
401 * if errbuf isn't NULL, store error messages there instead
402 * of writing to the screen.
403 */
404 char *
405 remglob(argv, doswitch, errbuf)
406 char *argv[];
407 int doswitch;
408 char **errbuf;
409 {
410 char temp[MAXPATHLEN];
411 static char buf[MAXPATHLEN];
412 static FILE *ftemp = NULL;
413 static char **args;
414 int oldverbose, oldhash, fd;
415 char *cp, *mode;
416
417 if (!mflag) {
418 if (!doglob)
419 args = NULL;
420 else {
421 if (ftemp) {
422 (void)fclose(ftemp);
423 ftemp = NULL;
424 }
425 }
426 return (NULL);
427 }
428 if (!doglob) {
429 if (args == NULL)
430 args = argv;
431 if ((cp = *++args) == NULL)
432 args = NULL;
433 return (cp);
434 }
435 if (ftemp == NULL) {
436 strlcpy(temp, tmpdir, sizeof(temp));
437 strlcat(temp, "/", sizeof(temp));
438 strlcat(temp, TMPFILE, sizeof(temp));
439 if ((fd = mkstemp(temp)) < 0) {
440 warn("unable to create temporary file %s", temp);
441 return (NULL);
442 }
443 close(fd);
444 oldverbose = verbose;
445 verbose = (errbuf != NULL) ? -1 : 0;
446 oldhash = hash;
447 hash = 0;
448 if (doswitch)
449 pswitch(!proxy);
450 for (mode = "w"; *++argv != NULL; mode = "a")
451 recvrequest("NLST", temp, *argv, mode, 0, 0);
452 if ((code / 100) != COMPLETE) {
453 if (errbuf != NULL)
454 *errbuf = reply_string;
455 }
456 if (doswitch)
457 pswitch(!proxy);
458 verbose = oldverbose;
459 hash = oldhash;
460 ftemp = fopen(temp, "r");
461 (void)unlink(temp);
462 if (ftemp == NULL) {
463 if (errbuf == NULL)
464 fputs(
465 "can't find list of remote files, oops.\n",
466 ttyout);
467 else
468 *errbuf =
469 "can't find list of remote files, oops.";
470 return (NULL);
471 }
472 }
473 if (fgets(buf, sizeof(buf), ftemp) == NULL) {
474 (void)fclose(ftemp);
475 ftemp = NULL;
476 return (NULL);
477 }
478 if ((cp = strchr(buf, '\n')) != NULL)
479 *cp = '\0';
480 return (buf);
481 }
482
483 int
484 confirm(cmd, file)
485 const char *cmd, *file;
486 {
487 char line[BUFSIZ];
488
489 if (!interactive || confirmrest)
490 return (1);
491 fprintf(ttyout, "%s %s? ", cmd, file);
492 (void)fflush(ttyout);
493 if (fgets(line, sizeof(line), stdin) == NULL)
494 return (0);
495 switch (tolower(*line)) {
496 case 'n':
497 return (0);
498 case 'p':
499 interactive = 0;
500 fputs("Interactive mode: off.\n", ttyout);
501 break;
502 case 'a':
503 confirmrest = 1;
504 fprintf(ttyout, "Prompting off for duration of %s.\n",
505 cmd);
506 break;
507 }
508 return (1);
509 }
510
511 /*
512 * Glob a local file name specification with
513 * the expectation of a single return value.
514 * Can't control multiple values being expanded
515 * from the expression, we return only the first.
516 */
517 int
518 globulize(cpp)
519 char **cpp;
520 {
521 glob_t gl;
522 int flags;
523
524 if (!doglob)
525 return (1);
526
527 flags = GLOB_BRACE|GLOB_NOCHECK|GLOB_TILDE;
528 memset(&gl, 0, sizeof(gl));
529 if (glob(*cpp, flags, NULL, &gl) || gl.gl_pathc == 0) {
530 warnx("%s: not found", *cpp);
531 globfree(&gl);
532 return (0);
533 }
534 /* XXX: caller should check if *cpp changed, and
535 * free(*cpp) if that is the case
536 */
537 *cpp = xstrdup(gl.gl_pathv[0]);
538 globfree(&gl);
539 return (1);
540 }
541
542 /*
543 * determine size of remote file
544 */
545 off_t
546 remotesize(file, noisy)
547 const char *file;
548 int noisy;
549 {
550 int overbose;
551 off_t size;
552
553 overbose = verbose;
554 size = -1;
555 if (debug == 0)
556 verbose = -1;
557 if (command("SIZE %s", file) == COMPLETE) {
558 char *cp, *ep;
559
560 cp = strchr(reply_string, ' ');
561 if (cp != NULL) {
562 cp++;
563 #ifndef NO_QUAD
564 size = strtoq(cp, &ep, 10);
565 #else
566 size = strtol(cp, &ep, 10);
567 #endif
568 if (*ep != '\0' && !isspace((unsigned char)*ep))
569 size = -1;
570 }
571 } else if (noisy && debug == 0) {
572 fputs(reply_string, ttyout);
573 putc('\n', ttyout);
574 }
575 verbose = overbose;
576 return (size);
577 }
578
579 /*
580 * determine last modification time (in GMT) of remote file
581 */
582 time_t
583 remotemodtime(file, noisy)
584 const char *file;
585 int noisy;
586 {
587 int overbose;
588 time_t rtime;
589 int ocode;
590
591 overbose = verbose;
592 ocode = code;
593 rtime = -1;
594 if (debug == 0)
595 verbose = -1;
596 if (command("MDTM %s", file) == COMPLETE) {
597 struct tm timebuf;
598 int yy, mo, day, hour, min, sec;
599 sscanf(reply_string, "%*s %04d%02d%02d%02d%02d%02d", &yy, &mo,
600 &day, &hour, &min, &sec);
601 memset(&timebuf, 0, sizeof(timebuf));
602 timebuf.tm_sec = sec;
603 timebuf.tm_min = min;
604 timebuf.tm_hour = hour;
605 timebuf.tm_mday = day;
606 timebuf.tm_mon = mo - 1;
607 timebuf.tm_year = yy - TM_YEAR_BASE;
608 timebuf.tm_isdst = -1;
609 rtime = timegm(&timebuf);
610 if (rtime == -1 && (noisy || debug != 0))
611 fprintf(ttyout, "Can't convert %s to a time.\n",
612 reply_string);
613 } else if (noisy && debug == 0) {
614 fputs(reply_string, ttyout);
615 putc('\n', ttyout);
616 }
617 verbose = overbose;
618 if (rtime == -1)
619 code = ocode;
620 return (rtime);
621 }
622
623 #ifndef NO_PROGRESS
624
625 /*
626 * return non-zero if we're the current foreground process
627 */
628 int
629 foregroundproc()
630 {
631 static pid_t pgrp = -1;
632 int ctty_pgrp;
633
634 if (pgrp == -1)
635 pgrp = getpgrp();
636
637 return ((ioctl(fileno(ttyout), TIOCGPGRP, &ctty_pgrp) != -1 &&
638 ctty_pgrp == (int)pgrp));
639 }
640
641
642 static void updateprogressmeter __P((int));
643
644 static void
645 updateprogressmeter(dummy)
646 int dummy;
647 {
648 int oerrno;
649
650 oerrno = errno;
651 progressmeter(0);
652 errno = oerrno;
653 }
654 #endif /* NO_PROGRESS */
655
656
657 /*
658 * List of order of magnitude prefixes.
659 * The last is `P', as 2^64 = 16384 Petabytes
660 */
661 static const char prefixes[] = " KMGTP";
662
663 /*
664 * Display a transfer progress bar if progress is non-zero.
665 * SIGALRM is hijacked for use by this function.
666 * - Before the transfer, set filesize to size of file (or -1 if unknown),
667 * and call with flag = -1. This starts the once per second timer,
668 * and a call to updateprogressmeter() upon SIGALRM.
669 * - During the transfer, updateprogressmeter will call progressmeter
670 * with flag = 0
671 * - After the transfer, call with flag = 1
672 */
673 static struct timeval start;
674 static struct timeval lastupdate;
675
676 void
677 progressmeter(flag)
678 int flag;
679 {
680 static off_t lastsize;
681 #ifndef NO_PROGRESS
682 struct timeval now, td, wait;
683 off_t cursize, abbrevsize, bytespersec;
684 double elapsed;
685 int ratio, barlength, i, len, remaining;
686
687 /*
688 * Work variables for progress bar.
689 *
690 * XXX: if the format of the progress bar changes
691 * (especially the number of characters in the
692 * `static' portion of it), be sure to update
693 * these appropriately.
694 *
695 * XXX: sprintf() is used because it's more portable,
696 * so `buf' must be big enough to hold the
697 * largest values output.
698 */
699 char buf[256]; /* workspace for progress bar */
700 #define BAROVERHEAD 43 /* non `*' portion of progress bar */
701 /*
702 * stars should contain at least
703 * sizeof(buf) - BAROVERHEAD entries
704 */
705 const char stars[] =
706 "*****************************************************************************"
707 "*****************************************************************************"
708 "*****************************************************************************";
709
710 #endif
711
712 if (flag == -1) {
713 (void)gettimeofday(&start, NULL);
714 lastupdate = start;
715 lastsize = restart_point;
716 }
717 #ifndef NO_PROGRESS
718 len = 0;
719 if (!progress || filesize <= 0)
720 return;
721
722 (void)gettimeofday(&now, NULL);
723 cursize = bytes + restart_point;
724 timersub(&now, &lastupdate, &wait);
725 if (cursize > lastsize) {
726 lastupdate = now;
727 lastsize = cursize;
728 if (wait.tv_sec >= STALLTIME) { /* fudge out stalled time */
729 start.tv_sec += wait.tv_sec;
730 start.tv_usec += wait.tv_usec;
731 }
732 wait.tv_sec = 0;
733 }
734
735 /*
736 * print progress bar only if we are foreground process.
737 */
738 if (! foregroundproc())
739 return;
740
741 ratio = (int)((double)cursize * 100.0 / (double)filesize);
742 ratio = MAX(ratio, 0);
743 ratio = MIN(ratio, 100);
744 len += sprintf(buf + len, "\r%3d%% ", ratio);
745
746 /*
747 * calculate the length of the `*' bar, ensuring that
748 * the number of stars won't exceed the buffer size
749 */
750 barlength = MIN(sizeof(buf) - 1, ttywidth) - BAROVERHEAD;
751 if (barlength > 0) {
752 i = barlength * ratio / 100;
753 len += sprintf(buf + len, "|%.*s%*s|",
754 i, stars, barlength - i, "");
755 }
756
757 abbrevsize = cursize;
758 for (i = 0; abbrevsize >= 100000 && i < sizeof(prefixes); i++)
759 abbrevsize >>= 10;
760 len += sprintf(buf + len,
761 #ifndef NO_QUAD
762 " %5lld %c%c ", (long long)abbrevsize,
763 #else
764 " %5ld %c%c ", (long)abbrevsize,
765 #endif
766 prefixes[i],
767 i == 0 ? ' ' : 'B');
768
769 timersub(&now, &start, &td);
770 elapsed = td.tv_sec + (td.tv_usec / 1000000.0);
771
772 bytespersec = 0;
773 if (bytes > 0) {
774 bytespersec = bytes;
775 if (elapsed > 0.0)
776 bytespersec /= elapsed;
777 }
778 for (i = 1; bytespersec >= 1024000 && i < sizeof(prefixes); i++)
779 bytespersec >>= 10;
780 len += sprintf(buf + len,
781 #ifndef NO_QUAD
782 " %3lld.%02d %cB/s ", (long long)bytespersec / 1024,
783 #else
784 " %3ld.%02d %cB/s ", (long)bytespersec / 1024,
785 #endif
786 (int)((bytespersec % 1024) * 100 / 1024),
787 prefixes[i]);
788
789 if (bytes <= 0 || elapsed <= 0.0 || cursize > filesize) {
790 len += sprintf(buf + len, " --:-- ETA");
791 } else if (wait.tv_sec >= STALLTIME) {
792 len += sprintf(buf + len, " - stalled -");
793 } else {
794 remaining = (int)
795 ((filesize - restart_point) / (bytes / elapsed) - elapsed);
796 if (remaining >= 100 * SECSPERHOUR)
797 len += sprintf(buf + len, " --:-- ETA");
798 else {
799 i = remaining / SECSPERHOUR;
800 if (i)
801 len += sprintf(buf + len, "%2d:", i);
802 else
803 len += sprintf(buf + len, " ");
804 i = remaining % SECSPERHOUR;
805 len += sprintf(buf + len, "%02d:%02d ETA",
806 i / 60, i % 60);
807 }
808 }
809 (void)write(fileno(ttyout), buf, len);
810
811 if (flag == -1) {
812 (void)xsignal(SIGALRM, updateprogressmeter);
813 alarmtimer(1); /* set alarm timer for 1 Hz */
814 } else if (flag == 1) {
815 (void)xsignal(SIGALRM, SIG_DFL);
816 alarmtimer(0);
817 (void)putc('\n', ttyout);
818 }
819 fflush(ttyout);
820 #endif /* !NO_PROGRESS */
821 }
822
823 /*
824 * Display transfer statistics.
825 * Requires start to be initialised by progressmeter(-1),
826 * direction to be defined by xfer routines, and filesize and bytes
827 * to be updated by xfer routines
828 * If siginfo is nonzero, an ETA is displayed, and the output goes to stderr
829 * instead of ttyout.
830 */
831 void
832 ptransfer(siginfo)
833 int siginfo;
834 {
835 struct timeval now, td, wait;
836 double elapsed;
837 off_t bytespersec;
838 int remaining, hh, i, len;
839
840 /*
841 * Work variable for transfer status.
842 *
843 * XXX: sprintf() is used because it's more portable,
844 * so `buf' must be large enough to hold the
845 * largest message length.
846 */
847 char buf[256];
848
849 if (!verbose && !progress && !siginfo)
850 return;
851
852 (void)gettimeofday(&now, NULL);
853 timersub(&now, &start, &td);
854 elapsed = td.tv_sec + (td.tv_usec / 1000000.0);
855 bytespersec = 0;
856 if (bytes > 0) {
857 bytespersec = bytes;
858 if (elapsed > 0.0)
859 bytespersec /= elapsed;
860 }
861 len = 0;
862 len += sprintf(buf + len,
863 #ifndef NO_QUAD
864 "%lld byte%s %s in ", (long long)bytes,
865 #else
866 "%ld byte%s %s in ", (long)bytes,
867 #endif
868 bytes == 1 ? "" : "s", direction);
869 remaining = (int)elapsed;
870 if (remaining > SECSPERDAY) {
871 int days;
872
873 days = remaining / SECSPERDAY;
874 remaining %= SECSPERDAY;
875 len += sprintf(buf + len, "%d day%s ",
876 days, days == 1 ? "" : "s");
877 }
878 hh = remaining / SECSPERHOUR;
879 remaining %= SECSPERHOUR;
880 if (hh)
881 len += sprintf(buf + len, "%2d:", hh);
882 len += sprintf(buf + len, "%02d:%02d ", remaining / 60, remaining % 60);
883
884 for (i = 1; bytespersec >= 1024000 && i < sizeof(prefixes); i++)
885 bytespersec >>= 10;
886 len += sprintf(buf + len,
887 #ifndef NO_QUAD
888 "(%lld.%02d %cB/s)", (long long)bytespersec / 1024,
889 #else
890 "(%ld.%02d %cB/s)", (long)bytespersec / 1024,
891 #endif
892 (int)((bytespersec % 1024) * 100 / 1024),
893 prefixes[i]);
894
895 if (siginfo && bytes > 0 && elapsed > 0.0 && filesize >= 0
896 && bytes + restart_point <= filesize) {
897 remaining = (int)((filesize - restart_point) /
898 (bytes / elapsed) - elapsed);
899 hh = remaining / SECSPERHOUR;
900 remaining %= SECSPERHOUR;
901 len += sprintf(buf + len, " ETA: ");
902 if (hh)
903 len += sprintf(buf + len, "%2d:", hh);
904 len += sprintf(buf + len, "%02d:%02d",
905 remaining / 60, remaining % 60);
906 timersub(&now, &lastupdate, &wait);
907 if (wait.tv_sec >= STALLTIME)
908 len += sprintf(buf + len, " (stalled)");
909 }
910 len += sprintf(buf + len, "\n");
911 (void)write(siginfo ? STDERR_FILENO : fileno(ttyout), buf, len);
912 }
913
914 /*
915 * List words in stringlist, vertically arranged
916 */
917 void
918 list_vertical(sl)
919 StringList *sl;
920 {
921 int i, j, w;
922 int columns, width, lines, items;
923 char *p;
924
925 width = items = 0;
926
927 for (i = 0 ; i < sl->sl_cur ; i++) {
928 w = strlen(sl->sl_str[i]);
929 if (w > width)
930 width = w;
931 }
932 width = (width + 8) &~ 7;
933
934 columns = ttywidth / width;
935 if (columns == 0)
936 columns = 1;
937 lines = (sl->sl_cur + columns - 1) / columns;
938 for (i = 0; i < lines; i++) {
939 for (j = 0; j < columns; j++) {
940 p = sl->sl_str[j * lines + i];
941 if (p)
942 fputs(p, ttyout);
943 if (j * lines + i + lines >= sl->sl_cur) {
944 putc('\n', ttyout);
945 break;
946 }
947 w = strlen(p);
948 while (w < width) {
949 w = (w + 8) &~ 7;
950 (void)putc('\t', ttyout);
951 }
952 }
953 }
954 }
955
956 /*
957 * Update the global ttywidth value, using TIOCGWINSZ.
958 */
959 void
960 setttywidth(a)
961 int a;
962 {
963 struct winsize winsize;
964 int oerrno;
965
966 oerrno = errno;
967 if (ioctl(fileno(ttyout), TIOCGWINSZ, &winsize) != -1 &&
968 winsize.ws_col != 0)
969 ttywidth = winsize.ws_col;
970 else
971 ttywidth = 80;
972 errno = oerrno;
973 }
974
975 void
976 crankrate(int sig)
977 {
978
979 switch (sig) {
980 case SIGUSR1:
981 if (rate_get)
982 rate_get += rate_get_incr;
983 if (rate_put)
984 rate_put += rate_put_incr;
985 break;
986 case SIGUSR2:
987 if (rate_get && rate_get > rate_get_incr)
988 rate_get -= rate_get_incr;
989 if (rate_put && rate_put > rate_put_incr)
990 rate_put -= rate_put_incr;
991 break;
992 default:
993 err(1, "crankrate invoked with unknown signal: %d", sig);
994 }
995 }
996
997
998 /*
999 * Set the SIGALRM interval timer for wait seconds, 0 to disable.
1000 */
1001 void
1002 alarmtimer(wait)
1003 int wait;
1004 {
1005 struct itimerval itv;
1006
1007 itv.it_value.tv_sec = wait;
1008 itv.it_value.tv_usec = 0;
1009 itv.it_interval = itv.it_value;
1010 setitimer(ITIMER_REAL, &itv, NULL);
1011 }
1012
1013 /*
1014 * Setup or cleanup EditLine structures
1015 */
1016 #ifndef NO_EDITCOMPLETE
1017 void
1018 controlediting()
1019 {
1020 if (editing && el == NULL && hist == NULL) {
1021 HistEvent ev;
1022 int editmode;
1023
1024 el = el_init(__progname, stdin, ttyout, stderr);
1025 /* init editline */
1026 hist = history_init(); /* init the builtin history */
1027 history(hist, &ev, H_SETSIZE, 100);/* remember 100 events */
1028 el_set(el, EL_HIST, history, hist); /* use history */
1029
1030 el_set(el, EL_EDITOR, "emacs"); /* default editor is emacs */
1031 el_set(el, EL_PROMPT, prompt); /* set the prompt function */
1032
1033 /* add local file completion, bind to TAB */
1034 el_set(el, EL_ADDFN, "ftp-complete",
1035 "Context sensitive argument completion",
1036 complete);
1037 el_set(el, EL_BIND, "^I", "ftp-complete", NULL);
1038 el_source(el, NULL); /* read ~/.editrc */
1039 if ((el_get(el, EL_EDITMODE, &editmode) != -1) && editmode == 0)
1040 editing = 0; /* the user doesn't want editing,
1041 * so disable, and let statement
1042 * below cleanup */
1043 else
1044 el_set(el, EL_SIGNAL, 1);
1045 }
1046 if (!editing) {
1047 if (hist) {
1048 history_end(hist);
1049 hist = NULL;
1050 }
1051 if (el) {
1052 el_end(el);
1053 el = NULL;
1054 }
1055 }
1056 }
1057 #endif /* !NO_EDITCOMPLETE */
1058
1059 /*
1060 * Convert the string `arg' to an int, which may have an optional SI suffix
1061 * (`b', `k', `m', `g'). Returns the number for success, -1 otherwise.
1062 */
1063 int
1064 strsuftoi(arg)
1065 const char *arg;
1066 {
1067 char *cp;
1068 long val;
1069
1070 if (!isdigit((unsigned char)arg[0]))
1071 return (-1);
1072
1073 val = strtol(arg, &cp, 10);
1074 if (cp != NULL) {
1075 if (cp[0] != '\0' && cp[1] != '\0')
1076 return (-1);
1077 switch (tolower((unsigned char)cp[0])) {
1078 case '\0':
1079 case 'b':
1080 break;
1081 case 'k':
1082 val <<= 10;
1083 break;
1084 case 'm':
1085 val <<= 20;
1086 break;
1087 case 'g':
1088 val <<= 30;
1089 break;
1090 default:
1091 return (-1);
1092 }
1093 }
1094 if (val < 0 || val > INT_MAX)
1095 return (-1);
1096
1097 return (val);
1098 }
1099
1100 /*
1101 * Set up socket buffer sizes before a connection is made.
1102 */
1103 void
1104 setupsockbufsize(sock)
1105 int sock;
1106 {
1107
1108 if (setsockopt(sock, SOL_SOCKET, SO_SNDBUF, (void *) &sndbuf_size,
1109 sizeof(rcvbuf_size)) < 0)
1110 warn("unable to set sndbuf size %d", sndbuf_size);
1111
1112 if (setsockopt(sock, SOL_SOCKET, SO_RCVBUF, (void *) &rcvbuf_size,
1113 sizeof(rcvbuf_size)) < 0)
1114 warn("unable to set rcvbuf size %d", rcvbuf_size);
1115 }
1116
1117 void
1118 ftpvis(dst, dstlen, src, srclen)
1119 char *dst;
1120 size_t dstlen;
1121 const char *src;
1122 size_t srclen;
1123 {
1124 int di, si;
1125
1126 for (di = si = 0;
1127 src[si] != '\0' && di < dstlen && si < srclen;
1128 di++, si++) {
1129 switch (src[si]) {
1130 case '\\':
1131 case ' ':
1132 case '\t':
1133 case '\r':
1134 case '\n':
1135 case '"':
1136 dst[di++] = '\\';
1137 if (di >= dstlen)
1138 break;
1139 /* FALLTHROUGH */
1140 default:
1141 dst[di] = src[si];
1142 }
1143 }
1144 dst[di] = '\0';
1145 }
1146
1147 /*
1148 * Determine if given string is an IPv6 address or not.
1149 * Return 1 for yes, 0 for no
1150 */
1151 int
1152 isipv6addr(addr)
1153 const char *addr;
1154 {
1155 int rv = 0;
1156 #ifdef INET6
1157 u_char buf[16]; /* XXX: sizeof(struct in_addr6) */
1158
1159 rv = inet_pton(AF_INET6, addr, &buf);
1160 if (debug)
1161 fprintf(ttyout, "isipv6addr: got %d for %s\n", rv, addr);
1162 #endif
1163 return rv;
1164 }
1165
1166
1167 /*
1168 * Internal version of connect(2); sets socket buffer sizes first.
1169 */
1170 int
1171 xconnect(sock, name, namelen)
1172 int sock;
1173 const struct sockaddr *name;
1174 int namelen;
1175 {
1176
1177 setupsockbufsize(sock);
1178 return (connect(sock, name, namelen));
1179 }
1180
1181 /*
1182 * Internal version of listen(2); sets socket buffer sizes first.
1183 */
1184 int
1185 xlisten(sock, backlog)
1186 int sock, backlog;
1187 {
1188
1189 setupsockbufsize(sock);
1190 return (listen(sock, backlog));
1191 }
1192
1193 void *
1194 xmalloc(size)
1195 size_t size;
1196 {
1197 void *p;
1198
1199 p = malloc(size);
1200 if (p == NULL)
1201 err(1, "Unable to allocate %ld bytes of memory", (long)size);
1202 return (p);
1203 }
1204
1205 char *
1206 xstrdup(str)
1207 const char *str;
1208 {
1209 char *s;
1210
1211 if (str == NULL)
1212 errx(1, "xstrdup() called with NULL argument");
1213 s = strdup(str);
1214 if (s == NULL)
1215 err(1, "Unable to allocate memory for string copy");
1216 return (s);
1217 }
1218
1219 sig_t
1220 xsignal(sig, func)
1221 int sig;
1222 void (*func) __P((int));
1223 {
1224 struct sigaction act, oact;
1225
1226 act.sa_handler = func;
1227 sigemptyset(&act.sa_mask);
1228 act.sa_flags = SA_RESTART;
1229 if (sigaction(sig, &act, &oact) < 0)
1230 return (SIG_ERR);
1231 return (oact.sa_handler);
1232 }
1233