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. All advertising materials mentioning features or use of this software
14 * must display the following acknowledgement:
15 * This product includes software developed by the University of
16 * California, Berkeley and its contributors.
17 * 4. Neither the name of the University nor the names of its contributors
18 * may be used to endorse or promote products derived from this software
19 * without specific prior written permission.
21 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
35 static const char copyright[] =
36 "@(#) Copyright (c) 1983, 1993\n\
37 The Regents of the University of California. All rights reserved.\n";
42 static char sccsid[] = "@(#)tftpd.c 8.1 (Berkeley) 6/4/93";
44 static const char rcsid[] =
49 * Trivial file transfer protocol server.
51 * This version includes many modifications by Jim Guyton
55 #include <sys/param.h>
56 #include <sys/ioctl.h>
58 #include <sys/socket.h>
59 #include <sys/types.h>
62 #include <netinet/in.h>
63 #include <arpa/tftp.h>
64 #include <arpa/inet.h>
83 #define MAX_TIMEOUTS 5
86 int rexmtval = TIMEOUT;
87 int max_rexmtval = 2*TIMEOUT;
89 #define PKTSIZE SEGSIZE+4
92 struct sockaddr_storage from;
94 void tftp(struct tftphdr *, int);
95 static void unmappedaddr(struct sockaddr_in6 *);
98 * Null-terminated directory prefix list for absolute pathname requests and
99 * search list for relative pathname requests.
101 * MAXDIRS should be at least as large as the number of arguments that
102 * inetd allows (currently 20).
105 static struct dirlist {
109 static int suppress_naks;
112 static int create_new = 0;
113 static mode_t mask = S_IWGRP|S_IWOTH;
115 static const char *errtomsg(int);
116 static void nak(int);
117 static void oack(void);
119 static void timer(int);
120 static void justquit(int);
123 main(int argc, char *argv[])
126 socklen_t fromlen, len;
129 struct sockaddr_storage me;
130 char *chroot_dir = NULL;
131 struct passwd *nobody;
132 const char *chuser = "nobody";
134 tzset(); /* syslog in localtime */
136 openlog("tftpd", LOG_PID | LOG_NDELAY, LOG_FTP);
137 while ((ch = getopt(argc, argv, "cClns:u:U:w")) != -1) {
158 mask = strtol(optarg, NULL, 0);
164 syslog(LOG_WARNING, "ignoring unknown option -%c", ch);
168 struct dirlist *dirp;
170 /* Get list of directory prefixes. Skip relative pathnames. */
171 for (dirp = dirs; optind < argc && dirp < &dirs[MAXDIRS];
173 if (argv[optind][0] == '/') {
174 dirp->name = argv[optind];
175 dirp->len = strlen(dirp->name);
180 else if (chroot_dir) {
184 if (ipchroot > 0 && chroot_dir == NULL) {
185 syslog(LOG_ERR, "-c requires -s");
192 if (ioctl(0, FIONBIO, &on) < 0) {
193 syslog(LOG_ERR, "ioctl(FIONBIO): %m");
196 fromlen = sizeof (from);
197 n = recvfrom(0, buf, sizeof (buf), 0,
198 (struct sockaddr *)&from, &fromlen);
200 syslog(LOG_ERR, "recvfrom: %m");
204 * Now that we have read the message out of the UDP
205 * socket, we fork and exit. Thus, inetd will go back
206 * to listening to the tftp port, and the next request
207 * to come in will start up a new instance of tftpd.
209 * We do this so that inetd can run tftpd in "wait" mode.
210 * The problem with tftpd running in "nowait" mode is that
211 * inetd may get one or more successful "selects" on the
212 * tftp port before we do our receive, so more than one
213 * instance of tftpd may be started up. Worse, if tftpd
214 * break before doing the above "recvfrom", inetd would
215 * spawn endless instances, clogging the system.
220 for (i = 1; i < 20; i++) {
225 * flush out to most recently sent request.
227 * This may drop some request, but those
228 * will be resent by the clients when
229 * they timeout. The positive effect of
230 * this flush is to (try to) prevent more
231 * than one tftpd being started up to service
232 * a single request from a single client.
234 fromlen = sizeof from;
235 i = recvfrom(0, buf, sizeof (buf), 0,
236 (struct sockaddr *)&from, &fromlen);
245 syslog(LOG_ERR, "fork: %m");
247 } else if (pid != 0) {
253 * Since we exit here, we should do that only after the above
254 * recvfrom to keep inetd from constantly forking should there
255 * be a problem. See the above comment about system clogging.
262 struct sockaddr_storage ss;
263 char hbuf[NI_MAXHOST];
265 memcpy(&ss, &from, from.ss_len);
266 unmappedaddr((struct sockaddr_in6 *)&ss);
267 getnameinfo((struct sockaddr *)&ss, ss.ss_len,
268 hbuf, sizeof(hbuf), NULL, 0,
270 asprintf(&tempchroot, "%s/%s", chroot_dir, hbuf);
272 statret = stat(tempchroot, &sb);
274 (statret == 0 && (sb.st_mode & S_IFDIR)))
275 chroot_dir = tempchroot;
277 /* Must get this before chroot because /etc might go away */
278 if ((nobody = getpwnam(chuser)) == NULL) {
279 syslog(LOG_ERR, "%s: no such user", chuser);
282 if (chroot(chroot_dir)) {
283 syslog(LOG_ERR, "chroot: %s: %m", chroot_dir);
287 setgroups(1, &nobody->pw_gid);
288 setuid(nobody->pw_uid);
292 if (getsockname(0, (struct sockaddr *)&me, &len) == 0) {
293 switch (me.ss_family) {
295 ((struct sockaddr_in *)&me)->sin_port = 0;
298 ((struct sockaddr_in6 *)&me)->sin6_port = 0;
305 memset(&me, 0, sizeof(me));
306 me.ss_family = from.ss_family;
307 me.ss_len = from.ss_len;
312 peer = socket(from.ss_family, SOCK_DGRAM, 0);
314 syslog(LOG_ERR, "socket: %m");
317 if (bind(peer, (struct sockaddr *)&me, me.ss_len) < 0) {
318 syslog(LOG_ERR, "bind: %m");
321 if (connect(peer, (struct sockaddr *)&from, from.ss_len) < 0) {
322 syslog(LOG_ERR, "connect: %m");
325 tp = (struct tftphdr *)buf;
326 tp->th_opcode = ntohs(tp->th_opcode);
327 if (tp->th_opcode == RRQ || tp->th_opcode == WRQ)
333 reduce_path(char *fn)
337 /* Reduce all "/+./" to "/" (just in case we've got "/./../" later */
338 while ((slash = strstr(fn, "/./")) != NULL) {
339 for (ptr = slash; ptr > fn && ptr[-1] == '/'; ptr--)
346 /* Now reduce all "/something/+../" to "/" */
347 while ((slash = strstr(fn, "/../")) != NULL) {
350 for (ptr = slash; ptr > fn && ptr[-1] == '/'; ptr--)
352 for (ptr--; ptr >= fn; ptr--)
364 int validate_access(char **, int);
365 void xmitfile(struct formats *);
366 void recvfile(struct formats *);
370 int (*f_validate)(char **, int);
371 void (*f_send)(struct formats *);
372 void (*f_recv)(struct formats *);
375 { "netascii", validate_access, xmitfile, recvfile, 1 },
376 { "octet", validate_access, xmitfile, recvfile, 0 },
378 { "mail", validate_user, sendmail, recvmail, 1 },
380 { 0, NULL, NULL, NULL, 0 }
386 int o_reply; /* turn into union if need be */
388 { "tsize", NULL, 0 }, /* OPT_TSIZE */
389 { "timeout", NULL, 0 }, /* OPT_TIMEOUT */
399 * Handle initial connection protocol.
402 tftp(struct tftphdr *tp, int size)
405 int i, first = 1, has_options = 0, ecode;
407 char *filename, *mode, *option, *ccp;
408 char fnbuf[PATH_MAX];
412 while (cp < buf + size) {
421 i = cp - tp->th_stuff;
422 if (i >= sizeof(fnbuf)) {
426 memcpy(fnbuf, tp->th_stuff, i);
435 for (cp = mode; *cp; cp++)
438 for (pf = formats; pf->f_mode; pf++)
439 if (strcmp(pf->f_mode, mode) == 0)
441 if (pf->f_mode == 0) {
445 while (++cp < buf + size) {
446 for (i = 2, ccp = cp; i > 0; ccp++) {
447 if (ccp >= buf + size) {
449 * Don't reject the request, just stop trying
450 * to parse the option and get on with it.
451 * Some Apple Open Firmware versions have
452 * trailing garbage on the end of otherwise
456 } else if (*ccp == '\0')
459 for (option = cp; *cp; cp++)
462 for (i = 0; options[i].o_type != NULL; i++)
463 if (strcmp(option, options[i].o_type) == 0) {
464 options[i].o_request = ++cp;
471 if (options[OPT_TIMEOUT].o_request) {
472 int to = atoi(options[OPT_TIMEOUT].o_request);
473 if (to < 1 || to > 255) {
477 else if (to <= max_rexmtval)
478 options[OPT_TIMEOUT].o_reply = rexmtval = to;
480 options[OPT_TIMEOUT].o_request = NULL;
483 ecode = (*pf->f_validate)(&filename, tp->th_opcode);
484 if (has_options && ecode == 0)
487 char hbuf[NI_MAXHOST];
489 getnameinfo((struct sockaddr *)&from, from.ss_len,
490 hbuf, sizeof(hbuf), NULL, 0, 0);
491 syslog(LOG_INFO, "%s: %s request for %s: %s", hbuf,
492 tp->th_opcode == WRQ ? "write" : "read",
493 filename, errtomsg(ecode));
497 * Avoid storms of naks to a RRQ broadcast for a relative
498 * bootfile pathname from a diskless Sun.
500 if (suppress_naks && *filename != '/' && ecode == ENOTFOUND)
505 if (tp->th_opcode == WRQ)
516 * Validate file access. Since we
517 * have no uid or gid, for now require
518 * file to exist and be publicly
520 * If we were invoked with arguments
521 * from inetd then the file must also be
522 * in one of the given directory prefixes.
523 * Note also, full path name must be
524 * given as we have no login directory.
527 validate_access(char **filep, int mode)
531 struct dirlist *dirp;
532 static char pathname[MAXPATHLEN];
533 char *filename = *filep;
536 * Prevent tricksters from getting around the directory restrictions
538 if (strstr(filename, "/../"))
541 if (*filename == '/') {
543 * Allow the request if it's in one of the approved locations.
544 * Special case: check the null prefix ("/") by looking
545 * for length = 1 and relying on the arg. processing that
548 for (dirp = dirs; dirp->name != NULL; dirp++) {
549 if (dirp->len == 1 ||
550 (!strncmp(filename, dirp->name, dirp->len) &&
551 filename[dirp->len] == '/'))
554 /* If directory list is empty, allow access to any file */
555 if (dirp->name == NULL && dirp != dirs)
557 if (stat(filename, &stbuf) < 0)
558 return (errno == ENOENT ? ENOTFOUND : EACCESS);
559 if ((stbuf.st_mode & S_IFMT) != S_IFREG)
562 if ((stbuf.st_mode & S_IROTH) == 0)
565 if ((stbuf.st_mode & S_IWOTH) == 0)
572 * Relative file name: search the approved locations for it.
573 * Don't allow write requests that avoid directory
577 if (!strncmp(filename, "../", 3))
581 * If the file exists in one of the directories and isn't
582 * readable, continue looking. However, change the error code
583 * to give an indication that the file exists.
586 for (dirp = dirs; dirp->name != NULL; dirp++) {
587 snprintf(pathname, sizeof(pathname), "%s/%s",
588 dirp->name, filename);
589 if (stat(pathname, &stbuf) == 0 &&
590 (stbuf.st_mode & S_IFMT) == S_IFREG) {
591 if ((stbuf.st_mode & S_IROTH) != 0) {
597 if (dirp->name != NULL)
598 *filep = filename = pathname;
599 else if (mode == RRQ)
602 if (options[OPT_TSIZE].o_request) {
604 options[OPT_TSIZE].o_reply = stbuf.st_size;
606 /* XXX Allows writes of all sizes. */
607 options[OPT_TSIZE].o_reply =
608 atoi(options[OPT_TSIZE].o_request);
611 fd = open(filename, O_RDONLY);
614 fd = open(filename, O_WRONLY|O_TRUNC|O_CREAT, 0666);
616 fd = open(filename, O_WRONLY|O_TRUNC);
619 return (errno + 100);
620 file = fdopen(fd, (mode == RRQ)? "r":"w");
623 return (errno + 100);
632 timer(int sig __unused)
634 if (++timeouts > MAX_TIMEOUTS)
636 longjmp(timeoutbuf, 1);
640 * Send the requested file.
643 xmitfile(struct formats *pf)
646 struct tftphdr *ap; /* ack packet */
648 volatile unsigned short block;
650 signal(SIGALRM, timer);
652 ap = (struct tftphdr *)ackbuf;
655 size = readit(file, &dp, pf->f_convert);
660 dp->th_opcode = htons((u_short)DATA);
661 dp->th_block = htons((u_short)block);
663 (void)setjmp(timeoutbuf);
669 if (send(peer, dp, size + 4, 0) != size + 4) {
671 t = (t < 32) ? t<< 1 : t;
673 syslog(LOG_ERR, "write: %m");
680 read_ahead(file, pf->f_convert);
682 alarm(rexmtval); /* read the ack */
683 n = recv(peer, ackbuf, sizeof (ackbuf), 0);
686 syslog(LOG_ERR, "read: %m");
689 ap->th_opcode = ntohs((u_short)ap->th_opcode);
690 ap->th_block = ntohs((u_short)ap->th_block);
692 if (ap->th_opcode == ERROR)
695 if (ap->th_opcode == ACK) {
696 if (ap->th_block == block)
698 /* Re-synchronize with the other side */
699 (void) synchnet(peer);
700 if (ap->th_block == (block -1))
706 } while (size == SEGSIZE);
712 justquit(int sig __unused)
722 recvfile(struct formats *pf)
725 struct tftphdr *ap; /* ack buffer */
727 volatile unsigned short block;
729 signal(SIGALRM, timer);
731 ap = (struct tftphdr *)ackbuf;
735 ap->th_opcode = htons((u_short)ACK);
736 ap->th_block = htons((u_short)block);
738 (void) setjmp(timeoutbuf);
740 if (send(peer, ackbuf, 4, 0) != 4) {
741 syslog(LOG_ERR, "write: %m");
744 write_behind(file, pf->f_convert);
747 n = recv(peer, dp, PKTSIZE, 0);
749 if (n < 0) { /* really? */
750 syslog(LOG_ERR, "read: %m");
753 dp->th_opcode = ntohs((u_short)dp->th_opcode);
754 dp->th_block = ntohs((u_short)dp->th_block);
755 if (dp->th_opcode == ERROR)
757 if (dp->th_opcode == DATA) {
758 if (dp->th_block == block) {
761 /* Re-synchronize with the other side */
762 (void) synchnet(peer);
763 if (dp->th_block == (block-1))
764 goto send_ack; /* rexmit */
767 /* size = write(file, dp->th_data, n - 4); */
768 size = writeit(file, &dp, n - 4, pf->f_convert);
769 if (size != (n-4)) { /* ahem */
770 if (size < 0) nak(errno + 100);
774 } while (size == SEGSIZE);
775 write_behind(file, pf->f_convert);
776 (void) fclose(file); /* close data file */
778 ap->th_opcode = htons((u_short)ACK); /* send the "final" ack */
779 ap->th_block = htons((u_short)(block));
780 (void) send(peer, ackbuf, 4, 0);
782 signal(SIGALRM, justquit); /* just quit on timeout */
784 n = recv(peer, buf, sizeof (buf), 0); /* normally times out and quits */
786 if (n >= 4 && /* if read some data */
787 dp->th_opcode == DATA && /* and got a data block */
788 block == dp->th_block) { /* then my last ack was lost */
789 (void) send(peer, ackbuf, 4, 0); /* resend final ack */
799 { EUNDEF, "Undefined error code" },
800 { ENOTFOUND, "File not found" },
801 { EACCESS, "Access violation" },
802 { ENOSPACE, "Disk full or allocation exceeded" },
803 { EBADOP, "Illegal TFTP operation" },
804 { EBADID, "Unknown transfer ID" },
805 { EEXISTS, "File already exists" },
806 { ENOUSER, "No such user" },
807 { EOPTNEG, "Option negotiation" },
814 static char ebuf[20];
818 for (pe = errmsgs; pe->e_code >= 0; pe++)
819 if (pe->e_code == error)
821 snprintf(ebuf, sizeof(buf), "error %d", error);
826 * Send a nak packet (error message).
827 * Error code passed in is one of the
828 * standard TFTP codes, or a UNIX errno
838 tp = (struct tftphdr *)buf;
839 tp->th_opcode = htons((u_short)ERROR);
840 tp->th_code = htons((u_short)error);
841 for (pe = errmsgs; pe->e_code >= 0; pe++)
842 if (pe->e_code == error)
844 if (pe->e_code < 0) {
845 pe->e_msg = strerror(error - 100);
846 tp->th_code = EUNDEF; /* set 'undef' errorcode */
848 strcpy(tp->th_msg, pe->e_msg);
849 length = strlen(pe->e_msg);
850 tp->th_msg[length] = '\0';
852 if (send(peer, buf, length, 0) != length)
853 syslog(LOG_ERR, "nak: %m");
856 /* translate IPv4 mapped IPv6 address to IPv4 address */
858 unmappedaddr(struct sockaddr_in6 *sin6)
860 struct sockaddr_in *sin4;
864 if (sin6->sin6_family != AF_INET6 ||
865 !IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr))
867 sin4 = (struct sockaddr_in *)sin6;
868 addr = *(u_int32_t *)&sin6->sin6_addr.s6_addr[12];
869 port = sin6->sin6_port;
870 memset(sin4, 0, sizeof(struct sockaddr_in));
871 sin4->sin_addr.s_addr = addr;
872 sin4->sin_port = port;
873 sin4->sin_family = AF_INET;
874 sin4->sin_len = sizeof(struct sockaddr_in);
878 * Send an oack packet (option acknowledgement).
883 struct tftphdr *tp, *ap;
887 tp = (struct tftphdr *)buf;
889 size = sizeof(buf) - 2;
890 tp->th_opcode = htons((u_short)OACK);
891 for (i = 0; options[i].o_type != NULL; i++) {
892 if (options[i].o_request) {
893 n = snprintf(bp, size, "%s%c%d", options[i].o_type,
894 0, options[i].o_reply);
898 syslog(LOG_ERR, "oack: buffer overflow");
904 ap = (struct tftphdr *)ackbuf;
905 signal(SIGALRM, timer);
908 (void)setjmp(timeoutbuf);
909 if (send(peer, buf, size, 0) != size) {
910 syslog(LOG_INFO, "oack: %m");
916 n = recv(peer, ackbuf, sizeof (ackbuf), 0);
919 syslog(LOG_ERR, "recv: %m");
922 ap->th_opcode = ntohs((u_short)ap->th_opcode);
923 ap->th_block = ntohs((u_short)ap->th_block);
924 if (ap->th_opcode == ERROR)
926 if (ap->th_opcode == ACK && ap->th_block == 0)