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