-> Clean up the use of autoconf macros a bit.
[tftp-hpa.git] / tftpd / tftpd.c
blob99692fbf206bd001381d4552cf7bff698c702f8a
1 /* tftp-hpa: $Id$ */
3 /* $OpenBSD: tftpd.c,v 1.13 1999/06/23 17:01:36 deraadt Exp $ */
5 /*
6 * Copyright (c) 1983 Regents of the University of California.
7 * All rights reserved.
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
11 * are met:
12 * 1. Redistributions of source code must retain the above copyright
13 * notice, this list of conditions and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the above copyright
15 * notice, this list of conditions and the following disclaimer in the
16 * documentation and/or other materials provided with the distribution.
17 * 3. All advertising materials mentioning features or use of this software
18 * must display the following acknowledgement:
19 * This product includes software developed by the University of
20 * California, Berkeley and its contributors.
21 * 4. Neither the name of the University nor the names of its contributors
22 * may be used to endorse or promote products derived from this software
23 * without specific prior written permission.
25 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
26 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
27 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
28 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
29 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
30 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
31 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
32 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
33 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
34 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
35 * SUCH DAMAGE.
38 #include "config.h" /* Must be included first */
39 #include "tftpd.h"
41 #ifndef lint
42 static const char *copyright UNUSED =
43 "@(#) Copyright (c) 1983 Regents of the University of California.\n\
44 All rights reserved.\n";
45 /*static char sccsid[] = "from: @(#)tftpd.c 5.13 (Berkeley) 2/26/91";*/
46 /*static char rcsid[] = "$OpenBSD: tftpd.c,v 1.13 1999/06/23 17:01:36 deraadt Exp $: tftpd.c,v 1.6 1997/02/16 23:49:21 deraadt Exp $";*/
47 static const char *rcsid UNUSED =
48 "tftp-hpa $Id$";
49 #endif /* not lint */
52 * Trivial file transfer protocol server.
54 * This version includes many modifications by Jim Guyton <guyton@rand-unix>
57 #include <sys/ioctl.h>
58 #include <signal.h>
59 #include <netdb.h>
60 #include <ctype.h>
61 #include <pwd.h>
62 #include <limits.h>
63 #include <syslog.h>
65 #include "tftpsubs.h"
66 #include "recvfrom.h"
67 #include "remap.h"
69 #ifdef HAVE_SYS_FILIO_H
70 #include <sys/filio.h> /* Necessary for FIONBIO on Solaris */
71 #endif
73 #ifdef HAVE_TCPWRAPPERS
74 #include <tcpd.h>
76 int deny_severity = LOG_WARNING;
77 int allow_severity = -1; /* Don't log at all */
79 struct request_info wrap_request;
80 #endif
82 #define TIMEOUT 5 /* Default timeout (seconds) */
83 #define TRIES 4 /* Number of attempts to send each packet */
84 #define TIMEOUT_LIMIT (TRIES*(TRIES+1)/2)
86 char *__progname;
87 int peer;
88 int timeout = TIMEOUT;
89 int rexmtval = TIMEOUT;
90 int maxtimeout = TIMEOUT_LIMIT*TIMEOUT;
92 #define PKTSIZE MAX_SEGSIZE+4
93 char buf[PKTSIZE];
94 char ackbuf[PKTSIZE];
95 struct sockaddr_in from;
96 int fromlen;
97 off_t tsize;
98 int tsize_ok;
100 int ndirs;
101 const char **dirs;
103 int secure = 0;
104 int cancreate = 0;
105 int unixperms = 0;
107 int verbosity = 0;
109 struct formats;
110 #ifdef WITH_REGEX
111 static struct rule *rewrite_rules = NULL;
112 #endif
114 int tftp(struct tftphdr *, int);
115 void nak(int);
116 void timer(int);
117 void justquit(int);
118 void do_opt(char *, char *, char **);
120 int set_blksize(char *, char **);
121 int set_blksize2(char *, char **);
122 int set_tsize(char *, char **);
123 int set_timeout(char *, char **);
125 struct options {
126 const char *o_opt;
127 int (*o_fnc)(char *, char **);
128 } options[] = {
129 { "blksize", set_blksize },
130 { "blksize2", set_blksize2 },
131 { "tsize", set_tsize },
132 { "timeout", set_timeout },
133 { NULL, NULL }
136 /* Simple handler for SIGHUP */
137 static volatile sig_atomic_t caught_sighup = 0;
138 static void handle_sighup(int sig)
140 (void)sig; /* Suppress unused warning */
141 caught_sighup = 1;
145 static void
146 usage(void)
148 syslog(LOG_ERR, "Usage: %s [-vcl][-a address][-m mappings][-u user][-t timeout][-r option...] [-s] [directory ...]",
149 __progname);
150 exit(EX_USAGE);
154 #ifdef WITH_REGEX
155 static struct rule *
156 read_remap_rules(const char *file)
158 FILE *f;
159 struct rule *rulep;
161 f = fopen(file, "rt");
162 if ( !f ) {
163 syslog(LOG_ERR, "Cannot open map file: %s: %m", file);
164 exit(EX_NOINPUT);
166 rulep = parserulefile(f);
167 fclose(f);
169 return rulep;
171 #endif
173 static inline void
174 set_socket_nonblock(int fd, int flag)
176 int err;
177 int flags;
178 #if defined(HAVE_FCNTL) && defined(HAVE_O_NONBLOCK_DEFINITION)
179 /* Posixly correct */
180 err = ((flags = fcntl(fd, F_GETFL, 0)) < 0) ||
181 (fcntl(fd, F_SETFL, flag ? flags|O_NONBLOCK : flags&~O_NONBLOCK) < 0);
182 #else
183 flags = flag ? 1 : 0;
184 err = (ioctl(fd, FIONBIO, &flags) < 0);
185 #endif
186 if ( err ) {
187 syslog(LOG_ERR, "Cannot set nonblock flag on socket: %m");
188 exit(EX_OSERR);
193 main(int argc, char **argv)
195 struct tftphdr *tp;
196 struct passwd *pw;
197 struct options *opt;
198 struct sockaddr_in myaddr;
199 struct sockaddr_in bindaddr;
200 int n;
201 int fd = 0;
202 int standalone = 0; /* Standalone (listen) mode */
203 char *address = NULL; /* Address to listen to */
204 pid_t pid;
205 mode_t my_umask = 0;
206 int spec_umask = 0;
207 int c;
208 int setrv;
209 int waittime = 900; /* Default time to wait for a connect*/
210 const char *user = "nobody"; /* Default user */
211 char *p, *ep;
212 #ifdef WITH_REGEX
213 char *rewrite_file = NULL;
214 #endif
216 /* basename() is way too much of a pain from a portability standpoint */
218 p = strrchr(argv[0], '/');
219 __progname = (p && p[1]) ? p+1 : argv[0];
221 openlog(__progname, LOG_PID|LOG_NDELAY, LOG_DAEMON);
223 while ((c = getopt(argc, argv, "cspvVla:u:U:r:t:m:")) != -1)
224 switch (c) {
225 case 'c':
226 cancreate = 1;
227 break;
228 case 's':
229 secure = 1;
230 break;
231 case 'p':
232 unixperms = 1;
233 break;
234 case 'l':
235 standalone = 1;
236 break;
237 case 'a':
238 address = optarg;
239 break;
240 case 't':
241 waittime = atoi(optarg);
242 break;
243 case 'u':
244 user = optarg;
245 break;
246 case 'U':
247 my_umask = strtoul(optarg, &ep, 8);
248 if ( *ep ) {
249 syslog(LOG_ERR, "Invalid umask: %s", optarg);
250 exit(EX_USAGE);
252 spec_umask = 1;
253 break;
254 case 'r':
255 for ( opt = options ; opt->o_opt ; opt++ ) {
256 if ( !strcasecmp(optarg, opt->o_opt) ) {
257 opt->o_opt = ""; /* Don't support this option */
258 break;
261 if ( !opt->o_opt ) {
262 syslog(LOG_ERR, "Unknown option: %s", optarg);
263 exit(EX_USAGE);
265 break;
266 #ifdef WITH_REGEX
267 case 'm':
268 if ( rewrite_file ) {
269 syslog(LOG_ERR, "Multiple -m options");
270 exit(EX_USAGE);
272 rewrite_file = optarg;
273 break;
274 #endif
275 case 'v':
276 verbosity++;
277 break;
278 case 'V':
279 /* Print configuration to stdout and exit */
280 printf("%s\n", TFTPD_CONFIG_STR);
281 exit(0);
282 break;
283 default:
284 usage();
285 break;
288 dirs = xmalloc((argc-optind+1)*sizeof(char *));
289 for ( ndirs = 0 ; optind != argc ; optind++ )
290 dirs[ndirs++] = argv[optind];
292 dirs[ndirs] = NULL;
294 if (secure) {
295 if (ndirs == 0) {
296 syslog(LOG_ERR, "no -s directory");
297 exit(EX_USAGE);
299 if (ndirs > 1) {
300 syslog(LOG_ERR, "too many -s directories");
301 exit(EX_USAGE);
303 if (chdir(dirs[0])) {
304 syslog(LOG_ERR, "%s: %m", dirs[0]);
305 exit(EX_NOINPUT);
309 pw = getpwnam(user);
310 if (!pw) {
311 syslog(LOG_ERR, "no user %s: %m", user);
312 exit(EX_NOUSER);
315 if ( spec_umask || !unixperms )
316 umask(my_umask);
318 /* Note: on Cygwin, select() on a nonblocking socket becomes
319 a nonblocking select. */
320 #ifndef __CYGWIN__
321 set_socket_nonblock(fd, 1);
322 #endif
324 #ifdef WITH_REGEX
325 if ( rewrite_file )
326 rewrite_rules = read_remap_rules(rewrite_file);
327 #endif
329 /* If we're running standalone, set up the input port */
330 if ( standalone ) {
331 fd = socket(PF_INET, SOCK_DGRAM, 0);
333 memset(&bindaddr, 0, sizeof bindaddr);
334 bindaddr.sin_family = AF_INET;
335 bindaddr.sin_addr.s_addr = INADDR_ANY;
336 bindaddr.sin_port = htons(IPPORT_TFTP);
338 if ( address ) {
339 char *portptr, *eportptr;
340 struct hostent *hostent;
341 struct servent *servent;
342 unsigned long port;
344 address = tfstrdup(address);
345 portptr = strrchr(address, ':');
346 if ( portptr )
347 *portptr++ = '\0';
349 if ( *address ) {
350 hostent = gethostbyname(address);
351 if ( !hostent || hostent->h_addrtype != AF_INET ) {
352 syslog(LOG_ERR, "cannot resolve local bind address: %s", address);
353 exit(EX_NOINPUT);
355 memcpy(&bindaddr.sin_addr, hostent->h_addr, hostent->h_length);
356 } else {
357 /* Default to using INADDR_ANY */
360 if ( portptr && *portptr ) {
361 servent = getservbyname(portptr, "udp");
362 if ( servent ) {
363 bindaddr.sin_port = servent->s_port;
364 } else if ( (port = strtoul(portptr, &eportptr, 0)) && !*eportptr ) {
365 bindaddr.sin_port = htons(port);
366 } else if ( !strcmp(portptr, "tftp") ) {
367 /* It's TFTP, we're OK */
368 } else {
369 syslog(LOG_ERR, "cannot resolve local bind port: %s", portptr);
370 exit(EX_NOINPUT);
375 if (bind(fd, (struct sockaddr *)&bindaddr, sizeof bindaddr) < 0) {
376 syslog(LOG_ERR, "cannot bind to local socket: %m");
377 exit(EX_OSERR);
380 /* Daemonize this process */
382 pid_t f = fork();
383 int nfd;
384 if ( f > 0 )
385 exit(0);
386 if ( f < 0 ) {
387 syslog(LOG_ERR, "cannot fork: %m");
388 exit(EX_OSERR);
390 nfd = open("/dev/null", O_RDWR);
391 if ( nfd >= 0 ) {
392 #ifdef HAVE_DUP2
393 dup2(nfd, 0);
394 dup2(nfd, 1);
395 dup2(nfd, 2);
396 #else
397 close(0); dup(nfd);
398 close(1); dup(nfd);
399 close(2); dup(nfd);
400 #endif
401 close(nfd);
402 } else {
403 close(0); close(1); close(2);
405 #ifdef HAVE_SETSID
406 #ifndef __CYGWIN__ /* Kills the process on Cygwin? */
407 setsid();
408 #endif
409 #endif
411 } else {
412 /* 0 is our socket descriptor */
413 close(1); close(2);
416 /* This means we don't want to wait() for children */
417 #ifdef SA_NOCLDWAIT
418 set_signal(SIGCHLD, SIG_IGN, SA_NOCLDSTOP|SA_NOCLDWAIT);
419 #else
420 set_signal(SIGCHLD, SIG_IGN, SA_NOCLDSTOP);
421 #endif
423 /* Take SIGHUP and use it to set a variable. This
424 is polled synchronously to make sure we don't
425 lose packets as a result. */
426 set_signal(SIGHUP, handle_sighup, 0);
428 while ( 1 ) {
429 fd_set readset;
430 struct timeval tv_waittime;
431 int rv;
433 if ( caught_sighup ) {
434 caught_sighup = 0;
435 if ( standalone ) {
436 #ifdef HAVE_REGEX
437 if ( rewrite_file ) {
438 freerules(rewrite_rules);
439 rewrite_rules = read_remap_rules(rewrite_file);
441 #endif
442 } else {
443 /* Return to inetd for respawn */
444 exit(0);
448 FD_ZERO(&readset);
449 FD_SET(fd, &readset);
450 tv_waittime.tv_sec = waittime;
451 tv_waittime.tv_usec = 0;
453 #ifdef __CYGWIN__
454 /* On Cygwin, select() on a nonblocking socket returns immediately,
455 with a rv of 0! */
456 set_socket_nonblock(fd, 0);
457 #endif
459 /* Never time out if we're in standalone mode */
460 rv = select(fd+1, &readset, NULL, NULL, standalone ? NULL : &tv_waittime);
461 if ( rv == -1 && errno == EINTR )
462 continue; /* Signal caught, reloop */
463 if ( rv == -1 ) {
464 syslog(LOG_ERR, "select loop: %m");
465 exit(EX_IOERR);
466 } else if ( rv == 0 ) {
467 exit(0); /* Timeout, return to inetd */
470 #ifdef __CYGWIN__
471 set_socket_nonblock(fd, 1);
472 #endif
474 fromlen = sizeof (from);
475 n = myrecvfrom(fd, buf, sizeof (buf), 0,
476 (struct sockaddr *)&from, &fromlen,
477 &myaddr);
479 if ( n < 0 ) {
480 if ( E_WOULD_BLOCK(errno) || errno == EINTR ) {
481 continue; /* Again, from the top */
482 } else {
483 syslog(LOG_ERR, "recvfrom: %m");
484 exit(EX_IOERR);
488 if ( standalone && myaddr.sin_addr.s_addr == INADDR_ANY ) {
489 /* myrecvfrom() didn't capture the source address; but we might
490 have bound to a specific address, if so we should use it */
491 memcpy(&myaddr.sin_addr, &bindaddr.sin_addr, sizeof bindaddr.sin_addr);
495 * Now that we have read the request packet from the UDP
496 * socket, we fork and go back to listening to the socket.
498 pid = fork();
499 if (pid < 0) {
500 syslog(LOG_ERR, "fork: %m");
501 exit(EX_OSERR); /* Return to inetd, just in case */
502 } else if ( pid == 0 )
503 break; /* Child exit, parent loop */
506 /* Child process: handle the actual request here */
508 /* Ignore SIGHUP */
509 set_signal(SIGHUP, SIG_IGN, 0);
511 #ifdef HAVE_TCPWRAPPERS
512 /* Verify if this was a legal request for us. This has to be
513 done before the chroot, while /etc is still accessible. */
514 request_init(&wrap_request,
515 RQ_DAEMON, __progname,
516 RQ_FILE, fd,
517 RQ_CLIENT_SIN, &from,
518 RQ_SERVER_SIN, &myaddr,
520 sock_methods(&wrap_request);
521 if ( hosts_access(&wrap_request) == 0 ) {
522 if ( deny_severity != -1 )
523 syslog(deny_severity, "connection refused from %s",
524 inet_ntoa(from.sin_addr));
525 exit(EX_NOPERM); /* Access denied */
526 } else if ( allow_severity != -1 ) {
527 syslog(allow_severity, "connect from %s",
528 inet_ntoa(from.sin_addr));
530 #endif
532 /* Close file descriptors we don't need */
533 close(fd);
535 /* Get a socket. This has to be done before the chroot(), since
536 some systems require access to /dev to create a socket. */
538 peer = socket(AF_INET, SOCK_DGRAM, 0);
539 if (peer < 0) {
540 syslog(LOG_ERR, "socket: %m");
541 exit(EX_IOERR);
544 /* Set up the supplementary group access list if possible */
545 /* /etc/group still need to be accessible at this point */
546 #ifdef HAVE_INITGROUPS
547 setrv = initgroups(user, pw->pw_gid);
548 if ( setrv ) {
549 syslog(LOG_ERR, "cannot set groups for user %s", user);
550 exit(EX_OSERR);
552 #else
553 #ifdef HAVE_SETGROUPS
554 if ( setgroups(0, NULL) ) {
555 syslog(LOG_ERR, "cannot clear group list");
557 #endif
558 #endif
560 /* Chroot and drop privileges */
562 if (secure && chroot(".")) {
563 syslog(LOG_ERR, "chroot: %m");
564 exit(EX_OSERR);
567 #ifdef __CYGWIN__
568 chdir("/"); /* Cygwin chroot() bug workaround */
569 #endif
571 #ifdef HAVE_SETREGID
572 setrv = setregid(pw->pw_gid, pw->pw_gid);
573 #else
574 setrv = setegid(pw->pw_gid) || setgid(pw->pw_gid);
575 #endif
577 #ifdef HAVE_SETREUID
578 setrv = setrv || setreuid(pw->pw_uid, pw->pw_uid);
579 #else
580 /* Important: setuid() must come first */
581 setrv = setrv || setuid(pw->pw_uid) ||
582 (geteuid() != pw->pw_uid && seteuid(pw->pw_uid));
583 #endif
585 if ( setrv ) {
586 syslog(LOG_ERR, "cannot drop privileges: %m");
587 exit(EX_OSERR);
590 /* Other basic setup */
591 from.sin_family = AF_INET;
592 alarm(0);
594 /* Process the request... */
596 myaddr.sin_port = htons(0); /* We want a new local port */
597 if (bind(peer, (struct sockaddr *)&myaddr, sizeof myaddr) < 0) {
598 syslog(LOG_ERR, "bind: %m");
599 exit(EX_IOERR);
601 if (connect(peer, (struct sockaddr *)&from, sizeof from) < 0) {
602 syslog(LOG_ERR, "connect: %m");
603 exit(EX_IOERR);
605 tp = (struct tftphdr *)buf;
606 tp->th_opcode = ntohs(tp->th_opcode);
607 if (tp->th_opcode == RRQ || tp->th_opcode == WRQ)
608 tftp(tp, n);
609 exit(0);
612 char *rewrite_access(char *, int);
613 int validate_access(char *, int, struct formats *);
614 void tftp_sendfile(struct formats *, struct tftphdr *, int);
615 void tftp_recvfile(struct formats *, struct tftphdr *, int);
617 struct formats {
618 const char *f_mode;
619 char *(*f_rewrite)(char *, int);
620 int (*f_validate)(char *, int, struct formats *);
621 void (*f_send)(struct formats *, struct tftphdr *, int);
622 void (*f_recv)(struct formats *, struct tftphdr *, int);
623 int f_convert;
624 } formats[] = {
625 { "netascii", rewrite_access, validate_access, tftp_sendfile, tftp_recvfile, 1 },
626 { "octet", rewrite_access, validate_access, tftp_sendfile, tftp_recvfile, 0 },
627 { NULL, NULL, NULL, NULL, NULL, 0 }
631 * Handle initial connection protocol.
634 tftp(struct tftphdr *tp, int size)
636 char *cp;
637 int argn, ecode;
638 struct formats *pf = NULL;
639 char *origfilename;
640 char *filename, *mode = NULL;
642 char *val = NULL, *opt = NULL;
643 char *ap = ackbuf + 2;
645 ((struct tftphdr *)ackbuf)->th_opcode = ntohs(OACK);
647 origfilename = cp = (char *) &(tp->th_stuff);
648 argn = 0;
650 while ( cp < buf + size && *cp ) {
651 do {
652 cp++;
653 } while (cp < buf + size && *cp);
655 if ( *cp ) {
656 nak(EBADOP); /* Corrupt packet - no final NULL */
657 exit(0);
660 argn++;
661 if (argn == 1) {
662 mode = ++cp;
663 } else if (argn == 2) {
664 for (cp = mode; *cp; cp++)
665 *cp = tolower(*cp);
666 for (pf = formats; pf->f_mode; pf++) {
667 if (!strcmp(pf->f_mode, mode))
668 break;
670 if (!pf->f_mode) {
671 nak(EBADOP);
672 exit(0);
674 if ( !(filename = (*pf->f_rewrite)(origfilename, tp->th_opcode)) ) {
675 nak(EACCESS); /* File denied by mapping rule */
676 exit(0);
678 if ( verbosity >= 1 ) {
679 if ( filename == origfilename || !strcmp(filename, origfilename) )
680 syslog(LOG_NOTICE, "%s from %s filename %s\n",
681 tp->th_opcode == WRQ ? "WRQ" : "RRQ",
682 inet_ntoa(from.sin_addr), filename);
683 else
684 syslog(LOG_NOTICE, "%s from %s filename %s remapped to %s\n",
685 tp->th_opcode == WRQ ? "WRQ" : "RRQ",
686 inet_ntoa(from.sin_addr), origfilename, filename);
688 ecode = (*pf->f_validate)(filename, tp->th_opcode, pf);
689 if (ecode) {
690 nak(ecode);
691 exit(0);
693 opt = ++cp;
694 } else if ( argn & 1 ) {
695 val = ++cp;
696 } else {
697 do_opt(opt, val, &ap);
698 opt = ++cp;
702 if (!pf) {
703 nak(EBADOP);
704 exit(0);
707 if ( ap != (ackbuf+2) ) {
708 if ( tp->th_opcode == WRQ )
709 (*pf->f_recv)(pf, (struct tftphdr *)ackbuf, ap-ackbuf);
710 else
711 (*pf->f_send)(pf, (struct tftphdr *)ackbuf, ap-ackbuf);
712 } else {
713 if (tp->th_opcode == WRQ)
714 (*pf->f_recv)(pf, NULL, 0);
715 else
716 (*pf->f_send)(pf, NULL, 0);
718 exit(0); /* Request completed */
721 static int blksize_set;
724 * Set a non-standard block size (c.f. RFC2348)
727 set_blksize(char *val, char **ret)
729 static char b_ret[6];
730 unsigned int sz;
731 char *vend;
733 sz = (unsigned int)strtoul(val, &vend, 10);
735 if ( blksize_set || *vend )
736 return 0;
738 if (sz < 8)
739 return(0);
740 else if (sz > MAX_SEGSIZE)
741 sz = MAX_SEGSIZE;
743 segsize = sz;
744 sprintf(*ret = b_ret, "%u", sz);
746 blksize_set = 1;
748 return(1);
752 * Set a power-of-two block size (nonstandard)
755 set_blksize2(char *val, char **ret)
757 static char b_ret[6];
758 unsigned int sz;
759 char *vend;
761 sz = (unsigned int)strtoul(val, &vend, 10);
763 if ( blksize_set || *vend )
764 return 0;
766 if (sz < 8)
767 return(0);
768 else if (sz > MAX_SEGSIZE)
769 sz = MAX_SEGSIZE;
771 /* Convert to a power of two */
772 if ( sz & (sz-1) ) {
773 unsigned int sz1 = 1;
774 /* Not a power of two - need to convert */
775 while ( sz >>= 1 )
776 sz1 <<= 1;
777 sz = sz1;
780 segsize = sz;
781 sprintf(*ret = b_ret, "%u", sz);
783 blksize_set = 1;
785 return(1);
789 * Return a file size (c.f. RFC2349)
790 * For netascii mode, we don't know the size ahead of time;
791 * so reject the option.
794 set_tsize(char *val, char **ret)
796 static char b_ret[sizeof(uintmax_t)*CHAR_BIT/3+2];
797 uintmax_t sz;
798 char *vend;
800 sz = strtoumax(val, &vend, 10);
802 if ( !tsize_ok || *vend )
803 return 0;
805 if (sz == 0)
806 sz = (uintmax_t)tsize;
808 sprintf(*ret = b_ret, "%"PRIuMAX, sz);
809 return(1);
813 * Set the timeout (c.f. RFC2349)
816 set_timeout(char *val, char **ret)
818 static char b_ret[4];
819 unsigned long to;
820 char *vend;
822 to = strtoul(val, &vend, 10);
824 if ( to < 1 || to > 255 || *vend )
825 return 0;
827 timeout = to;
828 rexmtval = to;
829 maxtimeout = TIMEOUT_LIMIT*to;
831 sprintf(*ret = b_ret, "%lu", to);
832 return(1);
836 * Parse RFC2347 style options
838 void
839 do_opt(char *opt, char *val, char **ap)
841 struct options *po;
842 char *ret;
844 /* Global option-parsing variables initialization */
845 blksize_set = 0;
847 if ( !*opt )
848 return;
850 for (po = options; po->o_opt; po++)
851 if (!strcasecmp(po->o_opt, opt)) {
852 if (po->o_fnc(val, &ret)) {
853 if (*ap + strlen(opt) + strlen(ret) + 2 >=
854 ackbuf + sizeof(ackbuf)) {
855 nak(ENOSPACE); /* EOPTNEG? */
856 exit(0);
858 *ap = strrchr(strcpy(strrchr(strcpy(*ap, opt),'\0') + 1,
859 ret),'\0') + 1;
860 } else {
861 nak(EOPTNEG);
862 exit(0);
864 break;
866 return;
869 #ifdef WITH_REGEX
872 * This is called by the remap engine when it encounters macros such
873 * as \i. It should write the output in "output" if non-NULL, and
874 * return the length of the output (generated or not).
876 * Return -1 on failure.
879 rewrite_macros(char macro, char *output);
882 rewrite_macros(char macro, char *output)
884 char *p;
886 switch (macro) {
887 case 'i':
888 p = inet_ntoa(from.sin_addr);
889 if ( output )
890 strcpy(output, p);
891 return strlen(p);
893 case 'x':
894 if ( output )
895 sprintf(output, "%08X",
896 ntohl(from.sin_addr.s_addr));
897 return 8;
899 default:
900 return -1;
905 * Modify the filename, if applicable. If it returns NULL, deny the access.
907 char *
908 rewrite_access(char *filename, int mode)
910 if ( rewrite_rules ) {
911 char *newname = rewrite_string(filename, rewrite_rules,
912 mode != RRQ, rewrite_macros);
913 filename = newname;
915 return filename;
918 #else
919 char *
920 rewrite_access(char *filename, int mode)
922 (void)mode; /* Avoid warning */
923 return filename;
925 #endif
927 FILE *file;
929 * Validate file access. Since we
930 * have no uid or gid, for now require
931 * file to exist and be publicly
932 * readable/writable, unless -p specified.
933 * If we were invoked with arguments
934 * from inetd then the file must also be
935 * in one of the given directory prefixes.
936 * Note also, full path name must be
937 * given as we have no login directory.
940 validate_access(char *filename, int mode, struct formats *pf)
942 struct stat stbuf;
943 int i, len;
944 int fd, wmode, rmode;
945 char *cp;
946 const char **dirp;
947 char stdio_mode[3];
949 tsize_ok = 0;
951 if (!secure) {
952 if (*filename != '/')
953 return (EACCESS);
955 * prevent tricksters from getting around the directory
956 * restrictions
958 len = strlen(filename);
959 for ( i = 1 ; i < len-3 ; i++ ) {
960 cp = filename + i;
961 if ( *cp == '.' && memcmp(cp-1, "/../", 4) == 0)
962 return(EACCESS);
965 for (dirp = dirs; *dirp; dirp++)
966 if (strncmp(filename, *dirp, strlen(*dirp)) == 0)
967 break;
968 if (*dirp==0 && dirp!=dirs)
969 return (EACCESS);
973 * We use different a different permissions scheme if `cancreate' is
974 * set.
976 wmode = O_WRONLY |
977 (cancreate ? O_CREAT : 0) |
978 (unixperms ? O_TRUNC : 0) |
979 (pf->f_convert ? O_TEXT : O_BINARY);
980 rmode = O_RDONLY |
981 (pf->f_convert ? O_TEXT : O_BINARY);
983 fd = open(filename, mode == RRQ ? rmode : wmode, 0666);
984 if (fd < 0) {
985 switch (errno) {
986 case ENOENT:
987 case ENOTDIR:
988 return ENOTFOUND;
989 case ENOSPC:
990 return ENOSPACE;
991 case EEXIST:
992 return EEXISTS;
993 default:
994 return EACCESS;
998 if ( fstat(fd, &stbuf) < 0 )
999 exit(EX_OSERR); /* This shouldn't happen */
1001 if (mode == RRQ) {
1002 if ( !unixperms && (stbuf.st_mode & (S_IREAD >> 6)) == 0 )
1003 return (EACCESS);
1004 tsize = stbuf.st_size;
1005 /* We don't know the tsize if conversion is needed */
1006 tsize_ok = !pf->f_convert;
1007 } else {
1008 if ( !unixperms ) {
1009 if ( (stbuf.st_mode & (S_IWRITE >> 6)) == 0 )
1010 return (EACCESS);
1012 /* We didn't get to truncate the file at open() time */
1013 #ifdef HAVE_FTRUNCATE
1014 if ( ftruncate(fd, (off_t)0) )
1015 return(EACCESS);
1016 #endif
1018 tsize = 0;
1019 tsize_ok = 1;
1022 stdio_mode[0] = (mode == RRQ) ? 'r':'w';
1023 stdio_mode[1] = (pf->f_convert) ? 't':'b';
1024 stdio_mode[2] = '\0';
1026 file = fdopen(fd, stdio_mode);
1027 if (file == NULL)
1028 exit(EX_OSERR); /* Internal error */
1030 return (0);
1033 int timeout;
1034 sigjmp_buf timeoutbuf;
1036 /* Handle timeout signal */
1037 void
1038 timer(int sig)
1040 (void)sig; /* Suppress unused warning */
1041 timeout += rexmtval;
1042 if (timeout >= maxtimeout)
1043 exit(0);
1044 siglongjmp(timeoutbuf, 1);
1048 * Send the requested file.
1050 void
1051 tftp_sendfile(struct formats *pf, struct tftphdr *oap, int oacklen)
1053 struct tftphdr *dp;
1054 struct tftphdr *ap; /* ack packet */
1055 static u_short block = 1; /* Static to avoid longjmp funnies */
1056 int size, n;
1058 ap = (struct tftphdr *)ackbuf;
1060 if (oap) {
1061 timeout = 0;
1062 (void)sigsetjmp(timeoutbuf,1);
1063 oack:
1064 if (send(peer, oap, oacklen, 0) != oacklen) {
1065 syslog(LOG_ERR, "tftpd: oack: %m\n");
1066 goto abort;
1068 for ( ; ; ) {
1069 set_signal(SIGALRM, timer, SA_RESTART);
1070 alarm(rexmtval);
1071 n = recv(peer, ackbuf, sizeof(ackbuf), 0);
1072 alarm(0);
1073 if (n < 0) {
1074 syslog(LOG_ERR, "tftpd: read: %m\n");
1075 goto abort;
1077 ap->th_opcode = ntohs((u_short)ap->th_opcode);
1078 ap->th_block = ntohs((u_short)ap->th_block);
1080 if (ap->th_opcode == ERROR) {
1081 syslog(LOG_ERR, "tftp: client does not accept "
1082 "options\n");
1083 goto abort;
1085 if (ap->th_opcode == ACK) {
1086 if (ap->th_block == 0)
1087 break;
1088 /* Resynchronize with the other side */
1089 (void)synchnet(peer);
1090 goto oack;
1095 dp = r_init();
1096 do {
1097 size = readit(file, &dp, pf->f_convert);
1098 if (size < 0) {
1099 nak(errno + 100);
1100 goto abort;
1102 dp->th_opcode = htons((u_short)DATA);
1103 dp->th_block = htons((u_short)block);
1104 timeout = 0;
1105 (void) sigsetjmp(timeoutbuf,1);
1107 if (send(peer, dp, size + 4, 0) != size + 4) {
1108 syslog(LOG_ERR, "tftpd: write: %m");
1109 goto abort;
1111 read_ahead(file, pf->f_convert);
1112 for ( ; ; ) {
1113 set_signal(SIGALRM, timer, SA_RESTART);
1114 alarm(rexmtval); /* read the ack */
1115 n = recv(peer, ackbuf, sizeof (ackbuf), 0);
1116 alarm(0);
1117 if (n < 0) {
1118 syslog(LOG_ERR, "tftpd: read(ack): %m");
1119 goto abort;
1121 ap->th_opcode = ntohs((u_short)ap->th_opcode);
1122 ap->th_block = ntohs((u_short)ap->th_block);
1124 if (ap->th_opcode == ERROR)
1125 goto abort;
1127 if (ap->th_opcode == ACK) {
1128 if (ap->th_block == block) {
1129 break;
1131 /* Re-synchronize with the other side */
1132 (void) synchnet(peer);
1134 * RFC1129/RFC1350: We MUST NOT re-send the DATA
1135 * packet in response to an invalid ACK. Doing so
1136 * would cause the Sorcerer's Apprentice bug.
1141 block++;
1142 } while (size == segsize);
1143 abort:
1144 (void) fclose(file);
1147 /* Bail out signal handler */
1148 void
1149 justquit(int sig)
1151 (void)sig; /* Suppress unused warning */
1152 exit(0);
1157 * Receive a file.
1159 void
1160 tftp_recvfile(struct formats *pf, struct tftphdr *oap, int oacklen)
1162 struct tftphdr *dp;
1163 int n, size;
1164 /* These are "static" to avoid longjmp funnies */
1165 static struct tftphdr *ap; /* ack buffer */
1166 static u_short block = 0;
1167 static int acksize;
1169 dp = w_init();
1170 do {
1171 timeout = 0;
1173 if (!block && oap) {
1174 ap = (struct tftphdr *)ackbuf;
1175 acksize = oacklen;
1176 } else {
1177 ap = (struct tftphdr *)ackbuf;
1178 ap->th_opcode = htons((u_short)ACK);
1179 ap->th_block = htons((u_short)block);
1180 acksize = 4;
1182 block++;
1183 (void) sigsetjmp(timeoutbuf,1);
1184 set_signal(SIGALRM, timer, SA_RESTART);
1185 send_ack:
1186 if (send(peer, ackbuf, acksize, 0) != acksize) {
1187 syslog(LOG_ERR, "tftpd: write(ack): %m");
1188 goto abort;
1190 write_behind(file, pf->f_convert);
1191 for ( ; ; ) {
1192 set_signal(SIGALRM, timer, SA_RESTART);
1193 alarm(rexmtval);
1194 n = recv(peer, dp, PKTSIZE, 0);
1195 alarm(0);
1196 if (n < 0) { /* really? */
1197 syslog(LOG_ERR, "tftpd: read: %m");
1198 goto abort;
1200 dp->th_opcode = ntohs((u_short)dp->th_opcode);
1201 dp->th_block = ntohs((u_short)dp->th_block);
1202 if (dp->th_opcode == ERROR)
1203 goto abort;
1204 if (dp->th_opcode == DATA) {
1205 if (dp->th_block == block) {
1206 break; /* normal */
1208 /* Re-synchronize with the other side */
1209 (void) synchnet(peer);
1210 if (dp->th_block == (block-1))
1211 goto send_ack; /* rexmit */
1214 /* size = write(file, dp->th_data, n - 4); */
1215 size = writeit(file, &dp, n - 4, pf->f_convert);
1216 if (size != (n-4)) { /* ahem */
1217 if (size < 0) nak(errno + 100);
1218 else nak(ENOSPACE);
1219 goto abort;
1221 } while (size == segsize);
1222 write_behind(file, pf->f_convert);
1223 (void) fclose(file); /* close data file */
1225 ap->th_opcode = htons((u_short)ACK); /* send the "final" ack */
1226 ap->th_block = htons((u_short)(block));
1227 (void) send(peer, ackbuf, 4, 0);
1229 set_signal(SIGALRM, justquit, 0); /* just quit on timeout */
1230 alarm(rexmtval);
1231 n = recv(peer, buf, sizeof (buf), 0); /* normally times out and quits */
1232 alarm(0);
1233 if (n >= 4 && /* if read some data */
1234 dp->th_opcode == DATA && /* and got a data block */
1235 block == dp->th_block) { /* then my last ack was lost */
1236 (void) send(peer, ackbuf, 4, 0); /* resend final ack */
1238 abort:
1239 return;
1242 struct errmsg {
1243 int e_code;
1244 const char *e_msg;
1245 } errmsgs[] = {
1246 { EUNDEF, "Undefined error code" },
1247 { ENOTFOUND, "File not found" },
1248 { EACCESS, "Access violation" },
1249 { ENOSPACE, "Disk full or allocation exceeded" },
1250 { EBADOP, "Illegal TFTP operation" },
1251 { EBADID, "Unknown transfer ID" },
1252 { EEXISTS, "File already exists" },
1253 { ENOUSER, "No such user" },
1254 { EOPTNEG, "Failure to negotiate RFC2347 options" },
1255 { -1, 0 }
1259 * Send a nak packet (error message).
1260 * Error code passed in is one of the
1261 * standard TFTP codes, or a UNIX errno
1262 * offset by 100.
1264 void
1265 nak(int error)
1267 struct tftphdr *tp;
1268 int length;
1269 struct errmsg *pe;
1271 tp = (struct tftphdr *)buf;
1272 tp->th_opcode = htons((u_short)ERROR);
1273 tp->th_code = htons((u_short)error);
1274 for (pe = errmsgs; pe->e_code >= 0; pe++)
1275 if (pe->e_code == error)
1276 break;
1277 if (pe->e_code < 0) {
1278 pe->e_msg = strerror(error - 100);
1279 tp->th_code = EUNDEF; /* set 'undef' errorcode */
1281 strcpy(tp->th_msg, pe->e_msg);
1282 length = strlen(pe->e_msg);
1283 tp->th_msg[length] = '\0';
1284 length += 5;
1286 if ( verbosity >= 2 ) {
1287 syslog(LOG_INFO, "sending NAK (%d, %s) to %s",
1288 error, tp->th_msg, inet_ntoa(from.sin_addr));
1291 if (send(peer, buf, length, 0) != length)
1292 syslog(LOG_ERR, "nak: %m");