Home | History | Annotate | Line # | Download | only in tftpd
tftpd.c revision 1.39.8.1
      1 /*	$NetBSD: tftpd.c,v 1.39.8.1 2014/08/20 00:02:23 tls 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.39.8.1 2014/08/20 00:02:23 tls 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 [-cdln] [-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 'c':
    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 *ecode)
    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 		*ecode = EBADOP;
    442 		return -1;
    443 	}
    444 	if (bsize < 8 || bsize > 65464) {
    445 		syslog(LOG_NOTICE, "%s: %s request for %s: "
    446 			"out of range value %s for blksize option",
    447 			verifyhost((struct sockaddr *)&from),
    448 			tp->th_opcode == WRQ ? "write" : "read",
    449 			tp->th_stuff, val);
    450 		*ecode = EBADOP;
    451 		return -1;
    452 	}
    453 
    454 	tftp_blksize = bsize;
    455 	if (asize > *ackl && (l = snprintf(ack + *ackl, asize - *ackl,
    456 	    "blksize%c%lu%c", 0, bsize, 0)) > 0) {
    457 		*ackl += l;
    458 	} else {
    459 		*ecode = EBADOP;
    460 		return -1;
    461 	}
    462 
    463 	return 0;
    464 }
    465 
    466 static int
    467 timeout_handler(struct tftphdr *tp, const char *val, char *ack, size_t asize,
    468 		size_t *ackl, int *ecode)
    469 {
    470 	unsigned long tout;
    471 	char *endp;
    472 	int l;
    473 
    474 	errno = 0;
    475 	tout = strtoul(val, &endp, 10);
    476 	if ((tout == ULONG_MAX && errno == ERANGE) || *endp) {
    477 		syslog(LOG_NOTICE, "%s: %s request for %s: "
    478 			"illegal value %s for timeout option",
    479 			verifyhost((struct sockaddr *)&from),
    480 			tp->th_opcode == WRQ ? "write" : "read",
    481 			tp->th_stuff, val);
    482 		*ecode = EBADOP;
    483 		return -1;
    484 	}
    485 	if (tout < 1 || tout > 255) {
    486 		syslog(LOG_NOTICE, "%s: %s request for %s: "
    487 			"out of range value %s for timeout option",
    488 			verifyhost((struct sockaddr *)&from),
    489 			tp->th_opcode == WRQ ? "write" : "read",
    490 			tp->th_stuff, val);
    491 		return 0;
    492 	}
    493 
    494 	rexmtval = tout;
    495 	if (asize > *ackl && (l = snprintf(ack + *ackl, asize - *ackl,
    496 	    "timeout%c%lu%c", 0, tout, 0)) > 0)
    497 		*ackl += l;
    498 	else
    499 		return -1;
    500 	/*
    501 	 * Arbitrarily pick a maximum timeout on a request to 3
    502 	 * retransmissions if the interval timeout is more than
    503 	 * one minute.  Longest possible timeout is therefore
    504 	 * 3 * 255 - 1, or 764 seconds.
    505 	 */
    506 	if (rexmtval > 60) {
    507 		maxtimeout = rexmtval * 3;
    508 	} else {
    509 		maxtimeout = rexmtval * 5;
    510 	}
    511 
    512 	return 0;
    513 }
    514 
    515 static int
    516 tsize_handler(struct tftphdr *tp, const char *val, char *ack, size_t asize,
    517     size_t *ackl, int *ecode)
    518 {
    519 	unsigned long fsize;
    520 	char *endp;
    521 
    522 	/*
    523 	 * Maximum file even with extended tftp is 65535 blocks of
    524 	 * length 65464, or 4290183240 octets (4784056 less than 2^32).
    525 	 * unsigned long is at least 32 bits on all NetBSD archs.
    526 	 */
    527 
    528 	errno = 0;
    529 	fsize = strtoul(val, &endp, 10);
    530 	if ((fsize == ULONG_MAX && errno == ERANGE) || *endp) {
    531 		syslog(LOG_NOTICE, "%s: %s request for %s: "
    532 			"illegal value %s for tsize option",
    533 			verifyhost((struct sockaddr *)&from),
    534 			tp->th_opcode == WRQ ? "write" : "read",
    535 			tp->th_stuff, val);
    536 		*ecode = EBADOP;
    537 		return -1;
    538 	}
    539 	if (fsize > (unsigned long) 65535 * 65464) {
    540 		syslog(LOG_NOTICE, "%s: %s request for %s: "
    541 			"out of range value %s for tsize option",
    542 			verifyhost((struct sockaddr *)&from),
    543 			tp->th_opcode == WRQ ? "write" : "read",
    544 			tp->th_stuff, val);
    545 		*ecode = EBADOP;
    546 		return -1;
    547 	}
    548 
    549 	tftp_opt_tsize = 1;
    550 	tftp_tsize = fsize;
    551 	/*
    552 	 * We will report this later -- either replying with the fsize (WRQ)
    553 	 * or replying with the actual filesize (RRQ).
    554 	 */
    555 
    556 	return 0;
    557 }
    558 
    559 static const struct tftp_options {
    560 	const char *o_name;
    561 	int (*o_handler)(struct tftphdr *, const char *, char *, size_t,
    562 			 size_t *, int *);
    563 } options[] = {
    564 	{ "blksize", blk_handler },
    565 	{ "timeout", timeout_handler },
    566 	{ "tsize", tsize_handler },
    567 	{ .o_name = NULL }
    568 };
    569 
    570 /*
    571  * Get options for an extended tftp session.  Stuff the ones we
    572  * recognize in oackbuf.
    573  */
    574 static int
    575 get_options(struct tftphdr *tp, char *cp, int size, char *ackb, size_t asize,
    576     size_t *alen, int *ecode)
    577 {
    578 	const struct tftp_options *op;
    579 	char *option, *value, *endp;
    580 	int r, rv=0;
    581 
    582 	endp = cp + size;
    583 	while (cp < endp) {
    584 		option = cp;
    585 		while (*cp && cp < endp) {
    586 			*cp = tolower((unsigned char)*cp);
    587 			cp++;
    588 		}
    589 		if (*cp) {
    590 			/* if we have garbage at the end, just ignore it */
    591 			break;
    592 		}
    593 		cp++;	/* skip over NUL */
    594 		value = cp;
    595 		while (*cp && cp < endp) {
    596 			cp++;
    597 		}
    598 		if (*cp) {
    599 			/* if we have garbage at the end, just ignore it */
    600 			break;
    601 		}
    602 		cp++;
    603 		for (op = options; op->o_name; op++) {
    604 			if (strcmp(op->o_name, option) == 0)
    605 				break;
    606 		}
    607 		if (op->o_name) {
    608 			r = op->o_handler(tp, value, ackb, asize, alen, ecode);
    609 			if (r < 0) {
    610 				rv = -1;
    611 				break;
    612 			}
    613 			rv++;
    614 		} /* else ignore unknown options */
    615 	}
    616 
    617 	return rv;
    618 }
    619 
    620 /*
    621  * Handle initial connection protocol.
    622  */
    623 static void
    624 tftp(struct tftphdr *tp, int size)
    625 {
    626 	struct formats *pf;
    627 	char	*cp;
    628 	char	*filename, *mode;
    629 	int	 first, ecode, etftp = 0, r;
    630 	size_t alen;
    631 
    632 	ecode = 0;	/* XXX gcc */
    633 	first = 1;
    634 	mode = NULL;
    635 
    636 	filename = cp = tp->th_stuff;
    637 again:
    638 	while (cp < buf + size) {
    639 		if (*cp == '\0')
    640 			break;
    641 		cp++;
    642 	}
    643 	if (*cp != '\0') {
    644 		nak(EBADOP);
    645 		exit(1);
    646 	}
    647 	if (first) {
    648 		mode = ++cp;
    649 		first = 0;
    650 		goto again;
    651 	}
    652 	for (cp = mode; *cp; cp++)
    653 		*cp = tolower((unsigned char)*cp);
    654 	for (pf = formats; pf->f_mode; pf++)
    655 		if (strcmp(pf->f_mode, mode) == 0)
    656 			break;
    657 	if (pf->f_mode == 0) {
    658 		nak(EBADOP);
    659 		exit(1);
    660 	}
    661 	/*
    662 	 * cp currently points to the NUL byte following the mode.
    663 	 *
    664 	 * If we have some valid options, then let's assume that we're
    665 	 * now dealing with an extended tftp session.  Note that if we
    666 	 * don't get any options, then we *must* assume that we do not
    667 	 * have an extended tftp session.  If we get options, we fill
    668 	 * in the ack buf to acknowledge them.  If we skip that, then
    669 	 * the client *must* assume that we are not using an extended
    670 	 * session.
    671 	 */
    672 	size -= (++cp - (char *) tp);
    673 	if (size > 0 && *cp) {
    674 		alen = 2; /* Skip over opcode */
    675 		r = get_options(tp, cp, size, oackbuf, sizeof(oackbuf),
    676 		    &alen, &ecode);
    677 		if (r > 0) {
    678 			etftp = 1;
    679 		} else if (r < 0) {
    680 			nak(ecode);
    681 			exit(1);
    682 		}
    683 	}
    684 	/*
    685 	 * Globally replace the path separator given in the -p option
    686 	 * with / to cope with clients expecting a non-unix path separator.
    687 	 */
    688 	if (pathsep != '\0') {
    689 		for (cp = filename; *cp != '\0'; ++cp) {
    690 			if (*cp == pathsep)
    691 				*cp = '/';
    692 		}
    693 	}
    694 	ecode = (*pf->f_validate)(&filename, tp->th_opcode);
    695 	if (logging) {
    696 		syslog(LOG_INFO, "%s: %s request for %s: %s",
    697 			verifyhost((struct sockaddr *)&from),
    698 			tp->th_opcode == WRQ ? "write" : "read",
    699 			filename, errtomsg(ecode));
    700 	}
    701 	if (ecode) {
    702 		/*
    703 		 * Avoid storms of naks to a RRQ broadcast for a relative
    704 		 * bootfile pathname from a diskless Sun.
    705 		 */
    706 		if (suppress_naks && *filename != '/' && ecode == ENOTFOUND)
    707 			exit(0);
    708 		nak(ecode);
    709 		exit(1);
    710 	}
    711 
    712 	if (etftp) {
    713 		struct tftphdr *oack_h;
    714 
    715 		if (tftp_opt_tsize) {
    716 			int l;
    717 
    718 			if (sizeof(oackbuf) > alen &&
    719 			    (l = snprintf(oackbuf + alen,
    720 			    sizeof(oackbuf) - alen, "tsize%c%u%c", 0,
    721 			    tftp_tsize, 0)) > 0)
    722 				alen += l;
    723 		}
    724 		oack_h = (struct tftphdr *) oackbuf;
    725 		oack_h->th_opcode = htons(OACK);
    726 	}
    727 
    728 	if (tp->th_opcode == WRQ)
    729 		(*pf->f_recv)(pf, etftp, alen);
    730 	else
    731 		(*pf->f_send)(pf, etftp, alen);
    732 	exit(0);
    733 }
    734 
    735 
    736 FILE *file;
    737 
    738 /*
    739  * Validate file access.  Since we
    740  * have no uid or gid, for now require
    741  * file to exist and be publicly
    742  * readable/writable.
    743  * If we were invoked with arguments
    744  * from inetd then the file must also be
    745  * in one of the given directory prefixes.
    746  */
    747 int
    748 validate_access(char **filep, int mode)
    749 {
    750 	struct stat	 stbuf;
    751 	struct dirlist	*dirp;
    752 	static char	 pathname[MAXPATHLEN];
    753 	char		*filename;
    754 	int		 fd;
    755 	int		 create = 0;
    756 	int		 trunc = 0;
    757 
    758 	filename = *filep;
    759 
    760 	/*
    761 	 * Prevent tricksters from getting around the directory restrictions
    762 	 */
    763 	if (strstr(filename, "/../"))
    764 		return (EACCESS);
    765 
    766 	if (*filename == '/') {
    767 		/*
    768 		 * Allow the request if it's in one of the approved locations.
    769 		 * Special case: check the null prefix ("/") by looking
    770 		 * for length = 1 and relying on the arg. processing that
    771 		 * it's a /.
    772 		 */
    773 		for (dirp = dirs; dirp->name != NULL; dirp++) {
    774 			if (dirp->len == 1 ||
    775 			    (!strncmp(filename, dirp->name, dirp->len) &&
    776 			     filename[dirp->len] == '/'))
    777 				    break;
    778 		}
    779 		/* If directory list is empty, allow access to any file */
    780 		if (dirp->name == NULL && dirp != dirs)
    781 			return (EACCESS);
    782 		if (stat(filename, &stbuf) < 0)
    783 			return (errno == ENOENT ? ENOTFOUND : EACCESS);
    784 		if (!S_ISREG(stbuf.st_mode))
    785 			return (ENOTFOUND);
    786 		if (mode == RRQ) {
    787 			if ((stbuf.st_mode & S_IROTH) == 0)
    788 				return (EACCESS);
    789 		} else {
    790 			if ((stbuf.st_mode & S_IWOTH) == 0)
    791 				return (EACCESS);
    792 		}
    793 	} else {
    794 		/*
    795 		 * Relative file name: search the approved locations for it.
    796 		 */
    797 
    798 		if (!strncmp(filename, "../", 3))
    799 			return (EACCESS);
    800 
    801 		/*
    802 		 * Find the first file that exists in any of the directories,
    803 		 * check access on it.
    804 		 */
    805 		if (dirs[0].name != NULL) {
    806 			for (dirp = dirs; dirp->name != NULL; dirp++) {
    807 				snprintf(pathname, sizeof pathname, "%s/%s",
    808 				    dirp->name, filename);
    809 				if (stat(pathname, &stbuf) == 0 &&
    810 				    (stbuf.st_mode & S_IFMT) == S_IFREG) {
    811 					break;
    812 				}
    813 			}
    814 			if (dirp->name == NULL)
    815 				return (ENOTFOUND);
    816 			if (mode == RRQ && !(stbuf.st_mode & S_IROTH))
    817 				return (EACCESS);
    818 			if (mode == WRQ && !(stbuf.st_mode & S_IWOTH))
    819 				return (EACCESS);
    820 			*filep = filename = pathname;
    821 		} else {
    822 			int stat_rc;
    823 
    824 			/*
    825 			 * If there's no directory list, take our cue from the
    826 			 * absolute file request check above (*filename == '/'),
    827 			 * and allow access to anything.
    828 			 */
    829 			stat_rc = stat(filename, &stbuf);
    830 			if (mode == RRQ) {
    831 				/* Read request */
    832 				if (stat_rc < 0)
    833 				       return (errno == ENOENT ? ENOTFOUND : EACCESS);
    834 				if (!S_ISREG(stbuf.st_mode))
    835 				       return (ENOTFOUND);
    836 				if ((stbuf.st_mode & S_IROTH) == 0)
    837 					return (EACCESS);
    838 			} else {
    839 				if (stat_rc < 0) {
    840 				       /* Can't stat */
    841 				       if (errno == EACCES) {
    842 					       /* Permission denied */
    843 					       return EACCESS;
    844 				       } else {
    845 					       /* Not there */
    846 					       if (unrestricted_writes) {
    847 						       /* need to creat new file! */
    848 						       create = O_CREAT;
    849 					       } else {
    850 						       /* Permission denied */
    851 						       return EACCESS;
    852 					       }
    853 				       }
    854 				} else {
    855 				       /* Can stat */
    856 				       if ((stbuf.st_mode & S_IWOTH) == 0) {
    857 					       return (EACCESS);
    858 				       }
    859 				       trunc = O_TRUNC;
    860 				}
    861 			}
    862 			*filep = filename;
    863 		}
    864 	}
    865 
    866 	if (tftp_opt_tsize && mode == RRQ)
    867 		tftp_tsize = (unsigned long) stbuf.st_size;
    868 
    869 	fd = open(filename, mode == RRQ ? O_RDONLY : O_WRONLY | trunc | create,
    870 			0644); /* debatable */
    871 	if (fd < 0)
    872 		return (errno + 100);
    873 	file = fdopen(fd, (mode == RRQ)? "r":"w");
    874 	if (file == NULL) {
    875 		close(fd);
    876 		return (errno + 100);
    877 	}
    878 	return (0);
    879 }
    880 
    881 static int	timeout;
    882 static jmp_buf	timeoutbuf;
    883 
    884 static void
    885 timer(int dummy)
    886 {
    887 
    888 	timeout += rexmtval;
    889 	if (timeout >= maxtimeout)
    890 		exit(1);
    891 	longjmp(timeoutbuf, 1);
    892 }
    893 
    894 static const char *
    895 opcode(int code)
    896 {
    897 	static char obuf[64];
    898 
    899 	switch (code) {
    900 	case RRQ:
    901 		return "RRQ";
    902 	case WRQ:
    903 		return "WRQ";
    904 	case DATA:
    905 		return "DATA";
    906 	case ACK:
    907 		return "ACK";
    908 	case ERROR:
    909 		return "ERROR";
    910 	case OACK:
    911 		return "OACK";
    912 	default:
    913 		(void)snprintf(obuf, sizeof(obuf), "*code 0x%x*", code);
    914 		return obuf;
    915 	}
    916 }
    917 
    918 /*
    919  * Send the requested file.
    920  */
    921 static void
    922 sendfile(struct formats *pf, volatile int etftp, int acklength)
    923 {
    924 	volatile unsigned int block;
    925 	struct tftphdr	*dp;
    926 	struct tftphdr	*ap;    /* ack packet */
    927 	volatile int	 size;
    928 	int n;
    929 
    930 	signal(SIGALRM, timer);
    931 	ap = (struct tftphdr *)ackbuf;
    932 	if (etftp) {
    933 		dp = (struct tftphdr *)oackbuf;
    934 		size = acklength - 4;
    935 		block = 0;
    936 	} else {
    937 		dp = r_init();
    938 		size = 0;
    939 		block = 1;
    940 	}
    941 
    942 	do {
    943 		if (block > 0) {
    944 			size = readit(file, &dp, tftp_blksize, pf->f_convert);
    945 			if (size < 0) {
    946 				nak(errno + 100);
    947 				goto abort;
    948 			}
    949 			dp->th_opcode = htons((u_short)DATA);
    950 			dp->th_block = htons((u_short)block);
    951 		}
    952 		timeout = 0;
    953 		(void)setjmp(timeoutbuf);
    954 
    955 send_data:
    956 		if (!etftp && debug)
    957 			syslog(LOG_DEBUG, "Send DATA %u", block);
    958 		if ((n = send(peer, dp, size + 4, 0)) != size + 4) {
    959 			syslog(LOG_ERR, "tftpd: write: %m");
    960 			goto abort;
    961 		}
    962 		if (block)
    963 			read_ahead(file, tftp_blksize, pf->f_convert);
    964 		for ( ; ; ) {
    965 			alarm(rexmtval);        /* read the ack */
    966 			n = recv(peer, ackbuf, tftp_blksize, 0);
    967 			alarm(0);
    968 			if (n < 0) {
    969 				syslog(LOG_ERR, "tftpd: read: %m");
    970 				goto abort;
    971 			}
    972 			ap->th_opcode = ntohs((u_short)ap->th_opcode);
    973 			ap->th_block = ntohs((u_short)ap->th_block);
    974 			switch (ap->th_opcode) {
    975 			case ERROR:
    976 				goto abort;
    977 
    978 			case ACK:
    979 				if (etftp && ap->th_block == 0) {
    980 					etftp = 0;
    981 					acklength = 0;
    982 					dp = r_init();
    983 					goto done;
    984 				}
    985 				if (ap->th_block == (u_short)block)
    986 					goto done;
    987 				if (debug)
    988 					syslog(LOG_DEBUG, "Resync ACK %u != %u",
    989 					    (unsigned int)ap->th_block, block);
    990 				/* Re-synchronize with the other side */
    991 				(void) synchnet(peer, tftp_blksize);
    992 				if (ap->th_block == (u_short)(block - 1))
    993 					goto send_data;
    994 			default:
    995 				syslog(LOG_INFO, "Received %s in sendfile\n",
    996 				    opcode(dp->th_opcode));
    997 			}
    998 
    999 		}
   1000 done:
   1001 		if (debug)
   1002 			syslog(LOG_DEBUG, "Received ACK for block %u", block);
   1003 		if (block == UINT16_MAX && size == tftp_blksize)
   1004 			syslog(LOG_WARNING,
   1005 			    "Block number wrapped (hint: increase block size)");
   1006 		block++;
   1007 	} while (size == tftp_blksize || block == 1);
   1008 abort:
   1009 	(void) fclose(file);
   1010 }
   1011 
   1012 static void
   1013 justquit(int dummy)
   1014 {
   1015 
   1016 	exit(0);
   1017 }
   1018 
   1019 /*
   1020  * Receive a file.
   1021  */
   1022 static void
   1023 recvfile(struct formats *pf, volatile int etftp, volatile int acklength)
   1024 {
   1025 	volatile unsigned int block;
   1026 	struct tftphdr	*dp;
   1027 	struct tftphdr	*ap;    /* ack buffer */
   1028 	volatile int size;
   1029 	int n;
   1030 
   1031 	signal(SIGALRM, timer);
   1032 	dp = w_init();
   1033 	ap = (struct tftphdr *)oackbuf;
   1034 	block = 0;
   1035 	do {
   1036 		timeout = 0;
   1037 		if (etftp == 0) {
   1038 			ap = (struct tftphdr *)ackbuf;
   1039 			ap->th_opcode = htons((u_short)ACK);
   1040 			ap->th_block = htons((u_short)block);
   1041 			acklength = 4;
   1042 		}
   1043 		if (debug)
   1044 			syslog(LOG_DEBUG, "Sending ACK for block %u\n", block);
   1045 		if (block == UINT16_MAX)
   1046 			syslog(LOG_WARNING,
   1047 			    "Block number wrapped (hint: increase block size)");
   1048 		block++;
   1049 		(void) setjmp(timeoutbuf);
   1050 send_ack:
   1051 		ap = (struct tftphdr *) (etftp ? oackbuf : ackbuf);
   1052 		if (send(peer, ap, acklength, 0) != acklength) {
   1053 			syslog(LOG_ERR, "tftpd: write: %m");
   1054 			goto abort;
   1055 		}
   1056 		write_behind(file, pf->f_convert);
   1057 		for ( ; ; ) {
   1058 			alarm(rexmtval);
   1059 			n = recv(peer, dp, tftp_blksize + 4, 0);
   1060 			alarm(0);
   1061 			if (n < 0) {            /* really? */
   1062 				syslog(LOG_ERR, "tftpd: read: %m");
   1063 				goto abort;
   1064 			}
   1065 			etftp = 0;
   1066 			dp->th_opcode = ntohs((u_short)dp->th_opcode);
   1067 			dp->th_block = ntohs((u_short)dp->th_block);
   1068 			if (debug)
   1069 				syslog(LOG_DEBUG, "Received %s for block %u",
   1070 				    opcode(dp->th_opcode),
   1071 				    (unsigned int)dp->th_block);
   1072 
   1073 			switch (dp->th_opcode) {
   1074 			case ERROR:
   1075 				goto abort;
   1076 			case DATA:
   1077 				if (dp->th_block == block)
   1078 					goto done;   /* normal */
   1079 				if (debug)
   1080 					syslog(LOG_DEBUG, "Resync %u != %u",
   1081 					    (unsigned int)dp->th_block, block);
   1082 				/* Re-synchronize with the other side */
   1083 				(void) synchnet(peer, tftp_blksize);
   1084 				if (dp->th_block == (block-1))
   1085 					goto send_ack;          /* rexmit */
   1086 				break;
   1087 			default:
   1088 				syslog(LOG_INFO, "Received %s in recvfile\n",
   1089 				    opcode(dp->th_opcode));
   1090 				break;
   1091 			}
   1092 		}
   1093 done:
   1094 		if (debug)
   1095 			syslog(LOG_DEBUG, "Got block %u", block);
   1096 		/*  size = write(file, dp->th_data, n - 4); */
   1097 		size = writeit(file, &dp, n - 4, pf->f_convert);
   1098 		if (size != (n-4)) {                    /* ahem */
   1099 			if (size < 0) nak(errno + 100);
   1100 			else nak(ENOSPACE);
   1101 			goto abort;
   1102 		}
   1103 	} while (size == tftp_blksize);
   1104 	write_behind(file, pf->f_convert);
   1105 	(void) fclose(file);            /* close data file */
   1106 
   1107 	ap->th_opcode = htons((u_short)ACK);    /* send the "final" ack */
   1108 	ap->th_block = htons((u_short)(block));
   1109 	if (debug)
   1110 		syslog(LOG_DEBUG, "Send final ACK %u", block);
   1111 	(void) send(peer, ackbuf, 4, 0);
   1112 
   1113 	signal(SIGALRM, justquit);      /* just quit on timeout */
   1114 	alarm(rexmtval);
   1115 	n = recv(peer, buf, sizeof (buf), 0); /* normally times out and quits */
   1116 	alarm(0);
   1117 	if (n >= 4 &&                   /* if read some data */
   1118 	    dp->th_opcode == DATA &&    /* and got a data block */
   1119 	    block == dp->th_block) {	/* then my last ack was lost */
   1120 		(void) send(peer, ackbuf, 4, 0);     /* resend final ack */
   1121 	}
   1122 abort:
   1123 	return;
   1124 }
   1125 
   1126 const struct errmsg {
   1127 	int		 e_code;
   1128 	const char	*e_msg;
   1129 } errmsgs[] = {
   1130 	{ EUNDEF,	"Undefined error code" },
   1131 	{ ENOTFOUND,	"File not found" },
   1132 	{ EACCESS,	"Access violation" },
   1133 	{ ENOSPACE,	"Disk full or allocation exceeded" },
   1134 	{ EBADOP,	"Illegal TFTP operation" },
   1135 	{ EBADID,	"Unknown transfer ID" },
   1136 	{ EEXISTS,	"File already exists" },
   1137 	{ ENOUSER,	"No such user" },
   1138 	{ EOPTNEG,	"Option negotiation failed" },
   1139 	{ -1,		0 }
   1140 };
   1141 
   1142 static const char *
   1143 errtomsg(int error)
   1144 {
   1145 	static char ebuf[20];
   1146 	const struct errmsg *pe;
   1147 
   1148 	if (error == 0)
   1149 		return ("success");
   1150 	for (pe = errmsgs; pe->e_code >= 0; pe++)
   1151 		if (pe->e_code == error)
   1152 			return (pe->e_msg);
   1153 	snprintf(ebuf, sizeof(ebuf), "error %d", error);
   1154 	return (ebuf);
   1155 }
   1156 
   1157 /*
   1158  * Send a nak packet (error message).
   1159  * Error code passed in is one of the
   1160  * standard TFTP codes, or a UNIX errno
   1161  * offset by 100.
   1162  */
   1163 static void
   1164 nak(int error)
   1165 {
   1166 	const struct errmsg *pe;
   1167 	struct tftphdr *tp;
   1168 	int	length;
   1169 	size_t	msglen;
   1170 
   1171 	tp = (struct tftphdr *)buf;
   1172 	tp->th_opcode = htons((u_short)ERROR);
   1173 	msglen = sizeof(buf) - (&tp->th_msg[0] - buf);
   1174 	for (pe = errmsgs; pe->e_code >= 0; pe++)
   1175 		if (pe->e_code == error)
   1176 			break;
   1177 	if (pe->e_code < 0) {
   1178 		tp->th_code = EUNDEF;   /* set 'undef' errorcode */
   1179 		strlcpy(tp->th_msg, strerror(error - 100), msglen);
   1180 	} else {
   1181 		tp->th_code = htons((u_short)error);
   1182 		strlcpy(tp->th_msg, pe->e_msg, msglen);
   1183 	}
   1184 	if (debug)
   1185 		syslog(LOG_DEBUG, "Send NACK %s", tp->th_msg);
   1186 	length = strlen(tp->th_msg);
   1187 	msglen = &tp->th_msg[length + 1] - buf;
   1188 	if (send(peer, buf, msglen, 0) != (ssize_t)msglen)
   1189 		syslog(LOG_ERR, "nak: %m");
   1190 }
   1191 
   1192 static char *
   1193 verifyhost(struct sockaddr *fromp)
   1194 {
   1195 	static char hbuf[MAXHOSTNAMELEN];
   1196 
   1197 	if (getnameinfo(fromp, fromp->sa_len, hbuf, sizeof(hbuf), NULL, 0, 0))
   1198 		strlcpy(hbuf, "?", sizeof(hbuf));
   1199 	return (hbuf);
   1200 }
   1201