tftp.c revision 92922
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#include <sys/cdefs.h>
35
36__FBSDID("$FreeBSD: head/usr.bin/tftp/tftp.c 92922 2002-03-22 01:42:45Z imp $");
37
38#ifndef lint
39static const char sccsid[] = "@(#)tftp.c	8.1 (Berkeley) 6/6/93";
40#endif
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
66extern  struct sockaddr_in peeraddr;	/* filled in by main */
67extern  int     f;			/* the opened socket */
68extern  int     trace;
69extern  int     verbose;
70extern  int     rexmtval;
71extern  int     maxtimeout;
72
73#define PKTSIZE    SEGSIZE+4
74char    ackbuf[PKTSIZE];
75int	timeout;
76jmp_buf	toplevel;
77jmp_buf	timeoutbuf;
78
79static void nak(int);
80static int makerequest(int, const char *, struct tftphdr *, const char *);
81static void printstats(const char *, unsigned long);
82static void startclock(void);
83static void stopclock(void);
84static void timer(int);
85static void tpacket(const char *, struct tftphdr *, int);
86
87/*
88 * Send the requested file.
89 */
90void
91xmitfile(fd, name, mode)
92	int fd;
93	char *name;
94	char *mode;
95{
96	struct tftphdr *ap;	   /* data and ack packets */
97	struct tftphdr *dp;
98	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);
130send_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);
186abort:
187	fclose(file);
188	stopclock();
189	if (amount > 0)
190		printstats("Sent", amount);
191}
192
193/*
194 * Receive a file.
195 */
196void
197recvfile(fd, name, mode)
198	int fd;
199	char *name;
200	char *mode;
201{
202	struct tftphdr *ap;
203	struct tftphdr *dp;
204	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);
235send_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);
294abort:						/* 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
306static int
307makerequest(request, name, tp, mode)
308	int request;
309	const char *name;
310	struct tftphdr *tp;
311	const char *mode;
312{
313	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
326struct errmsg {
327	int	e_code;
328	const 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 */
347static void
348nak(error)
349	int error;
350{
351	struct errmsg *pe;
352	struct tftphdr *tp;
353	int length;
354
355	tp = (struct tftphdr *)ackbuf;
356	tp->th_opcode = htons((u_short)ERROR);
357	tp->th_code = htons((u_short)error);
358	for (pe = errmsgs; pe->e_code >= 0; pe++)
359		if (pe->e_code == error)
360			break;
361	if (pe->e_code < 0) {
362		pe->e_msg = strerror(error - 100);
363		tp->th_code = EUNDEF;
364	}
365	strcpy(tp->th_msg, pe->e_msg);
366	length = strlen(pe->e_msg) + 4;
367	if (trace)
368		tpacket("sent", tp, length);
369	if (sendto(f, ackbuf, length, 0, (struct sockaddr *)&peeraddr,
370	    sizeof(peeraddr)) != length)
371		warn("nak");
372}
373
374static void
375tpacket(s, tp, n)
376	const char *s;
377	struct tftphdr *tp;
378	int n;
379{
380	static const char *opcodes[] =
381	   { "#0", "RRQ", "WRQ", "DATA", "ACK", "ERROR" };
382	char *cp, *file;
383	u_short op = ntohs(tp->th_opcode);
384
385	if (op < RRQ || op > ERROR)
386		printf("%s opcode=%x ", s, op);
387	else
388		printf("%s %s ", s, opcodes[op]);
389	switch (op) {
390
391	case RRQ:
392	case WRQ:
393		n -= 2;
394		file = cp = tp->th_stuff;
395		cp = index(cp, '\0');
396		printf("<file=%s, mode=%s>\n", file, cp + 1);
397		break;
398
399	case DATA:
400		printf("<block=%d, %d bytes>\n", ntohs(tp->th_block), n - 4);
401		break;
402
403	case ACK:
404		printf("<block=%d>\n", ntohs(tp->th_block));
405		break;
406
407	case ERROR:
408		printf("<code=%d, msg=%s>\n", ntohs(tp->th_code), tp->th_msg);
409		break;
410	}
411}
412
413struct timeval tstart;
414struct timeval tstop;
415
416static void
417startclock()
418{
419
420	(void)gettimeofday(&tstart, NULL);
421}
422
423static void
424stopclock()
425{
426
427	(void)gettimeofday(&tstop, NULL);
428}
429
430static void
431printstats(direction, amount)
432	const char *direction;
433	unsigned long amount;
434{
435	double delta;
436			/* compute delta in 1/10's second units */
437	delta = ((tstop.tv_sec*10.)+(tstop.tv_usec/100000)) -
438		((tstart.tv_sec*10.)+(tstart.tv_usec/100000));
439	delta = delta/10.;      /* back to seconds */
440	printf("%s %ld bytes in %.1f seconds", direction, amount, delta);
441	if (verbose)
442		printf(" [%.0f bits/sec]", (amount*8.)/delta);
443	putchar('\n');
444}
445
446static void
447timer(sig)
448	int sig __unused;
449{
450
451	timeout += rexmtval;
452	if (timeout >= maxtimeout) {
453		printf("Transfer timed out.\n");
454		longjmp(toplevel, -1);
455	}
456	longjmp(timeoutbuf, 1);
457}
458