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