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
33 * @(#) Copyright (c) 1983, 1993 The Regents of the University of California. All rights reserved.
34 * @(#)tftpd.c 8.1 (Berkeley) 6/4/93
35 * $FreeBSD: src/libexec/tftpd/tftpd.c,v 1.15.2.5 2003/04/06 19:42:56 dwmalone Exp $
36 * $DragonFly: src/libexec/tftpd/tftpd.c,v 1.3 2003/11/20 14:32:17 eirikn Exp $
40 * Trivial file transfer protocol server.
42 * This version includes many modifications by Jim Guyton
46 #include <sys/param.h>
47 #include <sys/ioctl.h>
49 #include <sys/socket.h>
50 #include <sys/types.h>
52 #include <netinet/in.h>
53 #include <arpa/tftp.h>
54 #include <arpa/inet.h>
73 #define MAX_TIMEOUTS 5
76 int rexmtval = TIMEOUT;
77 int max_rexmtval = 2*TIMEOUT;
79 #define PKTSIZE SEGSIZE+4
82 struct sockaddr_storage from;
85 void tftp(struct tftphdr *, int);
86 static void unmappedaddr(struct sockaddr_in6 *);
89 * Null-terminated directory prefix list for absolute pathname requests and
90 * search list for relative pathname requests.
92 * MAXDIRS should be at least as large as the number of arguments that
93 * inetd allows (currently 20).
96 static struct dirlist {
100 static int suppress_naks;
104 static const char *errtomsg(int);
105 static void nak(int);
106 static void oack(void);
108 static void timer(int);
109 static void justquit(int);
112 main(int argc, char *argv[])
117 struct sockaddr_storage me;
119 char *chroot_dir = NULL;
120 struct passwd *nobody;
121 const char *chuser = "nobody";
123 openlog("tftpd", LOG_PID | LOG_NDELAY, LOG_FTP);
124 while ((ch = getopt(argc, argv, "cClns:u:")) != -1) {
145 syslog(LOG_WARNING, "ignoring unknown option -%c", ch);
149 struct dirlist *dirp;
151 /* Get list of directory prefixes. Skip relative pathnames. */
152 for (dirp = dirs; optind < argc && dirp < &dirs[MAXDIRS];
154 if (argv[optind][0] == '/') {
155 dirp->name = argv[optind];
156 dirp->len = strlen(dirp->name);
161 else if (chroot_dir) {
165 if (ipchroot && chroot_dir == NULL) {
166 syslog(LOG_ERR, "-c requires -s");
171 if (ioctl(0, FIONBIO, &on) < 0) {
172 syslog(LOG_ERR, "ioctl(FIONBIO): %m");
175 fromlen = sizeof (from);
176 n = recvfrom(0, buf, sizeof (buf), 0,
177 (struct sockaddr *)&from, &fromlen);
179 syslog(LOG_ERR, "recvfrom: %m");
183 * Now that we have read the message out of the UDP
184 * socket, we fork and exit. Thus, inetd will go back
185 * to listening to the tftp port, and the next request
186 * to come in will start up a new instance of tftpd.
188 * We do this so that inetd can run tftpd in "wait" mode.
189 * The problem with tftpd running in "nowait" mode is that
190 * inetd may get one or more successful "selects" on the
191 * tftp port before we do our receive, so more than one
192 * instance of tftpd may be started up. Worse, if tftpd
193 * break before doing the above "recvfrom", inetd would
194 * spawn endless instances, clogging the system.
200 for (i = 1; i < 20; i++) {
205 * flush out to most recently sent request.
207 * This may drop some request, but those
208 * will be resent by the clients when
209 * they timeout. The positive effect of
210 * this flush is to (try to) prevent more
211 * than one tftpd being started up to service
212 * a single request from a single client.
215 i = recvfrom(0, buf, sizeof (buf), 0,
216 (struct sockaddr *)&from, &j);
226 syslog(LOG_ERR, "fork: %m");
228 } else if (pid != 0) {
234 * Since we exit here, we should do that only after the above
235 * recvfrom to keep inetd from constantly forking should there
236 * be a problem. See the above comment about system clogging.
243 struct sockaddr_storage ss;
244 char hbuf[NI_MAXHOST];
246 memcpy(&ss, &from, from.ss_len);
247 unmappedaddr((struct sockaddr_in6 *)&ss);
248 getnameinfo((struct sockaddr *)&ss, ss.ss_len,
249 hbuf, sizeof(hbuf), NULL, 0,
250 NI_NUMERICHOST | NI_WITHSCOPEID);
251 asprintf(&tempchroot, "%s/%s", chroot_dir, hbuf);
252 statret = stat(tempchroot, &sb);
253 if ((sb.st_mode & S_IFDIR) &&
254 (statret == 0 || (statret == -1 && ipchroot == 1)))
255 chroot_dir = tempchroot;
257 /* Must get this before chroot because /etc might go away */
258 if ((nobody = getpwnam(chuser)) == NULL) {
259 syslog(LOG_ERR, "%s: no such user", chuser);
262 if (chroot(chroot_dir)) {
263 syslog(LOG_ERR, "chroot: %s: %m", chroot_dir);
267 setuid(nobody->pw_uid);
268 setgroups(1, &nobody->pw_gid);
272 if (getsockname(0, (struct sockaddr *)&me, &len) == 0) {
273 switch (me.ss_family) {
275 ((struct sockaddr_in *)&me)->sin_port = 0;
278 ((struct sockaddr_in6 *)&me)->sin6_port = 0;
285 memset(&me, 0, sizeof(me));
286 me.ss_family = from.ss_family;
287 me.ss_len = from.ss_len;
292 peer = socket(from.ss_family, SOCK_DGRAM, 0);
294 syslog(LOG_ERR, "socket: %m");
297 if (bind(peer, (struct sockaddr *)&me, me.ss_len) < 0) {
298 syslog(LOG_ERR, "bind: %m");
301 if (connect(peer, (struct sockaddr *)&from, from.ss_len) < 0) {
302 syslog(LOG_ERR, "connect: %m");
305 tp = (struct tftphdr *)buf;
306 tp->th_opcode = ntohs(tp->th_opcode);
307 if (tp->th_opcode == RRQ || tp->th_opcode == WRQ)
313 int validate_access(char **, int);
314 void xmitfile(struct formats *);
315 void recvfile(struct formats *);
319 int (*f_validate)(char **, int);
320 void (*f_send)(struct formats *);
321 void (*f_recv)(struct formats *);
324 { "netascii", validate_access, xmitfile, recvfile, 1 },
325 { "octet", validate_access, xmitfile, recvfile, 0 },
327 { "mail", validate_user, sendmail, recvmail, 1 },
329 { 0, NULL, NULL, NULL, 0 }
335 int o_reply; /* turn into union if need be */
337 { "tsize", NULL, 0 }, /* OPT_TSIZE */
338 { "timeout", NULL, 0 }, /* OPT_TIMEOUT */
348 * Handle initial connection protocol.
351 tftp(struct tftphdr *tp, int size)
355 int first = 1, has_options = 0, ecode;
357 char *filename, *mode = NULL, *option, *ccp;
358 char fnbuf[MAXPATHLEN];
362 while (cp < buf + size) {
371 i = cp - tp->th_stuff;
372 if (i >= sizeof(fnbuf)) {
376 memcpy(fnbuf, tp->th_stuff, i);
384 for (cp = mode; *cp; cp++)
387 for (pf = formats; pf->f_mode; pf++)
388 if (strcmp(pf->f_mode, mode) == 0)
390 if (pf->f_mode == 0) {
394 while (++cp < buf + size) {
395 for (i = 2, ccp = cp; i > 0; ccp++) {
396 if (ccp >= buf + size) {
398 * Don't reject the request, just stop trying
399 * to parse the option and get on with it.
400 * Some Apple OpenFirmware versions have
401 * trailing garbage on the end of otherwise
405 } else if (*ccp == '\0')
408 for (option = cp; *cp; cp++)
411 for (i = 0; options[i].o_type != NULL; i++)
412 if (strcmp(option, options[i].o_type) == 0) {
413 options[i].o_request = ++cp;
420 if (options[OPT_TIMEOUT].o_request) {
421 int to = atoi(options[OPT_TIMEOUT].o_request);
422 if (to < 1 || to > 255) {
426 else if (to <= max_rexmtval)
427 options[OPT_TIMEOUT].o_reply = rexmtval = to;
429 options[OPT_TIMEOUT].o_request = NULL;
432 ecode = (*pf->f_validate)(&filename, tp->th_opcode);
436 char hbuf[NI_MAXHOST];
438 getnameinfo((struct sockaddr *)&from, from.ss_len,
439 hbuf, sizeof(hbuf), NULL, 0,
441 syslog(LOG_INFO, "%s: %s request for %s: %s", hbuf,
442 tp->th_opcode == WRQ ? "write" : "read",
443 filename, errtomsg(ecode));
447 * Avoid storms of naks to a RRQ broadcast for a relative
448 * bootfile pathname from a diskless Sun.
450 if (suppress_naks && *filename != '/' && ecode == ENOTFOUND)
455 if (tp->th_opcode == WRQ)
466 * Validate file access. Since we
467 * have no uid or gid, for now require
468 * file to exist and be publicly
470 * If we were invoked with arguments
471 * from inetd then the file must also be
472 * in one of the given directory prefixes.
473 * Note also, full path name must be
474 * given as we have no login directory.
477 validate_access(char **filep, int mode)
481 struct dirlist *dirp;
482 static char pathname[MAXPATHLEN];
483 char *filename = *filep;
486 * Prevent tricksters from getting around the directory restrictions
488 if (strstr(filename, "/../"))
491 if (*filename == '/') {
493 * Allow the request if it's in one of the approved locations.
494 * Special case: check the null prefix ("/") by looking
495 * for length = 1 and relying on the arg. processing that
498 for (dirp = dirs; dirp->name != NULL; dirp++) {
499 if (dirp->len == 1 ||
500 (!strncmp(filename, dirp->name, dirp->len) &&
501 filename[dirp->len] == '/'))
504 /* If directory list is empty, allow access to any file */
505 if (dirp->name == NULL && dirp != dirs)
507 if (stat(filename, &stbuf) < 0)
508 return (errno == ENOENT ? ENOTFOUND : EACCESS);
509 if ((stbuf.st_mode & S_IFMT) != S_IFREG)
512 if ((stbuf.st_mode & S_IROTH) == 0)
515 if ((stbuf.st_mode & S_IWOTH) == 0)
522 * Relative file name: search the approved locations for it.
523 * Don't allow write requests that avoid directory
527 if (!strncmp(filename, "../", 3))
531 * If the file exists in one of the directories and isn't
532 * readable, continue looking. However, change the error code
533 * to give an indication that the file exists.
536 for (dirp = dirs; dirp->name != NULL; dirp++) {
537 snprintf(pathname, sizeof(pathname), "%s/%s",
538 dirp->name, filename);
539 if (stat(pathname, &stbuf) == 0 &&
540 (stbuf.st_mode & S_IFMT) == S_IFREG) {
541 if ((stbuf.st_mode & S_IROTH) != 0) {
547 if (dirp->name == NULL)
549 *filep = filename = pathname;
551 if (options[OPT_TSIZE].o_request) {
553 options[OPT_TSIZE].o_reply = stbuf.st_size;
555 /* XXX Allows writes of all sizes. */
556 options[OPT_TSIZE].o_reply =
557 atoi(options[OPT_TSIZE].o_request);
559 fd = open(filename, mode == RRQ ? O_RDONLY : O_WRONLY|O_TRUNC);
561 return (errno + 100);
562 file = fdopen(fd, (mode == RRQ)? "r":"w");
573 timer(int sig __unused)
575 if (++timeouts > MAX_TIMEOUTS)
577 longjmp(timeoutbuf, 1);
581 * Send the requested file.
584 xmitfile(struct formats *pf)
587 struct tftphdr *ap; /* ack packet */
589 volatile unsigned short block;
591 signal(SIGALRM, timer);
593 ap = (struct tftphdr *)ackbuf;
596 size = readit(file, &dp, pf->f_convert);
601 dp->th_opcode = htons((u_short)DATA);
602 dp->th_block = htons((u_short)block);
604 (void)setjmp(timeoutbuf);
610 if (send(peer, dp, size + 4, 0) != size + 4) {
612 t = (t < 32) ? t<< 1 : t;
614 syslog(LOG_ERR, "write: %m");
621 read_ahead(file, pf->f_convert);
623 alarm(rexmtval); /* read the ack */
624 n = recv(peer, ackbuf, sizeof (ackbuf), 0);
627 syslog(LOG_ERR, "read: %m");
630 ap->th_opcode = ntohs((u_short)ap->th_opcode);
631 ap->th_block = ntohs((u_short)ap->th_block);
633 if (ap->th_opcode == ERROR)
636 if (ap->th_opcode == ACK) {
637 if (ap->th_block == block)
639 /* Re-synchronize with the other side */
640 (void) synchnet(peer);
641 if (ap->th_block == (block -1))
647 } while (size == SEGSIZE);
653 justquit(int sig __unused)
663 recvfile(struct formats *pf)
666 struct tftphdr *ap; /* ack buffer */
668 volatile unsigned short block;
670 signal(SIGALRM, timer);
672 ap = (struct tftphdr *)ackbuf;
676 ap->th_opcode = htons((u_short)ACK);
677 ap->th_block = htons((u_short)block);
679 (void) setjmp(timeoutbuf);
681 if (send(peer, ackbuf, 4, 0) != 4) {
682 syslog(LOG_ERR, "write: %m");
685 write_behind(file, pf->f_convert);
688 n = recv(peer, dp, PKTSIZE, 0);
690 if (n < 0) { /* really? */
691 syslog(LOG_ERR, "read: %m");
694 dp->th_opcode = ntohs((u_short)dp->th_opcode);
695 dp->th_block = ntohs((u_short)dp->th_block);
696 if (dp->th_opcode == ERROR)
698 if (dp->th_opcode == DATA) {
699 if (dp->th_block == block) {
702 /* Re-synchronize with the other side */
703 (void) synchnet(peer);
704 if (dp->th_block == (block-1))
705 goto send_ack; /* rexmit */
708 /* size = write(file, dp->th_data, n - 4); */
709 size = writeit(file, &dp, n - 4, pf->f_convert);
710 if (size != (n-4)) { /* ahem */
711 if (size < 0) nak(errno + 100);
715 } while (size == SEGSIZE);
716 write_behind(file, pf->f_convert);
717 (void) fclose(file); /* close data file */
719 ap->th_opcode = htons((u_short)ACK); /* send the "final" ack */
720 ap->th_block = htons((u_short)(block));
721 (void) send(peer, ackbuf, 4, 0);
723 signal(SIGALRM, justquit); /* just quit on timeout */
725 n = recv(peer, buf, sizeof (buf), 0); /* normally times out and quits */
727 if (n >= 4 && /* if read some data */
728 dp->th_opcode == DATA && /* and got a data block */
729 block == dp->th_block) { /* then my last ack was lost */
730 (void) send(peer, ackbuf, 4, 0); /* resend final ack */
740 { EUNDEF, "Undefined error code" },
741 { ENOTFOUND, "File not found" },
742 { EACCESS, "Access violation" },
743 { ENOSPACE, "Disk full or allocation exceeded" },
744 { EBADOP, "Illegal TFTP operation" },
745 { EBADID, "Unknown transfer ID" },
746 { EEXISTS, "File already exists" },
747 { ENOUSER, "No such user" },
748 { EOPTNEG, "Option negotiation" },
755 static char ebuf[20];
759 for (pe = errmsgs; pe->e_code >= 0; pe++)
760 if (pe->e_code == error)
762 snprintf(ebuf, sizeof(buf), "error %d", error);
767 * Send a nak packet (error message).
768 * Error code passed in is one of the
769 * standard TFTP codes, or a UNIX errno
779 tp = (struct tftphdr *)buf;
780 tp->th_opcode = htons((u_short)ERROR);
781 tp->th_code = htons((u_short)error);
782 for (pe = errmsgs; pe->e_code >= 0; pe++)
783 if (pe->e_code == error)
785 if (pe->e_code < 0) {
786 pe->e_msg = strerror(error - 100);
787 tp->th_code = EUNDEF; /* set 'undef' errorcode */
789 strcpy(tp->th_msg, pe->e_msg);
790 length = strlen(pe->e_msg);
791 tp->th_msg[length] = '\0';
793 if (send(peer, buf, length, 0) != length)
794 syslog(LOG_ERR, "nak: %m");
797 /* translate IPv4 mapped IPv6 address to IPv4 address */
799 unmappedaddr(struct sockaddr_in6 *sin6)
801 struct sockaddr_in *sin4;
805 if (sin6->sin6_family != AF_INET6 ||
806 !IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr))
808 sin4 = (struct sockaddr_in *)sin6;
809 addr = *(u_int32_t *)&sin6->sin6_addr.s6_addr[12];
810 port = sin6->sin6_port;
811 memset(sin4, 0, sizeof(struct sockaddr_in));
812 sin4->sin_addr.s_addr = addr;
813 sin4->sin_port = port;
814 sin4->sin_family = AF_INET;
815 sin4->sin_len = sizeof(struct sockaddr_in);
819 * Send an oack packet (option acknowledgement).
824 struct tftphdr *tp, *ap;
828 tp = (struct tftphdr *)buf;
830 size = sizeof(buf) - 2;
831 tp->th_opcode = htons((u_short)OACK);
832 for (i = 0; options[i].o_type != NULL; i++) {
833 if (options[i].o_request) {
834 n = snprintf(bp, size, "%s%c%d", options[i].o_type,
835 0, options[i].o_reply);
839 syslog(LOG_ERR, "oack: buffer overflow");
845 ap = (struct tftphdr *)ackbuf;
846 signal(SIGALRM, timer);
849 (void)setjmp(timeoutbuf);
850 if (send(peer, buf, size, 0) != size) {
851 syslog(LOG_INFO, "oack: %m");
857 n = recv(peer, ackbuf, sizeof (ackbuf), 0);
860 syslog(LOG_ERR, "recv: %m");
863 ap->th_opcode = ntohs((u_short)ap->th_opcode);
864 ap->th_block = ntohs((u_short)ap->th_block);
865 if (ap->th_opcode == ERROR)
867 if (ap->th_opcode == ACK && ap->th_block == 0)