xref: /freebsd/contrib/tnftp/src/util.c (revision 2abb9b42a53c39a8b781e25a05de1de9e98b8b9a)
1 /*	$NetBSD: util.c,v 1.21 2009/11/15 10:12:37 lukem Exp $	*/
2 /*	from	NetBSD: util.c,v 1.152 2009/07/13 19:05:41 roy Exp	*/
3 
4 /*-
5  * Copyright (c) 1997-2009 The NetBSD Foundation, Inc.
6  * All rights reserved.
7  *
8  * This code is derived from software contributed to The NetBSD Foundation
9  * by Luke Mewburn.
10  *
11  * This code is derived from software contributed to The NetBSD Foundation
12  * by Jason R. Thorpe of the Numerical Aerospace Simulation Facility,
13  * NASA Ames Research Center.
14  *
15  * Redistribution and use in source and binary forms, with or without
16  * modification, are permitted provided that the following conditions
17  * are met:
18  * 1. Redistributions of source code must retain the above copyright
19  *    notice, this list of conditions and the following disclaimer.
20  * 2. Redistributions in binary form must reproduce the above copyright
21  *    notice, this list of conditions and the following disclaimer in the
22  *    documentation and/or other materials provided with the distribution.
23  *
24  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
25  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
26  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
27  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
28  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
29  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
30  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
31  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
32  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
33  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
34  * POSSIBILITY OF SUCH DAMAGE.
35  */
36 
37 /*
38  * Copyright (c) 1985, 1989, 1993, 1994
39  *	The Regents of the University of California.  All rights reserved.
40  *
41  * Redistribution and use in source and binary forms, with or without
42  * modification, are permitted provided that the following conditions
43  * are met:
44  * 1. Redistributions of source code must retain the above copyright
45  *    notice, this list of conditions and the following disclaimer.
46  * 2. Redistributions in binary form must reproduce the above copyright
47  *    notice, this list of conditions and the following disclaimer in the
48  *    documentation and/or other materials provided with the distribution.
49  * 3. Neither the name of the University nor the names of its contributors
50  *    may be used to endorse or promote products derived from this software
51  *    without specific prior written permission.
52  *
53  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
54  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
55  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
56  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
57  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
58  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
59  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
60  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
61  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
62  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
63  * SUCH DAMAGE.
64  */
65 
66 #include "tnftp.h"
67 
68 #if 0	/* tnftp */
69 
70 #include <sys/cdefs.h>
71 #ifndef lint
72 __RCSID(" NetBSD: util.c,v 1.152 2009/07/13 19:05:41 roy Exp  ");
73 #endif /* not lint */
74 
75 /*
76  * FTP User Program -- Misc support routines
77  */
78 #include <sys/param.h>
79 #include <sys/socket.h>
80 #include <sys/ioctl.h>
81 #include <sys/time.h>
82 #include <netinet/in.h>
83 #include <arpa/ftp.h>
84 
85 #include <ctype.h>
86 #include <err.h>
87 #include <errno.h>
88 #include <fcntl.h>
89 #include <glob.h>
90 #include <signal.h>
91 #include <libgen.h>
92 #include <limits.h>
93 #include <netdb.h>
94 #include <stdio.h>
95 #include <stdlib.h>
96 #include <string.h>
97 #include <termios.h>
98 #include <time.h>
99 #include <tzfile.h>
100 #include <unistd.h>
101 
102 #endif	/* tnftp */
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 	const 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 		UPRINTF("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, "main: gateserver not defined");
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 *fline)
174 {
175 
176 			/*
177 			 * work-around broken ProFTPd servers that can't
178 			 * even obey RFC2389.
179 			 */
180 	while (*fline && isspace((int)*fline))
181 		fline++;
182 
183 	if (strcasecmp(fline, "MDTM") == 0)
184 		features[FEAT_MDTM] = 1;
185 	else if (strncasecmp(fline, "MLST", sizeof("MLST") - 1) == 0) {
186 		features[FEAT_MLST] = 1;
187 	} else if (strcasecmp(fline, "REST STREAM") == 0)
188 		features[FEAT_REST_STREAM] = 1;
189 	else if (strcasecmp(fline, "SIZE") == 0)
190 		features[FEAT_SIZE] = 1;
191 	else if (strcasecmp(fline, "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 (ftp_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 #ifndef NO_DEBUG
272 	if (ftp_debug) {
273 #define DEBUG_FEAT(x) fprintf(ttyout, "features[" #x "] = %d\n", features[(x)])
274 		DEBUG_FEAT(FEAT_FEAT);
275 		DEBUG_FEAT(FEAT_MDTM);
276 		DEBUG_FEAT(FEAT_MLST);
277 		DEBUG_FEAT(FEAT_REST_STREAM);
278 		DEBUG_FEAT(FEAT_SIZE);
279 		DEBUG_FEAT(FEAT_TVFS);
280 #undef DEBUG_FEAT
281 	}
282 #endif
283 	reply_callback = NULL;
284 
285 	verbose = overbose;
286 }
287 
288 /*
289  * Reset the various variables that indicate connection state back to
290  * disconnected settings.
291  * The caller is responsible for issuing any commands to the remote server
292  * to perform a clean shutdown before this is invoked.
293  */
294 void
295 cleanuppeer(void)
296 {
297 
298 	if (cout)
299 		(void)fclose(cout);
300 	cout = NULL;
301 	connected = 0;
302 	unix_server = 0;
303 	unix_proxy = 0;
304 			/*
305 			 * determine if anonftp was specifically set with -a
306 			 * (1), or implicitly set by auto_fetch() (2). in the
307 			 * latter case, disable after the current xfer
308 			 */
309 	if (anonftp == 2)
310 		anonftp = 0;
311 	data = -1;
312 	epsv4bad = 0;
313 	epsv6bad = 0;
314 	if (username)
315 		free(username);
316 	username = NULL;
317 	if (!proxy)
318 		macnum = 0;
319 }
320 
321 /*
322  * Top-level signal handler for interrupted commands.
323  */
324 void
325 intr(int signo)
326 {
327 
328 	sigint_raised = 1;
329 	alarmtimer(0);
330 	if (fromatty)
331 		write(fileno(ttyout), "\n", 1);
332 	siglongjmp(toplevel, 1);
333 }
334 
335 /*
336  * Signal handler for lost connections; cleanup various elements of
337  * the connection state, and call cleanuppeer() to finish it off.
338  */
339 void
340 lostpeer(int dummy)
341 {
342 	int oerrno = errno;
343 
344 	alarmtimer(0);
345 	if (connected) {
346 		if (cout != NULL) {
347 			(void)shutdown(fileno(cout), 1+1);
348 			(void)fclose(cout);
349 			cout = NULL;
350 		}
351 		if (data >= 0) {
352 			(void)shutdown(data, 1+1);
353 			(void)close(data);
354 			data = -1;
355 		}
356 		connected = 0;
357 	}
358 	pswitch(1);
359 	if (connected) {
360 		if (cout != NULL) {
361 			(void)shutdown(fileno(cout), 1+1);
362 			(void)fclose(cout);
363 			cout = NULL;
364 		}
365 		connected = 0;
366 	}
367 	proxflag = 0;
368 	pswitch(0);
369 	cleanuppeer();
370 	errno = oerrno;
371 }
372 
373 
374 /*
375  * Login to remote host, using given username & password if supplied.
376  * Return non-zero if successful.
377  */
378 int
379 ftp_login(const char *host, const char *luser, const char *lpass)
380 {
381 	char tmp[80];
382 	char *fuser, *pass, *facct, *p;
383 	char emptypass[] = "";
384 	const char *errormsg;
385 	int n, aflag, rval, nlen;
386 
387 	aflag = rval = 0;
388 	fuser = pass = facct = NULL;
389 	if (luser)
390 		fuser = ftp_strdup(luser);
391 	if (lpass)
392 		pass = ftp_strdup(lpass);
393 
394 	DPRINTF("ftp_login: user `%s' pass `%s' host `%s'\n",
395 	    STRorNULL(fuser), STRorNULL(pass), STRorNULL(host));
396 
397 	/*
398 	 * Set up arguments for an anonymous FTP session, if necessary.
399 	 */
400 	if (anonftp) {
401 		FREEPTR(fuser);
402 		fuser = ftp_strdup("anonymous");	/* as per RFC1635 */
403 		FREEPTR(pass);
404 		pass = ftp_strdup(getoptionvalue("anonpass"));
405 	}
406 
407 	if (ruserpass(host, &fuser, &pass, &facct) < 0) {
408 		code = -1;
409 		goto cleanup_ftp_login;
410 	}
411 
412 	while (fuser == NULL) {
413 		if (localname)
414 			fprintf(ttyout, "Name (%s:%s): ", host, localname);
415 		else
416 			fprintf(ttyout, "Name (%s): ", host);
417 		errormsg = NULL;
418 		nlen = get_line(stdin, tmp, sizeof(tmp), &errormsg);
419 		if (nlen < 0) {
420 			fprintf(ttyout, "%s; %s aborted.\n", errormsg, "login");
421 			code = -1;
422 			goto cleanup_ftp_login;
423 		} else if (nlen == 0) {
424 			fuser = ftp_strdup(localname);
425 		} else {
426 			fuser = ftp_strdup(tmp);
427 		}
428 	}
429 
430 	if (gatemode) {
431 		char *nuser;
432 		size_t len;
433 
434 		len = strlen(fuser) + 1 + strlen(host) + 1;
435 		nuser = ftp_malloc(len);
436 		(void)strlcpy(nuser, fuser, len);
437 		(void)strlcat(nuser, "@",  len);
438 		(void)strlcat(nuser, host, len);
439 		FREEPTR(fuser);
440 		fuser = nuser;
441 	}
442 
443 	n = command("USER %s", fuser);
444 	if (n == CONTINUE) {
445 		if (pass == NULL) {
446 			p = getpass("Password: ");
447 			if (p == NULL)
448 				p = emptypass;
449 			pass = ftp_strdup(p);
450 			memset(p, 0, strlen(p));
451 		}
452 		n = command("PASS %s", pass);
453 		memset(pass, 0, strlen(pass));
454 	}
455 	if (n == CONTINUE) {
456 		aflag++;
457 		if (facct == NULL) {
458 			p = getpass("Account: ");
459 			if (p == NULL)
460 				p = emptypass;
461 			facct = ftp_strdup(p);
462 			memset(p, 0, strlen(p));
463 		}
464 		if (facct[0] == '\0') {
465 			warnx("Login failed");
466 			goto cleanup_ftp_login;
467 		}
468 		n = command("ACCT %s", facct);
469 		memset(facct, 0, strlen(facct));
470 	}
471 	if ((n != COMPLETE) ||
472 	    (!aflag && facct != NULL && command("ACCT %s", facct) != COMPLETE)) {
473 		warnx("Login failed");
474 		goto cleanup_ftp_login;
475 	}
476 	rval = 1;
477 	username = ftp_strdup(fuser);
478 	if (proxy)
479 		goto cleanup_ftp_login;
480 
481 	connected = -1;
482 	getremoteinfo();
483 	for (n = 0; n < macnum; ++n) {
484 		if (!strcmp("init", macros[n].mac_name)) {
485 			(void)strlcpy(line, "$init", sizeof(line));
486 			makeargv();
487 			domacro(margc, margv);
488 			break;
489 		}
490 	}
491 	updatelocalcwd();
492 	updateremotecwd();
493 
494  cleanup_ftp_login:
495 	FREEPTR(fuser);
496 	if (pass != NULL)
497 		memset(pass, 0, strlen(pass));
498 	FREEPTR(pass);
499 	if (facct != NULL)
500 		memset(facct, 0, strlen(facct));
501 	FREEPTR(facct);
502 	return (rval);
503 }
504 
505 /*
506  * `another' gets another argument, and stores the new argc and argv.
507  * It reverts to the top level (via intr()) on EOF/error.
508  *
509  * Returns false if no new arguments have been added.
510  */
511 int
512 another(int *pargc, char ***pargv, const char *aprompt)
513 {
514 	const char	*errormsg;
515 	int		ret, nlen;
516 	size_t		len;
517 
518 	len = strlen(line);
519 	if (len >= sizeof(line) - 3) {
520 		fputs("Sorry, arguments too long.\n", ttyout);
521 		intr(0);
522 	}
523 	fprintf(ttyout, "(%s) ", aprompt);
524 	line[len++] = ' ';
525 	errormsg = NULL;
526 	nlen = get_line(stdin, line + len, sizeof(line)-len, &errormsg);
527 	if (nlen < 0) {
528 		fprintf(ttyout, "%s; %s aborted.\n", errormsg, "operation");
529 		intr(0);
530 	}
531 	len += nlen;
532 	makeargv();
533 	ret = margc > *pargc;
534 	*pargc = margc;
535 	*pargv = margv;
536 	return (ret);
537 }
538 
539 /*
540  * glob files given in argv[] from the remote server.
541  * if errbuf isn't NULL, store error messages there instead
542  * of writing to the screen.
543  */
544 char *
545 remglob(char *argv[], int doswitch, const char **errbuf)
546 {
547 	static char buf[MAXPATHLEN];
548 	static FILE *ftemp = NULL;
549 	static char **args;
550 	char temp[MAXPATHLEN];
551 	int oldverbose, oldhash, oldprogress, fd;
552 	char *cp;
553 	const char *rmode;
554 	size_t len;
555 
556 	if (!mflag || !connected) {
557 		if (!doglob)
558 			args = NULL;
559 		else {
560 			if (ftemp) {
561 				(void)fclose(ftemp);
562 				ftemp = NULL;
563 			}
564 		}
565 		return (NULL);
566 	}
567 	if (!doglob) {
568 		if (args == NULL)
569 			args = argv;
570 		if ((cp = *++args) == NULL)
571 			args = NULL;
572 		return (cp);
573 	}
574 	if (ftemp == NULL) {
575 		len = strlcpy(temp, tmpdir, sizeof(temp));
576 		if (temp[len - 1] != '/')
577 			(void)strlcat(temp, "/", sizeof(temp));
578 		(void)strlcat(temp, TMPFILE, sizeof(temp));
579 		if ((fd = mkstemp(temp)) < 0) {
580 			warn("Unable to create temporary file `%s'", temp);
581 			return (NULL);
582 		}
583 		close(fd);
584 		oldverbose = verbose;
585 		verbose = (errbuf != NULL) ? -1 : 0;
586 		oldhash = hash;
587 		oldprogress = progress;
588 		hash = 0;
589 		progress = 0;
590 		if (doswitch)
591 			pswitch(!proxy);
592 		for (rmode = "w"; *++argv != NULL; rmode = "a")
593 			recvrequest("NLST", temp, *argv, rmode, 0, 0);
594 		if ((code / 100) != COMPLETE) {
595 			if (errbuf != NULL)
596 				*errbuf = reply_string;
597 		}
598 		if (doswitch)
599 			pswitch(!proxy);
600 		verbose = oldverbose;
601 		hash = oldhash;
602 		progress = oldprogress;
603 		ftemp = fopen(temp, "r");
604 		(void)unlink(temp);
605 		if (ftemp == NULL) {
606 			if (errbuf == NULL)
607 				warnx("Can't find list of remote files");
608 			else
609 				*errbuf =
610 				    "Can't find list of remote files";
611 			return (NULL);
612 		}
613 	}
614 	if (fgets(buf, sizeof(buf), ftemp) == NULL) {
615 		(void)fclose(ftemp);
616 		ftemp = NULL;
617 		return (NULL);
618 	}
619 	if ((cp = strchr(buf, '\n')) != NULL)
620 		*cp = '\0';
621 	return (buf);
622 }
623 
624 /*
625  * Glob a local file name specification with the expectation of a single
626  * return value. Can't control multiple values being expanded from the
627  * expression, we return only the first.
628  * Returns NULL on error, or a pointer to a buffer containing the filename
629  * that's the caller's responsiblity to free(3) when finished with.
630  */
631 char *
632 globulize(const char *pattern)
633 {
634 	glob_t gl;
635 	int flags;
636 	char *p;
637 
638 	if (!doglob)
639 		return (ftp_strdup(pattern));
640 
641 	flags = GLOB_BRACE|GLOB_NOCHECK|GLOB_TILDE;
642 	memset(&gl, 0, sizeof(gl));
643 	if (glob(pattern, flags, NULL, &gl) || gl.gl_pathc == 0) {
644 		warnx("Glob pattern `%s' not found", pattern);
645 		globfree(&gl);
646 		return (NULL);
647 	}
648 	p = ftp_strdup(gl.gl_pathv[0]);
649 	globfree(&gl);
650 	return (p);
651 }
652 
653 /*
654  * determine size of remote file
655  */
656 off_t
657 remotesize(const char *file, int noisy)
658 {
659 	int overbose, r;
660 	off_t size;
661 
662 	overbose = verbose;
663 	size = -1;
664 	if (ftp_debug == 0)
665 		verbose = -1;
666 	if (! features[FEAT_SIZE]) {
667 		if (noisy)
668 			fprintf(ttyout,
669 			    "SIZE is not supported by remote server.\n");
670 		goto cleanup_remotesize;
671 	}
672 	r = command("SIZE %s", file);
673 	if (r == COMPLETE) {
674 		char *cp, *ep;
675 
676 		cp = strchr(reply_string, ' ');
677 		if (cp != NULL) {
678 			cp++;
679 			size = STRTOLL(cp, &ep, 10);
680 			if (*ep != '\0' && !isspace((unsigned char)*ep))
681 				size = -1;
682 		}
683 	} else {
684 		if (r == ERROR && code == 500 && features[FEAT_SIZE] == -1)
685 			features[FEAT_SIZE] = 0;
686 		if (noisy && ftp_debug == 0) {
687 			fputs(reply_string, ttyout);
688 			putc('\n', ttyout);
689 		}
690 	}
691  cleanup_remotesize:
692 	verbose = overbose;
693 	return (size);
694 }
695 
696 /*
697  * determine last modification time (in GMT) of remote file
698  */
699 time_t
700 remotemodtime(const char *file, int noisy)
701 {
702 	int	overbose, ocode, r;
703 	time_t	rtime;
704 
705 	overbose = verbose;
706 	ocode = code;
707 	rtime = -1;
708 	if (ftp_debug == 0)
709 		verbose = -1;
710 	if (! features[FEAT_MDTM]) {
711 		if (noisy)
712 			fprintf(ttyout,
713 			    "MDTM is not supported by remote server.\n");
714 		goto cleanup_parse_time;
715 	}
716 	r = command("MDTM %s", file);
717 	if (r == COMPLETE) {
718 		struct tm timebuf;
719 		char *timestr, *frac;
720 
721 		/*
722 		 * time-val = 14DIGIT [ "." 1*DIGIT ]
723 		 *		YYYYMMDDHHMMSS[.sss]
724 		 * mdtm-response = "213" SP time-val CRLF / error-response
725 		 */
726 		timestr = reply_string + 4;
727 
728 					/*
729 					 * parse fraction.
730 					 * XXX: ignored for now
731 					 */
732 		frac = strchr(timestr, '\r');
733 		if (frac != NULL)
734 			*frac = '\0';
735 		frac = strchr(timestr, '.');
736 		if (frac != NULL)
737 			*frac++ = '\0';
738 		if (strlen(timestr) == 15 && strncmp(timestr, "191", 3) == 0) {
739 			/*
740 			 * XXX:	Workaround for lame ftpd's that return
741 			 *	`19100' instead of `2000'
742 			 */
743 			fprintf(ttyout,
744 	    "Y2K warning! Incorrect time-val `%s' received from server.\n",
745 			    timestr);
746 			timestr++;
747 			timestr[0] = '2';
748 			timestr[1] = '0';
749 			fprintf(ttyout, "Converted to `%s'\n", timestr);
750 		}
751 		memset(&timebuf, 0, sizeof(timebuf));
752 		if (strlen(timestr) != 14 ||
753 		    (strptime(timestr, "%Y%m%d%H%M%S", &timebuf) == NULL)) {
754  bad_parse_time:
755 			fprintf(ttyout, "Can't parse time `%s'.\n", timestr);
756 			goto cleanup_parse_time;
757 		}
758 		timebuf.tm_isdst = -1;
759 		rtime = timegm(&timebuf);
760 		if (rtime == -1) {
761 			if (noisy || ftp_debug != 0)
762 				goto bad_parse_time;
763 			else
764 				goto cleanup_parse_time;
765 		} else {
766 			DPRINTF("remotemodtime: parsed date `%s' as " LLF
767 			    ", %s",
768 			    timestr, (LLT)rtime,
769 			    rfc2822time(localtime(&rtime)));
770 		}
771 	} else {
772 		if (r == ERROR && code == 500 && features[FEAT_MDTM] == -1)
773 			features[FEAT_MDTM] = 0;
774 		if (noisy && ftp_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  * Format tm in an RFC2822 compatible manner, with a trailing \n.
788  * Returns a pointer to a static string containing the result.
789  */
790 const char *
791 rfc2822time(const struct tm *tm)
792 {
793 	static char result[50];
794 
795 	if (strftime(result, sizeof(result),
796 	    "%a, %d %b %Y %H:%M:%S %z\n", tm) == 0)
797 		errx(1, "Can't convert RFC2822 time: buffer too small");
798 	return result;
799 }
800 
801 /*
802  * Update global `localcwd', which contains the state of the local cwd
803  */
804 void
805 updatelocalcwd(void)
806 {
807 
808 	if (getcwd(localcwd, sizeof(localcwd)) == NULL)
809 		localcwd[0] = '\0';
810 	DPRINTF("updatelocalcwd: got `%s'\n", localcwd);
811 }
812 
813 /*
814  * Update global `remotecwd', which contains the state of the remote cwd
815  */
816 void
817 updateremotecwd(void)
818 {
819 	int	 overbose, ocode;
820 	size_t	 i;
821 	char	*cp;
822 
823 	overbose = verbose;
824 	ocode = code;
825 	if (ftp_debug == 0)
826 		verbose = -1;
827 	if (command("PWD") != COMPLETE)
828 		goto badremotecwd;
829 	cp = strchr(reply_string, ' ');
830 	if (cp == NULL || cp[0] == '\0' || cp[1] != '"')
831 		goto badremotecwd;
832 	cp += 2;
833 	for (i = 0; *cp && i < sizeof(remotecwd) - 1; i++, cp++) {
834 		if (cp[0] == '"') {
835 			if (cp[1] == '"')
836 				cp++;
837 			else
838 				break;
839 		}
840 		remotecwd[i] = *cp;
841 	}
842 	remotecwd[i] = '\0';
843 	DPRINTF("updateremotecwd: got `%s'\n", remotecwd);
844 	goto cleanupremotecwd;
845  badremotecwd:
846 	remotecwd[0]='\0';
847  cleanupremotecwd:
848 	verbose = overbose;
849 	code = ocode;
850 }
851 
852 /*
853  * Ensure file is in or under dir.
854  * Returns 1 if so, 0 if not (or an error occurred).
855  */
856 int
857 fileindir(const char *file, const char *dir)
858 {
859 	char	parentdirbuf[PATH_MAX+1], *parentdir;
860 	char	realdir[PATH_MAX+1];
861 	size_t	dirlen;
862 
863 					/* determine parent directory of file */
864 	(void)strlcpy(parentdirbuf, file, sizeof(parentdirbuf));
865 	parentdir = dirname(parentdirbuf);
866 	if (strcmp(parentdir, ".") == 0)
867 		return 1;		/* current directory is ok */
868 
869 					/* find the directory */
870 	if (realpath(parentdir, realdir) == NULL) {
871 		warn("Unable to determine real path of `%s'", parentdir);
872 		return 0;
873 	}
874 	if (realdir[0] != '/')		/* relative result is ok */
875 		return 1;
876 	dirlen = strlen(dir);
877 	if (strncmp(realdir, dir, dirlen) == 0 &&
878 	    (realdir[dirlen] == '/' || realdir[dirlen] == '\0'))
879 		return 1;
880 	return 0;
881 }
882 
883 /*
884  * List words in stringlist, vertically arranged
885  */
886 void
887 list_vertical(StringList *sl)
888 {
889 	size_t i, j;
890 	size_t columns, lines;
891 	char *p;
892 	size_t w, width;
893 
894 	width = 0;
895 
896 	for (i = 0 ; i < sl->sl_cur ; i++) {
897 		w = strlen(sl->sl_str[i]);
898 		if (w > width)
899 			width = w;
900 	}
901 	width = (width + 8) &~ 7;
902 
903 	columns = ttywidth / width;
904 	if (columns == 0)
905 		columns = 1;
906 	lines = (sl->sl_cur + columns - 1) / columns;
907 	for (i = 0; i < lines; i++) {
908 		for (j = 0; j < columns; j++) {
909 			p = sl->sl_str[j * lines + i];
910 			if (p)
911 				fputs(p, ttyout);
912 			if (j * lines + i + lines >= sl->sl_cur) {
913 				putc('\n', ttyout);
914 				break;
915 			}
916 			if (p) {
917 				w = strlen(p);
918 				while (w < width) {
919 					w = (w + 8) &~ 7;
920 					(void)putc('\t', ttyout);
921 				}
922 			}
923 		}
924 	}
925 }
926 
927 /*
928  * Update the global ttywidth value, using TIOCGWINSZ.
929  */
930 void
931 setttywidth(int a)
932 {
933 	struct winsize winsize;
934 	int oerrno = errno;
935 
936 	if (ioctl(fileno(ttyout), TIOCGWINSZ, &winsize) != -1 &&
937 	    winsize.ws_col != 0)
938 		ttywidth = winsize.ws_col;
939 	else
940 		ttywidth = 80;
941 	errno = oerrno;
942 }
943 
944 /*
945  * Change the rate limit up (SIGUSR1) or down (SIGUSR2)
946  */
947 void
948 crankrate(int sig)
949 {
950 
951 	switch (sig) {
952 	case SIGUSR1:
953 		if (rate_get)
954 			rate_get += rate_get_incr;
955 		if (rate_put)
956 			rate_put += rate_put_incr;
957 		break;
958 	case SIGUSR2:
959 		if (rate_get && rate_get > rate_get_incr)
960 			rate_get -= rate_get_incr;
961 		if (rate_put && rate_put > rate_put_incr)
962 			rate_put -= rate_put_incr;
963 		break;
964 	default:
965 		err(1, "crankrate invoked with unknown signal: %d", sig);
966 	}
967 }
968 
969 
970 /*
971  * Setup or cleanup EditLine structures
972  */
973 #ifndef NO_EDITCOMPLETE
974 void
975 controlediting(void)
976 {
977 	if (editing && el == NULL && hist == NULL) {
978 		HistEvent ev;
979 		int editmode;
980 
981 		el = el_init(getprogname(), stdin, ttyout, stderr);
982 		/* init editline */
983 		hist = history_init();		/* init the builtin history */
984 		history(hist, &ev, H_SETSIZE, 100);/* remember 100 events */
985 		el_set(el, EL_HIST, history, hist);	/* use history */
986 
987 		el_set(el, EL_EDITOR, "emacs");	/* default editor is emacs */
988 		el_set(el, EL_PROMPT, prompt);	/* set the prompt functions */
989 		el_set(el, EL_RPROMPT, rprompt);
990 
991 		/* add local file completion, bind to TAB */
992 		el_set(el, EL_ADDFN, "ftp-complete",
993 		    "Context sensitive argument completion",
994 		    complete);
995 		el_set(el, EL_BIND, "^I", "ftp-complete", NULL);
996 		el_source(el, NULL);	/* read ~/.editrc */
997 		if ((el_get(el, EL_EDITMODE, &editmode) != -1) && editmode == 0)
998 			editing = 0;	/* the user doesn't want editing,
999 					 * so disable, and let statement
1000 					 * below cleanup */
1001 		else
1002 			el_set(el, EL_SIGNAL, 1);
1003 	}
1004 	if (!editing) {
1005 		if (hist) {
1006 			history_end(hist);
1007 			hist = NULL;
1008 		}
1009 		if (el) {
1010 			el_end(el);
1011 			el = NULL;
1012 		}
1013 	}
1014 }
1015 #endif /* !NO_EDITCOMPLETE */
1016 
1017 /*
1018  * Convert the string `arg' to an int, which may have an optional SI suffix
1019  * (`b', `k', `m', `g'). Returns the number for success, -1 otherwise.
1020  */
1021 int
1022 strsuftoi(const char *arg)
1023 {
1024 	char *cp;
1025 	long val;
1026 
1027 	if (!isdigit((unsigned char)arg[0]))
1028 		return (-1);
1029 
1030 	val = strtol(arg, &cp, 10);
1031 	if (cp != NULL) {
1032 		if (cp[0] != '\0' && cp[1] != '\0')
1033 			 return (-1);
1034 		switch (tolower((unsigned char)cp[0])) {
1035 		case '\0':
1036 		case 'b':
1037 			break;
1038 		case 'k':
1039 			val <<= 10;
1040 			break;
1041 		case 'm':
1042 			val <<= 20;
1043 			break;
1044 		case 'g':
1045 			val <<= 30;
1046 			break;
1047 		default:
1048 			return (-1);
1049 		}
1050 	}
1051 	if (val < 0 || val > INT_MAX)
1052 		return (-1);
1053 
1054 	return (val);
1055 }
1056 
1057 /*
1058  * Set up socket buffer sizes before a connection is made.
1059  */
1060 void
1061 setupsockbufsize(int sock)
1062 {
1063 	socklen_t slen;
1064 
1065 	if (0 == rcvbuf_size) {
1066 		slen = sizeof(rcvbuf_size);
1067 		if (getsockopt(sock, SOL_SOCKET, SO_RCVBUF,
1068 		    (void *)&rcvbuf_size, &slen) == -1)
1069 			err(1, "Unable to determine rcvbuf size");
1070 		if (rcvbuf_size <= 0)
1071 			rcvbuf_size = 8 * 1024;
1072 		if (rcvbuf_size > 8 * 1024 * 1024)
1073 			rcvbuf_size = 8 * 1024 * 1024;
1074 		DPRINTF("setupsockbufsize: rcvbuf_size determined as %d\n",
1075 		    rcvbuf_size);
1076 	}
1077 	if (0 == sndbuf_size) {
1078 		slen = sizeof(sndbuf_size);
1079 		if (getsockopt(sock, SOL_SOCKET, SO_SNDBUF,
1080 		    (void *)&sndbuf_size, &slen) == -1)
1081 			err(1, "Unable to determine sndbuf size");
1082 		if (sndbuf_size <= 0)
1083 			sndbuf_size = 8 * 1024;
1084 		if (sndbuf_size > 8 * 1024 * 1024)
1085 			sndbuf_size = 8 * 1024 * 1024;
1086 		DPRINTF("setupsockbufsize: sndbuf_size determined as %d\n",
1087 		    sndbuf_size);
1088 	}
1089 
1090 	if (setsockopt(sock, SOL_SOCKET, SO_SNDBUF,
1091 	    (void *)&sndbuf_size, sizeof(sndbuf_size)) == -1)
1092 		warn("Unable to set sndbuf size %d", sndbuf_size);
1093 
1094 	if (setsockopt(sock, SOL_SOCKET, SO_RCVBUF,
1095 	    (void *)&rcvbuf_size, sizeof(rcvbuf_size)) == -1)
1096 		warn("Unable to set rcvbuf size %d", rcvbuf_size);
1097 }
1098 
1099 /*
1100  * Copy characters from src into dst, \ quoting characters that require it
1101  */
1102 void
1103 ftpvis(char *dst, size_t dstlen, const char *src, size_t srclen)
1104 {
1105 	size_t	di, si;
1106 
1107 	for (di = si = 0;
1108 	    src[si] != '\0' && di < dstlen && si < srclen;
1109 	    di++, si++) {
1110 		switch (src[si]) {
1111 		case '\\':
1112 		case ' ':
1113 		case '\t':
1114 		case '\r':
1115 		case '\n':
1116 		case '"':
1117 			dst[di++] = '\\';
1118 			if (di >= dstlen)
1119 				break;
1120 			/* FALLTHROUGH */
1121 		default:
1122 			dst[di] = src[si];
1123 		}
1124 	}
1125 	dst[di] = '\0';
1126 }
1127 
1128 /*
1129  * Copy src into buf (which is len bytes long), expanding % sequences.
1130  */
1131 void
1132 formatbuf(char *buf, size_t len, const char *src)
1133 {
1134 	const char	*p, *p2, *q;
1135 	size_t		 i;
1136 	int		 op, updirs, pdirs;
1137 
1138 #define ADDBUF(x) do { \
1139 		if (i >= len - 1) \
1140 			goto endbuf; \
1141 		buf[i++] = (x); \
1142 	} while (0)
1143 
1144 	p = src;
1145 	for (i = 0; *p; p++) {
1146 		if (*p != '%') {
1147 			ADDBUF(*p);
1148 			continue;
1149 		}
1150 		p++;
1151 
1152 		switch (op = *p) {
1153 
1154 		case '/':
1155 		case '.':
1156 		case 'c':
1157 			p2 = connected ? remotecwd : "";
1158 			updirs = pdirs = 0;
1159 
1160 			/* option to determine fixed # of dirs from path */
1161 			if (op == '.' || op == 'c') {
1162 				int skip;
1163 
1164 				q = p2;
1165 				while (*p2)		/* calc # of /'s */
1166 					if (*p2++ == '/')
1167 						updirs++;
1168 				if (p[1] == '0') {	/* print <x> or ... */
1169 					pdirs = 1;
1170 					p++;
1171 				}
1172 				if (p[1] >= '1' && p[1] <= '9') {
1173 							/* calc # to skip  */
1174 					skip = p[1] - '0';
1175 					p++;
1176 				} else
1177 					skip = 1;
1178 
1179 				updirs -= skip;
1180 				while (skip-- > 0) {
1181 					while ((p2 > q) && (*p2 != '/'))
1182 						p2--;	/* back up */
1183 					if (skip && p2 > q)
1184 						p2--;
1185 				}
1186 				if (*p2 == '/' && p2 != q)
1187 					p2++;
1188 			}
1189 
1190 			if (updirs > 0 && pdirs) {
1191 				if (i >= len - 5)
1192 					break;
1193 				if (op == '.') {
1194 					ADDBUF('.');
1195 					ADDBUF('.');
1196 					ADDBUF('.');
1197 				} else {
1198 					ADDBUF('/');
1199 					ADDBUF('<');
1200 					if (updirs > 9) {
1201 						ADDBUF('9');
1202 						ADDBUF('+');
1203 					} else
1204 						ADDBUF('0' + updirs);
1205 					ADDBUF('>');
1206 				}
1207 			}
1208 			for (; *p2; p2++)
1209 				ADDBUF(*p2);
1210 			break;
1211 
1212 		case 'M':
1213 		case 'm':
1214 			for (p2 = connected && hostname ? hostname : "-";
1215 			    *p2 ; p2++) {
1216 				if (op == 'm' && *p2 == '.')
1217 					break;
1218 				ADDBUF(*p2);
1219 			}
1220 			break;
1221 
1222 		case 'n':
1223 			for (p2 = connected ? username : "-"; *p2 ; p2++)
1224 				ADDBUF(*p2);
1225 			break;
1226 
1227 		case '%':
1228 			ADDBUF('%');
1229 			break;
1230 
1231 		default:		/* display unknown codes literally */
1232 			ADDBUF('%');
1233 			ADDBUF(op);
1234 			break;
1235 
1236 		}
1237 	}
1238  endbuf:
1239 	buf[i] = '\0';
1240 }
1241 
1242 /*
1243  * Determine if given string is an IPv6 address or not.
1244  * Return 1 for yes, 0 for no
1245  */
1246 int
1247 isipv6addr(const char *addr)
1248 {
1249 	int rv = 0;
1250 #ifdef INET6
1251 	struct addrinfo hints, *res;
1252 
1253 	memset(&hints, 0, sizeof(hints));
1254 	hints.ai_family = AF_INET6;
1255 	hints.ai_socktype = SOCK_DGRAM;	/*dummy*/
1256 	hints.ai_flags = AI_NUMERICHOST;
1257 	if (getaddrinfo(addr, "0", &hints, &res) != 0)
1258 		rv = 0;
1259 	else {
1260 		rv = 1;
1261 		freeaddrinfo(res);
1262 	}
1263 	DPRINTF("isipv6addr: got %d for %s\n", rv, addr);
1264 #endif
1265 	return (rv == 1) ? 1 : 0;
1266 }
1267 
1268 /*
1269  * Read a line from the FILE stream into buf/buflen using fgets(), so up
1270  * to buflen-1 chars will be read and the result will be NUL terminated.
1271  * If the line has a trailing newline it will be removed.
1272  * If the line is too long, excess characters will be read until
1273  * newline/EOF/error.
1274  * If EOF/error occurs or a too-long line is encountered and errormsg
1275  * isn't NULL, it will be changed to a description of the problem.
1276  * (The EOF message has a leading \n for cosmetic purposes).
1277  * Returns:
1278  *	>=0	length of line (excluding trailing newline) if all ok
1279  *	-1	error occurred
1280  *	-2	EOF encountered
1281  *	-3	line was too long
1282  */
1283 int
1284 get_line(FILE *stream, char *buf, size_t buflen, const char **errormsg)
1285 {
1286 	int	rv, ch;
1287 	size_t	len;
1288 
1289 	if (fgets(buf, buflen, stream) == NULL) {
1290 		if (feof(stream)) {	/* EOF */
1291 			rv = -2;
1292 			if (errormsg)
1293 				*errormsg = "\nEOF received";
1294 		} else  {		/* error */
1295 			rv = -1;
1296 			if (errormsg)
1297 				*errormsg = "Error encountered";
1298 		}
1299 		clearerr(stream);
1300 		return rv;
1301 	}
1302 	len = strlen(buf);
1303 	if (buf[len-1] == '\n') {	/* clear any trailing newline */
1304 		buf[--len] = '\0';
1305 	} else if (len == buflen-1) {	/* line too long */
1306 		while ((ch = getchar()) != '\n' && ch != EOF)
1307 			continue;
1308 		if (errormsg)
1309 			*errormsg = "Input line is too long";
1310 		clearerr(stream);
1311 		return -3;
1312 	}
1313 	if (errormsg)
1314 		*errormsg = NULL;
1315 	return len;
1316 }
1317 
1318 /*
1319  * Internal version of connect(2); sets socket buffer sizes,
1320  * binds to a specific local address (if set), and
1321  * supports a connection timeout using a non-blocking connect(2) with
1322  * a poll(2).
1323  * Socket fcntl flags are temporarily updated to include O_NONBLOCK;
1324  * these will not be reverted on connection failure.
1325  * Returns 0 on success, or -1 upon failure (with an appropriate
1326  * error message displayed.)
1327  */
1328 int
1329 ftp_connect(int sock, const struct sockaddr *name, socklen_t namelen)
1330 {
1331 	int		flags, rv, timeout, error;
1332 	socklen_t	slen;
1333 	struct timeval	endtime, now, td;
1334 	struct pollfd	pfd[1];
1335 	char		hname[NI_MAXHOST];
1336 	char		sname[NI_MAXSERV];
1337 
1338 	setupsockbufsize(sock);
1339 	if (getnameinfo(name, namelen,
1340 	    hname, sizeof(hname), sname, sizeof(sname),
1341 	    NI_NUMERICHOST | NI_NUMERICSERV) != 0) {
1342 		strlcpy(hname, "?", sizeof(hname));
1343 		strlcpy(sname, "?", sizeof(sname));
1344 	}
1345 
1346 	if (bindai != NULL) {			/* bind to specific addr */
1347 		struct addrinfo *ai;
1348 
1349 		for (ai = bindai; ai != NULL; ai = ai->ai_next) {
1350 			if (ai->ai_family == name->sa_family)
1351 				break;
1352 		}
1353 		if (ai == NULL)
1354 			ai = bindai;
1355 		if (bind(sock, ai->ai_addr, ai->ai_addrlen) == -1) {
1356 			char	bname[NI_MAXHOST];
1357 			int	saveerr;
1358 
1359 			saveerr = errno;
1360 			if (getnameinfo(ai->ai_addr, ai->ai_addrlen,
1361 			    bname, sizeof(bname), NULL, 0, NI_NUMERICHOST) != 0)
1362 				strlcpy(bname, "?", sizeof(bname));
1363 			errno = saveerr;
1364 			warn("Can't bind to `%s'", bname);
1365 			return -1;
1366 		}
1367 	}
1368 
1369 						/* save current socket flags */
1370 	if ((flags = fcntl(sock, F_GETFL, 0)) == -1) {
1371 		warn("Can't %s socket flags for connect to `%s:%s'",
1372 		    "save", hname, sname);
1373 		return -1;
1374 	}
1375 						/* set non-blocking connect */
1376 	if (fcntl(sock, F_SETFL, flags | O_NONBLOCK) == -1) {
1377 		warn("Can't set socket non-blocking for connect to `%s:%s'",
1378 		    hname, sname);
1379 		return -1;
1380 	}
1381 
1382 	/* NOTE: we now must restore socket flags on successful exit */
1383 
1384 	pfd[0].fd = sock;
1385 	pfd[0].events = POLLIN|POLLOUT;
1386 
1387 	if (quit_time > 0) {			/* want a non default timeout */
1388 		(void)gettimeofday(&endtime, NULL);
1389 		endtime.tv_sec += quit_time;	/* determine end time */
1390 	}
1391 
1392 	rv = connect(sock, name, namelen);	/* inititate the connection */
1393 	if (rv == -1) {				/* connection error */
1394 		if (errno != EINPROGRESS) {	/* error isn't "please wait" */
1395  connecterror:
1396 			warn("Can't connect to `%s:%s'", hname, sname);
1397 			return -1;
1398 		}
1399 
1400 						/* connect EINPROGRESS; wait */
1401 		do {
1402 			if (quit_time > 0) {	/* determine timeout */
1403 				(void)gettimeofday(&now, NULL);
1404 				timersub(&endtime, &now, &td);
1405 				timeout = td.tv_sec * 1000 + td.tv_usec/1000;
1406 				if (timeout < 0)
1407 					timeout = 0;
1408 			} else {
1409 				timeout = INFTIM;
1410 			}
1411 			pfd[0].revents = 0;
1412 			rv = ftp_poll(pfd, 1, timeout);
1413 						/* loop until poll ! EINTR */
1414 		} while (rv == -1 && errno == EINTR);
1415 
1416 		if (rv == 0) {			/* poll (connect) timed out */
1417 			errno = ETIMEDOUT;
1418 			goto connecterror;
1419 		}
1420 
1421 		if (rv == -1) {			/* poll error */
1422 			goto connecterror;
1423 		} else if (pfd[0].revents & (POLLIN|POLLOUT)) {
1424 			slen = sizeof(error);	/* OK, or pending error */
1425 			if (getsockopt(sock, SOL_SOCKET, SO_ERROR,
1426 			    &error, &slen) == -1) {
1427 						/* Solaris pending error */
1428 				goto connecterror;
1429 			} else if (error != 0) {
1430 				errno = error;	/* BSD pending error */
1431 				goto connecterror;
1432 			}
1433 		} else {
1434 			errno = EBADF;		/* this shouldn't happen ... */
1435 			goto connecterror;
1436 		}
1437 	}
1438 
1439 	if (fcntl(sock, F_SETFL, flags) == -1) {
1440 						/* restore socket flags */
1441 		warn("Can't %s socket flags for connect to `%s:%s'",
1442 		    "restore", hname, sname);
1443 		return -1;
1444 	}
1445 	return 0;
1446 }
1447 
1448 /*
1449  * Internal version of listen(2); sets socket buffer sizes first.
1450  */
1451 int
1452 ftp_listen(int sock, int backlog)
1453 {
1454 
1455 	setupsockbufsize(sock);
1456 	return (listen(sock, backlog));
1457 }
1458 
1459 /*
1460  * Internal version of poll(2), to allow reimplementation by select(2)
1461  * on platforms without the former.
1462  */
1463 int
1464 ftp_poll(struct pollfd *fds, int nfds, int timeout)
1465 {
1466 #if defined(HAVE_POLL)
1467 	return poll(fds, nfds, timeout);
1468 
1469 #elif defined(HAVE_SELECT)
1470 		/* implement poll(2) using select(2) */
1471 	fd_set		rset, wset, xset;
1472 	const int	rsetflags = POLLIN | POLLRDNORM;
1473 	const int	wsetflags = POLLOUT | POLLWRNORM;
1474 	const int	xsetflags = POLLRDBAND;
1475 	struct timeval	tv, *ptv;
1476 	int		i, max, rv;
1477 
1478 	FD_ZERO(&rset);			/* build list of read & write events */
1479 	FD_ZERO(&wset);
1480 	FD_ZERO(&xset);
1481 	max = 0;
1482 	for (i = 0; i < nfds; i++) {
1483 		if (fds[i].fd > FD_SETSIZE) {
1484 			warnx("can't select fd %d", fds[i].fd);
1485 			errno = EINVAL;
1486 			return -1;
1487 		} else if (fds[i].fd > max)
1488 			max = fds[i].fd;
1489 		if (fds[i].events & rsetflags)
1490 			FD_SET(fds[i].fd, &rset);
1491 		if (fds[i].events & wsetflags)
1492 			FD_SET(fds[i].fd, &wset);
1493 		if (fds[i].events & xsetflags)
1494 			FD_SET(fds[i].fd, &xset);
1495 	}
1496 
1497 	ptv = &tv;			/* determine timeout */
1498 	if (timeout == -1) {		/* wait forever */
1499 		ptv = NULL;
1500 	} else if (timeout == 0) {	/* poll once */
1501 		ptv->tv_sec = 0;
1502 		ptv->tv_usec = 0;
1503 	}
1504 	else if (timeout != 0) {	/* wait timeout milliseconds */
1505 		ptv->tv_sec = timeout / 1000;
1506 		ptv->tv_usec = (timeout % 1000) * 1000;
1507 	}
1508 	rv = select(max + 1, &rset, &wset, &xset, ptv);
1509 	if (rv <= 0)			/* -1 == error, 0 == timeout */
1510 		return rv;
1511 
1512 	for (i = 0; i < nfds; i++) {	/* determine results */
1513 		if (FD_ISSET(fds[i].fd, &rset))
1514 			fds[i].revents |= (fds[i].events & rsetflags);
1515 		if (FD_ISSET(fds[i].fd, &wset))
1516 			fds[i].revents |= (fds[i].events & wsetflags);
1517 		if (FD_ISSET(fds[i].fd, &xset))
1518 			fds[i].revents |= (fds[i].events & xsetflags);
1519 	}
1520 	return rv;
1521 
1522 #else
1523 # error no way to implement xpoll
1524 #endif
1525 }
1526 
1527 /*
1528  * malloc() with inbuilt error checking
1529  */
1530 void *
1531 ftp_malloc(size_t size)
1532 {
1533 	void *p;
1534 
1535 	p = malloc(size);
1536 	if (p == NULL)
1537 		err(1, "Unable to allocate %ld bytes of memory", (long)size);
1538 	return (p);
1539 }
1540 
1541 /*
1542  * sl_init() with inbuilt error checking
1543  */
1544 StringList *
1545 ftp_sl_init(void)
1546 {
1547 	StringList *p;
1548 
1549 	p = sl_init();
1550 	if (p == NULL)
1551 		err(1, "Unable to allocate memory for stringlist");
1552 	return (p);
1553 }
1554 
1555 /*
1556  * sl_add() with inbuilt error checking
1557  */
1558 void
1559 ftp_sl_add(StringList *sl, char *i)
1560 {
1561 
1562 	if (sl_add(sl, i) == -1)
1563 		err(1, "Unable to add `%s' to stringlist", i);
1564 }
1565 
1566 /*
1567  * strdup() with inbuilt error checking
1568  */
1569 char *
1570 ftp_strdup(const char *str)
1571 {
1572 	char *s;
1573 
1574 	if (str == NULL)
1575 		errx(1, "ftp_strdup: called with NULL argument");
1576 	s = strdup(str);
1577 	if (s == NULL)
1578 		err(1, "Unable to allocate memory for string copy");
1579 	return (s);
1580 }
1581