tftpd.c revision 1.29 1 /* $NetBSD: tftpd.c,v 1.29 2004/11/05 22:03:26 dsl Exp $ */
2
3 /*
4 * Copyright (c) 1983, 1993
5 * The Regents of the University of California. All rights reserved.
6 *
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.
18 *
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.
30 */
31
32 #include <sys/cdefs.h>
33 #ifndef lint
34 __COPYRIGHT("@(#) Copyright (c) 1983, 1993\n\
35 The Regents of the University of California. All rights reserved.\n");
36 #if 0
37 static char sccsid[] = "@(#)tftpd.c 8.1 (Berkeley) 6/4/93";
38 #else
39 __RCSID("$NetBSD: tftpd.c,v 1.29 2004/11/05 22:03:26 dsl Exp $");
40 #endif
41 #endif /* not lint */
42
43 /*
44 * Trivial file transfer protocol server.
45 *
46 * This version includes many modifications by Jim Guyton
47 * <guyton@rand-unix>.
48 */
49
50 #include <sys/param.h>
51 #include <sys/ioctl.h>
52 #include <sys/stat.h>
53 #include <sys/socket.h>
54
55 #include <netinet/in.h>
56 #include <arpa/tftp.h>
57 #include <arpa/inet.h>
58
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>
73
74 #include "tftpsubs.h"
75
76 #define DEFAULTUSER "nobody"
77
78 #define TIMEOUT 5
79
80 int peer;
81 int rexmtval = TIMEOUT;
82 int maxtimeout = 5*TIMEOUT;
83
84 char buf[MAXPKTSIZE];
85 char ackbuf[PKTSIZE];
86 char oackbuf[PKTSIZE];
87 struct sockaddr_storage from;
88 int fromlen;
89 int debug;
90
91 int tftp_opt_tsize = 0;
92 int tftp_blksize = SEGSIZE;
93 int tftp_tsize = 0;
94
95 /*
96 * Null-terminated directory prefix list for absolute pathname requests and
97 * search list for relative pathname requests.
98 *
99 * MAXDIRS should be at least as large as the number of arguments that
100 * inetd allows (currently 20).
101 */
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;
111
112 struct formats;
113
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);
126
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 }
137 };
138
139 static void
140 usage(void)
141 {
142
143 syslog(LOG_ERR,
144 "Usage: %s [-dln] [-u user] [-g group] [-s directory] [directory ...]",
145 getprogname());
146 exit(1);
147 }
148
149 int
150 main(int argc, char *argv[])
151 {
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 len, soopt;
159 uid_t curuid, tgtuid;
160 gid_t curgid, tgtgid;
161 long nid;
162
163 n = 0;
164 fd = 0;
165 tzset();
166 openlog("tftpd", LOG_PID | LOG_NDELAY, LOG_DAEMON);
167 tgtuser = DEFAULTUSER;
168 tgtgroup = NULL;
169 curuid = getuid();
170 curgid = getgid();
171
172 while ((ch = getopt(argc, argv, "dg:lns:u:")) != -1)
173 switch (ch) {
174 case 'd':
175 debug++;
176 break;
177
178 case 'g':
179 tgtgroup = optarg;
180 break;
181
182 case 'l':
183 logging = 1;
184 break;
185
186 case 'n':
187 suppress_naks = 1;
188 break;
189
190 case 's':
191 secure = 1;
192 securedir = optarg;
193 break;
194
195 case 'u':
196 tgtuser = optarg;
197 break;
198
199 default:
200 usage();
201 break;
202 }
203
204 if (optind < argc) {
205 struct dirlist *dirp;
206
207 /* Get list of directory prefixes. Skip relative pathnames. */
208 for (dirp = dirs; optind < argc && dirp < &dirs[MAXDIRS];
209 optind++) {
210 if (argv[optind][0] == '/') {
211 dirp->name = argv[optind];
212 dirp->len = strlen(dirp->name);
213 dirp++;
214 }
215 }
216 }
217
218 if (*tgtuser == '\0' || (tgtgroup != NULL && *tgtgroup == '\0'))
219 usage();
220
221 nid = (strtol(tgtuser, &ep, 10));
222 if (*ep == '\0') {
223 if (nid > UID_MAX) {
224 syslog(LOG_ERR, "uid %ld is too large", nid);
225 exit(1);
226 }
227 pwent = getpwuid((uid_t)nid);
228 } else
229 pwent = getpwnam(tgtuser);
230 if (pwent == NULL) {
231 syslog(LOG_ERR, "unknown user `%s'", tgtuser);
232 exit(1);
233 }
234 tgtuid = pwent->pw_uid;
235 tgtgid = pwent->pw_gid;
236
237 if (tgtgroup != NULL) {
238 nid = (strtol(tgtgroup, &ep, 10));
239 if (*ep == '\0') {
240 if (nid > GID_MAX) {
241 syslog(LOG_ERR, "gid %ld is too large", nid);
242 exit(1);
243 }
244 grent = getgrgid((gid_t)nid);
245 } else
246 grent = getgrnam(tgtgroup);
247 if (grent != NULL)
248 tgtgid = grent->gr_gid;
249 else {
250 syslog(LOG_ERR, "unknown group `%s'", tgtgroup);
251 exit(1);
252 }
253 }
254
255 if (secure) {
256 if (chdir(securedir) < 0) {
257 syslog(LOG_ERR, "chdir %s: %m", securedir);
258 exit(1);
259 }
260 if (chroot(".")) {
261 syslog(LOG_ERR, "chroot: %m");
262 exit(1);
263 }
264 }
265
266 if (logging)
267 syslog(LOG_DEBUG, "running as user `%s' (%d), group `%s' (%d)",
268 tgtuser, tgtuid, tgtgroup ? tgtgroup : "(unspecified)",
269 tgtgid);
270 if (curgid != tgtgid) {
271 if (setgid(tgtgid)) {
272 syslog(LOG_ERR, "setgid to %d: %m", (int)tgtgid);
273 exit(1);
274 }
275 if (setgroups(0, NULL)) {
276 syslog(LOG_ERR, "setgroups: %m");
277 exit(1);
278 }
279 }
280
281 if (curuid != tgtuid) {
282 if (setuid(tgtuid)) {
283 syslog(LOG_ERR, "setuid to %d: %m", (int)tgtuid);
284 exit(1);
285 }
286 }
287
288 on = 1;
289 if (ioctl(fd, FIONBIO, &on) < 0) {
290 syslog(LOG_ERR, "ioctl(FIONBIO): %m");
291 exit(1);
292 }
293 fromlen = sizeof (from);
294 n = recvfrom(fd, buf, sizeof (buf), 0,
295 (struct sockaddr *)&from, &fromlen);
296 if (n < 0) {
297 syslog(LOG_ERR, "recvfrom: %m");
298 exit(1);
299 }
300 /*
301 * Now that we have read the message out of the UDP
302 * socket, we fork and exit. Thus, inetd will go back
303 * to listening to the tftp port, and the next request
304 * to come in will start up a new instance of tftpd.
305 *
306 * We do this so that inetd can run tftpd in "wait" mode.
307 * The problem with tftpd running in "nowait" mode is that
308 * inetd may get one or more successful "selects" on the
309 * tftp port before we do our receive, so more than one
310 * instance of tftpd may be started up. Worse, if tftpd
311 * break before doing the above "recvfrom", inetd would
312 * spawn endless instances, clogging the system.
313 */
314 {
315 int pid;
316 int i, j;
317
318 for (i = 1; i < 20; i++) {
319 pid = fork();
320 if (pid < 0) {
321 sleep(i);
322 /*
323 * flush out to most recently sent request.
324 *
325 * This may drop some request, but those
326 * will be resent by the clients when
327 * they timeout. The positive effect of
328 * this flush is to (try to) prevent more
329 * than one tftpd being started up to service
330 * a single request from a single client.
331 */
332 j = sizeof from;
333 i = recvfrom(fd, buf, sizeof (buf), 0,
334 (struct sockaddr *)&from, &j);
335 if (i > 0) {
336 n = i;
337 fromlen = j;
338 }
339 } else {
340 break;
341 }
342 }
343 if (pid < 0) {
344 syslog(LOG_ERR, "fork: %m");
345 exit(1);
346 } else if (pid != 0) {
347 exit(0);
348 }
349 }
350
351 /*
352 * remember what address this was sent to, so we can respond on the
353 * same interface
354 */
355 len = sizeof(me);
356 if (getsockname(fd, (struct sockaddr *)&me, &len) == 0) {
357 switch (me.ss_family) {
358 case AF_INET:
359 ((struct sockaddr_in *)&me)->sin_port = 0;
360 break;
361 case AF_INET6:
362 ((struct sockaddr_in6 *)&me)->sin6_port = 0;
363 break;
364 default:
365 /* unsupported */
366 break;
367 }
368 } else {
369 memset(&me, 0, sizeof(me));
370 me.ss_family = from.ss_family;
371 me.ss_len = from.ss_len;
372 }
373
374 alarm(0);
375 close(fd);
376 close(1);
377 peer = socket(from.ss_family, SOCK_DGRAM, 0);
378 if (peer < 0) {
379 syslog(LOG_ERR, "socket: %m");
380 exit(1);
381 }
382 if (bind(peer, (struct sockaddr *)&me, me.ss_len) < 0) {
383 syslog(LOG_ERR, "bind: %m");
384 exit(1);
385 }
386 if (connect(peer, (struct sockaddr *)&from, from.ss_len) < 0) {
387 syslog(LOG_ERR, "connect: %m");
388 exit(1);
389 }
390 soopt = 65536; /* larger than we'll ever need */
391 if (setsockopt(peer, SOL_SOCKET, SO_SNDBUF, (void *) &soopt, sizeof(soopt)) < 0) {
392 syslog(LOG_ERR, "set SNDBUF: %m");
393 exit(1);
394 }
395 if (setsockopt(peer, SOL_SOCKET, SO_RCVBUF, (void *) &soopt, sizeof(soopt)) < 0) {
396 syslog(LOG_ERR, "set RCVBUF: %m");
397 exit(1);
398 }
399
400 tp = (struct tftphdr *)buf;
401 tp->th_opcode = ntohs(tp->th_opcode);
402 if (tp->th_opcode == RRQ || tp->th_opcode == WRQ)
403 tftp(tp, n);
404 exit(1);
405 }
406
407 static int
408 blk_handler(struct tftphdr *tp, char *opt, char *val, char *ack,
409 int *ackl, int *ec)
410 {
411 unsigned long bsize;
412 char *endp;
413 int l;
414
415 /*
416 * On these failures, we could just ignore the blocksize option.
417 * Perhaps that should be a command-line option.
418 */
419 errno = 0;
420 bsize = strtoul(val, &endp, 10);
421 if ((bsize == ULONG_MAX && errno == ERANGE) || *endp) {
422 syslog(LOG_NOTICE, "%s: %s request for %s: "
423 "illegal value %s for blksize option",
424 verifyhost((struct sockaddr *)&from),
425 tp->th_opcode == WRQ ? "write" : "read",
426 tp->th_stuff, val);
427 return 0;
428 }
429 if (bsize < 8 || bsize > 65464) {
430 syslog(LOG_NOTICE, "%s: %s request for %s: "
431 "out of range value %s for blksize option",
432 verifyhost((struct sockaddr *)&from),
433 tp->th_opcode == WRQ ? "write" : "read",
434 tp->th_stuff, val);
435 return 0;
436 }
437
438 tftp_blksize = bsize;
439 strcpy(ack + *ackl, "blksize");
440 *ackl += 8;
441 l = sprintf(ack + *ackl, "%lu", bsize);
442 *ackl += l + 1;
443
444 return 0;
445 }
446
447 static int
448 timeout_handler(struct tftphdr *tp, char *opt, char *val, char *ack,
449 int *ackl, int *ec)
450 {
451 unsigned long tout;
452 char *endp;
453 int l;
454
455 errno = 0;
456 tout = strtoul(val, &endp, 10);
457 if ((tout == ULONG_MAX && errno == ERANGE) || *endp) {
458 syslog(LOG_NOTICE, "%s: %s request for %s: "
459 "illegal value %s for timeout option",
460 verifyhost((struct sockaddr *)&from),
461 tp->th_opcode == WRQ ? "write" : "read",
462 tp->th_stuff, val);
463 return 0;
464 }
465 if (tout < 1 || tout > 255) {
466 syslog(LOG_NOTICE, "%s: %s request for %s: "
467 "out of range value %s for timeout option",
468 verifyhost((struct sockaddr *)&from),
469 tp->th_opcode == WRQ ? "write" : "read",
470 tp->th_stuff, val);
471 return 0;
472 }
473
474 rexmtval = tout;
475 strcpy(ack + *ackl, "timeout");
476 *ackl += 8;
477 l = sprintf(ack + *ackl, "%lu", tout);
478 *ackl += l + 1;
479
480 /*
481 * Arbitrarily pick a maximum timeout on a request to 3
482 * retransmissions if the interval timeout is more than
483 * one minute. Longest possible timeout is therefore
484 * 3 * 255 - 1, or 764 seconds.
485 */
486 if (rexmtval > 60) {
487 maxtimeout = rexmtval * 3;
488 } else {
489 maxtimeout = rexmtval * 5;
490 }
491
492 return 0;
493 }
494
495 static int
496 tsize_handler(struct tftphdr *tp, char *opt, char *val, char *ack,
497 int *ackl, int *ec)
498 {
499 unsigned long fsize;
500 char *endp;
501
502 /*
503 * Maximum file even with extended tftp is 65535 blocks of
504 * length 65464, or 4290183240 octets (4784056 less than 2^32).
505 * unsigned long is at least 32 bits on all NetBSD archs.
506 */
507
508 errno = 0;
509 fsize = strtoul(val, &endp, 10);
510 if ((fsize == ULONG_MAX && errno == ERANGE) || *endp) {
511 syslog(LOG_NOTICE, "%s: %s request for %s: "
512 "illegal value %s for tsize option",
513 verifyhost((struct sockaddr *)&from),
514 tp->th_opcode == WRQ ? "write" : "read",
515 tp->th_stuff, val);
516 return 0;
517 }
518 if (fsize > (unsigned long) 65535 * 65464) {
519 syslog(LOG_NOTICE, "%s: %s request for %s: "
520 "out of range value %s for tsize option",
521 verifyhost((struct sockaddr *)&from),
522 tp->th_opcode == WRQ ? "write" : "read",
523 tp->th_stuff, val);
524 return 0;
525 }
526
527 tftp_opt_tsize = 1;
528 tftp_tsize = fsize;
529 /*
530 * We will report this later -- either replying with the fsize (WRQ)
531 * or replying with the actual filesize (RRQ).
532 */
533
534 return 0;
535 }
536
537 struct tftp_options {
538 char *o_name;
539 int (*o_handler)(struct tftphdr *, char *, char *, char *,
540 int *, int *);
541 } options[] = {
542 { "blksize", blk_handler },
543 { "timeout", timeout_handler },
544 { "tsize", tsize_handler },
545 { NULL, NULL }
546 };
547
548 /*
549 * Get options for an extended tftp session. Stuff the ones we
550 * recognize in oackbuf.
551 */
552 static int
553 get_options(struct tftphdr *tp, char *cp, int size, char *ackb,
554 int *alen, int *err)
555 {
556 struct tftp_options *op;
557 char *option, *value, *endp;
558 int r, rv=0, ec=0;
559
560 endp = cp + size;
561 while (cp < endp) {
562 option = cp;
563 while (*cp && cp < endp) {
564 *cp = tolower((unsigned char)*cp);
565 cp++;
566 }
567 if (*cp) {
568 /* if we have garbage at the end, just ignore it */
569 break;
570 }
571 cp++; /* skip over NUL */
572 value = cp;
573 while (*cp && cp < endp) {
574 cp++;
575 }
576 if (*cp) {
577 /* if we have garbage at the end, just ignore it */
578 break;
579 }
580 cp++;
581 for (op = options; op->o_name; op++) {
582 if (strcmp(op->o_name, option) == 0)
583 break;
584 }
585 if (op->o_name) {
586 r = op->o_handler(tp, option, value, ackb, alen, &ec);
587 if (r < 0) {
588 rv = -1;
589 break;
590 }
591 rv++;
592 } /* else ignore unknown options */
593 }
594
595 if (rv < 0)
596 *err = ec;
597
598 return rv;
599 }
600
601 /*
602 * Handle initial connection protocol.
603 */
604 static void
605 tftp(struct tftphdr *tp, int size)
606 {
607 struct formats *pf;
608 char *cp;
609 char *filename, *mode;
610 int first, ecode, alen, etftp=0, r;
611
612 first = 1;
613 mode = NULL;
614
615 filename = cp = tp->th_stuff;
616 again:
617 while (cp < buf + size) {
618 if (*cp == '\0')
619 break;
620 cp++;
621 }
622 if (*cp != '\0') {
623 nak(EBADOP);
624 exit(1);
625 }
626 if (first) {
627 mode = ++cp;
628 first = 0;
629 goto again;
630 }
631 for (cp = mode; *cp; cp++)
632 *cp = tolower((unsigned char)*cp);
633 for (pf = formats; pf->f_mode; pf++)
634 if (strcmp(pf->f_mode, mode) == 0)
635 break;
636 if (pf->f_mode == 0) {
637 nak(EBADOP);
638 exit(1);
639 }
640 /*
641 * cp currently points to the NUL byte following the mode.
642 *
643 * If we have some valid options, then let's assume that we're
644 * now dealing with an extended tftp session. Note that if we
645 * don't get any options, then we *must* assume that we do not
646 * have an extended tftp session. If we get options, we fill
647 * in the ack buf to acknowledge them. If we skip that, then
648 * the client *must* assume that we are not using an extended
649 * session.
650 */
651 size -= (++cp - (char *) tp);
652 if (size > 0 && *cp) {
653 alen = 2; /* Skip over opcode */
654 r = get_options(tp, cp, size, oackbuf, &alen, &ecode);
655 if (r > 0) {
656 etftp = 1;
657 } else if (r < 0) {
658 nak(ecode);
659 exit(1);
660 }
661 }
662 ecode = (*pf->f_validate)(&filename, tp->th_opcode);
663 if (logging) {
664 syslog(LOG_INFO, "%s: %s request for %s: %s",
665 verifyhost((struct sockaddr *)&from),
666 tp->th_opcode == WRQ ? "write" : "read",
667 filename, errtomsg(ecode));
668 }
669 if (ecode) {
670 /*
671 * Avoid storms of naks to a RRQ broadcast for a relative
672 * bootfile pathname from a diskless Sun.
673 */
674 if (suppress_naks && *filename != '/' && ecode == ENOTFOUND)
675 exit(0);
676 nak(ecode);
677 exit(1);
678 }
679
680 if (etftp) {
681 struct tftphdr *oack_h;
682
683 if (tftp_opt_tsize) {
684 int l;
685
686 strcpy(oackbuf + alen, "tsize");
687 alen += 6;
688 l = sprintf(oackbuf + alen, "%u", tftp_tsize);
689 alen += l + 1;
690 }
691 oack_h = (struct tftphdr *) oackbuf;
692 oack_h->th_opcode = htons(OACK);
693 }
694
695 if (tp->th_opcode == WRQ)
696 (*pf->f_recv)(pf, etftp, alen);
697 else
698 (*pf->f_send)(pf, etftp, alen);
699 exit(0);
700 }
701
702
703 FILE *file;
704
705 /*
706 * Validate file access. Since we
707 * have no uid or gid, for now require
708 * file to exist and be publicly
709 * readable/writable.
710 * If we were invoked with arguments
711 * from inetd then the file must also be
712 * in one of the given directory prefixes.
713 */
714 int
715 validate_access(char **filep, int mode)
716 {
717 struct stat stbuf;
718 struct dirlist *dirp;
719 static char pathname[MAXPATHLEN];
720 char *filename;
721 int fd;
722
723 filename = *filep;
724
725 /*
726 * Prevent tricksters from getting around the directory restrictions
727 */
728 if (strstr(filename, "/../"))
729 return (EACCESS);
730
731 if (*filename == '/') {
732 /*
733 * Allow the request if it's in one of the approved locations.
734 * Special case: check the null prefix ("/") by looking
735 * for length = 1 and relying on the arg. processing that
736 * it's a /.
737 */
738 for (dirp = dirs; dirp->name != NULL; dirp++) {
739 if (dirp->len == 1 ||
740 (!strncmp(filename, dirp->name, dirp->len) &&
741 filename[dirp->len] == '/'))
742 break;
743 }
744 /* If directory list is empty, allow access to any file */
745 if (dirp->name == NULL && dirp != dirs)
746 return (EACCESS);
747 if (stat(filename, &stbuf) < 0)
748 return (errno == ENOENT ? ENOTFOUND : EACCESS);
749 if (!S_ISREG(stbuf.st_mode))
750 return (ENOTFOUND);
751 if (mode == RRQ) {
752 if ((stbuf.st_mode & S_IROTH) == 0)
753 return (EACCESS);
754 } else {
755 if ((stbuf.st_mode & S_IWOTH) == 0)
756 return (EACCESS);
757 }
758 } else {
759 /*
760 * Relative file name: search the approved locations for it.
761 */
762
763 if (!strncmp(filename, "../", 3))
764 return (EACCESS);
765
766 /*
767 * Find the first file that exists in any of the directories,
768 * check access on it.
769 */
770 if (dirs[0].name != NULL) {
771 for (dirp = dirs; dirp->name != NULL; dirp++) {
772 snprintf(pathname, sizeof pathname, "%s/%s",
773 dirp->name, filename);
774 if (stat(pathname, &stbuf) == 0 &&
775 (stbuf.st_mode & S_IFMT) == S_IFREG) {
776 break;
777 }
778 }
779 if (dirp->name == NULL)
780 return (ENOTFOUND);
781 if (mode == RRQ && !(stbuf.st_mode & S_IROTH))
782 return (EACCESS);
783 if (mode == WRQ && !(stbuf.st_mode & S_IWOTH))
784 return (EACCESS);
785 *filep = filename = pathname;
786 } else {
787 /*
788 * If there's no directory list, take our cue from the
789 * absolute file request check above (*filename == '/'),
790 * and allow access to anything.
791 */
792 if (stat(filename, &stbuf) < 0)
793 return (errno == ENOENT ? ENOTFOUND : EACCESS);
794 if (!S_ISREG(stbuf.st_mode))
795 return (ENOTFOUND);
796 if (mode == RRQ) {
797 if ((stbuf.st_mode & S_IROTH) == 0)
798 return (EACCESS);
799 } else {
800 if ((stbuf.st_mode & S_IWOTH) == 0)
801 return (EACCESS);
802 }
803 *filep = filename;
804 }
805 }
806
807 if (tftp_opt_tsize && mode == RRQ)
808 tftp_tsize = (unsigned long) stbuf.st_size;
809
810 fd = open(filename, mode == RRQ ? O_RDONLY : O_WRONLY | O_TRUNC);
811 if (fd < 0)
812 return (errno + 100);
813 file = fdopen(fd, (mode == RRQ)? "r":"w");
814 if (file == NULL) {
815 close(fd);
816 return (errno + 100);
817 }
818 return (0);
819 }
820
821 int timeout;
822 jmp_buf timeoutbuf;
823
824 void
825 timer(int dummy)
826 {
827
828 timeout += rexmtval;
829 if (timeout >= maxtimeout)
830 exit(1);
831 longjmp(timeoutbuf, 1);
832 }
833
834 static const char *
835 opcode(int code)
836 {
837 static char buf[64];
838
839 switch (code) {
840 case RRQ:
841 return "RRQ";
842 case WRQ:
843 return "WRQ";
844 case DATA:
845 return "DATA";
846 case ACK:
847 return "ACK";
848 case ERROR:
849 return "ERROR";
850 case OACK:
851 return "OACK";
852 default:
853 (void)snprintf(buf, sizeof(buf), "*code %d*", code);
854 return buf;
855 }
856 }
857
858 /*
859 * Send the requested file.
860 */
861 void
862 sendfile(struct formats *pf, int etftp, int acklength)
863 {
864 volatile unsigned int block;
865 struct tftphdr *dp;
866 struct tftphdr *ap; /* ack packet */
867 int size, n;
868
869 signal(SIGALRM, timer);
870 ap = (struct tftphdr *)ackbuf;
871 if (etftp) {
872 dp = (struct tftphdr *)oackbuf;
873 size = acklength - 4;
874 block = 0;
875 } else {
876 dp = r_init();
877 size = 0;
878 block = 1;
879 }
880
881 do {
882 if (block > 0) {
883 size = readit(file, &dp, tftp_blksize, pf->f_convert);
884 if (size < 0) {
885 nak(errno + 100);
886 goto abort;
887 }
888 dp->th_opcode = htons((u_short)DATA);
889 dp->th_block = htons((u_short)block);
890 }
891 timeout = 0;
892 (void)setjmp(timeoutbuf);
893
894 send_data:
895 if (!etftp && debug)
896 syslog(LOG_DEBUG, "Send DATA %u", block);
897 if ((n = send(peer, dp, size + 4, 0)) != size + 4) {
898 syslog(LOG_ERR, "tftpd: write: %m");
899 goto abort;
900 }
901 if (block)
902 read_ahead(file, tftp_blksize, pf->f_convert);
903 for ( ; ; ) {
904 alarm(rexmtval); /* read the ack */
905 n = recv(peer, ackbuf, tftp_blksize, 0);
906 alarm(0);
907 if (n < 0) {
908 syslog(LOG_ERR, "tftpd: read: %m");
909 goto abort;
910 }
911 ap->th_opcode = ntohs((u_short)ap->th_opcode);
912 ap->th_block = ntohs((u_short)ap->th_block);
913 switch (ap->th_opcode) {
914 case ERROR:
915 goto abort;
916
917 case ACK:
918 if (ap->th_block == 0) {
919 etftp = 0;
920 acklength = 0;
921 dp = r_init();
922 goto done;
923 }
924 if (ap->th_block == block)
925 goto done;
926 if (debug)
927 syslog(LOG_DEBUG, "Resync ACK %u != %u",
928 (unsigned int)ap->th_block, block);
929 /* Re-synchronize with the other side */
930 (void) synchnet(peer, tftp_blksize);
931 if (ap->th_block == (block -1))
932 goto send_data;
933 default:
934 syslog(LOG_INFO, "Received %s in sendfile\n",
935 opcode(dp->th_opcode));
936 }
937
938 }
939 done:
940 if (debug)
941 syslog(LOG_DEBUG, "Received ACK for block %u", block);
942 block++;
943 } while (size == tftp_blksize || block == 1);
944 abort:
945 (void) fclose(file);
946 }
947
948 void
949 justquit(int dummy)
950 {
951
952 exit(0);
953 }
954
955 /*
956 * Receive a file.
957 */
958 void
959 recvfile(struct formats *pf, int etftp, int acklength)
960 {
961 volatile unsigned int block;
962 struct tftphdr *dp;
963 struct tftphdr *ap; /* ack buffer */
964 int n, size;
965
966 signal(SIGALRM, timer);
967 dp = w_init();
968 ap = (struct tftphdr *)oackbuf;
969 block = 0;
970 do {
971 timeout = 0;
972 if (etftp == 0) {
973 ap = (struct tftphdr *)ackbuf;
974 ap->th_opcode = htons((u_short)ACK);
975 ap->th_block = htons((u_short)block);
976 acklength = 4;
977 }
978 if (debug)
979 syslog(LOG_DEBUG, "Sending ACK for block %u\n", block);
980 block++;
981 (void) setjmp(timeoutbuf);
982 send_ack:
983 if (send(peer, ap, acklength, 0) != acklength) {
984 syslog(LOG_ERR, "tftpd: write: %m");
985 goto abort;
986 }
987 write_behind(file, pf->f_convert);
988 for ( ; ; ) {
989 alarm(rexmtval);
990 n = recv(peer, dp, tftp_blksize + 4, 0);
991 alarm(0);
992 if (n < 0) { /* really? */
993 syslog(LOG_ERR, "tftpd: read: %m");
994 goto abort;
995 }
996 etftp = 0;
997 dp->th_opcode = ntohs((u_short)dp->th_opcode);
998 dp->th_block = ntohs((u_short)dp->th_block);
999 if (debug)
1000 syslog(LOG_DEBUG, "Received %s for block %u",
1001 opcode(dp->th_opcode),
1002 (unsigned int)dp->th_block);
1003
1004 switch (dp->th_opcode) {
1005 case ERROR:
1006 goto abort;
1007 case DATA:
1008 if (dp->th_block == block)
1009 goto done; /* normal */
1010 if (debug)
1011 syslog(LOG_DEBUG, "Resync %u != %u",
1012 (unsigned int)dp->th_block, block);
1013 /* Re-synchronize with the other side */
1014 (void) synchnet(peer, tftp_blksize);
1015 if (dp->th_block == (block-1))
1016 goto send_ack; /* rexmit */
1017 break;
1018 default:
1019 syslog(LOG_INFO, "Received %s in recvfile\n",
1020 opcode(dp->th_opcode));
1021 break;
1022 }
1023 }
1024 done:
1025 if (debug)
1026 syslog(LOG_DEBUG, "Got block %u", block);
1027 /* size = write(file, dp->th_data, n - 4); */
1028 size = writeit(file, &dp, n - 4, pf->f_convert);
1029 if (size != (n-4)) { /* ahem */
1030 if (size < 0) nak(errno + 100);
1031 else nak(ENOSPACE);
1032 goto abort;
1033 }
1034 } while (size == tftp_blksize);
1035 write_behind(file, pf->f_convert);
1036 (void) fclose(file); /* close data file */
1037
1038 ap->th_opcode = htons((u_short)ACK); /* send the "final" ack */
1039 ap->th_block = htons((u_short)(block));
1040 if (debug)
1041 syslog(LOG_DEBUG, "Send final ACK %u", block);
1042 (void) send(peer, ackbuf, 4, 0);
1043
1044 signal(SIGALRM, justquit); /* just quit on timeout */
1045 alarm(rexmtval);
1046 n = recv(peer, buf, sizeof (buf), 0); /* normally times out and quits */
1047 alarm(0);
1048 if (n >= 4 && /* if read some data */
1049 dp->th_opcode == DATA && /* and got a data block */
1050 block == dp->th_block) { /* then my last ack was lost */
1051 (void) send(peer, ackbuf, 4, 0); /* resend final ack */
1052 }
1053 abort:
1054 return;
1055 }
1056
1057 const struct errmsg {
1058 int e_code;
1059 const char *e_msg;
1060 } errmsgs[] = {
1061 { EUNDEF, "Undefined error code" },
1062 { ENOTFOUND, "File not found" },
1063 { EACCESS, "Access violation" },
1064 { ENOSPACE, "Disk full or allocation exceeded" },
1065 { EBADOP, "Illegal TFTP operation" },
1066 { EBADID, "Unknown transfer ID" },
1067 { EEXISTS, "File already exists" },
1068 { ENOUSER, "No such user" },
1069 { EOPTNEG, "Option negotiation failed" },
1070 { -1, 0 }
1071 };
1072
1073 static const char *
1074 errtomsg(int error)
1075 {
1076 static char ebuf[20];
1077 const struct errmsg *pe;
1078
1079 if (error == 0)
1080 return ("success");
1081 for (pe = errmsgs; pe->e_code >= 0; pe++)
1082 if (pe->e_code == error)
1083 return (pe->e_msg);
1084 snprintf(ebuf, sizeof(ebuf), "error %d", error);
1085 return (ebuf);
1086 }
1087
1088 /*
1089 * Send a nak packet (error message).
1090 * Error code passed in is one of the
1091 * standard TFTP codes, or a UNIX errno
1092 * offset by 100.
1093 */
1094 static void
1095 nak(int error)
1096 {
1097 const struct errmsg *pe;
1098 struct tftphdr *tp;
1099 int length;
1100 size_t msglen;
1101
1102 tp = (struct tftphdr *)buf;
1103 tp->th_opcode = htons((u_short)ERROR);
1104 msglen = sizeof(buf) - (&tp->th_msg[0] - buf);
1105 for (pe = errmsgs; pe->e_code >= 0; pe++)
1106 if (pe->e_code == error)
1107 break;
1108 if (pe->e_code < 0) {
1109 tp->th_code = EUNDEF; /* set 'undef' errorcode */
1110 strlcpy(tp->th_msg, strerror(error - 100), msglen);
1111 } else {
1112 tp->th_code = htons((u_short)error);
1113 strlcpy(tp->th_msg, pe->e_msg, msglen);
1114 }
1115 if (debug)
1116 syslog(LOG_DEBUG, "Send NACK %s", tp->th_msg);
1117 length = strlen(tp->th_msg);
1118 msglen = &tp->th_msg[length + 1] - buf;
1119 if (send(peer, buf, msglen, 0) != msglen)
1120 syslog(LOG_ERR, "nak: %m");
1121 }
1122
1123 static char *
1124 verifyhost(struct sockaddr *fromp)
1125 {
1126 static char hbuf[MAXHOSTNAMELEN];
1127
1128 if (getnameinfo(fromp, fromp->sa_len, hbuf, sizeof(hbuf), NULL, 0, 0))
1129 strlcpy(hbuf, "?", sizeof(hbuf));
1130 return (hbuf);
1131 }
1132