Home | History | Annotate | Line # | Download | only in tftpd
tftpd.c revision 1.4
      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.4 1994/01/10 16:29:48 mycroft 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 #define	TIMEOUT		5
     71 
     72 extern	int errno;
     73 struct	sockaddr_in s_in = { AF_INET };
     74 int	peer;
     75 int	rexmtval = TIMEOUT;
     76 int	maxtimeout = 5*TIMEOUT;
     77 
     78 #define	PKTSIZE	SEGSIZE+4
     79 char	buf[PKTSIZE];
     80 char	ackbuf[PKTSIZE];
     81 struct	sockaddr_in from;
     82 int	fromlen;
     83 
     84 #define MAXARG	4
     85 char	*dirs[MAXARG+1];
     86 
     87 int	secure = 0;
     88 
     89 main(ac, av)
     90 	char **av;
     91 {
     92 	register struct tftphdr *tp;
     93 	register int n = 0;
     94 	int on = 1;
     95 
     96 	ac--; av++;
     97 	if (!strcmp(*av, "-s")) {
     98 		ac--; av++;
     99 		secure = 1;
    100 	}
    101 	openlog("tftpd", LOG_PID, LOG_DAEMON);
    102 	while (ac-- > 0) {
    103 		if (!secure) {
    104 			if (n >= MAXARG) {
    105 				syslog(LOG_ERR, "too many directories\n");
    106 				exit(1);
    107 			} else
    108 				dirs[n++] = *av;
    109 		}
    110 		if (chdir(*av++)) {
    111 			syslog(LOG_ERR, "%s: %m\n", av[-1]);
    112 			exit(1);
    113 		}
    114 	}
    115 	if (secure && chroot(".")) {
    116 		syslog(LOG_ERR, "chroot: %m\n");
    117 		exit(1);
    118 	}
    119 	if (ioctl(0, FIONBIO, &on) < 0) {
    120 		syslog(LOG_ERR, "ioctl(FIONBIO): %m\n");
    121 		exit(1);
    122 	}
    123 	fromlen = sizeof (from);
    124 	n = recvfrom(0, buf, sizeof (buf), 0,
    125 	    (struct sockaddr *)&from, &fromlen);
    126 	if (n < 0) {
    127 		syslog(LOG_ERR, "recvfrom: %m\n");
    128 		exit(1);
    129 	}
    130 	/*
    131 	 * Now that we have read the message out of the UDP
    132 	 * socket, we fork and exit.  Thus, inetd will go back
    133 	 * to listening to the tftp port, and the next request
    134 	 * to come in will start up a new instance of tftpd.
    135 	 *
    136 	 * We do this so that inetd can run tftpd in "wait" mode.
    137 	 * The problem with tftpd running in "nowait" mode is that
    138 	 * inetd may get one or more successful "selects" on the
    139 	 * tftp port before we do our receive, so more than one
    140 	 * instance of tftpd may be started up.  Worse, if tftpd
    141 	 * break before doing the above "recvfrom", inetd would
    142 	 * spawn endless instances, clogging the system.
    143 	 */
    144 	{
    145 		int pid;
    146 		int i, j;
    147 
    148 		for (i = 1; i < 20; i++) {
    149 		    pid = fork();
    150 		    if (pid < 0) {
    151 				sleep(i);
    152 				/*
    153 				 * flush out to most recently sent request.
    154 				 *
    155 				 * This may drop some request, but those
    156 				 * will be resent by the clients when
    157 				 * they timeout.  The positive effect of
    158 				 * this flush is to (try to) prevent more
    159 				 * than one tftpd being started up to service
    160 				 * a single request from a single client.
    161 				 */
    162 				j = sizeof from;
    163 				i = recvfrom(0, buf, sizeof (buf), 0,
    164 				    (struct sockaddr *)&from, &j);
    165 				if (i > 0) {
    166 					n = i;
    167 					fromlen = j;
    168 				}
    169 		    } else {
    170 				break;
    171 		    }
    172 		}
    173 		if (pid < 0) {
    174 			syslog(LOG_ERR, "fork: %m\n");
    175 			exit(1);
    176 		} else if (pid != 0) {
    177 			exit(0);
    178 		}
    179 	}
    180 	from.sin_family = AF_INET;
    181 	alarm(0);
    182 	close(0);
    183 	close(1);
    184 	peer = socket(AF_INET, SOCK_DGRAM, 0);
    185 	if (peer < 0) {
    186 		syslog(LOG_ERR, "socket: %m\n");
    187 		exit(1);
    188 	}
    189 	if (bind(peer, (struct sockaddr *)&s_in, sizeof (s_in)) < 0) {
    190 		syslog(LOG_ERR, "bind: %m\n");
    191 		exit(1);
    192 	}
    193 	if (connect(peer, (struct sockaddr *)&from, sizeof(from)) < 0) {
    194 		syslog(LOG_ERR, "connect: %m\n");
    195 		exit(1);
    196 	}
    197 	tp = (struct tftphdr *)buf;
    198 	tp->th_opcode = ntohs(tp->th_opcode);
    199 	if (tp->th_opcode == RRQ || tp->th_opcode == WRQ)
    200 		tftp(tp, n);
    201 	exit(1);
    202 }
    203 
    204 int	validate_access();
    205 int	sendfile(), recvfile();
    206 
    207 struct formats {
    208 	char	*f_mode;
    209 	int	(*f_validate)();
    210 	int	(*f_send)();
    211 	int	(*f_recv)();
    212 	int	f_convert;
    213 } formats[] = {
    214 	{ "netascii",	validate_access,	sendfile,	recvfile, 1 },
    215 	{ "octet",	validate_access,	sendfile,	recvfile, 0 },
    216 #ifdef notdef
    217 	{ "mail",	validate_user,		sendmail,	recvmail, 1 },
    218 #endif
    219 	{ 0 }
    220 };
    221 
    222 /*
    223  * Handle initial connection protocol.
    224  */
    225 tftp(tp, size)
    226 	struct tftphdr *tp;
    227 	int size;
    228 {
    229 	register char *cp;
    230 	int first = 1, ecode;
    231 	register struct formats *pf;
    232 	char *filename, *mode;
    233 
    234 	filename = cp = tp->th_stuff;
    235 again:
    236 	while (cp < buf + size) {
    237 		if (*cp == '\0')
    238 			break;
    239 		cp++;
    240 	}
    241 	if (*cp != '\0') {
    242 		nak(EBADOP);
    243 		exit(1);
    244 	}
    245 	if (first) {
    246 		mode = ++cp;
    247 		first = 0;
    248 		goto again;
    249 	}
    250 	for (cp = mode; *cp; cp++)
    251 		if (isupper(*cp))
    252 			*cp = tolower(*cp);
    253 	for (pf = formats; pf->f_mode; pf++)
    254 		if (strcmp(pf->f_mode, mode) == 0)
    255 			break;
    256 	if (pf->f_mode == 0) {
    257 		nak(EBADOP);
    258 		exit(1);
    259 	}
    260 	ecode = (*pf->f_validate)(filename, tp->th_opcode);
    261 	if (ecode) {
    262 		nak(ecode);
    263 		exit(1);
    264 	}
    265 	if (tp->th_opcode == WRQ)
    266 		(*pf->f_recv)(pf);
    267 	else
    268 		(*pf->f_send)(pf);
    269 	exit(0);
    270 }
    271 
    272 
    273 FILE *file;
    274 
    275 /*
    276  * Validate file access.  Since we
    277  * have no uid or gid, for now require
    278  * file to exist and be publicly
    279  * readable/writable.
    280  * If we were invoked with arguments
    281  * from inetd then the file must also be
    282  * in one of the given directory prefixes.
    283  * Note also, full path name must be
    284  * given as we have no login directory.
    285  */
    286 validate_access(filename, mode)
    287 	char *filename;
    288 	int mode;
    289 {
    290 	struct stat stbuf;
    291 	int	fd;
    292 	char *cp, **dirp;
    293 
    294 	if (!secure) {
    295 		if (*filename != '/')
    296 			return (EACCESS);
    297 		/*
    298 		 * prevent tricksters from getting around the directory
    299 		 * restrictions
    300 		 */
    301 		for (cp = filename + 1; *cp; cp++)
    302 			if(*cp == '.' && strncmp(cp-1, "/../", 4) == 0)
    303 				return(EACCESS);
    304 		for (dirp = dirs; *dirp; dirp++)
    305 			if (strncmp(filename, *dirp, strlen(*dirp)) == 0)
    306 				break;
    307 		if (*dirp==0 && dirp!=dirs)
    308 			return (EACCESS);
    309 	}
    310 	if (stat(filename, &stbuf) < 0)
    311 		return (errno == ENOENT ? ENOTFOUND : EACCESS);
    312 	if (mode == RRQ) {
    313 		if ((stbuf.st_mode&(S_IREAD >> 6)) == 0)
    314 			return (EACCESS);
    315 	} else {
    316 		if ((stbuf.st_mode&(S_IWRITE >> 6)) == 0)
    317 			return (EACCESS);
    318 	}
    319 	fd = open(filename, mode == RRQ ? 0 : 1);
    320 	if (fd < 0)
    321 		return (errno + 100);
    322 	file = fdopen(fd, (mode == RRQ)? "r":"w");
    323 	if (file == NULL) {
    324 		return errno+100;
    325 	}
    326 	return (0);
    327 }
    328 
    329 int	timeout;
    330 jmp_buf	timeoutbuf;
    331 
    332 void
    333 timer()
    334 {
    335 
    336 	timeout += rexmtval;
    337 	if (timeout >= maxtimeout)
    338 		exit(1);
    339 	longjmp(timeoutbuf, 1);
    340 }
    341 
    342 /*
    343  * Send the requested file.
    344  */
    345 sendfile(pf)
    346 	struct formats *pf;
    347 {
    348 	struct tftphdr *dp, *r_init();
    349 	register struct tftphdr *ap;    /* ack packet */
    350 	register int block = 1, size, n;
    351 
    352 	signal(SIGALRM, timer);
    353 	dp = r_init();
    354 	ap = (struct tftphdr *)ackbuf;
    355 	do {
    356 		size = readit(file, &dp, pf->f_convert);
    357 		if (size < 0) {
    358 			nak(errno + 100);
    359 			goto abort;
    360 		}
    361 		dp->th_opcode = htons((u_short)DATA);
    362 		dp->th_block = htons((u_short)block);
    363 		timeout = 0;
    364 		(void) setjmp(timeoutbuf);
    365 
    366 send_data:
    367 		if (send(peer, dp, size + 4, 0) != size + 4) {
    368 			syslog(LOG_ERR, "tftpd: write: %m\n");
    369 			goto abort;
    370 		}
    371 		read_ahead(file, pf->f_convert);
    372 		for ( ; ; ) {
    373 			alarm(rexmtval);        /* read the ack */
    374 			n = recv(peer, ackbuf, sizeof (ackbuf), 0);
    375 			alarm(0);
    376 			if (n < 0) {
    377 				syslog(LOG_ERR, "tftpd: read: %m\n");
    378 				goto abort;
    379 			}
    380 			ap->th_opcode = ntohs((u_short)ap->th_opcode);
    381 			ap->th_block = ntohs((u_short)ap->th_block);
    382 
    383 			if (ap->th_opcode == ERROR)
    384 				goto abort;
    385 
    386 			if (ap->th_opcode == ACK) {
    387 				if (ap->th_block == block) {
    388 					break;
    389 				}
    390 				/* Re-synchronize with the other side */
    391 				(void) synchnet(peer);
    392 				if (ap->th_block == (block -1)) {
    393 					goto send_data;
    394 				}
    395 			}
    396 
    397 		}
    398 		block++;
    399 	} while (size == SEGSIZE);
    400 abort:
    401 	(void) fclose(file);
    402 }
    403 
    404 void
    405 justquit()
    406 {
    407 	exit(0);
    408 }
    409 
    410 
    411 /*
    412  * Receive a file.
    413  */
    414 recvfile(pf)
    415 	struct formats *pf;
    416 {
    417 	struct tftphdr *dp, *w_init();
    418 	register struct tftphdr *ap;    /* ack buffer */
    419 	register int block = 0, n, size;
    420 
    421 	signal(SIGALRM, timer);
    422 	dp = w_init();
    423 	ap = (struct tftphdr *)ackbuf;
    424 	do {
    425 		timeout = 0;
    426 		ap->th_opcode = htons((u_short)ACK);
    427 		ap->th_block = htons((u_short)block);
    428 		block++;
    429 		(void) setjmp(timeoutbuf);
    430 send_ack:
    431 		if (send(peer, ackbuf, 4, 0) != 4) {
    432 			syslog(LOG_ERR, "tftpd: write: %m\n");
    433 			goto abort;
    434 		}
    435 		write_behind(file, pf->f_convert);
    436 		for ( ; ; ) {
    437 			alarm(rexmtval);
    438 			n = recv(peer, dp, PKTSIZE, 0);
    439 			alarm(0);
    440 			if (n < 0) {            /* really? */
    441 				syslog(LOG_ERR, "tftpd: read: %m\n");
    442 				goto abort;
    443 			}
    444 			dp->th_opcode = ntohs((u_short)dp->th_opcode);
    445 			dp->th_block = ntohs((u_short)dp->th_block);
    446 			if (dp->th_opcode == ERROR)
    447 				goto abort;
    448 			if (dp->th_opcode == DATA) {
    449 				if (dp->th_block == block) {
    450 					break;   /* normal */
    451 				}
    452 				/* Re-synchronize with the other side */
    453 				(void) synchnet(peer);
    454 				if (dp->th_block == (block-1))
    455 					goto send_ack;          /* rexmit */
    456 			}
    457 		}
    458 		/*  size = write(file, dp->th_data, n - 4); */
    459 		size = writeit(file, &dp, n - 4, pf->f_convert);
    460 		if (size != (n-4)) {                    /* ahem */
    461 			if (size < 0) nak(errno + 100);
    462 			else nak(ENOSPACE);
    463 			goto abort;
    464 		}
    465 	} while (size == SEGSIZE);
    466 	write_behind(file, pf->f_convert);
    467 	(void) fclose(file);            /* close data file */
    468 
    469 	ap->th_opcode = htons((u_short)ACK);    /* send the "final" ack */
    470 	ap->th_block = htons((u_short)(block));
    471 	(void) send(peer, ackbuf, 4, 0);
    472 
    473 	signal(SIGALRM, justquit);      /* just quit on timeout */
    474 	alarm(rexmtval);
    475 	n = recv(peer, buf, sizeof (buf), 0); /* normally times out and quits */
    476 	alarm(0);
    477 	if (n >= 4 &&                   /* if read some data */
    478 	    dp->th_opcode == DATA &&    /* and got a data block */
    479 	    block == dp->th_block) {	/* then my last ack was lost */
    480 		(void) send(peer, ackbuf, 4, 0);     /* resend final ack */
    481 	}
    482 abort:
    483 	return;
    484 }
    485 
    486 struct errmsg {
    487 	int	e_code;
    488 	char	*e_msg;
    489 } errmsgs[] = {
    490 	{ EUNDEF,	"Undefined error code" },
    491 	{ ENOTFOUND,	"File not found" },
    492 	{ EACCESS,	"Access violation" },
    493 	{ ENOSPACE,	"Disk full or allocation exceeded" },
    494 	{ EBADOP,	"Illegal TFTP operation" },
    495 	{ EBADID,	"Unknown transfer ID" },
    496 	{ EEXISTS,	"File already exists" },
    497 	{ ENOUSER,	"No such user" },
    498 	{ -1,		0 }
    499 };
    500 
    501 /*
    502  * Send a nak packet (error message).
    503  * Error code passed in is one of the
    504  * standard TFTP codes, or a UNIX errno
    505  * offset by 100.
    506  */
    507 nak(error)
    508 	int error;
    509 {
    510 	register struct tftphdr *tp;
    511 	int length;
    512 	register struct errmsg *pe;
    513 
    514 	tp = (struct tftphdr *)buf;
    515 	tp->th_opcode = htons((u_short)ERROR);
    516 	tp->th_code = htons((u_short)error);
    517 	for (pe = errmsgs; pe->e_code >= 0; pe++)
    518 		if (pe->e_code == error)
    519 			break;
    520 	if (pe->e_code < 0) {
    521 		pe->e_msg = strerror(error - 100);
    522 		tp->th_code = EUNDEF;   /* set 'undef' errorcode */
    523 	}
    524 	strcpy(tp->th_msg, pe->e_msg);
    525 	length = strlen(pe->e_msg);
    526 	tp->th_msg[length] = '\0';
    527 	length += 5;
    528 	if (send(peer, buf, length, 0) != length)
    529 		syslog(LOG_ERR, "nak: %m\n");
    530 }
    531