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