util.c revision 1.59 1 /* $NetBSD: util.c,v 1.59 1999/09/24 00:48:24 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.59 1999/09/24 00:48:24 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 #ifndef HAVE_TIMEGM
110 static time_t sub_mkgmt __P((struct tm *tm));
111 #endif
112
113 /*
114 * Connect to peer server and
115 * auto-login, if possible.
116 */
117 void
118 setpeer(argc, argv)
119 int argc;
120 char *argv[];
121 {
122 char *host;
123 char *port;
124
125 if (connected) {
126 fprintf(ttyout, "Already connected to %s, use close first.\n",
127 hostname);
128 code = -1;
129 return;
130 }
131 if (argc < 2)
132 (void)another(&argc, &argv, "to");
133 if (argc < 2 || argc > 3) {
134 fprintf(ttyout, "usage: %s host-name [port]\n", argv[0]);
135 code = -1;
136 return;
137 }
138 if (gatemode)
139 port = gateport;
140 else
141 port = ftpport;
142 if (argc > 2)
143 port = strdup(argv[2]);
144
145 if (gatemode) {
146 if (gateserver == NULL || *gateserver == '\0')
147 errx(1, "gateserver not defined (shouldn't happen)");
148 host = hookup(gateserver, port);
149 } else
150 host = hookup(argv[1], port);
151
152 if (host) {
153 int overbose;
154
155 if (gatemode && verbose) {
156 fprintf(ttyout,
157 "Connecting via pass-through server %s\n",
158 gateserver);
159 }
160
161 connected = 1;
162 /*
163 * Set up defaults for FTP.
164 */
165 (void)strcpy(typename, "ascii"), type = TYPE_A;
166 curtype = TYPE_A;
167 (void)strcpy(formname, "non-print"), form = FORM_N;
168 (void)strcpy(modename, "stream"), mode = MODE_S;
169 (void)strcpy(structname, "file"), stru = STRU_F;
170 (void)strcpy(bytename, "8"), 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)strcpy(typename, "binary");
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 strlcpy(anonpass, pass, len);
270 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 strlcpy(nuser, user, len);
317 strlcat(nuser, "@", len);
318 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)strcpy(line, "$init");
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 strlcpy(temp, tmpdir, sizeof(temp));
441 strlcat(temp, "/", sizeof(temp));
442 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
517 * the expectation of a single return value.
518 * Can't control multiple values being expanded
519 * from the expression, we return only the first.
520 */
521 int
522 globulize(cpp)
523 char **cpp;
524 {
525 glob_t gl;
526 int flags;
527
528 if (!doglob)
529 return (1);
530
531 flags = GLOB_BRACE|GLOB_NOCHECK|GLOB_TILDE;
532 memset(&gl, 0, sizeof(gl));
533 if (glob(*cpp, flags, NULL, &gl) || gl.gl_pathc == 0) {
534 warnx("%s: not found", *cpp);
535 globfree(&gl);
536 return (0);
537 }
538 /* XXX: caller should check if *cpp changed, and
539 * free(*cpp) if that is the case
540 */
541 *cpp = xstrdup(gl.gl_pathv[0]);
542 globfree(&gl);
543 return (1);
544 }
545
546 /*
547 * determine size of remote file
548 */
549 off_t
550 remotesize(file, noisy)
551 const char *file;
552 int noisy;
553 {
554 int overbose;
555 off_t size;
556
557 overbose = verbose;
558 size = -1;
559 if (debug == 0)
560 verbose = -1;
561 if (command("SIZE %s", file) == COMPLETE) {
562 char *cp, *ep;
563
564 cp = strchr(reply_string, ' ');
565 if (cp != NULL) {
566 cp++;
567 #ifndef NO_QUAD
568 size = strtoq(cp, &ep, 10);
569 #else
570 size = strtol(cp, &ep, 10);
571 #endif
572 if (*ep != '\0' && !isspace((unsigned char)*ep))
573 size = -1;
574 }
575 } else if (noisy && debug == 0) {
576 fputs(reply_string, ttyout);
577 putc('\n', ttyout);
578 }
579 verbose = overbose;
580 return (size);
581 }
582
583 /*
584 * determine last modification time (in GMT) of remote file
585 */
586 time_t
587 remotemodtime(file, noisy)
588 const char *file;
589 int noisy;
590 {
591 int overbose;
592 time_t rtime;
593 int ocode;
594
595 overbose = verbose;
596 ocode = code;
597 rtime = -1;
598 if (debug == 0)
599 verbose = -1;
600 if (command("MDTM %s", file) == COMPLETE) {
601 struct tm timebuf;
602 int yy, mo, day, hour, min, sec;
603 sscanf(reply_string, "%*s %04d%02d%02d%02d%02d%02d", &yy, &mo,
604 &day, &hour, &min, &sec);
605 memset(&timebuf, 0, sizeof(timebuf));
606 timebuf.tm_sec = sec;
607 timebuf.tm_min = min;
608 timebuf.tm_hour = hour;
609 timebuf.tm_mday = day;
610 timebuf.tm_mon = mo - 1;
611 timebuf.tm_year = yy - TM_YEAR_BASE;
612 timebuf.tm_isdst = -1;
613 rtime = mkgmtime(&timebuf);
614 if (rtime == -1 && (noisy || debug != 0))
615 fprintf(ttyout, "Can't convert %s to a time.\n",
616 reply_string);
617 } else if (noisy && debug == 0) {
618 fputs(reply_string, ttyout);
619 putc('\n', ttyout);
620 }
621 verbose = overbose;
622 if (rtime == -1)
623 code = ocode;
624 return (rtime);
625 }
626
627 /*
628 * UTC version of mktime(3)
629 */
630 #ifdef HAVE_TIMEGM
631 time_t
632 mkgmtime(tm)
633 struct tm *tm;
634 {
635
636 /* This is very clean, but not portable at all. */
637 return (timegm(tm));
638 }
639
640 #else /* not HAVE_TIMEGM */
641
642 /*
643 * This code is not portable, but works on most Unix-like systems.
644 * If the local timezone has no summer time, using mktime(3) function
645 * and adjusting offset would be usable (adjusting leap seconds
646 * is still required, though), but the assumption is not always true.
647 *
648 * Anyway, no portable and correct implementation of UTC to time_t
649 * conversion exists....
650 */
651
652 static time_t
653 sub_mkgmt(tm)
654 struct tm *tm;
655 {
656 int y, nleapdays;
657 time_t t;
658 /* days before the month */
659 static const unsigned short moff[12] = {
660 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334
661 };
662
663 /*
664 * XXX: This code assumes the given time to be normalized.
665 * Normalizing here is impossible in case the given time is a leap
666 * second but the local time library is ignorant of leap seconds.
667 */
668
669 /* minimal sanity checking not to access outside of the array */
670 if ((unsigned) tm->tm_mon >= 12)
671 return (time_t) -1;
672 if (tm->tm_year < EPOCH_YEAR - TM_YEAR_BASE)
673 return (time_t) -1;
674
675 y = tm->tm_year + TM_YEAR_BASE - (tm->tm_mon < 2);
676 nleapdays = y / 4 - y / 100 + y / 400 -
677 ((EPOCH_YEAR-1) / 4 - (EPOCH_YEAR-1) / 100 + (EPOCH_YEAR-1) / 400);
678 t = ((((time_t) (tm->tm_year - (EPOCH_YEAR - TM_YEAR_BASE)) * 365 +
679 moff[tm->tm_mon] + tm->tm_mday - 1 + nleapdays) * 24 +
680 tm->tm_hour) * 60 + tm->tm_min) * 60 + tm->tm_sec;
681
682 return (t < 0 ? (time_t) -1 : t);
683 }
684
685 time_t
686 mkgmtime(tm)
687 struct tm *tm;
688 {
689 time_t t, t2;
690 struct tm *tm2;
691 int sec;
692
693 /* Do the first guess. */
694 if ((t = sub_mkgmt(tm)) == (time_t) -1)
695 return (time_t) -1;
696
697 /* save value in case *tm is overwritten by gmtime() */
698 sec = tm->tm_sec;
699
700 tm2 = gmtime(&t);
701 if ((t2 = sub_mkgmt(tm2)) == (time_t) -1)
702 return (time_t) -1;
703
704 if (t2 < t || tm2->tm_sec != sec) {
705 /*
706 * Adjust for leap seconds.
707 *
708 * real time_t time
709 * |
710 * tm
711 * / ... (a) first sub_mkgmt() conversion
712 * t
713 * |
714 * tm2
715 * / ... (b) second sub_mkgmt() conversion
716 * t2
717 * --->time
718 */
719 /*
720 * Do the second guess, assuming (a) and (b) are almost equal.
721 */
722 t += t - t2;
723 tm2 = gmtime(&t);
724
725 /*
726 * Either (a) or (b), may include one or two extra
727 * leap seconds. Try t, t + 2, t - 2, t + 1, and t - 1.
728 */
729 if (tm2->tm_sec == sec
730 || (t += 2, tm2 = gmtime(&t), tm2->tm_sec == sec)
731 || (t -= 4, tm2 = gmtime(&t), tm2->tm_sec == sec)
732 || (t += 3, tm2 = gmtime(&t), tm2->tm_sec == sec)
733 || (t -= 2, tm2 = gmtime(&t), tm2->tm_sec == sec))
734 ; /* found */
735 else {
736 /*
737 * Not found.
738 */
739 if (sec >= 60)
740 /*
741 * The given time is a leap second
742 * (sec 60 or 61), but the time library
743 * is ignorant of the leap second.
744 */
745 ; /* treat sec 60 as 59,
746 sec 61 as 0 of the next minute */
747 else
748 /* The given time may not be normalized. */
749 t++; /* restore t */
750 }
751 }
752
753 return (t < 0 ? (time_t) -1 : t);
754 }
755 #endif /* not HAVE_TIMEGM */
756
757 #ifndef NO_PROGRESS
758
759 /*
760 * return non-zero if we're the current foreground process
761 */
762 int
763 foregroundproc()
764 {
765 static pid_t pgrp = -1;
766 int ctty_pgrp;
767
768 if (pgrp == -1)
769 pgrp = getpgrp();
770
771 return ((ioctl(fileno(ttyout), TIOCGPGRP, &ctty_pgrp) != -1 &&
772 ctty_pgrp == (int)pgrp));
773 }
774
775
776 static void updateprogressmeter __P((int));
777
778 static void
779 updateprogressmeter(dummy)
780 int dummy;
781 {
782 int oerrno;
783
784 oerrno = errno;
785 progressmeter(0);
786 errno = oerrno;
787 }
788 #endif /* NO_PROGRESS */
789
790
791 /*
792 * List of order of magnitude prefixes.
793 * The last is `P', as 2^64 = 16384 Petabytes
794 */
795 static const char prefixes[] = " KMGTP";
796
797 /*
798 * Display a transfer progress bar if progress is non-zero.
799 * SIGALRM is hijacked for use by this function.
800 * - Before the transfer, set filesize to size of file (or -1 if unknown),
801 * and call with flag = -1. This starts the once per second timer,
802 * and a call to updateprogressmeter() upon SIGALRM.
803 * - During the transfer, updateprogressmeter will call progressmeter
804 * with flag = 0
805 * - After the transfer, call with flag = 1
806 */
807 static struct timeval start;
808 static struct timeval lastupdate;
809
810 void
811 progressmeter(flag)
812 int flag;
813 {
814 static off_t lastsize;
815 #ifndef NO_PROGRESS
816 struct timeval now, td, wait;
817 off_t cursize, abbrevsize, bytespersec;
818 double elapsed;
819 int ratio, barlength, i, len, remaining;
820
821 /*
822 * Work variables for progress bar.
823 *
824 * XXX: if the format of the progress bar changes
825 * (especially the number of characters in the
826 * `static' portion of it), be sure to update
827 * these appropriately.
828 *
829 * XXX: sprintf() is used because it's more portable,
830 * so `buf' must be big enough to hold the
831 * largest values output.
832 */
833 char buf[256]; /* workspace for progress bar */
834 #define BAROVERHEAD 43 /* non `*' portion of progress bar */
835 /*
836 * stars should contain at least
837 * sizeof(buf) - BAROVERHEAD entries
838 */
839 const char stars[] =
840 "*****************************************************************************"
841 "*****************************************************************************"
842 "*****************************************************************************";
843
844 #endif
845
846 if (flag == -1) {
847 (void)gettimeofday(&start, NULL);
848 lastupdate = start;
849 lastsize = restart_point;
850 }
851 #ifndef NO_PROGRESS
852 len = 0;
853 if (!progress || filesize <= 0)
854 return;
855
856 (void)gettimeofday(&now, NULL);
857 cursize = bytes + restart_point;
858 timersub(&now, &lastupdate, &wait);
859 if (cursize > lastsize) {
860 lastupdate = now;
861 lastsize = cursize;
862 if (wait.tv_sec >= STALLTIME) { /* fudge out stalled time */
863 start.tv_sec += wait.tv_sec;
864 start.tv_usec += wait.tv_usec;
865 }
866 wait.tv_sec = 0;
867 }
868
869 /*
870 * print progress bar only if we are foreground process.
871 */
872 if (! foregroundproc())
873 return;
874
875 ratio = (int)((double)cursize * 100.0 / (double)filesize);
876 ratio = MAX(ratio, 0);
877 ratio = MIN(ratio, 100);
878 len += sprintf(buf + len, "\r%3d%% ", ratio);
879
880 /*
881 * calculate the length of the `*' bar, ensuring that
882 * the number of stars won't exceed the buffer size
883 */
884 barlength = MIN(sizeof(buf) - 1, ttywidth) - BAROVERHEAD;
885 if (barlength > 0) {
886 i = barlength * ratio / 100;
887 len += sprintf(buf + len, "|%.*s%*s|",
888 i, stars, barlength - i, "");
889 }
890
891 abbrevsize = cursize;
892 for (i = 0; abbrevsize >= 100000 && i < sizeof(prefixes); i++)
893 abbrevsize >>= 10;
894 len += sprintf(buf + len,
895 #ifndef NO_QUAD
896 " %5qd %c%c ", (long long)abbrevsize,
897 #else
898 " %5ld %c%c ", (long)abbrevsize,
899 #endif
900 prefixes[i],
901 i == 0 ? ' ' : 'B');
902
903 timersub(&now, &start, &td);
904 elapsed = td.tv_sec + (td.tv_usec / 1000000.0);
905
906 bytespersec = 0;
907 if (bytes > 0) {
908 bytespersec = bytes;
909 if (elapsed > 0.0)
910 bytespersec /= elapsed;
911 }
912 for (i = 1; bytespersec >= 1024000 && i < sizeof(prefixes); i++)
913 bytespersec >>= 10;
914 len += sprintf(buf + len,
915 #ifndef NO_QUAD
916 " %3qd.%02d %cB/s ", (long long)bytespersec / 1024,
917 #else
918 " %3ld.%02d %cB/s ", (long)bytespersec / 1024,
919 #endif
920 (int)((bytespersec % 1024) * 100 / 1024),
921 prefixes[i]);
922
923 if (bytes <= 0 || elapsed <= 0.0 || cursize > filesize) {
924 len += sprintf(buf + len, " --:-- ETA");
925 } else if (wait.tv_sec >= STALLTIME) {
926 len += sprintf(buf + len, " - stalled -");
927 } else {
928 remaining = (int)
929 ((filesize - restart_point) / (bytes / elapsed) - elapsed);
930 if (remaining >= 100 * SECSPERHOUR)
931 len += sprintf(buf + len, " --:-- ETA");
932 else {
933 i = remaining / SECSPERHOUR;
934 if (i)
935 len += sprintf(buf + len, "%2d:", i);
936 else
937 len += sprintf(buf + len, " ");
938 i = remaining % SECSPERHOUR;
939 len += sprintf(buf + len, "%02d:%02d ETA",
940 i / 60, i % 60);
941 }
942 }
943 (void)write(fileno(ttyout), buf, len);
944
945 if (flag == -1) {
946 (void)xsignal(SIGALRM, updateprogressmeter);
947 alarmtimer(1); /* set alarm timer for 1 Hz */
948 } else if (flag == 1) {
949 (void)xsignal(SIGALRM, SIG_DFL);
950 alarmtimer(0);
951 (void)putc('\n', ttyout);
952 }
953 fflush(ttyout);
954 #endif /* !NO_PROGRESS */
955 }
956
957 /*
958 * Display transfer statistics.
959 * Requires start to be initialised by progressmeter(-1),
960 * direction to be defined by xfer routines, and filesize and bytes
961 * to be updated by xfer routines
962 * If siginfo is nonzero, an ETA is displayed, and the output goes to stderr
963 * instead of ttyout.
964 */
965 void
966 ptransfer(siginfo)
967 int siginfo;
968 {
969 struct timeval now, td, wait;
970 double elapsed;
971 off_t bytespersec;
972 int remaining, hh, i, len;
973
974 /*
975 * Work variable for transfer status.
976 *
977 * XXX: sprintf() is used because it's more portable,
978 * so `buf' must be large enough to hold the
979 * largest message length.
980 */
981 char buf[256];
982
983 if (!verbose && !progress && !siginfo)
984 return;
985
986 (void)gettimeofday(&now, NULL);
987 timersub(&now, &start, &td);
988 elapsed = td.tv_sec + (td.tv_usec / 1000000.0);
989 bytespersec = 0;
990 if (bytes > 0) {
991 bytespersec = bytes;
992 if (elapsed > 0.0)
993 bytespersec /= elapsed;
994 }
995 len = 0;
996 len += sprintf(buf + len,
997 #ifndef NO_QUAD
998 "%qd byte%s %s in ", (long long)bytes,
999 #else
1000 "%ld byte%s %s in ", (long)bytes,
1001 #endif
1002 bytes == 1 ? "" : "s", direction);
1003 remaining = (int)elapsed;
1004 if (remaining > SECSPERDAY) {
1005 int days;
1006
1007 days = remaining / SECSPERDAY;
1008 remaining %= SECSPERDAY;
1009 len += sprintf(buf + len, "%d day%s ",
1010 days, days == 1 ? "" : "s");
1011 }
1012 hh = remaining / SECSPERHOUR;
1013 remaining %= SECSPERHOUR;
1014 if (hh)
1015 len += sprintf(buf + len, "%2d:", hh);
1016 len += sprintf(buf + len, "%02d:%02d ", remaining / 60, remaining % 60);
1017
1018 for (i = 1; bytespersec >= 1024000 && i < sizeof(prefixes); i++)
1019 bytespersec >>= 10;
1020 len += sprintf(buf + len,
1021 #ifndef NO_QUAD
1022 "(%qd.%02d %cB/s)", (long long)bytespersec / 1024,
1023 #else
1024 "(%ld.%02d %cB/s)", (long)bytespersec / 1024,
1025 #endif
1026 (int)((bytespersec % 1024) * 100 / 1024),
1027 prefixes[i]);
1028
1029 if (siginfo && bytes > 0 && elapsed > 0.0 && filesize >= 0
1030 && bytes + restart_point <= filesize) {
1031 remaining = (int)((filesize - restart_point) /
1032 (bytes / elapsed) - elapsed);
1033 hh = remaining / SECSPERHOUR;
1034 remaining %= SECSPERHOUR;
1035 len += sprintf(buf + len, " ETA: ");
1036 if (hh)
1037 len += sprintf(buf + len, "%2d:", hh);
1038 len += sprintf(buf + len, "%02d:%02d",
1039 remaining / 60, remaining % 60);
1040 timersub(&now, &lastupdate, &wait);
1041 if (wait.tv_sec >= STALLTIME)
1042 len += sprintf(buf + len, " (stalled)");
1043 }
1044 len += sprintf(buf + len, "\n");
1045 (void)write(siginfo ? STDERR_FILENO : fileno(ttyout), buf, len);
1046 }
1047
1048 /*
1049 * List words in stringlist, vertically arranged
1050 */
1051 void
1052 list_vertical(sl)
1053 StringList *sl;
1054 {
1055 int i, j, w;
1056 int columns, width, lines, items;
1057 char *p;
1058
1059 width = items = 0;
1060
1061 for (i = 0 ; i < sl->sl_cur ; i++) {
1062 w = strlen(sl->sl_str[i]);
1063 if (w > width)
1064 width = w;
1065 }
1066 width = (width + 8) &~ 7;
1067
1068 columns = ttywidth / width;
1069 if (columns == 0)
1070 columns = 1;
1071 lines = (sl->sl_cur + columns - 1) / columns;
1072 for (i = 0; i < lines; i++) {
1073 for (j = 0; j < columns; j++) {
1074 p = sl->sl_str[j * lines + i];
1075 if (p)
1076 fputs(p, ttyout);
1077 if (j * lines + i + lines >= sl->sl_cur) {
1078 putc('\n', ttyout);
1079 break;
1080 }
1081 w = strlen(p);
1082 while (w < width) {
1083 w = (w + 8) &~ 7;
1084 (void)putc('\t', ttyout);
1085 }
1086 }
1087 }
1088 }
1089
1090 /*
1091 * Update the global ttywidth value, using TIOCGWINSZ.
1092 */
1093 void
1094 setttywidth(a)
1095 int a;
1096 {
1097 struct winsize winsize;
1098 int oerrno;
1099
1100 oerrno = errno;
1101 if (ioctl(fileno(ttyout), TIOCGWINSZ, &winsize) != -1 &&
1102 winsize.ws_col != 0)
1103 ttywidth = winsize.ws_col;
1104 else
1105 ttywidth = 80;
1106 errno = oerrno;
1107 }
1108
1109 void
1110 crankrate(int sig)
1111 {
1112
1113 switch (sig) {
1114 case SIGUSR1:
1115 if (rate_get)
1116 rate_get += rate_get_incr;
1117 if (rate_put)
1118 rate_put += rate_put_incr;
1119 break;
1120 case SIGUSR2:
1121 if (rate_get && rate_get > rate_get_incr)
1122 rate_get -= rate_get_incr;
1123 if (rate_put && rate_put > rate_put_incr)
1124 rate_put -= rate_put_incr;
1125 break;
1126 default:
1127 err(1, "crankrate invoked with unknown signal: %d", sig);
1128 }
1129 }
1130
1131
1132 /*
1133 * Set the SIGALRM interval timer for wait seconds, 0 to disable.
1134 */
1135 void
1136 alarmtimer(wait)
1137 int wait;
1138 {
1139 struct itimerval itv;
1140
1141 itv.it_value.tv_sec = wait;
1142 itv.it_value.tv_usec = 0;
1143 itv.it_interval = itv.it_value;
1144 setitimer(ITIMER_REAL, &itv, NULL);
1145 }
1146
1147 /*
1148 * Setup or cleanup EditLine structures
1149 */
1150 #ifndef NO_EDITCOMPLETE
1151 void
1152 controlediting()
1153 {
1154 if (editing && el == NULL && hist == NULL) {
1155 HistEvent ev;
1156 int editmode;
1157
1158 el = el_init(__progname, stdin, ttyout, stderr);
1159 /* init editline */
1160 hist = history_init(); /* init the builtin history */
1161 history(hist, &ev, H_SETSIZE, 100);/* remember 100 events */
1162 el_set(el, EL_HIST, history, hist); /* use history */
1163
1164 el_set(el, EL_EDITOR, "emacs"); /* default editor is emacs */
1165 el_set(el, EL_PROMPT, prompt); /* set the prompt function */
1166
1167 /* add local file completion, bind to TAB */
1168 el_set(el, EL_ADDFN, "ftp-complete",
1169 "Context sensitive argument completion",
1170 complete);
1171 el_set(el, EL_BIND, "^I", "ftp-complete", NULL);
1172 el_source(el, NULL); /* read ~/.editrc */
1173 if ((el_get(el, EL_EDITMODE, &editmode) != -1) && editmode == 0)
1174 editing = 0; /* the user doesn't want editing,
1175 * so disable, and let statement
1176 * below cleanup */
1177 else
1178 el_set(el, EL_SIGNAL, 1);
1179 }
1180 if (!editing) {
1181 if (hist) {
1182 history_end(hist);
1183 hist = NULL;
1184 }
1185 if (el) {
1186 el_end(el);
1187 el = NULL;
1188 }
1189 }
1190 }
1191 #endif /* !NO_EDITCOMPLETE */
1192
1193 /*
1194 * Convert the string `arg' to an int, which may have an optional SI suffix
1195 * (`b', `k', `m', `g'). Returns the number for success, -1 otherwise.
1196 */
1197 int
1198 strsuftoi(arg)
1199 const char *arg;
1200 {
1201 char *cp;
1202 long val;
1203
1204 if (!isdigit((unsigned char)arg[0]))
1205 return (-1);
1206
1207 val = strtol(arg, &cp, 10);
1208 if (cp != NULL) {
1209 if (cp[0] != '\0' && cp[1] != '\0')
1210 return (-1);
1211 switch (tolower((unsigned char)cp[0])) {
1212 case '\0':
1213 case 'b':
1214 break;
1215 case 'k':
1216 val <<= 10;
1217 break;
1218 case 'm':
1219 val <<= 20;
1220 break;
1221 case 'g':
1222 val <<= 30;
1223 break;
1224 default:
1225 return (-1);
1226 }
1227 }
1228 if (val < 0 || val > INT_MAX)
1229 return (-1);
1230
1231 return (val);
1232 }
1233
1234 /*
1235 * Set up socket buffer sizes before a connection is made.
1236 */
1237 void
1238 setupsockbufsize(sock)
1239 int sock;
1240 {
1241
1242 if (setsockopt(sock, SOL_SOCKET, SO_SNDBUF, (void *) &sndbuf_size,
1243 sizeof(rcvbuf_size)) < 0)
1244 warn("unable to set sndbuf size %d", sndbuf_size);
1245
1246 if (setsockopt(sock, SOL_SOCKET, SO_RCVBUF, (void *) &rcvbuf_size,
1247 sizeof(rcvbuf_size)) < 0)
1248 warn("unable to set rcvbuf size %d", rcvbuf_size);
1249 }
1250
1251 void
1252 ftpvis(dst, dstlen, src, srclen)
1253 char *dst;
1254 size_t dstlen;
1255 const char *src;
1256 size_t srclen;
1257 {
1258 int di, si;
1259
1260 for (di = si = 0;
1261 src[si] != '\0' && di < dstlen && si < srclen;
1262 di++, si++) {
1263 switch (src[si]) {
1264 case '\\':
1265 case ' ':
1266 case '\t':
1267 case '\r':
1268 case '\n':
1269 case '"':
1270 dst[di++] = '\\';
1271 if (di >= dstlen)
1272 break;
1273 /* FALLTHROUGH */
1274 default:
1275 dst[di] = src[si];
1276 }
1277 }
1278 dst[di] = '\0';
1279 }
1280
1281 /*
1282 * Determine if given string is an IPv6 address or not.
1283 * Return 1 for yes, 0 for no
1284 */
1285 int
1286 isipv6addr(addr)
1287 const char *addr;
1288 {
1289 int rv = 0;
1290 #ifdef INET6
1291 u_char buf[16]; /* XXX: sizeof(struct in_addr6) */
1292
1293 rv = inet_pton(AF_INET6, addr, &buf);
1294 if (debug)
1295 fprintf(ttyout, "isipv6addr: got %d for %s\n", rv, addr);
1296 #endif
1297 return rv;
1298 }
1299
1300
1301 /*
1302 * Internal version of connect(2); sets socket buffer sizes first.
1303 */
1304 int
1305 xconnect(sock, name, namelen)
1306 int sock;
1307 const struct sockaddr *name;
1308 int namelen;
1309 {
1310
1311 setupsockbufsize(sock);
1312 return (connect(sock, name, namelen));
1313 }
1314
1315 /*
1316 * Internal version of listen(2); sets socket buffer sizes first.
1317 */
1318 int
1319 xlisten(sock, backlog)
1320 int sock, backlog;
1321 {
1322
1323 setupsockbufsize(sock);
1324 return (listen(sock, backlog));
1325 }
1326
1327 void *
1328 xmalloc(size)
1329 size_t size;
1330 {
1331 void *p;
1332
1333 p = malloc(size);
1334 if (p == NULL)
1335 err(1, "Unable to allocate %ld bytes of memory", (long)size);
1336 return (p);
1337 }
1338
1339 char *
1340 xstrdup(str)
1341 const char *str;
1342 {
1343 char *s;
1344
1345 if (str == NULL)
1346 errx(1, "xstrdup() called with NULL argument");
1347 s = strdup(str);
1348 if (s == NULL)
1349 err(1, "Unable to allocate memory for string copy");
1350 return (s);
1351 }
1352
1353 sig_t
1354 xsignal(sig, func)
1355 int sig;
1356 void (*func) __P((int));
1357 {
1358 struct sigaction act, oact;
1359
1360 act.sa_handler = func;
1361 sigemptyset(&act.sa_mask);
1362 act.sa_flags = SA_RESTART;
1363 if (sigaction(sig, &act, &oact) < 0)
1364 return (SIG_ERR);
1365 return (oact.sa_handler);
1366 }
1367