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.3 2003/10/04 20:36:45 hmp 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.
77 setpeer(int argc, char **argv)
83 printf("Already connected to %s, use close first.\n",
89 (void)another(&argc, &argv, "to");
90 if (argc < 2 || argc > 3) {
91 printf("usage: %s host-name [port]\n", argv[0]);
100 port = strdup(argv[2]);
103 if (gateserver == NULL || *gateserver == '\0')
104 errx(1, "gateserver not defined (shouldn't happen)");
105 host = hookup(gateserver, port);
107 host = hookup(argv[1], port);
113 if (command("PASSERVE %s", argv[1]) != COMPLETE)
116 printf("Connected via pass-through server %s\n",
123 * Set up defaults for FTP.
125 (void)strcpy(typename, "ascii"), type = TYPE_A;
127 (void)strcpy(formname, "non-print"), form = FORM_N;
128 (void)strcpy(modename, "stream"), mode = MODE_S;
129 (void)strcpy(structname, "file"), stru = STRU_F;
130 (void)strcpy(bytename, "8"), bytesize = 8;
132 (void)login(argv[1], NULL, NULL);
137 if (command("SYST") == COMPLETE && overbose) {
140 cp = strchr(reply_string+4, ' ');
142 cp = strchr(reply_string+4, '\r');
150 printf("Remote system type is %s.\n", reply_string + 4);
154 if (!strncmp(reply_string, "215 UNIX Type: L8", 17)) {
160 * Set type to 0 (not specified by user),
161 * meaning binary by default, but don't bother
162 * telling server. We can use binary
163 * for text files unless changed by the user.
166 (void)strcpy(typename, "binary");
168 printf("Using %s mode to transfer files.\n",
176 !strncmp(reply_string, "215 TOPS20", 10))
178 "Remember to set tenex mode when transferring binary files from this machine.");
186 * login to remote host, using given username & password if supplied
189 login(const char *host, char *user, char *pass)
193 char anonpass[MAXLOGNAME + 1 + MAXHOSTNAMELEN]; /* "user@hostname" */
194 char hostname[MAXHOSTNAMELEN];
200 if (ruserpass(host, &user, &pass, &acct) < 0) {
207 * Set up arguments for an anonymous FTP session, if necessary.
209 if ((user == NULL || pass == NULL) && anonftp) {
210 memset(anonpass, 0, sizeof(anonpass));
211 memset(hostname, 0, sizeof(hostname));
214 * Set up anonymous login password.
216 if ((user = getlogin()) == NULL) {
217 if ((pw = getpwuid(getuid())) == NULL)
222 gethostname(hostname, MAXHOSTNAMELEN);
223 #ifndef DONT_CHEAT_ANONPASS
225 * Every anonymous FTP server I've encountered
226 * will accept the string "username@", and will
227 * append the hostname itself. We do this by default
228 * since many servers are picky about not having
229 * a FQDN in the anonymous password. - thorpej@netbsd.org
231 snprintf(anonpass, sizeof(anonpass) - 1, "%s@",
234 snprintf(anonpass, sizeof(anonpass) - 1, "%s@%s",
238 user = "anonymous"; /* as per RFC 1635 */
241 while (user == NULL) {
242 char *myname = getlogin();
244 if (myname == NULL && (pw = getpwuid(getuid())) != NULL)
245 myname = pw->pw_name;
247 printf("Name (%s:%s): ", host, myname);
249 printf("Name (%s): ", host);
250 if (fgets(tmp, sizeof(tmp) - 1, stdin) == NULL)
252 tmp[strlen(tmp) - 1] = '\0';
258 n = command("USER %s", user);
261 pass = getpass("Password:");
262 n = command("PASS %s", pass);
267 acct = getpass("Account:");
268 n = command("ACCT %s", acct);
270 if ((n != COMPLETE) ||
271 (!aflag && acct != NULL && command("ACCT %s", acct) != COMPLETE)) {
272 warnx("Login failed.");
278 for (n = 0; n < macnum; ++n) {
279 if (!strcmp("init", macros[n].mac_name)) {
280 (void)strcpy(line, "$init");
282 domacro(margc, margv);
290 * `another' gets another argument, and stores the new argc and argv.
291 * It reverts to the top level (via main.c's intr()) on EOF/error.
293 * Returns false if no new arguments have been added.
296 another(int *pargc, char ***pargv, const char *prompt)
298 int len = strlen(line), ret;
300 if (len >= sizeof(line) - 3) {
301 puts("sorry, arguments too long.");
304 printf("(%s) ", prompt);
306 if (fgets(&line[len], sizeof(line) - len, stdin) == NULL)
308 len += strlen(&line[len]);
309 if (len > 0 && line[len - 1] == '\n')
310 line[len - 1] = '\0';
312 ret = margc > *pargc;
319 * glob files given in argv[] from the remote server.
320 * if errbuf isn't NULL, store error messages there instead
321 * of writing to the screen.
324 remglob(char **argv, int doswitch, char **errbuf)
326 char temp[MAXPATHLEN];
327 static char buf[MAXPATHLEN];
328 static FILE *ftemp = NULL;
330 int oldverbose, oldhash, fd;
347 if ((cp = *++args) == NULL)
352 (void)snprintf(temp, sizeof(temp), "%s/%s", tmpdir, TMPFILE);
353 if ((fd = mkstemp(temp)) < 0) {
354 warn("unable to create temporary file %s", temp);
358 oldverbose = verbose;
359 verbose = (errbuf != NULL) ? -1 : 0;
364 for (mode = "w"; *++argv != NULL; mode = "a")
365 recvrequest("NLST", temp, *argv, mode, 0, 0);
366 if ((code / 100) != COMPLETE) {
368 *errbuf = reply_string;
372 verbose = oldverbose;
374 ftemp = fopen(temp, "r");
378 puts("can't find list of remote files, oops.");
381 "can't find list of remote files, oops.";
385 if (fgets(buf, sizeof(buf), ftemp) == NULL) {
390 if ((cp = strchr(buf, '\n')) != NULL)
396 confirm(const char *cmd, const char *file)
400 if (!interactive || confirmrest)
402 printf("%s %s? ", cmd, file);
403 (void)fflush(stdout);
404 if (fgets(line, sizeof(line), stdin) == NULL)
406 switch (tolower((unsigned char)*line)) {
411 puts("Interactive mode: off.");
415 printf("Prompting off for duration of %s.\n", cmd);
422 * Glob a local file name specification with
423 * the expectation of a single return value.
424 * Can't control multiple values being expanded
425 * from the expression, we return only the first.
428 globulize(char **cpp)
436 flags = GLOB_BRACE|GLOB_NOCHECK|GLOB_QUOTE|GLOB_TILDE;
437 memset(&gl, 0, sizeof(gl));
438 if (glob(*cpp, flags, NULL, &gl) ||
440 warnx("%s: not found", *cpp);
444 /* XXX: caller should check if *cpp changed, and
445 * free(*cpp) if that is the case
447 *cpp = strdup(gl.gl_pathv[0]);
453 * determine size of remote file
456 remotesize(const char *file, int noisy)
465 if (command("SIZE %s", file) == COMPLETE) {
468 cp = strchr(reply_string, ' ');
471 size = strtoq(cp, &ep, 10);
472 if (*ep != '\0' && !isspace((unsigned char)*ep))
475 } else if (noisy && debug == 0)
482 * determine last modification time (in GMT) of remote file
485 remotemodtime(const char *file, int noisy)
489 int len, month, ocode, overbose, y2kbug, year;
498 if (command("MDTM %s", file) == COMPLETE) {
499 memset(&timebuf, 0, sizeof(timebuf));
501 * Parse the time string, which is expected to be 14
502 * characters long. Some broken servers send tm_year
503 * formatted with "19%02d", which produces an incorrect
504 * (but parsable) 15 characters for years >= 2000.
505 * Scan for invalid trailing junk by accepting up to 16
508 if (sscanf(reply_string, "%*s %16s", mtbuf) == 1) {
512 if (len == 15 && strncmp(mtbuf, "19", 2) == 0) {
513 fmt = "19%03d%02d%02d%02d%02d%02d";
515 } else if (len == 14)
516 fmt = "%04d%02d%02d%02d%02d%02d";
518 if (sscanf(mtbuf, fmt, &year, &month,
519 &timebuf.tm_mday, &timebuf.tm_hour,
520 &timebuf.tm_min, &timebuf.tm_sec) == 6) {
521 timebuf.tm_isdst = -1;
522 timebuf.tm_mon = month - 1;
524 timebuf.tm_year = year;
526 timebuf.tm_year = year - 1900;
527 rtime = mktime(&timebuf);
532 if (noisy || debug != 0)
533 printf("Can't convert %s to a time.\n", mtbuf);
535 rtime += timebuf.tm_gmtoff; /* conv. local -> GMT */
536 } else if (noisy && debug == 0)
544 void updateprogressmeter(int);
547 updateprogressmeter(int dummy)
549 static pid_t pgrp = -1;
556 * print progress bar only if we are foreground process.
558 if (ioctl(STDOUT_FILENO, TIOCGPGRP, &ctty_pgrp) != -1 &&
559 ctty_pgrp == (int)pgrp)
564 * Display a transfer progress bar if progress is non-zero.
565 * SIGALRM is hijacked for use by this function.
566 * - Before the transfer, set filesize to size of file (or -1 if unknown),
567 * and call with flag = -1. This starts the once per second timer,
568 * and a call to updateprogressmeter() upon SIGALRM.
569 * - During the transfer, updateprogressmeter will call progressmeter
571 * - After the transfer, call with flag = 1
573 static struct timeval start;
576 progressmeter(int flag)
579 * List of order of magnitude prefixes.
580 * The last is `P', as 2^64 = 16384 Petabytes
582 static const char prefixes[] = " KMGTP";
584 static struct timeval lastupdate;
585 static off_t lastsize;
586 struct timeval now, td, wait;
587 off_t cursize, abbrevsize;
589 int ratio, barlength, i, len;
596 (void)gettimeofday(&start, (struct timezone *)0);
598 lastsize = restart_point;
600 (void)gettimeofday(&now, (struct timezone *)0);
601 if (!progress || filesize <= 0)
603 cursize = bytes + restart_point;
605 ratio = cursize * 100 / filesize;
606 ratio = MAX(ratio, 0);
607 ratio = MIN(ratio, 100);
608 len += snprintf(buf + len, sizeof(buf) - len, "\r%3d%% ", ratio);
610 barlength = ttywidth - 30;
612 i = barlength * ratio / 100;
613 len += snprintf(buf + len, sizeof(buf) - len,
615 "*****************************************************************************"
616 "*****************************************************************************",
621 abbrevsize = cursize;
622 while (abbrevsize >= 100000 && i < sizeof(prefixes)) {
626 len += snprintf(buf + len, sizeof(buf) - len,
627 " %5qd %c%c ", (long long)abbrevsize, prefixes[i],
628 prefixes[i] == ' ' ? ' ' : 'B');
630 timersub(&now, &lastupdate, &wait);
631 if (cursize > lastsize) {
634 if (wait.tv_sec >= STALLTIME) { /* fudge out stalled time */
635 start.tv_sec += wait.tv_sec;
636 start.tv_usec += wait.tv_usec;
641 timersub(&now, &start, &td);
642 elapsed = td.tv_sec + (td.tv_usec / 1000000.0);
644 if (bytes <= 0 || elapsed <= 0.0 || cursize > filesize) {
645 len += snprintf(buf + len, sizeof(buf) - len,
647 } else if (wait.tv_sec >= STALLTIME) {
648 len += snprintf(buf + len, sizeof(buf) - len,
652 ((filesize - restart_point) / (bytes / elapsed) - elapsed);
653 if (remaining >= 100 * SECSPERHOUR)
654 len += snprintf(buf + len, sizeof(buf) - len,
657 i = remaining / SECSPERHOUR;
659 len += snprintf(buf + len, sizeof(buf) - len,
662 len += snprintf(buf + len, sizeof(buf) - len,
664 i = remaining % SECSPERHOUR;
665 len += snprintf(buf + len, sizeof(buf) - len,
666 "%02d:%02d ETA", i / 60, i % 60);
669 (void)write(STDOUT_FILENO, buf, len);
672 (void)signal(SIGALRM, updateprogressmeter);
673 alarmtimer(1); /* set alarm timer for 1 Hz */
674 } else if (flag == 1) {
682 * Display transfer statistics.
683 * Requires start to be initialised by progressmeter(-1),
684 * direction to be defined by xfer routines, and filesize and bytes
685 * to be updated by xfer routines
686 * If siginfo is nonzero, an ETA is displayed, and the output goes to STDERR
690 ptransfer(int siginfo)
692 struct timeval now, td;
695 int meg, remaining, hh, len;
698 if (!verbose && !siginfo)
701 (void)gettimeofday(&now, (struct timezone *)0);
702 timersub(&now, &start, &td);
703 elapsed = td.tv_sec + (td.tv_usec / 1000000.0);
704 bs = bytes / (elapsed == 0.0 ? 1 : elapsed);
706 if (bs > (1024 * 1024))
709 len += snprintf(buf + len, sizeof(buf) - len,
710 "%qd byte%s %s in %.2f seconds (%.2f %sB/s)\n",
711 (long long)bytes, bytes == 1 ? "" : "s", direction, elapsed,
712 bs / (1024.0 * (meg ? 1024.0 : 1.0)), meg ? "M" : "K");
713 if (siginfo && bytes > 0 && elapsed > 0.0 && filesize >= 0
714 && bytes + restart_point <= filesize) {
715 remaining = (int)((filesize - restart_point) /
716 (bytes / elapsed) - elapsed);
717 hh = remaining / SECSPERHOUR;
718 remaining %= SECSPERHOUR;
719 len--; /* decrement len to overwrite \n */
720 len += snprintf(buf + len, sizeof(buf) - len,
721 " ETA: %02d:%02d:%02d\n", hh, remaining / 60,
724 (void)write(siginfo ? STDERR_FILENO : STDOUT_FILENO, buf, len);
728 * List words in stringlist, vertically arranged
731 list_vertical(StringList *sl)
734 int columns, width, lines, items;
739 for (i = 0 ; i < sl->sl_cur ; i++) {
740 w = strlen(sl->sl_str[i]);
744 width = (width + 8) &~ 7;
746 columns = ttywidth / width;
749 lines = (sl->sl_cur + columns - 1) / columns;
750 for (i = 0; i < lines; i++) {
751 for (j = 0; j < columns; j++) {
752 p = sl->sl_str[j * lines + i];
755 if (j * lines + i + lines >= sl->sl_cur) {
769 * Update the global ttywidth value, using TIOCGWINSZ.
774 struct winsize winsize;
776 if (ioctl(fileno(stdout), TIOCGWINSZ, &winsize) != -1)
777 ttywidth = winsize.ws_col;
783 * Set the SIGALRM interval timer for wait seconds, 0 to disable.
788 struct itimerval itv;
790 itv.it_value.tv_sec = wait;
791 itv.it_value.tv_usec = 0;
792 itv.it_interval = itv.it_value;
793 setitimer(ITIMER_REAL, &itv, NULL);
797 * Setup or cleanup EditLine structures
803 if (editing && el == NULL && hist == NULL) {
804 el = el_init(__progname, stdin, stdout); /* init editline */
805 hist = history_init(); /* init the builtin history */
806 history(hist, H_EVENT, 100); /* remember 100 events */
807 el_set(el, EL_HIST, history, hist); /* use history */
809 el_set(el, EL_EDITOR, "emacs"); /* default editor is emacs */
810 el_set(el, EL_PROMPT, prompt); /* set the prompt function */
812 /* add local file completion, bind to TAB */
813 el_set(el, EL_ADDFN, "ftp-complete",
814 "Context sensitive argument completion",
816 el_set(el, EL_BIND, "^I", "ftp-complete", NULL);
818 el_source(el, NULL); /* read ~/.editrc */
819 el_set(el, EL_SIGNAL, 1);
820 } else if (!editing) {
834 * Determine if given string is an IPv6 address or not.
835 * Return 1 for yes, 0 for no
838 isipv6addr(const char *addr)
842 struct addrinfo hints, *res;
844 memset(&hints, 0, sizeof(hints));
845 hints.ai_family = PF_INET6;
846 hints.ai_socktype = SOCK_DGRAM; /*dummy*/
847 hints.ai_flags = AI_NUMERICHOST;
848 if (getaddrinfo(addr, "0", &hints, &res) != 0)
855 printf("isipv6addr: got %d for %s\n", rv, addr);
857 return (rv == 1) ? 1 : 0;