util.c revision 1.52 1 /* $NetBSD: util.c,v 1.52 1999/06/26 00:17:02 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.52 1999/06/26 00:17:02 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 <fcntl.h>
93 #include <glob.h>
94 #include <termios.h>
95 #include <signal.h>
96 #include <limits.h>
97 #include <pwd.h>
98 #include <stdio.h>
99 #include <stdlib.h>
100 #include <string.h>
101 #include <time.h>
102 #include <tzfile.h>
103 #include <unistd.h>
104
105 #include "ftp_var.h"
106 #include "pathnames.h"
107
108 #ifndef HAVE_TIMEGM
109 static time_t sub_mkgmt __P((struct tm *tm));
110 #endif
111
112 /*
113 * Connect to peer server and
114 * auto-login, if possible.
115 */
116 void
117 setpeer(argc, argv)
118 int argc;
119 char *argv[];
120 {
121 char *host;
122 in_port_t port;
123
124 if (connected) {
125 fprintf(ttyout, "Already connected to %s, use close first.\n",
126 hostname);
127 code = -1;
128 return;
129 }
130 if (argc < 2)
131 (void)another(&argc, &argv, "to");
132 if (argc < 2 || argc > 3) {
133 fprintf(ttyout, "usage: %s host-name [port]\n", argv[0]);
134 code = -1;
135 return;
136 }
137 if (gatemode)
138 port = gateport;
139 else
140 port = ftpport;
141 if (argc > 2) {
142 char *ep;
143 long nport;
144
145 nport = strtol(argv[2], &ep, 10);
146 if (nport < 1 || nport > MAX_IN_PORT_T || *ep != '\0') {
147 fprintf(ttyout, "%s: bad port number '%s'.\n",
148 argv[1], argv[2]);
149 fprintf(ttyout, "usage: %s host-name [port]\n",
150 argv[0]);
151 code = -1;
152 return;
153 }
154 port = htons((in_port_t)nport);
155 }
156
157 if (gatemode) {
158 if (gateserver == NULL || *gateserver == '\0')
159 errx(1, "gateserver not defined (shouldn't happen)");
160 host = hookup(gateserver, port);
161 } else
162 host = hookup(argv[1], port);
163
164 if (host) {
165 int overbose;
166
167 if (gatemode && verbose) {
168 fprintf(ttyout,
169 "Connecting via pass-through server %s\n",
170 gateserver);
171 }
172
173 connected = 1;
174 /*
175 * Set up defaults for FTP.
176 */
177 (void)strcpy(typename, "ascii"), type = TYPE_A;
178 curtype = TYPE_A;
179 (void)strcpy(formname, "non-print"), form = FORM_N;
180 (void)strcpy(modename, "stream"), mode = MODE_S;
181 (void)strcpy(structname, "file"), stru = STRU_F;
182 (void)strcpy(bytename, "8"), bytesize = 8;
183 if (autologin)
184 (void)ftp_login(argv[1], NULL, NULL);
185
186 overbose = verbose;
187 if (debug == 0)
188 verbose = -1;
189 if (command("SYST") == COMPLETE && overbose) {
190 char *cp, c;
191 c = 0;
192 cp = strchr(reply_string + 4, ' ');
193 if (cp == NULL)
194 cp = strchr(reply_string + 4, '\r');
195 if (cp) {
196 if (cp[-1] == '.')
197 cp--;
198 c = *cp;
199 *cp = '\0';
200 }
201
202 fprintf(ttyout, "Remote system type is %s.\n",
203 reply_string + 4);
204 if (cp)
205 *cp = c;
206 }
207 if (!strncmp(reply_string, "215 UNIX Type: L8", 17)) {
208 if (proxy)
209 unix_proxy = 1;
210 else
211 unix_server = 1;
212 /*
213 * Set type to 0 (not specified by user),
214 * meaning binary by default, but don't bother
215 * telling server. We can use binary
216 * for text files unless changed by the user.
217 */
218 type = 0;
219 (void)strcpy(typename, "binary");
220 if (overbose)
221 fprintf(ttyout,
222 "Using %s mode to transfer files.\n",
223 typename);
224 } else {
225 if (proxy)
226 unix_proxy = 0;
227 else
228 unix_server = 0;
229 if (overbose &&
230 !strncmp(reply_string, "215 TOPS20", 10))
231 fputs(
232 "Remember to set tenex mode when transferring binary files from this machine.\n",
233 ttyout);
234 }
235 verbose = overbose;
236 }
237 }
238
239 /*
240 * login to remote host, using given username & password if supplied
241 */
242 int
243 ftp_login(host, user, pass)
244 const char *host;
245 const char *user, *pass;
246 {
247 char tmp[80];
248 const char *acct;
249 struct passwd *pw;
250 int n, aflag, rval, freeuser, freepass, freeacct, len;
251
252 acct = NULL;
253 aflag = rval = freeuser = freepass = freeacct = 0;
254
255 /*
256 * Set up arguments for an anonymous FTP session, if necessary.
257 */
258 if (anonftp) {
259 /*
260 * Set up anonymous login password.
261 */
262 if ((pass = getenv("FTPANONPASS")) == NULL) {
263 char *anonpass;
264
265 if ((pass = getlogin()) == NULL) {
266 if ((pw = getpwuid(getuid())) == NULL)
267 pass = "anonymous";
268 else
269 pass = pw->pw_name;
270 }
271 /*
272 * Every anonymous FTP server I've encountered
273 * will accept the string "username@", and will
274 * append the hostname itself. We do this by default
275 * since many servers are picky about not having
276 * a FQDN in the anonymous password.
277 * - thorpej (at) netbsd.org
278 */
279 len = strlen(pass) + 2;
280 anonpass = xmalloc(len);
281 snprintf(anonpass, len, "%s@", pass);
282 pass = anonpass;
283 freepass = 1;
284 }
285 user = "anonymous"; /* as per RFC 1635 */
286 }
287
288 if (user == NULL) {
289 freeuser = 1;
290 if (pass == NULL)
291 freepass = 1;
292 freeacct = 1;
293 if (ruserpass(host, &user, &pass, &acct) < 0) {
294 code = -1;
295 goto cleanup_ftp_login;
296 }
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
791 progressmeter(0);
792 }
793 #endif /* NO_PROGRESS */
794
795
796 /*
797 * List of order of magnitude prefixes.
798 * The last is `P', as 2^64 = 16384 Petabytes
799 */
800 static const char prefixes[] = " KMGTP";
801
802 /*
803 * Display a transfer progress bar if progress is non-zero.
804 * SIGALRM is hijacked for use by this function.
805 * - Before the transfer, set filesize to size of file (or -1 if unknown),
806 * and call with flag = -1. This starts the once per second timer,
807 * and a call to updateprogressmeter() upon SIGALRM.
808 * - During the transfer, updateprogressmeter will call progressmeter
809 * with flag = 0
810 * - After the transfer, call with flag = 1
811 */
812 static struct timeval start;
813 static struct timeval lastupdate;
814
815 void
816 progressmeter(flag)
817 int flag;
818 {
819 static off_t lastsize;
820 #ifndef NO_PROGRESS
821 struct timeval now, td, wait;
822 off_t cursize, abbrevsize, bytespersec;
823 double elapsed;
824 int ratio, barlength, i, len, remaining;
825 char buf[256];
826 #endif
827
828 if (flag == -1) {
829 (void)gettimeofday(&start, NULL);
830 lastupdate = start;
831 lastsize = restart_point;
832 }
833 #ifndef NO_PROGRESS
834 len = 0;
835 if (!progress || filesize <= 0)
836 return;
837
838 (void)gettimeofday(&now, NULL);
839 cursize = bytes + restart_point;
840 timersub(&now, &lastupdate, &wait);
841 if (cursize > lastsize) {
842 lastupdate = now;
843 lastsize = cursize;
844 if (wait.tv_sec >= STALLTIME) { /* fudge out stalled time */
845 start.tv_sec += wait.tv_sec;
846 start.tv_usec += wait.tv_usec;
847 }
848 wait.tv_sec = 0;
849 }
850
851 /*
852 * print progress bar only if we are foreground process.
853 */
854 if (! foregroundproc())
855 return;
856
857 ratio = (int)((double)cursize * 100.0 / (double)filesize);
858 ratio = MAX(ratio, 0);
859 ratio = MIN(ratio, 100);
860 len += snprintf(buf + len, sizeof(buf) - len, "\r%3d%% ", ratio);
861
862 barlength = ttywidth - 43;
863 if (barlength > 0) {
864 i = barlength * ratio / 100;
865 len += snprintf(buf + len, sizeof(buf) - len,
866 "|%.*s%*s|", i,
867 "*****************************************************************************"
868 "*****************************************************************************",
869 barlength - i, "");
870 }
871
872 abbrevsize = cursize;
873 for (i = 0; abbrevsize >= 100000 && i < sizeof(prefixes); i++)
874 abbrevsize >>= 10;
875 len += snprintf(buf + len, sizeof(buf) - len,
876 #ifndef NO_QUAD
877 " %5qd %c%c ", (long long)abbrevsize,
878 #else
879 " %5ld %c%c ", (long)abbrevsize,
880 #endif
881 prefixes[i],
882 i == 0 ? ' ' : 'B');
883
884 timersub(&now, &start, &td);
885 elapsed = td.tv_sec + (td.tv_usec / 1000000.0);
886
887 bytespersec = 0;
888 if (bytes > 0) {
889 bytespersec = bytes;
890 if (elapsed > 0.0)
891 bytespersec /= elapsed;
892 }
893 for (i = 1; bytespersec >= 1024000 && i < sizeof(prefixes); i++)
894 bytespersec >>= 10;
895 len += snprintf(buf + len, sizeof(buf) - len,
896 #ifndef NO_QUAD
897 " %3qd.%02d %cB/s ", (long long)bytespersec / 1024,
898 #else
899 " %3ld.%02d %cB/s ", (long)bytespersec / 1024,
900 #endif
901 (int)((bytespersec % 1024) * 100 / 1024),
902 prefixes[i]);
903
904 if (bytes <= 0 || elapsed <= 0.0 || cursize > filesize) {
905 len += snprintf(buf + len, sizeof(buf) - len,
906 " --:-- ETA");
907 } else if (wait.tv_sec >= STALLTIME) {
908 len += snprintf(buf + len, sizeof(buf) - len,
909 " - stalled -");
910 } else {
911 remaining = (int)
912 ((filesize - restart_point) / (bytes / elapsed) - elapsed);
913 if (remaining >= 100 * SECSPERHOUR)
914 len += snprintf(buf + len, sizeof(buf) - len,
915 " --:-- ETA");
916 else {
917 i = remaining / SECSPERHOUR;
918 if (i)
919 len += snprintf(buf + len, sizeof(buf) - len,
920 "%2d:", i);
921 else
922 len += snprintf(buf + len, sizeof(buf) - len,
923 " ");
924 i = remaining % SECSPERHOUR;
925 len += snprintf(buf + len, sizeof(buf) - len,
926 "%02d:%02d ETA", i / 60, i % 60);
927 }
928 }
929 (void)write(fileno(ttyout), buf, len);
930
931 if (flag == -1) {
932 (void)xsignal(SIGALRM, updateprogressmeter);
933 alarmtimer(1); /* set alarm timer for 1 Hz */
934 } else if (flag == 1) {
935 (void)xsignal(SIGALRM, SIG_DFL);
936 alarmtimer(0);
937 (void)putc('\n', ttyout);
938 }
939 fflush(ttyout);
940 #endif /* !NO_PROGRESS */
941 }
942
943 /*
944 * Display transfer statistics.
945 * Requires start to be initialised by progressmeter(-1),
946 * direction to be defined by xfer routines, and filesize and bytes
947 * to be updated by xfer routines
948 * If siginfo is nonzero, an ETA is displayed, and the output goes to stderr
949 * instead of ttyout.
950 */
951 void
952 ptransfer(siginfo)
953 int siginfo;
954 {
955 struct timeval now, td, wait;
956 double elapsed;
957 off_t bytespersec;
958 int remaining, hh, i, len;
959 char buf[100];
960
961 if (!verbose && !progress && !siginfo)
962 return;
963
964 (void)gettimeofday(&now, NULL);
965 timersub(&now, &start, &td);
966 elapsed = td.tv_sec + (td.tv_usec / 1000000.0);
967 bytespersec = 0;
968 if (bytes > 0) {
969 bytespersec = bytes;
970 if (elapsed > 0.0)
971 bytespersec /= elapsed;
972 }
973 len = 0;
974 len += snprintf(buf + len, sizeof(buf) - len,
975 #ifndef NO_QUAD
976 "%qd byte%s %s in ", (long long)bytes,
977 #else
978 "%ld byte%s %s in ", (long)bytes,
979 #endif
980 bytes == 1 ? "" : "s", direction);
981 remaining = (int)elapsed;
982 if (remaining > SECSPERDAY) {
983 int days;
984
985 days = remaining / SECSPERDAY;
986 remaining %= SECSPERDAY;
987 len += snprintf(buf + len, sizeof(buf) - len,
988 "%d day%s ", days, days == 1 ? "" : "s");
989 }
990 hh = remaining / SECSPERHOUR;
991 remaining %= SECSPERHOUR;
992 if (hh)
993 len += snprintf(buf + len, sizeof(buf) - len, "%2d:", hh);
994 len += snprintf(buf + len, sizeof(buf) - len,
995 "%02d:%02d ", remaining / 60, remaining % 60);
996
997 for (i = 1; bytespersec >= 1024000 && i < sizeof(prefixes); i++)
998 bytespersec >>= 10;
999 len += snprintf(buf + len, sizeof(buf) - len,
1000 #ifndef NO_QUAD
1001 "(%qd.%02d %cB/s)", (long long)bytespersec / 1024,
1002 #else
1003 "(%ld.%02d %cB/s)", (long)bytespersec / 1024,
1004 #endif
1005 (int)((bytespersec % 1024) * 100 / 1024),
1006 prefixes[i]);
1007
1008 if (siginfo && bytes > 0 && elapsed > 0.0 && filesize >= 0
1009 && bytes + restart_point <= filesize) {
1010 remaining = (int)((filesize - restart_point) /
1011 (bytes / elapsed) - elapsed);
1012 hh = remaining / SECSPERHOUR;
1013 remaining %= SECSPERHOUR;
1014 len += snprintf(buf + len, sizeof(buf) - len, " ETA: ");
1015 if (hh)
1016 len += snprintf(buf + len, sizeof(buf) - len, "%2d:",
1017 hh);
1018 len += snprintf(buf + len, sizeof(buf) - len,
1019 "%02d:%02d", remaining / 60, remaining % 60);
1020 timersub(&now, &lastupdate, &wait);
1021 if (wait.tv_sec >= STALLTIME)
1022 len += snprintf(buf + len, sizeof(buf) - len,
1023 " (stalled)");
1024 }
1025 len += snprintf(buf + len, sizeof(buf) - len, "\n");
1026 (void)write(siginfo ? STDERR_FILENO : fileno(ttyout), buf, len);
1027 }
1028
1029 /*
1030 * List words in stringlist, vertically arranged
1031 */
1032 void
1033 list_vertical(sl)
1034 StringList *sl;
1035 {
1036 int i, j, w;
1037 int columns, width, lines, items;
1038 char *p;
1039
1040 width = items = 0;
1041
1042 for (i = 0 ; i < sl->sl_cur ; i++) {
1043 w = strlen(sl->sl_str[i]);
1044 if (w > width)
1045 width = w;
1046 }
1047 width = (width + 8) &~ 7;
1048
1049 columns = ttywidth / width;
1050 if (columns == 0)
1051 columns = 1;
1052 lines = (sl->sl_cur + columns - 1) / columns;
1053 for (i = 0; i < lines; i++) {
1054 for (j = 0; j < columns; j++) {
1055 p = sl->sl_str[j * lines + i];
1056 if (p)
1057 fputs(p, ttyout);
1058 if (j * lines + i + lines >= sl->sl_cur) {
1059 putc('\n', ttyout);
1060 break;
1061 }
1062 w = strlen(p);
1063 while (w < width) {
1064 w = (w + 8) &~ 7;
1065 (void)putc('\t', ttyout);
1066 }
1067 }
1068 }
1069 }
1070
1071 /*
1072 * Update the global ttywidth value, using TIOCGWINSZ.
1073 */
1074 void
1075 setttywidth(a)
1076 int a;
1077 {
1078 struct winsize winsize;
1079
1080 if (ioctl(fileno(ttyout), TIOCGWINSZ, &winsize) != -1 &&
1081 winsize.ws_col != 0)
1082 ttywidth = winsize.ws_col;
1083 else
1084 ttywidth = 80;
1085 }
1086
1087 /*
1088 * Set the SIGALRM interval timer for wait seconds, 0 to disable.
1089 */
1090 void
1091 alarmtimer(wait)
1092 int wait;
1093 {
1094 struct itimerval itv;
1095
1096 itv.it_value.tv_sec = wait;
1097 itv.it_value.tv_usec = 0;
1098 itv.it_interval = itv.it_value;
1099 setitimer(ITIMER_REAL, &itv, NULL);
1100 }
1101
1102 /*
1103 * Setup or cleanup EditLine structures
1104 */
1105 #ifndef NO_EDITCOMPLETE
1106 void
1107 controlediting()
1108 {
1109 if (editing && el == NULL && hist == NULL) {
1110 HistEvent ev;
1111 int editmode;
1112
1113 el = el_init(__progname, stdin, ttyout, stderr);
1114 /* init editline */
1115 hist = history_init(); /* init the builtin history */
1116 history(hist, &ev, H_SETSIZE, 100);/* remember 100 events */
1117 el_set(el, EL_HIST, history, hist); /* use history */
1118
1119 el_set(el, EL_EDITOR, "emacs"); /* default editor is emacs */
1120 el_set(el, EL_PROMPT, prompt); /* set the prompt function */
1121
1122 /* add local file completion, bind to TAB */
1123 el_set(el, EL_ADDFN, "ftp-complete",
1124 "Context sensitive argument completion",
1125 complete);
1126 el_set(el, EL_BIND, "^I", "ftp-complete", NULL);
1127 el_source(el, NULL); /* read ~/.editrc */
1128 if ((el_get(el, EL_EDITMODE, &editmode) != -1) && editmode == 0)
1129 editing = 0; /* the user doesn't want editing,
1130 * so disable, and let statement
1131 * below cleanup */
1132 else
1133 el_set(el, EL_SIGNAL, 1);
1134 }
1135 if (!editing) {
1136 if (hist) {
1137 history_end(hist);
1138 hist = NULL;
1139 }
1140 if (el) {
1141 el_end(el);
1142 el = NULL;
1143 }
1144 }
1145 }
1146 #endif /* !NO_EDITCOMPLETE */
1147
1148 /*
1149 * Parse the specified socket buffer size.
1150 */
1151 int
1152 getsockbufsize(arg)
1153 const char *arg;
1154 {
1155 char *cp;
1156 int val;
1157
1158 if (!isdigit((unsigned char)arg[0]))
1159 return (-1);
1160
1161 val = strtol(arg, &cp, 10);
1162 if (cp != NULL) {
1163 if (cp[1] != '\0')
1164 return (-1);
1165 if (cp[0] == 'k')
1166 val *= 1024;
1167 if (cp[0] == 'm')
1168 val *= 1024 * 1024;
1169 }
1170
1171 if (val < 0)
1172 return (-1);
1173
1174 return (val);
1175 }
1176
1177 /*
1178 * Set up socket buffer sizes before a connection is made.
1179 */
1180 void
1181 setupsockbufsize(sock)
1182 int sock;
1183 {
1184 static int sndbuf_default, rcvbuf_default;
1185 int len, size;
1186
1187 /*
1188 * Get the default socket buffer sizes if we don't already
1189 * have them. It doesn't matter which socket we do this
1190 * to, because on the first call no socket buffer sizes
1191 * will have been modified, so we are guaranteed to get
1192 * the system defaults.
1193 */
1194 if (sndbuf_default == 0) {
1195 len = sizeof(sndbuf_default);
1196 if (getsockopt(sock, SOL_SOCKET, SO_SNDBUF, &sndbuf_default,
1197 &len) < 0)
1198 err(1, "unable to get default sndbuf size");
1199 len = sizeof(rcvbuf_default);
1200 if (getsockopt(sock, SOL_SOCKET, SO_RCVBUF, &rcvbuf_default,
1201 &len) < 0)
1202 err(1, "unable to get default rcvbuf size");
1203
1204 }
1205
1206 size = sndbuf_size ? sndbuf_size : sndbuf_default;
1207 if (setsockopt(sock, SOL_SOCKET, SO_SNDBUF, &size, sizeof(size)) < 0)
1208 warn("unable to set sndbuf size %d", size);
1209
1210 size = rcvbuf_size ? rcvbuf_size : rcvbuf_default;
1211 if (setsockopt(sock, SOL_SOCKET, SO_RCVBUF, &size, sizeof(size)) < 0)
1212 warn("unable to set rcvbuf size %d", size);
1213 }
1214
1215 /*
1216 * If the socket buffer sizes were not set manually (i.e. came from a
1217 * configuration file), reset them so the right thing will happen on
1218 * subsequent connections.
1219 */
1220 void
1221 resetsockbufsize()
1222 {
1223
1224 if (sndbuf_manual == 0)
1225 sndbuf_size = 0;
1226 if (rcvbuf_manual == 0)
1227 rcvbuf_size = 0;
1228 }
1229
1230 void
1231 ftpvis(dst, dstlen, src, srclen)
1232 char *dst;
1233 size_t dstlen;
1234 const char *src;
1235 size_t srclen;
1236 {
1237 int di, si;
1238
1239 for (di = si = 0;
1240 src[si] != '\0' && di < dstlen && si < srclen;
1241 di++, si++) {
1242 switch (src[si]) {
1243 case '\\':
1244 case ' ':
1245 case '\t':
1246 case '\r':
1247 case '\n':
1248 case '"':
1249 dst[di++] = '\\';
1250 if (di >= dstlen)
1251 break;
1252 /* FALLTHROUGH */
1253 default:
1254 dst[di] = src[si];
1255 }
1256 }
1257 dst[di] = '\0';
1258 }
1259
1260 /*
1261 * Internal version of connect(2); sets socket buffer sizes first.
1262 */
1263 int
1264 xconnect(sock, name, namelen)
1265 int sock;
1266 const struct sockaddr *name;
1267 int namelen;
1268 {
1269
1270 setupsockbufsize(sock);
1271 return (connect(sock, name, namelen));
1272 }
1273
1274 /*
1275 * Internal version of listen(2); sets socket buffer sizes first.
1276 */
1277 int
1278 xlisten(sock, backlog)
1279 int sock, backlog;
1280 {
1281
1282 setupsockbufsize(sock);
1283 return (listen(sock, backlog));
1284 }
1285
1286 void *
1287 xmalloc(size)
1288 size_t size;
1289 {
1290 void *p;
1291
1292 p = malloc(size);
1293 if (p == NULL)
1294 err(1, "Unable to allocate %ld bytes of memory", (long)size);
1295 return (p);
1296 }
1297
1298 char *
1299 xstrdup(str)
1300 const char *str;
1301 {
1302 char *s;
1303
1304 if (str == NULL)
1305 errx(1, "xstrdup() called with NULL argument");
1306 s = strdup(str);
1307 if (s == NULL)
1308 err(1, "Unable to allocate memory for string copy");
1309 return (s);
1310 }
1311
1312 sig_t
1313 xsignal(sig, func)
1314 int sig;
1315 void (*func) __P((int));
1316 {
1317 struct sigaction act, oact;
1318
1319 act.sa_handler = func;
1320 sigemptyset(&act.sa_mask);
1321 act.sa_flags = SA_RESTART;
1322 if (sigaction(sig, &act, &oact) < 0)
1323 return (SIG_ERR);
1324 return (oact.sa_handler);
1325 }
1326