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