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