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