tftp.c revision 1.23 1 /* $NetBSD: tftp.c,v 1.23 2006/01/31 17:36:56 christos 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 #if 0
35 static char sccsid[] = "@(#)tftp.c 8.1 (Berkeley) 6/6/93";
36 #else
37 __RCSID("$NetBSD: tftp.c,v 1.23 2006/01/31 17:36:56 christos Exp $");
38 #endif
39 #endif /* not lint */
40
41 /* Many bug fixes are from Jim Guyton <guyton@rand-unix> */
42
43 /*
44 * TFTP User Program -- Protocol Machines
45 */
46 #include <sys/types.h>
47 #include <sys/param.h>
48 #include <sys/socket.h>
49 #include <sys/stat.h>
50 #include <sys/time.h>
51
52 #include <netinet/in.h>
53
54 #include <arpa/tftp.h>
55
56 #include <err.h>
57 #include <errno.h>
58 #include <setjmp.h>
59 #include <signal.h>
60 #include <stdio.h>
61 #include <stdlib.h>
62 #include <string.h>
63 #include <unistd.h>
64 #include <netdb.h>
65
66 #include "extern.h"
67 #include "tftpsubs.h"
68
69 char ackbuf[PKTSIZE];
70 int timeout;
71 jmp_buf toplevel;
72 jmp_buf timeoutbuf;
73
74 static void nak __P((int, struct sockaddr *));
75 static int makerequest __P((int, const char *, struct tftphdr *, const char *, off_t));
76 static void printstats __P((const char *, unsigned long));
77 static void startclock __P((void));
78 static void stopclock __P((void));
79 static void timer __P((int));
80 static void tpacket __P((const char *, struct tftphdr *, int));
81 static int cmpport __P((struct sockaddr *, struct sockaddr *));
82
83 static void get_options(struct tftphdr *, int);
84
85 static void
86 get_options(struct tftphdr *ap, int size)
87 {
88 unsigned long val;
89 char *opt, *endp, *nextopt, *valp;
90 int l;
91
92 size -= 2; /* skip over opcode */
93 opt = ap->th_stuff;
94 endp = opt + size - 1;
95 *endp = '\0';
96
97 while (opt < endp) {
98 l = strlen(opt) + 1;
99 valp = opt + l;
100 if (valp < endp) {
101 val = strtoul(valp, NULL, 10);
102 l = strlen(valp) + 1;
103 nextopt = valp + l;
104 if (val == ULONG_MAX && errno == ERANGE) {
105 /* Report illegal value */
106 opt = nextopt;
107 continue;
108 }
109 } else {
110 /* Badly formed OACK */
111 break;
112 }
113 if (strcmp(opt, "tsize") == 0) {
114 /* cool, but we'll ignore it */
115 } else if (strcmp(opt, "timeout") == 0) {
116 if (val >= 1 && val <= 255) {
117 rexmtval = val;
118 } else {
119 /* Report error? */
120 }
121 } else if (strcmp(opt, "blksize") == 0) {
122 if (val >= 8 && val <= MAXSEGSIZE) {
123 blksize = val;
124 } else {
125 /* Report error? */
126 }
127 } else {
128 /* unknown option */
129 }
130 opt = nextopt;
131 }
132 }
133
134 /*
135 * Send the requested file.
136 */
137 void
138 sendfile(fd, name, mode)
139 int fd;
140 char *name;
141 char *mode;
142 {
143 struct tftphdr *ap; /* data and ack packets */
144 struct tftphdr *dp;
145 int j, n;
146 volatile unsigned int block;
147 volatile int size, convert;
148 volatile unsigned long amount;
149 struct sockaddr_storage from;
150 struct stat sbuf;
151 off_t filesize=0;
152 socklen_t fromlen;
153 FILE *file;
154 struct sockaddr_storage peer;
155 struct sockaddr_storage serv; /* valid server port number */
156
157 startclock(); /* start stat's clock */
158 dp = r_init(); /* reset fillbuf/read-ahead code */
159 ap = (struct tftphdr *)(void *)ackbuf;
160 if (tsize) {
161 if (fstat(fd, &sbuf) == 0) {
162 filesize = sbuf.st_size;
163 } else {
164 filesize = -1ULL;
165 }
166 }
167 file = fdopen(fd, "r");
168 convert = !strcmp(mode, "netascii");
169 block = 0;
170 amount = 0;
171 memcpy(&peer, &peeraddr, (size_t)peeraddr.ss_len);
172 memset(&serv, 0, sizeof(serv));
173
174 signal(SIGALRM, timer);
175 do {
176 if (block == 0)
177 size = makerequest(WRQ, name, dp, mode, filesize) - 4;
178 else {
179 /* size = read(fd, dp->th_data, SEGSIZE); */
180 size = readit(file, &dp, blksize, convert);
181 if (size < 0) {
182 nak(errno + 100, (struct sockaddr *)(void *)&peer);
183 break;
184 }
185 dp->th_opcode = htons((u_short)DATA);
186 dp->th_block = htons((u_short)block);
187 }
188 timeout = 0;
189 (void) setjmp(timeoutbuf);
190 send_data:
191 if (trace)
192 tpacket("sent", dp, size + 4);
193 n = sendto(f, dp, (socklen_t)(size + 4), 0,
194 (struct sockaddr *)(void *)&peer, (socklen_t)peer.ss_len);
195 if (n != size + 4) {
196 warn("sendto");
197 goto abort;
198 }
199 if (block)
200 read_ahead(file, blksize, convert);
201 for ( ; ; ) {
202 alarm(rexmtval);
203 do {
204 fromlen = sizeof(from);
205 n = recvfrom(f, ackbuf, sizeof(ackbuf), 0,
206 (struct sockaddr *)(void *)&from, &fromlen);
207 } while (n <= 0);
208 alarm(0);
209 if (n < 0) {
210 warn("recvfrom");
211 goto abort;
212 }
213 if (!serv.ss_family)
214 serv = from;
215 else if (!cmpport((struct sockaddr *)(void *)&serv,
216 (struct sockaddr *)(void *)&from)) {
217 warn("server port mismatch");
218 goto abort;
219 }
220 peer = from;
221 if (trace)
222 tpacket("received", ap, n);
223 /* should verify packet came from server */
224 ap->th_opcode = ntohs(ap->th_opcode);
225 if (ap->th_opcode == ERROR) {
226 printf("Error code %d: %s\n", ap->th_code,
227 ap->th_msg);
228 goto abort;
229 }
230 if (ap->th_opcode == ACK) {
231 ap->th_block = ntohs(ap->th_block);
232
233 if (ap->th_block == 0) {
234 /*
235 * If the extended options are enabled,
236 * the server just refused 'em all.
237 * The only one that _really_
238 * matters is blksize, but we'll
239 * clear timeout, too.
240 */
241 blksize = def_blksize;
242 rexmtval = def_rexmtval;
243 }
244 if (ap->th_block == block) {
245 break;
246 }
247 /* On an error, try to synchronize
248 * both sides.
249 */
250 j = synchnet(f, blksize+4);
251 if (j && trace) {
252 printf("discarded %d packets\n",
253 j);
254 }
255 if (ap->th_block == (block-1)) {
256 goto send_data;
257 }
258 }
259 if (ap->th_opcode == OACK) {
260 if (block == 0) {
261 blksize = def_blksize;
262 rexmtval = def_rexmtval;
263 get_options(ap, n);
264 break;
265 }
266 }
267 }
268 if (block > 0)
269 amount += size;
270 block++;
271 } while (size == blksize || block == 1);
272 abort:
273 fclose(file);
274 stopclock();
275 if (amount > 0)
276 printstats("Sent", amount);
277 }
278
279 /*
280 * Receive a file.
281 */
282 void
283 recvfile(fd, name, mode)
284 int fd;
285 char *name;
286 char *mode;
287 {
288 struct tftphdr *ap;
289 struct tftphdr *dp;
290 int j, n, oack=0;
291 volatile unsigned int block;
292 volatile int size, firsttrip;
293 volatile unsigned long amount;
294 struct sockaddr_storage from;
295 socklen_t fromlen;
296 size_t readlen;
297 FILE *file;
298 volatile int convert; /* true if converting crlf -> lf */
299 struct sockaddr_storage peer;
300 struct sockaddr_storage serv; /* valid server port number */
301
302 startclock();
303 dp = w_init();
304 ap = (struct tftphdr *)(void *)ackbuf;
305 file = fdopen(fd, "w");
306 convert = !strcmp(mode, "netascii");
307 block = 1;
308 firsttrip = 1;
309 amount = 0;
310 memcpy(&peer, &peeraddr, (size_t)peeraddr.ss_len);
311 memset(&serv, 0, sizeof(serv));
312
313 signal(SIGALRM, timer);
314 do {
315 if (firsttrip) {
316 size = makerequest(RRQ, name, ap, mode, (off_t)0);
317 readlen = PKTSIZE;
318 firsttrip = 0;
319 } else {
320 ap->th_opcode = htons((u_short)ACK);
321 ap->th_block = htons((u_short)(block));
322 readlen = blksize+4;
323 size = 4;
324 block++;
325 }
326 timeout = 0;
327 (void) setjmp(timeoutbuf);
328 send_ack:
329 if (trace)
330 tpacket("sent", ap, size);
331 if (sendto(f, ackbuf, (socklen_t)size, 0,
332 (struct sockaddr *)(void *)&peer,
333 (socklen_t)peer.ss_len) != size) {
334 alarm(0);
335 warn("sendto");
336 goto abort;
337 }
338 if (write_behind(file, convert) == -1)
339 goto abort;
340 for ( ; ; ) {
341 alarm(rexmtval);
342 do {
343 fromlen = sizeof(from);
344 n = recvfrom(f, dp, readlen, 0,
345 (struct sockaddr *)(void *)&from, &fromlen);
346 } while (n <= 0);
347 alarm(0);
348 if (n < 0) {
349 warn("recvfrom");
350 goto abort;
351 }
352 if (!serv.ss_family)
353 serv = from;
354 else if (!cmpport((struct sockaddr *)(void *)&serv,
355 (struct sockaddr *)(void *)&from)) {
356 warn("server port mismatch");
357 goto abort;
358 }
359 peer = from;
360 if (trace)
361 tpacket("received", dp, n);
362 /* should verify client address */
363 dp->th_opcode = ntohs(dp->th_opcode);
364 if (dp->th_opcode == ERROR) {
365 printf("Error code %d: %s\n", dp->th_code,
366 dp->th_msg);
367 goto abort;
368 }
369 if (dp->th_opcode == DATA) {
370 dp->th_block = ntohs(dp->th_block);
371
372 if (dp->th_block == 1 && !oack) {
373 /* no OACK, revert to defaults */
374 blksize = def_blksize;
375 rexmtval = def_rexmtval;
376 }
377 if (dp->th_block == block) {
378 break; /* have next packet */
379 }
380 /* On an error, try to synchronize
381 * both sides.
382 */
383 j = synchnet(f, blksize);
384 if (j && trace) {
385 printf("discarded %d packets\n", j);
386 }
387 if (dp->th_block == (block-1)) {
388 goto send_ack; /* resend ack */
389 }
390 }
391 if (dp->th_opcode == OACK) {
392 if (block == 1) {
393 oack = 1;
394 blksize = def_blksize;
395 rexmtval = def_rexmtval;
396 get_options(dp, n);
397 ap->th_opcode = htons(ACK);
398 ap->th_block = 0;
399 readlen = blksize+4;
400 size = 4;
401 goto send_ack;
402 }
403 }
404 }
405 /* size = write(fd, dp->th_data, n - 4); */
406 size = writeit(file, &dp, n - 4, convert);
407 if (size < 0) {
408 nak(errno + 100, (struct sockaddr *)(void *)&peer);
409 break;
410 }
411 amount += size;
412 } while (size == blksize);
413 abort: /* ok to ack, since user */
414 ap->th_opcode = htons((u_short)ACK); /* has seen err msg */
415 ap->th_block = htons((u_short)block);
416 (void) sendto(f, ackbuf, 4, 0, (struct sockaddr *)(void *)&peer,
417 (socklen_t)peer.ss_len);
418 /*
419 * flush last buffer
420 * We do not check for failure because last buffer
421 * can be empty, thus returning an error.
422 * XXX maybe we should fix 'write_behind' instead.
423 */
424 (void)write_behind(file, convert);
425 fclose(file);
426 stopclock();
427 if (amount > 0)
428 printstats("Received", amount);
429 }
430
431 static int
432 makerequest(request, name, tp, mode, filesize)
433 int request;
434 const char *name;
435 struct tftphdr *tp;
436 const char *mode;
437 off_t filesize;
438 {
439 char *cp;
440
441 tp->th_opcode = htons((u_short)request);
442 #ifndef __SVR4
443 cp = tp->th_stuff;
444 #else
445 cp = (void *)&tp->th_stuff;
446 #endif
447 strcpy(cp, name);
448 cp += strlen(name);
449 *cp++ = '\0';
450 strcpy(cp, mode);
451 cp += strlen(mode);
452 *cp++ = '\0';
453 if (tsize) {
454 strcpy(cp, "tsize");
455 cp += strlen(cp);
456 *cp++ = '\0';
457 sprintf(cp, "%lu", (unsigned long) filesize);
458 cp += strlen(cp);
459 *cp++ = '\0';
460 }
461 if (tout) {
462 strcpy(cp, "timeout");
463 cp += strlen(cp);
464 *cp++ = '\0';
465 sprintf(cp, "%d", rexmtval);
466 cp += strlen(cp);
467 *cp++ = '\0';
468 }
469 if (blksize != SEGSIZE) {
470 strcpy(cp, "blksize");
471 cp += strlen(cp);
472 *cp++ = '\0';
473 sprintf(cp, "%d", blksize);
474 cp += strlen(cp);
475 *cp++ = '\0';
476 }
477 return (cp - (char *)(void *)tp);
478 }
479
480 const struct errmsg {
481 int e_code;
482 const char *e_msg;
483 } errmsgs[] = {
484 { EUNDEF, "Undefined error code" },
485 { ENOTFOUND, "File not found" },
486 { EACCESS, "Access violation" },
487 { ENOSPACE, "Disk full or allocation exceeded" },
488 { EBADOP, "Illegal TFTP operation" },
489 { EBADID, "Unknown transfer ID" },
490 { EEXISTS, "File already exists" },
491 { ENOUSER, "No such user" },
492 { EOPTNEG, "Option negotiation failed" },
493 { -1, 0 }
494 };
495
496 /*
497 * Send a nak packet (error message).
498 * Error code passed in is one of the
499 * standard TFTP codes, or a UNIX errno
500 * offset by 100.
501 */
502 static void
503 nak(error, peer)
504 int error;
505 struct sockaddr *peer;
506 {
507 const struct errmsg *pe;
508 struct tftphdr *tp;
509 int length;
510 size_t msglen;
511
512 tp = (struct tftphdr *)(void *)ackbuf;
513 tp->th_opcode = htons((u_short)ERROR);
514 msglen = sizeof(ackbuf) - (&tp->th_msg[0] - ackbuf);
515 for (pe = errmsgs; pe->e_code >= 0; pe++)
516 if (pe->e_code == error)
517 break;
518 if (pe->e_code < 0) {
519 tp->th_code = EUNDEF;
520 strlcpy(tp->th_msg, strerror(error - 100), msglen);
521 } else {
522 tp->th_code = htons((u_short)error);
523 strlcpy(tp->th_msg, pe->e_msg, msglen);
524 }
525 length = strlen(tp->th_msg);
526 msglen = &tp->th_msg[length + 1] - ackbuf;
527 if (trace)
528 tpacket("sent", tp, (int)msglen);
529 if (sendto(f, ackbuf, msglen, 0, peer, (socklen_t)peer->sa_len) != msglen)
530 warn("nak");
531 }
532
533 static void
534 tpacket(s, tp, n)
535 const char *s;
536 struct tftphdr *tp;
537 int n;
538 {
539 static const char *opcodes[] =
540 { "#0", "RRQ", "WRQ", "DATA", "ACK", "ERROR", "OACK" };
541 char *cp, *file, *endp, *opt = NULL;
542 const char *spc;
543 u_short op = ntohs(tp->th_opcode);
544 int i, o;
545
546 if (op < RRQ || op > OACK)
547 printf("%s opcode=%x ", s, op);
548 else
549 printf("%s %s ", s, opcodes[op]);
550 switch (op) {
551
552 case RRQ:
553 case WRQ:
554 n -= 2;
555 #ifndef __SVR4
556 cp = tp->th_stuff;
557 #else
558 cp = (void *) &tp->th_stuff;
559 #endif
560 endp = cp + n - 1;
561 if (*endp != '\0') { /* Shouldn't happen, but... */
562 *endp = '\0';
563 }
564 file = cp;
565 cp = strchr(cp, '\0') + 1;
566 printf("<file=%s, mode=%s", file, cp);
567 cp = strchr(cp, '\0') + 1;
568 o = 0;
569 while (cp < endp) {
570 i = strlen(cp) + 1;
571 if (o) {
572 printf(", %s=%s", opt, cp);
573 } else {
574 opt = cp;
575 }
576 o = (o+1) % 2;
577 cp += i;
578 }
579 printf(">\n");
580 break;
581
582 case DATA:
583 printf("<block=%d, %d bytes>\n", ntohs(tp->th_block), n - 4);
584 break;
585
586 case ACK:
587 printf("<block=%d>\n", ntohs(tp->th_block));
588 break;
589
590 case ERROR:
591 printf("<code=%d, msg=%s>\n", ntohs(tp->th_code), tp->th_msg);
592 break;
593
594 case OACK:
595 o = 0;
596 n -= 2;
597 cp = tp->th_stuff;
598 endp = cp + n - 1;
599 if (*endp != '\0') { /* Shouldn't happen, but... */
600 *endp = '\0';
601 }
602 printf("<");
603 spc = "";
604 while (cp < endp) {
605 i = strlen(cp) + 1;
606 if (o) {
607 printf("%s%s=%s", spc, opt, cp);
608 spc = ", ";
609 } else {
610 opt = cp;
611 }
612 o = (o+1) % 2;
613 cp += i;
614 }
615 printf(">\n");
616 break;
617 }
618 }
619
620 struct timeval tstart;
621 struct timeval tstop;
622
623 static void
624 startclock()
625 {
626
627 (void)gettimeofday(&tstart, NULL);
628 }
629
630 static void
631 stopclock()
632 {
633
634 (void)gettimeofday(&tstop, NULL);
635 }
636
637 static void
638 printstats(direction, amount)
639 const char *direction;
640 unsigned long amount;
641 {
642 double delta;
643
644 /* compute delta in 1/10's second units */
645 delta = ((tstop.tv_sec*10.)+(tstop.tv_usec/100000)) -
646 ((tstart.tv_sec*10.)+(tstart.tv_usec/100000));
647 delta = delta/10.; /* back to seconds */
648 printf("%s %ld bytes in %.1f seconds", direction, amount, delta);
649 if (verbose)
650 printf(" [%.0f bits/sec]", (amount*8.)/delta);
651 putchar('\n');
652 }
653
654 static void
655 /*ARGSUSED*/
656 timer(sig)
657 int sig;
658 {
659
660 timeout += rexmtval;
661 if (timeout >= maxtimeout) {
662 printf("Transfer timed out.\n");
663 longjmp(toplevel, -1);
664 }
665 longjmp(timeoutbuf, 1);
666 }
667
668 static int
669 cmpport(sa, sb)
670 struct sockaddr *sa;
671 struct sockaddr *sb;
672 {
673 char a[NI_MAXSERV], b[NI_MAXSERV];
674
675 if (getnameinfo(sa, (socklen_t)sa->sa_len, NULL, 0, a, sizeof(a), NI_NUMERICSERV))
676 return 0;
677 if (getnameinfo(sb, (socklen_t)sb->sa_len, NULL, 0, b, sizeof(b), NI_NUMERICSERV))
678 return 0;
679 if (strcmp(a, b) != 0)
680 return 0;
681
682 return 1;
683 }
684