util.c revision 1.46.2.3 1 /* $NetBSD: util.c,v 1.46.2.3 2000/02/12 16:53:41 he 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.46.2.3 2000/02/12 16:53:41 he 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 if (*tmp == '\0')
316 user = myname;
317 else
318 user = tmp;
319 }
320
321 if (gatemode) {
322 char *nuser;
323 int len;
324
325 len = strlen(user) + 1 + strlen(host) + 1;
326 nuser = xmalloc(len);
327 snprintf(nuser, len, "%s@%s", user, host);
328 user = nuser;
329 freeuser = 1;
330 }
331
332 n = command("USER %s", user);
333 if (n == CONTINUE) {
334 if (pass == NULL)
335 pass = getpass("Password:");
336 n = command("PASS %s", pass);
337 }
338 if (n == CONTINUE) {
339 aflag++;
340 if (acct == NULL) {
341 acct = getpass("Account:");
342 freeacct = 0;
343 }
344 if (acct[0] == '\0') {
345 warnx("Login failed.");
346 goto cleanup_ftp_login;
347 }
348 n = command("ACCT %s", acct);
349 }
350 if ((n != COMPLETE) ||
351 (!aflag && acct != NULL && command("ACCT %s", acct) != COMPLETE)) {
352 warnx("Login failed.");
353 goto cleanup_ftp_login;
354 }
355 rval = 1;
356 if (proxy)
357 goto cleanup_ftp_login;
358
359 connected = -1;
360 for (n = 0; n < macnum; ++n) {
361 if (!strcmp("init", macros[n].mac_name)) {
362 (void)strcpy(line, "$init");
363 makeargv();
364 domacro(margc, margv);
365 break;
366 }
367 }
368 cleanup_ftp_login:
369 if (user != NULL && freeuser)
370 free((char *)user);
371 if (pass != NULL && freepass)
372 free((char *)pass);
373 if (acct != NULL && freeacct)
374 free((char *)acct);
375 return (rval);
376 }
377
378 /*
379 * `another' gets another argument, and stores the new argc and argv.
380 * It reverts to the top level (via main.c's intr()) on EOF/error.
381 *
382 * Returns false if no new arguments have been added.
383 */
384 int
385 another(pargc, pargv, prompt)
386 int *pargc;
387 char ***pargv;
388 const char *prompt;
389 {
390 int len = strlen(line), ret;
391
392 if (len >= sizeof(line) - 3) {
393 fputs("sorry, arguments too long.\n", ttyout);
394 intr();
395 }
396 fprintf(ttyout, "(%s) ", prompt);
397 line[len++] = ' ';
398 if (fgets(&line[len], sizeof(line) - len, stdin) == NULL)
399 intr();
400 len += strlen(&line[len]);
401 if (len > 0 && line[len - 1] == '\n')
402 line[len - 1] = '\0';
403 makeargv();
404 ret = margc > *pargc;
405 *pargc = margc;
406 *pargv = margv;
407 return (ret);
408 }
409
410 /*
411 * glob files given in argv[] from the remote server.
412 * if errbuf isn't NULL, store error messages there instead
413 * of writing to the screen.
414 */
415 char *
416 remglob(argv, doswitch, errbuf)
417 char *argv[];
418 int doswitch;
419 char **errbuf;
420 {
421 char temp[MAXPATHLEN];
422 static char buf[MAXPATHLEN];
423 static FILE *ftemp = NULL;
424 static char **args;
425 int oldverbose, oldhash, fd;
426 char *cp, *mode;
427
428 if (!mflag) {
429 if (!doglob)
430 args = NULL;
431 else {
432 if (ftemp) {
433 (void)fclose(ftemp);
434 ftemp = NULL;
435 }
436 }
437 return (NULL);
438 }
439 if (!doglob) {
440 if (args == NULL)
441 args = argv;
442 if ((cp = *++args) == NULL)
443 args = NULL;
444 return (cp);
445 }
446 if (ftemp == NULL) {
447 (void)snprintf(temp, sizeof(temp), "%s/%s", tmpdir, TMPFILE);
448 if ((fd = mkstemp(temp)) < 0) {
449 warn("unable to create temporary file %s", temp);
450 return (NULL);
451 }
452 close(fd);
453 oldverbose = verbose;
454 verbose = (errbuf != NULL) ? -1 : 0;
455 oldhash = hash;
456 hash = 0;
457 if (doswitch)
458 pswitch(!proxy);
459 for (mode = "w"; *++argv != NULL; mode = "a")
460 recvrequest("NLST", temp, *argv, mode, 0, 0);
461 if ((code / 100) != COMPLETE) {
462 if (errbuf != NULL)
463 *errbuf = reply_string;
464 }
465 if (doswitch)
466 pswitch(!proxy);
467 verbose = oldverbose;
468 hash = oldhash;
469 ftemp = fopen(temp, "r");
470 (void)unlink(temp);
471 if (ftemp == NULL) {
472 if (errbuf == NULL)
473 fputs(
474 "can't find list of remote files, oops.\n",
475 ttyout);
476 else
477 *errbuf =
478 "can't find list of remote files, oops.";
479 return (NULL);
480 }
481 }
482 if (fgets(buf, sizeof(buf), ftemp) == NULL) {
483 (void)fclose(ftemp);
484 ftemp = NULL;
485 return (NULL);
486 }
487 if ((cp = strchr(buf, '\n')) != NULL)
488 *cp = '\0';
489 return (buf);
490 }
491
492 int
493 confirm(cmd, file)
494 const char *cmd, *file;
495 {
496 char line[BUFSIZ];
497
498 if (!interactive || confirmrest)
499 return (1);
500 fprintf(ttyout, "%s %s? ", cmd, file);
501 (void)fflush(ttyout);
502 if (fgets(line, sizeof(line), stdin) == NULL)
503 return (0);
504 switch (tolower(*line)) {
505 case 'n':
506 return (0);
507 case 'p':
508 interactive = 0;
509 fputs("Interactive mode: off.\n", ttyout);
510 break;
511 case 'a':
512 confirmrest = 1;
513 fprintf(ttyout, "Prompting off for duration of %s.\n",
514 cmd);
515 break;
516 }
517 return (1);
518 }
519
520 /*
521 * Glob a local file name specification with
522 * the expectation of a single return value.
523 * Can't control multiple values being expanded
524 * from the expression, we return only the first.
525 */
526 int
527 globulize(cpp)
528 char **cpp;
529 {
530 glob_t gl;
531 int flags;
532
533 if (!doglob)
534 return (1);
535
536 flags = GLOB_BRACE|GLOB_NOCHECK|GLOB_TILDE;
537 memset(&gl, 0, sizeof(gl));
538 if (glob(*cpp, flags, NULL, &gl) || gl.gl_pathc == 0) {
539 warnx("%s: not found", *cpp);
540 globfree(&gl);
541 return (0);
542 }
543 /* XXX: caller should check if *cpp changed, and
544 * free(*cpp) if that is the case
545 */
546 *cpp = xstrdup(gl.gl_pathv[0]);
547 globfree(&gl);
548 return (1);
549 }
550
551 /*
552 * determine size of remote file
553 */
554 off_t
555 remotesize(file, noisy)
556 const char *file;
557 int noisy;
558 {
559 int overbose;
560 off_t size;
561
562 overbose = verbose;
563 size = -1;
564 if (debug == 0)
565 verbose = -1;
566 if (command("SIZE %s", file) == COMPLETE) {
567 char *cp, *ep;
568
569 cp = strchr(reply_string, ' ');
570 if (cp != NULL) {
571 cp++;
572 #ifndef NO_QUAD
573 size = strtoq(cp, &ep, 10);
574 #else
575 size = strtol(cp, &ep, 10);
576 #endif
577 if (*ep != '\0' && !isspace((unsigned char)*ep))
578 size = -1;
579 }
580 } else if (noisy && debug == 0) {
581 fputs(reply_string, ttyout);
582 putc('\n', ttyout);
583 }
584 verbose = overbose;
585 return (size);
586 }
587
588 /*
589 * determine last modification time (in GMT) of remote file
590 */
591 time_t
592 remotemodtime(file, noisy)
593 const char *file;
594 int noisy;
595 {
596 int overbose;
597 time_t rtime;
598 int ocode;
599
600 overbose = verbose;
601 ocode = code;
602 rtime = -1;
603 if (debug == 0)
604 verbose = -1;
605 if (command("MDTM %s", file) == COMPLETE) {
606 struct tm timebuf;
607 char *timestr, *frac;
608 int yy, mo, day, hour, min, sec;
609
610 /*
611 * time-val = 14DIGIT [ "." 1*DIGIT ]
612 * YYYYMMDDHHMMSS[.sss]
613 * mdtm-response = "213" SP time-val CRLF / error-response
614 */
615 timestr = reply_string + 4;
616
617 /*
618 * parse fraction.
619 * XXX: ignored for now
620 */
621 frac = strchr(timestr, '\r');
622 if (frac != NULL)
623 *frac = '\0';
624 frac = strchr(timestr, '.');
625 if (frac != NULL)
626 *frac++ = '\0';
627 if (strlen(timestr) == 15 && strncmp(timestr, "191", 3) == 0) {
628 /*
629 * XXX: Workaround for lame ftpd's that return
630 * `19100' instead of `2000'
631 */
632 fprintf(ttyout,
633 "Y2K warning! Incorrect time-val `%s' received from server.\n",
634 timestr);
635 timestr++;
636 timestr[0] = '2';
637 timestr[1] = '0';
638 fprintf(ttyout, "Converted to `%s'\n", timestr);
639 }
640 if (strlen(timestr) != 14 ||
641 sscanf(timestr, "%04d%02d%02d%02d%02d%02d",
642 &yy, &mo, &day, &hour, &min, &sec) != 6) {
643 bad_parse_time:
644 fprintf(ttyout, "Can't parse time `%s'.\n", timestr);
645 goto cleanup_parse_time;
646 }
647 memset(&timebuf, 0, sizeof(timebuf));
648 timebuf.tm_sec = sec;
649 timebuf.tm_min = min;
650 timebuf.tm_hour = hour;
651 timebuf.tm_mday = day;
652 timebuf.tm_mon = mo - 1;
653 timebuf.tm_year = yy - TM_YEAR_BASE;
654 timebuf.tm_isdst = -1;
655 rtime = mkgmtime(&timebuf);
656 if (rtime == -1) {
657 if (noisy || debug != 0)
658 goto bad_parse_time;
659 else
660 goto cleanup_parse_time;
661 } else if (debug)
662 fprintf(ttyout, "parsed date as: %s", ctime(&rtime));
663 } else if (noisy && debug == 0) {
664 fputs(reply_string, ttyout);
665 putc('\n', ttyout);
666 }
667 cleanup_parse_time:
668 verbose = overbose;
669 if (rtime == -1)
670 code = ocode;
671 return (rtime);
672 }
673
674 /*
675 * UTC version of mktime(3)
676 */
677 #ifdef HAVE_TIMEGM
678 time_t
679 mkgmtime(tm)
680 struct tm *tm;
681 {
682
683 /* This is very clean, but not portable at all. */
684 return (timegm(tm));
685 }
686
687 #else /* not HAVE_TIMEGM */
688
689 /*
690 * This code is not portable, but works on most Unix-like systems.
691 * If the local timezone has no summer time, using mktime(3) function
692 * and adjusting offset would be usable (adjusting leap seconds
693 * is still required, though), but the assumption is not always true.
694 *
695 * Anyway, no portable and correct implementation of UTC to time_t
696 * conversion exists....
697 */
698
699 static time_t
700 sub_mkgmt(tm)
701 struct tm *tm;
702 {
703 int y, nleapdays;
704 time_t t;
705 /* days before the month */
706 static const unsigned short moff[12] = {
707 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334
708 };
709
710 /*
711 * XXX This code assumes the given time to be normalized.
712 * Normalizing here is impossible in case the given time is a leap
713 * second but the local time library is ignorant of leap seconds.
714 */
715
716 /* minimal sanity checking not to access outside of the array */
717 if ((unsigned) tm->tm_mon >= 12)
718 return (time_t) -1;
719 if (tm->tm_year < EPOCH_YEAR - TM_YEAR_BASE)
720 return (time_t) -1;
721
722 y = tm->tm_year + TM_YEAR_BASE - (tm->tm_mon < 2);
723 nleapdays = y / 4 - y / 100 + y / 400 -
724 ((EPOCH_YEAR-1) / 4 - (EPOCH_YEAR-1) / 100 + (EPOCH_YEAR-1) / 400);
725 t = ((((time_t) (tm->tm_year - (EPOCH_YEAR - TM_YEAR_BASE)) * 365 +
726 moff[tm->tm_mon] + tm->tm_mday - 1 + nleapdays) * 24 +
727 tm->tm_hour) * 60 + tm->tm_min) * 60 + tm->tm_sec;
728
729 return (t < 0 ? (time_t) -1 : t);
730 }
731
732 time_t
733 mkgmtime(tm)
734 struct tm *tm;
735 {
736 time_t t, t2;
737 struct tm *tm2;
738 int sec;
739
740 /* Do the first guess. */
741 if ((t = sub_mkgmt(tm)) == (time_t) -1)
742 return (time_t) -1;
743
744 /* save value in case *tm is overwritten by gmtime() */
745 sec = tm->tm_sec;
746
747 tm2 = gmtime(&t);
748 if ((t2 = sub_mkgmt(tm2)) == (time_t) -1)
749 return (time_t) -1;
750
751 if (t2 < t || tm2->tm_sec != sec) {
752 /*
753 * Adjust for leap seconds.
754 *
755 * real time_t time
756 * |
757 * tm
758 * / ... (a) first sub_mkgmt() conversion
759 * t
760 * |
761 * tm2
762 * / ... (b) second sub_mkgmt() conversion
763 * t2
764 * --->time
765 */
766 /*
767 * Do the second guess, assuming (a) and (b) are almost equal.
768 */
769 t += t - t2;
770 tm2 = gmtime(&t);
771
772 /*
773 * Either (a) or (b), may include one or two extra
774 * leap seconds. Try t, t + 2, t - 2, t + 1, and t - 1.
775 */
776 if (tm2->tm_sec == sec
777 || (t += 2, tm2 = gmtime(&t), tm2->tm_sec == sec)
778 || (t -= 4, tm2 = gmtime(&t), tm2->tm_sec == sec)
779 || (t += 3, tm2 = gmtime(&t), tm2->tm_sec == sec)
780 || (t -= 2, tm2 = gmtime(&t), tm2->tm_sec == sec))
781 ; /* found */
782 else {
783 /*
784 * Not found.
785 */
786 if (sec >= 60)
787 /*
788 * The given time is a leap second
789 * (sec 60 or 61), but the time library
790 * is ignorant of the leap second.
791 */
792 ; /* treat sec 60 as 59,
793 sec 61 as 0 of the next minute */
794 else
795 /* The given time may not be normalized. */
796 t++; /* restore t */
797 }
798 }
799
800 return (t < 0 ? (time_t) -1 : t);
801 }
802 #endif /* not HAVE_TIMEGM */
803
804 #ifndef NO_PROGRESS
805
806 /*
807 * return non-zero if we're the current foreground process
808 */
809 int
810 foregroundproc()
811 {
812 static pid_t pgrp = -1;
813 int ctty_pgrp;
814
815 if (pgrp == -1)
816 pgrp = getpgrp();
817
818 return ((ioctl(fileno(ttyout), TIOCGPGRP, &ctty_pgrp) != -1 &&
819 ctty_pgrp == (int)pgrp));
820 }
821
822
823 static void updateprogressmeter __P((int));
824
825 static void
826 updateprogressmeter(dummy)
827 int dummy;
828 {
829
830 progressmeter(0);
831 }
832 #endif /* NO_PROGRESS */
833
834
835 /*
836 * List of order of magnitude prefixes.
837 * The last is `P', as 2^64 = 16384 Petabytes
838 */
839 static const char prefixes[] = " KMGTP";
840
841 /*
842 * Display a transfer progress bar if progress is non-zero.
843 * SIGALRM is hijacked for use by this function.
844 * - Before the transfer, set filesize to size of file (or -1 if unknown),
845 * and call with flag = -1. This starts the once per second timer,
846 * and a call to updateprogressmeter() upon SIGALRM.
847 * - During the transfer, updateprogressmeter will call progressmeter
848 * with flag = 0
849 * - After the transfer, call with flag = 1
850 */
851 #ifndef NO_PROGRESS
852 static struct timeval start;
853 static struct timeval lastupdate;
854 #endif
855
856 void
857 progressmeter(flag)
858 int flag;
859 {
860 #ifndef NO_PROGRESS
861 static off_t lastsize;
862 struct timeval now, td, wait;
863 off_t cursize, abbrevsize, bytespersec;
864 double elapsed;
865 int ratio, barlength, i, len, remaining;
866 char buf[256];
867
868 len = 0;
869 if (flag == -1) {
870 (void)gettimeofday(&start, NULL);
871 lastupdate = start;
872 lastsize = restart_point;
873 }
874 if (!progress || filesize <= 0)
875 return;
876
877 (void)gettimeofday(&now, NULL);
878 cursize = bytes + restart_point;
879 timersub(&now, &lastupdate, &wait);
880 if (cursize > lastsize) {
881 lastupdate = now;
882 lastsize = cursize;
883 if (wait.tv_sec >= STALLTIME) { /* fudge out stalled time */
884 start.tv_sec += wait.tv_sec;
885 start.tv_usec += wait.tv_usec;
886 }
887 wait.tv_sec = 0;
888 }
889
890 /*
891 * print progress bar only if we are foreground process.
892 */
893 if (! foregroundproc())
894 return;
895
896 ratio = (int)((double)cursize * 100.0 / (double)filesize);
897 ratio = MAX(ratio, 0);
898 ratio = MIN(ratio, 100);
899 len += snprintf(buf + len, sizeof(buf) - len, "\r%3d%% ", ratio);
900
901 barlength = ttywidth - 43;
902 if (barlength > 0) {
903 i = barlength * ratio / 100;
904 len += snprintf(buf + len, sizeof(buf) - len,
905 "|%.*s%*s|", i,
906 "*****************************************************************************"
907 "*****************************************************************************",
908 barlength - i, "");
909 }
910
911 abbrevsize = cursize;
912 for (i = 0; abbrevsize >= 100000 && i < sizeof(prefixes); i++)
913 abbrevsize >>= 10;
914 len += snprintf(buf + len, sizeof(buf) - len,
915 #ifndef NO_QUAD
916 " %5qd %c%c ", (long long)abbrevsize,
917 #else
918 " %5ld %c%c ", (long)abbrevsize,
919 #endif
920 prefixes[i],
921 i == 0 ? ' ' : 'B');
922
923 timersub(&now, &start, &td);
924 elapsed = td.tv_sec + (td.tv_usec / 1000000.0);
925
926 bytespersec = 0;
927 if (bytes > 0) {
928 bytespersec = bytes;
929 if (elapsed > 0.0)
930 bytespersec /= elapsed;
931 }
932 for (i = 1; bytespersec >= 1024000 && i < sizeof(prefixes); i++)
933 bytespersec >>= 10;
934 len += snprintf(buf + len, sizeof(buf) - len,
935 #ifndef NO_QUAD
936 " %3qd.%02d %cB/s ", (long long)bytespersec / 1024,
937 #else
938 " %3ld.%02d %cB/s ", (long)bytespersec / 1024,
939 #endif
940 (int)((bytespersec % 1024) * 100 / 1024),
941 prefixes[i]);
942
943 if (bytes <= 0 || elapsed <= 0.0 || cursize > filesize) {
944 len += snprintf(buf + len, sizeof(buf) - len,
945 " --:-- ETA");
946 } else if (wait.tv_sec >= STALLTIME) {
947 len += snprintf(buf + len, sizeof(buf) - len,
948 " - stalled -");
949 } else {
950 remaining = (int)
951 ((filesize - restart_point) / (bytes / elapsed) - elapsed);
952 if (remaining >= 100 * SECSPERHOUR)
953 len += snprintf(buf + len, sizeof(buf) - len,
954 " --:-- ETA");
955 else {
956 i = remaining / SECSPERHOUR;
957 if (i)
958 len += snprintf(buf + len, sizeof(buf) - len,
959 "%2d:", i);
960 else
961 len += snprintf(buf + len, sizeof(buf) - len,
962 " ");
963 i = remaining % SECSPERHOUR;
964 len += snprintf(buf + len, sizeof(buf) - len,
965 "%02d:%02d ETA", i / 60, i % 60);
966 }
967 }
968 (void)write(fileno(ttyout), buf, len);
969
970 if (flag == -1) {
971 (void)xsignal(SIGALRM, updateprogressmeter);
972 alarmtimer(1); /* set alarm timer for 1 Hz */
973 } else if (flag == 1) {
974 (void)xsignal(SIGALRM, SIG_DFL);
975 alarmtimer(0);
976 (void)putc('\n', ttyout);
977 }
978 fflush(ttyout);
979 #endif /* NO_PROGRESS */
980 }
981
982 /*
983 * Display transfer statistics.
984 * Requires start to be initialised by progressmeter(-1),
985 * direction to be defined by xfer routines, and filesize and bytes
986 * to be updated by xfer routines
987 * If siginfo is nonzero, an ETA is displayed, and the output goes to stderr
988 * instead of ttyout.
989 */
990 void
991 ptransfer(siginfo)
992 int siginfo;
993 {
994 #ifndef NO_PROGRESS
995 struct timeval now, td, wait;
996 double elapsed;
997 off_t bytespersec;
998 int remaining, hh, i, len;
999 char buf[100];
1000
1001 if (!verbose && !siginfo)
1002 return;
1003
1004 (void)gettimeofday(&now, NULL);
1005 timersub(&now, &start, &td);
1006 elapsed = td.tv_sec + (td.tv_usec / 1000000.0);
1007 bytespersec = 0;
1008 if (bytes > 0) {
1009 bytespersec = bytes;
1010 if (elapsed > 0.0)
1011 bytespersec /= elapsed;
1012 }
1013 len = 0;
1014 len += snprintf(buf + len, sizeof(buf) - len,
1015 #ifndef NO_QUAD
1016 "%qd byte%s %s in ", (long long)bytes,
1017 #else
1018 "%ld byte%s %s in ", (long)bytes,
1019 #endif
1020 bytes == 1 ? "" : "s", direction);
1021 remaining = (int)elapsed;
1022 if (remaining > SECSPERDAY) {
1023 int days;
1024
1025 days = remaining / SECSPERDAY;
1026 remaining %= SECSPERDAY;
1027 len += snprintf(buf + len, sizeof(buf) - len,
1028 "%d day%s ", days, days == 1 ? "" : "s");
1029 }
1030 hh = remaining / SECSPERHOUR;
1031 remaining %= SECSPERHOUR;
1032 if (hh)
1033 len += snprintf(buf + len, sizeof(buf) - len, "%2d:", hh);
1034 len += snprintf(buf + len, sizeof(buf) - len,
1035 "%02d:%02d ", remaining / 60, remaining % 60);
1036
1037 for (i = 1; bytespersec >= 1024000 && i < sizeof(prefixes); i++)
1038 bytespersec >>= 10;
1039 len += snprintf(buf + len, sizeof(buf) - len,
1040 #ifndef NO_QUAD
1041 "(%qd.%02d %cB/s)", (long long)bytespersec / 1024,
1042 #else
1043 "(%ld.%02d %cB/s)", (long)bytespersec / 1024,
1044 #endif
1045 (int)((bytespersec % 1024) * 100 / 1024),
1046 prefixes[i]);
1047
1048 if (siginfo && bytes > 0 && elapsed > 0.0 && filesize >= 0
1049 && bytes + restart_point <= filesize) {
1050 remaining = (int)((filesize - restart_point) /
1051 (bytes / elapsed) - elapsed);
1052 hh = remaining / SECSPERHOUR;
1053 remaining %= SECSPERHOUR;
1054 len += snprintf(buf + len, sizeof(buf) - len, " ETA: ");
1055 if (hh)
1056 len += snprintf(buf + len, sizeof(buf) - len, "%2d:",
1057 hh);
1058 len += snprintf(buf + len, sizeof(buf) - len,
1059 "%02d:%02d", remaining / 60, remaining % 60);
1060 timersub(&now, &lastupdate, &wait);
1061 if (wait.tv_sec >= STALLTIME)
1062 len += snprintf(buf + len, sizeof(buf) - len,
1063 " (stalled)");
1064 }
1065 len += snprintf(buf + len, sizeof(buf) - len, "\n");
1066 (void)write(siginfo ? STDERR_FILENO : fileno(ttyout), buf, len);
1067 #endif /* NO_PROGRESS */
1068 }
1069
1070 /*
1071 * List words in stringlist, vertically arranged
1072 */
1073 void
1074 list_vertical(sl)
1075 StringList *sl;
1076 {
1077 int i, j, w;
1078 int columns, width, lines, items;
1079 char *p;
1080
1081 width = items = 0;
1082
1083 for (i = 0 ; i < sl->sl_cur ; i++) {
1084 w = strlen(sl->sl_str[i]);
1085 if (w > width)
1086 width = w;
1087 }
1088 width = (width + 8) &~ 7;
1089
1090 columns = ttywidth / width;
1091 if (columns == 0)
1092 columns = 1;
1093 lines = (sl->sl_cur + columns - 1) / columns;
1094 for (i = 0; i < lines; i++) {
1095 for (j = 0; j < columns; j++) {
1096 p = sl->sl_str[j * lines + i];
1097 if (p)
1098 fputs(p, ttyout);
1099 if (j * lines + i + lines >= sl->sl_cur) {
1100 putc('\n', ttyout);
1101 break;
1102 }
1103 w = strlen(p);
1104 while (w < width) {
1105 w = (w + 8) &~ 7;
1106 (void)putc('\t', ttyout);
1107 }
1108 }
1109 }
1110 }
1111
1112 /*
1113 * Update the global ttywidth value, using TIOCGWINSZ.
1114 */
1115 void
1116 setttywidth(a)
1117 int a;
1118 {
1119 struct winsize winsize;
1120
1121 if (ioctl(fileno(ttyout), TIOCGWINSZ, &winsize) != -1 &&
1122 winsize.ws_col != 0)
1123 ttywidth = winsize.ws_col;
1124 else
1125 ttywidth = 80;
1126 }
1127
1128 /*
1129 * Set the SIGALRM interval timer for wait seconds, 0 to disable.
1130 */
1131 void
1132 alarmtimer(wait)
1133 int wait;
1134 {
1135 struct itimerval itv;
1136
1137 itv.it_value.tv_sec = wait;
1138 itv.it_value.tv_usec = 0;
1139 itv.it_interval = itv.it_value;
1140 setitimer(ITIMER_REAL, &itv, NULL);
1141 }
1142
1143 /*
1144 * Setup or cleanup EditLine structures
1145 */
1146 #ifndef NO_EDITCOMPLETE
1147 void
1148 controlediting()
1149 {
1150 if (editing && el == NULL && hist == NULL) {
1151 HistEvent ev;
1152 int editmode;
1153
1154 el = el_init(__progname, stdin, ttyout, stderr);
1155 /* init editline */
1156 hist = history_init(); /* init the builtin history */
1157 history(hist, &ev, H_SETSIZE, 100);/* remember 100 events */
1158 el_set(el, EL_HIST, history, hist); /* use history */
1159
1160 el_set(el, EL_EDITOR, "emacs"); /* default editor is emacs */
1161 el_set(el, EL_PROMPT, prompt); /* set the prompt function */
1162
1163 /* add local file completion, bind to TAB */
1164 el_set(el, EL_ADDFN, "ftp-complete",
1165 "Context sensitive argument completion",
1166 complete);
1167 el_set(el, EL_BIND, "^I", "ftp-complete", NULL);
1168 el_source(el, NULL); /* read ~/.editrc */
1169 if ((el_get(el, EL_EDITMODE, &editmode) != -1) && editmode == 0)
1170 editing = 0; /* the user doesn't want editing,
1171 * so disable, and let statement
1172 * below cleanup */
1173 else
1174 el_set(el, EL_SIGNAL, 1);
1175 }
1176 if (!editing) {
1177 if (hist) {
1178 history_end(hist);
1179 hist = NULL;
1180 }
1181 if (el) {
1182 el_end(el);
1183 el = NULL;
1184 }
1185 }
1186 }
1187 #endif /* !NO_EDITCOMPLETE */
1188
1189 /*
1190 * Parse the specified socket buffer size.
1191 */
1192 int
1193 getsockbufsize(arg)
1194 const char *arg;
1195 {
1196 char *cp;
1197 int val;
1198
1199 if (!isdigit((unsigned char)arg[0]))
1200 return (-1);
1201
1202 val = strtol(arg, &cp, 10);
1203 if (cp != NULL) {
1204 if (cp[1] != '\0')
1205 return (-1);
1206 if (cp[0] == 'k')
1207 val *= 1024;
1208 if (cp[0] == 'm')
1209 val *= 1024 * 1024;
1210 }
1211
1212 if (val < 0)
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