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