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";
45 #include <sys/cdefs.h>
46 __FBSDID("$FreeBSD$");
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>
60 #include <netinet/in.h>
61 #include <arpa/tftp.h>
76 #include "tftp-file.h"
78 #include "tftp-utils.h"
79 #include "tftp-transfer.h"
80 #include "tftp-options.h"
82 static void tftp_wrq(int peer, char *, ssize_t);
83 static void tftp_rrq(int peer, char *, ssize_t);
86 * Null-terminated directory prefix list for absolute pathname requests and
87 * search list for relative pathname requests.
89 * MAXDIRS should be at least as large as the number of arguments that
90 * inetd allows (currently 20).
93 static struct dirlist {
97 static int suppress_naks;
100 static int create_new = 0;
101 static const char *newfile_format = "%Y%m%d";
102 static int increase_name = 0;
103 static mode_t mask = S_IWGRP | S_IWOTH;
106 static void tftp_recvfile(int peer, const char *mode);
107 static void tftp_xmitfile(int peer, const char *mode);
108 static int validate_access(int peer, char **, int);
109 static char peername[NI_MAXHOST];
113 static struct formats {
123 main(int argc, char *argv[])
127 socklen_t peerlen, len;
130 char *chroot_dir = NULL;
131 struct passwd *nobody;
132 const char *chuser = "nobody";
133 char recvbuffer[MAXPKTSIZE];
134 int allow_ro = 1, allow_wo = 1;
136 tzset(); /* syslog in localtime */
137 acting_as_client = 0;
139 tftp_openlog("tftpd", LOG_PID | LOG_NDELAY, LOG_FTP);
140 while ((ch = getopt(argc, argv, "cCd:F:lnoOp:s:u:U:wW")) != -1) {
149 if (atoi(optarg) != 0)
150 debug += atoi(optarg);
152 debug |= debug_finds(optarg);
155 newfile_format = optarg;
164 options_rfc_enabled = 0;
167 options_extra_enabled = 0;
170 packetdroppercentage = atoi(optarg);
172 "Randomly dropping %d out of 100 packets",
173 packetdroppercentage);
182 mask = strtol(optarg, NULL, 0);
192 tftp_log(LOG_WARNING,
193 "ignoring unknown option -%c", ch);
197 struct dirlist *dirp;
199 /* Get list of directory prefixes. Skip relative pathnames. */
200 for (dirp = dirs; optind < argc && dirp < &dirs[MAXDIRS];
202 if (argv[optind][0] == '/') {
203 dirp->name = argv[optind];
204 dirp->len = strlen(dirp->name);
209 else if (chroot_dir) {
213 if (ipchroot > 0 && chroot_dir == NULL) {
214 tftp_log(LOG_ERR, "-c requires -s");
222 if (ioctl(0, FIONBIO, &on) < 0) {
223 tftp_log(LOG_ERR, "ioctl(FIONBIO): %s", strerror(errno));
228 /* Find out who we are talking to and what we are going to do */
229 peerlen = sizeof(peer_sock);
230 n = recvfrom(0, recvbuffer, MAXPKTSIZE, 0,
231 (struct sockaddr *)&peer_sock, &peerlen);
233 tftp_log(LOG_ERR, "recvfrom: %s", strerror(errno));
236 getnameinfo((struct sockaddr *)&peer_sock, peer_sock.ss_len,
237 peername, sizeof(peername), NULL, 0, NI_NUMERICHOST);
240 * Now that we have read the message out of the UDP
241 * socket, we fork and exit. Thus, inetd will go back
242 * to listening to the tftp port, and the next request
243 * to come in will start up a new instance of tftpd.
245 * We do this so that inetd can run tftpd in "wait" mode.
246 * The problem with tftpd running in "nowait" mode is that
247 * inetd may get one or more successful "selects" on the
248 * tftp port before we do our receive, so more than one
249 * instance of tftpd may be started up. Worse, if tftpd
250 * break before doing the above "recvfrom", inetd would
251 * spawn endless instances, clogging the system.
256 for (i = 1; i < 20; i++) {
261 * flush out to most recently sent request.
263 * This may drop some request, but those
264 * will be resent by the clients when
265 * they timeout. The positive effect of
266 * this flush is to (try to) prevent more
267 * than one tftpd being started up to service
268 * a single request from a single client.
270 peerlen = sizeof peer_sock;
271 i = recvfrom(0, recvbuffer, MAXPKTSIZE, 0,
272 (struct sockaddr *)&peer_sock, &peerlen);
281 tftp_log(LOG_ERR, "fork: %s", strerror(errno));
283 } else if (pid != 0) {
289 * See if the client is allowed to talk to me.
290 * (This needs to be done before the chroot())
293 struct request_info req;
295 request_init(&req, RQ_CLIENT_ADDR, peername, 0);
296 request_set(&req, RQ_DAEMON, "tftpd", 0);
298 if (hosts_access(&req) == 0) {
299 if (debug&DEBUG_ACCESS)
300 tftp_log(LOG_WARNING,
301 "Access denied by 'tftpd' entry "
302 "in /etc/hosts.allow");
305 * Full access might be disabled, but maybe the
306 * client is allowed to do read-only access.
308 request_set(&req, RQ_DAEMON, "tftpd-ro", 0);
309 allow_ro = hosts_access(&req);
311 request_set(&req, RQ_DAEMON, "tftpd-wo", 0);
312 allow_wo = hosts_access(&req);
314 if (allow_ro == 0 && allow_wo == 0) {
315 tftp_log(LOG_WARNING,
316 "Unauthorized access from %s", peername);
320 if (debug&DEBUG_ACCESS) {
322 tftp_log(LOG_WARNING,
323 "But allowed readonly access "
324 "via 'tftpd-ro' entry");
326 tftp_log(LOG_WARNING,
327 "But allowed writeonly access "
328 "via 'tftpd-wo' entry");
331 if (debug&DEBUG_ACCESS)
332 tftp_log(LOG_WARNING,
333 "Full access allowed"
334 "in /etc/hosts.allow");
338 * Since we exit here, we should do that only after the above
339 * recvfrom to keep inetd from constantly forking should there
340 * be a problem. See the above comment about system clogging.
347 struct sockaddr_storage ss;
348 char hbuf[NI_MAXHOST];
351 memcpy(&ss, &peer_sock, peer_sock.ss_len);
352 unmappedaddr((struct sockaddr_in6 *)&ss);
353 getnameinfo((struct sockaddr *)&ss, ss.ss_len,
354 hbuf, sizeof(hbuf), NULL, 0,
356 asprintf(&tempchroot, "%s/%s", chroot_dir, hbuf);
358 statret = stat(tempchroot, &sb);
360 (statret == 0 && (sb.st_mode & S_IFDIR)))
361 chroot_dir = tempchroot;
363 /* Must get this before chroot because /etc might go away */
364 if ((nobody = getpwnam(chuser)) == NULL) {
365 tftp_log(LOG_ERR, "%s: no such user", chuser);
368 if (chroot(chroot_dir)) {
369 tftp_log(LOG_ERR, "chroot: %s: %s",
370 chroot_dir, strerror(errno));
374 setgroups(1, &nobody->pw_gid);
375 if (setuid(nobody->pw_uid) != 0) {
376 tftp_log(LOG_ERR, "setuid failed");
381 len = sizeof(me_sock);
382 if (getsockname(0, (struct sockaddr *)&me_sock, &len) == 0) {
383 switch (me_sock.ss_family) {
385 ((struct sockaddr_in *)&me_sock)->sin_port = 0;
388 ((struct sockaddr_in6 *)&me_sock)->sin6_port = 0;
395 memset(&me_sock, 0, sizeof(me_sock));
396 me_sock.ss_family = peer_sock.ss_family;
397 me_sock.ss_len = peer_sock.ss_len;
401 peer = socket(peer_sock.ss_family, SOCK_DGRAM, 0);
403 tftp_log(LOG_ERR, "socket: %s", strerror(errno));
406 if (bind(peer, (struct sockaddr *)&me_sock, me_sock.ss_len) < 0) {
407 tftp_log(LOG_ERR, "bind: %s", strerror(errno));
411 tp = (struct tftphdr *)recvbuffer;
412 tp->th_opcode = ntohs(tp->th_opcode);
413 if (tp->th_opcode == RRQ) {
415 tftp_rrq(peer, tp->th_stuff, n - 1);
417 tftp_log(LOG_WARNING,
418 "%s read access denied", peername);
422 if (tp->th_opcode == WRQ) {
424 tftp_wrq(peer, tp->th_stuff, n - 1);
426 tftp_log(LOG_WARNING,
427 "%s write access denied", peername);
435 reduce_path(char *fn)
439 /* Reduce all "/+./" to "/" (just in case we've got "/./../" later */
440 while ((slash = strstr(fn, "/./")) != NULL) {
441 for (ptr = slash; ptr > fn && ptr[-1] == '/'; ptr--)
448 /* Now reduce all "/something/+../" to "/" */
449 while ((slash = strstr(fn, "/../")) != NULL) {
452 for (ptr = slash; ptr > fn && ptr[-1] == '/'; ptr--)
454 for (ptr--; ptr >= fn; ptr--)
466 parse_header(int peer, char *recvbuffer, ssize_t size,
467 char **filename, char **mode)
476 i = get_field(peer, recvbuffer, size);
478 tftp_log(LOG_ERR, "Bad option - filename too long");
479 send_error(peer, EBADOP);
482 *filename = recvbuffer;
483 tftp_log(LOG_INFO, "Filename: '%s'", *filename);
486 i = get_field(peer, cp, size);
490 /* Find the file transfer mode */
491 for (cp = *mode; *cp; cp++)
494 for (pf = formats; pf->f_mode; pf++)
495 if (strcmp(pf->f_mode, *mode) == 0)
497 if (pf->f_mode == NULL) {
499 "Bad option - Unknown transfer mode (%s)", *mode);
500 send_error(peer, EBADOP);
503 tftp_log(LOG_INFO, "Mode: '%s'", *mode);
509 * WRQ - receive a file from the client
512 tftp_wrq(int peer, char *recvbuffer, ssize_t size)
515 int has_options = 0, ecode;
516 char *filename, *mode;
517 char fnbuf[PATH_MAX];
519 cp = parse_header(peer, recvbuffer, size, &filename, &mode);
520 size -= (cp - recvbuffer) + 1;
522 strcpy(fnbuf, filename);
527 if (options_rfc_enabled)
528 has_options = !parse_options(peer, cp, size);
530 tftp_log(LOG_INFO, "Options found but not enabled");
533 ecode = validate_access(peer, &filename, WRQ);
541 tftp_log(LOG_INFO, "%s: write request for %s: %s", peername,
542 filename, errtomsg(ecode));
545 tftp_recvfile(peer, mode);
550 * RRQ - send a file to the client
553 tftp_rrq(int peer, char *recvbuffer, ssize_t size)
556 int has_options = 0, ecode;
557 char *filename, *mode;
558 char fnbuf[PATH_MAX];
560 cp = parse_header(peer, recvbuffer, size, &filename, &mode);
561 size -= (cp - recvbuffer) + 1;
563 strcpy(fnbuf, filename);
568 if (options_rfc_enabled)
569 has_options = !parse_options(peer, cp, size);
571 tftp_log(LOG_INFO, "Options found but not enabled");
574 ecode = validate_access(peer, &filename, RRQ);
578 char lrecvbuffer[MAXPKTSIZE];
579 struct tftphdr *rp = (struct tftphdr *)lrecvbuffer;
582 n = receive_packet(peer, lrecvbuffer, MAXPKTSIZE,
583 NULL, timeoutpacket);
585 if (debug&DEBUG_SIMPLE)
586 tftp_log(LOG_DEBUG, "Aborting: %s",
590 if (rp->th_opcode != ACK) {
591 if (debug&DEBUG_SIMPLE)
593 "Expected ACK, got %s on OACK",
594 packettype(rp->th_opcode));
601 tftp_log(LOG_INFO, "%s: read request for %s: %s", peername,
602 filename, errtomsg(ecode));
606 * Avoid storms of naks to a RRQ broadcast for a relative
607 * bootfile pathname from a diskless Sun.
609 if (suppress_naks && *filename != '/' && ecode == ENOTFOUND)
611 send_error(peer, ecode);
614 tftp_xmitfile(peer, mode);
618 * Find the next value for YYYYMMDD.nn when the file to be written should
619 * be unique. Due to the limitations of nn, we will fail if nn reaches 100.
620 * Besides, that is four updates per hour on a file, which is kind of
624 find_next_name(char *filename, int *fd)
630 char yyyymmdd[MAXPATHLEN];
631 char newname[MAXPATHLEN];
633 /* Create the YYYYMMDD part of the filename */
635 lt = *localtime(&tval);
636 len = strftime(yyyymmdd, sizeof(yyyymmdd), newfile_format, <);
639 "Filename suffix too long (%d characters maximum)",
644 /* Make sure the new filename is not too long */
645 if (strlen(filename) > MAXPATHLEN - len - 5) {
647 "Filename too long (%zd characters, %zd maximum)",
648 strlen(filename), MAXPATHLEN - len - 5);
652 /* Find the first file which doesn't exist */
653 for (i = 0; i < 100; i++) {
654 sprintf(newname, "%s.%s.%02d", filename, yyyymmdd, i);
656 O_WRONLY | O_CREAT | O_EXCL,
657 S_IRUSR | S_IWUSR | S_IRGRP |
658 S_IWGRP | S_IROTH | S_IWOTH);
667 * Validate file access. Since we
668 * have no uid or gid, for now require
669 * file to exist and be publicly
671 * If we were invoked with arguments
672 * from inetd then the file must also be
673 * in one of the given directory prefixes.
674 * Note also, full path name must be
675 * given as we have no login directory.
678 validate_access(int peer, char **filep, int mode)
683 struct dirlist *dirp;
684 static char pathname[MAXPATHLEN];
685 char *filename = *filep;
688 * Prevent tricksters from getting around the directory restrictions
690 if (strstr(filename, "/../"))
693 if (*filename == '/') {
695 * Allow the request if it's in one of the approved locations.
696 * Special case: check the null prefix ("/") by looking
697 * for length = 1 and relying on the arg. processing that
700 for (dirp = dirs; dirp->name != NULL; dirp++) {
701 if (dirp->len == 1 ||
702 (!strncmp(filename, dirp->name, dirp->len) &&
703 filename[dirp->len] == '/'))
706 /* If directory list is empty, allow access to any file */
707 if (dirp->name == NULL && dirp != dirs)
709 if (stat(filename, &stbuf) < 0)
710 return (errno == ENOENT ? ENOTFOUND : EACCESS);
711 if ((stbuf.st_mode & S_IFMT) != S_IFREG)
714 if ((stbuf.st_mode & S_IROTH) == 0)
717 if ((stbuf.st_mode & S_IWOTH) == 0)
724 * Relative file name: search the approved locations for it.
725 * Don't allow write requests that avoid directory
729 if (!strncmp(filename, "../", 3))
733 * If the file exists in one of the directories and isn't
734 * readable, continue looking. However, change the error code
735 * to give an indication that the file exists.
738 for (dirp = dirs; dirp->name != NULL; dirp++) {
739 snprintf(pathname, sizeof(pathname), "%s/%s",
740 dirp->name, filename);
741 if (stat(pathname, &stbuf) == 0 &&
742 (stbuf.st_mode & S_IFMT) == S_IFREG) {
743 if ((stbuf.st_mode & S_IROTH) != 0) {
749 if (dirp->name != NULL)
750 *filep = filename = pathname;
751 else if (mode == RRQ)
756 * This option is handled here because it (might) require(s) the
759 option_tsize(peer, NULL, mode, &stbuf);
762 fd = open(filename, O_RDONLY);
766 error = find_next_name(filename, &fd);
768 return (error + 100);
771 O_WRONLY | O_TRUNC | O_CREAT,
772 S_IRUSR | S_IWUSR | S_IRGRP |
773 S_IWGRP | S_IROTH | S_IWOTH );
775 fd = open(filename, O_WRONLY | O_TRUNC);
778 return (errno + 100);
779 file = fdopen(fd, (mode == RRQ)? "r":"w");
782 return (errno + 100);
788 tftp_xmitfile(int peer, const char *mode)
792 struct tftp_stats ts;
795 if (debug&DEBUG_SIMPLE)
796 tftp_log(LOG_DEBUG, "Transmitting file");
798 read_init(0, file, mode);
800 tftp_send(peer, &block, &ts);
802 if (debug&DEBUG_SIMPLE)
803 tftp_log(LOG_INFO, "Sent %jd bytes in %jd seconds",
804 (intmax_t)ts.amount, (intmax_t)time(NULL) - now);
808 tftp_recvfile(int peer, const char *mode)
811 struct timeval now1, now2;
812 struct tftp_stats ts;
814 gettimeofday(&now1, NULL);
815 if (debug&DEBUG_SIMPLE)
816 tftp_log(LOG_DEBUG, "Receiving file");
818 write_init(0, file, mode);
821 tftp_receive(peer, &block, &ts, NULL, 0);
824 gettimeofday(&now2, NULL);
826 if (debug&DEBUG_SIMPLE) {
828 if (now1.tv_usec > now2.tv_usec) {
829 now2.tv_usec += 1000000;
833 f = now2.tv_sec - now1.tv_sec +
834 (now2.tv_usec - now1.tv_usec) / 100000.0;
836 "Download of %jd bytes in %d blocks completed after %0.1f seconds\n",
837 (intmax_t)ts.amount, block, f);