Move /var/svc/log to /var/log/svc
[unleashed/lotheac.git] / usr / src / cmd / cmd-inet / usr.sbin / in.tftpd.c
blobcaa65f28eccef35dfc6aa5697cdead99718cd262
1 /*
2 * CDDL HEADER START
4 * The contents of this file are subject to the terms of the
5 * Common Development and Distribution License (the "License").
6 * You may not use this file except in compliance with the License.
8 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9 * or http://www.opensolaris.org/os/licensing.
10 * See the License for the specific language governing permissions
11 * and limitations under the License.
13 * When distributing Covered Code, include this CDDL HEADER in each
14 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15 * If applicable, add the following below this CDDL HEADER, with the
16 * fields enclosed by brackets "[]" replaced with your own identifying
17 * information: Portions Copyright [yyyy] [name of copyright owner]
19 * CDDL HEADER END
21 * Copyright 2010 Sun Microsystems, Inc. All rights reserved.
22 * Use is subject to license terms.
23 * Copyright (c) 2016 by Delphix. All rights reserved.
27 * Copyright (c) 1983, 1984, 1985, 1986, 1987, 1988, 1989 AT&T
28 * All Rights Reserved.
32 * University Copyright- Copyright (c) 1982, 1986, 1988
33 * The Regents of the University of California.
34 * All Rights Reserved.
36 * University Acknowledgment- Portions of this document are derived from
37 * software developed by the University of California, Berkeley, and its
38 * contributors.
42 * Trivial file transfer protocol server. A top level process runs in
43 * an infinite loop fielding new TFTP requests. A child process,
44 * communicating via a pipe with the top level process, sends delayed
45 * NAKs for those that we can't handle. A new child process is created
46 * to service each request that we can handle. The top level process
47 * exits after a period of time during which no new requests are
48 * received.
51 #include <sys/types.h>
52 #include <sys/socket.h>
53 #include <sys/wait.h>
54 #include <sys/stat.h>
55 #include <sys/time.h>
57 #include <netinet/in.h>
59 #include <arpa/inet.h>
60 #include <dirent.h>
61 #include <signal.h>
62 #include <stdio.h>
63 #include <stdlib.h>
64 #include <unistd.h>
65 #include <errno.h>
66 #include <ctype.h>
67 #include <netdb.h>
68 #include <setjmp.h>
69 #include <syslog.h>
70 #include <sys/param.h>
71 #include <fcntl.h>
72 #include <pwd.h>
73 #include <string.h>
74 #include <priv_utils.h>
75 #include "tftpcommon.h"
77 #define TIMEOUT 5
78 #define DELAY_SECS 3
79 #define DALLYSECS 60
81 #define SYSLOG_MSG(message) \
82 (syslog((((errno == ENETUNREACH) || (errno == EHOSTUNREACH) || \
83 (errno == ECONNREFUSED)) ? LOG_WARNING : LOG_ERR), message))
85 static int rexmtval = TIMEOUT;
86 static int maxtimeout = 5*TIMEOUT;
87 static int securetftp;
88 static int debug;
89 static int disable_pnp;
90 static int standalone;
91 static uid_t uid_nobody = UID_NOBODY;
92 static uid_t gid_nobody = GID_NOBODY;
93 static int reqsock = -1;
94 /* file descriptor of request socket */
95 static socklen_t fromlen;
96 static socklen_t fromplen;
97 static struct sockaddr_storage client;
98 static struct sockaddr_in6 *sin6_ptr;
99 static struct sockaddr_in *sin_ptr;
100 static struct sockaddr_in6 *from6_ptr;
101 static struct sockaddr_in *from_ptr;
102 static int addrfmly;
103 static int peer;
104 static off_t tsize;
105 static tftpbuf ackbuf;
106 static struct sockaddr_storage from;
107 static boolean_t tsize_set;
108 static pid_t child;
109 /* pid of child handling delayed replys */
110 static int delay_fd [2];
111 /* pipe for communicating with child */
112 static FILE *file;
113 static char *filename;
115 static union {
116 struct tftphdr hdr;
117 char data[SEGSIZE + 4];
118 } buf;
120 static union {
121 struct tftphdr hdr;
122 char data[SEGSIZE];
123 } oackbuf;
125 struct delay_info {
126 long timestamp; /* time request received */
127 int ecode; /* error code to return */
128 struct sockaddr_storage from; /* address of client */
131 int blocksize = SEGSIZE; /* Number of data bytes in a DATA packet */
134 * Default directory for unqualified names
135 * Used by TFTP boot procedures
137 static char *homedir = "/tftpboot";
139 struct formats {
140 char *f_mode;
141 int (*f_validate)(int);
142 void (*f_send)(struct formats *, int);
143 void (*f_recv)(struct formats *, int);
144 int f_convert;
147 static void delayed_responder(void);
148 static void tftp(struct tftphdr *, int);
149 static int validate_filename(int);
150 static void tftpd_sendfile(struct formats *, int);
151 static void tftpd_recvfile(struct formats *, int);
152 static void nak(int);
153 static char *blksize_handler(int, char *, int *);
154 static char *timeout_handler(int, char *, int *);
155 static char *tsize_handler(int, char *, int *);
157 static struct formats formats[] = {
158 { "netascii", validate_filename, tftpd_sendfile, tftpd_recvfile, 1 },
159 { "octet", validate_filename, tftpd_sendfile, tftpd_recvfile, 0 },
160 { NULL }
163 struct options {
164 char *opt_name;
165 char *(*opt_handler)(int, char *, int *);
168 static struct options options[] = {
169 { "blksize", blksize_handler },
170 { "timeout", timeout_handler },
171 { "tsize", tsize_handler },
172 { NULL }
175 static char optbuf[MAX_OPTVAL_LEN];
176 static int timeout;
177 static sigjmp_buf timeoutbuf;
180 main(int argc, char **argv)
182 struct tftphdr *tp;
183 int n;
184 int c;
185 struct passwd *pwd; /* for "nobody" entry */
186 struct in_addr ipv4addr;
187 char abuf[INET6_ADDRSTRLEN];
188 socklen_t addrlen;
190 openlog("tftpd", LOG_PID, LOG_DAEMON);
192 pwd = getpwnam("nobody");
193 if (pwd != NULL) {
194 uid_nobody = pwd->pw_uid;
195 gid_nobody = pwd->pw_gid;
198 /* Tftp will not start new executables; clear the limit set. */
199 (void) __init_daemon_priv(PU_CLEARLIMITSET, uid_nobody, gid_nobody,
200 PRIV_PROC_CHROOT, PRIV_NET_PRIVADDR, NULL);
202 /* Remove the unneeded basic privileges everywhere. */
203 (void) priv_set(PRIV_OFF, PRIV_ALLSETS, PRIV_PROC_EXEC,
204 PRIV_FILE_LINK_ANY, PRIV_PROC_INFO, PRIV_PROC_SESSION, NULL);
206 /* Remove the other privileges from E until we need them. */
207 (void) priv_set(PRIV_OFF, PRIV_EFFECTIVE, PRIV_PROC_CHROOT,
208 PRIV_NET_PRIVADDR, NULL);
210 while ((c = getopt(argc, argv, "dspST:")) != EOF)
211 switch (c) {
212 case 'd': /* enable debug */
213 debug++;
214 continue;
215 case 's': /* secure daemon */
216 securetftp = 1;
217 continue;
218 case 'p': /* disable name pnp mapping */
219 disable_pnp = 1;
220 continue;
221 case 'S':
222 standalone = 1;
223 continue;
224 case 'T':
225 rexmtval = atoi(optarg);
226 if (rexmtval <= 0 || rexmtval > MAX_TIMEOUT) {
227 (void) fprintf(stderr,
228 "%s: Invalid retransmission "
229 "timeout value: %s\n", argv[0], optarg);
230 exit(1);
232 maxtimeout = 5 * rexmtval;
233 continue;
234 case '?':
235 default:
236 usage:
237 (void) fprintf(stderr,
238 "usage: %s [-T rexmtval] [-spd] [home-directory]\n",
239 argv[0]);
240 for (; optind < argc; optind++)
241 syslog(LOG_ERR, "bad argument %s",
242 argv[optind]);
243 exit(1);
246 if (optind < argc)
247 if (optind == argc - 1 && *argv [optind] == '/')
248 homedir = argv [optind];
249 else
250 goto usage;
252 if (pipe(delay_fd) < 0) {
253 syslog(LOG_ERR, "pipe (main): %m");
254 exit(1);
257 (void) sigset(SIGCHLD, SIG_IGN); /* no zombies please */
259 if (standalone) {
260 socklen_t clientlen;
262 sin6_ptr = (struct sockaddr_in6 *)&client;
263 clientlen = sizeof (struct sockaddr_in6);
264 reqsock = socket(AF_INET6, SOCK_DGRAM, 0);
265 if (reqsock == -1) {
266 perror("socket");
267 exit(1);
269 (void) memset(&client, 0, clientlen);
270 sin6_ptr->sin6_family = AF_INET6;
271 sin6_ptr->sin6_port = htons(IPPORT_TFTP);
273 /* Enable privilege as tftp port is < 1024 */
274 (void) priv_set(PRIV_ON,
275 PRIV_EFFECTIVE, PRIV_NET_PRIVADDR, NULL);
276 if (bind(reqsock, (struct sockaddr *)&client,
277 clientlen) == -1) {
278 perror("bind");
279 exit(1);
281 (void) priv_set(PRIV_OFF, PRIV_EFFECTIVE, PRIV_NET_PRIVADDR,
282 NULL);
284 if (debug)
285 (void) puts("running in standalone mode...");
286 } else {
287 /* request socket passed on fd 0 by inetd */
288 reqsock = 0;
290 if (debug) {
291 int on = 1;
293 (void) setsockopt(reqsock, SOL_SOCKET, SO_DEBUG,
294 (char *)&on, sizeof (on));
297 (void) chdir(homedir);
299 (void) priv_set(PRIV_ON, PRIV_EFFECTIVE, PRIV_PROC_FORK, NULL);
300 if ((child = fork()) < 0) {
301 syslog(LOG_ERR, "fork (main): %m");
302 exit(1);
304 (void) priv_set(PRIV_OFF, PRIV_EFFECTIVE, PRIV_PROC_FORK, NULL);
306 if (child == 0) {
307 delayed_responder();
308 } /* child */
310 /* close read side of pipe */
311 (void) close(delay_fd[0]);
315 * Top level handling of incomming tftp requests. Read a request
316 * and pass it off to be handled. If request is valid, handling
317 * forks off and parent returns to this loop. If no new requests
318 * are received for DALLYSECS, exit and return to inetd.
321 for (;;) {
322 fd_set readfds;
323 struct timeval dally;
325 FD_ZERO(&readfds);
326 FD_SET(reqsock, &readfds);
327 dally.tv_sec = DALLYSECS;
328 dally.tv_usec = 0;
330 n = select(reqsock + 1, &readfds, NULL, NULL, &dally);
331 if (n < 0) {
332 if (errno == EINTR)
333 continue;
334 syslog(LOG_ERR, "select: %m");
335 (void) kill(child, SIGKILL);
336 exit(1);
338 if (n == 0) {
339 /* Select timed out. Its time to die. */
340 if (standalone)
341 continue;
342 else {
343 (void) kill(child, SIGKILL);
344 exit(0);
347 addrlen = sizeof (from);
348 if (getsockname(reqsock, (struct sockaddr *)&from,
349 &addrlen) < 0) {
350 syslog(LOG_ERR, "getsockname: %m");
351 exit(1);
354 switch (from.ss_family) {
355 case AF_INET:
356 fromlen = (socklen_t)sizeof (struct sockaddr_in);
357 break;
358 case AF_INET6:
359 fromlen = (socklen_t)sizeof (struct sockaddr_in6);
360 break;
361 default:
362 syslog(LOG_ERR,
363 "Unknown address Family on peer connection %d",
364 from.ss_family);
365 exit(1);
368 n = recvfrom(reqsock, &buf, sizeof (buf), 0,
369 (struct sockaddr *)&from, &fromlen);
370 if (n < 0) {
371 if (errno == EINTR)
372 continue;
373 if (standalone)
374 perror("recvfrom");
375 else
376 syslog(LOG_ERR, "recvfrom: %m");
377 (void) kill(child, SIGKILL);
378 exit(1);
381 (void) alarm(0);
383 switch (from.ss_family) {
384 case AF_INET:
385 addrfmly = AF_INET;
386 fromplen = sizeof (struct sockaddr_in);
387 sin_ptr = (struct sockaddr_in *)&client;
388 (void) memset(&client, 0, fromplen);
389 sin_ptr->sin_family = AF_INET;
390 break;
391 case AF_INET6:
392 addrfmly = AF_INET6;
393 fromplen = sizeof (struct sockaddr_in6);
394 sin6_ptr = (struct sockaddr_in6 *)&client;
395 (void) memset(&client, 0, fromplen);
396 sin6_ptr->sin6_family = AF_INET6;
397 break;
398 default:
399 syslog(LOG_ERR,
400 "Unknown address Family on peer connection");
401 exit(1);
403 peer = socket(addrfmly, SOCK_DGRAM, 0);
404 if (peer < 0) {
405 if (standalone)
406 perror("socket (main)");
407 else
408 syslog(LOG_ERR, "socket (main): %m");
409 (void) kill(child, SIGKILL);
410 exit(1);
412 if (debug) {
413 int on = 1;
415 (void) setsockopt(peer, SOL_SOCKET, SO_DEBUG,
416 (char *)&on, sizeof (on));
419 if (bind(peer, (struct sockaddr *)&client, fromplen) < 0) {
420 if (standalone)
421 perror("bind (main)");
422 else
423 syslog(LOG_ERR, "bind (main): %m");
424 (void) kill(child, SIGKILL);
425 exit(1);
427 if (standalone && debug) {
428 sin6_ptr = (struct sockaddr_in6 *)&client;
429 from6_ptr = (struct sockaddr_in6 *)&from;
430 if (IN6_IS_ADDR_V4MAPPED(&from6_ptr->sin6_addr)) {
431 IN6_V4MAPPED_TO_INADDR(&from6_ptr->sin6_addr,
432 &ipv4addr);
433 (void) inet_ntop(AF_INET, &ipv4addr, abuf,
434 sizeof (abuf));
435 } else {
436 (void) inet_ntop(AF_INET6,
437 &from6_ptr->sin6_addr, abuf,
438 sizeof (abuf));
440 /* get local port */
441 if (getsockname(peer, (struct sockaddr *)&client,
442 &fromplen) < 0)
443 perror("getsockname (main)");
444 (void) fprintf(stderr,
445 "request from %s port %d; local port %d\n",
446 abuf, from6_ptr->sin6_port, sin6_ptr->sin6_port);
448 tp = &buf.hdr;
449 tp->th_opcode = ntohs((ushort_t)tp->th_opcode);
450 if (tp->th_opcode == RRQ || tp->th_opcode == WRQ)
451 tftp(tp, n);
453 (void) close(peer);
454 (void) fclose(file);
457 /*NOTREACHED*/
458 return (0);
461 static void
462 delayed_responder(void)
464 struct delay_info dinfo;
465 long now;
467 /* we don't use the descriptors passed in to the parent */
468 (void) close(0);
469 (void) close(1);
470 if (standalone)
471 (void) close(reqsock);
473 /* close write side of pipe */
474 (void) close(delay_fd[1]);
476 for (;;) {
477 int n;
479 if ((n = read(delay_fd[0], &dinfo,
480 sizeof (dinfo))) != sizeof (dinfo)) {
481 if (n < 0) {
482 if (errno == EINTR)
483 continue;
484 if (standalone)
485 perror("read from pipe "
486 "(delayed responder)");
487 else
488 syslog(LOG_ERR, "read from pipe: %m");
490 exit(1);
492 switch (dinfo.from.ss_family) {
493 case AF_INET:
494 addrfmly = AF_INET;
495 fromplen = sizeof (struct sockaddr_in);
496 sin_ptr = (struct sockaddr_in *)&client;
497 (void) memset(&client, 0, fromplen);
498 sin_ptr->sin_family = AF_INET;
499 break;
500 case AF_INET6:
501 addrfmly = AF_INET6;
502 fromplen = sizeof (struct sockaddr_in6);
503 sin6_ptr = (struct sockaddr_in6 *)&client;
504 (void) memset(&client, 0, fromplen);
505 sin6_ptr->sin6_family = AF_INET6;
506 break;
508 peer = socket(addrfmly, SOCK_DGRAM, 0);
509 if (peer == -1) {
510 if (standalone)
511 perror("socket (delayed responder)");
512 else
513 syslog(LOG_ERR, "socket (delay): %m");
514 exit(1);
516 if (debug) {
517 int on = 1;
519 (void) setsockopt(peer, SOL_SOCKET, SO_DEBUG,
520 (char *)&on, sizeof (on));
523 if (bind(peer, (struct sockaddr *)&client, fromplen) < 0) {
524 if (standalone)
525 perror("bind (delayed responder)");
526 else
527 syslog(LOG_ERR, "bind (delay): %m");
528 exit(1);
530 if (client.ss_family == AF_INET) {
531 from_ptr = (struct sockaddr_in *)&dinfo.from;
532 from_ptr->sin_family = AF_INET;
533 } else {
534 from6_ptr = (struct sockaddr_in6 *)&dinfo.from;
535 from6_ptr->sin6_family = AF_INET6;
538 * Since a request hasn't been received from the client
539 * before the delayed responder process is forked, the
540 * from variable is uninitialized. So set it to contain
541 * the client address.
543 from = dinfo.from;
546 * only sleep if DELAY_SECS has not elapsed since
547 * original request was received. Ensure that `now'
548 * is not earlier than `dinfo.timestamp'
550 now = time(0);
551 if ((uint_t)(now - dinfo.timestamp) < DELAY_SECS)
552 (void) sleep(DELAY_SECS - (now - dinfo.timestamp));
553 nak(dinfo.ecode);
554 (void) close(peer);
555 } /* for */
557 /* NOTREACHED */
561 * Handle the Blocksize option.
562 * Return the blksize option value string to include in the OACK reply.
564 /*ARGSUSED*/
565 static char *
566 blksize_handler(int opcode, char *optval, int *errcode)
568 char *endp;
569 int value;
571 *errcode = -1;
572 errno = 0;
573 value = (int)strtol(optval, &endp, 10);
574 if (errno != 0 || value < MIN_BLKSIZE || *endp != '\0')
575 return (NULL);
577 * As the blksize value in the OACK reply can be less than the value
578 * requested, to support broken clients if the value requested is larger
579 * than allowed in the RFC, reply with the maximum value permitted.
581 if (value > MAX_BLKSIZE)
582 value = MAX_BLKSIZE;
584 blocksize = value;
585 (void) snprintf(optbuf, sizeof (optbuf), "%d", blocksize);
586 return (optbuf);
590 * Handle the Timeout Interval option.
591 * Return the timeout option value string to include in the OACK reply.
593 /*ARGSUSED*/
594 static char *
595 timeout_handler(int opcode, char *optval, int *errcode)
597 char *endp;
598 int value;
600 *errcode = -1;
601 errno = 0;
602 value = (int)strtol(optval, &endp, 10);
603 if (errno != 0 || *endp != '\0')
604 return (NULL);
606 * The timeout value in the OACK reply must match the value specified
607 * by the client, so if an invalid timeout is requested don't include
608 * the timeout option in the OACK reply.
610 if (value < MIN_TIMEOUT || value > MAX_TIMEOUT)
611 return (NULL);
613 rexmtval = value;
614 maxtimeout = 5 * rexmtval;
615 (void) snprintf(optbuf, sizeof (optbuf), "%d", rexmtval);
616 return (optbuf);
620 * Handle the Transfer Size option.
621 * Return the tsize option value string to include in the OACK reply.
623 static char *
624 tsize_handler(int opcode, char *optval, int *errcode)
626 char *endp;
627 longlong_t value;
629 *errcode = -1;
630 errno = 0;
631 value = strtoll(optval, &endp, 10);
632 if (errno != 0 || value < 0 || *endp != '\0')
633 return (NULL);
635 if (opcode == RRQ) {
636 if (tsize_set == B_FALSE)
637 return (NULL);
639 * The tsize value should be 0 for a read request, but to
640 * support broken clients we don't check that it is.
642 } else {
643 tsize = value;
644 tsize_set = B_TRUE;
646 (void) snprintf(optbuf, sizeof (optbuf), OFF_T_FMT, tsize);
647 return (optbuf);
651 * Process any options included by the client in the request packet.
652 * Return the size of the OACK reply packet built or 0 for no OACK reply.
654 static int
655 process_options(int opcode, char *opts, char *endopts)
657 char *cp, *optname, *optval, *ostr, *oackend;
658 struct tftphdr *oackp;
659 int i, errcode;
662 * To continue to interoperate with broken TFTP clients, ignore
663 * null padding appended to requests which don't include options.
665 cp = opts;
666 while ((cp < endopts) && (*cp == '\0'))
667 cp++;
668 if (cp == endopts)
669 return (0);
672 * Construct an Option ACKnowledgement packet if any requested option
673 * is recognized.
675 oackp = &oackbuf.hdr;
676 oackend = oackbuf.data + sizeof (oackbuf.data);
677 oackp->th_opcode = htons((ushort_t)OACK);
678 cp = (char *)&oackp->th_stuff;
679 while (opts < endopts) {
680 optname = opts;
681 if ((optval = next_field(optname, endopts)) == NULL) {
682 nak(EOPTNEG);
683 exit(1);
685 if ((opts = next_field(optval, endopts)) == NULL) {
686 nak(EOPTNEG);
687 exit(1);
689 for (i = 0; options[i].opt_name != NULL; i++) {
690 if (strcasecmp(optname, options[i].opt_name) == 0)
691 break;
693 if (options[i].opt_name != NULL) {
694 ostr = options[i].opt_handler(opcode, optval, &errcode);
695 if (ostr != NULL) {
696 cp += strlcpy(cp, options[i].opt_name,
697 oackend - cp) + 1;
698 if (cp <= oackend)
699 cp += strlcpy(cp, ostr, oackend - cp)
700 + 1;
702 if (cp > oackend) {
703 nak(EOPTNEG);
704 exit(1);
706 } else if (errcode >= 0) {
707 nak(errcode);
708 exit(1);
712 if (cp != (char *)&oackp->th_stuff)
713 return (cp - oackbuf.data);
714 return (0);
718 * Handle access errors caused by client requests.
721 static void
722 delay_exit(int ecode)
724 struct delay_info dinfo;
727 * The most likely cause of an error here is that
728 * something has broadcast an RRQ packet because it's
729 * trying to boot and doesn't know who the server is.
730 * Rather then sending an ERROR packet immediately, we
731 * wait a while so that the real server has a better chance
732 * of getting through (in case client has lousy Ethernet
733 * interface). We write to a child that handles delayed
734 * ERROR packets to avoid delaying service to new
735 * requests. Of course, we would rather just not answer
736 * RRQ packets that are broadcasted, but there's no way
737 * for a user process to determine this.
740 dinfo.timestamp = time(0);
743 * If running in secure mode, we map all errors to EACCESS
744 * so that the client gets no information about which files
745 * or directories exist.
747 if (securetftp)
748 dinfo.ecode = EACCESS;
749 else
750 dinfo.ecode = ecode;
752 dinfo.from = from;
753 if (write(delay_fd[1], &dinfo, sizeof (dinfo)) !=
754 sizeof (dinfo)) {
755 syslog(LOG_ERR, "delayed write failed.");
756 (void) kill(child, SIGKILL);
757 exit(1);
759 exit(0);
763 * Handle initial connection protocol.
765 static void
766 tftp(struct tftphdr *tp, int size)
768 char *cp;
769 int readmode, ecode;
770 struct formats *pf;
771 char *mode;
772 int fd;
773 static boolean_t firsttime = B_TRUE;
774 int oacklen;
775 struct stat statb;
777 readmode = (tp->th_opcode == RRQ);
778 filename = (char *)&tp->th_stuff;
779 mode = next_field(filename, &buf.data[size]);
780 cp = (mode != NULL) ? next_field(mode, &buf.data[size]) : NULL;
781 if (cp == NULL) {
782 nak(EBADOP);
783 exit(1);
785 if (debug && standalone) {
786 (void) fprintf(stderr, "%s for %s %s ",
787 readmode ? "RRQ" : "WRQ", filename, mode);
788 print_options(stderr, cp, size + buf.data - cp);
789 (void) putc('\n', stderr);
791 for (pf = formats; pf->f_mode != NULL; pf++)
792 if (strcasecmp(pf->f_mode, mode) == 0)
793 break;
794 if (pf->f_mode == NULL) {
795 nak(EBADOP);
796 exit(1);
800 * XXX fork a new process to handle this request before
801 * chroot(), otherwise the parent won't be able to create a
802 * new socket as that requires library access to system files
803 * and devices.
805 (void) priv_set(PRIV_ON, PRIV_EFFECTIVE, PRIV_PROC_FORK, NULL);
806 switch (fork()) {
807 case -1:
808 syslog(LOG_ERR, "fork (tftp): %m");
809 (void) priv_set(PRIV_OFF, PRIV_EFFECTIVE, PRIV_PROC_FORK, NULL);
810 return;
811 case 0:
812 (void) priv_set(PRIV_OFF, PRIV_EFFECTIVE, PRIV_PROC_FORK, NULL);
813 break;
814 default:
815 (void) priv_set(PRIV_OFF, PRIV_EFFECTIVE, PRIV_PROC_FORK, NULL);
816 return;
820 * Try to see if we can access the file. The access can still
821 * fail later if we are running in secure mode because of
822 * the chroot() call. We only want to execute the chroot() once.
824 if (securetftp && firsttime) {
825 (void) priv_set(PRIV_ON, PRIV_EFFECTIVE, PRIV_PROC_CHROOT,
826 NULL);
827 if (chroot(homedir) == -1) {
828 syslog(LOG_ERR,
829 "tftpd: cannot chroot to directory %s: %m\n",
830 homedir);
831 delay_exit(EACCESS);
833 else
835 firsttime = B_FALSE;
837 (void) priv_set(PRIV_OFF, PRIV_EFFECTIVE, PRIV_PROC_CHROOT,
838 NULL);
839 (void) chdir("/"); /* cd to new root */
841 (void) priv_set(PRIV_OFF, PRIV_ALLSETS, PRIV_PROC_CHROOT,
842 PRIV_NET_PRIVADDR, NULL);
844 ecode = (*pf->f_validate)(tp->th_opcode);
845 if (ecode != 0)
846 delay_exit(ecode);
848 /* we don't use the descriptors passed in to the parent */
849 (void) close(STDIN_FILENO);
850 (void) close(STDOUT_FILENO);
853 * Try to open file as low-priv setuid/setgid. Note that
854 * a chroot() has already been done.
856 fd = open(filename,
857 (readmode ? O_RDONLY : (O_WRONLY|O_TRUNC)) | O_NONBLOCK);
858 if ((fd < 0) || (fstat(fd, &statb) < 0))
859 delay_exit((errno == ENOENT) ? ENOTFOUND : EACCESS);
861 if (((statb.st_mode & ((readmode) ? S_IROTH : S_IWOTH)) == 0) ||
862 ((statb.st_mode & S_IFMT) != S_IFREG))
863 delay_exit(EACCESS);
865 file = fdopen(fd, readmode ? "r" : "w");
866 if (file == NULL)
867 delay_exit(errno + 100);
869 /* Don't know the size of transfers which involve conversion */
870 tsize_set = (readmode && (pf->f_convert == 0));
871 if (tsize_set)
872 tsize = statb.st_size;
874 /* Deal with any options sent by the client */
875 oacklen = process_options(tp->th_opcode, cp, buf.data + size);
877 if (tp->th_opcode == WRQ)
878 (*pf->f_recv)(pf, oacklen);
879 else
880 (*pf->f_send)(pf, oacklen);
882 exit(0);
886 * Maybe map filename into another one.
888 * For PNP, we get TFTP boot requests for filenames like
889 * <Unknown Hex IP Addr>.<Architecture Name>. We must
890 * map these to 'pnp.<Architecture Name>'. Note that
891 * uppercase is mapped to lowercase in the architecture names.
893 * For names <Hex IP Addr> there are two cases. First,
894 * it may be a buggy prom that omits the architecture code.
895 * So first check if <Hex IP Addr>.<arch> is on the filesystem.
896 * Second, this is how most Sun3s work; assume <arch> is sun3.
899 static char *
900 pnp_check(char *origname)
902 static char buf [MAXNAMLEN + 1];
903 char *arch, *s, *bufend;
904 in_addr_t ipaddr;
905 int len = (origname ? strlen(origname) : 0);
906 DIR *dir;
907 struct dirent *dp;
909 if (securetftp || disable_pnp || len < 8 || len > 14)
910 return (NULL);
913 * XXX see if this cable allows pnp; if not, return NULL
914 * Requires YP support for determining this!
917 ipaddr = htonl(strtol(origname, &arch, 16));
918 if ((arch == NULL) || (len > 8 && *arch != '.'))
919 return (NULL);
920 if (len == 8)
921 arch = "SUN3";
922 else
923 arch++;
926 * Allow <Hex IP Addr>* filename request to to be
927 * satisfied by <Hex IP Addr><Any Suffix> rather
928 * than enforcing this to be Sun3 systems. Also serves
929 * to make case of suffix a don't-care.
931 if ((dir = opendir(homedir)) == NULL)
932 return (NULL);
933 while ((dp = readdir(dir)) != NULL) {
934 if (strncmp(origname, dp->d_name, 8) == 0) {
935 (void) strlcpy(buf, dp->d_name, sizeof (buf));
936 (void) closedir(dir);
937 return (buf);
940 (void) closedir(dir);
943 * XXX maybe call YP master for most current data iff
944 * pnp is enabled.
948 * only do mapping PNP boot file name for machines that
949 * are not in the hosts database.
951 if (gethostbyaddr((char *)&ipaddr, sizeof (ipaddr), AF_INET) != NULL)
952 return (NULL);
954 s = buf + strlcpy(buf, "pnp.", sizeof (buf));
955 bufend = &buf[sizeof (buf) - 1];
956 while ((*arch != '\0') && (s < bufend))
957 *s++ = tolower (*arch++);
958 *s = '\0';
959 return (buf);
964 * Try to validate filename. If the filename doesn't exist try PNP mapping.
966 static int
967 validate_filename(int mode)
969 struct stat stbuf;
970 char *origfile;
972 if (stat(filename, &stbuf) < 0) {
973 if (errno != ENOENT)
974 return (EACCESS);
975 if (mode == WRQ)
976 return (ENOTFOUND);
978 /* try to map requested filename into a pnp filename */
979 origfile = filename;
980 filename = pnp_check(origfile);
981 if (filename == NULL)
982 return (ENOTFOUND);
984 if (stat(filename, &stbuf) < 0)
985 return (errno == ENOENT ? ENOTFOUND : EACCESS);
986 syslog(LOG_NOTICE, "%s -> %s\n", origfile, filename);
989 return (0);
992 /* ARGSUSED */
993 static void
994 timer(int signum)
996 timeout += rexmtval;
997 if (timeout >= maxtimeout)
998 exit(1);
999 siglongjmp(timeoutbuf, 1);
1003 * Send the requested file.
1005 static void
1006 tftpd_sendfile(struct formats *pf, int oacklen)
1008 struct tftphdr *dp;
1009 volatile ushort_t block = 1;
1010 int size, n, serrno;
1012 if (oacklen != 0) {
1013 (void) sigset(SIGALRM, timer);
1014 timeout = 0;
1015 (void) sigsetjmp(timeoutbuf, 1);
1016 if (debug && standalone) {
1017 (void) fputs("Sending OACK ", stderr);
1018 print_options(stderr, (char *)&oackbuf.hdr.th_stuff,
1019 oacklen - 2);
1020 (void) putc('\n', stderr);
1022 if (sendto(peer, &oackbuf, oacklen, 0,
1023 (struct sockaddr *)&from, fromplen) != oacklen) {
1024 if (debug && standalone) {
1025 serrno = errno;
1026 perror("sendto (oack)");
1027 errno = serrno;
1029 SYSLOG_MSG("sendto (oack): %m");
1030 goto abort;
1032 (void) alarm(rexmtval); /* read the ack */
1033 for (;;) {
1034 (void) sigrelse(SIGALRM);
1035 n = recv(peer, &ackbuf, sizeof (ackbuf), 0);
1036 (void) sighold(SIGALRM);
1037 if (n < 0) {
1038 if (errno == EINTR)
1039 continue;
1040 serrno = errno;
1041 SYSLOG_MSG("recv (ack): %m");
1042 if (debug && standalone) {
1043 errno = serrno;
1044 perror("recv (ack)");
1046 goto abort;
1048 ackbuf.tb_hdr.th_opcode =
1049 ntohs((ushort_t)ackbuf.tb_hdr.th_opcode);
1050 ackbuf.tb_hdr.th_block =
1051 ntohs((ushort_t)ackbuf.tb_hdr.th_block);
1053 if (ackbuf.tb_hdr.th_opcode == ERROR) {
1054 if (debug && standalone) {
1055 (void) fprintf(stderr,
1056 "received ERROR %d",
1057 ackbuf.tb_hdr.th_code);
1058 if (n > 4)
1059 (void) fprintf(stderr,
1060 " %.*s", n - 4,
1061 ackbuf.tb_hdr.th_msg);
1062 (void) putc('\n', stderr);
1064 goto abort;
1067 if (ackbuf.tb_hdr.th_opcode == ACK) {
1068 if (debug && standalone)
1069 (void) fprintf(stderr,
1070 "received ACK for block %d\n",
1071 ackbuf.tb_hdr.th_block);
1072 if (ackbuf.tb_hdr.th_block == 0)
1073 break;
1075 * Don't resend the OACK, avoids getting stuck
1076 * in an OACK/ACK loop if the client keeps
1077 * replying with a bad ACK. Client will either
1078 * send a good ACK or timeout sending bad ones.
1082 cancel_alarm();
1084 dp = r_init();
1085 do {
1086 (void) sigset(SIGALRM, timer);
1087 size = readit(file, &dp, pf->f_convert);
1088 if (size < 0) {
1089 nak(errno + 100);
1090 goto abort;
1092 dp->th_opcode = htons((ushort_t)DATA);
1093 dp->th_block = htons((ushort_t)block);
1094 timeout = 0;
1095 (void) sigsetjmp(timeoutbuf, 1);
1096 if (debug && standalone)
1097 (void) fprintf(stderr, "Sending DATA block %d\n",
1098 block);
1099 if (sendto(peer, dp, size + 4, 0,
1100 (struct sockaddr *)&from, fromplen) != size + 4) {
1101 if (debug && standalone) {
1102 serrno = errno;
1103 perror("sendto (data)");
1104 errno = serrno;
1106 SYSLOG_MSG("sendto (data): %m");
1107 goto abort;
1109 read_ahead(file, pf->f_convert);
1110 (void) alarm(rexmtval); /* read the ack */
1111 for (;;) {
1112 (void) sigrelse(SIGALRM);
1113 n = recv(peer, &ackbuf, sizeof (ackbuf), 0);
1114 (void) sighold(SIGALRM);
1115 if (n < 0) {
1116 if (errno == EINTR)
1117 continue;
1118 serrno = errno;
1119 SYSLOG_MSG("recv (ack): %m");
1120 if (debug && standalone) {
1121 errno = serrno;
1122 perror("recv (ack)");
1124 goto abort;
1126 ackbuf.tb_hdr.th_opcode =
1127 ntohs((ushort_t)ackbuf.tb_hdr.th_opcode);
1128 ackbuf.tb_hdr.th_block =
1129 ntohs((ushort_t)ackbuf.tb_hdr.th_block);
1131 if (ackbuf.tb_hdr.th_opcode == ERROR) {
1132 if (debug && standalone) {
1133 (void) fprintf(stderr,
1134 "received ERROR %d",
1135 ackbuf.tb_hdr.th_code);
1136 if (n > 4)
1137 (void) fprintf(stderr,
1138 " %.*s", n - 4,
1139 ackbuf.tb_hdr.th_msg);
1140 (void) putc('\n', stderr);
1142 goto abort;
1145 if (ackbuf.tb_hdr.th_opcode == ACK) {
1146 if (debug && standalone)
1147 (void) fprintf(stderr,
1148 "received ACK for block %d\n",
1149 ackbuf.tb_hdr.th_block);
1150 if (ackbuf.tb_hdr.th_block == block) {
1151 break;
1154 * Never resend the current DATA packet on
1155 * receipt of a duplicate ACK, doing so would
1156 * cause the "Sorcerer's Apprentice Syndrome".
1160 cancel_alarm();
1161 block++;
1162 } while (size == blocksize);
1164 abort:
1165 cancel_alarm();
1166 (void) fclose(file);
1169 /* ARGSUSED */
1170 static void
1171 justquit(int signum)
1173 exit(0);
1177 * Receive a file.
1179 static void
1180 tftpd_recvfile(struct formats *pf, int oacklen)
1182 struct tftphdr *dp;
1183 struct tftphdr *ap; /* ack buffer */
1184 ushort_t block = 0;
1185 int n, size, acklen, serrno;
1187 dp = w_init();
1188 ap = &ackbuf.tb_hdr;
1189 do {
1190 (void) sigset(SIGALRM, timer);
1191 timeout = 0;
1192 if (oacklen == 0) {
1193 ap->th_opcode = htons((ushort_t)ACK);
1194 ap->th_block = htons((ushort_t)block);
1195 acklen = 4;
1196 } else {
1197 /* copy OACK packet to the ack buffer ready to send */
1198 (void) memcpy(&ackbuf, &oackbuf, oacklen);
1199 acklen = oacklen;
1200 oacklen = 0;
1202 block++;
1203 (void) sigsetjmp(timeoutbuf, 1);
1204 send_ack:
1205 if (debug && standalone) {
1206 if (ap->th_opcode == htons((ushort_t)ACK)) {
1207 (void) fprintf(stderr,
1208 "Sending ACK for block %d\n", block - 1);
1209 } else {
1210 (void) fprintf(stderr, "Sending OACK ");
1211 print_options(stderr, (char *)&ap->th_stuff,
1212 acklen - 2);
1213 (void) putc('\n', stderr);
1216 if (sendto(peer, &ackbuf, acklen, 0, (struct sockaddr *)&from,
1217 fromplen) != acklen) {
1218 if (ap->th_opcode == htons((ushort_t)ACK)) {
1219 if (debug && standalone) {
1220 serrno = errno;
1221 perror("sendto (ack)");
1222 errno = serrno;
1224 syslog(LOG_ERR, "sendto (ack): %m\n");
1225 } else {
1226 if (debug && standalone) {
1227 serrno = errno;
1228 perror("sendto (oack)");
1229 errno = serrno;
1231 syslog(LOG_ERR, "sendto (oack): %m\n");
1233 goto abort;
1235 if (write_behind(file, pf->f_convert) < 0) {
1236 nak(errno + 100);
1237 goto abort;
1239 (void) alarm(rexmtval);
1240 for (;;) {
1241 (void) sigrelse(SIGALRM);
1242 n = recv(peer, dp, blocksize + 4, 0);
1243 (void) sighold(SIGALRM);
1244 if (n < 0) { /* really? */
1245 if (errno == EINTR)
1246 continue;
1247 syslog(LOG_ERR, "recv (data): %m");
1248 goto abort;
1250 dp->th_opcode = ntohs((ushort_t)dp->th_opcode);
1251 dp->th_block = ntohs((ushort_t)dp->th_block);
1252 if (dp->th_opcode == ERROR) {
1253 cancel_alarm();
1254 if (debug && standalone) {
1255 (void) fprintf(stderr,
1256 "received ERROR %d", dp->th_code);
1257 if (n > 4)
1258 (void) fprintf(stderr,
1259 " %.*s", n - 4, dp->th_msg);
1260 (void) putc('\n', stderr);
1262 return;
1264 if (dp->th_opcode == DATA) {
1265 if (debug && standalone)
1266 (void) fprintf(stderr,
1267 "Received DATA block %d\n",
1268 dp->th_block);
1269 if (dp->th_block == block) {
1270 break; /* normal */
1272 /* Re-synchronize with the other side */
1273 if (synchnet(peer) < 0) {
1274 nak(errno + 100);
1275 goto abort;
1277 if (dp->th_block == (block-1))
1278 goto send_ack; /* rexmit */
1281 cancel_alarm();
1282 /* size = write(file, dp->th_data, n - 4); */
1283 size = writeit(file, &dp, n - 4, pf->f_convert);
1284 if (size != (n - 4)) {
1285 nak((size < 0) ? (errno + 100) : ENOSPACE);
1286 goto abort;
1288 } while (size == blocksize);
1289 if (write_behind(file, pf->f_convert) < 0) {
1290 nak(errno + 100);
1291 goto abort;
1293 n = fclose(file); /* close data file */
1294 file = NULL;
1295 if (n == EOF) {
1296 nak(errno + 100);
1297 goto abort;
1300 ap->th_opcode = htons((ushort_t)ACK); /* send the "final" ack */
1301 ap->th_block = htons((ushort_t)(block));
1302 if (debug && standalone)
1303 (void) fprintf(stderr, "Sending ACK for block %d\n", block);
1304 if (sendto(peer, &ackbuf, 4, 0, (struct sockaddr *)&from,
1305 fromplen) == -1) {
1306 if (debug && standalone)
1307 perror("sendto (ack)");
1309 (void) sigset(SIGALRM, justquit); /* just quit on timeout */
1310 (void) alarm(rexmtval);
1311 /* normally times out and quits */
1312 n = recv(peer, dp, blocksize + 4, 0);
1313 (void) alarm(0);
1314 dp->th_opcode = ntohs((ushort_t)dp->th_opcode);
1315 dp->th_block = ntohs((ushort_t)dp->th_block);
1316 if (n >= 4 && /* if read some data */
1317 dp->th_opcode == DATA && /* and got a data block */
1318 block == dp->th_block) { /* then my last ack was lost */
1319 if (debug && standalone) {
1320 (void) fprintf(stderr, "Sending ACK for block %d\n",
1321 block);
1323 /* resend final ack */
1324 if (sendto(peer, &ackbuf, 4, 0, (struct sockaddr *)&from,
1325 fromplen) == -1) {
1326 if (debug && standalone)
1327 perror("sendto (last ack)");
1331 abort:
1332 cancel_alarm();
1333 if (file != NULL)
1334 (void) fclose(file);
1338 * Send a nak packet (error message).
1339 * Error code passed in is one of the
1340 * standard TFTP codes, or a UNIX errno
1341 * offset by 100.
1342 * Handles connected as well as unconnected peer.
1344 static void
1345 nak(int error)
1347 struct tftphdr *tp;
1348 int length;
1349 struct errmsg *pe;
1350 int ret;
1352 tp = &buf.hdr;
1353 tp->th_opcode = htons((ushort_t)ERROR);
1354 tp->th_code = htons((ushort_t)error);
1355 for (pe = errmsgs; pe->e_code >= 0; pe++)
1356 if (pe->e_code == error)
1357 break;
1358 if (pe->e_code < 0) {
1359 pe->e_msg = strerror(error - 100);
1360 tp->th_code = EUNDEF; /* set 'undef' errorcode */
1362 (void) strlcpy(tp->th_msg, (pe->e_msg != NULL) ? pe->e_msg : "UNKNOWN",
1363 sizeof (buf) - sizeof (struct tftphdr));
1364 length = strlen(tp->th_msg);
1365 length += sizeof (struct tftphdr);
1366 if (debug && standalone)
1367 (void) fprintf(stderr, "Sending NAK: %s\n", tp->th_msg);
1369 ret = sendto(peer, &buf, length, 0, (struct sockaddr *)&from,
1370 fromplen);
1371 if (ret == -1 && errno == EISCONN) {
1372 /* Try without an address */
1373 ret = send(peer, &buf, length, 0);
1375 if (ret == -1) {
1376 if (standalone)
1377 perror("sendto (nak)");
1378 else
1379 syslog(LOG_ERR, "tftpd: nak: %m\n");
1380 } else if (ret != length) {
1381 if (standalone)
1382 perror("sendto (nak) lost data");
1383 else
1384 syslog(LOG_ERR, "tftpd: nak: %d lost\n", length - ret);