Add Hama WLAN PCI Card 54 Mbps to recognized cards. Bump date.
[netbsd-mini2440.git] / libexec / tftpd / tftpd.c
blob405f079f61926bae6233d07eb6731f640cdaee52
1 /* $NetBSD: tftpd.c,v 1.31 2008/07/21 13:25:47 lukem Exp $ */
3 /*
4 * Copyright (c) 1983, 1993
5 * The Regents of the University of California. All rights reserved.
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
9 * are met:
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
15 * 3. Neither the name of the University nor the names of its contributors
16 * may be used to endorse or promote products derived from this software
17 * without specific prior written permission.
19 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
20 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29 * SUCH DAMAGE.
32 #include <sys/cdefs.h>
33 #ifndef lint
34 __COPYRIGHT("@(#) Copyright (c) 1983, 1993\
35 The Regents of the University of California. All rights reserved.");
36 #if 0
37 static char sccsid[] = "@(#)tftpd.c 8.1 (Berkeley) 6/4/93";
38 #else
39 __RCSID("$NetBSD: tftpd.c,v 1.31 2008/07/21 13:25:47 lukem Exp $");
40 #endif
41 #endif /* not lint */
44 * Trivial file transfer protocol server.
46 * This version includes many modifications by Jim Guyton
47 * <guyton@rand-unix>.
50 #include <sys/param.h>
51 #include <sys/ioctl.h>
52 #include <sys/stat.h>
53 #include <sys/socket.h>
55 #include <netinet/in.h>
56 #include <arpa/tftp.h>
57 #include <arpa/inet.h>
59 #include <ctype.h>
60 #include <errno.h>
61 #include <fcntl.h>
62 #include <grp.h>
63 #include <netdb.h>
64 #include <pwd.h>
65 #include <setjmp.h>
66 #include <signal.h>
67 #include <stdio.h>
68 #include <stdlib.h>
69 #include <string.h>
70 #include <syslog.h>
71 #include <time.h>
72 #include <unistd.h>
74 #include "tftpsubs.h"
76 #define DEFAULTUSER "nobody"
78 #define TIMEOUT 5
80 int peer;
81 int rexmtval = TIMEOUT;
82 int maxtimeout = 5*TIMEOUT;
84 char buf[MAXPKTSIZE];
85 char ackbuf[PKTSIZE];
86 char oackbuf[PKTSIZE];
87 struct sockaddr_storage from;
88 socklen_t fromlen;
89 int debug;
91 int tftp_opt_tsize = 0;
92 int tftp_blksize = SEGSIZE;
93 int tftp_tsize = 0;
96 * Null-terminated directory prefix list for absolute pathname requests and
97 * search list for relative pathname requests.
99 * MAXDIRS should be at least as large as the number of arguments that
100 * inetd allows (currently 20).
102 #define MAXDIRS 20
103 static struct dirlist {
104 char *name;
105 int len;
106 } dirs[MAXDIRS+1];
107 static int suppress_naks;
108 static int logging;
109 static int secure;
110 static char *securedir;
112 struct formats;
114 static const char *errtomsg(int);
115 static void nak(int);
116 static void tftp(struct tftphdr *, int);
117 static void usage(void);
118 static char *verifyhost(struct sockaddr *);
119 void justquit(int);
120 int main(int, char **);
121 void recvfile(struct formats *, int, int);
122 void sendfile(struct formats *, int, int);
123 void timer(int);
124 static const char *opcode(int);
125 int validate_access(char **, int);
127 struct formats {
128 const char *f_mode;
129 int (*f_validate)(char **, int);
130 void (*f_send)(struct formats *, int, int);
131 void (*f_recv)(struct formats *, int, int);
132 int f_convert;
133 } formats[] = {
134 { "netascii", validate_access, sendfile, recvfile, 1 },
135 { "octet", validate_access, sendfile, recvfile, 0 },
136 { 0 }
139 static void
140 usage(void)
143 syslog(LOG_ERR,
144 "Usage: %s [-dln] [-u user] [-g group] [-s directory] [directory ...]",
145 getprogname());
146 exit(1);
150 main(int argc, char *argv[])
152 struct sockaddr_storage me;
153 struct passwd *pwent;
154 struct group *grent;
155 struct tftphdr *tp;
156 char *tgtuser, *tgtgroup, *ep;
157 int n, ch, on, fd;
158 int soopt;
159 socklen_t len;
160 uid_t curuid, tgtuid;
161 gid_t curgid, tgtgid;
162 long nid;
164 n = 0;
165 fd = 0;
166 tzset();
167 openlog("tftpd", LOG_PID | LOG_NDELAY, LOG_DAEMON);
168 tgtuser = DEFAULTUSER;
169 tgtgroup = NULL;
170 curuid = getuid();
171 curgid = getgid();
173 while ((ch = getopt(argc, argv, "dg:lns:u:")) != -1)
174 switch (ch) {
175 case 'd':
176 debug++;
177 break;
179 case 'g':
180 tgtgroup = optarg;
181 break;
183 case 'l':
184 logging = 1;
185 break;
187 case 'n':
188 suppress_naks = 1;
189 break;
191 case 's':
192 secure = 1;
193 securedir = optarg;
194 break;
196 case 'u':
197 tgtuser = optarg;
198 break;
200 default:
201 usage();
202 break;
205 if (optind < argc) {
206 struct dirlist *dirp;
208 /* Get list of directory prefixes. Skip relative pathnames. */
209 for (dirp = dirs; optind < argc && dirp < &dirs[MAXDIRS];
210 optind++) {
211 if (argv[optind][0] == '/') {
212 dirp->name = argv[optind];
213 dirp->len = strlen(dirp->name);
214 dirp++;
219 if (*tgtuser == '\0' || (tgtgroup != NULL && *tgtgroup == '\0'))
220 usage();
222 nid = (strtol(tgtuser, &ep, 10));
223 if (*ep == '\0') {
224 if (nid > UID_MAX) {
225 syslog(LOG_ERR, "uid %ld is too large", nid);
226 exit(1);
228 pwent = getpwuid((uid_t)nid);
229 } else
230 pwent = getpwnam(tgtuser);
231 if (pwent == NULL) {
232 syslog(LOG_ERR, "unknown user `%s'", tgtuser);
233 exit(1);
235 tgtuid = pwent->pw_uid;
236 tgtgid = pwent->pw_gid;
238 if (tgtgroup != NULL) {
239 nid = (strtol(tgtgroup, &ep, 10));
240 if (*ep == '\0') {
241 if (nid > GID_MAX) {
242 syslog(LOG_ERR, "gid %ld is too large", nid);
243 exit(1);
245 grent = getgrgid((gid_t)nid);
246 } else
247 grent = getgrnam(tgtgroup);
248 if (grent != NULL)
249 tgtgid = grent->gr_gid;
250 else {
251 syslog(LOG_ERR, "unknown group `%s'", tgtgroup);
252 exit(1);
256 if (secure) {
257 if (chdir(securedir) < 0) {
258 syslog(LOG_ERR, "chdir %s: %m", securedir);
259 exit(1);
261 if (chroot(".")) {
262 syslog(LOG_ERR, "chroot: %m");
263 exit(1);
267 if (logging)
268 syslog(LOG_DEBUG, "running as user `%s' (%d), group `%s' (%d)",
269 tgtuser, tgtuid, tgtgroup ? tgtgroup : "(unspecified)",
270 tgtgid);
271 if (curgid != tgtgid) {
272 if (setgid(tgtgid)) {
273 syslog(LOG_ERR, "setgid to %d: %m", (int)tgtgid);
274 exit(1);
276 if (setgroups(0, NULL)) {
277 syslog(LOG_ERR, "setgroups: %m");
278 exit(1);
282 if (curuid != tgtuid) {
283 if (setuid(tgtuid)) {
284 syslog(LOG_ERR, "setuid to %d: %m", (int)tgtuid);
285 exit(1);
289 on = 1;
290 if (ioctl(fd, FIONBIO, &on) < 0) {
291 syslog(LOG_ERR, "ioctl(FIONBIO): %m");
292 exit(1);
294 fromlen = sizeof (from);
295 n = recvfrom(fd, buf, sizeof (buf), 0,
296 (struct sockaddr *)&from, &fromlen);
297 if (n < 0) {
298 syslog(LOG_ERR, "recvfrom: %m");
299 exit(1);
302 * Now that we have read the message out of the UDP
303 * socket, we fork and exit. Thus, inetd will go back
304 * to listening to the tftp port, and the next request
305 * to come in will start up a new instance of tftpd.
307 * We do this so that inetd can run tftpd in "wait" mode.
308 * The problem with tftpd running in "nowait" mode is that
309 * inetd may get one or more successful "selects" on the
310 * tftp port before we do our receive, so more than one
311 * instance of tftpd may be started up. Worse, if tftpd
312 * break before doing the above "recvfrom", inetd would
313 * spawn endless instances, clogging the system.
316 int pid;
317 int i;
318 socklen_t j;
320 for (i = 1; i < 20; i++) {
321 pid = fork();
322 if (pid < 0) {
323 sleep(i);
325 * flush out to most recently sent request.
327 * This may drop some request, but those
328 * will be resent by the clients when
329 * they timeout. The positive effect of
330 * this flush is to (try to) prevent more
331 * than one tftpd being started up to service
332 * a single request from a single client.
334 j = sizeof from;
335 i = recvfrom(fd, buf, sizeof (buf), 0,
336 (struct sockaddr *)&from, &j);
337 if (i > 0) {
338 n = i;
339 fromlen = j;
341 } else {
342 break;
345 if (pid < 0) {
346 syslog(LOG_ERR, "fork: %m");
347 exit(1);
348 } else if (pid != 0) {
349 exit(0);
354 * remember what address this was sent to, so we can respond on the
355 * same interface
357 len = sizeof(me);
358 if (getsockname(fd, (struct sockaddr *)&me, &len) == 0) {
359 switch (me.ss_family) {
360 case AF_INET:
361 ((struct sockaddr_in *)&me)->sin_port = 0;
362 break;
363 case AF_INET6:
364 ((struct sockaddr_in6 *)&me)->sin6_port = 0;
365 break;
366 default:
367 /* unsupported */
368 break;
370 } else {
371 memset(&me, 0, sizeof(me));
372 me.ss_family = from.ss_family;
373 me.ss_len = from.ss_len;
376 alarm(0);
377 close(fd);
378 close(1);
379 peer = socket(from.ss_family, SOCK_DGRAM, 0);
380 if (peer < 0) {
381 syslog(LOG_ERR, "socket: %m");
382 exit(1);
384 if (bind(peer, (struct sockaddr *)&me, me.ss_len) < 0) {
385 syslog(LOG_ERR, "bind: %m");
386 exit(1);
388 if (connect(peer, (struct sockaddr *)&from, from.ss_len) < 0) {
389 syslog(LOG_ERR, "connect: %m");
390 exit(1);
392 soopt = 65536; /* larger than we'll ever need */
393 if (setsockopt(peer, SOL_SOCKET, SO_SNDBUF, (void *) &soopt, sizeof(soopt)) < 0) {
394 syslog(LOG_ERR, "set SNDBUF: %m");
395 exit(1);
397 if (setsockopt(peer, SOL_SOCKET, SO_RCVBUF, (void *) &soopt, sizeof(soopt)) < 0) {
398 syslog(LOG_ERR, "set RCVBUF: %m");
399 exit(1);
402 tp = (struct tftphdr *)buf;
403 tp->th_opcode = ntohs(tp->th_opcode);
404 if (tp->th_opcode == RRQ || tp->th_opcode == WRQ)
405 tftp(tp, n);
406 exit(1);
409 static int
410 blk_handler(struct tftphdr *tp, char *opt, char *val, char *ack,
411 int *ackl, int *ec)
413 unsigned long bsize;
414 char *endp;
415 int l;
418 * On these failures, we could just ignore the blocksize option.
419 * Perhaps that should be a command-line option.
421 errno = 0;
422 bsize = strtoul(val, &endp, 10);
423 if ((bsize == ULONG_MAX && errno == ERANGE) || *endp) {
424 syslog(LOG_NOTICE, "%s: %s request for %s: "
425 "illegal value %s for blksize option",
426 verifyhost((struct sockaddr *)&from),
427 tp->th_opcode == WRQ ? "write" : "read",
428 tp->th_stuff, val);
429 return 0;
431 if (bsize < 8 || bsize > 65464) {
432 syslog(LOG_NOTICE, "%s: %s request for %s: "
433 "out of range value %s for blksize option",
434 verifyhost((struct sockaddr *)&from),
435 tp->th_opcode == WRQ ? "write" : "read",
436 tp->th_stuff, val);
437 return 0;
440 tftp_blksize = bsize;
441 strcpy(ack + *ackl, "blksize");
442 *ackl += 8;
443 l = sprintf(ack + *ackl, "%lu", bsize);
444 *ackl += l + 1;
446 return 0;
449 static int
450 timeout_handler(struct tftphdr *tp, char *opt, char *val, char *ack,
451 int *ackl, int *ec)
453 unsigned long tout;
454 char *endp;
455 int l;
457 errno = 0;
458 tout = strtoul(val, &endp, 10);
459 if ((tout == ULONG_MAX && errno == ERANGE) || *endp) {
460 syslog(LOG_NOTICE, "%s: %s request for %s: "
461 "illegal value %s for timeout option",
462 verifyhost((struct sockaddr *)&from),
463 tp->th_opcode == WRQ ? "write" : "read",
464 tp->th_stuff, val);
465 return 0;
467 if (tout < 1 || tout > 255) {
468 syslog(LOG_NOTICE, "%s: %s request for %s: "
469 "out of range value %s for timeout option",
470 verifyhost((struct sockaddr *)&from),
471 tp->th_opcode == WRQ ? "write" : "read",
472 tp->th_stuff, val);
473 return 0;
476 rexmtval = tout;
477 strcpy(ack + *ackl, "timeout");
478 *ackl += 8;
479 l = sprintf(ack + *ackl, "%lu", tout);
480 *ackl += l + 1;
483 * Arbitrarily pick a maximum timeout on a request to 3
484 * retransmissions if the interval timeout is more than
485 * one minute. Longest possible timeout is therefore
486 * 3 * 255 - 1, or 764 seconds.
488 if (rexmtval > 60) {
489 maxtimeout = rexmtval * 3;
490 } else {
491 maxtimeout = rexmtval * 5;
494 return 0;
497 static int
498 tsize_handler(struct tftphdr *tp, char *opt, char *val, char *ack,
499 int *ackl, int *ec)
501 unsigned long fsize;
502 char *endp;
505 * Maximum file even with extended tftp is 65535 blocks of
506 * length 65464, or 4290183240 octets (4784056 less than 2^32).
507 * unsigned long is at least 32 bits on all NetBSD archs.
510 errno = 0;
511 fsize = strtoul(val, &endp, 10);
512 if ((fsize == ULONG_MAX && errno == ERANGE) || *endp) {
513 syslog(LOG_NOTICE, "%s: %s request for %s: "
514 "illegal value %s for tsize option",
515 verifyhost((struct sockaddr *)&from),
516 tp->th_opcode == WRQ ? "write" : "read",
517 tp->th_stuff, val);
518 return 0;
520 if (fsize > (unsigned long) 65535 * 65464) {
521 syslog(LOG_NOTICE, "%s: %s request for %s: "
522 "out of range value %s for tsize option",
523 verifyhost((struct sockaddr *)&from),
524 tp->th_opcode == WRQ ? "write" : "read",
525 tp->th_stuff, val);
526 return 0;
529 tftp_opt_tsize = 1;
530 tftp_tsize = fsize;
532 * We will report this later -- either replying with the fsize (WRQ)
533 * or replying with the actual filesize (RRQ).
536 return 0;
539 struct tftp_options {
540 char *o_name;
541 int (*o_handler)(struct tftphdr *, char *, char *, char *,
542 int *, int *);
543 } options[] = {
544 { "blksize", blk_handler },
545 { "timeout", timeout_handler },
546 { "tsize", tsize_handler },
547 { NULL, NULL }
551 * Get options for an extended tftp session. Stuff the ones we
552 * recognize in oackbuf.
554 static int
555 get_options(struct tftphdr *tp, char *cp, int size, char *ackb,
556 int *alen, int *err)
558 struct tftp_options *op;
559 char *option, *value, *endp;
560 int r, rv=0, ec=0;
562 endp = cp + size;
563 while (cp < endp) {
564 option = cp;
565 while (*cp && cp < endp) {
566 *cp = tolower((unsigned char)*cp);
567 cp++;
569 if (*cp) {
570 /* if we have garbage at the end, just ignore it */
571 break;
573 cp++; /* skip over NUL */
574 value = cp;
575 while (*cp && cp < endp) {
576 cp++;
578 if (*cp) {
579 /* if we have garbage at the end, just ignore it */
580 break;
582 cp++;
583 for (op = options; op->o_name; op++) {
584 if (strcmp(op->o_name, option) == 0)
585 break;
587 if (op->o_name) {
588 r = op->o_handler(tp, option, value, ackb, alen, &ec);
589 if (r < 0) {
590 rv = -1;
591 break;
593 rv++;
594 } /* else ignore unknown options */
597 if (rv < 0)
598 *err = ec;
600 return rv;
604 * Handle initial connection protocol.
606 static void
607 tftp(struct tftphdr *tp, int size)
609 struct formats *pf;
610 char *cp;
611 char *filename, *mode;
612 int first, ecode, alen, etftp=0, r;
614 ecode = 0; /* XXX gcc */
615 first = 1;
616 mode = NULL;
618 filename = cp = tp->th_stuff;
619 again:
620 while (cp < buf + size) {
621 if (*cp == '\0')
622 break;
623 cp++;
625 if (*cp != '\0') {
626 nak(EBADOP);
627 exit(1);
629 if (first) {
630 mode = ++cp;
631 first = 0;
632 goto again;
634 for (cp = mode; *cp; cp++)
635 *cp = tolower((unsigned char)*cp);
636 for (pf = formats; pf->f_mode; pf++)
637 if (strcmp(pf->f_mode, mode) == 0)
638 break;
639 if (pf->f_mode == 0) {
640 nak(EBADOP);
641 exit(1);
644 * cp currently points to the NUL byte following the mode.
646 * If we have some valid options, then let's assume that we're
647 * now dealing with an extended tftp session. Note that if we
648 * don't get any options, then we *must* assume that we do not
649 * have an extended tftp session. If we get options, we fill
650 * in the ack buf to acknowledge them. If we skip that, then
651 * the client *must* assume that we are not using an extended
652 * session.
654 size -= (++cp - (char *) tp);
655 if (size > 0 && *cp) {
656 alen = 2; /* Skip over opcode */
657 r = get_options(tp, cp, size, oackbuf, &alen, &ecode);
658 if (r > 0) {
659 etftp = 1;
660 } else if (r < 0) {
661 nak(ecode);
662 exit(1);
665 ecode = (*pf->f_validate)(&filename, tp->th_opcode);
666 if (logging) {
667 syslog(LOG_INFO, "%s: %s request for %s: %s",
668 verifyhost((struct sockaddr *)&from),
669 tp->th_opcode == WRQ ? "write" : "read",
670 filename, errtomsg(ecode));
672 if (ecode) {
674 * Avoid storms of naks to a RRQ broadcast for a relative
675 * bootfile pathname from a diskless Sun.
677 if (suppress_naks && *filename != '/' && ecode == ENOTFOUND)
678 exit(0);
679 nak(ecode);
680 exit(1);
683 if (etftp) {
684 struct tftphdr *oack_h;
686 if (tftp_opt_tsize) {
687 int l;
689 strcpy(oackbuf + alen, "tsize");
690 alen += 6;
691 l = sprintf(oackbuf + alen, "%u", tftp_tsize);
692 alen += l + 1;
694 oack_h = (struct tftphdr *) oackbuf;
695 oack_h->th_opcode = htons(OACK);
698 if (tp->th_opcode == WRQ)
699 (*pf->f_recv)(pf, etftp, alen);
700 else
701 (*pf->f_send)(pf, etftp, alen);
702 exit(0);
706 FILE *file;
709 * Validate file access. Since we
710 * have no uid or gid, for now require
711 * file to exist and be publicly
712 * readable/writable.
713 * If we were invoked with arguments
714 * from inetd then the file must also be
715 * in one of the given directory prefixes.
718 validate_access(char **filep, int mode)
720 struct stat stbuf;
721 struct dirlist *dirp;
722 static char pathname[MAXPATHLEN];
723 char *filename;
724 int fd;
726 filename = *filep;
729 * Prevent tricksters from getting around the directory restrictions
731 if (strstr(filename, "/../"))
732 return (EACCESS);
734 if (*filename == '/') {
736 * Allow the request if it's in one of the approved locations.
737 * Special case: check the null prefix ("/") by looking
738 * for length = 1 and relying on the arg. processing that
739 * it's a /.
741 for (dirp = dirs; dirp->name != NULL; dirp++) {
742 if (dirp->len == 1 ||
743 (!strncmp(filename, dirp->name, dirp->len) &&
744 filename[dirp->len] == '/'))
745 break;
747 /* If directory list is empty, allow access to any file */
748 if (dirp->name == NULL && dirp != dirs)
749 return (EACCESS);
750 if (stat(filename, &stbuf) < 0)
751 return (errno == ENOENT ? ENOTFOUND : EACCESS);
752 if (!S_ISREG(stbuf.st_mode))
753 return (ENOTFOUND);
754 if (mode == RRQ) {
755 if ((stbuf.st_mode & S_IROTH) == 0)
756 return (EACCESS);
757 } else {
758 if ((stbuf.st_mode & S_IWOTH) == 0)
759 return (EACCESS);
761 } else {
763 * Relative file name: search the approved locations for it.
766 if (!strncmp(filename, "../", 3))
767 return (EACCESS);
770 * Find the first file that exists in any of the directories,
771 * check access on it.
773 if (dirs[0].name != NULL) {
774 for (dirp = dirs; dirp->name != NULL; dirp++) {
775 snprintf(pathname, sizeof pathname, "%s/%s",
776 dirp->name, filename);
777 if (stat(pathname, &stbuf) == 0 &&
778 (stbuf.st_mode & S_IFMT) == S_IFREG) {
779 break;
782 if (dirp->name == NULL)
783 return (ENOTFOUND);
784 if (mode == RRQ && !(stbuf.st_mode & S_IROTH))
785 return (EACCESS);
786 if (mode == WRQ && !(stbuf.st_mode & S_IWOTH))
787 return (EACCESS);
788 *filep = filename = pathname;
789 } else {
791 * If there's no directory list, take our cue from the
792 * absolute file request check above (*filename == '/'),
793 * and allow access to anything.
795 if (stat(filename, &stbuf) < 0)
796 return (errno == ENOENT ? ENOTFOUND : EACCESS);
797 if (!S_ISREG(stbuf.st_mode))
798 return (ENOTFOUND);
799 if (mode == RRQ) {
800 if ((stbuf.st_mode & S_IROTH) == 0)
801 return (EACCESS);
802 } else {
803 if ((stbuf.st_mode & S_IWOTH) == 0)
804 return (EACCESS);
806 *filep = filename;
810 if (tftp_opt_tsize && mode == RRQ)
811 tftp_tsize = (unsigned long) stbuf.st_size;
813 fd = open(filename, mode == RRQ ? O_RDONLY : O_WRONLY | O_TRUNC);
814 if (fd < 0)
815 return (errno + 100);
816 file = fdopen(fd, (mode == RRQ)? "r":"w");
817 if (file == NULL) {
818 close(fd);
819 return (errno + 100);
821 return (0);
824 int timeout;
825 jmp_buf timeoutbuf;
827 void
828 timer(int dummy)
831 timeout += rexmtval;
832 if (timeout >= maxtimeout)
833 exit(1);
834 longjmp(timeoutbuf, 1);
837 static const char *
838 opcode(int code)
840 static char obuf[64];
842 switch (code) {
843 case RRQ:
844 return "RRQ";
845 case WRQ:
846 return "WRQ";
847 case DATA:
848 return "DATA";
849 case ACK:
850 return "ACK";
851 case ERROR:
852 return "ERROR";
853 case OACK:
854 return "OACK";
855 default:
856 (void)snprintf(obuf, sizeof(obuf), "*code %d*", code);
857 return obuf;
862 * Send the requested file.
864 void
865 sendfile(struct formats *pf, int etftp, int acklength)
867 volatile unsigned int block;
868 struct tftphdr *dp;
869 struct tftphdr *ap; /* ack packet */
870 int size, n;
872 signal(SIGALRM, timer);
873 ap = (struct tftphdr *)ackbuf;
874 if (etftp) {
875 dp = (struct tftphdr *)oackbuf;
876 size = acklength - 4;
877 block = 0;
878 } else {
879 dp = r_init();
880 size = 0;
881 block = 1;
884 do {
885 if (block > 0) {
886 size = readit(file, &dp, tftp_blksize, pf->f_convert);
887 if (size < 0) {
888 nak(errno + 100);
889 goto abort;
891 dp->th_opcode = htons((u_short)DATA);
892 dp->th_block = htons((u_short)block);
894 timeout = 0;
895 (void)setjmp(timeoutbuf);
897 send_data:
898 if (!etftp && debug)
899 syslog(LOG_DEBUG, "Send DATA %u", block);
900 if ((n = send(peer, dp, size + 4, 0)) != size + 4) {
901 syslog(LOG_ERR, "tftpd: write: %m");
902 goto abort;
904 if (block)
905 read_ahead(file, tftp_blksize, pf->f_convert);
906 for ( ; ; ) {
907 alarm(rexmtval); /* read the ack */
908 n = recv(peer, ackbuf, tftp_blksize, 0);
909 alarm(0);
910 if (n < 0) {
911 syslog(LOG_ERR, "tftpd: read: %m");
912 goto abort;
914 ap->th_opcode = ntohs((u_short)ap->th_opcode);
915 ap->th_block = ntohs((u_short)ap->th_block);
916 switch (ap->th_opcode) {
917 case ERROR:
918 goto abort;
920 case ACK:
921 if (ap->th_block == 0) {
922 etftp = 0;
923 acklength = 0;
924 dp = r_init();
925 goto done;
927 if (ap->th_block == block)
928 goto done;
929 if (debug)
930 syslog(LOG_DEBUG, "Resync ACK %u != %u",
931 (unsigned int)ap->th_block, block);
932 /* Re-synchronize with the other side */
933 (void) synchnet(peer, tftp_blksize);
934 if (ap->th_block == (block -1))
935 goto send_data;
936 default:
937 syslog(LOG_INFO, "Received %s in sendfile\n",
938 opcode(dp->th_opcode));
942 done:
943 if (debug)
944 syslog(LOG_DEBUG, "Received ACK for block %u", block);
945 block++;
946 } while (size == tftp_blksize || block == 1);
947 abort:
948 (void) fclose(file);
951 void
952 justquit(int dummy)
955 exit(0);
959 * Receive a file.
961 void
962 recvfile(struct formats *pf, int etftp, int acklength)
964 volatile unsigned int block;
965 struct tftphdr *dp;
966 struct tftphdr *ap; /* ack buffer */
967 int n, size;
969 signal(SIGALRM, timer);
970 dp = w_init();
971 ap = (struct tftphdr *)oackbuf;
972 block = 0;
973 do {
974 timeout = 0;
975 if (etftp == 0) {
976 ap = (struct tftphdr *)ackbuf;
977 ap->th_opcode = htons((u_short)ACK);
978 ap->th_block = htons((u_short)block);
979 acklength = 4;
981 if (debug)
982 syslog(LOG_DEBUG, "Sending ACK for block %u\n", block);
983 block++;
984 (void) setjmp(timeoutbuf);
985 send_ack:
986 if (send(peer, ap, acklength, 0) != acklength) {
987 syslog(LOG_ERR, "tftpd: write: %m");
988 goto abort;
990 write_behind(file, pf->f_convert);
991 for ( ; ; ) {
992 alarm(rexmtval);
993 n = recv(peer, dp, tftp_blksize + 4, 0);
994 alarm(0);
995 if (n < 0) { /* really? */
996 syslog(LOG_ERR, "tftpd: read: %m");
997 goto abort;
999 etftp = 0;
1000 dp->th_opcode = ntohs((u_short)dp->th_opcode);
1001 dp->th_block = ntohs((u_short)dp->th_block);
1002 if (debug)
1003 syslog(LOG_DEBUG, "Received %s for block %u",
1004 opcode(dp->th_opcode),
1005 (unsigned int)dp->th_block);
1007 switch (dp->th_opcode) {
1008 case ERROR:
1009 goto abort;
1010 case DATA:
1011 if (dp->th_block == block)
1012 goto done; /* normal */
1013 if (debug)
1014 syslog(LOG_DEBUG, "Resync %u != %u",
1015 (unsigned int)dp->th_block, block);
1016 /* Re-synchronize with the other side */
1017 (void) synchnet(peer, tftp_blksize);
1018 if (dp->th_block == (block-1))
1019 goto send_ack; /* rexmit */
1020 break;
1021 default:
1022 syslog(LOG_INFO, "Received %s in recvfile\n",
1023 opcode(dp->th_opcode));
1024 break;
1027 done:
1028 if (debug)
1029 syslog(LOG_DEBUG, "Got block %u", block);
1030 /* size = write(file, dp->th_data, n - 4); */
1031 size = writeit(file, &dp, n - 4, pf->f_convert);
1032 if (size != (n-4)) { /* ahem */
1033 if (size < 0) nak(errno + 100);
1034 else nak(ENOSPACE);
1035 goto abort;
1037 } while (size == tftp_blksize);
1038 write_behind(file, pf->f_convert);
1039 (void) fclose(file); /* close data file */
1041 ap->th_opcode = htons((u_short)ACK); /* send the "final" ack */
1042 ap->th_block = htons((u_short)(block));
1043 if (debug)
1044 syslog(LOG_DEBUG, "Send final ACK %u", block);
1045 (void) send(peer, ackbuf, 4, 0);
1047 signal(SIGALRM, justquit); /* just quit on timeout */
1048 alarm(rexmtval);
1049 n = recv(peer, buf, sizeof (buf), 0); /* normally times out and quits */
1050 alarm(0);
1051 if (n >= 4 && /* if read some data */
1052 dp->th_opcode == DATA && /* and got a data block */
1053 block == dp->th_block) { /* then my last ack was lost */
1054 (void) send(peer, ackbuf, 4, 0); /* resend final ack */
1056 abort:
1057 return;
1060 const struct errmsg {
1061 int e_code;
1062 const char *e_msg;
1063 } errmsgs[] = {
1064 { EUNDEF, "Undefined error code" },
1065 { ENOTFOUND, "File not found" },
1066 { EACCESS, "Access violation" },
1067 { ENOSPACE, "Disk full or allocation exceeded" },
1068 { EBADOP, "Illegal TFTP operation" },
1069 { EBADID, "Unknown transfer ID" },
1070 { EEXISTS, "File already exists" },
1071 { ENOUSER, "No such user" },
1072 { EOPTNEG, "Option negotiation failed" },
1073 { -1, 0 }
1076 static const char *
1077 errtomsg(int error)
1079 static char ebuf[20];
1080 const struct errmsg *pe;
1082 if (error == 0)
1083 return ("success");
1084 for (pe = errmsgs; pe->e_code >= 0; pe++)
1085 if (pe->e_code == error)
1086 return (pe->e_msg);
1087 snprintf(ebuf, sizeof(ebuf), "error %d", error);
1088 return (ebuf);
1092 * Send a nak packet (error message).
1093 * Error code passed in is one of the
1094 * standard TFTP codes, or a UNIX errno
1095 * offset by 100.
1097 static void
1098 nak(int error)
1100 const struct errmsg *pe;
1101 struct tftphdr *tp;
1102 int length;
1103 size_t msglen;
1105 tp = (struct tftphdr *)buf;
1106 tp->th_opcode = htons((u_short)ERROR);
1107 msglen = sizeof(buf) - (&tp->th_msg[0] - buf);
1108 for (pe = errmsgs; pe->e_code >= 0; pe++)
1109 if (pe->e_code == error)
1110 break;
1111 if (pe->e_code < 0) {
1112 tp->th_code = EUNDEF; /* set 'undef' errorcode */
1113 strlcpy(tp->th_msg, strerror(error - 100), msglen);
1114 } else {
1115 tp->th_code = htons((u_short)error);
1116 strlcpy(tp->th_msg, pe->e_msg, msglen);
1118 if (debug)
1119 syslog(LOG_DEBUG, "Send NACK %s", tp->th_msg);
1120 length = strlen(tp->th_msg);
1121 msglen = &tp->th_msg[length + 1] - buf;
1122 if (send(peer, buf, msglen, 0) != msglen)
1123 syslog(LOG_ERR, "nak: %m");
1126 static char *
1127 verifyhost(struct sockaddr *fromp)
1129 static char hbuf[MAXHOSTNAMELEN];
1131 if (getnameinfo(fromp, fromp->sa_len, hbuf, sizeof(hbuf), NULL, 0, 0))
1132 strlcpy(hbuf, "?", sizeof(hbuf));
1133 return (hbuf);