xref: /freebsd/usr.bin/tftp/tftp.c (revision 282a3889ebf826db9839be296ff1dd903f6d6d6e)
1 /*
2  * Copyright (c) 1983, 1993
3  *	The Regents of the University of California.  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 #if 0
35 #ifndef lint
36 static char sccsid[] = "@(#)tftp.c	8.1 (Berkeley) 6/6/93";
37 #endif /* not lint */
38 #endif
39 
40 #include <sys/cdefs.h>
41 __FBSDID("$FreeBSD$");
42 
43 /* Many bug fixes are from Jim Guyton <guyton@rand-unix> */
44 
45 /*
46  * TFTP User Program -- Protocol Machines
47  */
48 #include <sys/types.h>
49 #include <sys/socket.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 #include <stdio.h>
62 #include <string.h>
63 #include <unistd.h>
64 #include <netdb.h>
65 
66 #include "extern.h"
67 #include "tftpsubs.h"
68 
69 extern  struct sockaddr_storage peeraddr; /* filled in by main */
70 extern  int     f;			/* the opened socket */
71 extern  int     trace;
72 extern  int     verbose;
73 extern  int     rexmtval;
74 extern  int     maxtimeout;
75 extern  volatile int txrx_error;
76 
77 #define PKTSIZE    SEGSIZE+4
78 char    ackbuf[PKTSIZE];
79 int	timeout;
80 jmp_buf	toplevel;
81 jmp_buf	timeoutbuf;
82 
83 static void nak(int, struct sockaddr *);
84 static int makerequest(int, const char *, struct tftphdr *, const char *);
85 static void printstats(const char *, unsigned long);
86 static void startclock(void);
87 static void stopclock(void);
88 static void timer(int);
89 static void tpacket(const char *, struct tftphdr *, int);
90 static int cmpport(struct sockaddr *, struct sockaddr *);
91 
92 /*
93  * Send the requested file.
94  */
95 void
96 xmitfile(fd, name, mode)
97 	int fd;
98 	char *name;
99 	char *mode;
100 {
101 	struct tftphdr *ap;	   /* data and ack packets */
102 	struct tftphdr *dp;
103 	int n;
104 	volatile unsigned short block;
105 	volatile int size, convert;
106 	volatile unsigned long amount;
107 	struct sockaddr_storage from;
108 	socklen_t fromlen;
109 	FILE *file;
110 	struct sockaddr_storage peer;
111 	struct sockaddr_storage serv;	/* valid server port number */
112 
113 	startclock();		/* start stat's clock */
114 	dp = r_init();		/* reset fillbuf/read-ahead code */
115 	ap = (struct tftphdr *)ackbuf;
116 	file = fdopen(fd, "r");
117 	convert = !strcmp(mode, "netascii");
118 	block = 0;
119 	amount = 0;
120 	memcpy(&peer, &peeraddr, peeraddr.ss_len);
121 	memset(&serv, 0, sizeof(serv));
122 
123 	signal(SIGALRM, timer);
124 	do {
125 		if (block == 0)
126 			size = makerequest(WRQ, name, dp, mode) - 4;
127 		else {
128 		/*	size = read(fd, dp->th_data, SEGSIZE);	 */
129 			size = readit(file, &dp, convert);
130 			if (size < 0) {
131 				nak(errno + 100, (struct sockaddr *)&peer);
132 				break;
133 			}
134 			dp->th_opcode = htons((u_short)DATA);
135 			dp->th_block = htons((u_short)block);
136 		}
137 		timeout = 0;
138 		(void) setjmp(timeoutbuf);
139 send_data:
140 		if (trace)
141 			tpacket("sent", dp, size + 4);
142 		n = sendto(f, dp, size + 4, 0,
143 		    (struct sockaddr *)&peer, peer.ss_len);
144 		if (n != size + 4) {
145 			warn("sendto");
146 			goto abort;
147 		}
148 		read_ahead(file, convert);
149 		for ( ; ; ) {
150 			alarm(rexmtval);
151 			do {
152 				fromlen = sizeof(from);
153 				n = recvfrom(f, ackbuf, sizeof(ackbuf), 0,
154 				    (struct sockaddr *)&from, &fromlen);
155 			} while (n <= 0);
156 			alarm(0);
157 			if (n < 0) {
158 				warn("recvfrom");
159 				goto abort;
160 			}
161 			if (!serv.ss_family)
162 				serv = from;
163 			else if (!cmpport((struct sockaddr *)&serv,
164 			    (struct sockaddr *)&from)) {
165 				warn("server port mismatch");
166 				goto abort;
167 			}
168 			peer = from;
169 			if (trace)
170 				tpacket("received", ap, n);
171 			/* should verify packet came from server */
172 			ap->th_opcode = ntohs(ap->th_opcode);
173 			ap->th_block = ntohs(ap->th_block);
174 			if (ap->th_opcode == ERROR) {
175 				printf("Error code %d: %s\n", ap->th_code,
176 					ap->th_msg);
177 				txrx_error = 1;
178 				goto abort;
179 			}
180 			if (ap->th_opcode == ACK) {
181 				int j;
182 
183 				if (ap->th_block == block) {
184 					break;
185 				}
186 				/* On an error, try to synchronize
187 				 * both sides.
188 				 */
189 				j = synchnet(f);
190 				if (j && trace) {
191 					printf("discarded %d packets\n",
192 							j);
193 				}
194 				if (ap->th_block == (block-1)) {
195 					goto send_data;
196 				}
197 			}
198 		}
199 		if (block > 0)
200 			amount += size;
201 		block++;
202 	} while (size == SEGSIZE || block == 1);
203 abort:
204 	fclose(file);
205 	stopclock();
206 	if (amount > 0)
207 		printstats("Sent", amount);
208 	txrx_error = 1;
209 }
210 
211 /*
212  * Receive a file.
213  */
214 void
215 recvfile(fd, name, mode)
216 	int fd;
217 	char *name;
218 	char *mode;
219 {
220 	struct tftphdr *ap;
221 	struct tftphdr *dp;
222 	int n;
223 	volatile unsigned short block;
224 	volatile int size, firsttrip;
225 	volatile unsigned long amount;
226 	struct sockaddr_storage from;
227 	socklen_t fromlen;
228 	FILE *file;
229 	volatile int convert;		/* true if converting crlf -> lf */
230 	struct sockaddr_storage peer;
231 	struct sockaddr_storage serv;	/* valid server port number */
232 
233 	startclock();
234 	dp = w_init();
235 	ap = (struct tftphdr *)ackbuf;
236 	file = fdopen(fd, "w");
237 	convert = !strcmp(mode, "netascii");
238 	block = 1;
239 	firsttrip = 1;
240 	amount = 0;
241 	memcpy(&peer, &peeraddr, peeraddr.ss_len);
242 	memset(&serv, 0, sizeof(serv));
243 
244 	signal(SIGALRM, timer);
245 	do {
246 		if (firsttrip) {
247 			size = makerequest(RRQ, name, ap, mode);
248 			firsttrip = 0;
249 		} else {
250 			ap->th_opcode = htons((u_short)ACK);
251 			ap->th_block = htons((u_short)(block));
252 			size = 4;
253 			block++;
254 		}
255 		timeout = 0;
256 		(void) setjmp(timeoutbuf);
257 send_ack:
258 		if (trace)
259 			tpacket("sent", ap, size);
260 		if (sendto(f, ackbuf, size, 0, (struct sockaddr *)&peer,
261 		    peer.ss_len) != size) {
262 			alarm(0);
263 			warn("sendto");
264 			goto abort;
265 		}
266 		write_behind(file, convert);
267 		for ( ; ; ) {
268 			alarm(rexmtval);
269 			do  {
270 				fromlen = sizeof(from);
271 				n = recvfrom(f, dp, PKTSIZE, 0,
272 				    (struct sockaddr *)&from, &fromlen);
273 			} while (n <= 0);
274 			alarm(0);
275 			if (n < 0) {
276 				warn("recvfrom");
277 				goto abort;
278 			}
279 			if (!serv.ss_family)
280 				serv = from;
281 			else if (!cmpport((struct sockaddr *)&serv,
282 			    (struct sockaddr *)&from)) {
283 				warn("server port mismatch");
284 				goto abort;
285 			}
286 			peer = from;
287 			if (trace)
288 				tpacket("received", dp, n);
289 			/* should verify client address */
290 			dp->th_opcode = ntohs(dp->th_opcode);
291 			dp->th_block = ntohs(dp->th_block);
292 			if (dp->th_opcode == ERROR) {
293 				printf("Error code %d: %s\n", dp->th_code,
294 					dp->th_msg);
295 				txrx_error = 1;
296 				goto abort;
297 			}
298 			if (dp->th_opcode == DATA) {
299 				int j;
300 
301 				if (dp->th_block == block) {
302 					break;		/* have next packet */
303 				}
304 				/* On an error, try to synchronize
305 				 * both sides.
306 				 */
307 				j = synchnet(f);
308 				if (j && trace) {
309 					printf("discarded %d packets\n", j);
310 				}
311 				if (dp->th_block == (block-1)) {
312 					goto send_ack;	/* resend ack */
313 				}
314 			}
315 		}
316 	/*	size = write(fd, dp->th_data, n - 4); */
317 		size = writeit(file, &dp, n - 4, convert);
318 		if (size < 0) {
319 			nak(errno + 100, (struct sockaddr *)&peer);
320 			break;
321 		}
322 		amount += size;
323 	} while (size == SEGSIZE);
324 abort:						/* ok to ack, since user */
325 	ap->th_opcode = htons((u_short)ACK);	/* has seen err msg */
326 	ap->th_block = htons((u_short)block);
327 	(void) sendto(f, ackbuf, 4, 0, (struct sockaddr *)&peer,
328 	    peer.ss_len);
329 	write_behind(file, convert);		/* flush last buffer */
330 	fclose(file);
331 	stopclock();
332 	if (amount > 0)
333 		printstats("Received", amount);
334 	txrx_error = 1;
335 }
336 
337 static int
338 makerequest(request, name, tp, mode)
339 	int request;
340 	const char *name;
341 	struct tftphdr *tp;
342 	const char *mode;
343 {
344 	char *cp;
345 
346 	tp->th_opcode = htons((u_short)request);
347 	cp = tp->th_stuff;
348 	strcpy(cp, name);
349 	cp += strlen(name);
350 	*cp++ = '\0';
351 	strcpy(cp, mode);
352 	cp += strlen(mode);
353 	*cp++ = '\0';
354 	return (cp - (char *)tp);
355 }
356 
357 struct errmsg {
358 	int	e_code;
359 	const char	*e_msg;
360 } errmsgs[] = {
361 	{ EUNDEF,	"Undefined error code" },
362 	{ ENOTFOUND,	"File not found" },
363 	{ EACCESS,	"Access violation" },
364 	{ ENOSPACE,	"Disk full or allocation exceeded" },
365 	{ EBADOP,	"Illegal TFTP operation" },
366 	{ EBADID,	"Unknown transfer ID" },
367 	{ EEXISTS,	"File already exists" },
368 	{ ENOUSER,	"No such user" },
369 	{ -1,		0 }
370 };
371 
372 /*
373  * Send a nak packet (error message).
374  * Error code passed in is one of the
375  * standard TFTP codes, or a UNIX errno
376  * offset by 100.
377  */
378 static void
379 nak(error, peer)
380 	int error;
381 	struct sockaddr *peer;
382 {
383 	struct errmsg *pe;
384 	struct tftphdr *tp;
385 	int length;
386 
387 	tp = (struct tftphdr *)ackbuf;
388 	tp->th_opcode = htons((u_short)ERROR);
389 	tp->th_code = htons((u_short)error);
390 	for (pe = errmsgs; pe->e_code >= 0; pe++)
391 		if (pe->e_code == error)
392 			break;
393 	if (pe->e_code < 0) {
394 		pe->e_msg = strerror(error - 100);
395 		tp->th_code = EUNDEF;
396 	}
397 	strcpy(tp->th_msg, pe->e_msg);
398 	length = strlen(pe->e_msg) + 4;
399 	if (trace)
400 		tpacket("sent", tp, length);
401 	if (sendto(f, ackbuf, length, 0, peer, peer->sa_len) != length)
402 		warn("nak");
403 }
404 
405 static void
406 tpacket(s, tp, n)
407 	const char *s;
408 	struct tftphdr *tp;
409 	int n;
410 {
411 	static const char *opcodes[] =
412 	   { "#0", "RRQ", "WRQ", "DATA", "ACK", "ERROR" };
413 	char *cp, *file;
414 	u_short op = ntohs(tp->th_opcode);
415 
416 	if (op < RRQ || op > ERROR)
417 		printf("%s opcode=%x ", s, op);
418 	else
419 		printf("%s %s ", s, opcodes[op]);
420 	switch (op) {
421 
422 	case RRQ:
423 	case WRQ:
424 		n -= 2;
425 		file = cp = tp->th_stuff;
426 		cp = index(cp, '\0');
427 		printf("<file=%s, mode=%s>\n", file, cp + 1);
428 		break;
429 
430 	case DATA:
431 		printf("<block=%d, %d bytes>\n", ntohs(tp->th_block), n - 4);
432 		break;
433 
434 	case ACK:
435 		printf("<block=%d>\n", ntohs(tp->th_block));
436 		break;
437 
438 	case ERROR:
439 		printf("<code=%d, msg=%s>\n", ntohs(tp->th_code), tp->th_msg);
440 		break;
441 	}
442 }
443 
444 struct timeval tstart;
445 struct timeval tstop;
446 
447 static void
448 startclock()
449 {
450 
451 	(void)gettimeofday(&tstart, NULL);
452 }
453 
454 static void
455 stopclock()
456 {
457 
458 	(void)gettimeofday(&tstop, NULL);
459 }
460 
461 static void
462 printstats(direction, amount)
463 	const char *direction;
464 	unsigned long amount;
465 {
466 	double delta;
467 			/* compute delta in 1/10's second units */
468 	delta = ((tstop.tv_sec*10.)+(tstop.tv_usec/100000)) -
469 		((tstart.tv_sec*10.)+(tstart.tv_usec/100000));
470 	delta = delta/10.;      /* back to seconds */
471 	printf("%s %ld bytes in %.1f seconds", direction, amount, delta);
472 	if (verbose)
473 		printf(" [%.0f bits/sec]", (amount*8.)/delta);
474 	putchar('\n');
475 }
476 
477 static void
478 timer(sig)
479 	int sig __unused;
480 {
481 
482 	timeout += rexmtval;
483 	if (timeout >= maxtimeout) {
484 		printf("Transfer timed out.\n");
485 		longjmp(toplevel, -1);
486 	}
487         txrx_error = 1;
488 	longjmp(timeoutbuf, 1);
489 }
490 
491 static int
492 cmpport(sa, sb)
493 	struct sockaddr *sa;
494 	struct sockaddr *sb;
495 {
496 	char a[NI_MAXSERV], b[NI_MAXSERV];
497 
498 	if (getnameinfo(sa, sa->sa_len, NULL, 0, a, sizeof(a), NI_NUMERICSERV))
499 		return 0;
500 	if (getnameinfo(sb, sb->sa_len, NULL, 0, b, sizeof(b), NI_NUMERICSERV))
501 		return 0;
502 	if (strcmp(a, b) != 0)
503 		return 0;
504 
505 	return 1;
506 }
507