util.c revision 1.87 1 /* $NetBSD: util.c,v 1.87 2000/01/25 06:11:00 lukem Exp $ */
2
3 /*-
4 * Copyright (c) 1997-1999 The NetBSD Foundation, Inc.
5 * All rights reserved.
6 *
7 * This code is derived from software contributed to The NetBSD Foundation
8 * by Luke Mewburn.
9 *
10 * This code is derived from software contributed to The NetBSD Foundation
11 * by Jason R. Thorpe of the Numerical Aerospace Simulation Facility,
12 * NASA Ames Research Center.
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.87 2000/01/25 06:11:00 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 <netinet/in.h>
89 #include <arpa/ftp.h>
90
91 #include <ctype.h>
92 #include <err.h>
93 #include <errno.h>
94 #include <fcntl.h>
95 #include <glob.h>
96 #include <signal.h>
97 #include <limits.h>
98 #include <pwd.h>
99 #include <stdio.h>
100 #include <stdlib.h>
101 #include <string.h>
102 #include <termios.h>
103 #include <time.h>
104 #include <tzfile.h>
105 #include <unistd.h>
106
107 #include "ftp_var.h"
108
109 /*
110 * Connect to peer server and
111 * auto-login, if possible.
112 */
113 void
114 setpeer(argc, argv)
115 int argc;
116 char *argv[];
117 {
118 char *host;
119 char *port;
120
121 if (argc == 0)
122 goto usage;
123 if (connected) {
124 fprintf(ttyout, "Already connected to %s, use close first.\n",
125 hostname);
126 code = -1;
127 return;
128 }
129 if (argc < 2)
130 (void)another(&argc, &argv, "to");
131 if (argc < 2 || argc > 3) {
132 usage:
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 port = argv[2];
143
144 if (gatemode) {
145 if (gateserver == NULL || *gateserver == '\0')
146 errx(1, "gateserver not defined (shouldn't happen)");
147 host = hookup(gateserver, port);
148 } else
149 host = hookup(argv[1], port);
150
151 if (host) {
152 int overbose;
153
154 if (gatemode && verbose) {
155 fprintf(ttyout,
156 "Connecting via pass-through server %s\n",
157 gateserver);
158 }
159
160 connected = 1;
161 /*
162 * Set up defaults for FTP.
163 */
164 (void)strlcpy(typename, "ascii", sizeof(typename));
165 type = TYPE_A;
166 curtype = TYPE_A;
167 (void)strlcpy(formname, "non-print", sizeof(formname));
168 form = FORM_N;
169 (void)strlcpy(modename, "stream", sizeof(modename));
170 mode = MODE_S;
171 (void)strlcpy(structname, "file", sizeof(structname));
172 stru = STRU_F;
173 (void)strlcpy(bytename, "8", sizeof(bytename));
174 bytesize = 8;
175 if (autologin)
176 (void)ftp_login(argv[1], NULL, NULL);
177
178 overbose = verbose;
179 if (debug == 0)
180 verbose = -1;
181 if (command("SYST") == COMPLETE && overbose) {
182 char *cp, c;
183 c = 0;
184 cp = strchr(reply_string + 4, ' ');
185 if (cp == NULL)
186 cp = strchr(reply_string + 4, '\r');
187 if (cp) {
188 if (cp[-1] == '.')
189 cp--;
190 c = *cp;
191 *cp = '\0';
192 }
193
194 fprintf(ttyout, "Remote system type is %s.\n",
195 reply_string + 4);
196 if (cp)
197 *cp = c;
198 }
199 if (!strncmp(reply_string, "215 UNIX Type: L8", 17)) {
200 if (proxy)
201 unix_proxy = 1;
202 else
203 unix_server = 1;
204 /*
205 * Set type to 0 (not specified by user),
206 * meaning binary by default, but don't bother
207 * telling server. We can use binary
208 * for text files unless changed by the user.
209 */
210 type = 0;
211 (void)strlcpy(typename, "binary", sizeof(typename));
212 if (overbose)
213 fprintf(ttyout,
214 "Using %s mode to transfer files.\n",
215 typename);
216 } else {
217 if (proxy)
218 unix_proxy = 0;
219 else
220 unix_server = 0;
221 if (overbose &&
222 !strncmp(reply_string, "215 TOPS20", 10))
223 fputs(
224 "Remember to set tenex mode when transferring binary files from this machine.\n",
225 ttyout);
226 }
227 verbose = overbose;
228 }
229 }
230
231 /*
232 * Reset the various variables that indicate connection state back to
233 * disconnected settings.
234 * The caller is responsible for issuing any commands to the remote server
235 * to perform a clean shutdown before this is invoked.
236 */
237 void
238 cleanuppeer()
239 {
240
241 if (cout)
242 (void)fclose(cout);
243 cout = NULL;
244 connected = 0;
245 /*
246 * determine if anonftp was specifically set with -a
247 * (1), or implicitly set by auto_fetch() (2). in the
248 * latter case, disable after the current xfer
249 */
250 if (anonftp == 2)
251 anonftp = 0;
252 data = -1;
253 epsv4bad = 0;
254 if (username)
255 free(username);
256 username = NULL;
257 if (!proxy)
258 macnum = 0;
259 }
260
261 /*
262 * Top-level signal handler for interrupted commands.
263 */
264 void
265 intr(dummy)
266 int dummy;
267 {
268
269 alarmtimer(0);
270 if (fromatty)
271 write(fileno(ttyout), "\n", 1);
272 siglongjmp(toplevel, 1);
273 }
274
275 /*
276 * Signal handler for lost connections; cleanup various elements of
277 * the connection state, and call cleanuppeer() to finish it off.
278 */
279 void
280 lostpeer(dummy)
281 int dummy;
282 {
283 int oerrno = errno;
284
285 alarmtimer(0);
286 if (connected) {
287 if (cout != NULL) {
288 (void)shutdown(fileno(cout), 1+1);
289 (void)fclose(cout);
290 cout = NULL;
291 }
292 if (data >= 0) {
293 (void)shutdown(data, 1+1);
294 (void)close(data);
295 data = -1;
296 }
297 connected = 0;
298 }
299 pswitch(1);
300 if (connected) {
301 if (cout != NULL) {
302 (void)shutdown(fileno(cout), 1+1);
303 (void)fclose(cout);
304 cout = NULL;
305 }
306 connected = 0;
307 }
308 proxflag = 0;
309 pswitch(0);
310 cleanuppeer();
311 errno = oerrno;
312 }
313
314
315 /*
316 * login to remote host, using given username & password if supplied
317 */
318 int
319 ftp_login(host, user, pass)
320 const char *host;
321 const char *user, *pass;
322 {
323 char tmp[80];
324 const char *acct;
325 struct passwd *pw;
326 int n, aflag, rval, freeuser, freepass, freeacct;
327
328 acct = NULL;
329 aflag = rval = freeuser = freepass = freeacct = 0;
330
331 if (debug)
332 fprintf(ttyout, "ftp_login: user `%s' pass `%s' host `%s'\n",
333 user ? user : "<null>", pass ? pass : "<null>",
334 host ? host : "<null>");
335
336
337 /*
338 * Set up arguments for an anonymous FTP session, if necessary.
339 */
340 if (anonftp) {
341 user = "anonymous"; /* as per RFC 1635 */
342 pass = getoptionvalue("anonpass");
343 }
344
345 if (user == NULL)
346 freeuser = 1;
347 if (pass == NULL)
348 freepass = 1;
349 freeacct = 1;
350 if (ruserpass(host, &user, &pass, &acct) < 0) {
351 code = -1;
352 goto cleanup_ftp_login;
353 }
354
355 while (user == NULL) {
356 const char *myname = getlogin();
357
358 if (myname == NULL && (pw = getpwuid(getuid())) != NULL)
359 myname = pw->pw_name;
360 if (myname)
361 fprintf(ttyout, "Name (%s:%s): ", host, myname);
362 else
363 fprintf(ttyout, "Name (%s): ", host);
364 *tmp = '\0';
365 if (fgets(tmp, sizeof(tmp) - 1, stdin) == NULL) {
366 fprintf(ttyout, "\nEOF received; login aborted.\n");
367 clearerr(stdin);
368 code = -1;
369 goto cleanup_ftp_login;
370 }
371 tmp[strlen(tmp) - 1] = '\0';
372 freeuser = 0;
373 if (*tmp == '\0')
374 user = myname;
375 else
376 user = tmp;
377 }
378
379 if (gatemode) {
380 char *nuser;
381 int len;
382
383 len = strlen(user) + 1 + strlen(host) + 1;
384 nuser = xmalloc(len);
385 (void)strlcpy(nuser, user, len);
386 (void)strlcat(nuser, "@", len);
387 (void)strlcat(nuser, host, len);
388 freeuser = 1;
389 user = nuser;
390 }
391
392 n = command("USER %s", user);
393 if (n == CONTINUE) {
394 if (pass == NULL) {
395 freepass = 0;
396 pass = getpass("Password:");
397 }
398 n = command("PASS %s", pass);
399 }
400 if (n == CONTINUE) {
401 aflag++;
402 if (acct == NULL) {
403 freeacct = 0;
404 acct = getpass("Account:");
405 }
406 if (acct[0] == '\0') {
407 warnx("Login failed.");
408 goto cleanup_ftp_login;
409 }
410 n = command("ACCT %s", acct);
411 }
412 if ((n != COMPLETE) ||
413 (!aflag && acct != NULL && command("ACCT %s", acct) != COMPLETE)) {
414 warnx("Login failed.");
415 goto cleanup_ftp_login;
416 }
417 rval = 1;
418 username = xstrdup(user);
419 if (proxy)
420 goto cleanup_ftp_login;
421
422 connected = -1;
423 for (n = 0; n < macnum; ++n) {
424 if (!strcmp("init", macros[n].mac_name)) {
425 (void)strlcpy(line, "$init", sizeof(line));
426 makeargv();
427 domacro(margc, margv);
428 break;
429 }
430 }
431 updateremotepwd();
432
433 cleanup_ftp_login:
434 if (user != NULL && freeuser)
435 free((char *)user);
436 if (pass != NULL && freepass)
437 free((char *)pass);
438 if (acct != NULL && freeacct)
439 free((char *)acct);
440 return (rval);
441 }
442
443 /*
444 * `another' gets another argument, and stores the new argc and argv.
445 * It reverts to the top level (via intr()) on EOF/error.
446 *
447 * Returns false if no new arguments have been added.
448 */
449 int
450 another(pargc, pargv, prompt)
451 int *pargc;
452 char ***pargv;
453 const char *prompt;
454 {
455 int len = strlen(line), ret;
456
457 if (len >= sizeof(line) - 3) {
458 fputs("sorry, arguments too long.\n", ttyout);
459 intr(0);
460 }
461 fprintf(ttyout, "(%s) ", prompt);
462 line[len++] = ' ';
463 if (fgets(&line[len], sizeof(line) - len, stdin) == NULL) {
464 clearerr(stdin);
465 intr(0);
466 }
467 len += strlen(&line[len]);
468 if (len > 0 && line[len - 1] == '\n')
469 line[len - 1] = '\0';
470 makeargv();
471 ret = margc > *pargc;
472 *pargc = margc;
473 *pargv = margv;
474 return (ret);
475 }
476
477 /*
478 * glob files given in argv[] from the remote server.
479 * if errbuf isn't NULL, store error messages there instead
480 * of writing to the screen.
481 */
482 char *
483 remglob(argv, doswitch, errbuf)
484 char *argv[];
485 int doswitch;
486 char **errbuf;
487 {
488 char temp[MAXPATHLEN];
489 static char buf[MAXPATHLEN];
490 static FILE *ftemp = NULL;
491 static char **args;
492 int oldverbose, oldhash, fd, len;
493 char *cp, *mode;
494
495 if (!mflag || !connected) {
496 if (!doglob)
497 args = NULL;
498 else {
499 if (ftemp) {
500 (void)fclose(ftemp);
501 ftemp = NULL;
502 }
503 }
504 return (NULL);
505 }
506 if (!doglob) {
507 if (args == NULL)
508 args = argv;
509 if ((cp = *++args) == NULL)
510 args = NULL;
511 return (cp);
512 }
513 if (ftemp == NULL) {
514 len = strlcpy(temp, tmpdir, sizeof(temp));
515 if (temp[len - 1] != '/')
516 (void)strlcat(temp, "/", sizeof(temp));
517 (void)strlcat(temp, TMPFILE, sizeof(temp));
518 if ((fd = mkstemp(temp)) < 0) {
519 warn("unable to create temporary file %s", temp);
520 return (NULL);
521 }
522 close(fd);
523 oldverbose = verbose;
524 verbose = (errbuf != NULL) ? -1 : 0;
525 oldhash = hash;
526 hash = 0;
527 if (doswitch)
528 pswitch(!proxy);
529 for (mode = "w"; *++argv != NULL; mode = "a")
530 recvrequest("NLST", temp, *argv, mode, 0, 0);
531 if ((code / 100) != COMPLETE) {
532 if (errbuf != NULL)
533 *errbuf = reply_string;
534 }
535 if (doswitch)
536 pswitch(!proxy);
537 verbose = oldverbose;
538 hash = oldhash;
539 ftemp = fopen(temp, "r");
540 (void)unlink(temp);
541 if (ftemp == NULL) {
542 if (errbuf == NULL)
543 fputs(
544 "can't find list of remote files, oops.\n",
545 ttyout);
546 else
547 *errbuf =
548 "can't find list of remote files, oops.";
549 return (NULL);
550 }
551 }
552 if (fgets(buf, sizeof(buf), ftemp) == NULL) {
553 (void)fclose(ftemp);
554 ftemp = NULL;
555 return (NULL);
556 }
557 if ((cp = strchr(buf, '\n')) != NULL)
558 *cp = '\0';
559 return (buf);
560 }
561
562 /*
563 * Glob a local file name specification with the expectation of a single
564 * return value. Can't control multiple values being expanded from the
565 * expression, we return only the first.
566 * Returns NULL on error, or a pointer to a buffer containing the filename
567 * that's the caller's responsiblity to free(3) when finished with.
568 */
569 char *
570 globulize(pattern)
571 const char *pattern;
572 {
573 glob_t gl;
574 int flags;
575 char *p;
576
577 if (!doglob)
578 return (xstrdup(pattern));
579
580 flags = GLOB_BRACE|GLOB_NOCHECK|GLOB_TILDE;
581 memset(&gl, 0, sizeof(gl));
582 if (glob(pattern, flags, NULL, &gl) || gl.gl_pathc == 0) {
583 warnx("%s: not found", pattern);
584 globfree(&gl);
585 return (NULL);
586 }
587 p = xstrdup(gl.gl_pathv[0]);
588 globfree(&gl);
589 return (p);
590 }
591
592 /*
593 * determine size of remote file
594 */
595 off_t
596 remotesize(file, noisy)
597 const char *file;
598 int noisy;
599 {
600 int overbose;
601 off_t size;
602
603 overbose = verbose;
604 size = -1;
605 if (debug == 0)
606 verbose = -1;
607 if (command("SIZE %s", file) == COMPLETE) {
608 char *cp, *ep;
609
610 cp = strchr(reply_string, ' ');
611 if (cp != NULL) {
612 cp++;
613 #ifndef NO_QUAD
614 size = strtoq(cp, &ep, 10);
615 #else
616 size = strtol(cp, &ep, 10);
617 #endif
618 if (*ep != '\0' && !isspace((unsigned char)*ep))
619 size = -1;
620 }
621 } else if (noisy && debug == 0) {
622 fputs(reply_string, ttyout);
623 putc('\n', ttyout);
624 }
625 verbose = overbose;
626 return (size);
627 }
628
629 /*
630 * determine last modification time (in GMT) of remote file
631 */
632 time_t
633 remotemodtime(file, noisy)
634 const char *file;
635 int noisy;
636 {
637 int overbose;
638 time_t rtime;
639 int ocode;
640
641 overbose = verbose;
642 ocode = code;
643 rtime = -1;
644 if (debug == 0)
645 verbose = -1;
646 if (command("MDTM %s", file) == COMPLETE) {
647 struct tm timebuf;
648 char *timestr, *frac;
649
650 /*
651 * time-val = 14DIGIT [ "." 1*DIGIT ]
652 * YYYYMMDDHHMMSS[.sss]
653 * mdtm-response = "213" SP time-val CRLF / error-response
654 */
655 timestr = reply_string + 4;
656
657 /*
658 * parse fraction.
659 * XXX: ignored for now
660 */
661 frac = strchr(timestr, '\r');
662 if (frac != NULL)
663 *frac = '\0';
664 frac = strchr(timestr, '.');
665 if (frac != NULL)
666 *frac++ = '\0';
667 if (strlen(timestr) == 15 && strncmp(timestr, "191", 3) == 0) {
668 /*
669 * workaround lame ftpd's that return `19100'
670 * instead of `2000'
671 */
672 fprintf(ttyout,
673 "Y2K warning! Incorrect time-val `%s' received from server.\n",
674 timestr);
675 timestr++;
676 timestr[0] = '2';
677 timestr[1] = '0';
678 fprintf(ttyout, "Converted to `%s'\n", timestr);
679 }
680 if (strlen(timestr) != 14 ||
681 strptime(timestr, "%Y%m%d%H%M%S", &timebuf) == NULL) {
682 bad_parse_time:
683 fprintf(ttyout, "Can't parse time %s.\n", timestr);
684 goto cleanup_parse_time;
685 }
686 rtime = timegm(&timebuf);
687 if (rtime == -1 && (noisy || debug != 0))
688 goto bad_parse_time;
689 } else if (noisy && debug == 0) {
690 fputs(reply_string, ttyout);
691 putc('\n', ttyout);
692 }
693 cleanup_parse_time:
694 verbose = overbose;
695 if (rtime == -1)
696 code = ocode;
697 return (rtime);
698 }
699
700 /*
701 * update global `remotepwd', which contains the state of the remote cwd
702 */
703 void
704 updateremotepwd()
705 {
706 int overbose, ocode, i;
707 char *cp;
708
709 overbose = verbose;
710 ocode = code;
711 if (debug == 0)
712 verbose = -1;
713 if (command("PWD") != COMPLETE)
714 goto badremotepwd;
715 cp = strchr(reply_string, ' ');
716 if (cp == NULL || cp[0] == '\0' || cp[1] != '"')
717 goto badremotepwd;
718 cp += 2;
719 for (i = 0; *cp && i < sizeof(remotepwd) - 1; i++, cp++) {
720 if (cp[0] == '"') {
721 if (cp[1] == '"')
722 cp++;
723 else
724 break;
725 }
726 remotepwd[i] = *cp;
727 }
728 remotepwd[i] = '\0';
729 if (debug)
730 fprintf(ttyout, "got remotepwd as `%s'\n", remotepwd);
731 goto cleanupremotepwd;
732 badremotepwd:
733 remotepwd[0]='\0';
734 cleanupremotepwd:
735 verbose = overbose;
736 code = ocode;
737 }
738
739 #ifndef NO_PROGRESS
740
741 /*
742 * return non-zero if we're the current foreground process
743 */
744 int
745 foregroundproc()
746 {
747 static pid_t pgrp = -1;
748
749 if (pgrp == -1)
750 pgrp = getpgrp();
751
752 return (tcgetpgrp(fileno(ttyout)) == pgrp);
753 }
754
755
756 static void updateprogressmeter __P((int));
757
758 /*
759 * SIGALRM handler to update the progress meter
760 */
761 static void
762 updateprogressmeter(dummy)
763 int dummy;
764 {
765 int oerrno = errno;
766
767 progressmeter(0);
768 errno = oerrno;
769 }
770 #endif /* NO_PROGRESS */
771
772
773 /*
774 * List of order of magnitude prefixes.
775 * The last is `P', as 2^64 = 16384 Petabytes
776 */
777 static const char prefixes[] = " KMGTP";
778
779 /*
780 * Display a transfer progress bar if progress is non-zero.
781 * SIGALRM is hijacked for use by this function.
782 * - Before the transfer, set filesize to size of file (or -1 if unknown),
783 * and call with flag = -1. This starts the once per second timer,
784 * and a call to updateprogressmeter() upon SIGALRM.
785 * - During the transfer, updateprogressmeter will call progressmeter
786 * with flag = 0
787 * - After the transfer, call with flag = 1
788 */
789 static struct timeval start;
790 static struct timeval lastupdate;
791
792 #define BUFLEFT (sizeof(buf) - len)
793
794 void
795 progressmeter(flag)
796 int flag;
797 {
798 static off_t lastsize;
799 #ifndef NO_PROGRESS
800 struct timeval now, td, wait;
801 off_t cursize, abbrevsize, bytespersec;
802 double elapsed;
803 int ratio, barlength, i, len, remaining;
804
805 /*
806 * Work variables for progress bar.
807 *
808 * XXX: if the format of the progress bar changes
809 * (especially the number of characters in the
810 * `static' portion of it), be sure to update
811 * these appropriately.
812 */
813 char buf[256]; /* workspace for progress bar */
814 #define BAROVERHEAD 43 /* non `*' portion of progress bar */
815 /*
816 * stars should contain at least
817 * sizeof(buf) - BAROVERHEAD entries
818 */
819 const char stars[] =
820 "*****************************************************************************"
821 "*****************************************************************************"
822 "*****************************************************************************";
823
824 #endif
825
826 if (flag == -1) {
827 (void)gettimeofday(&start, NULL);
828 lastupdate = start;
829 lastsize = restart_point;
830 }
831 #ifndef NO_PROGRESS
832 len = 0;
833 if (!progress || filesize <= 0)
834 return;
835
836 (void)gettimeofday(&now, NULL);
837 cursize = bytes + restart_point;
838 timersub(&now, &lastupdate, &wait);
839 if (cursize > lastsize) {
840 lastupdate = now;
841 lastsize = cursize;
842 wait.tv_sec = 0;
843 }
844
845 /*
846 * print progress bar only if we are foreground process.
847 */
848 if (! foregroundproc())
849 return;
850
851 ratio = (int)((double)cursize * 100.0 / (double)filesize);
852 ratio = MAX(ratio, 0);
853 ratio = MIN(ratio, 100);
854 len += snprintf(buf + len, BUFLEFT, "\r%3d%% ", ratio);
855
856 /*
857 * calculate the length of the `*' bar, ensuring that
858 * the number of stars won't exceed the buffer size
859 */
860 barlength = MIN(sizeof(buf) - 1, ttywidth) - BAROVERHEAD;
861 if (barlength > 0) {
862 i = barlength * ratio / 100;
863 len += snprintf(buf + len, BUFLEFT,
864 "|%.*s%*s|", i, stars, barlength - i, "");
865 }
866
867 abbrevsize = cursize;
868 for (i = 0; abbrevsize >= 100000 && i < sizeof(prefixes); i++)
869 abbrevsize >>= 10;
870 len += snprintf(buf + len, BUFLEFT,
871 #ifndef NO_QUAD
872 " %5lld %c%c ", (long long)abbrevsize,
873 #else
874 " %5ld %c%c ", (long)abbrevsize,
875 #endif
876 prefixes[i],
877 i == 0 ? ' ' : 'B');
878
879 timersub(&now, &start, &td);
880 elapsed = td.tv_sec + (td.tv_usec / 1000000.0);
881
882 bytespersec = 0;
883 if (bytes > 0) {
884 bytespersec = bytes;
885 if (elapsed > 0.0)
886 bytespersec /= elapsed;
887 }
888 for (i = 1; bytespersec >= 1024000 && i < sizeof(prefixes); i++)
889 bytespersec >>= 10;
890 len += snprintf(buf + len, BUFLEFT,
891 #ifndef NO_QUAD
892 " %3lld.%02d %cB/s ", (long long)bytespersec / 1024,
893 #else
894 " %3ld.%02d %cB/s ", (long)bytespersec / 1024,
895 #endif
896 (int)((bytespersec % 1024) * 100 / 1024),
897 prefixes[i]);
898
899 if (bytes <= 0 || elapsed <= 0.0 || cursize > filesize) {
900 len += snprintf(buf + len, BUFLEFT, " --:-- ETA");
901 } else if (wait.tv_sec >= STALLTIME) {
902 len += snprintf(buf + len, BUFLEFT, " - stalled -");
903 } else {
904 remaining = (int)
905 ((filesize - restart_point) / (bytes / elapsed) - elapsed);
906 if (remaining >= 100 * SECSPERHOUR)
907 len += snprintf(buf + len, BUFLEFT, " --:-- ETA");
908 else {
909 i = remaining / SECSPERHOUR;
910 if (i)
911 len += snprintf(buf + len, BUFLEFT, "%2d:", i);
912 else
913 len += snprintf(buf + len, BUFLEFT, " ");
914 i = remaining % SECSPERHOUR;
915 len += snprintf(buf + len, BUFLEFT,
916 "%02d:%02d ETA", i / 60, i % 60);
917 }
918 }
919 if (flag == 1)
920 len += snprintf(buf + len, BUFLEFT, "\n");
921 (void)write(fileno(ttyout), buf, len);
922
923 if (flag == -1) {
924 (void)xsignal_restart(SIGALRM, updateprogressmeter, 1);
925 alarmtimer(1); /* set alarm timer for 1 Hz */
926 } else if (flag == 1) {
927 (void)xsignal(SIGALRM, SIG_DFL);
928 alarmtimer(0);
929 }
930 #endif /* !NO_PROGRESS */
931 }
932
933 /*
934 * Display transfer statistics.
935 * Requires start to be initialised by progressmeter(-1),
936 * direction to be defined by xfer routines, and filesize and bytes
937 * to be updated by xfer routines
938 * If siginfo is nonzero, an ETA is displayed, and the output goes to stderr
939 * instead of ttyout.
940 */
941 void
942 ptransfer(siginfo)
943 int siginfo;
944 {
945 struct timeval now, td, wait;
946 double elapsed;
947 off_t bytespersec;
948 int remaining, hh, i, len;
949
950 char buf[256]; /* Work variable for transfer status. */
951
952 if (!verbose && !progress && !siginfo)
953 return;
954
955 (void)gettimeofday(&now, NULL);
956 timersub(&now, &start, &td);
957 elapsed = td.tv_sec + (td.tv_usec / 1000000.0);
958 bytespersec = 0;
959 if (bytes > 0) {
960 bytespersec = bytes;
961 if (elapsed > 0.0)
962 bytespersec /= elapsed;
963 }
964 len = 0;
965 len += snprintf(buf + len, BUFLEFT,
966 #ifndef NO_QUAD
967 "%lld byte%s %s in ", (long long)bytes,
968 #else
969 "%ld byte%s %s in ", (long)bytes,
970 #endif
971 bytes == 1 ? "" : "s", direction);
972 remaining = (int)elapsed;
973 if (remaining > SECSPERDAY) {
974 int days;
975
976 days = remaining / SECSPERDAY;
977 remaining %= SECSPERDAY;
978 len += snprintf(buf + len, BUFLEFT,
979 "%d day%s ", days, days == 1 ? "" : "s");
980 }
981 hh = remaining / SECSPERHOUR;
982 remaining %= SECSPERHOUR;
983 if (hh)
984 len += snprintf(buf + len, BUFLEFT, "%2d:", hh);
985 len += snprintf(buf + len, BUFLEFT,
986 "%02d:%02d ", remaining / 60, remaining % 60);
987
988 for (i = 1; bytespersec >= 1024000 && i < sizeof(prefixes); i++)
989 bytespersec >>= 10;
990 len += snprintf(buf + len, BUFLEFT,
991 #ifndef NO_QUAD
992 "(%lld.%02d %cB/s)", (long long)bytespersec / 1024,
993 #else
994 "(%ld.%02d %cB/s)", (long)bytespersec / 1024,
995 #endif
996 (int)((bytespersec % 1024) * 100 / 1024),
997 prefixes[i]);
998
999 if (siginfo && bytes > 0 && elapsed > 0.0 && filesize >= 0
1000 && bytes + restart_point <= filesize) {
1001 remaining = (int)((filesize - restart_point) /
1002 (bytes / elapsed) - elapsed);
1003 hh = remaining / SECSPERHOUR;
1004 remaining %= SECSPERHOUR;
1005 len += snprintf(buf + len, BUFLEFT, " ETA: ");
1006 if (hh)
1007 len += snprintf(buf + len, BUFLEFT, "%2d:", hh);
1008 len += snprintf(buf + len, BUFLEFT, "%02d:%02d",
1009 remaining / 60, remaining % 60);
1010 timersub(&now, &lastupdate, &wait);
1011 if (wait.tv_sec >= STALLTIME)
1012 len += snprintf(buf + len, BUFLEFT, " (stalled)");
1013 }
1014 len += snprintf(buf + len, BUFLEFT, "\n");
1015 (void)write(siginfo ? STDERR_FILENO : fileno(ttyout), buf, len);
1016 }
1017
1018 /*
1019 * SIG{INFO,QUIT} handler to print transfer stats if a transfer is in progress
1020 */
1021 void
1022 psummary(notused)
1023 int notused;
1024 {
1025 int oerrno = errno;
1026
1027 if (bytes > 0) {
1028 if (fromatty)
1029 write(fileno(ttyout), "\n", 1);
1030 ptransfer(1);
1031 }
1032 errno = oerrno;
1033 }
1034
1035 /*
1036 * List words in stringlist, vertically arranged
1037 */
1038 void
1039 list_vertical(sl)
1040 StringList *sl;
1041 {
1042 int i, j, w;
1043 int columns, width, lines, items;
1044 char *p;
1045
1046 width = items = 0;
1047
1048 for (i = 0 ; i < sl->sl_cur ; i++) {
1049 w = strlen(sl->sl_str[i]);
1050 if (w > width)
1051 width = w;
1052 }
1053 width = (width + 8) &~ 7;
1054
1055 columns = ttywidth / width;
1056 if (columns == 0)
1057 columns = 1;
1058 lines = (sl->sl_cur + columns - 1) / columns;
1059 for (i = 0; i < lines; i++) {
1060 for (j = 0; j < columns; j++) {
1061 p = sl->sl_str[j * lines + i];
1062 if (p)
1063 fputs(p, ttyout);
1064 if (j * lines + i + lines >= sl->sl_cur) {
1065 putc('\n', ttyout);
1066 break;
1067 }
1068 w = strlen(p);
1069 while (w < width) {
1070 w = (w + 8) &~ 7;
1071 (void)putc('\t', ttyout);
1072 }
1073 }
1074 }
1075 }
1076
1077 /*
1078 * Update the global ttywidth value, using TIOCGWINSZ.
1079 */
1080 void
1081 setttywidth(a)
1082 int a;
1083 {
1084 struct winsize winsize;
1085 int oerrno = errno;
1086
1087 if (ioctl(fileno(ttyout), TIOCGWINSZ, &winsize) != -1 &&
1088 winsize.ws_col != 0)
1089 ttywidth = winsize.ws_col;
1090 else
1091 ttywidth = 80;
1092 errno = oerrno;
1093 }
1094
1095 /*
1096 * Change the rate limit up (SIGUSR1) or down (SIGUSR2)
1097 */
1098 void
1099 crankrate(sig)
1100 int sig;
1101 {
1102
1103 switch (sig) {
1104 case SIGUSR1:
1105 if (rate_get)
1106 rate_get += rate_get_incr;
1107 if (rate_put)
1108 rate_put += rate_put_incr;
1109 break;
1110 case SIGUSR2:
1111 if (rate_get && rate_get > rate_get_incr)
1112 rate_get -= rate_get_incr;
1113 if (rate_put && rate_put > rate_put_incr)
1114 rate_put -= rate_put_incr;
1115 break;
1116 default:
1117 err(1, "crankrate invoked with unknown signal: %d", sig);
1118 }
1119 }
1120
1121
1122 /*
1123 * Set the SIGALRM interval timer for wait seconds, 0 to disable.
1124 */
1125 void
1126 alarmtimer(wait)
1127 int wait;
1128 {
1129 struct itimerval itv;
1130
1131 itv.it_value.tv_sec = wait;
1132 itv.it_value.tv_usec = 0;
1133 itv.it_interval = itv.it_value;
1134 setitimer(ITIMER_REAL, &itv, NULL);
1135 }
1136
1137 /*
1138 * Setup or cleanup EditLine structures
1139 */
1140 #ifndef NO_EDITCOMPLETE
1141 void
1142 controlediting()
1143 {
1144 if (editing && el == NULL && hist == NULL) {
1145 HistEvent ev;
1146 int editmode;
1147
1148 el = el_init(__progname, stdin, ttyout, stderr);
1149 /* init editline */
1150 hist = history_init(); /* init the builtin history */
1151 history(hist, &ev, H_SETSIZE, 100);/* remember 100 events */
1152 el_set(el, EL_HIST, history, hist); /* use history */
1153
1154 el_set(el, EL_EDITOR, "emacs"); /* default editor is emacs */
1155 el_set(el, EL_PROMPT, prompt); /* set the prompt functions */
1156 el_set(el, EL_RPROMPT, rprompt);
1157
1158 /* add local file completion, bind to TAB */
1159 el_set(el, EL_ADDFN, "ftp-complete",
1160 "Context sensitive argument completion",
1161 complete);
1162 el_set(el, EL_BIND, "^I", "ftp-complete", NULL);
1163 el_source(el, NULL); /* read ~/.editrc */
1164 if ((el_get(el, EL_EDITMODE, &editmode) != -1) && editmode == 0)
1165 editing = 0; /* the user doesn't want editing,
1166 * so disable, and let statement
1167 * below cleanup */
1168 else
1169 el_set(el, EL_SIGNAL, 1);
1170 }
1171 if (!editing) {
1172 if (hist) {
1173 history_end(hist);
1174 hist = NULL;
1175 }
1176 if (el) {
1177 el_end(el);
1178 el = NULL;
1179 }
1180 }
1181 }
1182 #endif /* !NO_EDITCOMPLETE */
1183
1184 /*
1185 * Convert the string `arg' to an int, which may have an optional SI suffix
1186 * (`b', `k', `m', `g'). Returns the number for success, -1 otherwise.
1187 */
1188 int
1189 strsuftoi(arg)
1190 const char *arg;
1191 {
1192 char *cp;
1193 long val;
1194
1195 if (!isdigit((unsigned char)arg[0]))
1196 return (-1);
1197
1198 val = strtol(arg, &cp, 10);
1199 if (cp != NULL) {
1200 if (cp[0] != '\0' && cp[1] != '\0')
1201 return (-1);
1202 switch (tolower((unsigned char)cp[0])) {
1203 case '\0':
1204 case 'b':
1205 break;
1206 case 'k':
1207 val <<= 10;
1208 break;
1209 case 'm':
1210 val <<= 20;
1211 break;
1212 case 'g':
1213 val <<= 30;
1214 break;
1215 default:
1216 return (-1);
1217 }
1218 }
1219 if (val < 0 || val > INT_MAX)
1220 return (-1);
1221
1222 return (val);
1223 }
1224
1225 /*
1226 * Set up socket buffer sizes before a connection is made.
1227 */
1228 void
1229 setupsockbufsize(sock)
1230 int sock;
1231 {
1232
1233 if (setsockopt(sock, SOL_SOCKET, SO_SNDBUF, (void *) &sndbuf_size,
1234 sizeof(rcvbuf_size)) < 0)
1235 warn("unable to set sndbuf size %d", sndbuf_size);
1236
1237 if (setsockopt(sock, SOL_SOCKET, SO_RCVBUF, (void *) &rcvbuf_size,
1238 sizeof(rcvbuf_size)) < 0)
1239 warn("unable to set rcvbuf size %d", rcvbuf_size);
1240 }
1241
1242 /*
1243 * Copy characters from src into dst, \ quoting characters that require it
1244 */
1245 void
1246 ftpvis(dst, dstlen, src, srclen)
1247 char *dst;
1248 size_t dstlen;
1249 const char *src;
1250 size_t srclen;
1251 {
1252 int di, si;
1253
1254 for (di = si = 0;
1255 src[si] != '\0' && di < dstlen && si < srclen;
1256 di++, si++) {
1257 switch (src[si]) {
1258 case '\\':
1259 case ' ':
1260 case '\t':
1261 case '\r':
1262 case '\n':
1263 case '"':
1264 dst[di++] = '\\';
1265 if (di >= dstlen)
1266 break;
1267 /* FALLTHROUGH */
1268 default:
1269 dst[di] = src[si];
1270 }
1271 }
1272 dst[di] = '\0';
1273 }
1274
1275 /*
1276 * Copy src into buf (which is len bytes long), expanding % sequences.
1277 */
1278 void
1279 formatbuf(buf, len, src)
1280 char *buf;
1281 size_t len;
1282 const char *src;
1283 {
1284 const char *p;
1285 char *p2, *q;
1286 int i, op, updirs, pdirs;
1287
1288 #define ADDBUF(x) do { \
1289 if (i >= len - 1) \
1290 goto endbuf; \
1291 buf[i++] = (x); \
1292 } while (0)
1293
1294 p = src;
1295 for (i = 0; *p; p++) {
1296 if (*p != '%') {
1297 ADDBUF(*p);
1298 continue;
1299 }
1300 p++;
1301
1302 switch (op = *p) {
1303
1304 case '/':
1305 case '.':
1306 case 'c':
1307 p2 = connected ? remotepwd : "";
1308 updirs = pdirs = 0;
1309
1310 /* option to determine fixed # of dirs from path */
1311 if (op == '.' || op == 'c') {
1312 int skip;
1313
1314 q = p2;
1315 while (*p2) /* calc # of /'s */
1316 if (*p2++ == '/')
1317 updirs++;
1318 if (p[1] == '0') { /* print <x> or ... */
1319 pdirs = 1;
1320 p++;
1321 }
1322 if (p[1] >= '1' && p[1] <= '9') {
1323 /* calc # to skip */
1324 skip = p[1] - '0';
1325 p++;
1326 } else
1327 skip = 1;
1328
1329 updirs -= skip;
1330 while (skip-- > 0) {
1331 while ((p2 > q) && (*p2 != '/'))
1332 p2--; /* back up */
1333 if (skip && p2 > q)
1334 p2--;
1335 }
1336 if (*p2 == '/' && p2 != q)
1337 p2++;
1338 }
1339
1340 if (updirs > 0 && pdirs) {
1341 if (i >= len - 5)
1342 break;
1343 if (op == '.') {
1344 ADDBUF('.');
1345 ADDBUF('.');
1346 ADDBUF('.');
1347 } else {
1348 ADDBUF('/');
1349 ADDBUF('<');
1350 if (updirs > 9) {
1351 ADDBUF('9');
1352 ADDBUF('+');
1353 } else
1354 ADDBUF('0' + updirs);
1355 ADDBUF('>');
1356 }
1357 }
1358 for (; *p2; p2++)
1359 ADDBUF(*p2);
1360 break;
1361
1362 case 'M':
1363 case 'm':
1364 for (p2 = connected ? hostname : "-"; *p2; p2++) {
1365 if (op == 'm' && *p2 == '.')
1366 break;
1367 ADDBUF(*p2);
1368 }
1369 break;
1370
1371 case 'n':
1372 for (p2 = connected ? username : "-"; *p2 ; p2++)
1373 ADDBUF(*p2);
1374 break;
1375
1376 case '%':
1377 ADDBUF('%');
1378 break;
1379
1380 default: /* display unknown codes literally */
1381 ADDBUF('%');
1382 ADDBUF(op);
1383 break;
1384
1385 }
1386 }
1387 endbuf:
1388 buf[i] = '\0';
1389 }
1390
1391 /*
1392 * Determine if given string is an IPv6 address or not.
1393 * Return 1 for yes, 0 for no
1394 */
1395 int
1396 isipv6addr(addr)
1397 const char *addr;
1398 {
1399 int rv = 0;
1400 #ifdef INET6
1401 struct sockaddr_in6 su_sin6;
1402
1403 rv = inet_pton(AF_INET6, addr, &su_sin6.sin6_addr);
1404 if (debug)
1405 fprintf(ttyout, "isipv6addr: got %d for %s\n", rv, addr);
1406 #endif
1407 return (rv == 1) ? 1 : 0;
1408 }
1409
1410
1411 /*
1412 * Internal version of connect(2); sets socket buffer sizes first.
1413 */
1414 int
1415 xconnect(sock, name, namelen)
1416 int sock;
1417 const struct sockaddr *name;
1418 int namelen;
1419 {
1420
1421 setupsockbufsize(sock);
1422 return (connect(sock, name, namelen));
1423 }
1424
1425 /*
1426 * Internal version of listen(2); sets socket buffer sizes first.
1427 */
1428 int
1429 xlisten(sock, backlog)
1430 int sock, backlog;
1431 {
1432
1433 setupsockbufsize(sock);
1434 return (listen(sock, backlog));
1435 }
1436
1437 /*
1438 * malloc() with inbuilt error checking
1439 */
1440 void *
1441 xmalloc(size)
1442 size_t size;
1443 {
1444 void *p;
1445
1446 p = malloc(size);
1447 if (p == NULL)
1448 err(1, "Unable to allocate %ld bytes of memory", (long)size);
1449 return (p);
1450 }
1451
1452 /*
1453 * sl_init() with inbuilt error checking
1454 */
1455 StringList *
1456 xsl_init()
1457 {
1458 StringList *p;
1459
1460 p = sl_init();
1461 if (p == NULL)
1462 err(1, "Unable to allocate memory for stringlist");
1463 return (p);
1464 }
1465
1466 /*
1467 * sl_add() with inbuilt error checking
1468 */
1469 void
1470 xsl_add(sl, i)
1471 StringList *sl;
1472 char *i;
1473 {
1474
1475 if (sl_add(sl, i) == -1)
1476 err(1, "Unable to add `%s' to stringlist", i);
1477 }
1478
1479 /*
1480 * strdup() with inbuilt error checking
1481 */
1482 char *
1483 xstrdup(str)
1484 const char *str;
1485 {
1486 char *s;
1487
1488 if (str == NULL)
1489 errx(1, "xstrdup() called with NULL argument");
1490 s = strdup(str);
1491 if (s == NULL)
1492 err(1, "Unable to allocate memory for string copy");
1493 return (s);
1494 }
1495
1496 /*
1497 * Install a POSIX signal handler, allowing the invoker to set whether
1498 * the signal should be restartable or not
1499 */
1500 sig_t
1501 xsignal_restart(sig, func, restartable)
1502 int sig;
1503 void (*func) __P((int));
1504 int restartable;
1505 {
1506 struct sigaction act, oact;
1507 act.sa_handler = func;
1508
1509 sigemptyset(&act.sa_mask);
1510 #if defined(SA_RESTART) /* 4.4BSD, Posix(?), SVR4 */
1511 act.sa_flags = restartable ? SA_RESTART : 0;
1512 #elif defined(SA_INTERRUPT) /* SunOS 4.x */
1513 act.sa_flags = restartable ? 0 : SA_INTERRUPT;
1514 #else
1515 #error "system must have SA_RESTART or SA_INTERRUPT"
1516 #endif
1517 if (sigaction(sig, &act, &oact) < 0)
1518 return (SIG_ERR);
1519 return (oact.sa_handler);
1520 }
1521
1522 /*
1523 * Install a signal handler with the `restartable' flag set dependent upon
1524 * which signal is being set. (This is a wrapper to xsignal_restart())
1525 */
1526 sig_t
1527 xsignal(sig, func)
1528 int sig;
1529 void (*func) __P((int));
1530 {
1531 int restartable;
1532
1533 /*
1534 * Some signals print output or change the state of the process.
1535 * There should be restartable, so that reads and writes are
1536 * not affected. Some signals should cause program flow to change;
1537 * these signals should not be restartable, so that the system call
1538 * will return with EINTR, and the program will go do something
1539 * different. If the signal handler calls longjmp() or siglongjmp(),
1540 * it doesn't matter if it's restartable.
1541 */
1542
1543 switch(sig) {
1544 #ifdef SIGINFO
1545 case SIGINFO:
1546 #endif
1547 case SIGQUIT:
1548 case SIGUSR1:
1549 case SIGUSR2:
1550 case SIGWINCH:
1551 restartable = 1;
1552 break;
1553
1554 case SIGALRM:
1555 case SIGINT:
1556 case SIGPIPE:
1557 restartable = 0;
1558 break;
1559
1560 default:
1561 /*
1562 * This is unpleasant, but I don't know what would be better.
1563 * Right now, this "can't happen"
1564 */
1565 errx(1, "xsignal_restart called with signal %d", sig);
1566 }
1567
1568 return(xsignal_restart(sig, func, restartable));
1569 }
1570