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