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