Home | History | Annotate | Line # | Download | only in tftpd
tftpd.c revision 1.24
      1  1.24  christos /*	$NetBSD: tftpd.c,v 1.24 2001/10/09 18:46:18 christos Exp $	*/
      2   1.9       mrg 
      3   1.1       cgd /*
      4   1.9       mrg  * Copyright (c) 1983, 1993
      5   1.9       mrg  *	The Regents of the University of California.  All rights reserved.
      6   1.1       cgd  *
      7   1.1       cgd  * Redistribution and use in source and binary forms, with or without
      8   1.1       cgd  * modification, are permitted provided that the following conditions
      9   1.1       cgd  * are met:
     10   1.1       cgd  * 1. Redistributions of source code must retain the above copyright
     11   1.1       cgd  *    notice, this list of conditions and the following disclaimer.
     12   1.1       cgd  * 2. Redistributions in binary form must reproduce the above copyright
     13   1.1       cgd  *    notice, this list of conditions and the following disclaimer in the
     14   1.1       cgd  *    documentation and/or other materials provided with the distribution.
     15   1.1       cgd  * 3. All advertising materials mentioning features or use of this software
     16   1.1       cgd  *    must display the following acknowledgement:
     17   1.1       cgd  *	This product includes software developed by the University of
     18   1.1       cgd  *	California, Berkeley and its contributors.
     19   1.1       cgd  * 4. Neither the name of the University nor the names of its contributors
     20   1.1       cgd  *    may be used to endorse or promote products derived from this software
     21   1.1       cgd  *    without specific prior written permission.
     22   1.1       cgd  *
     23   1.1       cgd  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     24   1.1       cgd  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     25   1.1       cgd  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     26   1.1       cgd  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     27   1.1       cgd  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     28   1.1       cgd  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     29   1.1       cgd  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     30   1.1       cgd  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     31   1.1       cgd  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     32   1.1       cgd  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     33   1.1       cgd  * SUCH DAMAGE.
     34   1.1       cgd  */
     35   1.1       cgd 
     36   1.9       mrg #include <sys/cdefs.h>
     37   1.1       cgd #ifndef lint
     38   1.9       mrg __COPYRIGHT("@(#) Copyright (c) 1983, 1993\n\
     39   1.9       mrg 	The Regents of the University of California.  All rights reserved.\n");
     40   1.9       mrg #if 0
     41   1.9       mrg static char sccsid[] = "@(#)tftpd.c	8.1 (Berkeley) 6/4/93";
     42   1.9       mrg #else
     43  1.24  christos __RCSID("$NetBSD: tftpd.c,v 1.24 2001/10/09 18:46:18 christos Exp $");
     44   1.9       mrg #endif
     45   1.1       cgd #endif /* not lint */
     46   1.1       cgd 
     47   1.1       cgd /*
     48   1.1       cgd  * Trivial file transfer protocol server.
     49   1.1       cgd  *
     50   1.9       mrg  * This version includes many modifications by Jim Guyton
     51   1.9       mrg  * <guyton@rand-unix>.
     52   1.1       cgd  */
     53   1.1       cgd 
     54   1.9       mrg #include <sys/param.h>
     55   1.1       cgd #include <sys/ioctl.h>
     56   1.1       cgd #include <sys/stat.h>
     57   1.9       mrg #include <sys/socket.h>
     58   1.9       mrg 
     59   1.1       cgd #include <netinet/in.h>
     60   1.1       cgd #include <arpa/tftp.h>
     61   1.9       mrg #include <arpa/inet.h>
     62   1.9       mrg 
     63   1.9       mrg #include <ctype.h>
     64   1.9       mrg #include <errno.h>
     65   1.9       mrg #include <fcntl.h>
     66  1.22     lukem #include <fcntl.h>
     67  1.14     lukem #include <grp.h>
     68   1.1       cgd #include <netdb.h>
     69  1.14     lukem #include <pwd.h>
     70   1.1       cgd #include <setjmp.h>
     71   1.9       mrg #include <signal.h>
     72  1.22     lukem #include <signal.h>
     73   1.1       cgd #include <stdio.h>
     74   1.9       mrg #include <stdlib.h>
     75   1.1       cgd #include <string.h>
     76   1.9       mrg #include <syslog.h>
     77   1.9       mrg #include <unistd.h>
     78   1.9       mrg 
     79   1.9       mrg #include "tftpsubs.h"
     80   1.1       cgd 
     81  1.14     lukem #define	DEFAULTUSER	"nobody"
     82   1.7       jtc 
     83   1.1       cgd #define	TIMEOUT		5
     84   1.1       cgd 
     85   1.1       cgd int	peer;
     86   1.1       cgd int	rexmtval = TIMEOUT;
     87   1.1       cgd int	maxtimeout = 5*TIMEOUT;
     88   1.1       cgd 
     89   1.1       cgd #define	PKTSIZE	SEGSIZE+4
     90   1.1       cgd char	buf[PKTSIZE];
     91   1.1       cgd char	ackbuf[PKTSIZE];
     92  1.18    itojun struct	sockaddr_storage from;
     93   1.1       cgd int	fromlen;
     94  1.24  christos int	debug;
     95   1.1       cgd 
     96   1.9       mrg /*
     97   1.9       mrg  * Null-terminated directory prefix list for absolute pathname requests and
     98   1.9       mrg  * search list for relative pathname requests.
     99   1.9       mrg  *
    100   1.9       mrg  * MAXDIRS should be at least as large as the number of arguments that
    101   1.9       mrg  * inetd allows (currently 20).
    102   1.9       mrg  */
    103   1.9       mrg #define MAXDIRS	20
    104   1.9       mrg static struct dirlist {
    105   1.9       mrg 	char	*name;
    106   1.9       mrg 	int	len;
    107   1.9       mrg } dirs[MAXDIRS+1];
    108   1.9       mrg static int	suppress_naks;
    109   1.9       mrg static int	logging;
    110   1.9       mrg static int	secure;
    111   1.9       mrg static char	*securedir;
    112   1.9       mrg 
    113   1.9       mrg struct formats;
    114   1.9       mrg 
    115  1.22     lukem static const char *errtomsg(int);
    116  1.22     lukem static void	 nak(int);
    117  1.22     lukem static void	 tftp(struct tftphdr *, int);
    118  1.22     lukem static void	 usage(void);
    119  1.22     lukem static char	*verifyhost(struct sockaddr *);
    120  1.22     lukem void	justquit(int);
    121  1.22     lukem int	main(int, char **);
    122  1.22     lukem void	recvfile(struct formats *);
    123  1.22     lukem void	sendfile(struct formats *);
    124  1.22     lukem void	timer(int);
    125  1.24  christos static const char *opcode(int);
    126  1.22     lukem int	validate_access(char **, int);
    127   1.1       cgd 
    128   1.9       mrg struct formats {
    129  1.22     lukem 	const char	*f_mode;
    130  1.22     lukem 	int		(*f_validate)(char **, int);
    131  1.22     lukem 	void		(*f_send)(struct formats *);
    132  1.22     lukem 	void		(*f_recv)(struct formats *);
    133  1.22     lukem 	int		f_convert;
    134   1.9       mrg } formats[] = {
    135   1.9       mrg 	{ "netascii",	validate_access,	sendfile,	recvfile, 1 },
    136   1.9       mrg 	{ "octet",	validate_access,	sendfile,	recvfile, 0 },
    137   1.9       mrg 	{ 0 }
    138   1.9       mrg };
    139   1.4   mycroft 
    140   1.5       cgd static void
    141  1.22     lukem usage(void)
    142   1.5       cgd {
    143  1.22     lukem 
    144  1.14     lukem 	syslog(LOG_ERR,
    145  1.24  christos     "Usage: %s [-dln] [-u user] [-g group] [-s directory] [directory ...]",
    146  1.23       cgd 		    getprogname());
    147   1.5       cgd 	exit(1);
    148   1.5       cgd }
    149   1.5       cgd 
    150   1.9       mrg int
    151  1.22     lukem main(int argc, char *argv[])
    152   1.1       cgd {
    153  1.18    itojun 	struct sockaddr_storage me;
    154  1.22     lukem 	struct passwd	*pwent;
    155  1.22     lukem 	struct group	*grent;
    156  1.22     lukem 	struct tftphdr	*tp;
    157  1.22     lukem 	char		*tgtuser, *tgtgroup, *ep;
    158  1.22     lukem 	int	n, ch, on, fd;
    159  1.22     lukem 	int	len;
    160  1.22     lukem 	uid_t	curuid, tgtuid;
    161  1.22     lukem 	gid_t	curgid, tgtgid;
    162  1.22     lukem 	long	nid;
    163   1.1       cgd 
    164  1.22     lukem 	n = 0;
    165  1.22     lukem 	fd = 0;
    166  1.11     lukem 	openlog("tftpd", LOG_PID | LOG_NDELAY, LOG_DAEMON);
    167  1.14     lukem 	tgtuser = DEFAULTUSER;
    168  1.14     lukem 	tgtgroup = NULL;
    169  1.14     lukem 	curuid = getuid();
    170  1.14     lukem 	curgid = getgid();
    171   1.5       cgd 
    172  1.24  christos 	while ((ch = getopt(argc, argv, "dg:lns:u:")) != -1)
    173   1.9       mrg 		switch (ch) {
    174  1.24  christos 		case 'd':
    175  1.24  christos 			debug++;
    176  1.24  christos 			break;
    177  1.14     lukem 
    178  1.14     lukem 		case 'g':
    179  1.14     lukem 			tgtgroup = optarg;
    180  1.14     lukem 			break;
    181  1.14     lukem 
    182   1.9       mrg 		case 'l':
    183   1.9       mrg 			logging = 1;
    184   1.9       mrg 			break;
    185   1.9       mrg 
    186   1.9       mrg 		case 'n':
    187   1.9       mrg 			suppress_naks = 1;
    188   1.9       mrg 			break;
    189   1.9       mrg 
    190   1.5       cgd 		case 's':
    191   1.5       cgd 			secure = 1;
    192   1.9       mrg 			securedir = optarg;
    193   1.5       cgd 			break;
    194   1.5       cgd 
    195  1.14     lukem 		case 'u':
    196  1.14     lukem 			tgtuser = optarg;
    197  1.14     lukem 			break;
    198  1.14     lukem 
    199   1.5       cgd 		default:
    200   1.5       cgd 			usage();
    201   1.5       cgd 			break;
    202   1.5       cgd 		}
    203   1.5       cgd 
    204   1.9       mrg 	if (optind < argc) {
    205   1.9       mrg 		struct dirlist *dirp;
    206   1.9       mrg 
    207   1.9       mrg 		/* Get list of directory prefixes. Skip relative pathnames. */
    208   1.9       mrg 		for (dirp = dirs; optind < argc && dirp < &dirs[MAXDIRS];
    209   1.9       mrg 		     optind++) {
    210   1.9       mrg 			if (argv[optind][0] == '/') {
    211   1.9       mrg 				dirp->name = argv[optind];
    212   1.9       mrg 				dirp->len  = strlen(dirp->name);
    213   1.9       mrg 				dirp++;
    214   1.9       mrg 			}
    215   1.9       mrg 		}
    216   1.9       mrg 	}
    217   1.9       mrg 
    218  1.14     lukem 	if (*tgtuser == '\0' || (tgtgroup != NULL && *tgtgroup == '\0'))
    219  1.14     lukem 		usage();
    220  1.14     lukem 
    221  1.14     lukem 	nid = (strtol(tgtuser, &ep, 10));
    222  1.14     lukem 	if (*ep == '\0') {
    223  1.14     lukem 		if (nid > UID_MAX) {
    224  1.14     lukem 			syslog(LOG_ERR, "uid %ld is too large", nid);
    225  1.14     lukem 			exit(1);
    226  1.14     lukem 		}
    227  1.14     lukem 		pwent = getpwuid((uid_t)nid);
    228  1.14     lukem 	} else
    229  1.14     lukem 		pwent = getpwnam(tgtuser);
    230  1.14     lukem 	if (pwent == NULL) {
    231  1.14     lukem 		syslog(LOG_ERR, "unknown user `%s'", tgtuser);
    232  1.14     lukem 		exit(1);
    233  1.14     lukem 	}
    234  1.14     lukem 	tgtuid = pwent->pw_uid;
    235  1.14     lukem 	tgtgid = pwent->pw_gid;
    236  1.14     lukem 
    237  1.14     lukem 	if (tgtgroup != NULL) {
    238  1.14     lukem 		nid = (strtol(tgtgroup, &ep, 10));
    239  1.14     lukem 		if (*ep == '\0') {
    240  1.14     lukem 			if (nid > GID_MAX) {
    241  1.14     lukem 				syslog(LOG_ERR, "gid %ld is too large", nid);
    242  1.14     lukem 				exit(1);
    243  1.14     lukem 			}
    244  1.14     lukem 			grent = getgrgid((gid_t)nid);
    245  1.14     lukem 		} else
    246  1.14     lukem 			grent = getgrnam(tgtgroup);
    247  1.14     lukem 		if (grent != NULL)
    248  1.14     lukem 			tgtgid = grent->gr_gid;
    249  1.14     lukem 		else {
    250  1.14     lukem 			syslog(LOG_ERR, "unknown group `%s'", tgtgroup);
    251  1.14     lukem 			exit(1);
    252  1.14     lukem 		}
    253  1.14     lukem 	}
    254  1.14     lukem 
    255   1.9       mrg 	if (secure) {
    256   1.9       mrg 		if (chdir(securedir) < 0) {
    257   1.9       mrg 			syslog(LOG_ERR, "chdir %s: %m", securedir);
    258   1.9       mrg 			exit(1);
    259   1.4   mycroft 		}
    260   1.9       mrg 		if (chroot(".")) {
    261  1.14     lukem 			syslog(LOG_ERR, "chroot: %m");
    262   1.4   mycroft 			exit(1);
    263   1.4   mycroft 		}
    264   1.4   mycroft 	}
    265   1.5       cgd 
    266  1.22     lukem 	if (logging)
    267  1.22     lukem 		syslog(LOG_DEBUG, "running as user `%s' (%d), group `%s' (%d)",
    268  1.22     lukem 		    tgtuser, tgtuid, tgtgroup ? tgtgroup : "(unspecified)",
    269  1.22     lukem 		    tgtgid);
    270  1.14     lukem 	if (curgid != tgtgid) {
    271  1.14     lukem 		if (setgid(tgtgid)) {
    272  1.14     lukem 			syslog(LOG_ERR, "setgid to %d: %m", (int)tgtgid);
    273  1.14     lukem 			exit(1);
    274  1.14     lukem 		}
    275  1.14     lukem 		if (setgroups(0, NULL)) {
    276  1.14     lukem 			syslog(LOG_ERR, "setgroups: %m");
    277  1.14     lukem 			exit(1);
    278  1.14     lukem 		}
    279   1.8       mrg 	}
    280   1.8       mrg 
    281  1.14     lukem 	if (curuid != tgtuid) {
    282  1.14     lukem 		if (setuid(tgtuid)) {
    283  1.14     lukem 			syslog(LOG_ERR, "setuid to %d: %m", (int)tgtuid);
    284  1.14     lukem 			exit(1);
    285  1.14     lukem 		}
    286   1.4   mycroft 	}
    287   1.5       cgd 
    288   1.9       mrg 	on = 1;
    289   1.5       cgd 	if (ioctl(fd, FIONBIO, &on) < 0) {
    290  1.14     lukem 		syslog(LOG_ERR, "ioctl(FIONBIO): %m");
    291   1.1       cgd 		exit(1);
    292   1.1       cgd 	}
    293   1.1       cgd 	fromlen = sizeof (from);
    294   1.5       cgd 	n = recvfrom(fd, buf, sizeof (buf), 0,
    295   1.1       cgd 	    (struct sockaddr *)&from, &fromlen);
    296   1.1       cgd 	if (n < 0) {
    297  1.14     lukem 		syslog(LOG_ERR, "recvfrom: %m");
    298   1.1       cgd 		exit(1);
    299   1.1       cgd 	}
    300   1.1       cgd 	/*
    301   1.1       cgd 	 * Now that we have read the message out of the UDP
    302   1.1       cgd 	 * socket, we fork and exit.  Thus, inetd will go back
    303   1.1       cgd 	 * to listening to the tftp port, and the next request
    304   1.1       cgd 	 * to come in will start up a new instance of tftpd.
    305   1.1       cgd 	 *
    306   1.1       cgd 	 * We do this so that inetd can run tftpd in "wait" mode.
    307   1.1       cgd 	 * The problem with tftpd running in "nowait" mode is that
    308   1.1       cgd 	 * inetd may get one or more successful "selects" on the
    309   1.1       cgd 	 * tftp port before we do our receive, so more than one
    310   1.1       cgd 	 * instance of tftpd may be started up.  Worse, if tftpd
    311   1.1       cgd 	 * break before doing the above "recvfrom", inetd would
    312   1.1       cgd 	 * spawn endless instances, clogging the system.
    313   1.1       cgd 	 */
    314   1.1       cgd 	{
    315   1.1       cgd 		int pid;
    316   1.1       cgd 		int i, j;
    317   1.1       cgd 
    318   1.1       cgd 		for (i = 1; i < 20; i++) {
    319   1.1       cgd 		    pid = fork();
    320   1.1       cgd 		    if (pid < 0) {
    321   1.1       cgd 				sleep(i);
    322   1.1       cgd 				/*
    323   1.1       cgd 				 * flush out to most recently sent request.
    324   1.1       cgd 				 *
    325   1.1       cgd 				 * This may drop some request, but those
    326   1.1       cgd 				 * will be resent by the clients when
    327   1.1       cgd 				 * they timeout.  The positive effect of
    328   1.1       cgd 				 * this flush is to (try to) prevent more
    329   1.1       cgd 				 * than one tftpd being started up to service
    330   1.1       cgd 				 * a single request from a single client.
    331   1.1       cgd 				 */
    332   1.1       cgd 				j = sizeof from;
    333   1.5       cgd 				i = recvfrom(fd, buf, sizeof (buf), 0,
    334   1.1       cgd 				    (struct sockaddr *)&from, &j);
    335   1.1       cgd 				if (i > 0) {
    336   1.1       cgd 					n = i;
    337   1.1       cgd 					fromlen = j;
    338   1.1       cgd 				}
    339   1.1       cgd 		    } else {
    340   1.1       cgd 				break;
    341   1.1       cgd 		    }
    342   1.1       cgd 		}
    343   1.1       cgd 		if (pid < 0) {
    344  1.14     lukem 			syslog(LOG_ERR, "fork: %m");
    345   1.1       cgd 			exit(1);
    346   1.1       cgd 		} else if (pid != 0) {
    347   1.1       cgd 			exit(0);
    348   1.1       cgd 		}
    349   1.1       cgd 	}
    350  1.15  explorer 
    351  1.15  explorer 	/*
    352  1.15  explorer 	 * remember what address this was sent to, so we can respond on the
    353  1.15  explorer 	 * same interface
    354  1.15  explorer 	 */
    355  1.18    itojun 	len = sizeof(me);
    356  1.18    itojun 	if (getsockname(fd, (struct sockaddr *)&me, &len) == 0) {
    357  1.18    itojun 		switch (me.ss_family) {
    358  1.18    itojun 		case AF_INET:
    359  1.18    itojun 			((struct sockaddr_in *)&me)->sin_port = 0;
    360  1.18    itojun 			break;
    361  1.18    itojun 		case AF_INET6:
    362  1.18    itojun 			((struct sockaddr_in6 *)&me)->sin6_port = 0;
    363  1.18    itojun 			break;
    364  1.18    itojun 		default:
    365  1.18    itojun 			/* unsupported */
    366  1.18    itojun 			break;
    367  1.18    itojun 		}
    368  1.18    itojun 	} else {
    369  1.18    itojun 		memset(&me, 0, sizeof(me));
    370  1.18    itojun 		me.ss_family = from.ss_family;
    371  1.18    itojun 		me.ss_len = from.ss_len;
    372  1.15  explorer 	}
    373  1.15  explorer 
    374   1.1       cgd 	alarm(0);
    375   1.5       cgd 	close(fd);
    376   1.1       cgd 	close(1);
    377  1.18    itojun 	peer = socket(from.ss_family, SOCK_DGRAM, 0);
    378   1.1       cgd 	if (peer < 0) {
    379  1.14     lukem 		syslog(LOG_ERR, "socket: %m");
    380   1.1       cgd 		exit(1);
    381   1.1       cgd 	}
    382  1.18    itojun 	if (bind(peer, (struct sockaddr *)&me, me.ss_len) < 0) {
    383  1.14     lukem 		syslog(LOG_ERR, "bind: %m");
    384   1.1       cgd 		exit(1);
    385   1.1       cgd 	}
    386  1.18    itojun 	if (connect(peer, (struct sockaddr *)&from, from.ss_len) < 0) {
    387  1.14     lukem 		syslog(LOG_ERR, "connect: %m");
    388   1.1       cgd 		exit(1);
    389   1.1       cgd 	}
    390   1.1       cgd 	tp = (struct tftphdr *)buf;
    391   1.1       cgd 	tp->th_opcode = ntohs(tp->th_opcode);
    392   1.1       cgd 	if (tp->th_opcode == RRQ || tp->th_opcode == WRQ)
    393   1.1       cgd 		tftp(tp, n);
    394   1.1       cgd 	exit(1);
    395   1.1       cgd }
    396   1.1       cgd 
    397   1.1       cgd /*
    398   1.1       cgd  * Handle initial connection protocol.
    399   1.1       cgd  */
    400   1.9       mrg static void
    401  1.22     lukem tftp(struct tftphdr *tp, int size)
    402   1.1       cgd {
    403  1.14     lukem 	struct formats *pf;
    404  1.22     lukem 	char	*cp;
    405  1.22     lukem 	char	*filename, *mode;
    406  1.22     lukem 	int	 first, ecode;
    407  1.22     lukem 
    408  1.22     lukem 	first = 1;
    409  1.22     lukem 	mode = NULL;
    410   1.1       cgd 
    411   1.1       cgd 	filename = cp = tp->th_stuff;
    412   1.1       cgd again:
    413   1.1       cgd 	while (cp < buf + size) {
    414   1.1       cgd 		if (*cp == '\0')
    415   1.1       cgd 			break;
    416   1.1       cgd 		cp++;
    417   1.1       cgd 	}
    418   1.1       cgd 	if (*cp != '\0') {
    419   1.1       cgd 		nak(EBADOP);
    420   1.1       cgd 		exit(1);
    421   1.1       cgd 	}
    422   1.1       cgd 	if (first) {
    423   1.1       cgd 		mode = ++cp;
    424   1.1       cgd 		first = 0;
    425   1.1       cgd 		goto again;
    426   1.1       cgd 	}
    427   1.1       cgd 	for (cp = mode; *cp; cp++)
    428   1.1       cgd 		if (isupper(*cp))
    429   1.1       cgd 			*cp = tolower(*cp);
    430   1.1       cgd 	for (pf = formats; pf->f_mode; pf++)
    431   1.1       cgd 		if (strcmp(pf->f_mode, mode) == 0)
    432   1.1       cgd 			break;
    433   1.1       cgd 	if (pf->f_mode == 0) {
    434   1.1       cgd 		nak(EBADOP);
    435   1.1       cgd 		exit(1);
    436   1.1       cgd 	}
    437   1.9       mrg 	ecode = (*pf->f_validate)(&filename, tp->th_opcode);
    438   1.9       mrg 	if (logging) {
    439   1.9       mrg 		syslog(LOG_INFO, "%s: %s request for %s: %s",
    440  1.18    itojun 			verifyhost((struct sockaddr *)&from),
    441   1.9       mrg 			tp->th_opcode == WRQ ? "write" : "read",
    442   1.9       mrg 			filename, errtomsg(ecode));
    443   1.9       mrg 	}
    444   1.1       cgd 	if (ecode) {
    445   1.9       mrg 		/*
    446   1.9       mrg 		 * Avoid storms of naks to a RRQ broadcast for a relative
    447   1.9       mrg 		 * bootfile pathname from a diskless Sun.
    448   1.9       mrg 		 */
    449   1.9       mrg 		if (suppress_naks && *filename != '/' && ecode == ENOTFOUND)
    450   1.9       mrg 			exit(0);
    451   1.1       cgd 		nak(ecode);
    452   1.1       cgd 		exit(1);
    453   1.1       cgd 	}
    454   1.1       cgd 	if (tp->th_opcode == WRQ)
    455   1.1       cgd 		(*pf->f_recv)(pf);
    456   1.1       cgd 	else
    457   1.1       cgd 		(*pf->f_send)(pf);
    458   1.1       cgd 	exit(0);
    459   1.1       cgd }
    460   1.1       cgd 
    461   1.1       cgd 
    462   1.1       cgd FILE *file;
    463   1.1       cgd 
    464   1.1       cgd /*
    465   1.1       cgd  * Validate file access.  Since we
    466   1.1       cgd  * have no uid or gid, for now require
    467   1.1       cgd  * file to exist and be publicly
    468   1.1       cgd  * readable/writable.
    469   1.1       cgd  * If we were invoked with arguments
    470   1.1       cgd  * from inetd then the file must also be
    471   1.1       cgd  * in one of the given directory prefixes.
    472   1.1       cgd  */
    473   1.9       mrg int
    474  1.22     lukem validate_access(char **filep, int mode)
    475  1.22     lukem {
    476  1.22     lukem 	struct stat	 stbuf;
    477  1.22     lukem 	struct dirlist	*dirp;
    478  1.22     lukem 	static char	 pathname[MAXPATHLEN];
    479  1.22     lukem 	char		*filename;
    480  1.22     lukem 	int		 fd;
    481  1.22     lukem 
    482  1.22     lukem 	filename = *filep;
    483   1.1       cgd 
    484   1.9       mrg 	/*
    485   1.9       mrg 	 * Prevent tricksters from getting around the directory restrictions
    486   1.9       mrg 	 */
    487   1.9       mrg 	if (strstr(filename, "/../"))
    488   1.9       mrg 		return (EACCESS);
    489   1.9       mrg 
    490   1.9       mrg 	if (*filename == '/') {
    491   1.4   mycroft 		/*
    492   1.9       mrg 		 * Allow the request if it's in one of the approved locations.
    493   1.9       mrg 		 * Special case: check the null prefix ("/") by looking
    494   1.9       mrg 		 * for length = 1 and relying on the arg. processing that
    495   1.9       mrg 		 * it's a /.
    496   1.4   mycroft 		 */
    497   1.9       mrg 		for (dirp = dirs; dirp->name != NULL; dirp++) {
    498   1.9       mrg 			if (dirp->len == 1 ||
    499   1.9       mrg 			    (!strncmp(filename, dirp->name, dirp->len) &&
    500   1.9       mrg 			     filename[dirp->len] == '/'))
    501   1.9       mrg 				    break;
    502   1.9       mrg 		}
    503   1.9       mrg 		/* If directory list is empty, allow access to any file */
    504   1.9       mrg 		if (dirp->name == NULL && dirp != dirs)
    505   1.1       cgd 			return (EACCESS);
    506   1.9       mrg 		if (stat(filename, &stbuf) < 0)
    507   1.9       mrg 			return (errno == ENOENT ? ENOTFOUND : EACCESS);
    508  1.10   mycroft 		if (!S_ISREG(stbuf.st_mode))
    509   1.9       mrg 			return (ENOTFOUND);
    510   1.9       mrg 		if (mode == RRQ) {
    511   1.9       mrg 			if ((stbuf.st_mode & S_IROTH) == 0)
    512   1.9       mrg 				return (EACCESS);
    513   1.9       mrg 		} else {
    514   1.9       mrg 			if ((stbuf.st_mode & S_IWOTH) == 0)
    515   1.9       mrg 				return (EACCESS);
    516   1.9       mrg 		}
    517   1.1       cgd 	} else {
    518   1.9       mrg 		/*
    519   1.9       mrg 		 * Relative file name: search the approved locations for it.
    520   1.9       mrg 		 */
    521   1.9       mrg 
    522  1.16     aidan 		if (!strncmp(filename, "../", 3))
    523   1.1       cgd 			return (EACCESS);
    524   1.9       mrg 
    525   1.9       mrg 		/*
    526  1.16     aidan 		 * Find the first file that exists in any of the directories,
    527  1.16     aidan 		 * check access on it.
    528   1.9       mrg 		 */
    529   1.9       mrg 		if (dirs[0].name != NULL) {
    530   1.9       mrg 			for (dirp = dirs; dirp->name != NULL; dirp++) {
    531   1.9       mrg 				snprintf(pathname, sizeof pathname, "%s/%s",
    532   1.9       mrg 				    dirp->name, filename);
    533   1.9       mrg 				if (stat(pathname, &stbuf) == 0 &&
    534   1.9       mrg 				    (stbuf.st_mode & S_IFMT) == S_IFREG) {
    535  1.16     aidan 					break;
    536   1.9       mrg 				}
    537   1.9       mrg 			}
    538   1.9       mrg 			if (dirp->name == NULL)
    539  1.16     aidan 				return (ENOTFOUND);
    540  1.16     aidan 			if (mode == RRQ && !(stbuf.st_mode & S_IROTH))
    541  1.16     aidan 				return (EACCESS);
    542  1.16     aidan 			if (mode == WRQ && !(stbuf.st_mode & S_IWOTH))
    543  1.16     aidan 				return (EACCESS);
    544   1.9       mrg 			*filep = filename = pathname;
    545  1.16     aidan 		} else {
    546  1.16     aidan 			/*
    547  1.16     aidan 			 * If there's no directory list, take our cue from the
    548  1.16     aidan 			 * absolute file request check above (*filename == '/'),
    549  1.16     aidan 			 * and allow access to anything.
    550  1.16     aidan 			 */
    551  1.16     aidan 			if (stat(filename, &stbuf) < 0)
    552  1.16     aidan 				return (errno == ENOENT ? ENOTFOUND : EACCESS);
    553  1.16     aidan 			if (!S_ISREG(stbuf.st_mode))
    554  1.16     aidan 				return (ENOTFOUND);
    555  1.16     aidan 			if (mode == RRQ) {
    556  1.16     aidan 				if ((stbuf.st_mode & S_IROTH) == 0)
    557  1.16     aidan 					return (EACCESS);
    558  1.16     aidan 			} else {
    559  1.16     aidan 				if ((stbuf.st_mode & S_IWOTH) == 0)
    560  1.16     aidan 					return (EACCESS);
    561  1.16     aidan 			}
    562   1.9       mrg 			*filep = filename;
    563  1.16     aidan 		}
    564   1.1       cgd 	}
    565  1.17    carrel 	fd = open(filename, mode == RRQ ? O_RDONLY : O_WRONLY | O_TRUNC);
    566   1.1       cgd 	if (fd < 0)
    567   1.1       cgd 		return (errno + 100);
    568   1.1       cgd 	file = fdopen(fd, (mode == RRQ)? "r":"w");
    569   1.1       cgd 	if (file == NULL) {
    570  1.16     aidan 		close(fd);
    571  1.22     lukem 		return (errno + 100);
    572   1.1       cgd 	}
    573   1.1       cgd 	return (0);
    574   1.1       cgd }
    575   1.1       cgd 
    576   1.1       cgd int	timeout;
    577   1.1       cgd jmp_buf	timeoutbuf;
    578   1.1       cgd 
    579   1.1       cgd void
    580  1.22     lukem timer(int dummy)
    581   1.1       cgd {
    582   1.1       cgd 
    583   1.1       cgd 	timeout += rexmtval;
    584   1.1       cgd 	if (timeout >= maxtimeout)
    585   1.1       cgd 		exit(1);
    586   1.1       cgd 	longjmp(timeoutbuf, 1);
    587   1.1       cgd }
    588   1.1       cgd 
    589  1.24  christos static const char *
    590  1.24  christos opcode(int code)
    591  1.24  christos {
    592  1.24  christos 	static char buf[64];
    593  1.24  christos 
    594  1.24  christos 	switch (code) {
    595  1.24  christos 	case RRQ:
    596  1.24  christos 		return "RRQ";
    597  1.24  christos 	case WRQ:
    598  1.24  christos 		return "WRQ";
    599  1.24  christos 	case DATA:
    600  1.24  christos 		return "DATA";
    601  1.24  christos 	case ACK:
    602  1.24  christos 		return "ACK";
    603  1.24  christos 	case ERROR:
    604  1.24  christos 		return "ERROR";
    605  1.24  christos 	default:
    606  1.24  christos 		(void)snprintf(buf, sizeof(buf), "*code %d*", code);
    607  1.24  christos 		return buf;
    608  1.24  christos 	}
    609  1.24  christos }
    610  1.24  christos 
    611   1.1       cgd /*
    612   1.1       cgd  * Send the requested file.
    613   1.1       cgd  */
    614   1.9       mrg void
    615  1.22     lukem sendfile(struct formats *pf)
    616   1.1       cgd {
    617  1.19    dogcow 	volatile unsigned int block;
    618  1.22     lukem 	struct tftphdr	*dp;
    619  1.22     lukem 	struct tftphdr	*ap;    /* ack packet */
    620  1.22     lukem 	int		 size, n;
    621   1.1       cgd 
    622   1.1       cgd 	signal(SIGALRM, timer);
    623   1.1       cgd 	dp = r_init();
    624   1.1       cgd 	ap = (struct tftphdr *)ackbuf;
    625   1.9       mrg 	block = 1;
    626   1.1       cgd 	do {
    627   1.1       cgd 		size = readit(file, &dp, pf->f_convert);
    628   1.1       cgd 		if (size < 0) {
    629   1.1       cgd 			nak(errno + 100);
    630   1.1       cgd 			goto abort;
    631   1.1       cgd 		}
    632   1.1       cgd 		dp->th_opcode = htons((u_short)DATA);
    633   1.1       cgd 		dp->th_block = htons((u_short)block);
    634   1.1       cgd 		timeout = 0;
    635   1.9       mrg 		(void)setjmp(timeoutbuf);
    636   1.1       cgd 
    637   1.1       cgd send_data:
    638  1.24  christos 		if (debug)
    639  1.24  christos 			syslog(LOG_DEBUG, "Send DATA %u", block);
    640   1.1       cgd 		if (send(peer, dp, size + 4, 0) != size + 4) {
    641  1.14     lukem 			syslog(LOG_ERR, "tftpd: write: %m");
    642   1.1       cgd 			goto abort;
    643   1.1       cgd 		}
    644   1.1       cgd 		read_ahead(file, pf->f_convert);
    645   1.1       cgd 		for ( ; ; ) {
    646   1.1       cgd 			alarm(rexmtval);        /* read the ack */
    647   1.1       cgd 			n = recv(peer, ackbuf, sizeof (ackbuf), 0);
    648   1.1       cgd 			alarm(0);
    649   1.1       cgd 			if (n < 0) {
    650  1.14     lukem 				syslog(LOG_ERR, "tftpd: read: %m");
    651   1.1       cgd 				goto abort;
    652   1.1       cgd 			}
    653   1.1       cgd 			ap->th_opcode = ntohs((u_short)ap->th_opcode);
    654   1.1       cgd 			ap->th_block = ntohs((u_short)ap->th_block);
    655  1.24  christos 			switch (ap->th_opcode) {
    656  1.24  christos 			case ERROR:
    657   1.1       cgd 				goto abort;
    658   1.9       mrg 
    659  1.24  christos 			case ACK:
    660   1.9       mrg 				if (ap->th_block == block)
    661  1.24  christos 					goto done;
    662  1.24  christos 				if (debug)
    663  1.24  christos 					syslog(LOG_DEBUG, "Resync ACK %u != %u",
    664  1.24  christos 					    (unsigned int)ap->th_block, block);
    665   1.1       cgd 				/* Re-synchronize with the other side */
    666   1.1       cgd 				(void) synchnet(peer);
    667   1.9       mrg 				if (ap->th_block == (block -1))
    668   1.1       cgd 					goto send_data;
    669  1.24  christos 			default:
    670  1.24  christos 				syslog(LOG_INFO, "Received %s in sendfile\n",
    671  1.24  christos 				    opcode(dp->th_opcode));
    672   1.1       cgd 			}
    673   1.1       cgd 
    674   1.1       cgd 		}
    675  1.24  christos done:
    676  1.24  christos 		if (debug)
    677  1.24  christos 			syslog(LOG_DEBUG, "Received ACK for block %u", block);
    678   1.1       cgd 		block++;
    679   1.1       cgd 	} while (size == SEGSIZE);
    680   1.1       cgd abort:
    681   1.1       cgd 	(void) fclose(file);
    682   1.1       cgd }
    683   1.1       cgd 
    684   1.1       cgd void
    685  1.22     lukem justquit(int dummy)
    686   1.1       cgd {
    687  1.22     lukem 
    688   1.1       cgd 	exit(0);
    689   1.1       cgd }
    690   1.1       cgd 
    691   1.1       cgd /*
    692   1.1       cgd  * Receive a file.
    693   1.1       cgd  */
    694   1.9       mrg void
    695  1.22     lukem recvfile(struct formats *pf)
    696   1.1       cgd {
    697  1.19    dogcow 	volatile unsigned int block;
    698  1.22     lukem 	struct tftphdr	*dp;
    699  1.22     lukem 	struct tftphdr	*ap;    /* ack buffer */
    700  1.22     lukem 	int		 n, size;
    701   1.1       cgd 
    702   1.1       cgd 	signal(SIGALRM, timer);
    703   1.1       cgd 	dp = w_init();
    704   1.1       cgd 	ap = (struct tftphdr *)ackbuf;
    705   1.9       mrg 	block = 0;
    706   1.1       cgd 	do {
    707   1.1       cgd 		timeout = 0;
    708   1.1       cgd 		ap->th_opcode = htons((u_short)ACK);
    709   1.1       cgd 		ap->th_block = htons((u_short)block);
    710  1.24  christos 		if (debug)
    711  1.24  christos 			syslog(LOG_DEBUG, "Sending ACK for block %u\n", block);
    712   1.1       cgd 		block++;
    713   1.1       cgd 		(void) setjmp(timeoutbuf);
    714   1.1       cgd send_ack:
    715   1.1       cgd 		if (send(peer, ackbuf, 4, 0) != 4) {
    716  1.14     lukem 			syslog(LOG_ERR, "tftpd: write: %m");
    717   1.1       cgd 			goto abort;
    718   1.1       cgd 		}
    719   1.1       cgd 		write_behind(file, pf->f_convert);
    720   1.1       cgd 		for ( ; ; ) {
    721   1.1       cgd 			alarm(rexmtval);
    722   1.1       cgd 			n = recv(peer, dp, PKTSIZE, 0);
    723   1.1       cgd 			alarm(0);
    724   1.1       cgd 			if (n < 0) {            /* really? */
    725  1.14     lukem 				syslog(LOG_ERR, "tftpd: read: %m");
    726   1.1       cgd 				goto abort;
    727   1.1       cgd 			}
    728   1.1       cgd 			dp->th_opcode = ntohs((u_short)dp->th_opcode);
    729   1.1       cgd 			dp->th_block = ntohs((u_short)dp->th_block);
    730  1.24  christos 			if (debug)
    731  1.24  christos 				syslog(LOG_DEBUG, "Received %s for block %u",
    732  1.24  christos 				    opcode(dp->th_opcode),
    733  1.24  christos 				    (unsigned int)dp->th_block);
    734  1.24  christos 
    735  1.24  christos 			switch (dp->th_opcode) {
    736  1.24  christos 			case ERROR:
    737   1.1       cgd 				goto abort;
    738  1.24  christos 			case DATA:
    739  1.24  christos 				if (dp->th_block == block)
    740  1.24  christos 					goto done;   /* normal */
    741  1.24  christos 				if (debug)
    742  1.24  christos 					syslog(LOG_DEBUG, "Resync %u != %u",
    743  1.24  christos 					    (unsigned int)dp->th_block, block);
    744   1.1       cgd 				/* Re-synchronize with the other side */
    745   1.1       cgd 				(void) synchnet(peer);
    746   1.1       cgd 				if (dp->th_block == (block-1))
    747   1.1       cgd 					goto send_ack;          /* rexmit */
    748  1.24  christos 				break;
    749  1.24  christos 			default:
    750  1.24  christos 				syslog(LOG_INFO, "Received %s in recvfile\n",
    751  1.24  christos 				    opcode(dp->th_opcode));
    752  1.24  christos 				break;
    753   1.1       cgd 			}
    754   1.1       cgd 		}
    755  1.24  christos done:
    756  1.24  christos 		if (debug)
    757  1.24  christos 			syslog(LOG_DEBUG, "Got block %u", block);
    758   1.1       cgd 		/*  size = write(file, dp->th_data, n - 4); */
    759   1.1       cgd 		size = writeit(file, &dp, n - 4, pf->f_convert);
    760   1.1       cgd 		if (size != (n-4)) {                    /* ahem */
    761   1.1       cgd 			if (size < 0) nak(errno + 100);
    762   1.1       cgd 			else nak(ENOSPACE);
    763   1.1       cgd 			goto abort;
    764   1.1       cgd 		}
    765   1.1       cgd 	} while (size == SEGSIZE);
    766   1.1       cgd 	write_behind(file, pf->f_convert);
    767   1.1       cgd 	(void) fclose(file);            /* close data file */
    768   1.1       cgd 
    769   1.1       cgd 	ap->th_opcode = htons((u_short)ACK);    /* send the "final" ack */
    770   1.1       cgd 	ap->th_block = htons((u_short)(block));
    771  1.24  christos 	if (debug)
    772  1.24  christos 		syslog(LOG_DEBUG, "Send final ACK %u", block);
    773   1.1       cgd 	(void) send(peer, ackbuf, 4, 0);
    774   1.1       cgd 
    775   1.1       cgd 	signal(SIGALRM, justquit);      /* just quit on timeout */
    776   1.1       cgd 	alarm(rexmtval);
    777   1.1       cgd 	n = recv(peer, buf, sizeof (buf), 0); /* normally times out and quits */
    778   1.1       cgd 	alarm(0);
    779   1.1       cgd 	if (n >= 4 &&                   /* if read some data */
    780   1.1       cgd 	    dp->th_opcode == DATA &&    /* and got a data block */
    781   1.1       cgd 	    block == dp->th_block) {	/* then my last ack was lost */
    782   1.1       cgd 		(void) send(peer, ackbuf, 4, 0);     /* resend final ack */
    783   1.1       cgd 	}
    784   1.1       cgd abort:
    785   1.1       cgd 	return;
    786   1.1       cgd }
    787   1.1       cgd 
    788  1.13   mycroft const struct errmsg {
    789  1.22     lukem 	int		 e_code;
    790  1.22     lukem 	const char	*e_msg;
    791   1.1       cgd } errmsgs[] = {
    792   1.1       cgd 	{ EUNDEF,	"Undefined error code" },
    793   1.1       cgd 	{ ENOTFOUND,	"File not found" },
    794   1.1       cgd 	{ EACCESS,	"Access violation" },
    795   1.1       cgd 	{ ENOSPACE,	"Disk full or allocation exceeded" },
    796   1.1       cgd 	{ EBADOP,	"Illegal TFTP operation" },
    797   1.1       cgd 	{ EBADID,	"Unknown transfer ID" },
    798   1.1       cgd 	{ EEXISTS,	"File already exists" },
    799   1.1       cgd 	{ ENOUSER,	"No such user" },
    800   1.1       cgd 	{ -1,		0 }
    801   1.1       cgd };
    802   1.1       cgd 
    803  1.13   mycroft static const char *
    804  1.22     lukem errtomsg(int error)
    805   1.9       mrg {
    806  1.22     lukem 	static char ebuf[20];
    807  1.14     lukem 	const struct errmsg *pe;
    808   1.9       mrg 
    809   1.9       mrg 	if (error == 0)
    810  1.22     lukem 		return ("success");
    811   1.9       mrg 	for (pe = errmsgs; pe->e_code >= 0; pe++)
    812   1.9       mrg 		if (pe->e_code == error)
    813  1.22     lukem 			return (pe->e_msg);
    814  1.22     lukem 	snprintf(ebuf, sizeof(ebuf), "error %d", error);
    815  1.22     lukem 	return (ebuf);
    816   1.9       mrg }
    817   1.9       mrg 
    818   1.1       cgd /*
    819   1.1       cgd  * Send a nak packet (error message).
    820   1.1       cgd  * Error code passed in is one of the
    821   1.1       cgd  * standard TFTP codes, or a UNIX errno
    822   1.1       cgd  * offset by 100.
    823   1.1       cgd  */
    824   1.9       mrg static void
    825  1.22     lukem nak(int error)
    826   1.1       cgd {
    827  1.22     lukem 	const struct errmsg *pe;
    828  1.14     lukem 	struct tftphdr *tp;
    829  1.22     lukem 	int	length;
    830  1.22     lukem 	size_t	msglen;
    831   1.1       cgd 
    832   1.1       cgd 	tp = (struct tftphdr *)buf;
    833   1.1       cgd 	tp->th_opcode = htons((u_short)ERROR);
    834  1.21    itojun 	msglen = sizeof(buf) - (&tp->th_msg[0] - buf);
    835   1.1       cgd 	for (pe = errmsgs; pe->e_code >= 0; pe++)
    836   1.1       cgd 		if (pe->e_code == error)
    837   1.1       cgd 			break;
    838   1.1       cgd 	if (pe->e_code < 0) {
    839   1.1       cgd 		tp->th_code = EUNDEF;   /* set 'undef' errorcode */
    840  1.21    itojun 		strlcpy(tp->th_msg, strerror(error - 100), msglen);
    841  1.13   mycroft 	} else {
    842  1.13   mycroft 		tp->th_code = htons((u_short)error);
    843  1.21    itojun 		strlcpy(tp->th_msg, pe->e_msg, msglen);
    844   1.1       cgd 	}
    845  1.24  christos 	if (debug)
    846  1.24  christos 		syslog(LOG_DEBUG, "Send NACK %s", tp->th_msg);
    847  1.21    itojun 	length = strlen(tp->th_msg);
    848  1.21    itojun 	msglen = &tp->th_msg[length + 1] - buf;
    849  1.21    itojun 	if (send(peer, buf, msglen, 0) != msglen)
    850  1.14     lukem 		syslog(LOG_ERR, "nak: %m");
    851   1.9       mrg }
    852   1.9       mrg 
    853   1.9       mrg static char *
    854  1.22     lukem verifyhost(struct sockaddr *fromp)
    855   1.9       mrg {
    856  1.18    itojun 	static char hbuf[MAXHOSTNAMELEN];
    857   1.9       mrg 
    858  1.20    itojun 	if (getnameinfo(fromp, fromp->sa_len, hbuf, sizeof(hbuf), NULL, 0, 0))
    859  1.20    itojun 		strlcpy(hbuf, "?", sizeof(hbuf));
    860  1.22     lukem 	return (hbuf);
    861   1.1       cgd }
    862