Home | History | Annotate | Line # | Download | only in tftpd
tftpd.c revision 1.8
      1 /*
      2  * Copyright (c) 1983 Regents of the University of California.
      3  * All rights reserved.
      4  *
      5  * Redistribution and use in source and binary forms, with or without
      6  * modification, are permitted provided that the following conditions
      7  * are met:
      8  * 1. Redistributions of source code must retain the above copyright
      9  *    notice, this list of conditions and the following disclaimer.
     10  * 2. Redistributions in binary form must reproduce the above copyright
     11  *    notice, this list of conditions and the following disclaimer in the
     12  *    documentation and/or other materials provided with the distribution.
     13  * 3. All advertising materials mentioning features or use of this software
     14  *    must display the following acknowledgement:
     15  *	This product includes software developed by the University of
     16  *	California, Berkeley and its contributors.
     17  * 4. Neither the name of the University nor the names of its contributors
     18  *    may be used to endorse or promote products derived from this software
     19  *    without specific prior written permission.
     20  *
     21  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     31  * SUCH DAMAGE.
     32  */
     33 
     34 #ifndef lint
     35 char copyright[] =
     36 "@(#) Copyright (c) 1983 Regents of the University of California.\n\
     37  All rights reserved.\n";
     38 #endif /* not lint */
     39 
     40 #ifndef lint
     41 /*static char sccsid[] = "from: @(#)tftpd.c	5.13 (Berkeley) 2/26/91";*/
     42 static char rcsid[] = "$Id: tftpd.c,v 1.8 1997/04/22 10:33:07 mrg Exp $";
     43 #endif /* not lint */
     44 
     45 /*
     46  * Trivial file transfer protocol server.
     47  *
     48  * This version includes many modifications by Jim Guyton <guyton@rand-unix>
     49  */
     50 
     51 #include <sys/types.h>
     52 #include <sys/ioctl.h>
     53 #include <sys/stat.h>
     54 #include <signal.h>
     55 #include <fcntl.h>
     56 
     57 #include <sys/socket.h>
     58 #include <netinet/in.h>
     59 #include <arpa/tftp.h>
     60 #include <netdb.h>
     61 
     62 #include <setjmp.h>
     63 #include <syslog.h>
     64 #include <stdio.h>
     65 #include <errno.h>
     66 #include <ctype.h>
     67 #include <string.h>
     68 #include <stdlib.h>
     69 
     70 /* XXX svr4 defines UID_NOBODY and GID_NOBODY constants in <sys/param.h> */
     71 #define UID_NOBODY	32767
     72 #define GID_NOBODY	32766
     73 
     74 #define	TIMEOUT		5
     75 
     76 extern	int errno;
     77 extern	char *__progname;
     78 struct	sockaddr_in s_in = { AF_INET };
     79 int	peer;
     80 int	rexmtval = TIMEOUT;
     81 int	maxtimeout = 5*TIMEOUT;
     82 
     83 #define	PKTSIZE	SEGSIZE+4
     84 char	buf[PKTSIZE];
     85 char	ackbuf[PKTSIZE];
     86 struct	sockaddr_in from;
     87 int	fromlen;
     88 
     89 #define MAXARG	4
     90 char	*dirs[MAXARG+1];
     91 
     92 int	secure = 0;
     93 
     94 static void
     95 usage()
     96 {
     97 	syslog(LOG_ERR, "Usage: %s [-s] [directory ...]\n", __progname);
     98 	exit(1);
     99 }
    100 
    101 main(argc, argv)
    102 	int    argc;
    103 	char **argv;
    104 {
    105 	register struct tftphdr *tp;
    106 	register int n = 0;
    107 	int on = 1;
    108 	int fd = 0;
    109 	int c;
    110 
    111 	openlog("tftpd", LOG_PID, LOG_DAEMON);
    112 
    113 	while ((c = getopt(argc, argv, "s")) != -1)
    114 		switch (c) {
    115 		case 's':
    116 			secure = 1;
    117 			break;
    118 
    119 		default:
    120 			usage();
    121 			break;
    122 		}
    123 
    124 	for (; optind != argc; optind++) {
    125 		if (!secure) {
    126 			if (n >= MAXARG) {
    127 				syslog(LOG_ERR, "too many directories\n");
    128 				exit(1);
    129 			} else
    130 				dirs[n++] = argv[optind];
    131 		}
    132 		if (chdir(argv[optind])) {
    133 			syslog(LOG_ERR, "%s: %m\n", argv[optind]);
    134 			exit(1);
    135 		}
    136 	}
    137 
    138 	if (secure && chroot(".")) {
    139 		syslog(LOG_ERR, "chroot: %m\n");
    140 		exit(1);
    141 	}
    142 
    143 	if (setgid(GID_NOBODY)) {
    144 		syslog(LOG_ERR, "setgid: %m");
    145 		exit(1);
    146 	}
    147 
    148 	if (setgroups(0, NULL)) {
    149 		syslog(LOG_ERR, "setgroups: %m");
    150 		exit(1);
    151 	}
    152 
    153 	if (setuid(UID_NOBODY)) {
    154 		syslog(LOG_ERR, "setuid: %m");
    155 		exit(1);
    156 	}
    157 
    158 	if (ioctl(fd, FIONBIO, &on) < 0) {
    159 		syslog(LOG_ERR, "ioctl(FIONBIO): %m\n");
    160 		exit(1);
    161 	}
    162 	fromlen = sizeof (from);
    163 	n = recvfrom(fd, buf, sizeof (buf), 0,
    164 	    (struct sockaddr *)&from, &fromlen);
    165 	if (n < 0) {
    166 		syslog(LOG_ERR, "recvfrom: %m\n");
    167 		exit(1);
    168 	}
    169 	/*
    170 	 * Now that we have read the message out of the UDP
    171 	 * socket, we fork and exit.  Thus, inetd will go back
    172 	 * to listening to the tftp port, and the next request
    173 	 * to come in will start up a new instance of tftpd.
    174 	 *
    175 	 * We do this so that inetd can run tftpd in "wait" mode.
    176 	 * The problem with tftpd running in "nowait" mode is that
    177 	 * inetd may get one or more successful "selects" on the
    178 	 * tftp port before we do our receive, so more than one
    179 	 * instance of tftpd may be started up.  Worse, if tftpd
    180 	 * break before doing the above "recvfrom", inetd would
    181 	 * spawn endless instances, clogging the system.
    182 	 */
    183 	{
    184 		int pid;
    185 		int i, j;
    186 
    187 		for (i = 1; i < 20; i++) {
    188 		    pid = fork();
    189 		    if (pid < 0) {
    190 				sleep(i);
    191 				/*
    192 				 * flush out to most recently sent request.
    193 				 *
    194 				 * This may drop some request, but those
    195 				 * will be resent by the clients when
    196 				 * they timeout.  The positive effect of
    197 				 * this flush is to (try to) prevent more
    198 				 * than one tftpd being started up to service
    199 				 * a single request from a single client.
    200 				 */
    201 				j = sizeof from;
    202 				i = recvfrom(fd, buf, sizeof (buf), 0,
    203 				    (struct sockaddr *)&from, &j);
    204 				if (i > 0) {
    205 					n = i;
    206 					fromlen = j;
    207 				}
    208 		    } else {
    209 				break;
    210 		    }
    211 		}
    212 		if (pid < 0) {
    213 			syslog(LOG_ERR, "fork: %m\n");
    214 			exit(1);
    215 		} else if (pid != 0) {
    216 			exit(0);
    217 		}
    218 	}
    219 	from.sin_len = sizeof(struct sockaddr_in);
    220 	from.sin_family = AF_INET;
    221 	alarm(0);
    222 	close(fd);
    223 	close(1);
    224 	peer = socket(AF_INET, SOCK_DGRAM, 0);
    225 	if (peer < 0) {
    226 		syslog(LOG_ERR, "socket: %m\n");
    227 		exit(1);
    228 	}
    229 	if (bind(peer, (struct sockaddr *)&s_in, sizeof (s_in)) < 0) {
    230 		syslog(LOG_ERR, "bind: %m\n");
    231 		exit(1);
    232 	}
    233 	if (connect(peer, (struct sockaddr *)&from, sizeof(from)) < 0) {
    234 		syslog(LOG_ERR, "connect: %m\n");
    235 		exit(1);
    236 	}
    237 	tp = (struct tftphdr *)buf;
    238 	tp->th_opcode = ntohs(tp->th_opcode);
    239 	if (tp->th_opcode == RRQ || tp->th_opcode == WRQ)
    240 		tftp(tp, n);
    241 	exit(1);
    242 }
    243 
    244 int	validate_access();
    245 int	sendfile(), recvfile();
    246 
    247 struct formats {
    248 	char	*f_mode;
    249 	int	(*f_validate)();
    250 	int	(*f_send)();
    251 	int	(*f_recv)();
    252 	int	f_convert;
    253 } formats[] = {
    254 	{ "netascii",	validate_access,	sendfile,	recvfile, 1 },
    255 	{ "octet",	validate_access,	sendfile,	recvfile, 0 },
    256 #ifdef notdef
    257 	{ "mail",	validate_user,		sendmail,	recvmail, 1 },
    258 #endif
    259 	{ 0 }
    260 };
    261 
    262 /*
    263  * Handle initial connection protocol.
    264  */
    265 tftp(tp, size)
    266 	struct tftphdr *tp;
    267 	int size;
    268 {
    269 	register char *cp;
    270 	int first = 1, ecode;
    271 	register struct formats *pf;
    272 	char *filename, *mode;
    273 
    274 	filename = cp = tp->th_stuff;
    275 again:
    276 	while (cp < buf + size) {
    277 		if (*cp == '\0')
    278 			break;
    279 		cp++;
    280 	}
    281 	if (*cp != '\0') {
    282 		nak(EBADOP);
    283 		exit(1);
    284 	}
    285 	if (first) {
    286 		mode = ++cp;
    287 		first = 0;
    288 		goto again;
    289 	}
    290 	for (cp = mode; *cp; cp++)
    291 		if (isupper(*cp))
    292 			*cp = tolower(*cp);
    293 	for (pf = formats; pf->f_mode; pf++)
    294 		if (strcmp(pf->f_mode, mode) == 0)
    295 			break;
    296 	if (pf->f_mode == 0) {
    297 		nak(EBADOP);
    298 		exit(1);
    299 	}
    300 	ecode = (*pf->f_validate)(filename, tp->th_opcode);
    301 	if (ecode) {
    302 		nak(ecode);
    303 		exit(1);
    304 	}
    305 	if (tp->th_opcode == WRQ)
    306 		(*pf->f_recv)(pf);
    307 	else
    308 		(*pf->f_send)(pf);
    309 	exit(0);
    310 }
    311 
    312 
    313 FILE *file;
    314 
    315 /*
    316  * Validate file access.  Since we
    317  * have no uid or gid, for now require
    318  * file to exist and be publicly
    319  * readable/writable.
    320  * If we were invoked with arguments
    321  * from inetd then the file must also be
    322  * in one of the given directory prefixes.
    323  * Note also, full path name must be
    324  * given as we have no login directory.
    325  */
    326 validate_access(filename, mode)
    327 	char *filename;
    328 	int mode;
    329 {
    330 	struct stat stbuf;
    331 	int	fd;
    332 	char *cp, **dirp;
    333 
    334 	if (!secure) {
    335 		if (*filename != '/')
    336 			return (EACCESS);
    337 		/*
    338 		 * prevent tricksters from getting around the directory
    339 		 * restrictions
    340 		 */
    341 		for (cp = filename + 1; *cp; cp++)
    342 			if(*cp == '.' && strncmp(cp-1, "/../", 4) == 0)
    343 				return(EACCESS);
    344 		for (dirp = dirs; *dirp; dirp++)
    345 			if (strncmp(filename, *dirp, strlen(*dirp)) == 0)
    346 				break;
    347 		if (*dirp==0 && dirp!=dirs)
    348 			return (EACCESS);
    349 	}
    350 	if (stat(filename, &stbuf) < 0)
    351 		return (errno == ENOENT ? ENOTFOUND : EACCESS);
    352 	if (mode == RRQ) {
    353 		if ((stbuf.st_mode&(S_IREAD >> 6)) == 0)
    354 			return (EACCESS);
    355 	} else {
    356 		if ((stbuf.st_mode&(S_IWRITE >> 6)) == 0)
    357 			return (EACCESS);
    358 	}
    359 	fd = open(filename, mode == RRQ ? 0 : 1);
    360 	if (fd < 0)
    361 		return (errno + 100);
    362 	file = fdopen(fd, (mode == RRQ)? "r":"w");
    363 	if (file == NULL) {
    364 		return errno+100;
    365 	}
    366 	return (0);
    367 }
    368 
    369 int	timeout;
    370 jmp_buf	timeoutbuf;
    371 
    372 void
    373 timer()
    374 {
    375 
    376 	timeout += rexmtval;
    377 	if (timeout >= maxtimeout)
    378 		exit(1);
    379 	longjmp(timeoutbuf, 1);
    380 }
    381 
    382 /*
    383  * Send the requested file.
    384  */
    385 sendfile(pf)
    386 	struct formats *pf;
    387 {
    388 	struct tftphdr *dp, *r_init();
    389 	register struct tftphdr *ap;    /* ack packet */
    390 	register int block = 1, size, n;
    391 
    392 	signal(SIGALRM, timer);
    393 	dp = r_init();
    394 	ap = (struct tftphdr *)ackbuf;
    395 	do {
    396 		size = readit(file, &dp, pf->f_convert);
    397 		if (size < 0) {
    398 			nak(errno + 100);
    399 			goto abort;
    400 		}
    401 		dp->th_opcode = htons((u_short)DATA);
    402 		dp->th_block = htons((u_short)block);
    403 		timeout = 0;
    404 		(void) setjmp(timeoutbuf);
    405 
    406 send_data:
    407 		if (send(peer, dp, size + 4, 0) != size + 4) {
    408 			syslog(LOG_ERR, "tftpd: write: %m\n");
    409 			goto abort;
    410 		}
    411 		read_ahead(file, pf->f_convert);
    412 		for ( ; ; ) {
    413 			alarm(rexmtval);        /* read the ack */
    414 			n = recv(peer, ackbuf, sizeof (ackbuf), 0);
    415 			alarm(0);
    416 			if (n < 0) {
    417 				syslog(LOG_ERR, "tftpd: read: %m\n");
    418 				goto abort;
    419 			}
    420 			ap->th_opcode = ntohs((u_short)ap->th_opcode);
    421 			ap->th_block = ntohs((u_short)ap->th_block);
    422 
    423 			if (ap->th_opcode == ERROR)
    424 				goto abort;
    425 
    426 			if (ap->th_opcode == ACK) {
    427 				if (ap->th_block == block) {
    428 					break;
    429 				}
    430 				/* Re-synchronize with the other side */
    431 				(void) synchnet(peer);
    432 				if (ap->th_block == (block -1)) {
    433 					goto send_data;
    434 				}
    435 			}
    436 
    437 		}
    438 		block++;
    439 	} while (size == SEGSIZE);
    440 abort:
    441 	(void) fclose(file);
    442 }
    443 
    444 void
    445 justquit()
    446 {
    447 	exit(0);
    448 }
    449 
    450 
    451 /*
    452  * Receive a file.
    453  */
    454 recvfile(pf)
    455 	struct formats *pf;
    456 {
    457 	struct tftphdr *dp, *w_init();
    458 	register struct tftphdr *ap;    /* ack buffer */
    459 	register int block = 0, n, size;
    460 
    461 	signal(SIGALRM, timer);
    462 	dp = w_init();
    463 	ap = (struct tftphdr *)ackbuf;
    464 	do {
    465 		timeout = 0;
    466 		ap->th_opcode = htons((u_short)ACK);
    467 		ap->th_block = htons((u_short)block);
    468 		block++;
    469 		(void) setjmp(timeoutbuf);
    470 send_ack:
    471 		if (send(peer, ackbuf, 4, 0) != 4) {
    472 			syslog(LOG_ERR, "tftpd: write: %m\n");
    473 			goto abort;
    474 		}
    475 		write_behind(file, pf->f_convert);
    476 		for ( ; ; ) {
    477 			alarm(rexmtval);
    478 			n = recv(peer, dp, PKTSIZE, 0);
    479 			alarm(0);
    480 			if (n < 0) {            /* really? */
    481 				syslog(LOG_ERR, "tftpd: read: %m\n");
    482 				goto abort;
    483 			}
    484 			dp->th_opcode = ntohs((u_short)dp->th_opcode);
    485 			dp->th_block = ntohs((u_short)dp->th_block);
    486 			if (dp->th_opcode == ERROR)
    487 				goto abort;
    488 			if (dp->th_opcode == DATA) {
    489 				if (dp->th_block == block) {
    490 					break;   /* normal */
    491 				}
    492 				/* Re-synchronize with the other side */
    493 				(void) synchnet(peer);
    494 				if (dp->th_block == (block-1))
    495 					goto send_ack;          /* rexmit */
    496 			}
    497 		}
    498 		/*  size = write(file, dp->th_data, n - 4); */
    499 		size = writeit(file, &dp, n - 4, pf->f_convert);
    500 		if (size != (n-4)) {                    /* ahem */
    501 			if (size < 0) nak(errno + 100);
    502 			else nak(ENOSPACE);
    503 			goto abort;
    504 		}
    505 	} while (size == SEGSIZE);
    506 	write_behind(file, pf->f_convert);
    507 	(void) fclose(file);            /* close data file */
    508 
    509 	ap->th_opcode = htons((u_short)ACK);    /* send the "final" ack */
    510 	ap->th_block = htons((u_short)(block));
    511 	(void) send(peer, ackbuf, 4, 0);
    512 
    513 	signal(SIGALRM, justquit);      /* just quit on timeout */
    514 	alarm(rexmtval);
    515 	n = recv(peer, buf, sizeof (buf), 0); /* normally times out and quits */
    516 	alarm(0);
    517 	if (n >= 4 &&                   /* if read some data */
    518 	    dp->th_opcode == DATA &&    /* and got a data block */
    519 	    block == dp->th_block) {	/* then my last ack was lost */
    520 		(void) send(peer, ackbuf, 4, 0);     /* resend final ack */
    521 	}
    522 abort:
    523 	return;
    524 }
    525 
    526 struct errmsg {
    527 	int	e_code;
    528 	char	*e_msg;
    529 } errmsgs[] = {
    530 	{ EUNDEF,	"Undefined error code" },
    531 	{ ENOTFOUND,	"File not found" },
    532 	{ EACCESS,	"Access violation" },
    533 	{ ENOSPACE,	"Disk full or allocation exceeded" },
    534 	{ EBADOP,	"Illegal TFTP operation" },
    535 	{ EBADID,	"Unknown transfer ID" },
    536 	{ EEXISTS,	"File already exists" },
    537 	{ ENOUSER,	"No such user" },
    538 	{ -1,		0 }
    539 };
    540 
    541 /*
    542  * Send a nak packet (error message).
    543  * Error code passed in is one of the
    544  * standard TFTP codes, or a UNIX errno
    545  * offset by 100.
    546  */
    547 nak(error)
    548 	int error;
    549 {
    550 	register struct tftphdr *tp;
    551 	int length;
    552 	register struct errmsg *pe;
    553 
    554 	tp = (struct tftphdr *)buf;
    555 	tp->th_opcode = htons((u_short)ERROR);
    556 	tp->th_code = htons((u_short)error);
    557 	for (pe = errmsgs; pe->e_code >= 0; pe++)
    558 		if (pe->e_code == error)
    559 			break;
    560 	if (pe->e_code < 0) {
    561 		pe->e_msg = strerror(error - 100);
    562 		tp->th_code = EUNDEF;   /* set 'undef' errorcode */
    563 	}
    564 	strcpy(tp->th_msg, pe->e_msg);
    565 	length = strlen(pe->e_msg);
    566 	tp->th_msg[length] = '\0';
    567 	length += 5;
    568 	if (send(peer, buf, length, 0) != length)
    569 		syslog(LOG_ERR, "nak: %m\n");
    570 }
    571