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