]> git.saurik.com Git - apple/network_cmds.git/blob - tftpd.tproj/tftpd.c
20146c0843212d26e64e3594d44a739920775019
[apple/network_cmds.git] / tftpd.tproj / tftpd.c
1 /*
2 * Copyright (c) 1983, 1993
3 * The Regents of the University of California. All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
13 * 3. All advertising materials mentioning features or use of this software
14 * must display the following acknowledgement:
15 * This product includes software developed by the University of
16 * California, Berkeley and its contributors.
17 * 4. Neither the name of the University nor the names of its contributors
18 * may be used to endorse or promote products derived from this software
19 * without specific prior written permission.
20 *
21 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31 * SUCH DAMAGE.
32 */
33
34 #ifndef lint
35 static const char copyright[] =
36 "@(#) Copyright (c) 1983, 1993\n\
37 The Regents of the University of California. All rights reserved.\n";
38 #endif /* not lint */
39
40 #ifndef lint
41 #if 0
42 static char sccsid[] = "@(#)tftpd.c 8.1 (Berkeley) 6/4/93";
43 #endif
44 static const char rcsid[] =
45 "$FreeBSD: src/libexec/tftpd/tftpd.c,v 1.18 2001/02/02 10:52:58 asmodai Exp $";
46 #endif /* not lint */
47
48 /*
49 * Trivial file transfer protocol server.
50 *
51 * This version includes many modifications by Jim Guyton
52 * <guyton@rand-unix>.
53 */
54
55 #include <sys/param.h>
56 #include <sys/ioctl.h>
57 #include <sys/stat.h>
58 #include <sys/socket.h>
59 #include <sys/types.h>
60
61 #include <netinet/in.h>
62 #include <arpa/tftp.h>
63 #include <arpa/inet.h>
64
65 #include <ctype.h>
66 #include <errno.h>
67 #include <fcntl.h>
68 #include <netdb.h>
69 #include <pwd.h>
70 #include <setjmp.h>
71 #include <signal.h>
72 #include <stdio.h>
73 #include <stdlib.h>
74 #include <string.h>
75 #include <syslog.h>
76 #include <unistd.h>
77
78 #include "tftpsubs.h"
79
80 #define TIMEOUT 5
81
82 int peer;
83 int rexmtval = TIMEOUT;
84 int maxtimeout = 5*TIMEOUT;
85
86 #define PKTSIZE SEGSIZE+4
87 char buf[PKTSIZE];
88 char ackbuf[PKTSIZE];
89 struct sockaddr_in from;
90 int fromlen;
91
92 void tftp __P((struct tftphdr *, int));
93
94 /*
95 * Null-terminated directory prefix list for absolute pathname requests and
96 * search list for relative pathname requests.
97 *
98 * MAXDIRS should be at least as large as the number of arguments that
99 * inetd allows (currently 20).
100 */
101 #define MAXDIRS 20
102 static struct dirlist {
103 char *name;
104 int len;
105 } dirs[MAXDIRS+1];
106 static int suppress_naks;
107 static int logging;
108 static int ipchroot;
109
110 static char *errtomsg __P((int));
111 static void nak __P((int));
112 static char * __P(verifyhost(struct sockaddr_in *));
113
114 int
115 main(argc, argv)
116 int argc;
117 char *argv[];
118 {
119 register struct tftphdr *tp;
120 register int n;
121 int ch, on;
122 struct sockaddr_in sin;
123 char *chroot_dir = NULL;
124 struct passwd *nobody;
125 char *chuser = "nobody";
126
127 openlog("tftpd", LOG_PID | LOG_NDELAY, LOG_FTP);
128 while ((ch = getopt(argc, argv, "cClns:u:")) != -1) {
129 switch (ch) {
130 case 'c':
131 ipchroot = 1;
132 break;
133 case 'C':
134 ipchroot = 2;
135 break;
136 case 'l':
137 logging = 1;
138 break;
139 case 'n':
140 suppress_naks = 1;
141 break;
142 case 's':
143 chroot_dir = optarg;
144 break;
145 case 'u':
146 chuser = optarg;
147 break;
148 default:
149 syslog(LOG_WARNING, "ignoring unknown option -%c", ch);
150 }
151 }
152 if (optind < argc) {
153 struct dirlist *dirp;
154
155 /* Get list of directory prefixes. Skip relative pathnames. */
156 for (dirp = dirs; optind < argc && dirp < &dirs[MAXDIRS];
157 optind++) {
158 if (argv[optind][0] == '/') {
159 dirp->name = argv[optind];
160 dirp->len = strlen(dirp->name);
161 dirp++;
162 }
163 }
164 }
165 else if (chroot_dir) {
166 dirs->name = "/";
167 dirs->len = 1;
168 }
169 if (ipchroot && chroot_dir == NULL) {
170 syslog(LOG_ERR, "-c requires -s");
171 exit(1);
172 }
173
174 on = 1;
175 if (ioctl(0, FIONBIO, &on) < 0) {
176 syslog(LOG_ERR, "ioctl(FIONBIO): %m");
177 exit(1);
178 }
179 fromlen = sizeof (from);
180 n = recvfrom(0, buf, sizeof (buf), 0,
181 (struct sockaddr *)&from, &fromlen);
182 if (n < 0) {
183 syslog(LOG_ERR, "recvfrom: %m");
184 exit(1);
185 }
186 /*
187 * Now that we have read the message out of the UDP
188 * socket, we fork and exit. Thus, inetd will go back
189 * to listening to the tftp port, and the next request
190 * to come in will start up a new instance of tftpd.
191 *
192 * We do this so that inetd can run tftpd in "wait" mode.
193 * The problem with tftpd running in "nowait" mode is that
194 * inetd may get one or more successful "selects" on the
195 * tftp port before we do our receive, so more than one
196 * instance of tftpd may be started up. Worse, if tftpd
197 * break before doing the above "recvfrom", inetd would
198 * spawn endless instances, clogging the system.
199 */
200 {
201 int pid;
202 int i, j;
203
204 for (i = 1; i < 20; i++) {
205 pid = fork();
206 if (pid < 0) {
207 sleep(i);
208 /*
209 * flush out to most recently sent request.
210 *
211 * This may drop some request, but those
212 * will be resent by the clients when
213 * they timeout. The positive effect of
214 * this flush is to (try to) prevent more
215 * than one tftpd being started up to service
216 * a single request from a single client.
217 */
218 j = sizeof from;
219 i = recvfrom(0, buf, sizeof (buf), 0,
220 (struct sockaddr *)&from, &j);
221 if (i > 0) {
222 n = i;
223 fromlen = j;
224 }
225 } else {
226 break;
227 }
228 }
229 if (pid < 0) {
230 syslog(LOG_ERR, "fork: %m");
231 exit(1);
232 } else if (pid != 0) {
233 exit(0);
234 }
235 }
236
237 /*
238 * Since we exit here, we should do that only after the above
239 * recvfrom to keep inetd from constantly forking should there
240 * be a problem. See the above comment about system clogging.
241 */
242 if (chroot_dir) {
243 if (ipchroot) {
244 char tempchroot[MAXPATHLEN];
245 char *tempaddr;
246 struct stat sb;
247 int statret;
248
249 tempaddr = inet_ntoa(from.sin_addr);
250 snprintf(tempchroot, sizeof(tempchroot), "%s/%s", chroot_dir, tempaddr);
251 statret = stat(tempchroot, &sb);
252 if ((sb.st_mode & S_IFDIR) &&
253 (statret == 0 || (statret == -1 && ipchroot == 1)))
254 chroot_dir = tempchroot;
255 }
256 /* Must get this before chroot because /etc might go away */
257 if ((nobody = getpwnam(chuser)) == NULL) {
258 syslog(LOG_ERR, "%s: no such user", chuser);
259 exit(1);
260 }
261 if (chroot(chroot_dir)) {
262 syslog(LOG_ERR, "chroot: %s: %m", chroot_dir);
263 exit(1);
264 }
265 chdir( "/" );
266 setuid(nobody->pw_uid);
267 }
268
269 from.sin_family = AF_INET;
270 alarm(0);
271 close(0);
272 close(1);
273 peer = socket(AF_INET, SOCK_DGRAM, 0);
274 if (peer < 0) {
275 syslog(LOG_ERR, "socket: %m");
276 exit(1);
277 }
278 memset(&sin, 0, sizeof(sin));
279 sin.sin_family = AF_INET;
280 if (bind(peer, (struct sockaddr *)&sin, sizeof (sin)) < 0) {
281 syslog(LOG_ERR, "bind: %m");
282 exit(1);
283 }
284 if (connect(peer, (struct sockaddr *)&from, sizeof(from)) < 0) {
285 syslog(LOG_ERR, "connect: %m");
286 exit(1);
287 }
288 tp = (struct tftphdr *)buf;
289 tp->th_opcode = ntohs(tp->th_opcode);
290 if (tp->th_opcode == RRQ || tp->th_opcode == WRQ)
291 tftp(tp, n);
292 exit(1);
293 }
294
295 struct formats;
296 int validate_access __P((char **, int));
297 void xmitfile __P((struct formats *));
298 void recvfile __P((struct formats *));
299
300 struct formats {
301 char *f_mode;
302 int (*f_validate) __P((char **, int));
303 void (*f_send) __P((struct formats *));
304 void (*f_recv) __P((struct formats *));
305 int f_convert;
306 } formats[] = {
307 { "netascii", validate_access, xmitfile, recvfile, 1 },
308 { "octet", validate_access, xmitfile, recvfile, 0 },
309 #ifdef notdef
310 { "mail", validate_user, sendmail, recvmail, 1 },
311 #endif
312 { 0 }
313 };
314
315 /*
316 * Handle initial connection protocol.
317 */
318 void
319 tftp(tp, size)
320 struct tftphdr *tp;
321 int size;
322 {
323 register char *cp;
324 int first = 1, ecode;
325 register struct formats *pf;
326 char *filename, *mode;
327
328 filename = cp = tp->th_stuff;
329 again:
330 while (cp < buf + size) {
331 if (*cp == '\0')
332 break;
333 cp++;
334 }
335 if (*cp != '\0') {
336 nak(EBADOP);
337 exit(1);
338 }
339 if (first) {
340 mode = ++cp;
341 first = 0;
342 goto again;
343 }
344 for (cp = mode; *cp; cp++)
345 if (isupper(*cp))
346 *cp = tolower(*cp);
347 for (pf = formats; pf->f_mode; pf++)
348 if (strcmp(pf->f_mode, mode) == 0)
349 break;
350 if (pf->f_mode == 0) {
351 nak(EBADOP);
352 exit(1);
353 }
354 ecode = (*pf->f_validate)(&filename, tp->th_opcode);
355 if (logging) {
356 syslog(LOG_INFO, "%s: %s request for %s: %s", verifyhost(&from),
357 tp->th_opcode == WRQ ? "write" : "read",
358 filename, errtomsg(ecode));
359 }
360 if (ecode) {
361 /*
362 * Avoid storms of naks to a RRQ broadcast for a relative
363 * bootfile pathname from a diskless Sun.
364 */
365 if (suppress_naks && *filename != '/' && ecode == ENOTFOUND)
366 exit(0);
367 nak(ecode);
368 exit(1);
369 }
370 if (tp->th_opcode == WRQ)
371 (*pf->f_recv)(pf);
372 else
373 (*pf->f_send)(pf);
374 exit(0);
375 }
376
377
378 FILE *file;
379
380 /*
381 * Validate file access. Since we
382 * have no uid or gid, for now require
383 * file to exist and be publicly
384 * readable/writable.
385 * If we were invoked with arguments
386 * from inetd then the file must also be
387 * in one of the given directory prefixes.
388 * Note also, full path name must be
389 * given as we have no login directory.
390 */
391 int
392 validate_access(filep, mode)
393 char **filep;
394 int mode;
395 {
396 struct stat stbuf;
397 int fd;
398 struct dirlist *dirp;
399 static char pathname[MAXPATHLEN];
400 char *filename = *filep;
401
402 /*
403 * Prevent tricksters from getting around the directory restrictions
404 */
405 if (strstr(filename, "/../"))
406 return (EACCESS);
407
408 if (*filename == '/') {
409 /*
410 * Allow the request if it's in one of the approved locations.
411 * Special case: check the null prefix ("/") by looking
412 * for length = 1 and relying on the arg. processing that
413 * it's a /.
414 */
415 for (dirp = dirs; dirp->name != NULL; dirp++) {
416 if (dirp->len == 1 ||
417 (!strncmp(filename, dirp->name, dirp->len) &&
418 filename[dirp->len] == '/'))
419 break;
420 }
421 /* If directory list is empty, allow access to any file */
422 if (dirp->name == NULL && dirp != dirs)
423 return (EACCESS);
424 if (stat(filename, &stbuf) < 0)
425 return (errno == ENOENT ? ENOTFOUND : EACCESS);
426 if ((stbuf.st_mode & S_IFMT) != S_IFREG)
427 return (ENOTFOUND);
428 if (mode == RRQ) {
429 if ((stbuf.st_mode & S_IROTH) == 0)
430 return (EACCESS);
431 } else {
432 if ((stbuf.st_mode & S_IWOTH) == 0)
433 return (EACCESS);
434 }
435 } else {
436 int err;
437
438 /*
439 * Relative file name: search the approved locations for it.
440 * Don't allow write requests that avoid directory
441 * restrictions.
442 */
443
444 if (!strncmp(filename, "../", 3))
445 return (EACCESS);
446
447 /*
448 * If the file exists in one of the directories and isn't
449 * readable, continue looking. However, change the error code
450 * to give an indication that the file exists.
451 */
452 err = ENOTFOUND;
453 for (dirp = dirs; dirp->name != NULL; dirp++) {
454 snprintf(pathname, sizeof(pathname), "%s/%s",
455 dirp->name, filename);
456 if (stat(pathname, &stbuf) == 0 &&
457 (stbuf.st_mode & S_IFMT) == S_IFREG) {
458 if ((stbuf.st_mode & S_IROTH) != 0) {
459 break;
460 }
461 err = EACCESS;
462 }
463 }
464 if (dirp->name == NULL)
465 return (err);
466 *filep = filename = pathname;
467 }
468 fd = open(filename, mode == RRQ ? O_RDONLY : O_WRONLY|O_TRUNC);
469 if (fd < 0)
470 return (errno + 100);
471 file = fdopen(fd, (mode == RRQ)? "r":"w");
472 if (file == NULL) {
473 return errno+100;
474 }
475 return (0);
476 }
477
478 int timeout;
479 jmp_buf timeoutbuf;
480
481 void
482 timer()
483 {
484
485 timeout += rexmtval;
486 if (timeout >= maxtimeout)
487 exit(1);
488 longjmp(timeoutbuf, 1);
489 }
490
491 /*
492 * Send the requested file.
493 */
494 void
495 xmitfile(pf)
496 struct formats *pf;
497 {
498 struct tftphdr *dp, *r_init();
499 register struct tftphdr *ap; /* ack packet */
500 register int size, n;
501 volatile unsigned short block;
502
503 signal(SIGALRM, timer);
504 dp = r_init();
505 ap = (struct tftphdr *)ackbuf;
506 block = 1;
507 do {
508 size = readit(file, &dp, pf->f_convert);
509 if (size < 0) {
510 nak(errno + 100);
511 goto abort;
512 }
513 dp->th_opcode = htons((u_short)DATA);
514 dp->th_block = htons((u_short)block);
515 timeout = 0;
516 (void)setjmp(timeoutbuf);
517
518 send_data:
519 if (send(peer, dp, size + 4, 0) != size + 4) {
520 syslog(LOG_ERR, "write: %m");
521 goto abort;
522 }
523 read_ahead(file, pf->f_convert);
524 for ( ; ; ) {
525 alarm(rexmtval); /* read the ack */
526 n = recv(peer, ackbuf, sizeof (ackbuf), 0);
527 alarm(0);
528 if (n < 0) {
529 syslog(LOG_ERR, "read: %m");
530 goto abort;
531 }
532 ap->th_opcode = ntohs((u_short)ap->th_opcode);
533 ap->th_block = ntohs((u_short)ap->th_block);
534
535 if (ap->th_opcode == ERROR)
536 goto abort;
537
538 if (ap->th_opcode == ACK) {
539 if (ap->th_block == block)
540 break;
541 /* Re-synchronize with the other side */
542 (void) synchnet(peer);
543 if (ap->th_block == (block -1))
544 goto send_data;
545 }
546
547 }
548 block++;
549 } while (size == SEGSIZE);
550 abort:
551 (void) fclose(file);
552 }
553
554 void
555 justquit()
556 {
557 exit(0);
558 }
559
560
561 /*
562 * Receive a file.
563 */
564 void
565 recvfile(pf)
566 struct formats *pf;
567 {
568 struct tftphdr *dp, *w_init();
569 register struct tftphdr *ap; /* ack buffer */
570 register int n, size;
571 volatile unsigned short block;
572
573 signal(SIGALRM, timer);
574 dp = w_init();
575 ap = (struct tftphdr *)ackbuf;
576 block = 0;
577 do {
578 timeout = 0;
579 ap->th_opcode = htons((u_short)ACK);
580 ap->th_block = htons((u_short)block);
581 block++;
582 (void) setjmp(timeoutbuf);
583 send_ack:
584 if (send(peer, ackbuf, 4, 0) != 4) {
585 syslog(LOG_ERR, "write: %m");
586 goto abort;
587 }
588 write_behind(file, pf->f_convert);
589 for ( ; ; ) {
590 alarm(rexmtval);
591 n = recv(peer, dp, PKTSIZE, 0);
592 alarm(0);
593 if (n < 0) { /* really? */
594 syslog(LOG_ERR, "read: %m");
595 goto abort;
596 }
597 dp->th_opcode = ntohs((u_short)dp->th_opcode);
598 dp->th_block = ntohs((u_short)dp->th_block);
599 if (dp->th_opcode == ERROR)
600 goto abort;
601 if (dp->th_opcode == DATA) {
602 if (dp->th_block == block) {
603 break; /* normal */
604 }
605 /* Re-synchronize with the other side */
606 (void) synchnet(peer);
607 if (dp->th_block == (block-1))
608 goto send_ack; /* rexmit */
609 }
610 }
611 /* size = write(file, dp->th_data, n - 4); */
612 size = writeit(file, &dp, n - 4, pf->f_convert);
613 if (size != (n-4)) { /* ahem */
614 if (size < 0) nak(errno + 100);
615 else nak(ENOSPACE);
616 goto abort;
617 }
618 } while (size == SEGSIZE);
619 write_behind(file, pf->f_convert);
620 (void) fclose(file); /* close data file */
621
622 ap->th_opcode = htons((u_short)ACK); /* send the "final" ack */
623 ap->th_block = htons((u_short)(block));
624 (void) send(peer, ackbuf, 4, 0);
625
626 signal(SIGALRM, justquit); /* just quit on timeout */
627 alarm(rexmtval);
628 n = recv(peer, buf, sizeof (buf), 0); /* normally times out and quits */
629 alarm(0);
630 if (n >= 4 && /* if read some data */
631 dp->th_opcode == DATA && /* and got a data block */
632 block == dp->th_block) { /* then my last ack was lost */
633 (void) send(peer, ackbuf, 4, 0); /* resend final ack */
634 }
635 abort:
636 return;
637 }
638
639 struct errmsg {
640 int e_code;
641 char *e_msg;
642 } errmsgs[] = {
643 { EUNDEF, "Undefined error code" },
644 { ENOTFOUND, "File not found" },
645 { EACCESS, "Access violation" },
646 { ENOSPACE, "Disk full or allocation exceeded" },
647 { EBADOP, "Illegal TFTP operation" },
648 { EBADID, "Unknown transfer ID" },
649 { EEXISTS, "File already exists" },
650 { ENOUSER, "No such user" },
651 { -1, 0 }
652 };
653
654 static char *
655 errtomsg(error)
656 int error;
657 {
658 static char buf[20];
659 register struct errmsg *pe;
660 if (error == 0)
661 return "success";
662 for (pe = errmsgs; pe->e_code >= 0; pe++)
663 if (pe->e_code == error)
664 return pe->e_msg;
665 snprintf(buf, sizeof(buf), "error %d", error);
666 return buf;
667 }
668
669 /*
670 * Send a nak packet (error message).
671 * Error code passed in is one of the
672 * standard TFTP codes, or a UNIX errno
673 * offset by 100.
674 */
675 static void
676 nak(error)
677 int error;
678 {
679 register struct tftphdr *tp;
680 int length;
681 register struct errmsg *pe;
682
683 tp = (struct tftphdr *)buf;
684 tp->th_opcode = htons((u_short)ERROR);
685 tp->th_code = htons((u_short)error);
686 for (pe = errmsgs; pe->e_code >= 0; pe++)
687 if (pe->e_code == error)
688 break;
689 if (pe->e_code < 0) {
690 pe->e_msg = strerror(error - 100);
691 tp->th_code = EUNDEF; /* set 'undef' errorcode */
692 }
693 strcpy(tp->th_msg, pe->e_msg);
694 length = strlen(pe->e_msg);
695 tp->th_msg[length] = '\0';
696 length += 5;
697 if (send(peer, buf, length, 0) != length)
698 syslog(LOG_ERR, "nak: %m");
699 }
700
701 static char *
702 verifyhost(fromp)
703 struct sockaddr_in *fromp;
704 {
705 struct hostent *hp;
706
707 hp = gethostbyaddr((char *)&fromp->sin_addr, sizeof(fromp->sin_addr),
708 fromp->sin_family);
709 if(hp)
710 return hp->h_name;
711 else
712 return inet_ntoa(fromp->sin_addr);
713 }