1 /* $FreeBSD: src/usr.bin/ftp/util.c,v 1.12.2.4 2002/08/27 09:55:08 yar Exp $ */
2 /* $DragonFly: src/usr.bin/ftp/Attic/util.c,v 1.2 2003/06/17 04:29:26 dillon Exp $ */
3 /* $NetBSD: util.c,v 1.16.2.1 1997/11/18 01:02:33 mellon Exp $ */
6 * Copyright (c) 1985, 1989, 1993, 1994
7 * The Regents of the University of California. All rights reserved.
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
12 * 1. Redistributions of source code must retain the above copyright
13 * notice, this list of conditions and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the above copyright
15 * notice, this list of conditions and the following disclaimer in the
16 * documentation and/or other materials provided with the distribution.
17 * 3. All advertising materials mentioning features or use of this software
18 * must display the following acknowledgement:
19 * This product includes software developed by the University of
20 * California, Berkeley and its contributors.
21 * 4. Neither the name of the University nor the names of its contributors
22 * may be used to endorse or promote products derived from this software
23 * without specific prior written permission.
25 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
26 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
27 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
28 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
29 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
30 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
31 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
32 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
33 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
34 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
37 * $NetBSD: util.c,v 1.16.2.1 1997/11/18 01:02:33 mellon Exp $
38 * $FreeBSD: src/usr.bin/ftp/util.c,v 1.12.2.4 2002/08/27 09:55:08 yar Exp $
41 #include <sys/cdefs.h>
44 * FTP User Program -- Misc support routines
46 #include <sys/ioctl.h>
66 #include "pathnames.h"
69 #define SECSPERHOUR (60*60)
73 * Connect to peer server and
74 * auto-login, if possible.
85 printf("Already connected to %s, use close first.\n",
91 (void)another(&argc, &argv, "to");
92 if (argc < 2 || argc > 3) {
93 printf("usage: %s host-name [port]\n", argv[0]);
102 port = strdup(argv[2]);
105 if (gateserver == NULL || *gateserver == '\0')
106 errx(1, "gateserver not defined (shouldn't happen)");
107 host = hookup(gateserver, port);
109 host = hookup(argv[1], port);
115 if (command("PASSERVE %s", argv[1]) != COMPLETE)
118 printf("Connected via pass-through server %s\n",
125 * Set up defaults for FTP.
127 (void)strcpy(typename, "ascii"), type = TYPE_A;
129 (void)strcpy(formname, "non-print"), form = FORM_N;
130 (void)strcpy(modename, "stream"), mode = MODE_S;
131 (void)strcpy(structname, "file"), stru = STRU_F;
132 (void)strcpy(bytename, "8"), bytesize = 8;
134 (void)login(argv[1], NULL, NULL);
139 if (command("SYST") == COMPLETE && overbose) {
142 cp = strchr(reply_string+4, ' ');
144 cp = strchr(reply_string+4, '\r');
152 printf("Remote system type is %s.\n", reply_string + 4);
156 if (!strncmp(reply_string, "215 UNIX Type: L8", 17)) {
162 * Set type to 0 (not specified by user),
163 * meaning binary by default, but don't bother
164 * telling server. We can use binary
165 * for text files unless changed by the user.
168 (void)strcpy(typename, "binary");
170 printf("Using %s mode to transfer files.\n",
178 !strncmp(reply_string, "215 TOPS20", 10))
180 "Remember to set tenex mode when transferring binary files from this machine.");
188 * login to remote host, using given username & password if supplied
191 login(host, user, pass)
197 char anonpass[MAXLOGNAME + 1 + MAXHOSTNAMELEN]; /* "user@hostname" */
198 char hostname[MAXHOSTNAMELEN];
204 if (ruserpass(host, &user, &pass, &acct) < 0) {
211 * Set up arguments for an anonymous FTP session, if necessary.
213 if ((user == NULL || pass == NULL) && anonftp) {
214 memset(anonpass, 0, sizeof(anonpass));
215 memset(hostname, 0, sizeof(hostname));
218 * Set up anonymous login password.
220 if ((user = getlogin()) == NULL) {
221 if ((pw = getpwuid(getuid())) == NULL)
226 gethostname(hostname, MAXHOSTNAMELEN);
227 #ifndef DONT_CHEAT_ANONPASS
229 * Every anonymous FTP server I've encountered
230 * will accept the string "username@", and will
231 * append the hostname itself. We do this by default
232 * since many servers are picky about not having
233 * a FQDN in the anonymous password. - thorpej@netbsd.org
235 snprintf(anonpass, sizeof(anonpass) - 1, "%s@",
238 snprintf(anonpass, sizeof(anonpass) - 1, "%s@%s",
242 user = "anonymous"; /* as per RFC 1635 */
245 while (user == NULL) {
246 char *myname = getlogin();
248 if (myname == NULL && (pw = getpwuid(getuid())) != NULL)
249 myname = pw->pw_name;
251 printf("Name (%s:%s): ", host, myname);
253 printf("Name (%s): ", host);
254 if (fgets(tmp, sizeof(tmp) - 1, stdin) == NULL)
256 tmp[strlen(tmp) - 1] = '\0';
262 n = command("USER %s", user);
265 pass = getpass("Password:");
266 n = command("PASS %s", pass);
271 acct = getpass("Account:");
272 n = command("ACCT %s", acct);
274 if ((n != COMPLETE) ||
275 (!aflag && acct != NULL && command("ACCT %s", acct) != COMPLETE)) {
276 warnx("Login failed.");
282 for (n = 0; n < macnum; ++n) {
283 if (!strcmp("init", macros[n].mac_name)) {
284 (void)strcpy(line, "$init");
286 domacro(margc, margv);
294 * `another' gets another argument, and stores the new argc and argv.
295 * It reverts to the top level (via main.c's intr()) on EOF/error.
297 * Returns false if no new arguments have been added.
300 another(pargc, pargv, prompt)
305 int len = strlen(line), ret;
307 if (len >= sizeof(line) - 3) {
308 puts("sorry, arguments too long.");
311 printf("(%s) ", prompt);
313 if (fgets(&line[len], sizeof(line) - len, stdin) == NULL)
315 len += strlen(&line[len]);
316 if (len > 0 && line[len - 1] == '\n')
317 line[len - 1] = '\0';
319 ret = margc > *pargc;
326 * glob files given in argv[] from the remote server.
327 * if errbuf isn't NULL, store error messages there instead
328 * of writing to the screen.
331 remglob(argv, doswitch, errbuf)
336 char temp[MAXPATHLEN];
337 static char buf[MAXPATHLEN];
338 static FILE *ftemp = NULL;
340 int oldverbose, oldhash, fd;
357 if ((cp = *++args) == NULL)
362 (void)snprintf(temp, sizeof(temp), "%s/%s", tmpdir, TMPFILE);
363 if ((fd = mkstemp(temp)) < 0) {
364 warn("unable to create temporary file %s", temp);
368 oldverbose = verbose;
369 verbose = (errbuf != NULL) ? -1 : 0;
374 for (mode = "w"; *++argv != NULL; mode = "a")
375 recvrequest("NLST", temp, *argv, mode, 0, 0);
376 if ((code / 100) != COMPLETE) {
378 *errbuf = reply_string;
382 verbose = oldverbose;
384 ftemp = fopen(temp, "r");
388 puts("can't find list of remote files, oops.");
391 "can't find list of remote files, oops.";
395 if (fgets(buf, sizeof(buf), ftemp) == NULL) {
400 if ((cp = strchr(buf, '\n')) != NULL)
407 const char *cmd, *file;
411 if (!interactive || confirmrest)
413 printf("%s %s? ", cmd, file);
414 (void)fflush(stdout);
415 if (fgets(line, sizeof(line), stdin) == NULL)
417 switch (tolower((unsigned char)*line)) {
422 puts("Interactive mode: off.");
426 printf("Prompting off for duration of %s.\n", cmd);
433 * Glob a local file name specification with
434 * the expectation of a single return value.
435 * Can't control multiple values being expanded
436 * from the expression, we return only the first.
448 flags = GLOB_BRACE|GLOB_NOCHECK|GLOB_QUOTE|GLOB_TILDE;
449 memset(&gl, 0, sizeof(gl));
450 if (glob(*cpp, flags, NULL, &gl) ||
452 warnx("%s: not found", *cpp);
456 /* XXX: caller should check if *cpp changed, and
457 * free(*cpp) if that is the case
459 *cpp = strdup(gl.gl_pathv[0]);
465 * determine size of remote file
468 remotesize(file, noisy)
479 if (command("SIZE %s", file) == COMPLETE) {
482 cp = strchr(reply_string, ' ');
485 size = strtoq(cp, &ep, 10);
486 if (*ep != '\0' && !isspace((unsigned char)*ep))
489 } else if (noisy && debug == 0)
496 * determine last modification time (in GMT) of remote file
499 remotemodtime(file, noisy)
505 int len, month, ocode, overbose, y2kbug, year;
514 if (command("MDTM %s", file) == COMPLETE) {
515 memset(&timebuf, 0, sizeof(timebuf));
517 * Parse the time string, which is expected to be 14
518 * characters long. Some broken servers send tm_year
519 * formatted with "19%02d", which produces an incorrect
520 * (but parsable) 15 characters for years >= 2000.
521 * Scan for invalid trailing junk by accepting up to 16
524 if (sscanf(reply_string, "%*s %16s", mtbuf) == 1) {
528 if (len == 15 && strncmp(mtbuf, "19", 2) == 0) {
529 fmt = "19%03d%02d%02d%02d%02d%02d";
531 } else if (len == 14)
532 fmt = "%04d%02d%02d%02d%02d%02d";
534 if (sscanf(mtbuf, fmt, &year, &month,
535 &timebuf.tm_mday, &timebuf.tm_hour,
536 &timebuf.tm_min, &timebuf.tm_sec) == 6) {
537 timebuf.tm_isdst = -1;
538 timebuf.tm_mon = month - 1;
540 timebuf.tm_year = year;
542 timebuf.tm_year = year - 1900;
543 rtime = mktime(&timebuf);
548 if (noisy || debug != 0)
549 printf("Can't convert %s to a time.\n", mtbuf);
551 rtime += timebuf.tm_gmtoff; /* conv. local -> GMT */
552 } else if (noisy && debug == 0)
560 void updateprogressmeter __P((int));
563 updateprogressmeter(dummy)
566 static pid_t pgrp = -1;
573 * print progress bar only if we are foreground process.
575 if (ioctl(STDOUT_FILENO, TIOCGPGRP, &ctty_pgrp) != -1 &&
576 ctty_pgrp == (int)pgrp)
581 * Display a transfer progress bar if progress is non-zero.
582 * SIGALRM is hijacked for use by this function.
583 * - Before the transfer, set filesize to size of file (or -1 if unknown),
584 * and call with flag = -1. This starts the once per second timer,
585 * and a call to updateprogressmeter() upon SIGALRM.
586 * - During the transfer, updateprogressmeter will call progressmeter
588 * - After the transfer, call with flag = 1
590 static struct timeval start;
597 * List of order of magnitude prefixes.
598 * The last is `P', as 2^64 = 16384 Petabytes
600 static const char prefixes[] = " KMGTP";
602 static struct timeval lastupdate;
603 static off_t lastsize;
604 struct timeval now, td, wait;
605 off_t cursize, abbrevsize;
607 int ratio, barlength, i, len;
614 (void)gettimeofday(&start, (struct timezone *)0);
616 lastsize = restart_point;
618 (void)gettimeofday(&now, (struct timezone *)0);
619 if (!progress || filesize <= 0)
621 cursize = bytes + restart_point;
623 ratio = cursize * 100 / filesize;
624 ratio = MAX(ratio, 0);
625 ratio = MIN(ratio, 100);
626 len += snprintf(buf + len, sizeof(buf) - len, "\r%3d%% ", ratio);
628 barlength = ttywidth - 30;
630 i = barlength * ratio / 100;
631 len += snprintf(buf + len, sizeof(buf) - len,
633 "*****************************************************************************"
634 "*****************************************************************************",
639 abbrevsize = cursize;
640 while (abbrevsize >= 100000 && i < sizeof(prefixes)) {
644 len += snprintf(buf + len, sizeof(buf) - len,
645 " %5qd %c%c ", (long long)abbrevsize, prefixes[i],
646 prefixes[i] == ' ' ? ' ' : 'B');
648 timersub(&now, &lastupdate, &wait);
649 if (cursize > lastsize) {
652 if (wait.tv_sec >= STALLTIME) { /* fudge out stalled time */
653 start.tv_sec += wait.tv_sec;
654 start.tv_usec += wait.tv_usec;
659 timersub(&now, &start, &td);
660 elapsed = td.tv_sec + (td.tv_usec / 1000000.0);
662 if (bytes <= 0 || elapsed <= 0.0 || cursize > filesize) {
663 len += snprintf(buf + len, sizeof(buf) - len,
665 } else if (wait.tv_sec >= STALLTIME) {
666 len += snprintf(buf + len, sizeof(buf) - len,
670 ((filesize - restart_point) / (bytes / elapsed) - elapsed);
671 if (remaining >= 100 * SECSPERHOUR)
672 len += snprintf(buf + len, sizeof(buf) - len,
675 i = remaining / SECSPERHOUR;
677 len += snprintf(buf + len, sizeof(buf) - len,
680 len += snprintf(buf + len, sizeof(buf) - len,
682 i = remaining % SECSPERHOUR;
683 len += snprintf(buf + len, sizeof(buf) - len,
684 "%02d:%02d ETA", i / 60, i % 60);
687 (void)write(STDOUT_FILENO, buf, len);
690 (void)signal(SIGALRM, updateprogressmeter);
691 alarmtimer(1); /* set alarm timer for 1 Hz */
692 } else if (flag == 1) {
700 * Display transfer statistics.
701 * Requires start to be initialised by progressmeter(-1),
702 * direction to be defined by xfer routines, and filesize and bytes
703 * to be updated by xfer routines
704 * If siginfo is nonzero, an ETA is displayed, and the output goes to STDERR
711 struct timeval now, td;
714 int meg, remaining, hh, len;
717 if (!verbose && !siginfo)
720 (void)gettimeofday(&now, (struct timezone *)0);
721 timersub(&now, &start, &td);
722 elapsed = td.tv_sec + (td.tv_usec / 1000000.0);
723 bs = bytes / (elapsed == 0.0 ? 1 : elapsed);
725 if (bs > (1024 * 1024))
728 len += snprintf(buf + len, sizeof(buf) - len,
729 "%qd byte%s %s in %.2f seconds (%.2f %sB/s)\n",
730 (long long)bytes, bytes == 1 ? "" : "s", direction, elapsed,
731 bs / (1024.0 * (meg ? 1024.0 : 1.0)), meg ? "M" : "K");
732 if (siginfo && bytes > 0 && elapsed > 0.0 && filesize >= 0
733 && bytes + restart_point <= filesize) {
734 remaining = (int)((filesize - restart_point) /
735 (bytes / elapsed) - elapsed);
736 hh = remaining / SECSPERHOUR;
737 remaining %= SECSPERHOUR;
738 len--; /* decrement len to overwrite \n */
739 len += snprintf(buf + len, sizeof(buf) - len,
740 " ETA: %02d:%02d:%02d\n", hh, remaining / 60,
743 (void)write(siginfo ? STDERR_FILENO : STDOUT_FILENO, buf, len);
747 * List words in stringlist, vertically arranged
754 int columns, width, lines, items;
759 for (i = 0 ; i < sl->sl_cur ; i++) {
760 w = strlen(sl->sl_str[i]);
764 width = (width + 8) &~ 7;
766 columns = ttywidth / width;
769 lines = (sl->sl_cur + columns - 1) / columns;
770 for (i = 0; i < lines; i++) {
771 for (j = 0; j < columns; j++) {
772 p = sl->sl_str[j * lines + i];
775 if (j * lines + i + lines >= sl->sl_cur) {
789 * Update the global ttywidth value, using TIOCGWINSZ.
795 struct winsize winsize;
797 if (ioctl(fileno(stdout), TIOCGWINSZ, &winsize) != -1)
798 ttywidth = winsize.ws_col;
804 * Set the SIGALRM interval timer for wait seconds, 0 to disable.
810 struct itimerval itv;
812 itv.it_value.tv_sec = wait;
813 itv.it_value.tv_usec = 0;
814 itv.it_interval = itv.it_value;
815 setitimer(ITIMER_REAL, &itv, NULL);
819 * Setup or cleanup EditLine structures
825 if (editing && el == NULL && hist == NULL) {
826 el = el_init(__progname, stdin, stdout); /* init editline */
827 hist = history_init(); /* init the builtin history */
828 history(hist, H_EVENT, 100); /* remember 100 events */
829 el_set(el, EL_HIST, history, hist); /* use history */
831 el_set(el, EL_EDITOR, "emacs"); /* default editor is emacs */
832 el_set(el, EL_PROMPT, prompt); /* set the prompt function */
834 /* add local file completion, bind to TAB */
835 el_set(el, EL_ADDFN, "ftp-complete",
836 "Context sensitive argument completion",
838 el_set(el, EL_BIND, "^I", "ftp-complete", NULL);
840 el_source(el, NULL); /* read ~/.editrc */
841 el_set(el, EL_SIGNAL, 1);
842 } else if (!editing) {
856 * Determine if given string is an IPv6 address or not.
857 * Return 1 for yes, 0 for no
860 isipv6addr(const char *addr)
864 struct addrinfo hints, *res;
866 memset(&hints, 0, sizeof(hints));
867 hints.ai_family = PF_INET6;
868 hints.ai_socktype = SOCK_DGRAM; /*dummy*/
869 hints.ai_flags = AI_NUMERICHOST;
870 if (getaddrinfo(addr, "0", &hints, &res) != 0)
877 printf("isipv6addr: got %d for %s\n", rv, addr);
879 return (rv == 1) ? 1 : 0;