Home | History | Annotate | Line # | Download | only in tftpd
tftpd.c revision 1.41
      1 /*	$NetBSD: tftpd.c,v 1.41 2013/07/03 21:20:45 christos Exp $	*/
      2 
      3 /*
      4  * Copyright (c) 1983, 1993
      5  *	The Regents of the University of California.  All rights reserved.
      6  *
      7  * Redistribution and use in source and binary forms, with or without
      8  * modification, are permitted provided that the following conditions
      9  * are met:
     10  * 1. Redistributions of source code must retain the above copyright
     11  *    notice, this list of conditions and the following disclaimer.
     12  * 2. Redistributions in binary form must reproduce the above copyright
     13  *    notice, this list of conditions and the following disclaimer in the
     14  *    documentation and/or other materials provided with the distribution.
     15  * 3. Neither the name of the University nor the names of its contributors
     16  *    may be used to endorse or promote products derived from this software
     17  *    without specific prior written permission.
     18  *
     19  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     29  * SUCH DAMAGE.
     30  */
     31 
     32 #include <sys/cdefs.h>
     33 #ifndef lint
     34 __COPYRIGHT("@(#) Copyright (c) 1983, 1993\
     35  The Regents of the University of California.  All rights reserved.");
     36 #if 0
     37 static char sccsid[] = "@(#)tftpd.c	8.1 (Berkeley) 6/4/93";
     38 #else
     39 __RCSID("$NetBSD: tftpd.c,v 1.41 2013/07/03 21:20:45 christos Exp $");
     40 #endif
     41 #endif /* not lint */
     42 
     43 /*
     44  * Trivial file transfer protocol server.
     45  *
     46  * This version includes many modifications by Jim Guyton
     47  * <guyton@rand-unix>.
     48  */
     49 
     50 #include <sys/param.h>
     51 #include <sys/ioctl.h>
     52 #include <sys/stat.h>
     53 #include <sys/socket.h>
     54 
     55 #include <netinet/in.h>
     56 #include <arpa/tftp.h>
     57 #include <arpa/inet.h>
     58 
     59 #include <ctype.h>
     60 #include <errno.h>
     61 #include <fcntl.h>
     62 #include <grp.h>
     63 #include <netdb.h>
     64 #include <pwd.h>
     65 #include <setjmp.h>
     66 #include <signal.h>
     67 #include <stdio.h>
     68 #include <stdlib.h>
     69 #include <string.h>
     70 #include <syslog.h>
     71 #include <time.h>
     72 #include <unistd.h>
     73 
     74 #include "tftpsubs.h"
     75 
     76 #define	DEFAULTUSER	"nobody"
     77 
     78 #define	TIMEOUT		5
     79 
     80 static int	peer;
     81 static int	rexmtval = TIMEOUT;
     82 static int	maxtimeout = 5*TIMEOUT;
     83 
     84 static char	buf[MAXPKTSIZE];
     85 static char	ackbuf[PKTSIZE];
     86 static char	oackbuf[PKTSIZE];
     87 static struct	sockaddr_storage from;
     88 static socklen_t	fromlen;
     89 static int	debug;
     90 
     91 static int	tftp_opt_tsize = 0;
     92 static int	tftp_blksize = SEGSIZE;
     93 static int	tftp_tsize = 0;
     94 
     95 /*
     96  * Null-terminated directory prefix list for absolute pathname requests and
     97  * search list for relative pathname requests.
     98  *
     99  * MAXDIRS should be at least as large as the number of arguments that
    100  * inetd allows (currently 20).
    101  */
    102 #define MAXDIRS	20
    103 static struct dirlist {
    104 	char	*name;
    105 	int	len;
    106 } dirs[MAXDIRS+1];
    107 static int	suppress_naks;
    108 static int	logging;
    109 static int	secure;
    110 static char	pathsep = '\0';
    111 static char	*securedir;
    112 static int	unrestricted_writes;    /* uploaded files don't have to exist */
    113 
    114 struct formats;
    115 
    116 static const char *errtomsg(int);
    117 static void	nak(int);
    118 __dead static void	tftp(struct tftphdr *, int);
    119 __dead static void	usage(void);
    120 static char	*verifyhost(struct sockaddr *);
    121 __dead static void	justquit(int);
    122 static void	recvfile(struct formats *, int, int);
    123 static void	sendfile(struct formats *, int, int);
    124 __dead static void	timer(int);
    125 static const char *opcode(int);
    126 static int	validate_access(char **, int);
    127 
    128 static struct formats {
    129 	const char	*f_mode;
    130 	int		(*f_validate)(char **, int);
    131 	void		(*f_send)(struct formats *, int, int);
    132 	void		(*f_recv)(struct formats *, int, int);
    133 	int		f_convert;
    134 } formats[] = {
    135 	{ "netascii",	validate_access,	sendfile,	recvfile, 1 },
    136 	{ "octet",	validate_access,	sendfile,	recvfile, 0 },
    137 	{ .f_mode = NULL }
    138 };
    139 
    140 static void
    141 usage(void)
    142 {
    143 
    144 	syslog(LOG_ERR,
    145     "Usage: %s [-dln] [-g group] [-p pathsep] [-s directory] [-u user] [directory ...]",
    146 		    getprogname());
    147 	exit(1);
    148 }
    149 
    150 int
    151 main(int argc, char *argv[])
    152 {
    153 	struct sockaddr_storage me;
    154 	struct passwd	*pwent;
    155 	struct group	*grent;
    156 	struct tftphdr	*tp;
    157 	const char	*tgtuser, *tgtgroup;
    158 	char *ep;
    159 	int	n, ch, on, fd;
    160 	int	soopt;
    161 	socklen_t len;
    162 	uid_t	curuid, tgtuid;
    163 	gid_t	curgid, tgtgid;
    164 	long	nid;
    165 
    166 	n = 0;
    167 	fd = 0;
    168 	tzset();
    169 	openlog("tftpd", LOG_PID | LOG_NDELAY, LOG_DAEMON);
    170 	tgtuser = DEFAULTUSER;
    171 	tgtgroup = NULL;
    172 	curuid = getuid();
    173 	curgid = getgid();
    174 
    175 	while ((ch = getopt(argc, argv, "cdg:lnp:s:u:")) != -1)
    176 		switch (ch) {
    177 		case 'w':
    178 			unrestricted_writes = 1;
    179 			break;
    180 
    181 		case 'd':
    182 			debug++;
    183 			break;
    184 
    185 		case 'g':
    186 			tgtgroup = optarg;
    187 			break;
    188 
    189 		case 'l':
    190 			logging = 1;
    191 			break;
    192 
    193 		case 'n':
    194 			suppress_naks = 1;
    195 			break;
    196 
    197 		case 'p':
    198 			if (optarg[0] == '\0' || optarg[1] != '\0')
    199 				usage();
    200 			pathsep = optarg[0];
    201 			break;
    202 
    203 		case 's':
    204 			secure = 1;
    205 			securedir = optarg;
    206 			break;
    207 
    208 		case 'u':
    209 			tgtuser = optarg;
    210 			break;
    211 
    212 		default:
    213 			usage();
    214 			break;
    215 		}
    216 
    217 	if (optind < argc) {
    218 		struct dirlist *dirp;
    219 
    220 		/* Get list of directory prefixes. Skip relative pathnames. */
    221 		for (dirp = dirs; optind < argc && dirp < &dirs[MAXDIRS];
    222 		     optind++) {
    223 			if (argv[optind][0] == '/') {
    224 				dirp->name = argv[optind];
    225 				dirp->len  = strlen(dirp->name);
    226 				dirp++;
    227 			}
    228 		}
    229 	}
    230 
    231 	if (*tgtuser == '\0' || (tgtgroup != NULL && *tgtgroup == '\0'))
    232 		usage();
    233 
    234 	nid = (strtol(tgtuser, &ep, 10));
    235 	if (*ep == '\0') {
    236 		if ((uid_t)nid > UID_MAX) {
    237 			syslog(LOG_ERR, "uid %ld is too large", nid);
    238 			exit(1);
    239 		}
    240 		pwent = getpwuid((uid_t)nid);
    241 	} else
    242 		pwent = getpwnam(tgtuser);
    243 	if (pwent == NULL) {
    244 		syslog(LOG_ERR, "unknown user `%s'", tgtuser);
    245 		exit(1);
    246 	}
    247 	tgtuid = pwent->pw_uid;
    248 	tgtgid = pwent->pw_gid;
    249 
    250 	if (tgtgroup != NULL) {
    251 		nid = (strtol(tgtgroup, &ep, 10));
    252 		if (*ep == '\0') {
    253 			if ((uid_t)nid > GID_MAX) {
    254 				syslog(LOG_ERR, "gid %ld is too large", nid);
    255 				exit(1);
    256 			}
    257 			grent = getgrgid((gid_t)nid);
    258 		} else
    259 			grent = getgrnam(tgtgroup);
    260 		if (grent != NULL)
    261 			tgtgid = grent->gr_gid;
    262 		else {
    263 			syslog(LOG_ERR, "unknown group `%s'", tgtgroup);
    264 			exit(1);
    265 		}
    266 	}
    267 
    268 	if (secure) {
    269 		if (chdir(securedir) < 0) {
    270 			syslog(LOG_ERR, "chdir %s: %m", securedir);
    271 			exit(1);
    272 		}
    273 		if (chroot(".")) {
    274 			syslog(LOG_ERR, "chroot: %m");
    275 			exit(1);
    276 		}
    277 	}
    278 
    279 	if (logging)
    280 		syslog(LOG_DEBUG, "running as user `%s' (%d), group `%s' (%d)",
    281 		    tgtuser, tgtuid, tgtgroup ? tgtgroup : "(unspecified)",
    282 		    tgtgid);
    283 	if (curgid != tgtgid) {
    284 		if (setgid(tgtgid)) {
    285 			syslog(LOG_ERR, "setgid to %d: %m", (int)tgtgid);
    286 			exit(1);
    287 		}
    288 		if (setgroups(0, NULL)) {
    289 			syslog(LOG_ERR, "setgroups: %m");
    290 			exit(1);
    291 		}
    292 	}
    293 
    294 	if (curuid != tgtuid) {
    295 		if (setuid(tgtuid)) {
    296 			syslog(LOG_ERR, "setuid to %d: %m", (int)tgtuid);
    297 			exit(1);
    298 		}
    299 	}
    300 
    301 	on = 1;
    302 	if (ioctl(fd, FIONBIO, &on) < 0) {
    303 		syslog(LOG_ERR, "ioctl(FIONBIO): %m");
    304 		exit(1);
    305 	}
    306 	fromlen = sizeof (from);
    307 	n = recvfrom(fd, buf, sizeof (buf), 0,
    308 	    (struct sockaddr *)&from, &fromlen);
    309 	if (n < 0) {
    310 		syslog(LOG_ERR, "recvfrom: %m");
    311 		exit(1);
    312 	}
    313 	/*
    314 	 * Now that we have read the message out of the UDP
    315 	 * socket, we fork and exit.  Thus, inetd will go back
    316 	 * to listening to the tftp port, and the next request
    317 	 * to come in will start up a new instance of tftpd.
    318 	 *
    319 	 * We do this so that inetd can run tftpd in "wait" mode.
    320 	 * The problem with tftpd running in "nowait" mode is that
    321 	 * inetd may get one or more successful "selects" on the
    322 	 * tftp port before we do our receive, so more than one
    323 	 * instance of tftpd may be started up.  Worse, if tftpd
    324 	 * break before doing the above "recvfrom", inetd would
    325 	 * spawn endless instances, clogging the system.
    326 	 */
    327 	{
    328 		int pid;
    329 		int i;
    330 		socklen_t j;
    331 
    332 		for (i = 1; i < 20; i++) {
    333 		    pid = fork();
    334 		    if (pid < 0) {
    335 				sleep(i);
    336 				/*
    337 				 * flush out to most recently sent request.
    338 				 *
    339 				 * This may drop some request, but those
    340 				 * will be resent by the clients when
    341 				 * they timeout.  The positive effect of
    342 				 * this flush is to (try to) prevent more
    343 				 * than one tftpd being started up to service
    344 				 * a single request from a single client.
    345 				 */
    346 				j = sizeof from;
    347 				i = recvfrom(fd, buf, sizeof (buf), 0,
    348 				    (struct sockaddr *)&from, &j);
    349 				if (i > 0) {
    350 					n = i;
    351 					fromlen = j;
    352 				}
    353 		    } else {
    354 				break;
    355 		    }
    356 		}
    357 		if (pid < 0) {
    358 			syslog(LOG_ERR, "fork: %m");
    359 			exit(1);
    360 		} else if (pid != 0) {
    361 			exit(0);
    362 		}
    363 	}
    364 
    365 	/*
    366 	 * remember what address this was sent to, so we can respond on the
    367 	 * same interface
    368 	 */
    369 	len = sizeof(me);
    370 	if (getsockname(fd, (struct sockaddr *)&me, &len) == 0) {
    371 		switch (me.ss_family) {
    372 		case AF_INET:
    373 			((struct sockaddr_in *)&me)->sin_port = 0;
    374 			break;
    375 		case AF_INET6:
    376 			((struct sockaddr_in6 *)&me)->sin6_port = 0;
    377 			break;
    378 		default:
    379 			/* unsupported */
    380 			break;
    381 		}
    382 	} else {
    383 		memset(&me, 0, sizeof(me));
    384 		me.ss_family = from.ss_family;
    385 		me.ss_len = from.ss_len;
    386 	}
    387 
    388 	alarm(0);
    389 	close(fd);
    390 	close(1);
    391 	peer = socket(from.ss_family, SOCK_DGRAM, 0);
    392 	if (peer < 0) {
    393 		syslog(LOG_ERR, "socket: %m");
    394 		exit(1);
    395 	}
    396 	if (bind(peer, (struct sockaddr *)&me, me.ss_len) < 0) {
    397 		syslog(LOG_ERR, "bind: %m");
    398 		exit(1);
    399 	}
    400 	if (connect(peer, (struct sockaddr *)&from, from.ss_len) < 0) {
    401 		syslog(LOG_ERR, "connect: %m");
    402 		exit(1);
    403 	}
    404 	soopt = 65536;	/* larger than we'll ever need */
    405 	if (setsockopt(peer, SOL_SOCKET, SO_SNDBUF, (void *) &soopt, sizeof(soopt)) < 0) {
    406 		syslog(LOG_ERR, "set SNDBUF: %m");
    407 		exit(1);
    408 	}
    409 	if (setsockopt(peer, SOL_SOCKET, SO_RCVBUF, (void *) &soopt, sizeof(soopt)) < 0) {
    410 		syslog(LOG_ERR, "set RCVBUF: %m");
    411 		exit(1);
    412 	}
    413 
    414 	tp = (struct tftphdr *)buf;
    415 	tp->th_opcode = ntohs(tp->th_opcode);
    416 	if (tp->th_opcode == RRQ || tp->th_opcode == WRQ)
    417 		tftp(tp, n);
    418 	exit(1);
    419 }
    420 
    421 static int
    422 blk_handler(struct tftphdr *tp, const char *val, char *ack, size_t asize,
    423     size_t *ackl, int *ec)
    424 {
    425 	unsigned long bsize;
    426 	char *endp;
    427 	int l;
    428 
    429 	/*
    430 	 * On these failures, we could just ignore the blocksize option.
    431 	 * Perhaps that should be a command-line option.
    432 	 */
    433 	errno = 0;
    434 	bsize = strtoul(val, &endp, 10);
    435 	if ((bsize == ULONG_MAX && errno == ERANGE) || *endp) {
    436 		syslog(LOG_NOTICE, "%s: %s request for %s: "
    437 			"illegal value %s for blksize option",
    438 			verifyhost((struct sockaddr *)&from),
    439 			tp->th_opcode == WRQ ? "write" : "read",
    440 			tp->th_stuff, val);
    441 		return 0;
    442 	}
    443 	if (bsize < 8 || bsize > 65464) {
    444 		syslog(LOG_NOTICE, "%s: %s request for %s: "
    445 			"out of range value %s for blksize option",
    446 			verifyhost((struct sockaddr *)&from),
    447 			tp->th_opcode == WRQ ? "write" : "read",
    448 			tp->th_stuff, val);
    449 		return 0;
    450 	}
    451 
    452 	tftp_blksize = bsize;
    453 	if (asize > *ackl && (l = snprintf(ack + *ackl, asize - *ackl,
    454 	    "blksize%c%lu%c", 0, bsize, 0)) > 0)
    455 		*ackl += l;
    456 	else
    457 		return -1;
    458 
    459 	return 0;
    460 }
    461 
    462 static int
    463 timeout_handler(struct tftphdr *tp, const char *val, char *ack, size_t asize,
    464 		size_t *ackl, int *ec)
    465 {
    466 	unsigned long tout;
    467 	char *endp;
    468 	int l;
    469 
    470 	errno = 0;
    471 	tout = strtoul(val, &endp, 10);
    472 	if ((tout == ULONG_MAX && errno == ERANGE) || *endp) {
    473 		syslog(LOG_NOTICE, "%s: %s request for %s: "
    474 			"illegal value %s for timeout option",
    475 			verifyhost((struct sockaddr *)&from),
    476 			tp->th_opcode == WRQ ? "write" : "read",
    477 			tp->th_stuff, val);
    478 		return 0;
    479 	}
    480 	if (tout < 1 || tout > 255) {
    481 		syslog(LOG_NOTICE, "%s: %s request for %s: "
    482 			"out of range value %s for timeout option",
    483 			verifyhost((struct sockaddr *)&from),
    484 			tp->th_opcode == WRQ ? "write" : "read",
    485 			tp->th_stuff, val);
    486 		return 0;
    487 	}
    488 
    489 	rexmtval = tout;
    490 	if (asize > *ackl && (l = snprintf(ack + *ackl, asize - *ackl,
    491 	    "timeout%c%lu%c", 0, tout, 0)) > 0)
    492 		*ackl += l;
    493 	else
    494 		return -1;
    495 	/*
    496 	 * Arbitrarily pick a maximum timeout on a request to 3
    497 	 * retransmissions if the interval timeout is more than
    498 	 * one minute.  Longest possible timeout is therefore
    499 	 * 3 * 255 - 1, or 764 seconds.
    500 	 */
    501 	if (rexmtval > 60) {
    502 		maxtimeout = rexmtval * 3;
    503 	} else {
    504 		maxtimeout = rexmtval * 5;
    505 	}
    506 
    507 	return 0;
    508 }
    509 
    510 static int
    511 tsize_handler(struct tftphdr *tp, const char *val, char *ack, size_t asize,
    512     size_t *ackl, int *ec)
    513 {
    514 	unsigned long fsize;
    515 	char *endp;
    516 
    517 	/*
    518 	 * Maximum file even with extended tftp is 65535 blocks of
    519 	 * length 65464, or 4290183240 octets (4784056 less than 2^32).
    520 	 * unsigned long is at least 32 bits on all NetBSD archs.
    521 	 */
    522 
    523 	errno = 0;
    524 	fsize = strtoul(val, &endp, 10);
    525 	if ((fsize == ULONG_MAX && errno == ERANGE) || *endp) {
    526 		syslog(LOG_NOTICE, "%s: %s request for %s: "
    527 			"illegal value %s for tsize option",
    528 			verifyhost((struct sockaddr *)&from),
    529 			tp->th_opcode == WRQ ? "write" : "read",
    530 			tp->th_stuff, val);
    531 		return 0;
    532 	}
    533 	if (fsize > (unsigned long) 65535 * 65464) {
    534 		syslog(LOG_NOTICE, "%s: %s request for %s: "
    535 			"out of range value %s for tsize option",
    536 			verifyhost((struct sockaddr *)&from),
    537 			tp->th_opcode == WRQ ? "write" : "read",
    538 			tp->th_stuff, val);
    539 		return 0;
    540 	}
    541 
    542 	tftp_opt_tsize = 1;
    543 	tftp_tsize = fsize;
    544 	/*
    545 	 * We will report this later -- either replying with the fsize (WRQ)
    546 	 * or replying with the actual filesize (RRQ).
    547 	 */
    548 
    549 	return 0;
    550 }
    551 
    552 static const struct tftp_options {
    553 	const char *o_name;
    554 	int (*o_handler)(struct tftphdr *, const char *, char *, size_t,
    555 			 size_t *, int *);
    556 } options[] = {
    557 	{ "blksize", blk_handler },
    558 	{ "timeout", timeout_handler },
    559 	{ "tsize", tsize_handler },
    560 	{ .o_name = NULL }
    561 };
    562 
    563 /*
    564  * Get options for an extended tftp session.  Stuff the ones we
    565  * recognize in oackbuf.
    566  */
    567 static int
    568 get_options(struct tftphdr *tp, char *cp, int size, char *ackb, size_t asize,
    569     size_t *alen, int *err)
    570 {
    571 	const struct tftp_options *op;
    572 	char *option, *value, *endp;
    573 	int r, rv=0, ec=0;
    574 
    575 	endp = cp + size;
    576 	while (cp < endp) {
    577 		option = cp;
    578 		while (*cp && cp < endp) {
    579 			*cp = tolower((unsigned char)*cp);
    580 			cp++;
    581 		}
    582 		if (*cp) {
    583 			/* if we have garbage at the end, just ignore it */
    584 			break;
    585 		}
    586 		cp++;	/* skip over NUL */
    587 		value = cp;
    588 		while (*cp && cp < endp) {
    589 			cp++;
    590 		}
    591 		if (*cp) {
    592 			/* if we have garbage at the end, just ignore it */
    593 			break;
    594 		}
    595 		cp++;
    596 		for (op = options; op->o_name; op++) {
    597 			if (strcmp(op->o_name, option) == 0)
    598 				break;
    599 		}
    600 		if (op->o_name) {
    601 			r = op->o_handler(tp, value, ackb, asize, alen, &ec);
    602 			if (r < 0) {
    603 				rv = -1;
    604 				break;
    605 			}
    606 			rv++;
    607 		} /* else ignore unknown options */
    608 	}
    609 
    610 	if (rv < 0)
    611 		*err = ec;
    612 
    613 	return rv;
    614 }
    615 
    616 /*
    617  * Handle initial connection protocol.
    618  */
    619 static void
    620 tftp(struct tftphdr *tp, int size)
    621 {
    622 	struct formats *pf;
    623 	char	*cp;
    624 	char	*filename, *mode;
    625 	int	 first, ecode, etftp = 0, r;
    626 	size_t alen;
    627 
    628 	ecode = 0;	/* XXX gcc */
    629 	first = 1;
    630 	mode = NULL;
    631 
    632 	filename = cp = tp->th_stuff;
    633 again:
    634 	while (cp < buf + size) {
    635 		if (*cp == '\0')
    636 			break;
    637 		cp++;
    638 	}
    639 	if (*cp != '\0') {
    640 		nak(EBADOP);
    641 		exit(1);
    642 	}
    643 	if (first) {
    644 		mode = ++cp;
    645 		first = 0;
    646 		goto again;
    647 	}
    648 	for (cp = mode; *cp; cp++)
    649 		*cp = tolower((unsigned char)*cp);
    650 	for (pf = formats; pf->f_mode; pf++)
    651 		if (strcmp(pf->f_mode, mode) == 0)
    652 			break;
    653 	if (pf->f_mode == 0) {
    654 		nak(EBADOP);
    655 		exit(1);
    656 	}
    657 	/*
    658 	 * cp currently points to the NUL byte following the mode.
    659 	 *
    660 	 * If we have some valid options, then let's assume that we're
    661 	 * now dealing with an extended tftp session.  Note that if we
    662 	 * don't get any options, then we *must* assume that we do not
    663 	 * have an extended tftp session.  If we get options, we fill
    664 	 * in the ack buf to acknowledge them.  If we skip that, then
    665 	 * the client *must* assume that we are not using an extended
    666 	 * session.
    667 	 */
    668 	size -= (++cp - (char *) tp);
    669 	if (size > 0 && *cp) {
    670 		alen = 2; /* Skip over opcode */
    671 		r = get_options(tp, cp, size, oackbuf, sizeof(oackbuf),
    672 		    &alen, &ecode);
    673 		if (r > 0) {
    674 			etftp = 1;
    675 		} else if (r < 0) {
    676 			nak(ecode);
    677 			exit(1);
    678 		}
    679 	}
    680 	/*
    681 	 * Globally replace the path separator given in the -p option
    682 	 * with / to cope with clients expecting a non-unix path separator.
    683 	 */
    684 	if (pathsep != '\0') {
    685 		for (cp = filename; *cp != '\0'; ++cp) {
    686 			if (*cp == pathsep)
    687 				*cp = '/';
    688 		}
    689 	}
    690 	ecode = (*pf->f_validate)(&filename, tp->th_opcode);
    691 	if (logging) {
    692 		syslog(LOG_INFO, "%s: %s request for %s: %s",
    693 			verifyhost((struct sockaddr *)&from),
    694 			tp->th_opcode == WRQ ? "write" : "read",
    695 			filename, errtomsg(ecode));
    696 	}
    697 	if (ecode) {
    698 		/*
    699 		 * Avoid storms of naks to a RRQ broadcast for a relative
    700 		 * bootfile pathname from a diskless Sun.
    701 		 */
    702 		if (suppress_naks && *filename != '/' && ecode == ENOTFOUND)
    703 			exit(0);
    704 		nak(ecode);
    705 		exit(1);
    706 	}
    707 
    708 	if (etftp) {
    709 		struct tftphdr *oack_h;
    710 
    711 		if (tftp_opt_tsize) {
    712 			int l;
    713 
    714 			if (sizeof(oackbuf) > alen &&
    715 			    (l = snprintf(oackbuf + alen,
    716 			    sizeof(oackbuf) - alen, "tsize%c%u%c", 0,
    717 			    tftp_tsize, 0)) > 0)
    718 				alen += l;
    719 		}
    720 		oack_h = (struct tftphdr *) oackbuf;
    721 		oack_h->th_opcode = htons(OACK);
    722 	}
    723 
    724 	if (tp->th_opcode == WRQ)
    725 		(*pf->f_recv)(pf, etftp, alen);
    726 	else
    727 		(*pf->f_send)(pf, etftp, alen);
    728 	exit(0);
    729 }
    730 
    731 
    732 FILE *file;
    733 
    734 /*
    735  * Validate file access.  Since we
    736  * have no uid or gid, for now require
    737  * file to exist and be publicly
    738  * readable/writable.
    739  * If we were invoked with arguments
    740  * from inetd then the file must also be
    741  * in one of the given directory prefixes.
    742  */
    743 int
    744 validate_access(char **filep, int mode)
    745 {
    746 	struct stat	 stbuf;
    747 	struct dirlist	*dirp;
    748 	static char	 pathname[MAXPATHLEN];
    749 	char		*filename;
    750 	int		 fd;
    751 	int		 create = 0;
    752 	int		 trunc = 0;
    753 
    754 	filename = *filep;
    755 
    756 	/*
    757 	 * Prevent tricksters from getting around the directory restrictions
    758 	 */
    759 	if (strstr(filename, "/../"))
    760 		return (EACCESS);
    761 
    762 	if (*filename == '/') {
    763 		/*
    764 		 * Allow the request if it's in one of the approved locations.
    765 		 * Special case: check the null prefix ("/") by looking
    766 		 * for length = 1 and relying on the arg. processing that
    767 		 * it's a /.
    768 		 */
    769 		for (dirp = dirs; dirp->name != NULL; dirp++) {
    770 			if (dirp->len == 1 ||
    771 			    (!strncmp(filename, dirp->name, dirp->len) &&
    772 			     filename[dirp->len] == '/'))
    773 				    break;
    774 		}
    775 		/* If directory list is empty, allow access to any file */
    776 		if (dirp->name == NULL && dirp != dirs)
    777 			return (EACCESS);
    778 		if (stat(filename, &stbuf) < 0)
    779 			return (errno == ENOENT ? ENOTFOUND : EACCESS);
    780 		if (!S_ISREG(stbuf.st_mode))
    781 			return (ENOTFOUND);
    782 		if (mode == RRQ) {
    783 			if ((stbuf.st_mode & S_IROTH) == 0)
    784 				return (EACCESS);
    785 		} else {
    786 			if ((stbuf.st_mode & S_IWOTH) == 0)
    787 				return (EACCESS);
    788 		}
    789 	} else {
    790 		/*
    791 		 * Relative file name: search the approved locations for it.
    792 		 */
    793 
    794 		if (!strncmp(filename, "../", 3))
    795 			return (EACCESS);
    796 
    797 		/*
    798 		 * Find the first file that exists in any of the directories,
    799 		 * check access on it.
    800 		 */
    801 		if (dirs[0].name != NULL) {
    802 			for (dirp = dirs; dirp->name != NULL; dirp++) {
    803 				snprintf(pathname, sizeof pathname, "%s/%s",
    804 				    dirp->name, filename);
    805 				if (stat(pathname, &stbuf) == 0 &&
    806 				    (stbuf.st_mode & S_IFMT) == S_IFREG) {
    807 					break;
    808 				}
    809 			}
    810 			if (dirp->name == NULL)
    811 				return (ENOTFOUND);
    812 			if (mode == RRQ && !(stbuf.st_mode & S_IROTH))
    813 				return (EACCESS);
    814 			if (mode == WRQ && !(stbuf.st_mode & S_IWOTH))
    815 				return (EACCESS);
    816 			*filep = filename = pathname;
    817 		} else {
    818 			int stat_rc;
    819 
    820 			/*
    821 			 * If there's no directory list, take our cue from the
    822 			 * absolute file request check above (*filename == '/'),
    823 			 * and allow access to anything.
    824 			 */
    825 			stat_rc = stat(filename, &stbuf);
    826 			if (mode == RRQ) {
    827 				/* Read request */
    828 				if (stat_rc < 0)
    829 				       return (errno == ENOENT ? ENOTFOUND : EACCESS);
    830 				if (!S_ISREG(stbuf.st_mode))
    831 				       return (ENOTFOUND);
    832 				if ((stbuf.st_mode & S_IROTH) == 0)
    833 					return (EACCESS);
    834 			} else {
    835 				if (stat_rc < 0) {
    836 				       /* Can't stat */
    837 				       if (errno == EACCES) {
    838 					       /* Permission denied */
    839 					       return EACCESS;
    840 				       } else {
    841 					       /* Not there */
    842 					       if (unrestricted_writes) {
    843 						       /* need to creat new file! */
    844 						       create = O_CREAT;
    845 					       } else {
    846 						       /* Permission denied */
    847 						       return EACCESS;
    848 					       }
    849 				       }
    850 				} else {
    851 				       /* Can stat */
    852 				       if ((stbuf.st_mode & S_IWOTH) == 0) {
    853 					       return (EACCESS);
    854 				       }
    855 				       trunc = O_TRUNC;
    856 				}
    857 			}
    858 			*filep = filename;
    859 		}
    860 	}
    861 
    862 	if (tftp_opt_tsize && mode == RRQ)
    863 		tftp_tsize = (unsigned long) stbuf.st_size;
    864 
    865 	fd = open(filename, mode == RRQ ? O_RDONLY : O_WRONLY | trunc | create,
    866 			0644); /* debatable */
    867 	if (fd < 0)
    868 		return (errno + 100);
    869 	file = fdopen(fd, (mode == RRQ)? "r":"w");
    870 	if (file == NULL) {
    871 		close(fd);
    872 		return (errno + 100);
    873 	}
    874 	return (0);
    875 }
    876 
    877 static int	timeout;
    878 static jmp_buf	timeoutbuf;
    879 
    880 static void
    881 timer(int dummy)
    882 {
    883 
    884 	timeout += rexmtval;
    885 	if (timeout >= maxtimeout)
    886 		exit(1);
    887 	longjmp(timeoutbuf, 1);
    888 }
    889 
    890 static const char *
    891 opcode(int code)
    892 {
    893 	static char obuf[64];
    894 
    895 	switch (code) {
    896 	case RRQ:
    897 		return "RRQ";
    898 	case WRQ:
    899 		return "WRQ";
    900 	case DATA:
    901 		return "DATA";
    902 	case ACK:
    903 		return "ACK";
    904 	case ERROR:
    905 		return "ERROR";
    906 	case OACK:
    907 		return "OACK";
    908 	default:
    909 		(void)snprintf(obuf, sizeof(obuf), "*code 0x%x*", code);
    910 		return obuf;
    911 	}
    912 }
    913 
    914 /*
    915  * Send the requested file.
    916  */
    917 static void
    918 sendfile(struct formats *pf, volatile int etftp, int acklength)
    919 {
    920 	volatile unsigned int block;
    921 	struct tftphdr	*dp;
    922 	struct tftphdr	*ap;    /* ack packet */
    923 	volatile int	 size;
    924 	int n;
    925 
    926 	signal(SIGALRM, timer);
    927 	ap = (struct tftphdr *)ackbuf;
    928 	if (etftp) {
    929 		dp = (struct tftphdr *)oackbuf;
    930 		size = acklength - 4;
    931 		block = 0;
    932 	} else {
    933 		dp = r_init();
    934 		size = 0;
    935 		block = 1;
    936 	}
    937 
    938 	do {
    939 		if (block > 0) {
    940 			size = readit(file, &dp, tftp_blksize, pf->f_convert);
    941 			if (size < 0) {
    942 				nak(errno + 100);
    943 				goto abort;
    944 			}
    945 			dp->th_opcode = htons((u_short)DATA);
    946 			dp->th_block = htons((u_short)block);
    947 		}
    948 		timeout = 0;
    949 		(void)setjmp(timeoutbuf);
    950 
    951 send_data:
    952 		if (!etftp && debug)
    953 			syslog(LOG_DEBUG, "Send DATA %u", block);
    954 		if ((n = send(peer, dp, size + 4, 0)) != size + 4) {
    955 			syslog(LOG_ERR, "tftpd: write: %m");
    956 			goto abort;
    957 		}
    958 		if (block)
    959 			read_ahead(file, tftp_blksize, pf->f_convert);
    960 		for ( ; ; ) {
    961 			alarm(rexmtval);        /* read the ack */
    962 			n = recv(peer, ackbuf, tftp_blksize, 0);
    963 			alarm(0);
    964 			if (n < 0) {
    965 				syslog(LOG_ERR, "tftpd: read: %m");
    966 				goto abort;
    967 			}
    968 			ap->th_opcode = ntohs((u_short)ap->th_opcode);
    969 			ap->th_block = ntohs((u_short)ap->th_block);
    970 			switch (ap->th_opcode) {
    971 			case ERROR:
    972 				goto abort;
    973 
    974 			case ACK:
    975 				if (etftp && ap->th_block == 0) {
    976 					etftp = 0;
    977 					acklength = 0;
    978 					dp = r_init();
    979 					goto done;
    980 				}
    981 				if (ap->th_block == (u_short)block)
    982 					goto done;
    983 				if (debug)
    984 					syslog(LOG_DEBUG, "Resync ACK %u != %u",
    985 					    (unsigned int)ap->th_block, block);
    986 				/* Re-synchronize with the other side */
    987 				(void) synchnet(peer, tftp_blksize);
    988 				if (ap->th_block == (u_short)(block - 1))
    989 					goto send_data;
    990 			default:
    991 				syslog(LOG_INFO, "Received %s in sendfile\n",
    992 				    opcode(dp->th_opcode));
    993 			}
    994 
    995 		}
    996 done:
    997 		if (debug)
    998 			syslog(LOG_DEBUG, "Received ACK for block %u", block);
    999 		if (block == UINT16_MAX && size == tftp_blksize)
   1000 			syslog(LOG_WARNING,
   1001 			    "Block number wrapped (hint: increase block size)");
   1002 		block++;
   1003 	} while (size == tftp_blksize || block == 1);
   1004 abort:
   1005 	(void) fclose(file);
   1006 }
   1007 
   1008 static void
   1009 justquit(int dummy)
   1010 {
   1011 
   1012 	exit(0);
   1013 }
   1014 
   1015 /*
   1016  * Receive a file.
   1017  */
   1018 static void
   1019 recvfile(struct formats *pf, volatile int etftp, volatile int acklength)
   1020 {
   1021 	volatile unsigned int block;
   1022 	struct tftphdr	*dp;
   1023 	struct tftphdr	*ap;    /* ack buffer */
   1024 	volatile int size;
   1025 	int n;
   1026 
   1027 	signal(SIGALRM, timer);
   1028 	dp = w_init();
   1029 	ap = (struct tftphdr *)oackbuf;
   1030 	block = 0;
   1031 	do {
   1032 		timeout = 0;
   1033 		if (etftp == 0) {
   1034 			ap = (struct tftphdr *)ackbuf;
   1035 			ap->th_opcode = htons((u_short)ACK);
   1036 			ap->th_block = htons((u_short)block);
   1037 			acklength = 4;
   1038 		}
   1039 		if (debug)
   1040 			syslog(LOG_DEBUG, "Sending ACK for block %u\n", block);
   1041 		if (block == UINT16_MAX)
   1042 			syslog(LOG_WARNING,
   1043 			    "Block number wrapped (hint: increase block size)");
   1044 		block++;
   1045 		(void) setjmp(timeoutbuf);
   1046 send_ack:
   1047 		ap = (struct tftphdr *) (etftp ? oackbuf : ackbuf);
   1048 		if (send(peer, ap, acklength, 0) != acklength) {
   1049 			syslog(LOG_ERR, "tftpd: write: %m");
   1050 			goto abort;
   1051 		}
   1052 		write_behind(file, pf->f_convert);
   1053 		for ( ; ; ) {
   1054 			alarm(rexmtval);
   1055 			n = recv(peer, dp, tftp_blksize + 4, 0);
   1056 			alarm(0);
   1057 			if (n < 0) {            /* really? */
   1058 				syslog(LOG_ERR, "tftpd: read: %m");
   1059 				goto abort;
   1060 			}
   1061 			etftp = 0;
   1062 			dp->th_opcode = ntohs((u_short)dp->th_opcode);
   1063 			dp->th_block = ntohs((u_short)dp->th_block);
   1064 			if (debug)
   1065 				syslog(LOG_DEBUG, "Received %s for block %u",
   1066 				    opcode(dp->th_opcode),
   1067 				    (unsigned int)dp->th_block);
   1068 
   1069 			switch (dp->th_opcode) {
   1070 			case ERROR:
   1071 				goto abort;
   1072 			case DATA:
   1073 				if (dp->th_block == block)
   1074 					goto done;   /* normal */
   1075 				if (debug)
   1076 					syslog(LOG_DEBUG, "Resync %u != %u",
   1077 					    (unsigned int)dp->th_block, block);
   1078 				/* Re-synchronize with the other side */
   1079 				(void) synchnet(peer, tftp_blksize);
   1080 				if (dp->th_block == (block-1))
   1081 					goto send_ack;          /* rexmit */
   1082 				break;
   1083 			default:
   1084 				syslog(LOG_INFO, "Received %s in recvfile\n",
   1085 				    opcode(dp->th_opcode));
   1086 				break;
   1087 			}
   1088 		}
   1089 done:
   1090 		if (debug)
   1091 			syslog(LOG_DEBUG, "Got block %u", block);
   1092 		/*  size = write(file, dp->th_data, n - 4); */
   1093 		size = writeit(file, &dp, n - 4, pf->f_convert);
   1094 		if (size != (n-4)) {                    /* ahem */
   1095 			if (size < 0) nak(errno + 100);
   1096 			else nak(ENOSPACE);
   1097 			goto abort;
   1098 		}
   1099 	} while (size == tftp_blksize);
   1100 	write_behind(file, pf->f_convert);
   1101 	(void) fclose(file);            /* close data file */
   1102 
   1103 	ap->th_opcode = htons((u_short)ACK);    /* send the "final" ack */
   1104 	ap->th_block = htons((u_short)(block));
   1105 	if (debug)
   1106 		syslog(LOG_DEBUG, "Send final ACK %u", block);
   1107 	(void) send(peer, ackbuf, 4, 0);
   1108 
   1109 	signal(SIGALRM, justquit);      /* just quit on timeout */
   1110 	alarm(rexmtval);
   1111 	n = recv(peer, buf, sizeof (buf), 0); /* normally times out and quits */
   1112 	alarm(0);
   1113 	if (n >= 4 &&                   /* if read some data */
   1114 	    dp->th_opcode == DATA &&    /* and got a data block */
   1115 	    block == dp->th_block) {	/* then my last ack was lost */
   1116 		(void) send(peer, ackbuf, 4, 0);     /* resend final ack */
   1117 	}
   1118 abort:
   1119 	return;
   1120 }
   1121 
   1122 const struct errmsg {
   1123 	int		 e_code;
   1124 	const char	*e_msg;
   1125 } errmsgs[] = {
   1126 	{ EUNDEF,	"Undefined error code" },
   1127 	{ ENOTFOUND,	"File not found" },
   1128 	{ EACCESS,	"Access violation" },
   1129 	{ ENOSPACE,	"Disk full or allocation exceeded" },
   1130 	{ EBADOP,	"Illegal TFTP operation" },
   1131 	{ EBADID,	"Unknown transfer ID" },
   1132 	{ EEXISTS,	"File already exists" },
   1133 	{ ENOUSER,	"No such user" },
   1134 	{ EOPTNEG,	"Option negotiation failed" },
   1135 	{ -1,		0 }
   1136 };
   1137 
   1138 static const char *
   1139 errtomsg(int error)
   1140 {
   1141 	static char ebuf[20];
   1142 	const struct errmsg *pe;
   1143 
   1144 	if (error == 0)
   1145 		return ("success");
   1146 	for (pe = errmsgs; pe->e_code >= 0; pe++)
   1147 		if (pe->e_code == error)
   1148 			return (pe->e_msg);
   1149 	snprintf(ebuf, sizeof(ebuf), "error %d", error);
   1150 	return (ebuf);
   1151 }
   1152 
   1153 /*
   1154  * Send a nak packet (error message).
   1155  * Error code passed in is one of the
   1156  * standard TFTP codes, or a UNIX errno
   1157  * offset by 100.
   1158  */
   1159 static void
   1160 nak(int error)
   1161 {
   1162 	const struct errmsg *pe;
   1163 	struct tftphdr *tp;
   1164 	int	length;
   1165 	size_t	msglen;
   1166 
   1167 	tp = (struct tftphdr *)buf;
   1168 	tp->th_opcode = htons((u_short)ERROR);
   1169 	msglen = sizeof(buf) - (&tp->th_msg[0] - buf);
   1170 	for (pe = errmsgs; pe->e_code >= 0; pe++)
   1171 		if (pe->e_code == error)
   1172 			break;
   1173 	if (pe->e_code < 0) {
   1174 		tp->th_code = EUNDEF;   /* set 'undef' errorcode */
   1175 		strlcpy(tp->th_msg, strerror(error - 100), msglen);
   1176 	} else {
   1177 		tp->th_code = htons((u_short)error);
   1178 		strlcpy(tp->th_msg, pe->e_msg, msglen);
   1179 	}
   1180 	if (debug)
   1181 		syslog(LOG_DEBUG, "Send NACK %s", tp->th_msg);
   1182 	length = strlen(tp->th_msg);
   1183 	msglen = &tp->th_msg[length + 1] - buf;
   1184 	if (send(peer, buf, msglen, 0) != (ssize_t)msglen)
   1185 		syslog(LOG_ERR, "nak: %m");
   1186 }
   1187 
   1188 static char *
   1189 verifyhost(struct sockaddr *fromp)
   1190 {
   1191 	static char hbuf[MAXHOSTNAMELEN];
   1192 
   1193 	if (getnameinfo(fromp, fromp->sa_len, hbuf, sizeof(hbuf), NULL, 0, 0))
   1194 		strlcpy(hbuf, "?", sizeof(hbuf));
   1195 	return (hbuf);
   1196 }
   1197