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>
61 #include <netinet/in.h>
62 #include <arpa/tftp.h>
63 #include <arpa/inet.h>
82 #define MAX_TIMEOUTS 5
85 int rexmtval = TIMEOUT;
86 int max_rexmtval = 2*TIMEOUT;
88 #define PKTSIZE SEGSIZE+4
91 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;
113 static char *errtomsg(int);
114 static void nak(int);
118 main(int argc, char *argv[])
123 struct sockaddr_storage me;
125 char *chroot_dir = NULL;
126 struct passwd *nobody;
127 char *chuser = "nobody";
129 openlog("tftpd", LOG_PID | LOG_NDELAY, LOG_FTP);
130 while ((ch = getopt(argc, argv, "cClns:u:")) != -1) {
151 syslog(LOG_WARNING, "ignoring unknown option -%c", ch);
155 struct dirlist *dirp;
157 /* Get list of directory prefixes. Skip relative pathnames. */
158 for (dirp = dirs; optind < argc && dirp < &dirs[MAXDIRS];
160 if (argv[optind][0] == '/') {
161 dirp->name = argv[optind];
162 dirp->len = strlen(dirp->name);
167 else if (chroot_dir) {
171 if (ipchroot && chroot_dir == NULL) {
172 syslog(LOG_ERR, "-c requires -s");
177 if (ioctl(0, FIONBIO, &on) < 0) {
178 syslog(LOG_ERR, "ioctl(FIONBIO): %m");
181 fromlen = sizeof (from);
182 n = recvfrom(0, buf, sizeof (buf), 0,
183 (struct sockaddr *)&from, &fromlen);
185 syslog(LOG_ERR, "recvfrom: %m");
189 * Now that we have read the message out of the UDP
190 * socket, we fork and exit. Thus, inetd will go back
191 * to listening to the tftp port, and the next request
192 * to come in will start up a new instance of tftpd.
194 * We do this so that inetd can run tftpd in "wait" mode.
195 * The problem with tftpd running in "nowait" mode is that
196 * inetd may get one or more successful "selects" on the
197 * tftp port before we do our receive, so more than one
198 * instance of tftpd may be started up. Worse, if tftpd
199 * break before doing the above "recvfrom", inetd would
200 * spawn endless instances, clogging the system.
206 for (i = 1; i < 20; i++) {
211 * flush out to most recently sent request.
213 * This may drop some request, but those
214 * will be resent by the clients when
215 * they timeout. The positive effect of
216 * this flush is to (try to) prevent more
217 * than one tftpd being started up to service
218 * a single request from a single client.
221 i = recvfrom(0, buf, sizeof (buf), 0,
222 (struct sockaddr *)&from, &j);
232 syslog(LOG_ERR, "fork: %m");
234 } else if (pid != 0) {
240 * Since we exit here, we should do that only after the above
241 * recvfrom to keep inetd from constantly forking should there
242 * be a problem. See the above comment about system clogging.
249 struct sockaddr_storage ss;
250 char hbuf[NI_MAXHOST];
252 memcpy(&ss, &from, from.ss_len);
253 unmappedaddr((struct sockaddr_in6 *)&ss);
254 getnameinfo((struct sockaddr *)&ss, ss.ss_len,
255 hbuf, sizeof(hbuf), NULL, 0,
256 NI_NUMERICHOST | NI_WITHSCOPEID);
257 asprintf(&tempchroot, "%s/%s", chroot_dir, hbuf);
258 statret = stat(tempchroot, &sb);
259 if ((sb.st_mode & S_IFDIR) &&
260 (statret == 0 || (statret == -1 && ipchroot == 1)))
261 chroot_dir = tempchroot;
263 /* Must get this before chroot because /etc might go away */
264 if ((nobody = getpwnam(chuser)) == NULL) {
265 syslog(LOG_ERR, "%s: no such user", chuser);
268 if (chroot(chroot_dir)) {
269 syslog(LOG_ERR, "chroot: %s: %m", chroot_dir);
273 setuid(nobody->pw_uid);
274 setgroups(1, &nobody->pw_gid);
278 if (getsockname(0, (struct sockaddr *)&me, &len) == 0) {
279 switch (me.ss_family) {
281 ((struct sockaddr_in *)&me)->sin_port = 0;
284 ((struct sockaddr_in6 *)&me)->sin6_port = 0;
291 memset(&me, 0, sizeof(me));
292 me.ss_family = from.ss_family;
293 me.ss_len = from.ss_len;
298 peer = socket(from.ss_family, SOCK_DGRAM, 0);
300 syslog(LOG_ERR, "socket: %m");
303 if (bind(peer, (struct sockaddr *)&me, me.ss_len) < 0) {
304 syslog(LOG_ERR, "bind: %m");
307 if (connect(peer, (struct sockaddr *)&from, from.ss_len) < 0) {
308 syslog(LOG_ERR, "connect: %m");
311 tp = (struct tftphdr *)buf;
312 tp->th_opcode = ntohs(tp->th_opcode);
313 if (tp->th_opcode == RRQ || tp->th_opcode == WRQ)
319 int validate_access(char **, int);
320 void xmitfile(struct formats *);
321 void recvfile(struct formats *);
325 int (*f_validate)(char **, int);
326 void (*f_send)(struct formats *);
327 void (*f_recv)(struct formats *);
330 { "netascii", validate_access, xmitfile, recvfile, 1 },
331 { "octet", validate_access, xmitfile, recvfile, 0 },
333 { "mail", validate_user, sendmail, recvmail, 1 },
341 int o_reply; /* turn into union if need be */
343 { "tsize" }, /* OPT_TSIZE */
344 { "timeout" }, /* OPT_TIMEOUT */
354 * Handle initial connection protocol.
357 tftp(struct tftphdr *tp, int size)
360 int i, first = 1, has_options = 0, ecode;
362 char *filename, *mode, *option, *ccp;
364 filename = cp = tp->th_stuff;
366 while (cp < buf + size) {
380 for (cp = mode; *cp; cp++)
383 for (pf = formats; pf->f_mode; pf++)
384 if (strcmp(pf->f_mode, mode) == 0)
386 if (pf->f_mode == 0) {
390 while (++cp < buf + size) {
391 for (i = 2, ccp = cp; i > 0; ccp++) {
392 if (ccp >= buf + size) {
394 * Don't reject the request, just stop trying
395 * to parse the option and get on with it.
396 * Some Apple OpenFirmware versions have
397 * trailing garbage on the end of otherwise
401 } else if (*ccp == '\0')
404 for (option = cp; *cp; cp++)
407 for (i = 0; options[i].o_type != NULL; i++)
408 if (strcmp(option, options[i].o_type) == 0) {
409 options[i].o_request = ++cp;
416 if (options[OPT_TIMEOUT].o_request) {
417 int to = atoi(options[OPT_TIMEOUT].o_request);
418 if (to < 1 || to > 255) {
422 else if (to <= max_rexmtval)
423 options[OPT_TIMEOUT].o_reply = rexmtval = to;
425 options[OPT_TIMEOUT].o_request = NULL;
428 ecode = (*pf->f_validate)(&filename, tp->th_opcode);
432 char hbuf[NI_MAXHOST];
434 getnameinfo((struct sockaddr *)&from, from.ss_len,
435 hbuf, sizeof(hbuf), NULL, 0,
437 syslog(LOG_INFO, "%s: %s request for %s: %s", hbuf,
438 tp->th_opcode == WRQ ? "write" : "read",
439 filename, errtomsg(ecode));
443 * Avoid storms of naks to a RRQ broadcast for a relative
444 * bootfile pathname from a diskless Sun.
446 if (suppress_naks && *filename != '/' && ecode == ENOTFOUND)
451 if (tp->th_opcode == WRQ)
462 * Validate file access. Since we
463 * have no uid or gid, for now require
464 * file to exist and be publicly
466 * If we were invoked with arguments
467 * from inetd then the file must also be
468 * in one of the given directory prefixes.
469 * Note also, full path name must be
470 * given as we have no login directory.
473 validate_access(char **filep, int mode)
477 struct dirlist *dirp;
478 static char pathname[MAXPATHLEN];
479 char *filename = *filep;
482 * Prevent tricksters from getting around the directory restrictions
484 if (strstr(filename, "/../"))
487 if (*filename == '/') {
489 * Allow the request if it's in one of the approved locations.
490 * Special case: check the null prefix ("/") by looking
491 * for length = 1 and relying on the arg. processing that
494 for (dirp = dirs; dirp->name != NULL; dirp++) {
495 if (dirp->len == 1 ||
496 (!strncmp(filename, dirp->name, dirp->len) &&
497 filename[dirp->len] == '/'))
500 /* If directory list is empty, allow access to any file */
501 if (dirp->name == NULL && dirp != dirs)
503 if (stat(filename, &stbuf) < 0)
504 return (errno == ENOENT ? ENOTFOUND : EACCESS);
505 if ((stbuf.st_mode & S_IFMT) != S_IFREG)
508 if ((stbuf.st_mode & S_IROTH) == 0)
511 if ((stbuf.st_mode & S_IWOTH) == 0)
518 * Relative file name: search the approved locations for it.
519 * Don't allow write requests that avoid directory
523 if (!strncmp(filename, "../", 3))
527 * If the file exists in one of the directories and isn't
528 * readable, continue looking. However, change the error code
529 * to give an indication that the file exists.
532 for (dirp = dirs; dirp->name != NULL; dirp++) {
533 snprintf(pathname, sizeof(pathname), "%s/%s",
534 dirp->name, filename);
535 if (stat(pathname, &stbuf) == 0 &&
536 (stbuf.st_mode & S_IFMT) == S_IFREG) {
537 if ((stbuf.st_mode & S_IROTH) != 0) {
543 if (dirp->name == NULL)
545 *filep = filename = pathname;
547 if (options[OPT_TSIZE].o_request) {
549 options[OPT_TSIZE].o_reply = stbuf.st_size;
551 /* XXX Allows writes of all sizes. */
552 options[OPT_TSIZE].o_reply =
553 atoi(options[OPT_TSIZE].o_request);
555 fd = open(filename, mode == RRQ ? O_RDONLY : O_WRONLY|O_TRUNC);
557 return (errno + 100);
558 file = fdopen(fd, (mode == RRQ)? "r":"w");
569 timer(int sig __unused)
571 if (++timeouts > MAX_TIMEOUTS)
573 longjmp(timeoutbuf, 1);
577 * Send the requested file.
580 xmitfile(struct formats *pf)
582 struct tftphdr *dp, *r_init();
583 struct tftphdr *ap; /* ack packet */
585 volatile unsigned short block;
587 signal(SIGALRM, timer);
589 ap = (struct tftphdr *)ackbuf;
592 size = readit(file, &dp, pf->f_convert);
597 dp->th_opcode = htons((u_short)DATA);
598 dp->th_block = htons((u_short)block);
600 (void)setjmp(timeoutbuf);
606 if (send(peer, dp, size + 4, 0) != size + 4) {
608 t = (t < 32) ? t<< 1 : t;
610 syslog(LOG_ERR, "write: %m");
617 read_ahead(file, pf->f_convert);
619 alarm(rexmtval); /* read the ack */
620 n = recv(peer, ackbuf, sizeof (ackbuf), 0);
623 syslog(LOG_ERR, "read: %m");
626 ap->th_opcode = ntohs((u_short)ap->th_opcode);
627 ap->th_block = ntohs((u_short)ap->th_block);
629 if (ap->th_opcode == ERROR)
632 if (ap->th_opcode == ACK) {
633 if (ap->th_block == block)
635 /* Re-synchronize with the other side */
636 (void) synchnet(peer);
637 if (ap->th_block == (block -1))
643 } while (size == SEGSIZE);
649 justquit(int sig __unused)
659 recvfile(struct formats *pf)
661 struct tftphdr *dp, *w_init();
662 struct tftphdr *ap; /* ack buffer */
664 volatile unsigned short block;
666 signal(SIGALRM, timer);
668 ap = (struct tftphdr *)ackbuf;
672 ap->th_opcode = htons((u_short)ACK);
673 ap->th_block = htons((u_short)block);
675 (void) setjmp(timeoutbuf);
677 if (send(peer, ackbuf, 4, 0) != 4) {
678 syslog(LOG_ERR, "write: %m");
681 write_behind(file, pf->f_convert);
684 n = recv(peer, dp, PKTSIZE, 0);
686 if (n < 0) { /* really? */
687 syslog(LOG_ERR, "read: %m");
690 dp->th_opcode = ntohs((u_short)dp->th_opcode);
691 dp->th_block = ntohs((u_short)dp->th_block);
692 if (dp->th_opcode == ERROR)
694 if (dp->th_opcode == DATA) {
695 if (dp->th_block == block) {
698 /* Re-synchronize with the other side */
699 (void) synchnet(peer);
700 if (dp->th_block == (block-1))
701 goto send_ack; /* rexmit */
704 /* size = write(file, dp->th_data, n - 4); */
705 size = writeit(file, &dp, n - 4, pf->f_convert);
706 if (size != (n-4)) { /* ahem */
707 if (size < 0) nak(errno + 100);
711 } while (size == SEGSIZE);
712 write_behind(file, pf->f_convert);
713 (void) fclose(file); /* close data file */
715 ap->th_opcode = htons((u_short)ACK); /* send the "final" ack */
716 ap->th_block = htons((u_short)(block));
717 (void) send(peer, ackbuf, 4, 0);
719 signal(SIGALRM, justquit); /* just quit on timeout */
721 n = recv(peer, buf, sizeof (buf), 0); /* normally times out and quits */
723 if (n >= 4 && /* if read some data */
724 dp->th_opcode == DATA && /* and got a data block */
725 block == dp->th_block) { /* then my last ack was lost */
726 (void) send(peer, ackbuf, 4, 0); /* resend final ack */
736 { EUNDEF, "Undefined error code" },
737 { ENOTFOUND, "File not found" },
738 { EACCESS, "Access violation" },
739 { ENOSPACE, "Disk full or allocation exceeded" },
740 { EBADOP, "Illegal TFTP operation" },
741 { EBADID, "Unknown transfer ID" },
742 { EEXISTS, "File already exists" },
743 { ENOUSER, "No such user" },
744 { EOPTNEG, "Option negotiation" },
755 for (pe = errmsgs; pe->e_code >= 0; pe++)
756 if (pe->e_code == error)
758 snprintf(buf, sizeof(buf), "error %d", error);
763 * Send a nak packet (error message).
764 * Error code passed in is one of the
765 * standard TFTP codes, or a UNIX errno
775 tp = (struct tftphdr *)buf;
776 tp->th_opcode = htons((u_short)ERROR);
777 tp->th_code = htons((u_short)error);
778 for (pe = errmsgs; pe->e_code >= 0; pe++)
779 if (pe->e_code == error)
781 if (pe->e_code < 0) {
782 pe->e_msg = strerror(error - 100);
783 tp->th_code = EUNDEF; /* set 'undef' errorcode */
785 strcpy(tp->th_msg, pe->e_msg);
786 length = strlen(pe->e_msg);
787 tp->th_msg[length] = '\0';
789 if (send(peer, buf, length, 0) != length)
790 syslog(LOG_ERR, "nak: %m");
793 /* translate IPv4 mapped IPv6 address to IPv4 address */
795 unmappedaddr(struct sockaddr_in6 *sin6)
797 struct sockaddr_in *sin4;
801 if (sin6->sin6_family != AF_INET6 ||
802 !IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr))
804 sin4 = (struct sockaddr_in *)sin6;
805 addr = *(u_int32_t *)&sin6->sin6_addr.s6_addr[12];
806 port = sin6->sin6_port;
807 memset(sin4, 0, sizeof(struct sockaddr_in));
808 sin4->sin_addr.s_addr = addr;
809 sin4->sin_port = port;
810 sin4->sin_family = AF_INET;
811 sin4->sin_len = sizeof(struct sockaddr_in);
815 * Send an oack packet (option acknowledgement).
820 struct tftphdr *tp, *ap;
824 tp = (struct tftphdr *)buf;
826 size = sizeof(buf) - 2;
827 tp->th_opcode = htons((u_short)OACK);
828 for (i = 0; options[i].o_type != NULL; i++) {
829 if (options[i].o_request) {
830 n = snprintf(bp, size, "%s%c%d", options[i].o_type,
831 0, options[i].o_reply);
835 syslog(LOG_ERR, "oack: buffer overflow");
841 ap = (struct tftphdr *)ackbuf;
842 signal(SIGALRM, timer);
845 (void)setjmp(timeoutbuf);
846 if (send(peer, buf, size, 0) != size) {
847 syslog(LOG_INFO, "oack: %m");
853 n = recv(peer, ackbuf, sizeof (ackbuf), 0);
856 syslog(LOG_ERR, "recv: %m");
859 ap->th_opcode = ntohs((u_short)ap->th_opcode);
860 ap->th_block = ntohs((u_short)ap->th_block);
861 if (ap->th_opcode == ERROR)
863 if (ap->th_opcode == ACK && ap->th_block == 0)