util.c revision 1.62 1 /* $NetBSD: util.c,v 1.62 1999/09/26 14:18:01 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.62 1999/09/26 14:18:01 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 (tcgetpgrp(fileno(ttyout)) == pgrp);
638 }
639
640
641 static void updateprogressmeter __P((int));
642
643 static void
644 updateprogressmeter(dummy)
645 int dummy;
646 {
647 int oerrno;
648
649 oerrno = errno;
650 progressmeter(0);
651 errno = oerrno;
652 }
653 #endif /* NO_PROGRESS */
654
655
656 /*
657 * List of order of magnitude prefixes.
658 * The last is `P', as 2^64 = 16384 Petabytes
659 */
660 static const char prefixes[] = " KMGTP";
661
662 /*
663 * Display a transfer progress bar if progress is non-zero.
664 * SIGALRM is hijacked for use by this function.
665 * - Before the transfer, set filesize to size of file (or -1 if unknown),
666 * and call with flag = -1. This starts the once per second timer,
667 * and a call to updateprogressmeter() upon SIGALRM.
668 * - During the transfer, updateprogressmeter will call progressmeter
669 * with flag = 0
670 * - After the transfer, call with flag = 1
671 */
672 static struct timeval start;
673 static struct timeval lastupdate;
674
675 void
676 progressmeter(flag)
677 int flag;
678 {
679 static off_t lastsize;
680 #ifndef NO_PROGRESS
681 struct timeval now, td, wait;
682 off_t cursize, abbrevsize, bytespersec;
683 double elapsed;
684 int ratio, barlength, i, len, remaining;
685
686 /*
687 * Work variables for progress bar.
688 *
689 * XXX: if the format of the progress bar changes
690 * (especially the number of characters in the
691 * `static' portion of it), be sure to update
692 * these appropriately.
693 *
694 * XXX: sprintf() is used because it's more portable,
695 * so `buf' must be big enough to hold the
696 * largest values output.
697 */
698 char buf[256]; /* workspace for progress bar */
699 #define BAROVERHEAD 43 /* non `*' portion of progress bar */
700 /*
701 * stars should contain at least
702 * sizeof(buf) - BAROVERHEAD entries
703 */
704 const char stars[] =
705 "*****************************************************************************"
706 "*****************************************************************************"
707 "*****************************************************************************";
708
709 #endif
710
711 if (flag == -1) {
712 (void)gettimeofday(&start, NULL);
713 lastupdate = start;
714 lastsize = restart_point;
715 }
716 #ifndef NO_PROGRESS
717 len = 0;
718 if (!progress || filesize <= 0)
719 return;
720
721 (void)gettimeofday(&now, NULL);
722 cursize = bytes + restart_point;
723 timersub(&now, &lastupdate, &wait);
724 if (cursize > lastsize) {
725 lastupdate = now;
726 lastsize = cursize;
727 if (wait.tv_sec >= STALLTIME) { /* fudge out stalled time */
728 start.tv_sec += wait.tv_sec;
729 start.tv_usec += wait.tv_usec;
730 }
731 wait.tv_sec = 0;
732 }
733
734 /*
735 * print progress bar only if we are foreground process.
736 */
737 if (! foregroundproc())
738 return;
739
740 ratio = (int)((double)cursize * 100.0 / (double)filesize);
741 ratio = MAX(ratio, 0);
742 ratio = MIN(ratio, 100);
743 len += sprintf(buf + len, "\r%3d%% ", ratio);
744
745 /*
746 * calculate the length of the `*' bar, ensuring that
747 * the number of stars won't exceed the buffer size
748 */
749 barlength = MIN(sizeof(buf) - 1, ttywidth) - BAROVERHEAD;
750 if (barlength > 0) {
751 i = barlength * ratio / 100;
752 len += sprintf(buf + len, "|%.*s%*s|",
753 i, stars, barlength - i, "");
754 }
755
756 abbrevsize = cursize;
757 for (i = 0; abbrevsize >= 100000 && i < sizeof(prefixes); i++)
758 abbrevsize >>= 10;
759 len += sprintf(buf + len,
760 #ifndef NO_QUAD
761 " %5lld %c%c ", (long long)abbrevsize,
762 #else
763 " %5ld %c%c ", (long)abbrevsize,
764 #endif
765 prefixes[i],
766 i == 0 ? ' ' : 'B');
767
768 timersub(&now, &start, &td);
769 elapsed = td.tv_sec + (td.tv_usec / 1000000.0);
770
771 bytespersec = 0;
772 if (bytes > 0) {
773 bytespersec = bytes;
774 if (elapsed > 0.0)
775 bytespersec /= elapsed;
776 }
777 for (i = 1; bytespersec >= 1024000 && i < sizeof(prefixes); i++)
778 bytespersec >>= 10;
779 len += sprintf(buf + len,
780 #ifndef NO_QUAD
781 " %3lld.%02d %cB/s ", (long long)bytespersec / 1024,
782 #else
783 " %3ld.%02d %cB/s ", (long)bytespersec / 1024,
784 #endif
785 (int)((bytespersec % 1024) * 100 / 1024),
786 prefixes[i]);
787
788 if (bytes <= 0 || elapsed <= 0.0 || cursize > filesize) {
789 len += sprintf(buf + len, " --:-- ETA");
790 } else if (wait.tv_sec >= STALLTIME) {
791 len += sprintf(buf + len, " - stalled -");
792 } else {
793 remaining = (int)
794 ((filesize - restart_point) / (bytes / elapsed) - elapsed);
795 if (remaining >= 100 * SECSPERHOUR)
796 len += sprintf(buf + len, " --:-- ETA");
797 else {
798 i = remaining / SECSPERHOUR;
799 if (i)
800 len += sprintf(buf + len, "%2d:", i);
801 else
802 len += sprintf(buf + len, " ");
803 i = remaining % SECSPERHOUR;
804 len += sprintf(buf + len, "%02d:%02d ETA",
805 i / 60, i % 60);
806 }
807 }
808 (void)write(fileno(ttyout), buf, len);
809
810 if (flag == -1) {
811 (void)xsignal(SIGALRM, updateprogressmeter);
812 alarmtimer(1); /* set alarm timer for 1 Hz */
813 } else if (flag == 1) {
814 (void)xsignal(SIGALRM, SIG_DFL);
815 alarmtimer(0);
816 (void)putc('\n', ttyout);
817 }
818 fflush(ttyout);
819 #endif /* !NO_PROGRESS */
820 }
821
822 /*
823 * Display transfer statistics.
824 * Requires start to be initialised by progressmeter(-1),
825 * direction to be defined by xfer routines, and filesize and bytes
826 * to be updated by xfer routines
827 * If siginfo is nonzero, an ETA is displayed, and the output goes to stderr
828 * instead of ttyout.
829 */
830 void
831 ptransfer(siginfo)
832 int siginfo;
833 {
834 struct timeval now, td, wait;
835 double elapsed;
836 off_t bytespersec;
837 int remaining, hh, i, len;
838
839 /*
840 * Work variable for transfer status.
841 *
842 * XXX: sprintf() is used because it's more portable,
843 * so `buf' must be large enough to hold the
844 * largest message length.
845 */
846 char buf[256];
847
848 if (!verbose && !progress && !siginfo)
849 return;
850
851 (void)gettimeofday(&now, NULL);
852 timersub(&now, &start, &td);
853 elapsed = td.tv_sec + (td.tv_usec / 1000000.0);
854 bytespersec = 0;
855 if (bytes > 0) {
856 bytespersec = bytes;
857 if (elapsed > 0.0)
858 bytespersec /= elapsed;
859 }
860 len = 0;
861 len += sprintf(buf + len,
862 #ifndef NO_QUAD
863 "%lld byte%s %s in ", (long long)bytes,
864 #else
865 "%ld byte%s %s in ", (long)bytes,
866 #endif
867 bytes == 1 ? "" : "s", direction);
868 remaining = (int)elapsed;
869 if (remaining > SECSPERDAY) {
870 int days;
871
872 days = remaining / SECSPERDAY;
873 remaining %= SECSPERDAY;
874 len += sprintf(buf + len, "%d day%s ",
875 days, days == 1 ? "" : "s");
876 }
877 hh = remaining / SECSPERHOUR;
878 remaining %= SECSPERHOUR;
879 if (hh)
880 len += sprintf(buf + len, "%2d:", hh);
881 len += sprintf(buf + len, "%02d:%02d ", remaining / 60, remaining % 60);
882
883 for (i = 1; bytespersec >= 1024000 && i < sizeof(prefixes); i++)
884 bytespersec >>= 10;
885 len += sprintf(buf + len,
886 #ifndef NO_QUAD
887 "(%lld.%02d %cB/s)", (long long)bytespersec / 1024,
888 #else
889 "(%ld.%02d %cB/s)", (long)bytespersec / 1024,
890 #endif
891 (int)((bytespersec % 1024) * 100 / 1024),
892 prefixes[i]);
893
894 if (siginfo && bytes > 0 && elapsed > 0.0 && filesize >= 0
895 && bytes + restart_point <= filesize) {
896 remaining = (int)((filesize - restart_point) /
897 (bytes / elapsed) - elapsed);
898 hh = remaining / SECSPERHOUR;
899 remaining %= SECSPERHOUR;
900 len += sprintf(buf + len, " ETA: ");
901 if (hh)
902 len += sprintf(buf + len, "%2d:", hh);
903 len += sprintf(buf + len, "%02d:%02d",
904 remaining / 60, remaining % 60);
905 timersub(&now, &lastupdate, &wait);
906 if (wait.tv_sec >= STALLTIME)
907 len += sprintf(buf + len, " (stalled)");
908 }
909 len += sprintf(buf + len, "\n");
910 (void)write(siginfo ? STDERR_FILENO : fileno(ttyout), buf, len);
911 }
912
913 /*
914 * List words in stringlist, vertically arranged
915 */
916 void
917 list_vertical(sl)
918 StringList *sl;
919 {
920 int i, j, w;
921 int columns, width, lines, items;
922 char *p;
923
924 width = items = 0;
925
926 for (i = 0 ; i < sl->sl_cur ; i++) {
927 w = strlen(sl->sl_str[i]);
928 if (w > width)
929 width = w;
930 }
931 width = (width + 8) &~ 7;
932
933 columns = ttywidth / width;
934 if (columns == 0)
935 columns = 1;
936 lines = (sl->sl_cur + columns - 1) / columns;
937 for (i = 0; i < lines; i++) {
938 for (j = 0; j < columns; j++) {
939 p = sl->sl_str[j * lines + i];
940 if (p)
941 fputs(p, ttyout);
942 if (j * lines + i + lines >= sl->sl_cur) {
943 putc('\n', ttyout);
944 break;
945 }
946 w = strlen(p);
947 while (w < width) {
948 w = (w + 8) &~ 7;
949 (void)putc('\t', ttyout);
950 }
951 }
952 }
953 }
954
955 /*
956 * Update the global ttywidth value, using TIOCGWINSZ.
957 */
958 void
959 setttywidth(a)
960 int a;
961 {
962 struct winsize winsize;
963 int oerrno;
964
965 oerrno = errno;
966 if (ioctl(fileno(ttyout), TIOCGWINSZ, &winsize) != -1 &&
967 winsize.ws_col != 0)
968 ttywidth = winsize.ws_col;
969 else
970 ttywidth = 80;
971 errno = oerrno;
972 }
973
974 void
975 crankrate(int sig)
976 {
977
978 switch (sig) {
979 case SIGUSR1:
980 if (rate_get)
981 rate_get += rate_get_incr;
982 if (rate_put)
983 rate_put += rate_put_incr;
984 break;
985 case SIGUSR2:
986 if (rate_get && rate_get > rate_get_incr)
987 rate_get -= rate_get_incr;
988 if (rate_put && rate_put > rate_put_incr)
989 rate_put -= rate_put_incr;
990 break;
991 default:
992 err(1, "crankrate invoked with unknown signal: %d", sig);
993 }
994 }
995
996
997 /*
998 * Set the SIGALRM interval timer for wait seconds, 0 to disable.
999 */
1000 void
1001 alarmtimer(wait)
1002 int wait;
1003 {
1004 struct itimerval itv;
1005
1006 itv.it_value.tv_sec = wait;
1007 itv.it_value.tv_usec = 0;
1008 itv.it_interval = itv.it_value;
1009 setitimer(ITIMER_REAL, &itv, NULL);
1010 }
1011
1012 /*
1013 * Setup or cleanup EditLine structures
1014 */
1015 #ifndef NO_EDITCOMPLETE
1016 void
1017 controlediting()
1018 {
1019 if (editing && el == NULL && hist == NULL) {
1020 HistEvent ev;
1021 int editmode;
1022
1023 el = el_init(__progname, stdin, ttyout, stderr);
1024 /* init editline */
1025 hist = history_init(); /* init the builtin history */
1026 history(hist, &ev, H_SETSIZE, 100);/* remember 100 events */
1027 el_set(el, EL_HIST, history, hist); /* use history */
1028
1029 el_set(el, EL_EDITOR, "emacs"); /* default editor is emacs */
1030 el_set(el, EL_PROMPT, prompt); /* set the prompt function */
1031
1032 /* add local file completion, bind to TAB */
1033 el_set(el, EL_ADDFN, "ftp-complete",
1034 "Context sensitive argument completion",
1035 complete);
1036 el_set(el, EL_BIND, "^I", "ftp-complete", NULL);
1037 el_source(el, NULL); /* read ~/.editrc */
1038 if ((el_get(el, EL_EDITMODE, &editmode) != -1) && editmode == 0)
1039 editing = 0; /* the user doesn't want editing,
1040 * so disable, and let statement
1041 * below cleanup */
1042 else
1043 el_set(el, EL_SIGNAL, 1);
1044 }
1045 if (!editing) {
1046 if (hist) {
1047 history_end(hist);
1048 hist = NULL;
1049 }
1050 if (el) {
1051 el_end(el);
1052 el = NULL;
1053 }
1054 }
1055 }
1056 #endif /* !NO_EDITCOMPLETE */
1057
1058 /*
1059 * Convert the string `arg' to an int, which may have an optional SI suffix
1060 * (`b', `k', `m', `g'). Returns the number for success, -1 otherwise.
1061 */
1062 int
1063 strsuftoi(arg)
1064 const char *arg;
1065 {
1066 char *cp;
1067 long val;
1068
1069 if (!isdigit((unsigned char)arg[0]))
1070 return (-1);
1071
1072 val = strtol(arg, &cp, 10);
1073 if (cp != NULL) {
1074 if (cp[0] != '\0' && cp[1] != '\0')
1075 return (-1);
1076 switch (tolower((unsigned char)cp[0])) {
1077 case '\0':
1078 case 'b':
1079 break;
1080 case 'k':
1081 val <<= 10;
1082 break;
1083 case 'm':
1084 val <<= 20;
1085 break;
1086 case 'g':
1087 val <<= 30;
1088 break;
1089 default:
1090 return (-1);
1091 }
1092 }
1093 if (val < 0 || val > INT_MAX)
1094 return (-1);
1095
1096 return (val);
1097 }
1098
1099 /*
1100 * Set up socket buffer sizes before a connection is made.
1101 */
1102 void
1103 setupsockbufsize(sock)
1104 int sock;
1105 {
1106
1107 if (setsockopt(sock, SOL_SOCKET, SO_SNDBUF, (void *) &sndbuf_size,
1108 sizeof(rcvbuf_size)) < 0)
1109 warn("unable to set sndbuf size %d", sndbuf_size);
1110
1111 if (setsockopt(sock, SOL_SOCKET, SO_RCVBUF, (void *) &rcvbuf_size,
1112 sizeof(rcvbuf_size)) < 0)
1113 warn("unable to set rcvbuf size %d", rcvbuf_size);
1114 }
1115
1116 void
1117 ftpvis(dst, dstlen, src, srclen)
1118 char *dst;
1119 size_t dstlen;
1120 const char *src;
1121 size_t srclen;
1122 {
1123 int di, si;
1124
1125 for (di = si = 0;
1126 src[si] != '\0' && di < dstlen && si < srclen;
1127 di++, si++) {
1128 switch (src[si]) {
1129 case '\\':
1130 case ' ':
1131 case '\t':
1132 case '\r':
1133 case '\n':
1134 case '"':
1135 dst[di++] = '\\';
1136 if (di >= dstlen)
1137 break;
1138 /* FALLTHROUGH */
1139 default:
1140 dst[di] = src[si];
1141 }
1142 }
1143 dst[di] = '\0';
1144 }
1145
1146 /*
1147 * Determine if given string is an IPv6 address or not.
1148 * Return 1 for yes, 0 for no
1149 */
1150 int
1151 isipv6addr(addr)
1152 const char *addr;
1153 {
1154 int rv = 0;
1155 #ifdef INET6
1156 u_char buf[16]; /* XXX: sizeof(struct in_addr6) */
1157
1158 rv = inet_pton(AF_INET6, addr, &buf);
1159 if (debug)
1160 fprintf(ttyout, "isipv6addr: got %d for %s\n", rv, addr);
1161 #endif
1162 return rv;
1163 }
1164
1165
1166 /*
1167 * Internal version of connect(2); sets socket buffer sizes first.
1168 */
1169 int
1170 xconnect(sock, name, namelen)
1171 int sock;
1172 const struct sockaddr *name;
1173 int namelen;
1174 {
1175
1176 setupsockbufsize(sock);
1177 return (connect(sock, name, namelen));
1178 }
1179
1180 /*
1181 * Internal version of listen(2); sets socket buffer sizes first.
1182 */
1183 int
1184 xlisten(sock, backlog)
1185 int sock, backlog;
1186 {
1187
1188 setupsockbufsize(sock);
1189 return (listen(sock, backlog));
1190 }
1191
1192 void *
1193 xmalloc(size)
1194 size_t size;
1195 {
1196 void *p;
1197
1198 p = malloc(size);
1199 if (p == NULL)
1200 err(1, "Unable to allocate %ld bytes of memory", (long)size);
1201 return (p);
1202 }
1203
1204 char *
1205 xstrdup(str)
1206 const char *str;
1207 {
1208 char *s;
1209
1210 if (str == NULL)
1211 errx(1, "xstrdup() called with NULL argument");
1212 s = strdup(str);
1213 if (s == NULL)
1214 err(1, "Unable to allocate memory for string copy");
1215 return (s);
1216 }
1217
1218 sig_t
1219 xsignal(sig, func)
1220 int sig;
1221 void (*func) __P((int));
1222 {
1223 struct sigaction act, oact;
1224
1225 act.sa_handler = func;
1226 sigemptyset(&act.sa_mask);
1227 act.sa_flags = SA_RESTART;
1228 if (sigaction(sig, &act, &oact) < 0)
1229 return (SIG_ERR);
1230 return (oact.sa_handler);
1231 }
1232