xref: /netbsd-src/usr.bin/ftp/util.c (revision df0caa2637da0538ecdf6b878c4d08e684b43d8f)
1 /*	$NetBSD: util.c,v 1.129 2005/06/10 00:18:47 lukem Exp $	*/
2 
3 /*-
4  * Copyright (c) 1997-2005 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. Neither the name of the University nor the names of its contributors
56  *    may be used to endorse or promote products derived from this software
57  *    without specific prior written permission.
58  *
59  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
60  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
61  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
62  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
63  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
64  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
65  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
66  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
67  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
68  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
69  * SUCH DAMAGE.
70  */
71 
72 #include <sys/cdefs.h>
73 #ifndef lint
74 __RCSID("$NetBSD: util.c,v 1.129 2005/06/10 00:18:47 lukem Exp $");
75 #endif /* not lint */
76 
77 /*
78  * FTP User Program -- Misc support routines
79  */
80 #include <sys/param.h>
81 #include <sys/socket.h>
82 #include <sys/ioctl.h>
83 #include <sys/time.h>
84 #include <netinet/in.h>
85 #include <arpa/ftp.h>
86 
87 #include <ctype.h>
88 #include <err.h>
89 #include <errno.h>
90 #include <fcntl.h>
91 #include <glob.h>
92 #include <signal.h>
93 #include <libgen.h>
94 #include <limits.h>
95 #include <netdb.h>
96 #include <stdio.h>
97 #include <stdlib.h>
98 #include <string.h>
99 #include <termios.h>
100 #include <time.h>
101 #include <tzfile.h>
102 #include <unistd.h>
103 
104 #include "ftp_var.h"
105 
106 /*
107  * Connect to peer server and auto-login, if possible.
108  */
109 void
110 setpeer(int argc, char *argv[])
111 {
112 	char *host;
113 	char *port;
114 
115 	if (argc == 0)
116 		goto usage;
117 	if (connected) {
118 		fprintf(ttyout, "Already connected to %s, use close first.\n",
119 		    hostname);
120 		code = -1;
121 		return;
122 	}
123 	if (argc < 2)
124 		(void)another(&argc, &argv, "to");
125 	if (argc < 2 || argc > 3) {
126  usage:
127 		fprintf(ttyout, "usage: %s host-name [port]\n", argv[0]);
128 		code = -1;
129 		return;
130 	}
131 	if (gatemode)
132 		port = gateport;
133 	else
134 		port = ftpport;
135 	if (argc > 2)
136 		port = argv[2];
137 
138 	if (gatemode) {
139 		if (gateserver == NULL || *gateserver == '\0')
140 			errx(1, "gateserver not defined (shouldn't happen)");
141 		host = hookup(gateserver, port);
142 	} else
143 		host = hookup(argv[1], port);
144 
145 	if (host) {
146 		if (gatemode && verbose) {
147 			fprintf(ttyout,
148 			    "Connecting via pass-through server %s\n",
149 			    gateserver);
150 		}
151 
152 		connected = 1;
153 		/*
154 		 * Set up defaults for FTP.
155 		 */
156 		(void)strlcpy(typename, "ascii", sizeof(typename));
157 		type = TYPE_A;
158 		curtype = TYPE_A;
159 		(void)strlcpy(formname, "non-print", sizeof(formname));
160 		form = FORM_N;
161 		(void)strlcpy(modename, "stream", sizeof(modename));
162 		mode = MODE_S;
163 		(void)strlcpy(structname, "file", sizeof(structname));
164 		stru = STRU_F;
165 		(void)strlcpy(bytename, "8", sizeof(bytename));
166 		bytesize = 8;
167 		if (autologin)
168 			(void)ftp_login(argv[1], NULL, NULL);
169 	}
170 }
171 
172 static void
173 parse_feat(const char *line)
174 {
175 
176 			/*
177 			 * work-around broken ProFTPd servers that can't
178 			 * even obey RFC 2389.
179 			 */
180 	while (*line && isspace((int)*line))
181 		line++;
182 
183 	if (strcasecmp(line, "MDTM") == 0)
184 		features[FEAT_MDTM] = 1;
185 	else if (strncasecmp(line, "MLST", sizeof("MLST") - 1) == 0) {
186 		features[FEAT_MLST] = 1;
187 	} else if (strcasecmp(line, "REST STREAM") == 0)
188 		features[FEAT_REST_STREAM] = 1;
189 	else if (strcasecmp(line, "SIZE") == 0)
190 		features[FEAT_SIZE] = 1;
191 	else if (strcasecmp(line, "TVFS") == 0)
192 		features[FEAT_TVFS] = 1;
193 }
194 
195 /*
196  * Determine the remote system type (SYST) and features (FEAT).
197  * Call after a successful login (i.e, connected = -1)
198  */
199 void
200 getremoteinfo(void)
201 {
202 	int overbose, i;
203 
204 	overbose = verbose;
205 	if (debug == 0)
206 		verbose = -1;
207 
208 			/* determine remote system type */
209 	if (command("SYST") == COMPLETE) {
210 		if (overbose) {
211 			char *cp, c;
212 
213 			c = 0;
214 			cp = strchr(reply_string + 4, ' ');
215 			if (cp == NULL)
216 				cp = strchr(reply_string + 4, '\r');
217 			if (cp) {
218 				if (cp[-1] == '.')
219 					cp--;
220 				c = *cp;
221 				*cp = '\0';
222 			}
223 
224 			fprintf(ttyout, "Remote system type is %s.\n",
225 			    reply_string + 4);
226 			if (cp)
227 				*cp = c;
228 		}
229 		if (!strncmp(reply_string, "215 UNIX Type: L8", 17)) {
230 			if (proxy)
231 				unix_proxy = 1;
232 			else
233 				unix_server = 1;
234 			/*
235 			 * Set type to 0 (not specified by user),
236 			 * meaning binary by default, but don't bother
237 			 * telling server.  We can use binary
238 			 * for text files unless changed by the user.
239 			 */
240 			type = 0;
241 			(void)strlcpy(typename, "binary", sizeof(typename));
242 			if (overbose)
243 			    fprintf(ttyout,
244 				"Using %s mode to transfer files.\n",
245 				typename);
246 		} else {
247 			if (proxy)
248 				unix_proxy = 0;
249 			else
250 				unix_server = 0;
251 			if (overbose &&
252 			    !strncmp(reply_string, "215 TOPS20", 10))
253 				fputs(
254 "Remember to set tenex mode when transferring binary files from this machine.\n",
255 				    ttyout);
256 		}
257 	}
258 
259 			/* determine features (if any) */
260 	for (i = 0; i < FEAT_max; i++)
261 		features[i] = -1;
262 	reply_callback = parse_feat;
263 	if (command("FEAT") == COMPLETE) {
264 		for (i = 0; i < FEAT_max; i++) {
265 			if (features[i] == -1)
266 				features[i] = 0;
267 		}
268 		features[FEAT_FEAT] = 1;
269 	} else
270 		features[FEAT_FEAT] = 0;
271 	if (debug) {
272 #define DEBUG_FEAT(x) fprintf(ttyout, "features[" #x "] = %d\n", features[(x)])
273 		DEBUG_FEAT(FEAT_FEAT);
274 		DEBUG_FEAT(FEAT_MDTM);
275 		DEBUG_FEAT(FEAT_MLST);
276 		DEBUG_FEAT(FEAT_REST_STREAM);
277 		DEBUG_FEAT(FEAT_SIZE);
278 		DEBUG_FEAT(FEAT_TVFS);
279 #undef DEBUG_FEAT
280 	}
281 	reply_callback = NULL;
282 
283 	verbose = overbose;
284 }
285 
286 /*
287  * Reset the various variables that indicate connection state back to
288  * disconnected settings.
289  * The caller is responsible for issuing any commands to the remote server
290  * to perform a clean shutdown before this is invoked.
291  */
292 void
293 cleanuppeer(void)
294 {
295 
296 	if (cout)
297 		(void)fclose(cout);
298 	cout = NULL;
299 	connected = 0;
300 	unix_server = 0;
301 	unix_proxy = 0;
302 			/*
303 			 * determine if anonftp was specifically set with -a
304 			 * (1), or implicitly set by auto_fetch() (2). in the
305 			 * latter case, disable after the current xfer
306 			 */
307 	if (anonftp == 2)
308 		anonftp = 0;
309 	data = -1;
310 	epsv4bad = 0;
311 	if (username)
312 		free(username);
313 	username = NULL;
314 	if (!proxy)
315 		macnum = 0;
316 }
317 
318 /*
319  * Top-level signal handler for interrupted commands.
320  */
321 void
322 intr(int signo)
323 {
324 
325 	sigint_raised = 1;
326 	alarmtimer(0);
327 	if (fromatty)
328 		write(fileno(ttyout), "\n", 1);
329 	siglongjmp(toplevel, 1);
330 }
331 
332 /*
333  * Signal handler for lost connections; cleanup various elements of
334  * the connection state, and call cleanuppeer() to finish it off.
335  */
336 void
337 lostpeer(int dummy)
338 {
339 	int oerrno = errno;
340 
341 	alarmtimer(0);
342 	if (connected) {
343 		if (cout != NULL) {
344 			(void)shutdown(fileno(cout), 1+1);
345 			(void)fclose(cout);
346 			cout = NULL;
347 		}
348 		if (data >= 0) {
349 			(void)shutdown(data, 1+1);
350 			(void)close(data);
351 			data = -1;
352 		}
353 		connected = 0;
354 	}
355 	pswitch(1);
356 	if (connected) {
357 		if (cout != NULL) {
358 			(void)shutdown(fileno(cout), 1+1);
359 			(void)fclose(cout);
360 			cout = NULL;
361 		}
362 		connected = 0;
363 	}
364 	proxflag = 0;
365 	pswitch(0);
366 	cleanuppeer();
367 	errno = oerrno;
368 }
369 
370 
371 /*
372  * Login to remote host, using given username & password if supplied.
373  * Return non-zero if successful.
374  */
375 int
376 ftp_login(const char *host, const char *luser, const char *lpass)
377 {
378 	char tmp[80];
379 	char *user, *pass, *acct, *p;
380 	const char *errormsg;
381 	int n, aflag, rval, nlen;
382 
383 	aflag = rval = 0;
384 	user = pass = acct = NULL;
385 	if (luser)
386 		user = xstrdup(luser);
387 	if (lpass)
388 		pass = xstrdup(lpass);
389 
390 	if (debug)
391 		fprintf(ttyout, "ftp_login: user `%s' pass `%s' host `%s'\n",
392 		    user ? user : "<null>", pass ? pass : "<null>",
393 		    host ? host : "<null>");
394 
395 	/*
396 	 * Set up arguments for an anonymous FTP session, if necessary.
397 	 */
398 	if (anonftp) {
399 		FREEPTR(user);
400 		user = xstrdup("anonymous");	/* as per RFC 1635 */
401 		FREEPTR(pass);
402 		pass = xstrdup(getoptionvalue("anonpass"));
403 	}
404 
405 	if (ruserpass(host, &user, &pass, &acct) < 0) {
406 		code = -1;
407 		goto cleanup_ftp_login;
408 	}
409 
410 	while (user == NULL) {
411 		if (localname)
412 			fprintf(ttyout, "Name (%s:%s): ", host, localname);
413 		else
414 			fprintf(ttyout, "Name (%s): ", host);
415 		errormsg = NULL;
416 		nlen = getline(stdin, tmp, sizeof(tmp), &errormsg);
417 		if (nlen < 0) {
418 			fprintf(ttyout, "%s; %s aborted.\n", errormsg, "login");
419 			code = -1;
420 			goto cleanup_ftp_login;
421 		} else if (nlen == 0) {
422 			user = xstrdup(localname);
423 		} else {
424 			user = xstrdup(tmp);
425 		}
426 	}
427 
428 	if (gatemode) {
429 		char *nuser;
430 		size_t len;
431 
432 		len = strlen(user) + 1 + strlen(host) + 1;
433 		nuser = xmalloc(len);
434 		(void)strlcpy(nuser, user, len);
435 		(void)strlcat(nuser, "@",  len);
436 		(void)strlcat(nuser, host, len);
437 		FREEPTR(user);
438 		user = nuser;
439 	}
440 
441 	n = command("USER %s", user);
442 	if (n == CONTINUE) {
443 		if (pass == NULL) {
444 			p = getpass("Password: ");
445 			pass = xstrdup(p);
446 			memset(p, 0, strlen(p));
447 		}
448 		n = command("PASS %s", pass);
449 		memset(pass, 0, strlen(pass));
450 	}
451 	if (n == CONTINUE) {
452 		aflag++;
453 		if (acct == NULL) {
454 			p = getpass("Account: ");
455 			acct = xstrdup(p);
456 			memset(p, 0, strlen(p));
457 		}
458 		if (acct[0] == '\0') {
459 			warnx("Login failed.");
460 			goto cleanup_ftp_login;
461 		}
462 		n = command("ACCT %s", acct);
463 		memset(acct, 0, strlen(acct));
464 	}
465 	if ((n != COMPLETE) ||
466 	    (!aflag && acct != NULL && command("ACCT %s", acct) != COMPLETE)) {
467 		warnx("Login failed.");
468 		goto cleanup_ftp_login;
469 	}
470 	rval = 1;
471 	username = xstrdup(user);
472 	if (proxy)
473 		goto cleanup_ftp_login;
474 
475 	connected = -1;
476 	getremoteinfo();
477 	for (n = 0; n < macnum; ++n) {
478 		if (!strcmp("init", macros[n].mac_name)) {
479 			(void)strlcpy(line, "$init", sizeof(line));
480 			makeargv();
481 			domacro(margc, margv);
482 			break;
483 		}
484 	}
485 	updatelocalcwd();
486 	updateremotecwd();
487 
488  cleanup_ftp_login:
489 	FREEPTR(user);
490 	if (pass != NULL)
491 		memset(pass, 0, strlen(pass));
492 	FREEPTR(pass);
493 	if (acct != NULL)
494 		memset(acct, 0, strlen(pass));
495 	FREEPTR(acct);
496 	return (rval);
497 }
498 
499 /*
500  * `another' gets another argument, and stores the new argc and argv.
501  * It reverts to the top level (via intr()) on EOF/error.
502  *
503  * Returns false if no new arguments have been added.
504  */
505 int
506 another(int *pargc, char ***pargv, const char *prompt)
507 {
508 	const char	*errormsg;
509 	int		ret, nlen;
510 	size_t		len;
511 
512 	len = strlen(line);
513 	if (len >= sizeof(line) - 3) {
514 		fputs("Sorry, arguments too long.\n", ttyout);
515 		intr(0);
516 	}
517 	fprintf(ttyout, "(%s) ", prompt);
518 	line[len++] = ' ';
519 	errormsg = NULL;
520 	nlen = getline(stdin, line + len, sizeof(line)-len, &errormsg);
521 	if (nlen < 0) {
522 		fprintf(ttyout, "%s; %s aborted.\n", errormsg, "operation");
523 		intr(0);
524 	}
525 	len += nlen;
526 	makeargv();
527 	ret = margc > *pargc;
528 	*pargc = margc;
529 	*pargv = margv;
530 	return (ret);
531 }
532 
533 /*
534  * glob files given in argv[] from the remote server.
535  * if errbuf isn't NULL, store error messages there instead
536  * of writing to the screen.
537  */
538 char *
539 remglob(char *argv[], int doswitch, const char **errbuf)
540 {
541 	static char buf[MAXPATHLEN];
542 	static FILE *ftemp = NULL;
543 	static char **args;
544 	char temp[MAXPATHLEN];
545 	int oldverbose, oldhash, oldprogress, fd;
546 	char *cp;
547 	const char *mode;
548 	size_t len;
549 
550 	if (!mflag || !connected) {
551 		if (!doglob)
552 			args = NULL;
553 		else {
554 			if (ftemp) {
555 				(void)fclose(ftemp);
556 				ftemp = NULL;
557 			}
558 		}
559 		return (NULL);
560 	}
561 	if (!doglob) {
562 		if (args == NULL)
563 			args = argv;
564 		if ((cp = *++args) == NULL)
565 			args = NULL;
566 		return (cp);
567 	}
568 	if (ftemp == NULL) {
569 		len = strlcpy(temp, tmpdir, sizeof(temp));
570 		if (temp[len - 1] != '/')
571 			(void)strlcat(temp, "/", sizeof(temp));
572 		(void)strlcat(temp, TMPFILE, sizeof(temp));
573 		if ((fd = mkstemp(temp)) < 0) {
574 			warn("unable to create temporary file %s", temp);
575 			return (NULL);
576 		}
577 		close(fd);
578 		oldverbose = verbose;
579 		verbose = (errbuf != NULL) ? -1 : 0;
580 		oldhash = hash;
581 		oldprogress = progress;
582 		hash = 0;
583 		progress = 0;
584 		if (doswitch)
585 			pswitch(!proxy);
586 		for (mode = "w"; *++argv != NULL; mode = "a")
587 			recvrequest("NLST", temp, *argv, mode, 0, 0);
588 		if ((code / 100) != COMPLETE) {
589 			if (errbuf != NULL)
590 				*errbuf = reply_string;
591 		}
592 		if (doswitch)
593 			pswitch(!proxy);
594 		verbose = oldverbose;
595 		hash = oldhash;
596 		progress = oldprogress;
597 		ftemp = fopen(temp, "r");
598 		(void)unlink(temp);
599 		if (ftemp == NULL) {
600 			if (errbuf == NULL)
601 				fputs(
602 				    "can't find list of remote files, oops.\n",
603 				    ttyout);
604 			else
605 				*errbuf =
606 				    "can't find list of remote files, oops.";
607 			return (NULL);
608 		}
609 	}
610 	if (fgets(buf, sizeof(buf), ftemp) == NULL) {
611 		(void)fclose(ftemp);
612 		ftemp = NULL;
613 		return (NULL);
614 	}
615 	if ((cp = strchr(buf, '\n')) != NULL)
616 		*cp = '\0';
617 	return (buf);
618 }
619 
620 /*
621  * Glob a local file name specification with the expectation of a single
622  * return value. Can't control multiple values being expanded from the
623  * expression, we return only the first.
624  * Returns NULL on error, or a pointer to a buffer containing the filename
625  * that's the caller's responsiblity to free(3) when finished with.
626  */
627 char *
628 globulize(const char *pattern)
629 {
630 	glob_t gl;
631 	int flags;
632 	char *p;
633 
634 	if (!doglob)
635 		return (xstrdup(pattern));
636 
637 	flags = GLOB_BRACE|GLOB_NOCHECK|GLOB_TILDE;
638 	memset(&gl, 0, sizeof(gl));
639 	if (glob(pattern, flags, NULL, &gl) || gl.gl_pathc == 0) {
640 		warnx("%s: not found", pattern);
641 		globfree(&gl);
642 		return (NULL);
643 	}
644 	p = xstrdup(gl.gl_pathv[0]);
645 	globfree(&gl);
646 	return (p);
647 }
648 
649 /*
650  * determine size of remote file
651  */
652 off_t
653 remotesize(const char *file, int noisy)
654 {
655 	int overbose, r;
656 	off_t size;
657 
658 	overbose = verbose;
659 	size = -1;
660 	if (debug == 0)
661 		verbose = -1;
662 	if (! features[FEAT_SIZE]) {
663 		if (noisy)
664 			fprintf(ttyout,
665 			    "SIZE is not supported by remote server.\n");
666 		goto cleanup_remotesize;
667 	}
668 	r = command("SIZE %s", file);
669 	if (r == COMPLETE) {
670 		char *cp, *ep;
671 
672 		cp = strchr(reply_string, ' ');
673 		if (cp != NULL) {
674 			cp++;
675 			size = STRTOLL(cp, &ep, 10);
676 			if (*ep != '\0' && !isspace((unsigned char)*ep))
677 				size = -1;
678 		}
679 	} else {
680 		if (r == ERROR && code == 500 && features[FEAT_SIZE] == -1)
681 			features[FEAT_SIZE] = 0;
682 		if (noisy && debug == 0) {
683 			fputs(reply_string, ttyout);
684 			putc('\n', ttyout);
685 		}
686 	}
687  cleanup_remotesize:
688 	verbose = overbose;
689 	return (size);
690 }
691 
692 /*
693  * determine last modification time (in GMT) of remote file
694  */
695 time_t
696 remotemodtime(const char *file, int noisy)
697 {
698 	int	overbose, ocode, r;
699 	time_t	rtime;
700 
701 	overbose = verbose;
702 	ocode = code;
703 	rtime = -1;
704 	if (debug == 0)
705 		verbose = -1;
706 	if (! features[FEAT_MDTM]) {
707 		if (noisy)
708 			fprintf(ttyout,
709 			    "MDTM is not supported by remote server.\n");
710 		goto cleanup_parse_time;
711 	}
712 	r = command("MDTM %s", file);
713 	if (r == COMPLETE) {
714 		struct tm timebuf;
715 		char *timestr, *frac;
716 		int yy, mo, day, hour, min, sec;
717 
718 		/*
719 		 * time-val = 14DIGIT [ "." 1*DIGIT ]
720 		 *		YYYYMMDDHHMMSS[.sss]
721 		 * mdtm-response = "213" SP time-val CRLF / error-response
722 		 */
723 		timestr = reply_string + 4;
724 
725 					/*
726 					 * parse fraction.
727 					 * XXX: ignored for now
728 					 */
729 		frac = strchr(timestr, '\r');
730 		if (frac != NULL)
731 			*frac = '\0';
732 		frac = strchr(timestr, '.');
733 		if (frac != NULL)
734 			*frac++ = '\0';
735 		if (strlen(timestr) == 15 && strncmp(timestr, "191", 3) == 0) {
736 			/*
737 			 * XXX:	Workaround for lame ftpd's that return
738 			 *	`19100' instead of `2000'
739 			 */
740 			fprintf(ttyout,
741 	    "Y2K warning! Incorrect time-val `%s' received from server.\n",
742 			    timestr);
743 			timestr++;
744 			timestr[0] = '2';
745 			timestr[1] = '0';
746 			fprintf(ttyout, "Converted to `%s'\n", timestr);
747 		}
748 		if (strlen(timestr) != 14 ||
749 		    sscanf(timestr, "%04d%02d%02d%02d%02d%02d",
750 			&yy, &mo, &day, &hour, &min, &sec) != 6) {
751  bad_parse_time:
752 			fprintf(ttyout, "Can't parse time `%s'.\n", timestr);
753 			goto cleanup_parse_time;
754 		}
755 		memset(&timebuf, 0, sizeof(timebuf));
756 		timebuf.tm_sec = sec;
757 		timebuf.tm_min = min;
758 		timebuf.tm_hour = hour;
759 		timebuf.tm_mday = day;
760 		timebuf.tm_mon = mo - 1;
761 		timebuf.tm_year = yy - TM_YEAR_BASE;
762 		timebuf.tm_isdst = -1;
763 		rtime = timegm(&timebuf);
764 		if (rtime == -1) {
765 			if (noisy || debug != 0)
766 				goto bad_parse_time;
767 			else
768 				goto cleanup_parse_time;
769 		} else if (debug)
770 			fprintf(ttyout, "parsed date as: %s", ctime(&rtime));
771 	} else {
772 		if (r == ERROR && code == 500 && features[FEAT_MDTM] == -1)
773 			features[FEAT_MDTM] = 0;
774 		if (noisy && debug == 0) {
775 			fputs(reply_string, ttyout);
776 			putc('\n', ttyout);
777 		}
778 	}
779  cleanup_parse_time:
780 	verbose = overbose;
781 	if (rtime == -1)
782 		code = ocode;
783 	return (rtime);
784 }
785 
786 /*
787  * Update global `localcwd', which contains the state of the local cwd
788  */
789 void
790 updatelocalcwd(void)
791 {
792 
793 	if (getcwd(localcwd, sizeof(localcwd)) == NULL)
794 		localcwd[0] = '\0';
795 	if (debug)
796 		fprintf(ttyout, "got localcwd as `%s'\n", localcwd);
797 }
798 
799 /*
800  * Update global `remotecwd', which contains the state of the remote cwd
801  */
802 void
803 updateremotecwd(void)
804 {
805 	int	 overbose, ocode, i;
806 	char	*cp;
807 
808 	overbose = verbose;
809 	ocode = code;
810 	if (debug == 0)
811 		verbose = -1;
812 	if (command("PWD") != COMPLETE)
813 		goto badremotecwd;
814 	cp = strchr(reply_string, ' ');
815 	if (cp == NULL || cp[0] == '\0' || cp[1] != '"')
816 		goto badremotecwd;
817 	cp += 2;
818 	for (i = 0; *cp && i < sizeof(remotecwd) - 1; i++, cp++) {
819 		if (cp[0] == '"') {
820 			if (cp[1] == '"')
821 				cp++;
822 			else
823 				break;
824 		}
825 		remotecwd[i] = *cp;
826 	}
827 	remotecwd[i] = '\0';
828 	if (debug)
829 		fprintf(ttyout, "got remotecwd as `%s'\n", remotecwd);
830 	goto cleanupremotecwd;
831  badremotecwd:
832 	remotecwd[0]='\0';
833  cleanupremotecwd:
834 	verbose = overbose;
835 	code = ocode;
836 }
837 
838 /*
839  * Ensure file is in or under dir.
840  * Returns 1 if so, 0 if not (or an error occurred).
841  */
842 int
843 fileindir(const char *file, const char *dir)
844 {
845 	char	parentdirbuf[PATH_MAX+1], *parentdir;
846 	char	realdir[PATH_MAX+1];
847 	size_t	dirlen;
848 
849 		 			/* determine parent directory of file */
850 	(void)strlcpy(parentdirbuf, file, sizeof(parentdirbuf));
851 	parentdir = dirname(parentdirbuf);
852 	if (strcmp(parentdir, ".") == 0)
853 		return 1;		/* current directory is ok */
854 
855 					/* find the directory */
856 	if (realpath(parentdir, realdir) == NULL) {
857 		warn("Unable to determine real path of `%s'", parentdir);
858 		return 0;
859 	}
860 	if (realdir[0] != '/')		/* relative result is ok */
861 		return 1;
862 	dirlen = strlen(dir);
863 #if 0
864 printf("file %s parent %s realdir %s dir %s [%d]\n",
865     file, parentdir, realdir, dir, dirlen);
866 #endif
867 	if (strncmp(realdir, dir, dirlen) == 0 &&
868 	    (realdir[dirlen] == '/' || realdir[dirlen] == '\0'))
869 		return 1;
870 	return 0;
871 }
872 
873 /*
874  * List words in stringlist, vertically arranged
875  */
876 void
877 list_vertical(StringList *sl)
878 {
879 	int i, j;
880 	int columns, lines;
881 	char *p;
882 	size_t w, width;
883 
884 	width = 0;
885 
886 	for (i = 0 ; i < sl->sl_cur ; i++) {
887 		w = strlen(sl->sl_str[i]);
888 		if (w > width)
889 			width = w;
890 	}
891 	width = (width + 8) &~ 7;
892 
893 	columns = ttywidth / width;
894 	if (columns == 0)
895 		columns = 1;
896 	lines = (sl->sl_cur + columns - 1) / columns;
897 	for (i = 0; i < lines; i++) {
898 		for (j = 0; j < columns; j++) {
899 			p = sl->sl_str[j * lines + i];
900 			if (p)
901 				fputs(p, ttyout);
902 			if (j * lines + i + lines >= sl->sl_cur) {
903 				putc('\n', ttyout);
904 				break;
905 			}
906 			w = strlen(p);
907 			while (w < width) {
908 				w = (w + 8) &~ 7;
909 				(void)putc('\t', ttyout);
910 			}
911 		}
912 	}
913 }
914 
915 /*
916  * Update the global ttywidth value, using TIOCGWINSZ.
917  */
918 void
919 setttywidth(int a)
920 {
921 	struct winsize winsize;
922 	int oerrno = errno;
923 
924 	if (ioctl(fileno(ttyout), TIOCGWINSZ, &winsize) != -1 &&
925 	    winsize.ws_col != 0)
926 		ttywidth = winsize.ws_col;
927 	else
928 		ttywidth = 80;
929 	errno = oerrno;
930 }
931 
932 /*
933  * Change the rate limit up (SIGUSR1) or down (SIGUSR2)
934  */
935 void
936 crankrate(int sig)
937 {
938 
939 	switch (sig) {
940 	case SIGUSR1:
941 		if (rate_get)
942 			rate_get += rate_get_incr;
943 		if (rate_put)
944 			rate_put += rate_put_incr;
945 		break;
946 	case SIGUSR2:
947 		if (rate_get && rate_get > rate_get_incr)
948 			rate_get -= rate_get_incr;
949 		if (rate_put && rate_put > rate_put_incr)
950 			rate_put -= rate_put_incr;
951 		break;
952 	default:
953 		err(1, "crankrate invoked with unknown signal: %d", sig);
954 	}
955 }
956 
957 
958 /*
959  * Setup or cleanup EditLine structures
960  */
961 #ifndef NO_EDITCOMPLETE
962 void
963 controlediting(void)
964 {
965 	if (editing && el == NULL && hist == NULL) {
966 		HistEvent ev;
967 		int editmode;
968 
969 		el = el_init(getprogname(), stdin, ttyout, stderr);
970 		/* init editline */
971 		hist = history_init();		/* init the builtin history */
972 		history(hist, &ev, H_SETSIZE, 100);/* remember 100 events */
973 		el_set(el, EL_HIST, history, hist);	/* use history */
974 
975 		el_set(el, EL_EDITOR, "emacs");	/* default editor is emacs */
976 		el_set(el, EL_PROMPT, prompt);	/* set the prompt functions */
977 		el_set(el, EL_RPROMPT, rprompt);
978 
979 		/* add local file completion, bind to TAB */
980 		el_set(el, EL_ADDFN, "ftp-complete",
981 		    "Context sensitive argument completion",
982 		    complete);
983 		el_set(el, EL_BIND, "^I", "ftp-complete", NULL);
984 		el_source(el, NULL);	/* read ~/.editrc */
985 		if ((el_get(el, EL_EDITMODE, &editmode) != -1) && editmode == 0)
986 			editing = 0;	/* the user doesn't want editing,
987 					 * so disable, and let statement
988 					 * below cleanup */
989 		else
990 			el_set(el, EL_SIGNAL, 1);
991 	}
992 	if (!editing) {
993 		if (hist) {
994 			history_end(hist);
995 			hist = NULL;
996 		}
997 		if (el) {
998 			el_end(el);
999 			el = NULL;
1000 		}
1001 	}
1002 }
1003 #endif /* !NO_EDITCOMPLETE */
1004 
1005 /*
1006  * Convert the string `arg' to an int, which may have an optional SI suffix
1007  * (`b', `k', `m', `g'). Returns the number for success, -1 otherwise.
1008  */
1009 int
1010 strsuftoi(const char *arg)
1011 {
1012 	char *cp;
1013 	long val;
1014 
1015 	if (!isdigit((unsigned char)arg[0]))
1016 		return (-1);
1017 
1018 	val = strtol(arg, &cp, 10);
1019 	if (cp != NULL) {
1020 		if (cp[0] != '\0' && cp[1] != '\0')
1021 			 return (-1);
1022 		switch (tolower((unsigned char)cp[0])) {
1023 		case '\0':
1024 		case 'b':
1025 			break;
1026 		case 'k':
1027 			val <<= 10;
1028 			break;
1029 		case 'm':
1030 			val <<= 20;
1031 			break;
1032 		case 'g':
1033 			val <<= 30;
1034 			break;
1035 		default:
1036 			return (-1);
1037 		}
1038 	}
1039 	if (val < 0 || val > INT_MAX)
1040 		return (-1);
1041 
1042 	return (val);
1043 }
1044 
1045 /*
1046  * Set up socket buffer sizes before a connection is made.
1047  */
1048 void
1049 setupsockbufsize(int sock)
1050 {
1051 
1052 	if (setsockopt(sock, SOL_SOCKET, SO_SNDBUF,
1053 	    (void *)&sndbuf_size, sizeof(sndbuf_size)) == -1)
1054 		warn("unable to set sndbuf size %d", sndbuf_size);
1055 
1056 	if (setsockopt(sock, SOL_SOCKET, SO_RCVBUF,
1057 	    (void *)&rcvbuf_size, sizeof(rcvbuf_size)) == -1)
1058 		warn("unable to set rcvbuf size %d", rcvbuf_size);
1059 }
1060 
1061 /*
1062  * Copy characters from src into dst, \ quoting characters that require it
1063  */
1064 void
1065 ftpvis(char *dst, size_t dstlen, const char *src, size_t srclen)
1066 {
1067 	int	di, si;
1068 
1069 	for (di = si = 0;
1070 	    src[si] != '\0' && di < dstlen && si < srclen;
1071 	    di++, si++) {
1072 		switch (src[si]) {
1073 		case '\\':
1074 		case ' ':
1075 		case '\t':
1076 		case '\r':
1077 		case '\n':
1078 		case '"':
1079 			dst[di++] = '\\';
1080 			if (di >= dstlen)
1081 				break;
1082 			/* FALLTHROUGH */
1083 		default:
1084 			dst[di] = src[si];
1085 		}
1086 	}
1087 	dst[di] = '\0';
1088 }
1089 
1090 /*
1091  * Copy src into buf (which is len bytes long), expanding % sequences.
1092  */
1093 void
1094 formatbuf(char *buf, size_t len, const char *src)
1095 {
1096 	const char	*p, *p2, *q;
1097 	int		 i, op, updirs, pdirs;
1098 
1099 #define ADDBUF(x) do { \
1100 		if (i >= len - 1) \
1101 			goto endbuf; \
1102 		buf[i++] = (x); \
1103 	} while (0)
1104 
1105 	p = src;
1106 	for (i = 0; *p; p++) {
1107 		if (*p != '%') {
1108 			ADDBUF(*p);
1109 			continue;
1110 		}
1111 		p++;
1112 
1113 		switch (op = *p) {
1114 
1115 		case '/':
1116 		case '.':
1117 		case 'c':
1118 			p2 = connected ? remotecwd : "";
1119 			updirs = pdirs = 0;
1120 
1121 			/* option to determine fixed # of dirs from path */
1122 			if (op == '.' || op == 'c') {
1123 				int skip;
1124 
1125 				q = p2;
1126 				while (*p2)		/* calc # of /'s */
1127 					if (*p2++ == '/')
1128 						updirs++;
1129 				if (p[1] == '0') {	/* print <x> or ... */
1130 					pdirs = 1;
1131 					p++;
1132 				}
1133 				if (p[1] >= '1' && p[1] <= '9') {
1134 							/* calc # to skip  */
1135 					skip = p[1] - '0';
1136 					p++;
1137 				} else
1138 					skip = 1;
1139 
1140 				updirs -= skip;
1141 				while (skip-- > 0) {
1142 					while ((p2 > q) && (*p2 != '/'))
1143 						p2--;	/* back up */
1144 					if (skip && p2 > q)
1145 						p2--;
1146 				}
1147 				if (*p2 == '/' && p2 != q)
1148 					p2++;
1149 			}
1150 
1151 			if (updirs > 0 && pdirs) {
1152 				if (i >= len - 5)
1153 					break;
1154 				if (op == '.') {
1155 					ADDBUF('.');
1156 					ADDBUF('.');
1157 					ADDBUF('.');
1158 				} else {
1159 					ADDBUF('/');
1160 					ADDBUF('<');
1161 					if (updirs > 9) {
1162 						ADDBUF('9');
1163 						ADDBUF('+');
1164 					} else
1165 						ADDBUF('0' + updirs);
1166 					ADDBUF('>');
1167 				}
1168 			}
1169 			for (; *p2; p2++)
1170 				ADDBUF(*p2);
1171 			break;
1172 
1173 		case 'M':
1174 		case 'm':
1175 			for (p2 = connected && hostname ? hostname : "-";
1176 			    *p2 ; p2++) {
1177 				if (op == 'm' && *p2 == '.')
1178 					break;
1179 				ADDBUF(*p2);
1180 			}
1181 			break;
1182 
1183 		case 'n':
1184 			for (p2 = connected ? username : "-"; *p2 ; p2++)
1185 				ADDBUF(*p2);
1186 			break;
1187 
1188 		case '%':
1189 			ADDBUF('%');
1190 			break;
1191 
1192 		default:		/* display unknown codes literally */
1193 			ADDBUF('%');
1194 			ADDBUF(op);
1195 			break;
1196 
1197 		}
1198 	}
1199  endbuf:
1200 	buf[i] = '\0';
1201 }
1202 
1203 /*
1204  * Parse `port' into a TCP port number, defaulting to `defport' if `port' is
1205  * an unknown service name. If defport != -1, print a warning upon bad parse.
1206  */
1207 int
1208 parseport(const char *port, int defport)
1209 {
1210 	int	 rv;
1211 	long	 nport;
1212 	char	*p, *ep;
1213 
1214 	p = xstrdup(port);
1215 	nport = strtol(p, &ep, 10);
1216 	if (*ep != '\0' && ep == p) {
1217 		struct servent	*svp;
1218 
1219 		svp = getservbyname(port, "tcp");
1220 		if (svp == NULL) {
1221  badparseport:
1222 			if (defport != -1)
1223 				warnx("Unknown port `%s', using port %d",
1224 				    port, defport);
1225 			rv = defport;
1226 		} else
1227 			rv = ntohs(svp->s_port);
1228 	} else if (nport < 1 || nport > MAX_IN_PORT_T || *ep != '\0')
1229 		goto badparseport;
1230 	else
1231 		rv = nport;
1232 	free(p);
1233 	return (rv);
1234 }
1235 
1236 /*
1237  * Determine if given string is an IPv6 address or not.
1238  * Return 1 for yes, 0 for no
1239  */
1240 int
1241 isipv6addr(const char *addr)
1242 {
1243 	int rv = 0;
1244 #ifdef INET6
1245 	struct addrinfo hints, *res;
1246 
1247 	memset(&hints, 0, sizeof(hints));
1248 	hints.ai_family = PF_INET6;
1249 	hints.ai_socktype = SOCK_DGRAM;	/*dummy*/
1250 	hints.ai_flags = AI_NUMERICHOST;
1251 	if (getaddrinfo(addr, "0", &hints, &res) != 0)
1252 		rv = 0;
1253 	else {
1254 		rv = 1;
1255 		freeaddrinfo(res);
1256 	}
1257 	if (debug)
1258 		fprintf(ttyout, "isipv6addr: got %d for %s\n", rv, addr);
1259 #endif
1260 	return (rv == 1) ? 1 : 0;
1261 }
1262 
1263 /*
1264  * Read a line from the FILE stream into buf/buflen using fgets(), so up
1265  * to buflen-1 chars will be read and the result will be NUL terminated.
1266  * If the line has a trailing newline it will be removed.
1267  * If the line is too long, excess characters will be read until
1268  * newline/EOF/error.
1269  * If EOF/error occurs or a too-long line is encountered and errormsg
1270  * isn't NULL, it will be changed to a description of the problem.
1271  * (The EOF message has a leading \n for cosmetic purposes).
1272  * Returns:
1273  *	>=0	length of line (excluding trailing newline) if all ok
1274  *	-1	error occurred
1275  *	-2	EOF encountered
1276  *	-3	line was too long
1277  */
1278 int
1279 getline(FILE *stream, char *buf, size_t buflen, const char **errormsg)
1280 {
1281 	int	rv, ch;
1282 	size_t	len;
1283 
1284 	if (fgets(buf, buflen, stream) == NULL) {
1285 		if (feof(stream)) {	/* EOF */
1286 			rv = -2;
1287 			if (errormsg)
1288 				*errormsg = "\nEOF received";
1289 		} else  {		/* error */
1290 			rv = -1;
1291 			if (errormsg)
1292 				*errormsg = "Error encountered";
1293 		}
1294 		clearerr(stream);
1295 		return rv;
1296 	}
1297 	len = strlen(buf);
1298 	if (buf[len-1] == '\n') {	/* clear any trailing newline */
1299 		buf[--len] = '\0';
1300 	} else if (len == buflen-1) {	/* line too long */
1301 		while ((ch = getchar()) != '\n' && ch != EOF)
1302 			continue;
1303 		if (errormsg)
1304 			*errormsg = "Input line is too long";
1305 		clearerr(stream);
1306 		return -3;
1307 	}
1308 	if (errormsg)
1309 		*errormsg = NULL;
1310 	return len;
1311 }
1312 
1313 
1314 /*
1315  * Internal version of connect(2); sets socket buffer sizes first and
1316  * supports a connection timeout using a non-blocking connect(2) with
1317  * a poll(2).
1318  * Socket fcntl flags are temporarily updated to include O_NONBLOCK;
1319  * these will not be reverted on connection failure.
1320  * Returns -1 upon failure (with errno set to the problem), or 0 on success.
1321  */
1322 int
1323 xconnect(int sock, const struct sockaddr *name, socklen_t namelen)
1324 {
1325 	int		flags, rv, timeout, error;
1326 	socklen_t	slen;
1327 	struct timeval	endtime, now, td;
1328 	struct pollfd	pfd[1];
1329 
1330 	setupsockbufsize(sock);
1331 
1332 	if ((flags = fcntl(sock, F_GETFL, 0)) == -1)
1333 		return -1;			/* get current socket flags  */
1334 	if (fcntl(sock, F_SETFL, flags | O_NONBLOCK) == -1)
1335 		return -1;			/* set non-blocking connect */
1336 
1337 	/* NOTE: we now must restore socket flags on successful exit */
1338 
1339 	pfd[0].fd = sock;
1340 	pfd[0].events = POLLIN|POLLOUT;
1341 
1342 	if (quit_time > 0) {			/* want a non default timeout */
1343 		(void)gettimeofday(&endtime, NULL);
1344 		endtime.tv_sec += quit_time;	/* determine end time */
1345 	}
1346 
1347 	rv = connect(sock, name, namelen);	/* inititate the connection */
1348 	if (rv == -1) {				/* connection error */
1349 		if (errno != EINPROGRESS)	/* error isn't "please wait" */
1350 			return -1;
1351 
1352 						/* connect EINPROGRESS; wait */
1353 		do {
1354 			if (quit_time > 0) {	/* determine timeout */
1355 				(void)gettimeofday(&now, NULL);
1356 				timersub(&endtime, &now, &td);
1357 				timeout = td.tv_sec * 1000 + td.tv_usec/1000;
1358 				if (timeout < 0)
1359 					timeout = 0;
1360 			} else {
1361 				timeout = INFTIM;
1362 			}
1363 			pfd[0].revents = 0;
1364 			rv = xpoll(pfd, 1, timeout);
1365 						/* loop until poll ! EINTR */
1366 		} while (rv == -1 && errno == EINTR);
1367 
1368 		if (rv == 0) {			/* poll (connect) timed out */
1369 			errno = ETIMEDOUT;
1370 			return -1;
1371 		}
1372 
1373 		if (rv == -1) {			/* poll error */
1374 			return -1;
1375 		} else if (pfd[0].revents & (POLLIN|POLLOUT)) {
1376 			slen = sizeof(error);	/* OK, or pending error */
1377 			if (getsockopt(sock, SOL_SOCKET, SO_ERROR,
1378 			    &error, &slen) == -1)
1379 				return -1;	/* Solaris pending error */
1380 			if (error != 0) {
1381 				errno = error;	/* BSD pending error */
1382 				return -1;
1383 			}
1384 		} else {
1385 			errno = EBADF;		/* this shouldn't happen ... */
1386 			return -1;
1387 		}
1388 	}
1389 
1390 	if (fcntl(sock, F_SETFL, flags) == -1)	/* restore socket flags */
1391 		return -1;
1392 	return 0;
1393 }
1394 
1395 /*
1396  * Internal version of listen(2); sets socket buffer sizes first.
1397  */
1398 int
1399 xlisten(int sock, int backlog)
1400 {
1401 
1402 	setupsockbufsize(sock);
1403 	return (listen(sock, backlog));
1404 }
1405 
1406 /*
1407  * Internal version of poll(2), to allow reimplementation by select(2)
1408  * on platforms without the former.
1409  */
1410 int
1411 xpoll(struct pollfd *fds, int nfds, int timeout)
1412 {
1413 	return poll(fds, nfds, timeout);
1414 }
1415 
1416 /*
1417  * malloc() with inbuilt error checking
1418  */
1419 void *
1420 xmalloc(size_t size)
1421 {
1422 	void *p;
1423 
1424 	p = malloc(size);
1425 	if (p == NULL)
1426 		err(1, "Unable to allocate %ld bytes of memory", (long)size);
1427 	return (p);
1428 }
1429 
1430 /*
1431  * sl_init() with inbuilt error checking
1432  */
1433 StringList *
1434 xsl_init(void)
1435 {
1436 	StringList *p;
1437 
1438 	p = sl_init();
1439 	if (p == NULL)
1440 		err(1, "Unable to allocate memory for stringlist");
1441 	return (p);
1442 }
1443 
1444 /*
1445  * sl_add() with inbuilt error checking
1446  */
1447 void
1448 xsl_add(StringList *sl, char *i)
1449 {
1450 
1451 	if (sl_add(sl, i) == -1)
1452 		err(1, "Unable to add `%s' to stringlist", i);
1453 }
1454 
1455 /*
1456  * strdup() with inbuilt error checking
1457  */
1458 char *
1459 xstrdup(const char *str)
1460 {
1461 	char *s;
1462 
1463 	if (str == NULL)
1464 		errx(1, "xstrdup() called with NULL argument");
1465 	s = strdup(str);
1466 	if (s == NULL)
1467 		err(1, "Unable to allocate memory for string copy");
1468 	return (s);
1469 }
1470