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