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_in from;
94 void tftp(struct tftphdr *, int);
97 * Null-terminated directory prefix list for absolute pathname requests and
98 * search list for relative pathname requests.
100 * MAXDIRS should be at least as large as the number of arguments that
101 * inetd allows (currently 20).
104 static struct dirlist {
108 static int suppress_naks;
112 static char *errtomsg(int);
113 static void nak(int);
117 main(int argc, char *argv[])
122 struct sockaddr_in sin;
123 char *chroot_dir = NULL;
124 struct passwd *nobody;
125 char *chuser = "nobody";
127 openlog("tftpd", LOG_PID | LOG_NDELAY, LOG_FTP);
128 while ((ch = getopt(argc, argv, "cClns:u:")) != -1) {
149 syslog(LOG_WARNING, "ignoring unknown option -%c", ch);
153 struct dirlist *dirp;
155 /* Get list of directory prefixes. Skip relative pathnames. */
156 for (dirp = dirs; optind < argc && dirp < &dirs[MAXDIRS];
158 if (argv[optind][0] == '/') {
159 dirp->name = argv[optind];
160 dirp->len = strlen(dirp->name);
165 else if (chroot_dir) {
169 if (ipchroot && chroot_dir == NULL) {
170 syslog(LOG_ERR, "-c requires -s");
175 if (ioctl(0, FIONBIO, &on) < 0) {
176 syslog(LOG_ERR, "ioctl(FIONBIO): %m");
179 fromlen = sizeof (from);
180 n = recvfrom(0, buf, sizeof (buf), 0,
181 (struct sockaddr *)&from, &fromlen);
183 syslog(LOG_ERR, "recvfrom: %m");
187 * Now that we have read the message out of the UDP
188 * socket, we fork and exit. Thus, inetd will go back
189 * to listening to the tftp port, and the next request
190 * to come in will start up a new instance of tftpd.
192 * We do this so that inetd can run tftpd in "wait" mode.
193 * The problem with tftpd running in "nowait" mode is that
194 * inetd may get one or more successful "selects" on the
195 * tftp port before we do our receive, so more than one
196 * instance of tftpd may be started up. Worse, if tftpd
197 * break before doing the above "recvfrom", inetd would
198 * spawn endless instances, clogging the system.
204 for (i = 1; i < 20; i++) {
209 * flush out to most recently sent request.
211 * This may drop some request, but those
212 * will be resent by the clients when
213 * they timeout. The positive effect of
214 * this flush is to (try to) prevent more
215 * than one tftpd being started up to service
216 * a single request from a single client.
219 i = recvfrom(0, buf, sizeof (buf), 0,
220 (struct sockaddr *)&from, &j);
230 syslog(LOG_ERR, "fork: %m");
232 } else if (pid != 0) {
238 * Since we exit here, we should do that only after the above
239 * recvfrom to keep inetd from constantly forking should there
240 * be a problem. See the above comment about system clogging.
248 tempchroot = inet_ntoa(from.sin_addr);
249 asprintf(&tempchroot, "%s/%s", chroot_dir, tempchroot);
250 statret = stat(tempchroot, &sb);
251 if ((sb.st_mode & S_IFDIR) &&
252 (statret == 0 || (statret == -1 && ipchroot == 1)))
253 chroot_dir = tempchroot;
255 /* Must get this before chroot because /etc might go away */
256 if ((nobody = getpwnam(chuser)) == NULL) {
257 syslog(LOG_ERR, "%s: no such user", chuser);
260 if (chroot(chroot_dir)) {
261 syslog(LOG_ERR, "chroot: %s: %m", chroot_dir);
265 setuid(nobody->pw_uid);
266 setgroups(1, &nobody->pw_gid);
269 from.sin_family = AF_INET;
273 peer = socket(AF_INET, SOCK_DGRAM, 0);
275 syslog(LOG_ERR, "socket: %m");
278 memset(&sin, 0, sizeof(sin));
279 sin.sin_family = AF_INET;
280 if (bind(peer, (struct sockaddr *)&sin, sizeof (sin)) < 0) {
281 syslog(LOG_ERR, "bind: %m");
284 if (connect(peer, (struct sockaddr *)&from, sizeof(from)) < 0) {
285 syslog(LOG_ERR, "connect: %m");
288 tp = (struct tftphdr *)buf;
289 tp->th_opcode = ntohs(tp->th_opcode);
290 if (tp->th_opcode == RRQ || tp->th_opcode == WRQ)
296 int validate_access(char **, int);
297 void xmitfile(struct formats *);
298 void recvfile(struct formats *);
302 int (*f_validate)(char **, int);
303 void (*f_send)(struct formats *);
304 void (*f_recv)(struct formats *);
307 { "netascii", validate_access, xmitfile, recvfile, 1 },
308 { "octet", validate_access, xmitfile, recvfile, 0 },
310 { "mail", validate_user, sendmail, recvmail, 1 },
318 int o_reply; /* turn into union if need be */
320 { "tsize" }, /* OPT_TSIZE */
321 { "timeout" }, /* OPT_TIMEOUT */
331 * Handle initial connection protocol.
334 tftp(struct tftphdr *tp, int size)
337 int i, first = 1, has_options = 0, ecode;
339 char *filename, *mode, *option, *ccp;
341 filename = cp = tp->th_stuff;
343 while (cp < buf + size) {
357 for (cp = mode; *cp; cp++)
360 for (pf = formats; pf->f_mode; pf++)
361 if (strcmp(pf->f_mode, mode) == 0)
363 if (pf->f_mode == 0) {
367 while (++cp < buf + size) {
368 for (i = 2, ccp = cp; i > 0; ccp++) {
369 if (ccp >= buf + size) {
371 * Don't reject the request, just stop trying
372 * to parse the option and get on with it.
373 * Some Apple OpenFirmware versions have
374 * trailing garbage on the end of otherwise
378 } else if (*ccp == '\0')
381 for (option = cp; *cp; cp++)
384 for (i = 0; options[i].o_type != NULL; i++)
385 if (strcmp(option, options[i].o_type) == 0) {
386 options[i].o_request = ++cp;
393 if (options[OPT_TIMEOUT].o_request) {
394 int to = atoi(options[OPT_TIMEOUT].o_request);
395 if (to < 1 || to > 255) {
399 else if (to <= max_rexmtval)
400 options[OPT_TIMEOUT].o_reply = rexmtval = to;
402 options[OPT_TIMEOUT].o_request = NULL;
405 ecode = (*pf->f_validate)(&filename, tp->th_opcode);
409 char host[MAXHOSTNAMELEN];
411 realhostname(host, sizeof(host) - 1, &from.sin_addr);
412 host[sizeof(host) - 1] = '\0';
413 syslog(LOG_INFO, "%s: %s request for %s: %s", host,
414 tp->th_opcode == WRQ ? "write" : "read",
415 filename, errtomsg(ecode));
419 * Avoid storms of naks to a RRQ broadcast for a relative
420 * bootfile pathname from a diskless Sun.
422 if (suppress_naks && *filename != '/' && ecode == ENOTFOUND)
427 if (tp->th_opcode == WRQ)
438 * Validate file access. Since we
439 * have no uid or gid, for now require
440 * file to exist and be publicly
442 * If we were invoked with arguments
443 * from inetd then the file must also be
444 * in one of the given directory prefixes.
445 * Note also, full path name must be
446 * given as we have no login directory.
449 validate_access(char **filep, int mode)
453 struct dirlist *dirp;
454 static char pathname[MAXPATHLEN];
455 char *filename = *filep;
458 * Prevent tricksters from getting around the directory restrictions
460 if (strstr(filename, "/../"))
463 if (*filename == '/') {
465 * Allow the request if it's in one of the approved locations.
466 * Special case: check the null prefix ("/") by looking
467 * for length = 1 and relying on the arg. processing that
470 for (dirp = dirs; dirp->name != NULL; dirp++) {
471 if (dirp->len == 1 ||
472 (!strncmp(filename, dirp->name, dirp->len) &&
473 filename[dirp->len] == '/'))
476 /* If directory list is empty, allow access to any file */
477 if (dirp->name == NULL && dirp != dirs)
479 if (stat(filename, &stbuf) < 0)
480 return (errno == ENOENT ? ENOTFOUND : EACCESS);
481 if ((stbuf.st_mode & S_IFMT) != S_IFREG)
484 if ((stbuf.st_mode & S_IROTH) == 0)
487 if ((stbuf.st_mode & S_IWOTH) == 0)
494 * Relative file name: search the approved locations for it.
495 * Don't allow write requests that avoid directory
499 if (!strncmp(filename, "../", 3))
503 * If the file exists in one of the directories and isn't
504 * readable, continue looking. However, change the error code
505 * to give an indication that the file exists.
508 for (dirp = dirs; dirp->name != NULL; dirp++) {
509 snprintf(pathname, sizeof(pathname), "%s/%s",
510 dirp->name, filename);
511 if (stat(pathname, &stbuf) == 0 &&
512 (stbuf.st_mode & S_IFMT) == S_IFREG) {
513 if ((stbuf.st_mode & S_IROTH) != 0) {
519 if (dirp->name == NULL)
521 *filep = filename = pathname;
523 if (options[OPT_TSIZE].o_request) {
525 options[OPT_TSIZE].o_reply = stbuf.st_size;
527 /* XXX Allows writes of all sizes. */
528 options[OPT_TSIZE].o_reply =
529 atoi(options[OPT_TSIZE].o_request);
531 fd = open(filename, mode == RRQ ? O_RDONLY : O_WRONLY|O_TRUNC);
533 return (errno + 100);
534 file = fdopen(fd, (mode == RRQ)? "r":"w");
545 timer(int sig __unused)
547 if (++timeouts > MAX_TIMEOUTS)
549 longjmp(timeoutbuf, 1);
553 * Send the requested file.
556 xmitfile(struct formats *pf)
558 struct tftphdr *dp, *r_init();
559 struct tftphdr *ap; /* ack packet */
561 volatile unsigned short block;
563 signal(SIGALRM, timer);
565 ap = (struct tftphdr *)ackbuf;
568 size = readit(file, &dp, pf->f_convert);
573 dp->th_opcode = htons((u_short)DATA);
574 dp->th_block = htons((u_short)block);
576 (void)setjmp(timeoutbuf);
579 if (send(peer, dp, size + 4, 0) != size + 4) {
580 syslog(LOG_ERR, "write: %m");
583 read_ahead(file, pf->f_convert);
585 alarm(rexmtval); /* read the ack */
586 n = recv(peer, ackbuf, sizeof (ackbuf), 0);
589 syslog(LOG_ERR, "read: %m");
592 ap->th_opcode = ntohs((u_short)ap->th_opcode);
593 ap->th_block = ntohs((u_short)ap->th_block);
595 if (ap->th_opcode == ERROR)
598 if (ap->th_opcode == ACK) {
599 if (ap->th_block == block)
601 /* Re-synchronize with the other side */
602 (void) synchnet(peer);
603 if (ap->th_block == (block -1))
609 } while (size == SEGSIZE);
615 justquit(int sig __unused)
625 recvfile(struct formats *pf)
627 struct tftphdr *dp, *w_init();
628 struct tftphdr *ap; /* ack buffer */
630 volatile unsigned short block;
632 signal(SIGALRM, timer);
634 ap = (struct tftphdr *)ackbuf;
638 ap->th_opcode = htons((u_short)ACK);
639 ap->th_block = htons((u_short)block);
641 (void) setjmp(timeoutbuf);
643 if (send(peer, ackbuf, 4, 0) != 4) {
644 syslog(LOG_ERR, "write: %m");
647 write_behind(file, pf->f_convert);
650 n = recv(peer, dp, PKTSIZE, 0);
652 if (n < 0) { /* really? */
653 syslog(LOG_ERR, "read: %m");
656 dp->th_opcode = ntohs((u_short)dp->th_opcode);
657 dp->th_block = ntohs((u_short)dp->th_block);
658 if (dp->th_opcode == ERROR)
660 if (dp->th_opcode == DATA) {
661 if (dp->th_block == block) {
664 /* Re-synchronize with the other side */
665 (void) synchnet(peer);
666 if (dp->th_block == (block-1))
667 goto send_ack; /* rexmit */
670 /* size = write(file, dp->th_data, n - 4); */
671 size = writeit(file, &dp, n - 4, pf->f_convert);
672 if (size != (n-4)) { /* ahem */
673 if (size < 0) nak(errno + 100);
677 } while (size == SEGSIZE);
678 write_behind(file, pf->f_convert);
679 (void) fclose(file); /* close data file */
681 ap->th_opcode = htons((u_short)ACK); /* send the "final" ack */
682 ap->th_block = htons((u_short)(block));
683 (void) send(peer, ackbuf, 4, 0);
685 signal(SIGALRM, justquit); /* just quit on timeout */
687 n = recv(peer, buf, sizeof (buf), 0); /* normally times out and quits */
689 if (n >= 4 && /* if read some data */
690 dp->th_opcode == DATA && /* and got a data block */
691 block == dp->th_block) { /* then my last ack was lost */
692 (void) send(peer, ackbuf, 4, 0); /* resend final ack */
702 { EUNDEF, "Undefined error code" },
703 { ENOTFOUND, "File not found" },
704 { EACCESS, "Access violation" },
705 { ENOSPACE, "Disk full or allocation exceeded" },
706 { EBADOP, "Illegal TFTP operation" },
707 { EBADID, "Unknown transfer ID" },
708 { EEXISTS, "File already exists" },
709 { ENOUSER, "No such user" },
710 { EOPTNEG, "Option negotiation" },
721 for (pe = errmsgs; pe->e_code >= 0; pe++)
722 if (pe->e_code == error)
724 snprintf(buf, sizeof(buf), "error %d", error);
729 * Send a nak packet (error message).
730 * Error code passed in is one of the
731 * standard TFTP codes, or a UNIX errno
741 tp = (struct tftphdr *)buf;
742 tp->th_opcode = htons((u_short)ERROR);
743 tp->th_code = htons((u_short)error);
744 for (pe = errmsgs; pe->e_code >= 0; pe++)
745 if (pe->e_code == error)
747 if (pe->e_code < 0) {
748 pe->e_msg = strerror(error - 100);
749 tp->th_code = EUNDEF; /* set 'undef' errorcode */
751 strcpy(tp->th_msg, pe->e_msg);
752 length = strlen(pe->e_msg);
753 tp->th_msg[length] = '\0';
755 if (send(peer, buf, length, 0) != length)
756 syslog(LOG_ERR, "nak: %m");
760 * Send an oack packet (option acknowledgement).
765 struct tftphdr *tp, *ap;
769 tp = (struct tftphdr *)buf;
771 size = sizeof(buf) - 2;
772 tp->th_opcode = htons((u_short)OACK);
773 for (i = 0; options[i].o_type != NULL; i++) {
774 if (options[i].o_request) {
775 n = snprintf(bp, size, "%s%c%d", options[i].o_type,
776 0, options[i].o_reply);
780 syslog(LOG_ERR, "oack: buffer overflow");
786 ap = (struct tftphdr *)ackbuf;
787 signal(SIGALRM, timer);
790 (void)setjmp(timeoutbuf);
791 if (send(peer, buf, size, 0) != size) {
792 syslog(LOG_INFO, "oack: %m");
798 n = recv(peer, ackbuf, sizeof (ackbuf), 0);
801 syslog(LOG_ERR, "recv: %m");
804 ap->th_opcode = ntohs((u_short)ap->th_opcode);
805 ap->th_block = ntohs((u_short)ap->th_block);
806 if (ap->th_opcode == ERROR)
808 if (ap->th_opcode == ACK && ap->th_block == 0)