tftpd.c revision 122916
138032Speter/*
2261363Sgshapiro * Copyright (c) 1983, 1993
390792Sgshapiro *	The Regents of the University of California.  All rights reserved.
490792Sgshapiro *
590792Sgshapiro * Redistribution and use in source and binary forms, with or without
690792Sgshapiro * modification, are permitted provided that the following conditions
790792Sgshapiro * are met:
890792Sgshapiro * 1. Redistributions of source code must retain the above copyright
990792Sgshapiro *    notice, this list of conditions and the following disclaimer.
1090792Sgshapiro * 2. Redistributions in binary form must reproduce the above copyright
1190792Sgshapiro *    notice, this list of conditions and the following disclaimer in the
1238032Speter *    documentation and/or other materials provided with the distribution.
1390792Sgshapiro * 3. All advertising materials mentioning features or use of this software
1438032Speter *    must display the following acknowledgement:
1538032Speter *	This product includes software developed by the University of
1638032Speter *	California, Berkeley and its contributors.
1790792Sgshapiro * 4. Neither the name of the University nor the names of its contributors
1838032Speter *    may be used to endorse or promote products derived from this software
1938032Speter *    without specific prior written permission.
2038032Speter *
2138032Speter * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
2238032Speter * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
2338032Speter * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
2438032Speter * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
2564562Sgshapiro * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26266692Sgshapiro * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
2764562Sgshapiro * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
2864562Sgshapiro * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
2938032Speter * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
3064562Sgshapiro * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
3164562Sgshapiro * SUCH DAMAGE.
3238032Speter */
3364562Sgshapiro
3464562Sgshapiro#ifndef lint
3564562Sgshapirostatic const char copyright[] =
3690792Sgshapiro"@(#) Copyright (c) 1983, 1993\n\
3738032Speter	The Regents of the University of California.  All rights reserved.\n";
3890792Sgshapiro#endif /* not lint */
3990792Sgshapiro
4064562Sgshapiro#ifndef lint
4164562Sgshapiro#if 0
4264562Sgshapirostatic char sccsid[] = "@(#)tftpd.c	8.1 (Berkeley) 6/4/93";
4364562Sgshapiro#endif
4464562Sgshapirostatic const char rcsid[] =
4564562Sgshapiro  "$FreeBSD: head/libexec/tftpd/tftpd.c 122916 2003-11-20 13:36:31Z sobomax $";
4664562Sgshapiro#endif /* not lint */
4738032Speter
4838032Speter/*
4938032Speter * Trivial file transfer protocol server.
5038032Speter *
5138032Speter * This version includes many modifications by Jim Guyton
5238032Speter * <guyton@rand-unix>.
5338032Speter */
5490792Sgshapiro
5538032Speter#include <sys/param.h>
5638032Speter#include <sys/ioctl.h>
5738032Speter#include <sys/stat.h>
5838032Speter#include <sys/socket.h>
5938032Speter#include <sys/types.h>
6038032Speter
6138032Speter#include <netinet/in.h>
6238032Speter#include <arpa/tftp.h>
6338032Speter#include <arpa/inet.h>
6438032Speter
6538032Speter#include <ctype.h>
6638032Speter#include <errno.h>
6738032Speter#include <fcntl.h>
6838032Speter#include <libutil.h>
6938032Speter#include <netdb.h>
7038032Speter#include <pwd.h>
7190792Sgshapiro#include <setjmp.h>
7290792Sgshapiro#include <signal.h>
7390792Sgshapiro#include <stdio.h>
7490792Sgshapiro#include <stdlib.h>
7590792Sgshapiro#include <string.h>
7690792Sgshapiro#include <syslog.h>
7738032Speter#include <unistd.h>
7838032Speter
7938032Speter#include "tftpsubs.h"
8038032Speter
8138032Speter#define	TIMEOUT		5
8238032Speter#define	MAX_TIMEOUTS	5
8338032Speter
8438032Speterint	peer;
8538032Speterint	rexmtval = TIMEOUT;
8638032Speterint	max_rexmtval = 2*TIMEOUT;
8738032Speter
8838032Speter#define	PKTSIZE	SEGSIZE+4
8938032Speterchar	buf[PKTSIZE];
9038032Speterchar	ackbuf[PKTSIZE];
9138032Speterstruct	sockaddr_storage from;
9238032Speterint	fromlen;
9338032Speter
9490792Sgshapirovoid	tftp(struct tftphdr *, int);
9538032Speterstatic void unmappedaddr(struct sockaddr_in6 *);
9638032Speter
9738032Speter/*
9838032Speter * Null-terminated directory prefix list for absolute pathname requests and
9938032Speter * search list for relative pathname requests.
10038032Speter *
10138032Speter * MAXDIRS should be at least as large as the number of arguments that
10238032Speter * inetd allows (currently 20).
10338032Speter */
10438032Speter#define MAXDIRS	20
10538032Speterstatic struct dirlist {
10638032Speter	const char	*name;
10738032Speter	int	len;
10838032Speter} dirs[MAXDIRS+1];
10938032Speterstatic int	suppress_naks;
11038032Speterstatic int	logging;
11138032Speterstatic int	ipchroot;
11238032Speter
11338032Speterstatic const char *errtomsg(int);
11438032Speterstatic void  nak(int);
11538032Speterstatic void  oack(void);
11638032Speter
11738032Speterstatic void  timer(int);
11838032Speterstatic void  justquit(int);
11938032Speter
12038032Speterint
12138032Spetermain(int argc, char *argv[])
12238032Speter{
12390792Sgshapiro	struct tftphdr *tp;
12490792Sgshapiro	int n;
12590792Sgshapiro	int ch, on;
12690792Sgshapiro	struct sockaddr_storage me;
12790792Sgshapiro	int len;
12890792Sgshapiro	char *chroot_dir = NULL;
12938032Speter	struct passwd *nobody;
13038032Speter	const char *chuser = "nobody";
13138032Speter
13238032Speter	openlog("tftpd", LOG_PID | LOG_NDELAY, LOG_FTP);
13338032Speter	while ((ch = getopt(argc, argv, "cClns:u:")) != -1) {
13438032Speter		switch (ch) {
13538032Speter		case 'c':
13638032Speter			ipchroot = 1;
13738032Speter			break;
13838032Speter		case 'C':
13938032Speter			ipchroot = 2;
14090792Sgshapiro			break;
14138032Speter		case 'l':
14238032Speter			logging = 1;
14338032Speter			break;
14438032Speter		case 'n':
14538032Speter			suppress_naks = 1;
14638032Speter			break;
14738032Speter		case 's':
14838032Speter			chroot_dir = optarg;
14938032Speter			break;
15038032Speter		case 'u':
15138032Speter			chuser = optarg;
15238032Speter			break;
15338032Speter		default:
15438032Speter			syslog(LOG_WARNING, "ignoring unknown option -%c", ch);
15538032Speter		}
15638032Speter	}
15738032Speter	if (optind < argc) {
15838032Speter		struct dirlist *dirp;
15938032Speter
16038032Speter		/* Get list of directory prefixes. Skip relative pathnames. */
16138032Speter		for (dirp = dirs; optind < argc && dirp < &dirs[MAXDIRS];
16238032Speter		     optind++) {
16338032Speter			if (argv[optind][0] == '/') {
164				dirp->name = argv[optind];
165				dirp->len  = strlen(dirp->name);
166				dirp++;
167			}
168		}
169	}
170	else if (chroot_dir) {
171		dirs->name = "/";
172		dirs->len = 1;
173	}
174	if (ipchroot > 0 && chroot_dir == NULL) {
175		syslog(LOG_ERR, "-c requires -s");
176		exit(1);
177	}
178
179	on = 1;
180	if (ioctl(0, FIONBIO, &on) < 0) {
181		syslog(LOG_ERR, "ioctl(FIONBIO): %m");
182		exit(1);
183	}
184	fromlen = sizeof (from);
185	n = recvfrom(0, buf, sizeof (buf), 0,
186	    (struct sockaddr *)&from, &fromlen);
187	if (n < 0) {
188		syslog(LOG_ERR, "recvfrom: %m");
189		exit(1);
190	}
191	/*
192	 * Now that we have read the message out of the UDP
193	 * socket, we fork and exit.  Thus, inetd will go back
194	 * to listening to the tftp port, and the next request
195	 * to come in will start up a new instance of tftpd.
196	 *
197	 * We do this so that inetd can run tftpd in "wait" mode.
198	 * The problem with tftpd running in "nowait" mode is that
199	 * inetd may get one or more successful "selects" on the
200	 * tftp port before we do our receive, so more than one
201	 * instance of tftpd may be started up.  Worse, if tftpd
202	 * break before doing the above "recvfrom", inetd would
203	 * spawn endless instances, clogging the system.
204	 */
205	{
206		int pid;
207		int i, j;
208
209		for (i = 1; i < 20; i++) {
210		    pid = fork();
211		    if (pid < 0) {
212				sleep(i);
213				/*
214				 * flush out to most recently sent request.
215				 *
216				 * This may drop some request, but those
217				 * will be resent by the clients when
218				 * they timeout.  The positive effect of
219				 * this flush is to (try to) prevent more
220				 * than one tftpd being started up to service
221				 * a single request from a single client.
222				 */
223				j = sizeof from;
224				i = recvfrom(0, buf, sizeof (buf), 0,
225				    (struct sockaddr *)&from, &j);
226				if (i > 0) {
227					n = i;
228					fromlen = j;
229				}
230		    } else {
231				break;
232		    }
233		}
234		if (pid < 0) {
235			syslog(LOG_ERR, "fork: %m");
236			exit(1);
237		} else if (pid != 0) {
238			exit(0);
239		}
240	}
241
242	/*
243	 * Since we exit here, we should do that only after the above
244	 * recvfrom to keep inetd from constantly forking should there
245	 * be a problem.  See the above comment about system clogging.
246	 */
247	if (chroot_dir) {
248		if (ipchroot > 0) {
249			char *tempchroot;
250			struct stat sb;
251			int statret;
252			struct sockaddr_storage ss;
253			char hbuf[NI_MAXHOST];
254
255			memcpy(&ss, &from, from.ss_len);
256			unmappedaddr((struct sockaddr_in6 *)&ss);
257			getnameinfo((struct sockaddr *)&ss, ss.ss_len,
258				    hbuf, sizeof(hbuf), NULL, 0,
259				    NI_NUMERICHOST | NI_WITHSCOPEID);
260			asprintf(&tempchroot, "%s/%s", chroot_dir, hbuf);
261			if (ipchroot == 2)
262				statret = stat(tempchroot, &sb);
263			if (ipchroot == 1 ||
264			    (statret == 0 && (sb.st_mode & S_IFDIR)))
265				chroot_dir = tempchroot;
266		}
267		/* Must get this before chroot because /etc might go away */
268		if ((nobody = getpwnam(chuser)) == NULL) {
269			syslog(LOG_ERR, "%s: no such user", chuser);
270			exit(1);
271		}
272		if (chroot(chroot_dir)) {
273			syslog(LOG_ERR, "chroot: %s: %m", chroot_dir);
274			exit(1);
275		}
276		chdir( "/" );
277		setuid(nobody->pw_uid);
278		setgroups(1, &nobody->pw_gid);
279	}
280
281	len = sizeof(me);
282	if (getsockname(0, (struct sockaddr *)&me, &len) == 0) {
283		switch (me.ss_family) {
284		case AF_INET:
285			((struct sockaddr_in *)&me)->sin_port = 0;
286			break;
287		case AF_INET6:
288			((struct sockaddr_in6 *)&me)->sin6_port = 0;
289			break;
290		default:
291			/* unsupported */
292			break;
293		}
294	} else {
295		memset(&me, 0, sizeof(me));
296		me.ss_family = from.ss_family;
297		me.ss_len = from.ss_len;
298	}
299	alarm(0);
300	close(0);
301	close(1);
302	peer = socket(from.ss_family, SOCK_DGRAM, 0);
303	if (peer < 0) {
304		syslog(LOG_ERR, "socket: %m");
305		exit(1);
306	}
307	if (bind(peer, (struct sockaddr *)&me, me.ss_len) < 0) {
308		syslog(LOG_ERR, "bind: %m");
309		exit(1);
310	}
311	if (connect(peer, (struct sockaddr *)&from, from.ss_len) < 0) {
312		syslog(LOG_ERR, "connect: %m");
313		exit(1);
314	}
315	tp = (struct tftphdr *)buf;
316	tp->th_opcode = ntohs(tp->th_opcode);
317	if (tp->th_opcode == RRQ || tp->th_opcode == WRQ)
318		tftp(tp, n);
319	exit(1);
320}
321
322struct formats;
323int	validate_access(char **, int);
324void	xmitfile(struct formats *);
325void	recvfile(struct formats *);
326
327struct formats {
328	const char	*f_mode;
329	int	(*f_validate)(char **, int);
330	void	(*f_send)(struct formats *);
331	void	(*f_recv)(struct formats *);
332	int	f_convert;
333} formats[] = {
334	{ "netascii",	validate_access,	xmitfile,	recvfile, 1 },
335	{ "octet",	validate_access,	xmitfile,	recvfile, 0 },
336#ifdef notdef
337	{ "mail",	validate_user,		sendmail,	recvmail, 1 },
338#endif
339	{ 0,		NULL,			NULL,		NULL,	  0 }
340};
341
342struct options {
343	const char	*o_type;
344	char	*o_request;
345	int	o_reply;	/* turn into union if need be */
346} options[] = {
347	{ "tsize",	NULL, 0 },		/* OPT_TSIZE */
348	{ "timeout",	NULL, 0 },		/* OPT_TIMEOUT */
349	{ NULL,		NULL, 0 }
350};
351
352enum opt_enum {
353	OPT_TSIZE = 0,
354	OPT_TIMEOUT,
355};
356
357/*
358 * Handle initial connection protocol.
359 */
360void
361tftp(struct tftphdr *tp, int size)
362{
363	char *cp;
364	int i, first = 1, has_options = 0, ecode;
365	struct formats *pf;
366	char *filename, *mode, *option, *ccp;
367	char fnbuf[MAXPATHLEN];
368
369	cp = tp->th_stuff;
370again:
371	while (cp < buf + size) {
372		if (*cp == '\0')
373			break;
374		cp++;
375	}
376	if (*cp != '\0') {
377		nak(EBADOP);
378		exit(1);
379	}
380	i = cp - tp->th_stuff;
381	if (i >= sizeof(fnbuf)) {
382		nak(EBADOP);
383		exit(1);
384	}
385	memcpy(fnbuf, tp->th_stuff, i);
386	fnbuf[i] = '\0';
387	filename = fnbuf;
388	if (first) {
389		mode = ++cp;
390		first = 0;
391		goto again;
392	}
393	for (cp = mode; *cp; cp++)
394		if (isupper(*cp))
395			*cp = tolower(*cp);
396	for (pf = formats; pf->f_mode; pf++)
397		if (strcmp(pf->f_mode, mode) == 0)
398			break;
399	if (pf->f_mode == 0) {
400		nak(EBADOP);
401		exit(1);
402	}
403	while (++cp < buf + size) {
404		for (i = 2, ccp = cp; i > 0; ccp++) {
405			if (ccp >= buf + size) {
406				/*
407				 * Don't reject the request, just stop trying
408				 * to parse the option and get on with it.
409				 * Some Apple OpenFirmware versions have
410				 * trailing garbage on the end of otherwise
411				 * valid requests.
412				 */
413				goto option_fail;
414			} else if (*ccp == '\0')
415				i--;
416		}
417		for (option = cp; *cp; cp++)
418			if (isupper(*cp))
419				*cp = tolower(*cp);
420		for (i = 0; options[i].o_type != NULL; i++)
421			if (strcmp(option, options[i].o_type) == 0) {
422				options[i].o_request = ++cp;
423				has_options = 1;
424			}
425		cp = ccp-1;
426	}
427
428option_fail:
429	if (options[OPT_TIMEOUT].o_request) {
430		int to = atoi(options[OPT_TIMEOUT].o_request);
431		if (to < 1 || to > 255) {
432			nak(EBADOP);
433			exit(1);
434		}
435		else if (to <= max_rexmtval)
436			options[OPT_TIMEOUT].o_reply = rexmtval = to;
437		else
438			options[OPT_TIMEOUT].o_request = NULL;
439	}
440
441	ecode = (*pf->f_validate)(&filename, tp->th_opcode);
442	if (has_options)
443		oack();
444	if (logging) {
445		char hbuf[NI_MAXHOST];
446
447		getnameinfo((struct sockaddr *)&from, from.ss_len,
448			    hbuf, sizeof(hbuf), NULL, 0,
449			    NI_WITHSCOPEID);
450		syslog(LOG_INFO, "%s: %s request for %s: %s", hbuf,
451			tp->th_opcode == WRQ ? "write" : "read",
452			filename, errtomsg(ecode));
453	}
454	if (ecode) {
455		/*
456		 * Avoid storms of naks to a RRQ broadcast for a relative
457		 * bootfile pathname from a diskless Sun.
458		 */
459		if (suppress_naks && *filename != '/' && ecode == ENOTFOUND)
460			exit(0);
461		nak(ecode);
462		exit(1);
463	}
464	if (tp->th_opcode == WRQ)
465		(*pf->f_recv)(pf);
466	else
467		(*pf->f_send)(pf);
468	exit(0);
469}
470
471
472FILE *file;
473
474/*
475 * Validate file access.  Since we
476 * have no uid or gid, for now require
477 * file to exist and be publicly
478 * readable/writable.
479 * If we were invoked with arguments
480 * from inetd then the file must also be
481 * in one of the given directory prefixes.
482 * Note also, full path name must be
483 * given as we have no login directory.
484 */
485int
486validate_access(char **filep, int mode)
487{
488	struct stat stbuf;
489	int	fd;
490	struct dirlist *dirp;
491	static char pathname[MAXPATHLEN];
492	char *filename = *filep;
493
494	/*
495	 * Prevent tricksters from getting around the directory restrictions
496	 */
497	if (strstr(filename, "/../"))
498		return (EACCESS);
499
500	if (*filename == '/') {
501		/*
502		 * Allow the request if it's in one of the approved locations.
503		 * Special case: check the null prefix ("/") by looking
504		 * for length = 1 and relying on the arg. processing that
505		 * it's a /.
506		 */
507		for (dirp = dirs; dirp->name != NULL; dirp++) {
508			if (dirp->len == 1 ||
509			    (!strncmp(filename, dirp->name, dirp->len) &&
510			     filename[dirp->len] == '/'))
511				    break;
512		}
513		/* If directory list is empty, allow access to any file */
514		if (dirp->name == NULL && dirp != dirs)
515			return (EACCESS);
516		if (stat(filename, &stbuf) < 0)
517			return (errno == ENOENT ? ENOTFOUND : EACCESS);
518		if ((stbuf.st_mode & S_IFMT) != S_IFREG)
519			return (ENOTFOUND);
520		if (mode == RRQ) {
521			if ((stbuf.st_mode & S_IROTH) == 0)
522				return (EACCESS);
523		} else {
524			if ((stbuf.st_mode & S_IWOTH) == 0)
525				return (EACCESS);
526		}
527	} else {
528		int err;
529
530		/*
531		 * Relative file name: search the approved locations for it.
532		 * Don't allow write requests that avoid directory
533		 * restrictions.
534		 */
535
536		if (!strncmp(filename, "../", 3))
537			return (EACCESS);
538
539		/*
540		 * If the file exists in one of the directories and isn't
541		 * readable, continue looking. However, change the error code
542		 * to give an indication that the file exists.
543		 */
544		err = ENOTFOUND;
545		for (dirp = dirs; dirp->name != NULL; dirp++) {
546			snprintf(pathname, sizeof(pathname), "%s/%s",
547				dirp->name, filename);
548			if (stat(pathname, &stbuf) == 0 &&
549			    (stbuf.st_mode & S_IFMT) == S_IFREG) {
550				if ((stbuf.st_mode & S_IROTH) != 0) {
551					break;
552				}
553				err = EACCESS;
554			}
555		}
556		if (dirp->name == NULL)
557			return (err);
558		*filep = filename = pathname;
559	}
560	if (options[OPT_TSIZE].o_request) {
561		if (mode == RRQ)
562			options[OPT_TSIZE].o_reply = stbuf.st_size;
563		else
564			/* XXX Allows writes of all sizes. */
565			options[OPT_TSIZE].o_reply =
566				atoi(options[OPT_TSIZE].o_request);
567	}
568	fd = open(filename, mode == RRQ ? O_RDONLY : O_WRONLY|O_TRUNC);
569	if (fd < 0)
570		return (errno + 100);
571	file = fdopen(fd, (mode == RRQ)? "r":"w");
572	if (file == NULL) {
573		return errno+100;
574	}
575	return (0);
576}
577
578int	timeouts;
579jmp_buf	timeoutbuf;
580
581void
582timer(int sig __unused)
583{
584	if (++timeouts > MAX_TIMEOUTS)
585		exit(1);
586	longjmp(timeoutbuf, 1);
587}
588
589/*
590 * Send the requested file.
591 */
592void
593xmitfile(struct formats *pf)
594{
595	struct tftphdr *dp;
596	struct tftphdr *ap;    /* ack packet */
597	int size, n;
598	volatile unsigned short block;
599
600	signal(SIGALRM, timer);
601	dp = r_init();
602	ap = (struct tftphdr *)ackbuf;
603	block = 1;
604	do {
605		size = readit(file, &dp, pf->f_convert);
606		if (size < 0) {
607			nak(errno + 100);
608			goto abort;
609		}
610		dp->th_opcode = htons((u_short)DATA);
611		dp->th_block = htons((u_short)block);
612		timeouts = 0;
613		(void)setjmp(timeoutbuf);
614
615send_data:
616		{
617			int i, t = 1;
618			for (i = 0; ; i++){
619				if (send(peer, dp, size + 4, 0) != size + 4) {
620					sleep(t);
621					t = (t < 32) ? t<< 1 : t;
622					if (i >= 12) {
623						syslog(LOG_ERR, "write: %m");
624						goto abort;
625					}
626				}
627				break;
628			}
629		}
630		read_ahead(file, pf->f_convert);
631		for ( ; ; ) {
632			alarm(rexmtval);        /* read the ack */
633			n = recv(peer, ackbuf, sizeof (ackbuf), 0);
634			alarm(0);
635			if (n < 0) {
636				syslog(LOG_ERR, "read: %m");
637				goto abort;
638			}
639			ap->th_opcode = ntohs((u_short)ap->th_opcode);
640			ap->th_block = ntohs((u_short)ap->th_block);
641
642			if (ap->th_opcode == ERROR)
643				goto abort;
644
645			if (ap->th_opcode == ACK) {
646				if (ap->th_block == block)
647					break;
648				/* Re-synchronize with the other side */
649				(void) synchnet(peer);
650				if (ap->th_block == (block -1))
651					goto send_data;
652			}
653
654		}
655		block++;
656	} while (size == SEGSIZE);
657abort:
658	(void) fclose(file);
659}
660
661void
662justquit(int sig __unused)
663{
664	exit(0);
665}
666
667
668/*
669 * Receive a file.
670 */
671void
672recvfile(struct formats *pf)
673{
674	struct tftphdr *dp;
675	struct tftphdr *ap;    /* ack buffer */
676	int n, size;
677	volatile unsigned short block;
678
679	signal(SIGALRM, timer);
680	dp = w_init();
681	ap = (struct tftphdr *)ackbuf;
682	block = 0;
683	do {
684		timeouts = 0;
685		ap->th_opcode = htons((u_short)ACK);
686		ap->th_block = htons((u_short)block);
687		block++;
688		(void) setjmp(timeoutbuf);
689send_ack:
690		if (send(peer, ackbuf, 4, 0) != 4) {
691			syslog(LOG_ERR, "write: %m");
692			goto abort;
693		}
694		write_behind(file, pf->f_convert);
695		for ( ; ; ) {
696			alarm(rexmtval);
697			n = recv(peer, dp, PKTSIZE, 0);
698			alarm(0);
699			if (n < 0) {            /* really? */
700				syslog(LOG_ERR, "read: %m");
701				goto abort;
702			}
703			dp->th_opcode = ntohs((u_short)dp->th_opcode);
704			dp->th_block = ntohs((u_short)dp->th_block);
705			if (dp->th_opcode == ERROR)
706				goto abort;
707			if (dp->th_opcode == DATA) {
708				if (dp->th_block == block) {
709					break;   /* normal */
710				}
711				/* Re-synchronize with the other side */
712				(void) synchnet(peer);
713				if (dp->th_block == (block-1))
714					goto send_ack;          /* rexmit */
715			}
716		}
717		/*  size = write(file, dp->th_data, n - 4); */
718		size = writeit(file, &dp, n - 4, pf->f_convert);
719		if (size != (n-4)) {                    /* ahem */
720			if (size < 0) nak(errno + 100);
721			else nak(ENOSPACE);
722			goto abort;
723		}
724	} while (size == SEGSIZE);
725	write_behind(file, pf->f_convert);
726	(void) fclose(file);            /* close data file */
727
728	ap->th_opcode = htons((u_short)ACK);    /* send the "final" ack */
729	ap->th_block = htons((u_short)(block));
730	(void) send(peer, ackbuf, 4, 0);
731
732	signal(SIGALRM, justquit);      /* just quit on timeout */
733	alarm(rexmtval);
734	n = recv(peer, buf, sizeof (buf), 0); /* normally times out and quits */
735	alarm(0);
736	if (n >= 4 &&                   /* if read some data */
737	    dp->th_opcode == DATA &&    /* and got a data block */
738	    block == dp->th_block) {	/* then my last ack was lost */
739		(void) send(peer, ackbuf, 4, 0);     /* resend final ack */
740	}
741abort:
742	return;
743}
744
745struct errmsg {
746	int	e_code;
747	const char	*e_msg;
748} errmsgs[] = {
749	{ EUNDEF,	"Undefined error code" },
750	{ ENOTFOUND,	"File not found" },
751	{ EACCESS,	"Access violation" },
752	{ ENOSPACE,	"Disk full or allocation exceeded" },
753	{ EBADOP,	"Illegal TFTP operation" },
754	{ EBADID,	"Unknown transfer ID" },
755	{ EEXISTS,	"File already exists" },
756	{ ENOUSER,	"No such user" },
757	{ EOPTNEG,	"Option negotiation" },
758	{ -1,		0 }
759};
760
761static const char *
762errtomsg(int error)
763{
764	static char ebuf[20];
765	struct errmsg *pe;
766	if (error == 0)
767		return "success";
768	for (pe = errmsgs; pe->e_code >= 0; pe++)
769		if (pe->e_code == error)
770			return pe->e_msg;
771	snprintf(ebuf, sizeof(buf), "error %d", error);
772	return ebuf;
773}
774
775/*
776 * Send a nak packet (error message).
777 * Error code passed in is one of the
778 * standard TFTP codes, or a UNIX errno
779 * offset by 100.
780 */
781static void
782nak(int error)
783{
784	struct tftphdr *tp;
785	int length;
786	struct errmsg *pe;
787
788	tp = (struct tftphdr *)buf;
789	tp->th_opcode = htons((u_short)ERROR);
790	tp->th_code = htons((u_short)error);
791	for (pe = errmsgs; pe->e_code >= 0; pe++)
792		if (pe->e_code == error)
793			break;
794	if (pe->e_code < 0) {
795		pe->e_msg = strerror(error - 100);
796		tp->th_code = EUNDEF;   /* set 'undef' errorcode */
797	}
798	strcpy(tp->th_msg, pe->e_msg);
799	length = strlen(pe->e_msg);
800	tp->th_msg[length] = '\0';
801	length += 5;
802	if (send(peer, buf, length, 0) != length)
803		syslog(LOG_ERR, "nak: %m");
804}
805
806/* translate IPv4 mapped IPv6 address to IPv4 address */
807static void
808unmappedaddr(struct sockaddr_in6 *sin6)
809{
810	struct sockaddr_in *sin4;
811	u_int32_t addr;
812	int port;
813
814	if (sin6->sin6_family != AF_INET6 ||
815	    !IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr))
816		return;
817	sin4 = (struct sockaddr_in *)sin6;
818	addr = *(u_int32_t *)&sin6->sin6_addr.s6_addr[12];
819	port = sin6->sin6_port;
820	memset(sin4, 0, sizeof(struct sockaddr_in));
821	sin4->sin_addr.s_addr = addr;
822	sin4->sin_port = port;
823	sin4->sin_family = AF_INET;
824	sin4->sin_len = sizeof(struct sockaddr_in);
825}
826
827/*
828 * Send an oack packet (option acknowledgement).
829 */
830static void
831oack(void)
832{
833	struct tftphdr *tp, *ap;
834	int size, i, n;
835	char *bp;
836
837	tp = (struct tftphdr *)buf;
838	bp = buf + 2;
839	size = sizeof(buf) - 2;
840	tp->th_opcode = htons((u_short)OACK);
841	for (i = 0; options[i].o_type != NULL; i++) {
842		if (options[i].o_request) {
843			n = snprintf(bp, size, "%s%c%d", options[i].o_type,
844				     0, options[i].o_reply);
845			bp += n+1;
846			size -= n+1;
847			if (size < 0) {
848				syslog(LOG_ERR, "oack: buffer overflow");
849				exit(1);
850			}
851		}
852	}
853	size = bp - buf;
854	ap = (struct tftphdr *)ackbuf;
855	signal(SIGALRM, timer);
856	timeouts = 0;
857
858	(void)setjmp(timeoutbuf);
859	if (send(peer, buf, size, 0) != size) {
860		syslog(LOG_INFO, "oack: %m");
861		exit(1);
862	}
863
864	for (;;) {
865		alarm(rexmtval);
866		n = recv(peer, ackbuf, sizeof (ackbuf), 0);
867		alarm(0);
868		if (n < 0) {
869			syslog(LOG_ERR, "recv: %m");
870			exit(1);
871		}
872		ap->th_opcode = ntohs((u_short)ap->th_opcode);
873		ap->th_block = ntohs((u_short)ap->th_block);
874		if (ap->th_opcode == ERROR)
875			exit(1);
876		if (ap->th_opcode == ACK && ap->th_block == 0)
877			break;
878	}
879}
880