tftpd.c revision 1.6 1 /*
2 * Copyright (c) 1983 Regents of the University of California.
3 * 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 char copyright[] =
36 "@(#) Copyright (c) 1983 Regents of the University of California.\n\
37 All rights reserved.\n";
38 #endif /* not lint */
39
40 #ifndef lint
41 /*static char sccsid[] = "from: @(#)tftpd.c 5.13 (Berkeley) 2/26/91";*/
42 static char rcsid[] = "$Id: tftpd.c,v 1.6 1995/06/03 22:48:30 mycroft Exp $";
43 #endif /* not lint */
44
45 /*
46 * Trivial file transfer protocol server.
47 *
48 * This version includes many modifications by Jim Guyton <guyton@rand-unix>
49 */
50
51 #include <sys/types.h>
52 #include <sys/ioctl.h>
53 #include <sys/stat.h>
54 #include <signal.h>
55 #include <fcntl.h>
56
57 #include <sys/socket.h>
58 #include <netinet/in.h>
59 #include <arpa/tftp.h>
60 #include <netdb.h>
61
62 #include <setjmp.h>
63 #include <syslog.h>
64 #include <stdio.h>
65 #include <errno.h>
66 #include <ctype.h>
67 #include <string.h>
68 #include <stdlib.h>
69
70 #define TIMEOUT 5
71
72 extern int errno;
73 extern char *__progname;
74 struct sockaddr_in s_in = { AF_INET };
75 int peer;
76 int rexmtval = TIMEOUT;
77 int maxtimeout = 5*TIMEOUT;
78
79 #define PKTSIZE SEGSIZE+4
80 char buf[PKTSIZE];
81 char ackbuf[PKTSIZE];
82 struct sockaddr_in from;
83 int fromlen;
84
85 #define MAXARG 4
86 char *dirs[MAXARG+1];
87
88 int secure = 0;
89
90 static void
91 usage()
92 {
93 syslog(LOG_ERR, "Usage: %s [-s] [directory ...]\n", __progname);
94 exit(1);
95 }
96
97 main(argc, argv)
98 int argc;
99 char **argv;
100 {
101 register struct tftphdr *tp;
102 register int n = 0;
103 int on = 1;
104 int fd = 0;
105 int c;
106
107 openlog("tftpd", LOG_PID, LOG_DAEMON);
108
109 while ((c = getopt(argc, argv, "s")) != -1)
110 switch (c) {
111 case 's':
112 secure = 1;
113 break;
114
115 default:
116 usage();
117 break;
118 }
119
120 for (; optind != argc; optind++) {
121 if (!secure) {
122 if (n >= MAXARG) {
123 syslog(LOG_ERR, "too many directories\n");
124 exit(1);
125 } else
126 dirs[n++] = argv[optind];
127 }
128 if (chdir(argv[optind])) {
129 syslog(LOG_ERR, "%s: %m\n", argv[optind]);
130 exit(1);
131 }
132 }
133
134 if (secure && chroot(".")) {
135 syslog(LOG_ERR, "chroot: %m\n");
136 exit(1);
137 }
138
139 if (ioctl(fd, FIONBIO, &on) < 0) {
140 syslog(LOG_ERR, "ioctl(FIONBIO): %m\n");
141 exit(1);
142 }
143 fromlen = sizeof (from);
144 n = recvfrom(fd, buf, sizeof (buf), 0,
145 (struct sockaddr *)&from, &fromlen);
146 if (n < 0) {
147 syslog(LOG_ERR, "recvfrom: %m\n");
148 exit(1);
149 }
150 /*
151 * Now that we have read the message out of the UDP
152 * socket, we fork and exit. Thus, inetd will go back
153 * to listening to the tftp port, and the next request
154 * to come in will start up a new instance of tftpd.
155 *
156 * We do this so that inetd can run tftpd in "wait" mode.
157 * The problem with tftpd running in "nowait" mode is that
158 * inetd may get one or more successful "selects" on the
159 * tftp port before we do our receive, so more than one
160 * instance of tftpd may be started up. Worse, if tftpd
161 * break before doing the above "recvfrom", inetd would
162 * spawn endless instances, clogging the system.
163 */
164 {
165 int pid;
166 int i, j;
167
168 for (i = 1; i < 20; i++) {
169 pid = fork();
170 if (pid < 0) {
171 sleep(i);
172 /*
173 * flush out to most recently sent request.
174 *
175 * This may drop some request, but those
176 * will be resent by the clients when
177 * they timeout. The positive effect of
178 * this flush is to (try to) prevent more
179 * than one tftpd being started up to service
180 * a single request from a single client.
181 */
182 j = sizeof from;
183 i = recvfrom(fd, buf, sizeof (buf), 0,
184 (struct sockaddr *)&from, &j);
185 if (i > 0) {
186 n = i;
187 fromlen = j;
188 }
189 } else {
190 break;
191 }
192 }
193 if (pid < 0) {
194 syslog(LOG_ERR, "fork: %m\n");
195 exit(1);
196 } else if (pid != 0) {
197 exit(0);
198 }
199 }
200 from.sin_len = sizeof(struct sockaddr_in);
201 from.sin_family = AF_INET;
202 alarm(0);
203 close(fd);
204 close(1);
205 peer = socket(AF_INET, SOCK_DGRAM, 0);
206 if (peer < 0) {
207 syslog(LOG_ERR, "socket: %m\n");
208 exit(1);
209 }
210 if (bind(peer, (struct sockaddr *)&s_in, sizeof (s_in)) < 0) {
211 syslog(LOG_ERR, "bind: %m\n");
212 exit(1);
213 }
214 if (connect(peer, (struct sockaddr *)&from, sizeof(from)) < 0) {
215 syslog(LOG_ERR, "connect: %m\n");
216 exit(1);
217 }
218 tp = (struct tftphdr *)buf;
219 tp->th_opcode = ntohs(tp->th_opcode);
220 if (tp->th_opcode == RRQ || tp->th_opcode == WRQ)
221 tftp(tp, n);
222 exit(1);
223 }
224
225 int validate_access();
226 int sendfile(), recvfile();
227
228 struct formats {
229 char *f_mode;
230 int (*f_validate)();
231 int (*f_send)();
232 int (*f_recv)();
233 int f_convert;
234 } formats[] = {
235 { "netascii", validate_access, sendfile, recvfile, 1 },
236 { "octet", validate_access, sendfile, recvfile, 0 },
237 #ifdef notdef
238 { "mail", validate_user, sendmail, recvmail, 1 },
239 #endif
240 { 0 }
241 };
242
243 /*
244 * Handle initial connection protocol.
245 */
246 tftp(tp, size)
247 struct tftphdr *tp;
248 int size;
249 {
250 register char *cp;
251 int first = 1, ecode;
252 register struct formats *pf;
253 char *filename, *mode;
254
255 filename = cp = tp->th_stuff;
256 again:
257 while (cp < buf + size) {
258 if (*cp == '\0')
259 break;
260 cp++;
261 }
262 if (*cp != '\0') {
263 nak(EBADOP);
264 exit(1);
265 }
266 if (first) {
267 mode = ++cp;
268 first = 0;
269 goto again;
270 }
271 for (cp = mode; *cp; cp++)
272 if (isupper(*cp))
273 *cp = tolower(*cp);
274 for (pf = formats; pf->f_mode; pf++)
275 if (strcmp(pf->f_mode, mode) == 0)
276 break;
277 if (pf->f_mode == 0) {
278 nak(EBADOP);
279 exit(1);
280 }
281 ecode = (*pf->f_validate)(filename, tp->th_opcode);
282 if (ecode) {
283 nak(ecode);
284 exit(1);
285 }
286 if (tp->th_opcode == WRQ)
287 (*pf->f_recv)(pf);
288 else
289 (*pf->f_send)(pf);
290 exit(0);
291 }
292
293
294 FILE *file;
295
296 /*
297 * Validate file access. Since we
298 * have no uid or gid, for now require
299 * file to exist and be publicly
300 * readable/writable.
301 * If we were invoked with arguments
302 * from inetd then the file must also be
303 * in one of the given directory prefixes.
304 * Note also, full path name must be
305 * given as we have no login directory.
306 */
307 validate_access(filename, mode)
308 char *filename;
309 int mode;
310 {
311 struct stat stbuf;
312 int fd;
313 char *cp, **dirp;
314
315 if (!secure) {
316 if (*filename != '/')
317 return (EACCESS);
318 /*
319 * prevent tricksters from getting around the directory
320 * restrictions
321 */
322 for (cp = filename + 1; *cp; cp++)
323 if(*cp == '.' && strncmp(cp-1, "/../", 4) == 0)
324 return(EACCESS);
325 for (dirp = dirs; *dirp; dirp++)
326 if (strncmp(filename, *dirp, strlen(*dirp)) == 0)
327 break;
328 if (*dirp==0 && dirp!=dirs)
329 return (EACCESS);
330 }
331 if (stat(filename, &stbuf) < 0)
332 return (errno == ENOENT ? ENOTFOUND : EACCESS);
333 if (mode == RRQ) {
334 if ((stbuf.st_mode&(S_IREAD >> 6)) == 0)
335 return (EACCESS);
336 } else {
337 if ((stbuf.st_mode&(S_IWRITE >> 6)) == 0)
338 return (EACCESS);
339 }
340 fd = open(filename, mode == RRQ ? 0 : 1);
341 if (fd < 0)
342 return (errno + 100);
343 file = fdopen(fd, (mode == RRQ)? "r":"w");
344 if (file == NULL) {
345 return errno+100;
346 }
347 return (0);
348 }
349
350 int timeout;
351 jmp_buf timeoutbuf;
352
353 void
354 timer()
355 {
356
357 timeout += rexmtval;
358 if (timeout >= maxtimeout)
359 exit(1);
360 longjmp(timeoutbuf, 1);
361 }
362
363 /*
364 * Send the requested file.
365 */
366 sendfile(pf)
367 struct formats *pf;
368 {
369 struct tftphdr *dp, *r_init();
370 register struct tftphdr *ap; /* ack packet */
371 register int block = 1, size, n;
372
373 signal(SIGALRM, timer);
374 dp = r_init();
375 ap = (struct tftphdr *)ackbuf;
376 do {
377 size = readit(file, &dp, pf->f_convert);
378 if (size < 0) {
379 nak(errno + 100);
380 goto abort;
381 }
382 dp->th_opcode = htons((u_short)DATA);
383 dp->th_block = htons((u_short)block);
384 timeout = 0;
385 (void) setjmp(timeoutbuf);
386
387 send_data:
388 if (send(peer, dp, size + 4, 0) != size + 4) {
389 syslog(LOG_ERR, "tftpd: write: %m\n");
390 goto abort;
391 }
392 read_ahead(file, pf->f_convert);
393 for ( ; ; ) {
394 alarm(rexmtval); /* read the ack */
395 n = recv(peer, ackbuf, sizeof (ackbuf), 0);
396 alarm(0);
397 if (n < 0) {
398 syslog(LOG_ERR, "tftpd: read: %m\n");
399 goto abort;
400 }
401 ap->th_opcode = ntohs((u_short)ap->th_opcode);
402 ap->th_block = ntohs((u_short)ap->th_block);
403
404 if (ap->th_opcode == ERROR)
405 goto abort;
406
407 if (ap->th_opcode == ACK) {
408 if (ap->th_block == block) {
409 break;
410 }
411 /* Re-synchronize with the other side */
412 (void) synchnet(peer);
413 if (ap->th_block == (block -1)) {
414 goto send_data;
415 }
416 }
417
418 }
419 block++;
420 } while (size == SEGSIZE);
421 abort:
422 (void) fclose(file);
423 }
424
425 void
426 justquit()
427 {
428 exit(0);
429 }
430
431
432 /*
433 * Receive a file.
434 */
435 recvfile(pf)
436 struct formats *pf;
437 {
438 struct tftphdr *dp, *w_init();
439 register struct tftphdr *ap; /* ack buffer */
440 register int block = 0, n, size;
441
442 signal(SIGALRM, timer);
443 dp = w_init();
444 ap = (struct tftphdr *)ackbuf;
445 do {
446 timeout = 0;
447 ap->th_opcode = htons((u_short)ACK);
448 ap->th_block = htons((u_short)block);
449 block++;
450 (void) setjmp(timeoutbuf);
451 send_ack:
452 if (send(peer, ackbuf, 4, 0) != 4) {
453 syslog(LOG_ERR, "tftpd: write: %m\n");
454 goto abort;
455 }
456 write_behind(file, pf->f_convert);
457 for ( ; ; ) {
458 alarm(rexmtval);
459 n = recv(peer, dp, PKTSIZE, 0);
460 alarm(0);
461 if (n < 0) { /* really? */
462 syslog(LOG_ERR, "tftpd: read: %m\n");
463 goto abort;
464 }
465 dp->th_opcode = ntohs((u_short)dp->th_opcode);
466 dp->th_block = ntohs((u_short)dp->th_block);
467 if (dp->th_opcode == ERROR)
468 goto abort;
469 if (dp->th_opcode == DATA) {
470 if (dp->th_block == block) {
471 break; /* normal */
472 }
473 /* Re-synchronize with the other side */
474 (void) synchnet(peer);
475 if (dp->th_block == (block-1))
476 goto send_ack; /* rexmit */
477 }
478 }
479 /* size = write(file, dp->th_data, n - 4); */
480 size = writeit(file, &dp, n - 4, pf->f_convert);
481 if (size != (n-4)) { /* ahem */
482 if (size < 0) nak(errno + 100);
483 else nak(ENOSPACE);
484 goto abort;
485 }
486 } while (size == SEGSIZE);
487 write_behind(file, pf->f_convert);
488 (void) fclose(file); /* close data file */
489
490 ap->th_opcode = htons((u_short)ACK); /* send the "final" ack */
491 ap->th_block = htons((u_short)(block));
492 (void) send(peer, ackbuf, 4, 0);
493
494 signal(SIGALRM, justquit); /* just quit on timeout */
495 alarm(rexmtval);
496 n = recv(peer, buf, sizeof (buf), 0); /* normally times out and quits */
497 alarm(0);
498 if (n >= 4 && /* if read some data */
499 dp->th_opcode == DATA && /* and got a data block */
500 block == dp->th_block) { /* then my last ack was lost */
501 (void) send(peer, ackbuf, 4, 0); /* resend final ack */
502 }
503 abort:
504 return;
505 }
506
507 struct errmsg {
508 int e_code;
509 char *e_msg;
510 } errmsgs[] = {
511 { EUNDEF, "Undefined error code" },
512 { ENOTFOUND, "File not found" },
513 { EACCESS, "Access violation" },
514 { ENOSPACE, "Disk full or allocation exceeded" },
515 { EBADOP, "Illegal TFTP operation" },
516 { EBADID, "Unknown transfer ID" },
517 { EEXISTS, "File already exists" },
518 { ENOUSER, "No such user" },
519 { -1, 0 }
520 };
521
522 /*
523 * Send a nak packet (error message).
524 * Error code passed in is one of the
525 * standard TFTP codes, or a UNIX errno
526 * offset by 100.
527 */
528 nak(error)
529 int error;
530 {
531 register struct tftphdr *tp;
532 int length;
533 register struct errmsg *pe;
534
535 tp = (struct tftphdr *)buf;
536 tp->th_opcode = htons((u_short)ERROR);
537 tp->th_code = htons((u_short)error);
538 for (pe = errmsgs; pe->e_code >= 0; pe++)
539 if (pe->e_code == error)
540 break;
541 if (pe->e_code < 0) {
542 pe->e_msg = strerror(error - 100);
543 tp->th_code = EUNDEF; /* set 'undef' errorcode */
544 }
545 strcpy(tp->th_msg, pe->e_msg);
546 length = strlen(pe->e_msg);
547 tp->th_msg[length] = '\0';
548 length += 5;
549 if (send(peer, buf, length, 0) != length)
550 syslog(LOG_ERR, "nak: %m\n");
551 }
552