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;
95 void tftp(struct tftphdr *, int);
96 static void unmappedaddr(struct sockaddr_in6 *);
99 * Null-terminated directory prefix list for absolute pathname requests and
100 * search list for relative pathname requests.
102 * MAXDIRS should be at least as large as the number of arguments that
103 * inetd allows (currently 20).
106 static struct dirlist {
110 static int suppress_naks;
113 static int create_new = 0;
114 static mode_t mask = S_IWGRP|S_IWOTH;
116 static const char *errtomsg(int);
117 static void nak(int);
118 static void oack(void);
120 static void timer(int);
121 static void justquit(int);
124 main(int argc, char *argv[])
129 struct sockaddr_storage me;
131 char *chroot_dir = NULL;
132 struct passwd *nobody;
133 const char *chuser = "nobody";
135 tzset(); /* syslog in localtime */
137 openlog("tftpd", LOG_PID | LOG_NDELAY, LOG_FTP);
138 while ((ch = getopt(argc, argv, "cClns:u:Uw")) != -1) {
159 mask = strtol(optarg, NULL, 0);
165 syslog(LOG_WARNING, "ignoring unknown option -%c", ch);
169 struct dirlist *dirp;
171 /* Get list of directory prefixes. Skip relative pathnames. */
172 for (dirp = dirs; optind < argc && dirp < &dirs[MAXDIRS];
174 if (argv[optind][0] == '/') {
175 dirp->name = argv[optind];
176 dirp->len = strlen(dirp->name);
181 else if (chroot_dir) {
185 if (ipchroot > 0 && chroot_dir == NULL) {
186 syslog(LOG_ERR, "-c requires -s");
193 if (ioctl(0, FIONBIO, &on) < 0) {
194 syslog(LOG_ERR, "ioctl(FIONBIO): %m");
197 fromlen = sizeof (from);
198 n = recvfrom(0, buf, sizeof (buf), 0,
199 (struct sockaddr *)&from, &fromlen);
201 syslog(LOG_ERR, "recvfrom: %m");
205 * Now that we have read the message out of the UDP
206 * socket, we fork and exit. Thus, inetd will go back
207 * to listening to the tftp port, and the next request
208 * to come in will start up a new instance of tftpd.
210 * We do this so that inetd can run tftpd in "wait" mode.
211 * The problem with tftpd running in "nowait" mode is that
212 * inetd may get one or more successful "selects" on the
213 * tftp port before we do our receive, so more than one
214 * instance of tftpd may be started up. Worse, if tftpd
215 * break before doing the above "recvfrom", inetd would
216 * spawn endless instances, clogging the system.
222 for (i = 1; i < 20; i++) {
227 * flush out to most recently sent request.
229 * This may drop some request, but those
230 * will be resent by the clients when
231 * they timeout. The positive effect of
232 * this flush is to (try to) prevent more
233 * than one tftpd being started up to service
234 * a single request from a single client.
237 i = recvfrom(0, buf, sizeof (buf), 0,
238 (struct sockaddr *)&from, &j);
248 syslog(LOG_ERR, "fork: %m");
250 } else if (pid != 0) {
256 * Since we exit here, we should do that only after the above
257 * recvfrom to keep inetd from constantly forking should there
258 * be a problem. See the above comment about system clogging.
265 struct sockaddr_storage ss;
266 char hbuf[NI_MAXHOST];
268 memcpy(&ss, &from, from.ss_len);
269 unmappedaddr((struct sockaddr_in6 *)&ss);
270 getnameinfo((struct sockaddr *)&ss, ss.ss_len,
271 hbuf, sizeof(hbuf), NULL, 0,
272 NI_NUMERICHOST | NI_WITHSCOPEID);
273 asprintf(&tempchroot, "%s/%s", chroot_dir, hbuf);
275 statret = stat(tempchroot, &sb);
277 (statret == 0 && (sb.st_mode & S_IFDIR)))
278 chroot_dir = tempchroot;
280 /* Must get this before chroot because /etc might go away */
281 if ((nobody = getpwnam(chuser)) == NULL) {
282 syslog(LOG_ERR, "%s: no such user", chuser);
285 if (chroot(chroot_dir)) {
286 syslog(LOG_ERR, "chroot: %s: %m", chroot_dir);
290 setgroups(1, &nobody->pw_gid);
291 setuid(nobody->pw_uid);
295 if (getsockname(0, (struct sockaddr *)&me, &len) == 0) {
296 switch (me.ss_family) {
298 ((struct sockaddr_in *)&me)->sin_port = 0;
301 ((struct sockaddr_in6 *)&me)->sin6_port = 0;
308 memset(&me, 0, sizeof(me));
309 me.ss_family = from.ss_family;
310 me.ss_len = from.ss_len;
315 peer = socket(from.ss_family, SOCK_DGRAM, 0);
317 syslog(LOG_ERR, "socket: %m");
320 if (bind(peer, (struct sockaddr *)&me, me.ss_len) < 0) {
321 syslog(LOG_ERR, "bind: %m");
324 if (connect(peer, (struct sockaddr *)&from, from.ss_len) < 0) {
325 syslog(LOG_ERR, "connect: %m");
328 tp = (struct tftphdr *)buf;
329 tp->th_opcode = ntohs(tp->th_opcode);
330 if (tp->th_opcode == RRQ || tp->th_opcode == WRQ)
336 reduce_path(char *fn)
340 /* Reduce all "/+./" to "/" (just in case we've got "/./../" later */
341 while ((slash = strstr(fn, "/./")) != NULL) {
342 for (ptr = slash; ptr > fn && ptr[-1] == '/'; ptr--)
349 /* Now reduce all "/something/+../" to "/" */
350 while ((slash = strstr(fn, "/../")) != NULL) {
353 for (ptr = slash; ptr > fn && ptr[-1] == '/'; ptr--)
355 for (ptr--; ptr >= fn; ptr--)
367 int validate_access(char **, int);
368 void xmitfile(struct formats *);
369 void recvfile(struct formats *);
373 int (*f_validate)(char **, int);
374 void (*f_send)(struct formats *);
375 void (*f_recv)(struct formats *);
378 { "netascii", validate_access, xmitfile, recvfile, 1 },
379 { "octet", validate_access, xmitfile, recvfile, 0 },
381 { "mail", validate_user, sendmail, recvmail, 1 },
383 { 0, NULL, NULL, NULL, 0 }
389 int o_reply; /* turn into union if need be */
391 { "tsize", NULL, 0 }, /* OPT_TSIZE */
392 { "timeout", NULL, 0 }, /* OPT_TIMEOUT */
402 * Handle initial connection protocol.
405 tftp(struct tftphdr *tp, int size)
408 int i, first = 1, has_options = 0, ecode;
410 char *filename, *mode, *option, *ccp;
411 char fnbuf[PATH_MAX], resolved_fnbuf[PATH_MAX];
415 while (cp < buf + size) {
424 i = cp - tp->th_stuff;
425 if (i >= sizeof(fnbuf)) {
429 memcpy(fnbuf, tp->th_stuff, i);
438 for (cp = mode; *cp; cp++)
441 for (pf = formats; pf->f_mode; pf++)
442 if (strcmp(pf->f_mode, mode) == 0)
444 if (pf->f_mode == 0) {
448 while (++cp < buf + size) {
449 for (i = 2, ccp = cp; i > 0; ccp++) {
450 if (ccp >= buf + size) {
452 * Don't reject the request, just stop trying
453 * to parse the option and get on with it.
454 * Some Apple Open Firmware versions have
455 * trailing garbage on the end of otherwise
459 } else if (*ccp == '\0')
462 for (option = cp; *cp; cp++)
465 for (i = 0; options[i].o_type != NULL; i++)
466 if (strcmp(option, options[i].o_type) == 0) {
467 options[i].o_request = ++cp;
474 if (options[OPT_TIMEOUT].o_request) {
475 int to = atoi(options[OPT_TIMEOUT].o_request);
476 if (to < 1 || to > 255) {
480 else if (to <= max_rexmtval)
481 options[OPT_TIMEOUT].o_reply = rexmtval = to;
483 options[OPT_TIMEOUT].o_request = NULL;
486 ecode = (*pf->f_validate)(&filename, tp->th_opcode);
487 if (has_options && ecode == 0)
490 char hbuf[NI_MAXHOST];
492 getnameinfo((struct sockaddr *)&from, from.ss_len,
493 hbuf, sizeof(hbuf), NULL, 0,
495 syslog(LOG_INFO, "%s: %s request for %s: %s", hbuf,
496 tp->th_opcode == WRQ ? "write" : "read",
497 filename, errtomsg(ecode));
501 * Avoid storms of naks to a RRQ broadcast for a relative
502 * bootfile pathname from a diskless Sun.
504 if (suppress_naks && *filename != '/' && ecode == ENOTFOUND)
509 if (tp->th_opcode == WRQ)
520 * Validate file access. Since we
521 * have no uid or gid, for now require
522 * file to exist and be publicly
524 * If we were invoked with arguments
525 * from inetd then the file must also be
526 * in one of the given directory prefixes.
527 * Note also, full path name must be
528 * given as we have no login directory.
531 validate_access(char **filep, int mode)
535 struct dirlist *dirp;
536 static char pathname[MAXPATHLEN];
537 char *filename = *filep;
540 * Prevent tricksters from getting around the directory restrictions
542 if (strstr(filename, "/../"))
545 if (*filename == '/') {
547 * Allow the request if it's in one of the approved locations.
548 * Special case: check the null prefix ("/") by looking
549 * for length = 1 and relying on the arg. processing that
552 for (dirp = dirs; dirp->name != NULL; dirp++) {
553 if (dirp->len == 1 ||
554 (!strncmp(filename, dirp->name, dirp->len) &&
555 filename[dirp->len] == '/'))
558 /* If directory list is empty, allow access to any file */
559 if (dirp->name == NULL && dirp != dirs)
561 if (stat(filename, &stbuf) < 0)
562 return (errno == ENOENT ? ENOTFOUND : EACCESS);
563 if ((stbuf.st_mode & S_IFMT) != S_IFREG)
566 if ((stbuf.st_mode & S_IROTH) == 0)
569 if ((stbuf.st_mode & S_IWOTH) == 0)
576 * Relative file name: search the approved locations for it.
577 * Don't allow write requests that avoid directory
581 if (!strncmp(filename, "../", 3))
585 * If the file exists in one of the directories and isn't
586 * readable, continue looking. However, change the error code
587 * to give an indication that the file exists.
590 for (dirp = dirs; dirp->name != NULL; dirp++) {
591 snprintf(pathname, sizeof(pathname), "%s/%s",
592 dirp->name, filename);
593 if (stat(pathname, &stbuf) == 0 &&
594 (stbuf.st_mode & S_IFMT) == S_IFREG) {
595 if ((stbuf.st_mode & S_IROTH) != 0) {
601 if (dirp->name != NULL)
602 *filep = filename = pathname;
603 else if (mode == RRQ)
606 if (options[OPT_TSIZE].o_request) {
608 options[OPT_TSIZE].o_reply = stbuf.st_size;
610 /* XXX Allows writes of all sizes. */
611 options[OPT_TSIZE].o_reply =
612 atoi(options[OPT_TSIZE].o_request);
615 fd = open(filename, O_RDONLY);
618 fd = open(filename, O_WRONLY|O_TRUNC|O_CREAT, 0666);
620 fd = open(filename, O_WRONLY|O_TRUNC);
623 return (errno + 100);
624 file = fdopen(fd, (mode == RRQ)? "r":"w");
627 return (errno + 100);
636 timer(int sig __unused)
638 if (++timeouts > MAX_TIMEOUTS)
640 longjmp(timeoutbuf, 1);
644 * Send the requested file.
647 xmitfile(struct formats *pf)
650 struct tftphdr *ap; /* ack packet */
652 volatile unsigned short block;
654 signal(SIGALRM, timer);
656 ap = (struct tftphdr *)ackbuf;
659 size = readit(file, &dp, pf->f_convert);
664 dp->th_opcode = htons((u_short)DATA);
665 dp->th_block = htons((u_short)block);
667 (void)setjmp(timeoutbuf);
673 if (send(peer, dp, size + 4, 0) != size + 4) {
675 t = (t < 32) ? t<< 1 : t;
677 syslog(LOG_ERR, "write: %m");
684 read_ahead(file, pf->f_convert);
686 alarm(rexmtval); /* read the ack */
687 n = recv(peer, ackbuf, sizeof (ackbuf), 0);
690 syslog(LOG_ERR, "read: %m");
693 ap->th_opcode = ntohs((u_short)ap->th_opcode);
694 ap->th_block = ntohs((u_short)ap->th_block);
696 if (ap->th_opcode == ERROR)
699 if (ap->th_opcode == ACK) {
700 if (ap->th_block == block)
702 /* Re-synchronize with the other side */
703 (void) synchnet(peer);
704 if (ap->th_block == (block -1))
710 } while (size == SEGSIZE);
716 justquit(int sig __unused)
726 recvfile(struct formats *pf)
729 struct tftphdr *ap; /* ack buffer */
731 volatile unsigned short block;
733 signal(SIGALRM, timer);
735 ap = (struct tftphdr *)ackbuf;
739 ap->th_opcode = htons((u_short)ACK);
740 ap->th_block = htons((u_short)block);
742 (void) setjmp(timeoutbuf);
744 if (send(peer, ackbuf, 4, 0) != 4) {
745 syslog(LOG_ERR, "write: %m");
748 write_behind(file, pf->f_convert);
751 n = recv(peer, dp, PKTSIZE, 0);
753 if (n < 0) { /* really? */
754 syslog(LOG_ERR, "read: %m");
757 dp->th_opcode = ntohs((u_short)dp->th_opcode);
758 dp->th_block = ntohs((u_short)dp->th_block);
759 if (dp->th_opcode == ERROR)
761 if (dp->th_opcode == DATA) {
762 if (dp->th_block == block) {
765 /* Re-synchronize with the other side */
766 (void) synchnet(peer);
767 if (dp->th_block == (block-1))
768 goto send_ack; /* rexmit */
771 /* size = write(file, dp->th_data, n - 4); */
772 size = writeit(file, &dp, n - 4, pf->f_convert);
773 if (size != (n-4)) { /* ahem */
774 if (size < 0) nak(errno + 100);
778 } while (size == SEGSIZE);
779 write_behind(file, pf->f_convert);
780 (void) fclose(file); /* close data file */
782 ap->th_opcode = htons((u_short)ACK); /* send the "final" ack */
783 ap->th_block = htons((u_short)(block));
784 (void) send(peer, ackbuf, 4, 0);
786 signal(SIGALRM, justquit); /* just quit on timeout */
788 n = recv(peer, buf, sizeof (buf), 0); /* normally times out and quits */
790 if (n >= 4 && /* if read some data */
791 dp->th_opcode == DATA && /* and got a data block */
792 block == dp->th_block) { /* then my last ack was lost */
793 (void) send(peer, ackbuf, 4, 0); /* resend final ack */
803 { EUNDEF, "Undefined error code" },
804 { ENOTFOUND, "File not found" },
805 { EACCESS, "Access violation" },
806 { ENOSPACE, "Disk full or allocation exceeded" },
807 { EBADOP, "Illegal TFTP operation" },
808 { EBADID, "Unknown transfer ID" },
809 { EEXISTS, "File already exists" },
810 { ENOUSER, "No such user" },
811 { EOPTNEG, "Option negotiation" },
818 static char ebuf[20];
822 for (pe = errmsgs; pe->e_code >= 0; pe++)
823 if (pe->e_code == error)
825 snprintf(ebuf, sizeof(buf), "error %d", error);
830 * Send a nak packet (error message).
831 * Error code passed in is one of the
832 * standard TFTP codes, or a UNIX errno
842 tp = (struct tftphdr *)buf;
843 tp->th_opcode = htons((u_short)ERROR);
844 tp->th_code = htons((u_short)error);
845 for (pe = errmsgs; pe->e_code >= 0; pe++)
846 if (pe->e_code == error)
848 if (pe->e_code < 0) {
849 pe->e_msg = strerror(error - 100);
850 tp->th_code = EUNDEF; /* set 'undef' errorcode */
852 strcpy(tp->th_msg, pe->e_msg);
853 length = strlen(pe->e_msg);
854 tp->th_msg[length] = '\0';
856 if (send(peer, buf, length, 0) != length)
857 syslog(LOG_ERR, "nak: %m");
860 /* translate IPv4 mapped IPv6 address to IPv4 address */
862 unmappedaddr(struct sockaddr_in6 *sin6)
864 struct sockaddr_in *sin4;
868 if (sin6->sin6_family != AF_INET6 ||
869 !IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr))
871 sin4 = (struct sockaddr_in *)sin6;
872 addr = *(u_int32_t *)&sin6->sin6_addr.s6_addr[12];
873 port = sin6->sin6_port;
874 memset(sin4, 0, sizeof(struct sockaddr_in));
875 sin4->sin_addr.s_addr = addr;
876 sin4->sin_port = port;
877 sin4->sin_family = AF_INET;
878 sin4->sin_len = sizeof(struct sockaddr_in);
882 * Send an oack packet (option acknowledgement).
887 struct tftphdr *tp, *ap;
891 tp = (struct tftphdr *)buf;
893 size = sizeof(buf) - 2;
894 tp->th_opcode = htons((u_short)OACK);
895 for (i = 0; options[i].o_type != NULL; i++) {
896 if (options[i].o_request) {
897 n = snprintf(bp, size, "%s%c%d", options[i].o_type,
898 0, options[i].o_reply);
902 syslog(LOG_ERR, "oack: buffer overflow");
908 ap = (struct tftphdr *)ackbuf;
909 signal(SIGALRM, timer);
912 (void)setjmp(timeoutbuf);
913 if (send(peer, buf, size, 0) != size) {
914 syslog(LOG_INFO, "oack: %m");
920 n = recv(peer, ackbuf, sizeof (ackbuf), 0);
923 syslog(LOG_ERR, "recv: %m");
926 ap->th_opcode = ntohs((u_short)ap->th_opcode);
927 ap->th_block = ntohs((u_short)ap->th_block);
928 if (ap->th_opcode == ERROR)
930 if (ap->th_opcode == ACK && ap->th_block == 0)