1 /* $Id: util.c,v 1.5 1998/02/03 20:53:25 pst Exp $ */
2 /* $NetBSD: util.c,v 1.16.2.1 1997/11/18 01:02:33 mellon Exp $ */
5 * Copyright (c) 1985, 1989, 1993, 1994
6 * The Regents of the University of California. All rights reserved.
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
16 * 3. All advertising materials mentioning features or use of this software
17 * must display the following acknowledgement:
18 * This product includes software developed by the University of
19 * California, Berkeley and its contributors.
20 * 4. Neither the name of the University nor the names of its contributors
21 * may be used to endorse or promote products derived from this software
22 * without specific prior written permission.
24 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
37 #include <sys/cdefs.h>
39 __RCSID("$Id: util.c,v 1.5 1998/02/03 20:53:25 pst Exp $");
40 __RCSID_SOURCE("$NetBSD: util.c,v 1.16.2.1 1997/11/18 01:02:33 mellon Exp $");
44 * FTP User Program -- Misc support routines
46 #include <sys/ioctl.h>
63 #include "pathnames.h"
66 #define SECSPERHOUR (60*60)
70 * Connect to peer server and
71 * auto-login, if possible.
82 printf("Already connected to %s, use close first.\n",
88 (void)another(&argc, &argv, "to");
89 if (argc < 2 || argc > 3) {
90 printf("usage: %s host-name [port]\n", argv[0]);
102 nport = strtol(argv[2], &ep, 10);
103 if (nport < 1 || nport > 0xffff || *ep != '\0') {
104 printf("%s: bad port number '%s'.\n", argv[1], argv[2]);
105 printf("usage: %s host-name [port]\n", argv[0]);
113 if (gateserver == NULL || *gateserver == '\0')
114 errx(1, "gateserver not defined (shouldn't happen)");
115 host = hookup(gateserver, port);
117 host = hookup(argv[1], port);
123 if (command("PASSERVE %s", argv[1]) != COMPLETE)
126 printf("Connected via pass-through server %s\n",
132 * Set up defaults for FTP.
134 (void)strcpy(typename, "ascii"), type = TYPE_A;
136 (void)strcpy(formname, "non-print"), form = FORM_N;
137 (void)strcpy(modename, "stream"), mode = MODE_S;
138 (void)strcpy(structname, "file"), stru = STRU_F;
139 (void)strcpy(bytename, "8"), bytesize = 8;
141 (void)login(argv[1], NULL, NULL);
146 if (command("SYST") == COMPLETE && overbose) {
149 cp = strchr(reply_string+4, ' ');
151 cp = strchr(reply_string+4, '\r');
159 printf("Remote system type is %s.\n", reply_string + 4);
163 if (!strncmp(reply_string, "215 UNIX Type: L8", 17)) {
169 * Set type to 0 (not specified by user),
170 * meaning binary by default, but don't bother
171 * telling server. We can use binary
172 * for text files unless changed by the user.
175 (void)strcpy(typename, "binary");
177 printf("Using %s mode to transfer files.\n",
185 !strncmp(reply_string, "215 TOPS20", 10))
187 "Remember to set tenex mode when transferring binary files from this machine.");
195 * login to remote host, using given username & password if supplied
198 login(host, user, pass)
204 char anonpass[MAXLOGNAME + 1 + MAXHOSTNAMELEN]; /* "user@hostname" */
205 char hostname[MAXHOSTNAMELEN];
211 if (ruserpass(host, &user, &pass, &acct) < 0) {
218 * Set up arguments for an anonymous FTP session, if necessary.
220 if ((user == NULL || pass == NULL) && anonftp) {
221 memset(anonpass, 0, sizeof(anonpass));
222 memset(hostname, 0, sizeof(hostname));
225 * Set up anonymous login password.
227 if ((user = getlogin()) == NULL) {
228 if ((pw = getpwuid(getuid())) == NULL)
233 gethostname(hostname, MAXHOSTNAMELEN);
234 #ifndef DONT_CHEAT_ANONPASS
236 * Every anonymous FTP server I've encountered
237 * will accept the string "username@", and will
238 * append the hostname itself. We do this by default
239 * since many servers are picky about not having
240 * a FQDN in the anonymous password. - thorpej@netbsd.org
242 snprintf(anonpass, sizeof(anonpass) - 1, "%s@",
245 snprintf(anonpass, sizeof(anonpass) - 1, "%s@%s",
249 user = "anonymous"; /* as per RFC 1635 */
252 while (user == NULL) {
253 char *myname = getlogin();
255 if (myname == NULL && (pw = getpwuid(getuid())) != NULL)
256 myname = pw->pw_name;
258 printf("Name (%s:%s): ", host, myname);
260 printf("Name (%s): ", host);
261 if (fgets(tmp, sizeof(tmp) - 1, stdin) == NULL)
263 tmp[strlen(tmp) - 1] = '\0';
269 n = command("USER %s", user);
272 pass = getpass("Password:");
273 n = command("PASS %s", pass);
278 acct = getpass("Account:");
279 n = command("ACCT %s", acct);
281 if ((n != COMPLETE) ||
282 (!aflag && acct != NULL && command("ACCT %s", acct) != COMPLETE)) {
283 warnx("Login failed.");
289 for (n = 0; n < macnum; ++n) {
290 if (!strcmp("init", macros[n].mac_name)) {
291 (void)strcpy(line, "$init");
293 domacro(margc, margv);
301 * `another' gets another argument, and stores the new argc and argv.
302 * It reverts to the top level (via main.c's intr()) on EOF/error.
304 * Returns false if no new arguments have been added.
307 another(pargc, pargv, prompt)
312 int len = strlen(line), ret;
314 if (len >= sizeof(line) - 3) {
315 puts("sorry, arguments too long.");
318 printf("(%s) ", prompt);
320 if (fgets(&line[len], sizeof(line) - len, stdin) == NULL)
322 len += strlen(&line[len]);
323 if (len > 0 && line[len - 1] == '\n')
324 line[len - 1] = '\0';
326 ret = margc > *pargc;
333 * glob files given in argv[] from the remote server.
334 * if errbuf isn't NULL, store error messages there instead
335 * of writing to the screen.
338 remglob(argv, doswitch, errbuf)
343 char temp[MAXPATHLEN];
344 static char buf[MAXPATHLEN];
345 static FILE *ftemp = NULL;
347 int oldverbose, oldhash, fd;
364 if ((cp = *++args) == NULL)
369 (void)snprintf(temp, sizeof(temp), "%s/%s", tmpdir, TMPFILE);
370 if ((fd = mkstemp(temp)) < 0) {
371 warn("unable to create temporary file %s", temp);
375 oldverbose = verbose;
376 verbose = (errbuf != NULL) ? -1 : 0;
381 for (mode = "w"; *++argv != NULL; mode = "a")
382 recvrequest("NLST", temp, *argv, mode, 0, 0);
383 if ((code / 100) != COMPLETE) {
385 *errbuf = reply_string;
389 verbose = oldverbose;
391 ftemp = fopen(temp, "r");
395 puts("can't find list of remote files, oops.");
398 "can't find list of remote files, oops.";
402 if (fgets(buf, sizeof(buf), ftemp) == NULL) {
407 if ((cp = strchr(buf, '\n')) != NULL)
414 const char *cmd, *file;
418 if (!interactive || confirmrest)
420 printf("%s %s? ", cmd, file);
421 (void)fflush(stdout);
422 if (fgets(line, sizeof(line), stdin) == NULL)
424 switch (tolower((unsigned char)*line)) {
429 puts("Interactive mode: off.");
433 printf("Prompting off for duration of %s.\n", cmd);
440 * Glob a local file name specification with
441 * the expectation of a single return value.
442 * Can't control multiple values being expanded
443 * from the expression, we return only the first.
455 flags = GLOB_BRACE|GLOB_NOCHECK|GLOB_QUOTE|GLOB_TILDE;
456 memset(&gl, 0, sizeof(gl));
457 if (glob(*cpp, flags, NULL, &gl) ||
459 warnx("%s: not found", *cpp);
463 /* XXX: caller should check if *cpp changed, and
464 * free(*cpp) if that is the case
466 *cpp = strdup(gl.gl_pathv[0]);
472 * determine size of remote file
475 remotesize(file, noisy)
486 if (command("SIZE %s", file) == COMPLETE) {
489 cp = strchr(reply_string, ' ');
492 size = strtoq(cp, &ep, 10);
493 if (*ep != '\0' && !isspace((unsigned char)*ep))
496 } else if (noisy && debug == 0)
503 * determine last modification time (in GMT) of remote file
506 remotemodtime(file, noisy)
519 if (command("MDTM %s", file) == COMPLETE) {
521 int yy, mo, day, hour, min, sec;
522 sscanf(reply_string, "%*s %04d%02d%02d%02d%02d%02d", &yy, &mo,
523 &day, &hour, &min, &sec);
524 memset(&timebuf, 0, sizeof(timebuf));
525 timebuf.tm_sec = sec;
526 timebuf.tm_min = min;
527 timebuf.tm_hour = hour;
528 timebuf.tm_mday = day;
529 timebuf.tm_mon = mo - 1;
530 timebuf.tm_year = yy - 1900;
531 timebuf.tm_isdst = -1;
532 rtime = mktime(&timebuf);
533 if (rtime == -1 && (noisy || debug != 0))
534 printf("Can't convert %s to a time.\n", reply_string);
536 rtime += timebuf.tm_gmtoff; /* conv. local -> GMT */
537 } else if (noisy && debug == 0)
545 void updateprogressmeter __P((int));
548 updateprogressmeter(dummy)
551 static pid_t pgrp = -1;
558 * print progress bar only if we are foreground process.
560 if (ioctl(STDOUT_FILENO, TIOCGPGRP, &ctty_pgrp) != -1 &&
561 ctty_pgrp == (int)pgrp)
566 * Display a transfer progress bar if progress is non-zero.
567 * SIGALRM is hijacked for use by this function.
568 * - Before the transfer, set filesize to size of file (or -1 if unknown),
569 * and call with flag = -1. This starts the once per second timer,
570 * and a call to updateprogressmeter() upon SIGALRM.
571 * - During the transfer, updateprogressmeter will call progressmeter
573 * - After the transfer, call with flag = 1
575 static struct timeval start;
582 * List of order of magnitude prefixes.
583 * The last is `P', as 2^64 = 16384 Petabytes
585 static const char prefixes[] = " KMGTP";
587 static struct timeval lastupdate;
588 static off_t lastsize;
589 struct timeval now, td, wait;
590 off_t cursize, abbrevsize;
592 int ratio, barlength, i, len;
599 (void)gettimeofday(&start, (struct timezone *)0);
601 lastsize = restart_point;
603 (void)gettimeofday(&now, (struct timezone *)0);
604 if (!progress || filesize <= 0)
606 cursize = bytes + restart_point;
608 ratio = cursize * 100 / filesize;
609 ratio = MAX(ratio, 0);
610 ratio = MIN(ratio, 100);
611 len += snprintf(buf + len, sizeof(buf) - len, "\r%3d%% ", ratio);
613 barlength = ttywidth - 30;
615 i = barlength * ratio / 100;
616 len += snprintf(buf + len, sizeof(buf) - len,
618 "*****************************************************************************"
619 "*****************************************************************************",
624 abbrevsize = cursize;
625 while (abbrevsize >= 100000 && i < sizeof(prefixes)) {
629 len += snprintf(buf + len, sizeof(buf) - len,
630 " %5qd %c%c ", (long long)abbrevsize, prefixes[i],
631 prefixes[i] == ' ' ? ' ' : 'B');
633 timersub(&now, &lastupdate, &wait);
634 if (cursize > lastsize) {
637 if (wait.tv_sec >= STALLTIME) { /* fudge out stalled time */
638 start.tv_sec += wait.tv_sec;
639 start.tv_usec += wait.tv_usec;
644 timersub(&now, &start, &td);
645 elapsed = td.tv_sec + (td.tv_usec / 1000000.0);
647 if (bytes <= 0 || elapsed <= 0.0 || cursize > filesize) {
648 len += snprintf(buf + len, sizeof(buf) - len,
650 } else if (wait.tv_sec >= STALLTIME) {
651 len += snprintf(buf + len, sizeof(buf) - len,
655 ((filesize - restart_point) / (bytes / elapsed) - elapsed);
656 if (remaining >= 100 * SECSPERHOUR)
657 len += snprintf(buf + len, sizeof(buf) - len,
660 i = remaining / SECSPERHOUR;
662 len += snprintf(buf + len, sizeof(buf) - len,
665 len += snprintf(buf + len, sizeof(buf) - len,
667 i = remaining % SECSPERHOUR;
668 len += snprintf(buf + len, sizeof(buf) - len,
669 "%02d:%02d ETA", i / 60, i % 60);
672 (void)write(STDOUT_FILENO, buf, len);
675 (void)signal(SIGALRM, updateprogressmeter);
676 alarmtimer(1); /* set alarm timer for 1 Hz */
677 } else if (flag == 1) {
685 * Display transfer statistics.
686 * Requires start to be initialised by progressmeter(-1),
687 * direction to be defined by xfer routines, and filesize and bytes
688 * to be updated by xfer routines
689 * If siginfo is nonzero, an ETA is displayed, and the output goes to STDERR
696 struct timeval now, td;
699 int meg, remaining, hh, len;
702 if (!verbose && !siginfo)
705 (void)gettimeofday(&now, (struct timezone *)0);
706 timersub(&now, &start, &td);
707 elapsed = td.tv_sec + (td.tv_usec / 1000000.0);
708 bs = bytes / (elapsed == 0.0 ? 1 : elapsed);
710 if (bs > (1024 * 1024))
713 len += snprintf(buf + len, sizeof(buf) - len,
714 "%qd byte%s %s in %.2f seconds (%.2f %sB/s)\n",
715 (long long)bytes, bytes == 1 ? "" : "s", direction, elapsed,
716 bs / (1024.0 * (meg ? 1024.0 : 1.0)), meg ? "M" : "K");
717 if (siginfo && bytes > 0 && elapsed > 0.0 && filesize >= 0
718 && bytes + restart_point <= filesize) {
719 remaining = (int)((filesize - restart_point) /
720 (bytes / elapsed) - elapsed);
721 hh = remaining / SECSPERHOUR;
722 remaining %= SECSPERHOUR;
723 len--; /* decrement len to overwrite \n */
724 len += snprintf(buf + len, sizeof(buf) - len,
725 " ETA: %02d:%02d:%02d\n", hh, remaining / 60,
728 (void)write(siginfo ? STDERR_FILENO : STDOUT_FILENO, buf, len);
732 * List words in stringlist, vertically arranged
739 int columns, width, lines, items;
744 for (i = 0 ; i < sl->sl_cur ; i++) {
745 w = strlen(sl->sl_str[i]);
749 width = (width + 8) &~ 7;
751 columns = ttywidth / width;
754 lines = (sl->sl_cur + columns - 1) / columns;
755 for (i = 0; i < lines; i++) {
756 for (j = 0; j < columns; j++) {
757 p = sl->sl_str[j * lines + i];
760 if (j * lines + i + lines >= sl->sl_cur) {
774 * Update the global ttywidth value, using TIOCGWINSZ.
780 struct winsize winsize;
782 if (ioctl(fileno(stdout), TIOCGWINSZ, &winsize) != -1)
783 ttywidth = winsize.ws_col;
789 * Set the SIGALRM interval timer for wait seconds, 0 to disable.
795 struct itimerval itv;
797 itv.it_value.tv_sec = wait;
798 itv.it_value.tv_usec = 0;
799 itv.it_interval = itv.it_value;
800 setitimer(ITIMER_REAL, &itv, NULL);
804 * Setup or cleanup EditLine structures
810 if (editing && el == NULL && hist == NULL) {
811 el = el_init(__progname, stdin, stdout); /* init editline */
812 hist = history_init(); /* init the builtin history */
813 history(hist, H_EVENT, 100); /* remember 100 events */
814 el_set(el, EL_HIST, history, hist); /* use history */
816 el_set(el, EL_EDITOR, "emacs"); /* default editor is emacs */
817 el_set(el, EL_PROMPT, prompt); /* set the prompt function */
819 /* add local file completion, bind to TAB */
820 el_set(el, EL_ADDFN, "ftp-complete",
821 "Context sensitive argument completion",
823 el_set(el, EL_BIND, "^I", "ftp-complete", NULL);
825 el_source(el, NULL); /* read ~/.editrc */
826 el_set(el, EL_SIGNAL, 1);
827 } else if (!editing) {