Home | History | Annotate | Line # | Download | only in ftp
util.c revision 1.2
      1 /*	$NetBSD: util.c,v 1.2 1997/01/30 03:36:26 thorpej Exp $	*/
      2 
      3 /*
      4  * Copyright (c) 1985, 1989, 1993, 1994
      5  *	The Regents of the University of California.  All rights reserved.
      6  *
      7  * Redistribution and use in source and binary forms, with or without
      8  * modification, are permitted provided that the following conditions
      9  * are met:
     10  * 1. Redistributions of source code must retain the above copyright
     11  *    notice, this list of conditions and the following disclaimer.
     12  * 2. Redistributions in binary form must reproduce the above copyright
     13  *    notice, this list of conditions and the following disclaimer in the
     14  *    documentation and/or other materials provided with the distribution.
     15  * 3. All advertising materials mentioning features or use of this software
     16  *    must display the following acknowledgement:
     17  *	This product includes software developed by the University of
     18  *	California, Berkeley and its contributors.
     19  * 4. Neither the name of the University nor the names of its contributors
     20  *    may be used to endorse or promote products derived from this software
     21  *    without specific prior written permission.
     22  *
     23  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     24  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     25  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     26  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     27  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     28  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     29  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     30  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     31  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     32  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     33  * SUCH DAMAGE.
     34  */
     35 
     36 #ifndef lint
     37 static char rcsid[] = "$NetBSD: util.c,v 1.2 1997/01/30 03:36:26 thorpej Exp $";
     38 #endif /* not lint */
     39 
     40 /*
     41  * FTP User Program -- Misc support routines
     42  */
     43 #include <sys/ioctl.h>
     44 #include <sys/time.h>
     45 #include <arpa/ftp.h>
     46 
     47 #include <ctype.h>
     48 #include <err.h>
     49 #include <fcntl.h>
     50 #include <glob.h>
     51 #include <stdio.h>
     52 #include <string.h>
     53 #include <time.h>
     54 #include <unistd.h>
     55 
     56 #include "ftp_var.h"
     57 #include "pathnames.h"
     58 
     59 /*
     60  * Connect to peer server and
     61  * auto-login, if possible.
     62  */
     63 void
     64 setpeer(argc, argv)
     65 	int argc;
     66 	char *argv[];
     67 {
     68 	char *host;
     69 	short port;
     70 
     71 	if (connected) {
     72 		printf("Already connected to %s, use close first.\n",
     73 			hostname);
     74 		code = -1;
     75 		return;
     76 	}
     77 	if (argc < 2)
     78 		(void) another(&argc, &argv, "to");
     79 	if (argc < 2 || argc > 3) {
     80 		printf("usage: %s host-name [port]\n", argv[0]);
     81 		code = -1;
     82 		return;
     83 	}
     84 	port = ftpport;
     85 	if (argc > 2) {
     86 		port = atoi(argv[2]);
     87 		if (port <= 0) {
     88 			printf("%s: bad port number-- %s\n", argv[1], argv[2]);
     89 			printf ("usage: %s host-name [port]\n", argv[0]);
     90 			code = -1;
     91 			return;
     92 		}
     93 		port = htons(port);
     94 	}
     95 	host = hookup(argv[1], port);
     96 	if (host) {
     97 		int overbose;
     98 
     99 		connected = 1;
    100 		/*
    101 		 * Set up defaults for FTP.
    102 		 */
    103 		(void) strcpy(typename, "ascii"), type = TYPE_A;
    104 		curtype = TYPE_A;
    105 		(void) strcpy(formname, "non-print"), form = FORM_N;
    106 		(void) strcpy(modename, "stream"), mode = MODE_S;
    107 		(void) strcpy(structname, "file"), stru = STRU_F;
    108 		(void) strcpy(bytename, "8"), bytesize = 8;
    109 		if (autologin)
    110 			(void) login(argv[1]);
    111 
    112 		overbose = verbose;
    113 		if (debug == 0)
    114 			verbose = -1;
    115 		if (command("SYST") == COMPLETE && overbose) {
    116 			char *cp, c;
    117 			c = 0;
    118 			cp = strchr(reply_string+4, ' ');
    119 			if (cp == NULL)
    120 				cp = strchr(reply_string+4, '\r');
    121 			if (cp) {
    122 				if (cp[-1] == '.')
    123 					cp--;
    124 				c = *cp;
    125 				*cp = '\0';
    126 			}
    127 
    128 			printf("Remote system type is %s.\n",
    129 				reply_string+4);
    130 			if (cp)
    131 				*cp = c;
    132 		}
    133 		if (!strncmp(reply_string, "215 UNIX Type: L8", 17)) {
    134 			if (proxy)
    135 				unix_proxy = 1;
    136 			else
    137 				unix_server = 1;
    138 			/*
    139 			 * Set type to 0 (not specified by user),
    140 			 * meaning binary by default, but don't bother
    141 			 * telling server.  We can use binary
    142 			 * for text files unless changed by the user.
    143 			 */
    144 			type = 0;
    145 			(void) strcpy(typename, "binary");
    146 			if (overbose)
    147 			    printf("Using %s mode to transfer files.\n",
    148 				typename);
    149 		} else {
    150 			if (proxy)
    151 				unix_proxy = 0;
    152 			else
    153 				unix_server = 0;
    154 			if (overbose &&
    155 			    !strncmp(reply_string, "215 TOPS20", 10))
    156 				printf("Remember to set tenex mode when "
    157 				    "transferring binary files from this "
    158 				    "machine.\n");
    159 		}
    160 		verbose = overbose;
    161 	}
    162 }
    163 
    164 /*
    165  * `Another' gets another argument, and stores the new argc and argv.
    166  * It reverts to the top level (via main.c's intr()) on EOF/error.
    167  *
    168  * Returns false if no new arguments have been added.
    169  */
    170 int
    171 another(pargc, pargv, prompt)
    172 	int *pargc;
    173 	char ***pargv;
    174 	const char *prompt;
    175 {
    176 	int len = strlen(line), ret;
    177 
    178 	if (len >= sizeof(line) - 3) {
    179 		printf("sorry, arguments too long\n");
    180 		intr();
    181 	}
    182 	printf("(%s) ", prompt);
    183 	line[len++] = ' ';
    184 	if (fgets(&line[len], sizeof(line) - len, stdin) == NULL)
    185 		intr();
    186 	len += strlen(&line[len]);
    187 	if (len > 0 && line[len - 1] == '\n')
    188 		line[len - 1] = '\0';
    189 	makeargv();
    190 	ret = margc > *pargc;
    191 	*pargc = margc;
    192 	*pargv = margv;
    193 	return (ret);
    194 }
    195 
    196 char *
    197 remglob(argv, doswitch)
    198         char *argv[];
    199         int doswitch;
    200 {
    201         char temp[MAXPATHLEN];
    202         static char buf[MAXPATHLEN];
    203         static FILE *ftemp = NULL;
    204         static char **args;
    205         int oldverbose, oldhash, fd;
    206         char *cp, *mode;
    207 
    208         if (!mflag) {
    209                 if (!doglob) {
    210                         args = NULL;
    211                 }
    212                 else {
    213                         if (ftemp) {
    214                                 (void) fclose(ftemp);
    215                                 ftemp = NULL;
    216                         }
    217                 }
    218                 return (NULL);
    219         }
    220         if (!doglob) {
    221                 if (args == NULL)
    222                         args = argv;
    223                 if ((cp = *++args) == NULL)
    224                         args = NULL;
    225                 return (cp);
    226         }
    227         if (ftemp == NULL) {
    228                 (void) snprintf(temp, sizeof(temp), "%s%s", _PATH_TMP, TMPFILE)
    229 ;
    230                 fd = mkstemp(temp);
    231                 if (fd < 0) {
    232                         warn("unable to create temporary file %s", temp);
    233                         return (NULL);
    234                 }
    235                 close(fd);
    236                 oldverbose = verbose, verbose = 0;
    237                 oldhash = hash, hash = 0;
    238                 if (doswitch) {
    239                         pswitch(!proxy);
    240                 }
    241                 for (mode = "w"; *++argv != NULL; mode = "a")
    242                         recvrequest ("NLST", temp, *argv, mode, 0);
    243                 if (doswitch) {
    244                         pswitch(!proxy);
    245                 }
    246                 verbose = oldverbose; hash = oldhash;
    247                 ftemp = fopen(temp, "r");
    248                 (void) unlink(temp);
    249                 if (ftemp == NULL) {
    250                         printf("can't find list of remote files, oops\n");
    251                         return (NULL);
    252                 }
    253         }
    254         if (fgets(buf, sizeof (buf), ftemp) == NULL) {
    255                 (void) fclose(ftemp), ftemp = NULL;
    256                 return (NULL);
    257         }
    258         if ((cp = strchr(buf, '\n')) != NULL)
    259                 *cp = '\0';
    260         return (buf);
    261 }
    262 
    263 int
    264 confirm(cmd, file)
    265 	const char *cmd, *file;
    266 {
    267 	char line[BUFSIZ];
    268 
    269 	if (!interactive || confirmrest)
    270 		return (1);
    271 	printf("%s %s? ", cmd, file);
    272 	(void) fflush(stdout);
    273 	if (fgets(line, sizeof(line), stdin) == NULL)
    274 		return (0);
    275 	switch (tolower(*line)) {
    276 		case 'n':
    277 			return (0);
    278 		case 'p':
    279 			interactive = 0;
    280 			printf("Interactive mode: off\n");
    281 			break;
    282 		case 'a':
    283 			confirmrest = 1;
    284 			printf("Prompting off for duration of %s\n", cmd);
    285 			break;
    286 	}
    287 	return (1);
    288 }
    289 
    290 /*
    291  * Glob a local file name specification with
    292  * the expectation of a single return value.
    293  * Can't control multiple values being expanded
    294  * from the expression, we return only the first.
    295  */
    296 int
    297 globulize(cpp)
    298 	char **cpp;
    299 {
    300 	glob_t gl;
    301 	int flags;
    302 
    303 	if (!doglob)
    304 		return (1);
    305 
    306 	flags = GLOB_BRACE|GLOB_NOCHECK|GLOB_QUOTE|GLOB_TILDE;
    307 	memset(&gl, 0, sizeof(gl));
    308 	if (glob(*cpp, flags, NULL, &gl) ||
    309 	    gl.gl_pathc == 0) {
    310 		warnx("%s: not found", *cpp);
    311 		globfree(&gl);
    312 		return (0);
    313 	}
    314 	*cpp = strdup(gl.gl_pathv[0]);	/* XXX - wasted memory */
    315 	globfree(&gl);
    316 	return (1);
    317 }
    318 
    319 /*
    320  * determine size of remote file
    321  */
    322 off_t
    323 remotesize(file, noisy)
    324 	const char *file;
    325 	int noisy;
    326 {
    327 	int overbose;
    328 	off_t size;
    329 
    330 	overbose = verbose;
    331 	size = -1;
    332 	if (debug == 0)
    333 		verbose = -1;
    334 	if (command("SIZE %s", file) == COMPLETE)
    335 		sscanf(reply_string, "%*s %qd", &size);
    336 	else if (noisy && debug == 0)
    337 		printf("%s\n", reply_string);
    338 	verbose = overbose;
    339 	return (size);
    340 }
    341 
    342 /*
    343  * determine last modification time (in GMT) of remote file
    344  */
    345 time_t
    346 remotemodtime(file, noisy)
    347 	const char *file;
    348 	int noisy;
    349 {
    350 	int overbose;
    351 	time_t rtime;
    352 
    353 	overbose = verbose;
    354 	rtime = -1;
    355 	if (debug == 0)
    356 		verbose = -1;
    357 	if (command("MDTM %s", file) == COMPLETE) {
    358 		struct tm timebuf;
    359 		int yy, mo, day, hour, min, sec;
    360 		sscanf(reply_string, "%*s %04d%02d%02d%02d%02d%02d", &yy, &mo,
    361 			&day, &hour, &min, &sec);
    362 		memset(&timebuf, 0, sizeof(timebuf));
    363 		timebuf.tm_sec = sec;
    364 		timebuf.tm_min = min;
    365 		timebuf.tm_hour = hour;
    366 		timebuf.tm_mday = day;
    367 		timebuf.tm_mon = mo - 1;
    368 		timebuf.tm_year = yy - 1900;
    369 		timebuf.tm_isdst = -1;
    370 		rtime = mktime(&timebuf);
    371 		if (rtime == -1 && (noisy || debug != 0))
    372 			printf("Can't convert %s to a time\n", reply_string);
    373 		else
    374 			rtime += timebuf.tm_gmtoff;	/* conv. local -> GMT */
    375 	} else if (noisy && debug == 0)
    376 		printf("%s\n", reply_string);
    377 	verbose = overbose;
    378 	return (rtime);
    379 }
    380 
    381 /*
    382  * Display a transfer progress bar if progress is non-zero.
    383  * - Before transfer, set filesize to size of file (-1 = unknown),
    384  *   and call with flag < 0
    385  * - During transfer, update bytes and call with flag = 0
    386  * - After transfer, call with flag > 1
    387  */
    388 static struct timeval start;
    389 
    390 void
    391 progressmeter(flag)
    392 	int flag;
    393 {
    394 	static struct timeval before;
    395 	static int ttywidth;
    396 	struct winsize winsize;
    397 	struct timeval now, td;
    398 	off_t cursize, abbrevsize;
    399 	double elapsed;
    400 	int ratio, barlength, i, remaining;
    401 	char prefixes[] = " KMGTP";	/* `P' because 2^64 = 16384 Petabytes */
    402 
    403 	if (flag < 0)
    404 		(void) gettimeofday(&start, (struct timezone *)0);
    405 	if (!progress || filesize <= 0)
    406 		return;
    407 	if (flag < 0) {
    408 		before.tv_sec = -1;
    409 		if (ioctl(fileno(stdin), TIOCGWINSZ, &winsize) < 0)
    410 			ttywidth = 80;
    411 		else
    412 			ttywidth = winsize.ws_col;
    413 	} else if (flag == 0) {
    414 		(void) gettimeofday(&now, (struct timezone *)0);
    415 		if (now.tv_sec <= before.tv_sec)
    416 			return;
    417 	}
    418 	before = now;
    419 	cursize = bytes + restart_point;
    420 
    421 	ratio = cursize * 100 / filesize;
    422 	ratio = MAX(ratio, 0);
    423 	ratio = MIN(ratio, 100);
    424 	printf("\r%3d%% ", ratio);
    425 
    426 	barlength = ttywidth - 30;
    427 	if (barlength > 0) {
    428 		i = barlength * ratio / 100;
    429 		printf("|%.*s%*s|", i,
    430 "*****************************************************************************"
    431 "*****************************************************************************",
    432 		    barlength - i, "");
    433 	}
    434 
    435 	i = 0;
    436 	abbrevsize = cursize;
    437 	while (abbrevsize >= 100000 && i < sizeof(prefixes)) {
    438 		i++;
    439 		abbrevsize >>= 10;
    440 	}
    441 	printf(" %5qd %c%c  ", abbrevsize, prefixes[i],
    442 	    prefixes[i] == ' ' ? ' ' : 'B');
    443 
    444 	timersub(&now, &start, &td);
    445 	elapsed = td.tv_sec + (td.tv_usec / 1000000.0);
    446 	if (bytes <= 0 || elapsed <= 0.0) {
    447 		printf("   --:--");
    448 	} else {
    449 		remaining = (int)((filesize - restart_point) /
    450 				  (bytes / elapsed) - elapsed);
    451 		i = remaining / 3600;
    452 		if (i)
    453 			printf("%2d:", i);
    454 		else
    455 			printf("   ");
    456 		i = remaining % 3600;
    457 		printf("%02d:%02d", i / 60, i % 60);
    458 	}
    459 	printf(" ETA");
    460 
    461 	if (flag > 0)
    462 		(void) putchar('\n');
    463 	fflush(stdout);
    464 }
    465 
    466 /*
    467  * Display transfer statistics.
    468  * Requires start to be initialised by progressmeter(-1),
    469  * direction to be defined by xfer routines, and filesize and bytes
    470  * to be updated by xfer routines
    471  * If siginfo is nonzero, an ETA is displayed, and the output goes to STDERR
    472  * instead of STDOUT.
    473  */
    474 void
    475 ptransfer(siginfo)
    476 	int siginfo;
    477 {
    478 	struct timeval now, td;
    479 	double elapsed;
    480 	off_t bs;
    481 	int meg, remaining, hh;
    482 	char buf[100];
    483 
    484 	if (!verbose && !siginfo)
    485 		return;
    486 
    487 	(void) gettimeofday(&now, (struct timezone *)0);
    488 	timersub(&now, &start, &td);
    489 	elapsed = td.tv_sec + (td.tv_usec / 1000000.0);
    490 	bs = bytes / (elapsed == 0.0 ? 1 : elapsed);
    491 	meg = 0;
    492 	if (bs > (1024 * 1024))
    493 		meg = 1;
    494 	(void)snprintf(buf, sizeof(buf),
    495 	    "%qd byte%s %s in %.2f seconds (%.2f %sB/s)\n",
    496 	    bytes, bytes == 1 ? "" : "s", direction, elapsed,
    497 	    bs / (1024.0 * (meg ? 1024.0 : 1.0)), meg ? "M" : "K");
    498 	if (siginfo && bytes > 0 && elapsed > 0.0) {
    499 		remaining = (int)((filesize - restart_point) /
    500 				  (bytes / elapsed) - elapsed);
    501 		hh = remaining / 3600;
    502 		remaining %= 3600;
    503 		snprintf(buf + strlen(buf) - 1, sizeof(buf) - strlen(buf),
    504 		    "  ETA: %02d:%02d:%02d\n", hh, remaining / 60,
    505 		    remaining % 60);
    506 	}
    507 	(void)write(siginfo ? STDERR_FILENO : STDOUT_FILENO, buf, strlen(buf));
    508 }
    509 
    510 /*
    511  * List words in stringlist, vertically arranged
    512  */
    513 void
    514 list_vertical(sl)
    515 	StringList *sl;
    516 {
    517 	static int ttywidth;
    518 	struct winsize winsize;
    519 	int i, j, w;
    520 	int columns, width, lines, items;
    521 	char *p;
    522 
    523 	width = items = 0;
    524 	if (fromatty && ioctl(fileno(stdin), TIOCGWINSZ, &winsize) != -1)
    525 		ttywidth = winsize.ws_col;
    526 	else
    527 		ttywidth = 80;
    528 
    529 	for (i = 0 ; i < sl->sl_cur ; i++) {
    530 		w = strlen(sl->sl_str[i]);
    531 		if (w > width)
    532 			width = w;
    533 	}
    534 	width = (width + 8) &~ 7;
    535 
    536 	columns = ttywidth / width;
    537 	if (columns == 0)
    538 		columns = 1;
    539 	lines = (sl->sl_cur + columns - 1) / columns;
    540 	for (i = 0; i < lines; i++) {
    541 		for (j = 0; j < columns; j++) {
    542 			p = sl->sl_str[j * lines + i];
    543 			if (p)
    544 				printf("%s", p);
    545 			if (j * lines + i + lines >= sl->sl_cur) {
    546 				printf("\n");
    547 				break;
    548 			}
    549 			w = strlen(p);
    550 			while (w < width) {
    551 				w = (w + 8) &~ 7;
    552 				(void) putchar('\t');
    553 			}
    554 		}
    555 	}
    556 }
    557