util.c revision 1.32 1 /* $NetBSD: util.c,v 1.32 1998/08/08 05:06:56 lukem Exp $ */
2
3 /*-
4 * Copyright (c) 1998 The NetBSD Foundation, Inc.
5 * All rights reserved.
6 *
7 * This code is derived from software contributed to The NetBSD Foundation
8 * by Jason R. Thorpe of the Numerical Aerospace Simulation Facility,
9 * NASA Ames Research Center.
10 *
11 * Redistribution and use in source and binary forms, with or without
12 * modification, are permitted provided that the following conditions
13 * are met:
14 * 1. Redistributions of source code must retain the above copyright
15 * notice, this list of conditions and the following disclaimer.
16 * 2. Redistributions in binary form must reproduce the above copyright
17 * notice, this list of conditions and the following disclaimer in the
18 * documentation and/or other materials provided with the distribution.
19 * 3. All advertising materials mentioning features or use of this software
20 * must display the following acknowledgement:
21 * This product includes software developed by the NetBSD
22 * Foundation, Inc. and its contributors.
23 * 4. Neither the name of The NetBSD Foundation nor the names of its
24 * contributors may be used to endorse or promote products derived
25 * from this software without specific prior written permission.
26 *
27 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
28 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
29 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
30 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
31 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
32 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
33 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
34 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
35 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
36 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
37 * POSSIBILITY OF SUCH DAMAGE.
38 */
39
40 /*
41 * Copyright (c) 1985, 1989, 1993, 1994
42 * The Regents of the University of California. All rights reserved.
43 *
44 * Redistribution and use in source and binary forms, with or without
45 * modification, are permitted provided that the following conditions
46 * are met:
47 * 1. Redistributions of source code must retain the above copyright
48 * notice, this list of conditions and the following disclaimer.
49 * 2. Redistributions in binary form must reproduce the above copyright
50 * notice, this list of conditions and the following disclaimer in the
51 * documentation and/or other materials provided with the distribution.
52 * 3. All advertising materials mentioning features or use of this software
53 * must display the following acknowledgement:
54 * This product includes software developed by the University of
55 * California, Berkeley and its contributors.
56 * 4. Neither the name of the University nor the names of its contributors
57 * may be used to endorse or promote products derived from this software
58 * without specific prior written permission.
59 *
60 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
61 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
62 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
63 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
64 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
65 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
66 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
67 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
68 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
69 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
70 * SUCH DAMAGE.
71 */
72
73 #include <sys/cdefs.h>
74 #ifndef lint
75 __RCSID("$NetBSD: util.c,v 1.32 1998/08/08 05:06:56 lukem Exp $");
76 #endif /* not lint */
77
78 /*
79 * FTP User Program -- Misc support routines
80 */
81 #include <sys/types.h>
82 #include <sys/socket.h>
83 #include <sys/ioctl.h>
84 #include <sys/time.h>
85 #include <arpa/ftp.h>
86
87 #include <ctype.h>
88 #include <err.h>
89 #include <fcntl.h>
90 #include <glob.h>
91 #include <termios.h>
92 #include <signal.h>
93 #include <limits.h>
94 #include <pwd.h>
95 #include <stdio.h>
96 #include <stdlib.h>
97 #include <string.h>
98 #include <time.h>
99 #include <tzfile.h>
100 #include <unistd.h>
101
102 #include "ftp_var.h"
103 #include "pathnames.h"
104
105 /*
106 * Connect to peer server and
107 * auto-login, if possible.
108 */
109 void
110 setpeer(argc, argv)
111 int argc;
112 char *argv[];
113 {
114 char *host;
115 in_port_t port;
116
117 if (connected) {
118 fprintf(ttyout, "Already connected to %s, use close first.\n",
119 hostname);
120 code = -1;
121 return;
122 }
123 if (argc < 2)
124 (void)another(&argc, &argv, "to");
125 if (argc < 2 || argc > 3) {
126 fprintf(ttyout, "usage: %s host-name [port]\n", argv[0]);
127 code = -1;
128 return;
129 }
130 if (gatemode)
131 port = gateport;
132 else
133 port = ftpport;
134 if (argc > 2) {
135 char *ep;
136 long nport;
137
138 nport = strtol(argv[2], &ep, 10);
139 if (nport < 1 || nport > MAX_IN_PORT_T || *ep != '\0') {
140 fprintf(ttyout, "%s: bad port number '%s'.\n",
141 argv[1], argv[2]);
142 fprintf(ttyout, "usage: %s host-name [port]\n",
143 argv[0]);
144 code = -1;
145 return;
146 }
147 port = htons((in_port_t)nport);
148 }
149
150 if (gatemode) {
151 if (gateserver == NULL || *gateserver == '\0')
152 errx(1, "gateserver not defined (shouldn't happen)");
153 host = hookup(gateserver, port);
154 } else
155 host = hookup(argv[1], port);
156
157 if (host) {
158 int overbose;
159
160 if (gatemode) {
161 if (command("PASSERVE %s", argv[1]) != COMPLETE)
162 return;
163 if (verbose)
164 fprintf(ttyout,
165 "Connected via pass-through server %s\n",
166 gateserver);
167 }
168
169 connected = 1;
170 /*
171 * Set up defaults for FTP.
172 */
173 (void)strcpy(typename, "ascii"), type = TYPE_A;
174 curtype = TYPE_A;
175 (void)strcpy(formname, "non-print"), form = FORM_N;
176 (void)strcpy(modename, "stream"), mode = MODE_S;
177 (void)strcpy(structname, "file"), stru = STRU_F;
178 (void)strcpy(bytename, "8"), bytesize = 8;
179 if (autologin)
180 (void)ftp_login(argv[1], NULL, NULL);
181
182 overbose = verbose;
183 if (debug == 0)
184 verbose = -1;
185 if (command("SYST") == COMPLETE && overbose) {
186 char *cp, c;
187 c = 0;
188 cp = strchr(reply_string + 4, ' ');
189 if (cp == NULL)
190 cp = strchr(reply_string + 4, '\r');
191 if (cp) {
192 if (cp[-1] == '.')
193 cp--;
194 c = *cp;
195 *cp = '\0';
196 }
197
198 fprintf(ttyout, "Remote system type is %s.\n",
199 reply_string + 4);
200 if (cp)
201 *cp = c;
202 }
203 if (!strncmp(reply_string, "215 UNIX Type: L8", 17)) {
204 if (proxy)
205 unix_proxy = 1;
206 else
207 unix_server = 1;
208 /*
209 * Set type to 0 (not specified by user),
210 * meaning binary by default, but don't bother
211 * telling server. We can use binary
212 * for text files unless changed by the user.
213 */
214 type = 0;
215 (void)strcpy(typename, "binary");
216 if (overbose)
217 fprintf(ttyout,
218 "Using %s mode to transfer files.\n",
219 typename);
220 } else {
221 if (proxy)
222 unix_proxy = 0;
223 else
224 unix_server = 0;
225 if (overbose &&
226 !strncmp(reply_string, "215 TOPS20", 10))
227 fputs(
228 "Remember to set tenex mode when transferring binary files from this machine.\n",
229 ttyout);
230 }
231 verbose = overbose;
232 }
233 }
234
235 /*
236 * login to remote host, using given username & password if supplied
237 */
238 int
239 ftp_login(host, user, pass)
240 const char *host;
241 const char *user, *pass;
242 {
243 char tmp[80];
244 const char *acct;
245 char anonpass[MAXLOGNAME + 2]; /* "user@" */
246 struct passwd *pw;
247 int n, aflag = 0;
248
249 acct = NULL;
250 if (user == NULL) {
251 if (ruserpass(host, &user, &pass, &acct) < 0) {
252 code = -1;
253 return (0);
254 }
255 }
256
257 /*
258 * Set up arguments for an anonymous FTP session, if necessary.
259 */
260 if ((user == NULL || pass == NULL) && anonftp) {
261 memset(anonpass, 0, sizeof(anonpass));
262
263 /*
264 * Set up anonymous login password.
265 */
266 if ((pass = getenv("FTPANONPASS")) == NULL) {
267 if ((pass = getlogin()) == NULL) {
268 if ((pw = getpwuid(getuid())) == NULL)
269 pass = "anonymous";
270 else
271 pass = pw->pw_name;
272 }
273 /*
274 * Every anonymous FTP server I've encountered
275 * will accept the string "username@", and will
276 * append the hostname itself. We do this by default
277 * since many servers are picky about not having
278 * a FQDN in the anonymous password.
279 * - thorpej (at) netbsd.org
280 */
281 snprintf(anonpass, sizeof(anonpass) - 1, "%s@", pass);
282 pass = anonpass;
283 }
284 user = "anonymous"; /* as per RFC 1635 */
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 (void)fgets(tmp, sizeof(tmp) - 1, stdin);
298 tmp[strlen(tmp) - 1] = '\0';
299 if (*tmp == '\0')
300 user = myname;
301 else
302 user = tmp;
303 }
304 n = command("USER %s", user);
305 if (n == CONTINUE) {
306 if (pass == NULL)
307 pass = getpass("Password:");
308 n = command("PASS %s", pass);
309 }
310 if (n == CONTINUE) {
311 aflag++;
312 if (acct == NULL)
313 acct = getpass("Account:");
314 n = command("ACCT %s", acct);
315 }
316 if ((n != COMPLETE) ||
317 (!aflag && acct != NULL && command("ACCT %s", acct) != COMPLETE)) {
318 warnx("Login failed.");
319 return (0);
320 }
321 if (proxy)
322 return (1);
323 connected = -1;
324 for (n = 0; n < macnum; ++n) {
325 if (!strcmp("init", macros[n].mac_name)) {
326 (void)strcpy(line, "$init");
327 makeargv();
328 domacro(margc, margv);
329 break;
330 }
331 }
332 return (1);
333 }
334
335 /*
336 * `another' gets another argument, and stores the new argc and argv.
337 * It reverts to the top level (via main.c's intr()) on EOF/error.
338 *
339 * Returns false if no new arguments have been added.
340 */
341 int
342 another(pargc, pargv, prompt)
343 int *pargc;
344 char ***pargv;
345 const char *prompt;
346 {
347 int len = strlen(line), ret;
348
349 if (len >= sizeof(line) - 3) {
350 fputs("sorry, arguments too long.\n", ttyout);
351 intr();
352 }
353 fprintf(ttyout, "(%s) ", prompt);
354 line[len++] = ' ';
355 if (fgets(&line[len], sizeof(line) - len, stdin) == NULL)
356 intr();
357 len += strlen(&line[len]);
358 if (len > 0 && line[len - 1] == '\n')
359 line[len - 1] = '\0';
360 makeargv();
361 ret = margc > *pargc;
362 *pargc = margc;
363 *pargv = margv;
364 return (ret);
365 }
366
367 /*
368 * glob files given in argv[] from the remote server.
369 * if errbuf isn't NULL, store error messages there instead
370 * of writing to the screen.
371 */
372 char *
373 remglob(argv, doswitch, errbuf)
374 char *argv[];
375 int doswitch;
376 char **errbuf;
377 {
378 char temp[MAXPATHLEN];
379 static char buf[MAXPATHLEN];
380 static FILE *ftemp = NULL;
381 static char **args;
382 int oldverbose, oldhash, fd;
383 char *cp, *mode;
384
385 if (!mflag) {
386 if (!doglob)
387 args = NULL;
388 else {
389 if (ftemp) {
390 (void)fclose(ftemp);
391 ftemp = NULL;
392 }
393 }
394 return (NULL);
395 }
396 if (!doglob) {
397 if (args == NULL)
398 args = argv;
399 if ((cp = *++args) == NULL)
400 args = NULL;
401 return (cp);
402 }
403 if (ftemp == NULL) {
404 (void)snprintf(temp, sizeof(temp), "%s/%s", tmpdir, TMPFILE);
405 if ((fd = mkstemp(temp)) < 0) {
406 warn("unable to create temporary file %s", temp);
407 return (NULL);
408 }
409 close(fd);
410 oldverbose = verbose;
411 verbose = (errbuf != NULL) ? -1 : 0;
412 oldhash = hash;
413 hash = 0;
414 if (doswitch)
415 pswitch(!proxy);
416 for (mode = "w"; *++argv != NULL; mode = "a")
417 recvrequest("NLST", temp, *argv, mode, 0, 0);
418 if ((code / 100) != COMPLETE) {
419 if (errbuf != NULL)
420 *errbuf = reply_string;
421 }
422 if (doswitch)
423 pswitch(!proxy);
424 verbose = oldverbose;
425 hash = oldhash;
426 ftemp = fopen(temp, "r");
427 (void)unlink(temp);
428 if (ftemp == NULL) {
429 if (errbuf == NULL)
430 fputs(
431 "can't find list of remote files, oops.\n",
432 ttyout);
433 else
434 *errbuf =
435 "can't find list of remote files, oops.";
436 return (NULL);
437 }
438 }
439 if (fgets(buf, sizeof(buf), ftemp) == NULL) {
440 (void)fclose(ftemp);
441 ftemp = NULL;
442 return (NULL);
443 }
444 if ((cp = strchr(buf, '\n')) != NULL)
445 *cp = '\0';
446 return (buf);
447 }
448
449 int
450 confirm(cmd, file)
451 const char *cmd, *file;
452 {
453 char line[BUFSIZ];
454
455 if (!interactive || confirmrest)
456 return (1);
457 fprintf(ttyout, "%s %s? ", cmd, file);
458 (void)fflush(ttyout);
459 if (fgets(line, sizeof(line), stdin) == NULL)
460 return (0);
461 switch (tolower(*line)) {
462 case 'n':
463 return (0);
464 case 'p':
465 interactive = 0;
466 fputs("Interactive mode: off.\n", ttyout);
467 break;
468 case 'a':
469 confirmrest = 1;
470 fprintf(ttyout, "Prompting off for duration of %s.\n",
471 cmd);
472 break;
473 }
474 return (1);
475 }
476
477 /*
478 * Glob a local file name specification with
479 * the expectation of a single return value.
480 * Can't control multiple values being expanded
481 * from the expression, we return only the first.
482 */
483 int
484 globulize(cpp)
485 char **cpp;
486 {
487 glob_t gl;
488 int flags;
489
490 if (!doglob)
491 return (1);
492
493 flags = GLOB_BRACE|GLOB_NOCHECK|GLOB_TILDE;
494 memset(&gl, 0, sizeof(gl));
495 if (glob(*cpp, flags, NULL, &gl) ||
496 gl.gl_pathc == 0) {
497 warnx("%s: not found", *cpp);
498 globfree(&gl);
499 return (0);
500 }
501 /* XXX: caller should check if *cpp changed, and
502 * free(*cpp) if that is the case
503 */
504 *cpp = xstrdup(gl.gl_pathv[0]);
505 globfree(&gl);
506 return (1);
507 }
508
509 /*
510 * determine size of remote file
511 */
512 off_t
513 remotesize(file, noisy)
514 const char *file;
515 int noisy;
516 {
517 int overbose;
518 off_t size;
519
520 overbose = verbose;
521 size = -1;
522 if (debug == 0)
523 verbose = -1;
524 if (command("SIZE %s", file) == COMPLETE) {
525 char *cp, *ep;
526
527 cp = strchr(reply_string, ' ');
528 if (cp != NULL) {
529 cp++;
530 #ifndef NO_QUAD
531 size = strtoq(cp, &ep, 10);
532 #else
533 size = strtol(cp, &ep, 10);
534 #endif
535 if (*ep != '\0' && !isspace((unsigned char)*ep))
536 size = -1;
537 }
538 } else if (noisy && debug == 0) {
539 fputs(reply_string, ttyout);
540 putc('\n', ttyout);
541 }
542 verbose = overbose;
543 return (size);
544 }
545
546 /*
547 * determine last modification time (in GMT) of remote file
548 */
549 time_t
550 remotemodtime(file, noisy)
551 const char *file;
552 int noisy;
553 {
554 int overbose;
555 time_t rtime;
556 int ocode;
557
558 overbose = verbose;
559 ocode = code;
560 rtime = -1;
561 if (debug == 0)
562 verbose = -1;
563 if (command("MDTM %s", file) == COMPLETE) {
564 struct tm timebuf;
565 int yy, mo, day, hour, min, sec;
566 sscanf(reply_string, "%*s %04d%02d%02d%02d%02d%02d", &yy, &mo,
567 &day, &hour, &min, &sec);
568 memset(&timebuf, 0, sizeof(timebuf));
569 timebuf.tm_sec = sec;
570 timebuf.tm_min = min;
571 timebuf.tm_hour = hour;
572 timebuf.tm_mday = day;
573 timebuf.tm_mon = mo - 1;
574 timebuf.tm_year = yy - TM_YEAR_BASE;
575 timebuf.tm_isdst = -1;
576 rtime = mktime(&timebuf);
577 if (rtime == -1 && (noisy || debug != 0))
578 fprintf(ttyout, "Can't convert %s to a time.\n",
579 reply_string);
580 else
581 #ifndef __SVR4
582 rtime += timebuf.tm_gmtoff; /* conv. local -> GMT */
583 #else
584 rtime -= timezone;
585 #endif
586 } else if (noisy && debug == 0) {
587 fputs(reply_string, ttyout);
588 putc('\n', ttyout);
589 }
590 verbose = overbose;
591 if (rtime == -1)
592 code = ocode;
593 return (rtime);
594 }
595
596 #ifndef SMALL
597
598 /*
599 * return non-zero if we're the current foreground process
600 */
601 int
602 foregroundproc()
603 {
604 static pid_t pgrp = -1;
605 int ctty_pgrp;
606
607 if (pgrp == -1)
608 pgrp = getpgrp();
609
610 return ((ioctl(fileno(ttyout), TIOCGPGRP, &ctty_pgrp) != -1 &&
611 ctty_pgrp == (int)pgrp));
612 }
613
614
615 static void updateprogressmeter __P((int));
616
617 static void
618 updateprogressmeter(dummy)
619 int dummy;
620 {
621
622 /*
623 * print progress bar only if we are foreground process.
624 */
625 if (foregroundproc())
626 progressmeter(0);
627 }
628 #endif /* SMALL */
629
630 /*
631 * Display a transfer progress bar if progress is non-zero.
632 * SIGALRM is hijacked for use by this function.
633 * - Before the transfer, set filesize to size of file (or -1 if unknown),
634 * and call with flag = -1. This starts the once per second timer,
635 * and a call to updateprogressmeter() upon SIGALRM.
636 * - During the transfer, updateprogressmeter will call progressmeter
637 * with flag = 0
638 * - After the transfer, call with flag = 1
639 */
640 static struct timeval start;
641 static struct timeval lastupdate;
642
643 void
644 progressmeter(flag)
645 int flag;
646 {
647 #ifndef SMALL
648 /*
649 * List of order of magnitude prefixes.
650 * The last is `P', as 2^64 = 16384 Petabytes
651 */
652 static const char prefixes[] = " KMGTP";
653
654 static off_t lastsize;
655 struct timeval now, td, wait;
656 off_t cursize, abbrevsize;
657 double elapsed;
658 int ratio, barlength, i, len, remaining;
659 char buf[256];
660
661 len = 0;
662
663 if (flag == -1) {
664 (void)gettimeofday(&start, NULL);
665 lastupdate = start;
666 lastsize = restart_point;
667 }
668 (void)gettimeofday(&now, NULL);
669 if (!progress || filesize <= 0)
670 return;
671 cursize = bytes + restart_point;
672
673 ratio = cursize * 100 / filesize;
674 ratio = MAX(ratio, 0);
675 ratio = MIN(ratio, 100);
676 len += snprintf(buf + len, sizeof(buf) - len, "\r%3d%% ", ratio);
677
678 barlength = ttywidth - 30;
679 if (barlength > 0) {
680 i = barlength * ratio / 100;
681 len += snprintf(buf + len, sizeof(buf) - len,
682 "|%.*s%*s|", i,
683 "*****************************************************************************"
684 "*****************************************************************************",
685 barlength - i, "");
686 }
687
688 i = 0;
689 abbrevsize = cursize;
690 while (abbrevsize >= 100000 && i < sizeof(prefixes)) {
691 i++;
692 abbrevsize >>= 10;
693 }
694 len += snprintf(buf + len, sizeof(buf) - len,
695 #ifndef NO_QUAD
696 " %5qd %c%c ", (long long)abbrevsize,
697 #else
698 " %5ld %c%c ", (long)abbrevsize,
699 #endif
700 prefixes[i], prefixes[i] == ' ' ? ' ' : 'B');
701
702 timersub(&now, &lastupdate, &wait);
703 if (cursize > lastsize) {
704 lastupdate = now;
705 lastsize = cursize;
706 if (wait.tv_sec >= STALLTIME) { /* fudge out stalled time */
707 start.tv_sec += wait.tv_sec;
708 start.tv_usec += wait.tv_usec;
709 }
710 wait.tv_sec = 0;
711 }
712
713 timersub(&now, &start, &td);
714 elapsed = td.tv_sec + (td.tv_usec / 1000000.0);
715
716 if (bytes <= 0 || elapsed <= 0.0 || cursize > filesize) {
717 len += snprintf(buf + len, sizeof(buf) - len,
718 " --:-- ETA");
719 } else if (wait.tv_sec >= STALLTIME) {
720 len += snprintf(buf + len, sizeof(buf) - len,
721 " - stalled -");
722 } else {
723 remaining = (int)
724 ((filesize - restart_point) / (bytes / elapsed) - elapsed);
725 if (remaining >= 100 * SECSPERHOUR)
726 len += snprintf(buf + len, sizeof(buf) - len,
727 " --:-- ETA");
728 else {
729 i = remaining / SECSPERHOUR;
730 if (i)
731 len += snprintf(buf + len, sizeof(buf) - len,
732 "%2d:", i);
733 else
734 len += snprintf(buf + len, sizeof(buf) - len,
735 " ");
736 i = remaining % SECSPERHOUR;
737 len += snprintf(buf + len, sizeof(buf) - len,
738 "%02d:%02d ETA", i / 60, i % 60);
739 }
740 }
741 (void)write(fileno(ttyout), buf, len);
742
743 if (flag == -1) {
744 (void)signal(SIGALRM, updateprogressmeter);
745 alarmtimer(1); /* set alarm timer for 1 Hz */
746 } else if (flag == 1) {
747 alarmtimer(0);
748 (void)putc('\n', ttyout);
749 }
750 fflush(ttyout);
751 #endif /* SMALL */
752 }
753
754 /*
755 * Display transfer statistics.
756 * Requires start to be initialised by progressmeter(-1),
757 * direction to be defined by xfer routines, and filesize and bytes
758 * to be updated by xfer routines
759 * If siginfo is nonzero, an ETA is displayed, and the output goes to stderr
760 * instead of ttyout.
761 */
762 void
763 ptransfer(siginfo)
764 int siginfo;
765 {
766 #ifndef SMALL
767 struct timeval now, td, wait;
768 double elapsed;
769 off_t bs;
770 int meg, remaining, hh, len;
771 char buf[100];
772
773 if (!verbose && !siginfo)
774 return;
775
776 (void)gettimeofday(&now, NULL);
777 timersub(&now, &start, &td);
778 elapsed = td.tv_sec + (td.tv_usec / 1000000.0);
779 bs = bytes / (elapsed == 0.0 ? 1 : elapsed);
780 meg = 0;
781 if (bs > (1024 * 1024))
782 meg = 1;
783 len = 0;
784 len += snprintf(buf + len, sizeof(buf) - len,
785 #ifndef NO_QUAD
786 "%qd byte%s %s in ", (long long)bytes,
787 #else
788 "%ld byte%s %s in ", (long)bytes,
789 #endif
790 bytes == 1 ? "" : "s", direction);
791 remaining = (int)elapsed;
792 if (remaining > SECSPERDAY) {
793 int days;
794
795 days = remaining / SECSPERDAY;
796 remaining %= SECSPERDAY;
797 len += snprintf(buf + len, sizeof(buf) - len,
798 "%d day%s ", days, days == 1 ? "" : "s");
799 }
800 hh = remaining / SECSPERHOUR;
801 remaining %= SECSPERHOUR;
802 if (hh)
803 len += snprintf(buf + len, sizeof(buf) - len, "%2d:", hh);
804 len += snprintf(buf + len, sizeof(buf) - len,
805 "%02d:%02d (%.2f %sB/s)", remaining / 60, remaining % 60,
806 bs / (1024.0 * (meg ? 1024.0 : 1.0)),
807 meg ? "M" : "K");
808
809 if (siginfo && bytes > 0 && elapsed > 0.0 && filesize >= 0
810 && bytes + restart_point <= filesize) {
811 remaining = (int)((filesize - restart_point) /
812 (bytes / elapsed) - elapsed);
813 hh = remaining / SECSPERHOUR;
814 remaining %= SECSPERHOUR;
815 len += snprintf(buf + len, sizeof(buf) - len, " ETA: ");
816 if (hh)
817 len += snprintf(buf + len, sizeof(buf) - len, "%2d:",
818 hh);
819 len += snprintf(buf + len, sizeof(buf) - len,
820 "%02d:%02d", remaining / 60, remaining % 60);
821 timersub(&now, &lastupdate, &wait);
822 if (wait.tv_sec >= STALLTIME)
823 len += snprintf(buf + len, sizeof(buf) - len,
824 " (stalled)");
825 }
826 len += snprintf(buf + len, sizeof(buf) - len, "\n");
827 (void)write(siginfo ? STDERR_FILENO : fileno(ttyout), buf, len);
828 #endif /* SMALL */
829 }
830
831 /*
832 * List words in stringlist, vertically arranged
833 */
834 void
835 list_vertical(sl)
836 StringList *sl;
837 {
838 int i, j, w;
839 int columns, width, lines, items;
840 char *p;
841
842 width = items = 0;
843
844 for (i = 0 ; i < sl->sl_cur ; i++) {
845 w = strlen(sl->sl_str[i]);
846 if (w > width)
847 width = w;
848 }
849 width = (width + 8) &~ 7;
850
851 columns = ttywidth / width;
852 if (columns == 0)
853 columns = 1;
854 lines = (sl->sl_cur + columns - 1) / columns;
855 for (i = 0; i < lines; i++) {
856 for (j = 0; j < columns; j++) {
857 p = sl->sl_str[j * lines + i];
858 if (p)
859 fputs(p, ttyout);
860 if (j * lines + i + lines >= sl->sl_cur) {
861 putc('\n', ttyout);
862 break;
863 }
864 w = strlen(p);
865 while (w < width) {
866 w = (w + 8) &~ 7;
867 (void)putc('\t', ttyout);
868 }
869 }
870 }
871 }
872
873 /*
874 * Update the global ttywidth value, using TIOCGWINSZ.
875 */
876 void
877 setttywidth(a)
878 int a;
879 {
880 struct winsize winsize;
881
882 if (ioctl(fileno(ttyout), TIOCGWINSZ, &winsize) != -1)
883 ttywidth = winsize.ws_col;
884 else
885 ttywidth = 80;
886 }
887
888 /*
889 * Set the SIGALRM interval timer for wait seconds, 0 to disable.
890 */
891 void
892 alarmtimer(wait)
893 int wait;
894 {
895 struct itimerval itv;
896
897 itv.it_value.tv_sec = wait;
898 itv.it_value.tv_usec = 0;
899 itv.it_interval = itv.it_value;
900 setitimer(ITIMER_REAL, &itv, NULL);
901 }
902
903 /*
904 * Setup or cleanup EditLine structures
905 */
906 #ifndef SMALL
907 void
908 controlediting()
909 {
910 if (editing && el == NULL && hist == NULL) {
911 HistEvent ev;
912 int editmode;
913
914 el = el_init(__progname, stdin, ttyout, stderr);
915 /* init editline */
916 hist = history_init(); /* init the builtin history */
917 history(hist, &ev, H_SETSIZE, 100);/* remember 100 events */
918 el_set(el, EL_HIST, history, hist); /* use history */
919
920 el_set(el, EL_EDITOR, "emacs"); /* default editor is emacs */
921 el_set(el, EL_PROMPT, prompt); /* set the prompt function */
922
923 /* add local file completion, bind to TAB */
924 el_set(el, EL_ADDFN, "ftp-complete",
925 "Context sensitive argument completion",
926 complete);
927 el_set(el, EL_BIND, "^I", "ftp-complete", NULL);
928 el_source(el, NULL); /* read ~/.editrc */
929 if ((el_get(el, EL_EDITMODE, &editmode) != -1) && editmode == 0)
930 editing = 0; /* the user doesn't want editing,
931 * so disable, and let statement
932 * below cleanup */
933 else
934 el_set(el, EL_SIGNAL, 1);
935 }
936 if (!editing) {
937 if (hist) {
938 history_end(hist);
939 hist = NULL;
940 }
941 if (el) {
942 el_end(el);
943 el = NULL;
944 }
945 }
946 }
947 #endif /* !SMALL */
948
949 /*
950 * Parse the specified socket buffer size.
951 */
952 int
953 getsockbufsize(arg)
954 const char *arg;
955 {
956 char *cp;
957 int val;
958
959 if (!isdigit(arg[0]))
960 return (-1);
961
962 val = strtol(arg, &cp, 10);
963 if (cp != NULL) {
964 if (cp[1] != '\0')
965 return (-1);
966 if (cp[0] == 'k')
967 val *= 1024;
968 if (cp[0] == 'm')
969 val *= 1024 * 1024;
970 }
971
972 if (val < 0)
973 return (-1);
974
975 return (val);
976 }
977
978 /*
979 * Set up socket buffer sizes before a connection is made.
980 */
981 void
982 setupsockbufsize(sock)
983 int sock;
984 {
985 static int sndbuf_default, rcvbuf_default;
986 int len, size;
987
988 /*
989 * Get the default socket buffer sizes if we don't already
990 * have them. It doesn't matter which socket we do this
991 * to, because on the first call no socket buffer sizes
992 * will have been modified, so we are guaranteed to get
993 * the system defaults.
994 */
995 if (sndbuf_default == 0) {
996 len = sizeof(sndbuf_default);
997 if (getsockopt(sock, SOL_SOCKET, SO_SNDBUF, &sndbuf_default,
998 &len) < 0)
999 err(1, "unable to get default sndbuf size");
1000 len = sizeof(rcvbuf_default);
1001 if (getsockopt(sock, SOL_SOCKET, SO_RCVBUF, &rcvbuf_default,
1002 &len) < 0)
1003 err(1, "unable to get default rcvbuf size");
1004
1005 }
1006
1007 size = sndbuf_size ? sndbuf_size : sndbuf_default;
1008 if (setsockopt(sock, SOL_SOCKET, SO_SNDBUF, &size, sizeof(size)) < 0)
1009 warn("unable to set sndbuf size %d", size);
1010
1011 size = rcvbuf_size ? rcvbuf_size : rcvbuf_default;
1012 if (setsockopt(sock, SOL_SOCKET, SO_RCVBUF, &size, sizeof(size)) < 0)
1013 warn("unable to set rcvbuf size %d", size);
1014 }
1015
1016 /*
1017 * If the socket buffer sizes were not set manually (i.e. came from a
1018 * configuration file), reset them so the right thing will happen on
1019 * subsequent connections.
1020 */
1021 void
1022 resetsockbufsize()
1023 {
1024
1025 if (sndbuf_manual == 0)
1026 sndbuf_size = 0;
1027 if (rcvbuf_manual == 0)
1028 rcvbuf_size = 0;
1029 }
1030
1031 /*
1032 * Internal version of connect(2); sets socket buffer sizes first.
1033 */
1034 int
1035 xconnect(sock, name, namelen)
1036 int sock;
1037 const struct sockaddr *name;
1038 int namelen;
1039 {
1040
1041 setupsockbufsize(sock);
1042 return (connect(sock, name, namelen));
1043 }
1044
1045 /*
1046 * Internal version of listen(2); sets socket buffer sizes first.
1047 */
1048 int
1049 xlisten(sock, backlog)
1050 int sock, backlog;
1051 {
1052
1053 setupsockbufsize(sock);
1054 return (listen(sock, backlog));
1055 }
1056
1057 void *
1058 xmalloc(size)
1059 size_t size;
1060 {
1061 void *p;
1062
1063 p = malloc(size);
1064 if (p == NULL)
1065 err(1, "Unable to allocate %ld bytes of memory", (long)size);
1066 return (p);
1067 }
1068
1069 char *
1070 xstrdup(str)
1071 const char *str;
1072 {
1073 char *s;
1074
1075 if (str == NULL)
1076 errx(1, "xstrdup() called with NULL argument");
1077 s = strdup(str);
1078 if (s == NULL)
1079 err(1, "Unable to allocate memory for string copy");
1080 return (s);
1081 }
1082