Sync usage with man page.
[netbsd-mini2440.git] / usr.bin / tftp / tftp.c
blob831b4d335a630c460d12c31bf05c97ce838a2efc
1 /* $NetBSD: tftp.c,v 1.29 2008/12/11 18:40:02 seanb Exp $ */
3 /*
4 * Copyright (c) 1983, 1993
5 * The Regents of the University of California. All rights reserved.
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.
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.
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.29 2008/12/11 18:40:02 seanb Exp $");
38 #endif
39 #endif /* not lint */
41 /* Many bug fixes are from Jim Guyton <guyton@rand-unix> */
44 * TFTP User Program -- Protocol Machines
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>
52 #include <netinet/in.h>
54 #include <arpa/tftp.h>
55 #include <arpa/inet.h>
57 #include <err.h>
58 #include <errno.h>
59 #include <setjmp.h>
60 #include <signal.h>
61 #include <stdio.h>
62 #include <stdlib.h>
63 #include <string.h>
64 #include <unistd.h>
65 #include <netdb.h>
67 #include "extern.h"
68 #include "tftpsubs.h"
70 char ackbuf[PKTSIZE];
71 int timeout;
72 jmp_buf toplevel;
73 jmp_buf timeoutbuf;
75 static void nak __P((int, struct sockaddr *));
76 static int makerequest __P((int, const char *, struct tftphdr *, const char *, off_t));
77 static void printstats __P((const char *, unsigned long));
78 static void startclock __P((void));
79 static void stopclock __P((void));
80 static void timer __P((int));
81 static void tpacket __P((const char *, struct tftphdr *, int));
82 static int cmpport __P((struct sockaddr *, struct sockaddr *));
84 static void get_options(struct tftphdr *, int);
85 static int tftp_igmp_join(void);
86 static void tftp_igmp_leave(int);
88 static void
89 get_options(struct tftphdr *ap, int size)
91 unsigned long val;
92 char *opt, *endp, *nextopt, *valp;
93 int l;
95 size -= 2; /* skip over opcode */
96 opt = ap->th_stuff;
97 endp = opt + size - 1;
98 *endp = '\0';
100 while (opt < endp) {
101 int ismulticast;
102 l = strlen(opt) + 1;
103 valp = opt + l;
104 ismulticast = !strcasecmp(opt, "multicast");
105 if (valp < endp) {
106 val = strtoul(valp, NULL, 10);
107 l = strlen(valp) + 1;
108 nextopt = valp + l;
109 if (!ismulticast) {
110 if (val == ULONG_MAX && errno == ERANGE) {
111 /* Report illegal value */
112 opt = nextopt;
113 continue;
116 } else {
117 /* Badly formed OACK */
118 break;
120 if (strcmp(opt, "tsize") == 0) {
121 /* cool, but we'll ignore it */
122 } else if (strcmp(opt, "timeout") == 0) {
123 if (val >= 1 && val <= 255) {
124 rexmtval = val;
125 } else {
126 /* Report error? */
128 } else if (strcmp(opt, "blksize") == 0) {
129 if (val >= 8 && val <= MAXSEGSIZE) {
130 blksize = val;
131 } else {
132 /* Report error? */
134 } else if (ismulticast) {
135 char multicast[24];
136 char *pmulticast;
137 char *addr;
139 strlcpy(multicast, valp, sizeof(multicast));
140 pmulticast = multicast;
141 addr = strsep(&pmulticast, ",");
142 if (pmulticast == NULL)
143 continue; /* Report error? */
144 mcport = atoi(strsep(&pmulticast, ","));
145 if (pmulticast == NULL)
146 continue; /* Report error? */
147 mcmasterslave = atoi(pmulticast);
148 mcaddr = inet_addr(addr);
149 if (mcaddr == INADDR_NONE)
150 continue; /* Report error? */
151 } else {
152 /* unknown option */
154 opt = nextopt;
158 static int
159 tftp_igmp_join(void)
161 struct ip_mreq req;
162 struct sockaddr_in s;
163 int fd, rv;
165 memset(&req, 0, sizeof(struct ip_mreq));
166 req.imr_multiaddr.s_addr = mcaddr;
167 req.imr_interface.s_addr = INADDR_ANY;
169 fd = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP);
170 if (fd < 0) {
171 perror("socket");
172 return fd;
175 memset(&s, 0, sizeof(struct sockaddr_in));
176 s.sin_family = AF_INET;
177 s.sin_port = htons(mcport);
178 s.sin_len = sizeof(struct sockaddr_in);
179 rv = bind(fd, (struct sockaddr *)&s, sizeof(struct sockaddr_in));
180 if (rv < 0) {
181 perror("bind");
182 close(fd);
183 return rv;
186 rv = setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP, &req,
187 sizeof(struct ip_mreq));
188 if (rv < 0) {
189 perror("setsockopt");
190 close(fd);
191 return rv;
194 return fd;
197 static void
198 tftp_igmp_leave(int fd)
200 struct ip_mreq req;
201 int rv;
203 memset(&req, 0, sizeof(struct ip_mreq));
204 req.imr_multiaddr.s_addr = mcaddr;
205 req.imr_interface.s_addr = INADDR_ANY;
207 rv = setsockopt(fd, IPPROTO_IP, IP_DROP_MEMBERSHIP, &req,
208 sizeof(struct ip_mreq));
209 if (rv < 0)
210 perror("setsockopt");
212 close(fd);
214 return;
218 * Send the requested file.
220 void
221 sendfile(fd, name, mode)
222 int fd;
223 char *name;
224 char *mode;
226 struct tftphdr *ap; /* data and ack packets */
227 struct tftphdr *dp;
228 int j, n;
229 volatile unsigned int block;
230 volatile int size, convert;
231 volatile unsigned long amount;
232 struct sockaddr_storage from;
233 struct stat sbuf;
234 volatile off_t filesize = 0;
235 socklen_t fromlen;
236 FILE *file;
237 struct sockaddr_storage peer;
238 struct sockaddr_storage serv; /* valid server port number */
240 startclock(); /* start stat's clock */
241 dp = r_init(); /* reset fillbuf/read-ahead code */
242 ap = (struct tftphdr *)(void *)ackbuf;
243 if (tsize) {
244 if (fstat(fd, &sbuf) == 0) {
245 filesize = sbuf.st_size;
246 } else {
247 filesize = -1ULL;
250 file = fdopen(fd, "r");
251 convert = !strcmp(mode, "netascii");
252 block = 0;
253 amount = 0;
254 (void)memcpy(&peer, &peeraddr, (size_t)peeraddr.ss_len);
255 (void)memset(&serv, 0, sizeof(serv));
257 (void)signal(SIGALRM, timer);
258 do {
259 if (block == 0)
260 size = makerequest(WRQ, name, dp, mode, filesize) - 4;
261 else {
262 /* size = read(fd, dp->th_data, SEGSIZE); */
263 size = readit(file, &dp, blksize, convert);
264 if (size < 0) {
265 nak(errno + 100, (struct sockaddr *)(void *)&peer);
266 break;
268 dp->th_opcode = htons((u_short)DATA);
269 dp->th_block = htons((u_short)block);
271 timeout = 0;
272 (void) setjmp(timeoutbuf);
273 send_data:
274 if (trace)
275 tpacket("sent", dp, size + 4);
276 n = sendto(f, dp, (socklen_t)(size + 4), 0,
277 (struct sockaddr *)(void *)&peer, (socklen_t)peer.ss_len);
278 if (n != size + 4) {
279 warn("sendto");
280 goto abort;
282 if (block)
283 read_ahead(file, blksize, convert);
284 for ( ; ; ) {
285 (void)alarm(rexmtval);
286 do {
287 int curf;
288 fromlen = sizeof(from);
289 if (mcaddr != INADDR_NONE)
290 curf = mf;
291 else
292 curf = f;
293 n = recvfrom(curf, ackbuf, sizeof(ackbuf), 0,
294 (struct sockaddr *)(void *)&from, &fromlen);
295 } while (n <= 0);
296 (void)alarm(0);
297 if (n < 0) {
298 warn("recvfrom");
299 goto abort;
301 if (!serv.ss_family)
302 serv = from;
303 else if (!cmpport((struct sockaddr *)(void *)&serv,
304 (struct sockaddr *)(void *)&from)) {
305 warn("server port mismatch");
306 goto abort;
308 peer = from;
309 if (trace)
310 tpacket("received", ap, n);
311 /* should verify packet came from server */
312 ap->th_opcode = ntohs(ap->th_opcode);
313 if (ap->th_opcode == ERROR) {
314 (void)printf("Error code %d: %s\n", ap->th_code,
315 ap->th_msg);
316 goto abort;
318 if (ap->th_opcode == ACK) {
319 ap->th_block = ntohs(ap->th_block);
321 if (ap->th_block == 0) {
323 * If the extended options are enabled,
324 * the server just refused 'em all.
325 * The only one that _really_
326 * matters is blksize, but we'll
327 * clear timeout and mcaddr, too.
329 blksize = def_blksize;
330 rexmtval = def_rexmtval;
331 mcaddr = INADDR_NONE;
333 if (ap->th_block == block) {
334 break;
336 /* On an error, try to synchronize
337 * both sides.
339 j = synchnet(f, blksize+4);
340 if (j && trace) {
341 (void)printf("discarded %d packets\n",
344 if (ap->th_block == (block-1)) {
345 goto send_data;
348 if (ap->th_opcode == OACK) {
349 if (block == 0) {
350 blksize = def_blksize;
351 rexmtval = def_rexmtval;
352 mcaddr = INADDR_NONE;
353 get_options(ap, n);
354 break;
358 if (block > 0)
359 amount += size;
360 block++;
361 } while ((size_t)size == blksize || block == 1);
362 abort:
363 (void)fclose(file);
364 stopclock();
365 if (amount > 0)
366 printstats("Sent", amount);
370 * Receive a file.
372 void
373 recvfile(fd, name, mode)
374 int fd;
375 char *name;
376 char *mode;
378 struct tftphdr *ap;
379 struct tftphdr *dp;
380 int j, n;
381 volatile int oack = 0;
382 volatile unsigned int block;
383 volatile int size, firsttrip;
384 volatile unsigned long amount;
385 struct sockaddr_storage from;
386 socklen_t fromlen;
387 volatile size_t readlen;
388 FILE *file;
389 volatile int convert; /* true if converting crlf -> lf */
390 struct sockaddr_storage peer;
391 struct sockaddr_storage serv; /* valid server port number */
393 startclock();
394 dp = w_init();
395 ap = (struct tftphdr *)(void *)ackbuf;
396 file = fdopen(fd, "w");
397 convert = !strcmp(mode, "netascii");
398 block = 1;
399 firsttrip = 1;
400 amount = 0;
401 (void)memcpy(&peer, &peeraddr, (size_t)peeraddr.ss_len);
402 (void)memset(&serv, 0, sizeof(serv));
404 (void)signal(SIGALRM, timer);
405 do {
406 if (firsttrip) {
407 size = makerequest(RRQ, name, ap, mode, (off_t)0);
408 readlen = PKTSIZE;
409 firsttrip = 0;
410 } else {
411 ap->th_opcode = htons((u_short)ACK);
412 ap->th_block = htons((u_short)(block));
413 readlen = blksize+4;
414 size = 4;
415 block++;
417 timeout = 0;
418 (void) setjmp(timeoutbuf);
419 send_ack:
420 if (trace)
421 tpacket("sent", ap, size);
422 if (sendto(f, ackbuf, (socklen_t)size, 0,
423 (struct sockaddr *)(void *)&peer,
424 (socklen_t)peer.ss_len) != size) {
425 (void)alarm(0);
426 warn("sendto");
427 goto abort;
429 skip_ack:
430 if (write_behind(file, convert) == -1)
431 goto abort;
432 for ( ; ; ) {
433 (void)alarm(rexmtval);
434 do {
435 int readfd;
436 if (mf > 0)
437 readfd = mf;
438 else
439 readfd = f;
440 fromlen = sizeof(from);
441 n = recvfrom(readfd, dp, readlen, 0,
442 (struct sockaddr *)(void *)&from, &fromlen);
443 } while (n <= 0);
444 (void)alarm(0);
445 if (n < 0) {
446 warn("recvfrom");
447 goto abort;
449 if (!serv.ss_family)
450 serv = from;
451 else if (!cmpport((struct sockaddr *)(void *)&serv,
452 (struct sockaddr *)(void *)&from)) {
453 warn("server port mismatch");
454 goto abort;
456 peer = from;
457 if (trace)
458 tpacket("received", dp, n);
459 /* should verify client address */
460 dp->th_opcode = ntohs(dp->th_opcode);
461 if (dp->th_opcode == ERROR) {
462 (void)printf("Error code %d: %s\n", dp->th_code,
463 dp->th_msg);
464 goto abort;
466 if (dp->th_opcode == DATA) {
467 dp->th_block = ntohs(dp->th_block);
469 if (dp->th_block == 1 && !oack) {
470 /* no OACK, revert to defaults */
471 blksize = def_blksize;
472 rexmtval = def_rexmtval;
474 if (dp->th_block == block) {
475 break; /* have next packet */
477 /* On an error, try to synchronize
478 * both sides.
480 j = synchnet(f, blksize);
481 if (j && trace) {
482 (void)printf("discarded %d packets\n", j);
484 if (dp->th_block == (block-1)) {
485 goto send_ack; /* resend ack */
488 if (dp->th_opcode == OACK) {
489 if (block == 1) {
490 oack = 1;
491 blksize = def_blksize;
492 rexmtval = def_rexmtval;
493 get_options(dp, n);
494 ap->th_opcode = htons(ACK);
495 ap->th_block = 0;
496 readlen = blksize+4;
497 size = 4;
498 if (mcaddr != INADDR_NONE) {
499 mf = tftp_igmp_join();
500 if (mf < 0)
501 goto abort;
502 if (mcmasterslave == 0)
503 goto skip_ack;
505 goto send_ack;
509 /* size = write(fd, dp->th_data, n - 4); */
510 size = writeit(file, &dp, n - 4, convert);
511 if (size < 0) {
512 nak(errno + 100, (struct sockaddr *)(void *)&peer);
513 break;
515 amount += size;
516 } while ((size_t)size == blksize);
517 abort: /* ok to ack, since user */
518 ap->th_opcode = htons((u_short)ACK); /* has seen err msg */
519 ap->th_block = htons((u_short)block);
520 if (mcaddr != INADDR_NONE && mf >= 0) {
521 tftp_igmp_leave(mf);
522 mf = -1;
524 (void) sendto(f, ackbuf, 4, 0, (struct sockaddr *)(void *)&peer,
525 (socklen_t)peer.ss_len);
527 * flush last buffer
528 * We do not check for failure because last buffer
529 * can be empty, thus returning an error.
530 * XXX maybe we should fix 'write_behind' instead.
532 (void)write_behind(file, convert);
533 (void)fclose(file);
534 stopclock();
535 if (amount > 0)
536 printstats("Received", amount);
539 static int
540 makerequest(request, name, tp, mode, filesize)
541 int request;
542 const char *name;
543 struct tftphdr *tp;
544 const char *mode;
545 off_t filesize;
547 char *cp;
549 tp->th_opcode = htons((u_short)request);
550 #ifndef __SVR4
551 cp = tp->th_stuff;
552 #else
553 cp = (void *)&tp->th_stuff;
554 #endif
555 (void)strcpy(cp, name);
556 cp += strlen(name);
557 *cp++ = '\0';
558 (void)strcpy(cp, mode);
559 cp += strlen(mode);
560 *cp++ = '\0';
561 if (tsize) {
562 (void)strcpy(cp, "tsize");
563 cp += strlen(cp);
564 *cp++ = '\0';
565 (void)sprintf(cp, "%lu", (unsigned long) filesize);
566 cp += strlen(cp);
567 *cp++ = '\0';
569 if (tout) {
570 (void)strcpy(cp, "timeout");
571 cp += strlen(cp);
572 *cp++ = '\0';
573 (void)sprintf(cp, "%d", rexmtval);
574 cp += strlen(cp);
575 *cp++ = '\0';
577 if (blksize != SEGSIZE) {
578 (void)strcpy(cp, "blksize");
579 cp += strlen(cp);
580 *cp++ = '\0';
581 (void)sprintf(cp, "%zd", blksize);
582 cp += strlen(cp);
583 *cp++ = '\0';
585 return (cp - (char *)(void *)tp);
588 const struct errmsg {
589 int e_code;
590 const char *e_msg;
591 } errmsgs[] = {
592 { EUNDEF, "Undefined error code" },
593 { ENOTFOUND, "File not found" },
594 { EACCESS, "Access violation" },
595 { ENOSPACE, "Disk full or allocation exceeded" },
596 { EBADOP, "Illegal TFTP operation" },
597 { EBADID, "Unknown transfer ID" },
598 { EEXISTS, "File already exists" },
599 { ENOUSER, "No such user" },
600 { EOPTNEG, "Option negotiation failed" },
601 { -1, 0 }
605 * Send a nak packet (error message).
606 * Error code passed in is one of the
607 * standard TFTP codes, or a UNIX errno
608 * offset by 100.
610 static void
611 nak(error, peer)
612 int error;
613 struct sockaddr *peer;
615 const struct errmsg *pe;
616 struct tftphdr *tp;
617 int length;
618 size_t msglen;
620 tp = (struct tftphdr *)(void *)ackbuf;
621 tp->th_opcode = htons((u_short)ERROR);
622 msglen = sizeof(ackbuf) - (&tp->th_msg[0] - ackbuf);
623 for (pe = errmsgs; pe->e_code >= 0; pe++)
624 if (pe->e_code == error)
625 break;
626 if (pe->e_code < 0) {
627 tp->th_code = EUNDEF;
628 (void)strlcpy(tp->th_msg, strerror(error - 100), msglen);
629 } else {
630 tp->th_code = htons((u_short)error);
631 (void)strlcpy(tp->th_msg, pe->e_msg, msglen);
633 length = strlen(tp->th_msg);
634 msglen = &tp->th_msg[length + 1] - ackbuf;
635 if (trace)
636 tpacket("sent", tp, (int)msglen);
637 if ((size_t)sendto(f, ackbuf, msglen, 0, peer, (socklen_t)peer->sa_len) != msglen)
638 warn("nak");
641 static void
642 tpacket(s, tp, n)
643 const char *s;
644 struct tftphdr *tp;
645 int n;
647 static const char *opcodes[] =
648 { "#0", "RRQ", "WRQ", "DATA", "ACK", "ERROR", "OACK" };
649 char *cp, *file, *endp, *opt = NULL;
650 const char *spc;
651 u_short op = ntohs(tp->th_opcode);
652 int i, o;
654 if (op < RRQ || op > OACK)
655 (void)printf("%s opcode=%x ", s, op);
656 else
657 (void)printf("%s %s ", s, opcodes[op]);
658 switch (op) {
660 case RRQ:
661 case WRQ:
662 n -= 2;
663 #ifndef __SVR4
664 cp = tp->th_stuff;
665 #else
666 cp = (void *) &tp->th_stuff;
667 #endif
668 endp = cp + n - 1;
669 if (*endp != '\0') { /* Shouldn't happen, but... */
670 *endp = '\0';
672 file = cp;
673 cp = strchr(cp, '\0') + 1;
674 (void)printf("<file=%s, mode=%s", file, cp);
675 cp = strchr(cp, '\0') + 1;
676 o = 0;
677 while (cp < endp) {
678 i = strlen(cp) + 1;
679 if (o) {
680 (void)printf(", %s=%s", opt, cp);
681 } else {
682 opt = cp;
684 o = (o+1) % 2;
685 cp += i;
687 (void)printf(">\n");
688 break;
690 case DATA:
691 (void)printf("<block=%d, %d bytes>\n", ntohs(tp->th_block), n - 4);
692 break;
694 case ACK:
695 (void)printf("<block=%d>\n", ntohs(tp->th_block));
696 break;
698 case ERROR:
699 (void)printf("<code=%d, msg=%s>\n", ntohs(tp->th_code), tp->th_msg);
700 break;
702 case OACK:
703 o = 0;
704 n -= 2;
705 cp = tp->th_stuff;
706 endp = cp + n - 1;
707 if (*endp != '\0') { /* Shouldn't happen, but... */
708 *endp = '\0';
710 (void)printf("<");
711 spc = "";
712 while (cp < endp) {
713 i = strlen(cp) + 1;
714 if (o) {
715 (void)printf("%s%s=%s", spc, opt, cp);
716 spc = ", ";
717 } else {
718 opt = cp;
720 o = (o+1) % 2;
721 cp += i;
723 (void)printf(">\n");
724 break;
728 struct timeval tstart;
729 struct timeval tstop;
731 static void
732 startclock()
735 (void)gettimeofday(&tstart, NULL);
738 static void
739 stopclock()
742 (void)gettimeofday(&tstop, NULL);
745 static void
746 printstats(direction, amount)
747 const char *direction;
748 unsigned long amount;
750 double delta;
752 /* compute delta in 1/10's second units */
753 delta = ((tstop.tv_sec*10.)+(tstop.tv_usec/100000)) -
754 ((tstart.tv_sec*10.)+(tstart.tv_usec/100000));
755 delta = delta/10.; /* back to seconds */
756 (void)printf("%s %ld bytes in %.1f seconds", direction, amount, delta);
757 if (verbose)
758 (void)printf(" [%.0f bits/sec]", (amount*8.)/delta);
759 (void)putchar('\n');
762 static void
763 /*ARGSUSED*/
764 timer(sig)
765 int sig;
768 timeout += rexmtval;
769 if (timeout >= maxtimeout) {
770 (void)printf("Transfer timed out.\n");
771 longjmp(toplevel, -1);
773 longjmp(timeoutbuf, 1);
776 static int
777 cmpport(sa, sb)
778 struct sockaddr *sa;
779 struct sockaddr *sb;
781 char a[NI_MAXSERV], b[NI_MAXSERV];
783 if (getnameinfo(sa, (socklen_t)sa->sa_len, NULL, 0, a, sizeof(a), NI_NUMERICSERV))
784 return 0;
785 if (getnameinfo(sb, (socklen_t)sb->sa_len, NULL, 0, b, sizeof(b), NI_NUMERICSERV))
786 return 0;
787 if (strcmp(a, b) != 0)
788 return 0;
790 return 1;