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