2 * Copyright (c) 1983, 1993
3 * The Regents of the University of California. All rights reserved.
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
13 * 3. Neither the name of the University nor the names of its contributors
14 * may be used to endorse or promote products derived from this software
15 * without specific prior written permission.
17 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
18 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
21 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29 * @(#) Copyright (c) 1983, 1993 The Regents of the University of California. All rights reserved.
30 * @(#)tftpd.c 8.1 (Berkeley) 6/4/93
31 * $FreeBSD: src/libexec/tftpd/tftpd.c,v 1.15.2.5 2003/04/06 19:42:56 dwmalone Exp $
35 * Trivial file transfer protocol server.
37 * This version includes many modifications by Jim Guyton
41 #include <sys/param.h>
42 #include <sys/ioctl.h>
44 #include <sys/socket.h>
45 #include <sys/types.h>
47 #include <netinet/in.h>
48 #include <arpa/tftp.h>
49 #include <arpa/inet.h>
68 #define MAX_TIMEOUTS 5
71 static int rexmtval = TIMEOUT;
72 static int max_rexmtval = 2*TIMEOUT;
74 #define PKTSIZE SEGSIZE+4
75 static char buf[PKTSIZE];
76 static char ackbuf[PKTSIZE];
77 static struct sockaddr_storage from;
80 static void tftp(struct tftphdr *, int) __dead2;
81 static void unmappedaddr(struct sockaddr_in6 *);
84 * Null-terminated directory prefix list for absolute pathname requests and
85 * search list for relative pathname requests.
87 * MAXDIRS should be at least as large as the number of arguments that
88 * inetd allows (currently 20).
91 static struct dirlist {
95 static int suppress_naks;
99 static const char *errtomsg(int);
100 static void nak(int);
101 static void oack(void);
103 static void timer(int);
104 static void justquit(int);
107 main(int argc, char *argv[])
112 struct sockaddr_storage me;
114 char *chroot_dir = NULL;
115 struct passwd *nobody;
116 const char *chuser = "nobody";
118 openlog("tftpd", LOG_PID | LOG_NDELAY, LOG_FTP);
119 while ((ch = getopt(argc, argv, "cClns:u:")) != -1) {
140 syslog(LOG_WARNING, "ignoring unknown option -%c", ch);
144 struct dirlist *dirp;
146 /* Get list of directory prefixes. Skip relative pathnames. */
147 for (dirp = dirs; optind < argc && dirp < &dirs[MAXDIRS];
149 if (argv[optind][0] == '/') {
150 dirp->name = argv[optind];
151 dirp->len = strlen(dirp->name);
156 else if (chroot_dir) {
160 if (ipchroot && chroot_dir == NULL) {
161 syslog(LOG_ERR, "-c requires -s");
166 if (ioctl(0, FIONBIO, &on) < 0) {
167 syslog(LOG_ERR, "ioctl(FIONBIO): %m");
170 fromlen = sizeof (from);
171 n = recvfrom(0, buf, sizeof (buf), 0,
172 (struct sockaddr *)&from, &fromlen);
174 syslog(LOG_ERR, "recvfrom: %m");
178 * Now that we have read the message out of the UDP
179 * socket, we fork and exit. Thus, inetd will go back
180 * to listening to the tftp port, and the next request
181 * to come in will start up a new instance of tftpd.
183 * We do this so that inetd can run tftpd in "wait" mode.
184 * The problem with tftpd running in "nowait" mode is that
185 * inetd may get one or more successful "selects" on the
186 * tftp port before we do our receive, so more than one
187 * instance of tftpd may be started up. Worse, if tftpd
188 * break before doing the above "recvfrom", inetd would
189 * spawn endless instances, clogging the system.
195 for (i = 1; i < 20; i++) {
200 * flush out to most recently sent request.
202 * This may drop some request, but those
203 * will be resent by the clients when
204 * they timeout. The positive effect of
205 * this flush is to (try to) prevent more
206 * than one tftpd being started up to service
207 * a single request from a single client.
210 i = recvfrom(0, buf, sizeof (buf), 0,
211 (struct sockaddr *)&from, &j);
221 syslog(LOG_ERR, "fork: %m");
223 } else if (pid != 0) {
229 * Since we exit here, we should do that only after the above
230 * recvfrom to keep inetd from constantly forking should there
231 * be a problem. See the above comment about system clogging.
238 struct sockaddr_storage ss;
239 char hbuf[NI_MAXHOST];
241 memcpy(&ss, &from, from.ss_len);
242 unmappedaddr((struct sockaddr_in6 *)&ss);
243 getnameinfo((struct sockaddr *)&ss, ss.ss_len,
244 hbuf, sizeof(hbuf), NULL, 0,
245 NI_NUMERICHOST | NI_WITHSCOPEID);
246 asprintf(&tempchroot, "%s/%s", chroot_dir, hbuf);
247 statret = stat(tempchroot, &sb);
248 if ((sb.st_mode & S_IFDIR) &&
249 (statret == 0 || (statret == -1 && ipchroot == 1)))
250 chroot_dir = tempchroot;
252 /* Must get this before chroot because /etc might go away */
253 if ((nobody = getpwnam(chuser)) == NULL) {
254 syslog(LOG_ERR, "%s: no such user", chuser);
257 if (chroot(chroot_dir)) {
258 syslog(LOG_ERR, "chroot: %s: %m", chroot_dir);
262 setuid(nobody->pw_uid);
263 setgroups(1, &nobody->pw_gid);
267 if (getsockname(0, (struct sockaddr *)&me, &len) == 0) {
268 switch (me.ss_family) {
270 ((struct sockaddr_in *)&me)->sin_port = 0;
273 ((struct sockaddr_in6 *)&me)->sin6_port = 0;
280 memset(&me, 0, sizeof(me));
281 me.ss_family = from.ss_family;
282 me.ss_len = from.ss_len;
287 peer = socket(from.ss_family, SOCK_DGRAM, 0);
289 syslog(LOG_ERR, "socket: %m");
292 if (bind(peer, (struct sockaddr *)&me, me.ss_len) < 0) {
293 syslog(LOG_ERR, "bind: %m");
296 if (connect(peer, (struct sockaddr *)&from, from.ss_len) < 0) {
297 syslog(LOG_ERR, "connect: %m");
300 tp = (struct tftphdr *)buf;
301 tp->th_opcode = ntohs(tp->th_opcode);
302 if (tp->th_opcode == RRQ || tp->th_opcode == WRQ)
308 static int validate_access(char **, int);
309 static void xmitfile(struct formats *);
310 static void recvfile(struct formats *);
312 static struct formats {
314 int (*f_validate)(char **, int);
315 void (*f_send)(struct formats *);
316 void (*f_recv)(struct formats *);
319 { "netascii", validate_access, xmitfile, recvfile, 1 },
320 { "octet", validate_access, xmitfile, recvfile, 0 },
322 { "mail", validate_user, sendmail, recvmail, 1 },
324 { 0, NULL, NULL, NULL, 0 }
327 static struct options {
330 int o_reply; /* turn into union if need be */
332 { "tsize", NULL, 0 }, /* OPT_TSIZE */
333 { "timeout", NULL, 0 }, /* OPT_TIMEOUT */
343 * Handle initial connection protocol.
346 tftp(struct tftphdr *tp, int size)
350 int first = 1, has_options = 0, ecode;
352 char *filename, *mode = NULL, *option, *ccp;
353 char fnbuf[MAXPATHLEN];
357 while (cp < buf + size) {
366 i = cp - tp->th_stuff;
367 if (i >= sizeof(fnbuf)) {
371 memcpy(fnbuf, tp->th_stuff, i);
379 for (cp = mode; *cp; cp++)
382 for (pf = formats; pf->f_mode; pf++)
383 if (strcmp(pf->f_mode, mode) == 0)
385 if (pf->f_mode == NULL) {
389 while (++cp < buf + size) {
390 for (i = 2, ccp = cp; i > 0; ccp++) {
391 if (ccp >= buf + size) {
393 * Don't reject the request, just stop trying
394 * to parse the option and get on with it.
395 * Some Apple OpenFirmware versions have
396 * trailing garbage on the end of otherwise
400 } else if (*ccp == '\0')
403 for (option = cp; *cp; cp++)
406 for (i = 0; options[i].o_type != NULL; i++)
407 if (strcmp(option, options[i].o_type) == 0) {
408 options[i].o_request = ++cp;
415 if (options[OPT_TIMEOUT].o_request) {
416 int to = atoi(options[OPT_TIMEOUT].o_request);
417 if (to < 1 || to > 255) {
421 else if (to <= max_rexmtval)
422 options[OPT_TIMEOUT].o_reply = rexmtval = to;
424 options[OPT_TIMEOUT].o_request = NULL;
427 ecode = (*pf->f_validate)(&filename, tp->th_opcode);
431 char hbuf[NI_MAXHOST];
433 getnameinfo((struct sockaddr *)&from, from.ss_len,
434 hbuf, sizeof(hbuf), NULL, 0,
436 syslog(LOG_INFO, "%s: %s request for %s: %s", hbuf,
437 tp->th_opcode == WRQ ? "write" : "read",
438 filename, errtomsg(ecode));
442 * Avoid storms of naks to a RRQ broadcast for a relative
443 * bootfile pathname from a diskless Sun.
445 if (suppress_naks && *filename != '/' && ecode == ENOTFOUND)
450 if (tp->th_opcode == WRQ)
461 * Validate file access. Since we
462 * have no uid or gid, for now require
463 * file to exist and be publicly
465 * If we were invoked with arguments
466 * from inetd then the file must also be
467 * in one of the given directory prefixes.
468 * Note also, full path name must be
469 * given as we have no login directory.
472 validate_access(char **filep, int mode)
476 struct dirlist *dirp;
477 static char pathname[MAXPATHLEN];
478 char *filename = *filep;
481 * Prevent tricksters from getting around the directory restrictions
483 if (strstr(filename, "/../"))
486 if (*filename == '/') {
488 * Allow the request if it's in one of the approved locations.
489 * Special case: check the null prefix ("/") by looking
490 * for length = 1 and relying on the arg. processing that
493 for (dirp = dirs; dirp->name != NULL; dirp++) {
494 if (dirp->len == 1 ||
495 (!strncmp(filename, dirp->name, dirp->len) &&
496 filename[dirp->len] == '/'))
499 /* If directory list is empty, allow access to any file */
500 if (dirp->name == NULL && dirp != dirs)
502 if (stat(filename, &stbuf) < 0)
503 return (errno == ENOENT ? ENOTFOUND : EACCESS);
504 if ((stbuf.st_mode & S_IFMT) != S_IFREG)
507 if ((stbuf.st_mode & S_IROTH) == 0)
510 if ((stbuf.st_mode & S_IWOTH) == 0)
517 * Relative file name: search the approved locations for it.
518 * Don't allow write requests that avoid directory
522 if (!strncmp(filename, "../", 3))
526 * If the file exists in one of the directories and isn't
527 * readable, continue looking. However, change the error code
528 * to give an indication that the file exists.
531 for (dirp = dirs; dirp->name != NULL; dirp++) {
532 snprintf(pathname, sizeof(pathname), "%s/%s",
533 dirp->name, filename);
534 if (stat(pathname, &stbuf) == 0 &&
535 (stbuf.st_mode & S_IFMT) == S_IFREG) {
536 if ((stbuf.st_mode & S_IROTH) != 0) {
542 if (dirp->name == NULL)
544 *filep = filename = pathname;
546 if (options[OPT_TSIZE].o_request) {
548 options[OPT_TSIZE].o_reply = stbuf.st_size;
550 /* XXX Allows writes of all sizes. */
551 options[OPT_TSIZE].o_reply =
552 atoi(options[OPT_TSIZE].o_request);
554 fd = open(filename, mode == RRQ ? O_RDONLY : O_WRONLY|O_TRUNC);
556 return (errno + 100);
557 file = fdopen(fd, (mode == RRQ)? "r":"w");
565 static jmp_buf timeoutbuf;
568 timer(int sig __unused)
570 if (++timeouts > MAX_TIMEOUTS)
572 longjmp(timeoutbuf, 1);
576 * Send the requested file.
579 xmitfile(struct formats *pf)
582 struct tftphdr *ap; /* ack packet */
584 volatile unsigned short block;
586 signal(SIGALRM, timer);
588 ap = (struct tftphdr *)ackbuf;
591 size = readit(file, &dp, pf->f_convert);
596 dp->th_opcode = htons((u_short)DATA);
597 dp->th_block = htons((u_short)block);
599 (void)setjmp(timeoutbuf);
605 if (send(peer, dp, size + 4, 0) != size + 4) {
607 t = (t < 32) ? t<< 1 : t;
609 syslog(LOG_ERR, "write: %m");
616 read_ahead(file, pf->f_convert);
618 alarm(rexmtval); /* read the ack */
619 n = recv(peer, ackbuf, sizeof (ackbuf), 0);
622 syslog(LOG_ERR, "read: %m");
625 ap->th_opcode = ntohs((u_short)ap->th_opcode);
626 ap->th_block = ntohs((u_short)ap->th_block);
628 if (ap->th_opcode == ERROR)
631 if (ap->th_opcode == ACK) {
632 if (ap->th_block == block)
634 /* Re-synchronize with the other side */
635 (void) synchnet(peer);
636 if (ap->th_block == (block -1))
642 } while (size == SEGSIZE);
648 justquit(int sig __unused)
658 recvfile(struct formats *pf)
661 struct tftphdr *ap; /* ack buffer */
663 volatile unsigned short block;
665 signal(SIGALRM, timer);
667 ap = (struct tftphdr *)ackbuf;
671 ap->th_opcode = htons((u_short)ACK);
672 ap->th_block = htons((u_short)block);
674 (void) setjmp(timeoutbuf);
676 if (send(peer, ackbuf, 4, 0) != 4) {
677 syslog(LOG_ERR, "write: %m");
680 write_behind(file, pf->f_convert);
683 n = recv(peer, dp, PKTSIZE, 0);
685 if (n < 0) { /* really? */
686 syslog(LOG_ERR, "read: %m");
689 dp->th_opcode = ntohs((u_short)dp->th_opcode);
690 dp->th_block = ntohs((u_short)dp->th_block);
691 if (dp->th_opcode == ERROR)
693 if (dp->th_opcode == DATA) {
694 if (dp->th_block == block) {
697 /* Re-synchronize with the other side */
698 (void) synchnet(peer);
699 if (dp->th_block == (block-1))
700 goto send_ack; /* rexmit */
703 /* size = write(file, dp->th_data, n - 4); */
704 size = writeit(file, &dp, n - 4, pf->f_convert);
705 if (size != (n-4)) { /* ahem */
706 if (size < 0) nak(errno + 100);
710 } while (size == SEGSIZE);
711 write_behind(file, pf->f_convert);
712 (void) fclose(file); /* close data file */
714 ap->th_opcode = htons((u_short)ACK); /* send the "final" ack */
715 ap->th_block = htons((u_short)(block));
716 (void) send(peer, ackbuf, 4, 0);
718 signal(SIGALRM, justquit); /* just quit on timeout */
720 n = recv(peer, buf, sizeof (buf), 0); /* normally times out and quits */
722 if (n >= 4 && /* if read some data */
723 dp->th_opcode == DATA && /* and got a data block */
724 block == dp->th_block) { /* then my last ack was lost */
725 (void) send(peer, ackbuf, 4, 0); /* resend final ack */
731 static struct errmsg {
735 { EUNDEF, "Undefined error code" },
736 { ENOTFOUND, "File not found" },
737 { EACCESS, "Access violation" },
738 { ENOSPACE, "Disk full or allocation exceeded" },
739 { EBADOP, "Illegal TFTP operation" },
740 { EBADID, "Unknown transfer ID" },
741 { EEXISTS, "File already exists" },
742 { ENOUSER, "No such user" },
743 { EOPTNEG, "Option negotiation" },
750 static char ebuf[20];
754 for (pe = errmsgs; pe->e_code >= 0; pe++)
755 if (pe->e_code == error)
757 snprintf(ebuf, sizeof(buf), "error %d", error);
762 * Send a nak packet (error message).
763 * Error code passed in is one of the
764 * standard TFTP codes, or a UNIX errno
774 tp = (struct tftphdr *)buf;
775 tp->th_opcode = htons((u_short)ERROR);
776 tp->th_code = htons((u_short)error);
777 for (pe = errmsgs; pe->e_code >= 0; pe++)
778 if (pe->e_code == error)
780 if (pe->e_code < 0) {
781 pe->e_msg = strerror(error - 100);
782 tp->th_code = EUNDEF; /* set 'undef' errorcode */
784 strcpy(tp->th_msg, pe->e_msg);
785 length = strlen(pe->e_msg);
786 tp->th_msg[length] = '\0';
788 if (send(peer, buf, length, 0) != length)
789 syslog(LOG_ERR, "nak: %m");
792 /* translate IPv4 mapped IPv6 address to IPv4 address */
794 unmappedaddr(struct sockaddr_in6 *sin6)
796 struct sockaddr_in *sin4;
800 if (sin6->sin6_family != AF_INET6 ||
801 !IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr))
803 sin4 = (struct sockaddr_in *)sin6;
804 addr = *(u_int32_t *)&sin6->sin6_addr.s6_addr[12];
805 port = sin6->sin6_port;
806 memset(sin4, 0, sizeof(struct sockaddr_in));
807 sin4->sin_addr.s_addr = addr;
808 sin4->sin_port = port;
809 sin4->sin_family = AF_INET;
810 sin4->sin_len = sizeof(struct sockaddr_in);
814 * Send an oack packet (option acknowledgement).
819 struct tftphdr *tp, *ap;
823 tp = (struct tftphdr *)buf;
825 size = sizeof(buf) - 2;
826 tp->th_opcode = htons((u_short)OACK);
827 for (i = 0; options[i].o_type != NULL; i++) {
828 if (options[i].o_request) {
829 n = snprintf(bp, size, "%s%c%d", options[i].o_type,
830 0, options[i].o_reply);
834 syslog(LOG_ERR, "oack: buffer overflow");
840 ap = (struct tftphdr *)ackbuf;
841 signal(SIGALRM, timer);
844 (void)setjmp(timeoutbuf);
845 if (send(peer, buf, size, 0) != size) {
846 syslog(LOG_INFO, "oack: %m");
852 n = recv(peer, ackbuf, sizeof (ackbuf), 0);
855 syslog(LOG_ERR, "recv: %m");
858 ap->th_opcode = ntohs((u_short)ap->th_opcode);
859 ap->th_block = ntohs((u_short)ap->th_block);
860 if (ap->th_opcode == ERROR)
862 if (ap->th_opcode == ACK && ap->th_block == 0)