tftpsubs.c revision 1.10
1/*	$OpenBSD: tftpsubs.c,v 1.10 2006/07/12 16:58:51 mglocker Exp $	*/
2/*	$NetBSD: tftpsubs.c,v 1.3 1994/12/08 09:51:31 jtc Exp $	*/
3
4/*
5 * Copyright (c) 1983, 1993
6 *	The Regents of the University of California.  All rights reserved.
7 *
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
10 * are met:
11 * 1. Redistributions of source code must retain the above copyright
12 *    notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 *    notice, this list of conditions and the following disclaimer in the
15 *    documentation and/or other materials provided with the distribution.
16 * 3. Neither the name of the University nor the names of its contributors
17 *    may be used to endorse or promote products derived from this software
18 *    without specific prior written permission.
19 *
20 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30 * SUCH DAMAGE.
31 */
32
33#ifndef lint
34#if 0
35static char sccsid[] = "@(#)tftpsubs.c	8.1 (Berkeley) 6/6/93";
36#endif
37static const char rcsid[] =
38    "$OpenBSD: tftpsubs.c,v 1.10 2006/07/12 16:58:51 mglocker Exp $";
39#endif /* not lint */
40
41/*
42 * Simple minded read-ahead/write-behind subroutines for tftp user and
43 * server.  Written originally with multiple buffers in mind, but current
44 * implementation has two buffer logic wired in.
45 *
46 * Todo:  add some sort of final error check so when the write-buffer
47 * is finally flushed, the caller can detect if the disk filled up
48 * (or had an i/o error) and return a nak to the other side.
49 *
50 *			Jim Guyton 10/85
51 */
52
53#include <sys/types.h>
54#include <sys/socket.h>
55#include <sys/ioctl.h>
56
57#include <netinet/in.h>
58#include <arpa/tftp.h>
59
60#include <stdio.h>
61#include <unistd.h>
62
63#include "tftpsubs.h"
64
65#define PKTSIZE		SEGSIZE + 4	/* should be moved to tftp.h */
66					/* values for bf.counter */
67#define BF_ALLOC	-3		/* alloc'd but not yet filled */
68#define BF_FREE		-2		/* free */
69/* [-1 .. SEGSIZE] = size of data in the data buffer */
70
71static struct tftphdr	*rw_init(int);
72
73struct bf {
74	int	counter;	/* size of data in buffer, or flag */
75	char	buf[PKTSIZE];	/* room for data packet */
76} bfs[2];
77
78static int	nextone;	/* index of next buffer to use */
79static int	current;	/* index of buffer in use */
80				/* control flags for crlf conversions */
81int		newline = 0;	/* fillbuf: in middle of newline expansion */
82int		prevchar = -1;	/* putbuf: previous char (cr check) */
83
84struct tftphdr *
85w_init(void)
86{
87	return (rw_init(0));	/* write-behind */
88}
89
90struct tftphdr *
91r_init(void)
92{
93	return (rw_init(1));	/* read-ahead */
94}
95
96/*
97 * Init for either read-ahead or write-behind.
98 * Zero for write-behind, one for read-head.
99 */
100static struct tftphdr *
101rw_init(int x)
102{
103	newline = 0;			/* init crlf flag */
104	prevchar = -1;
105	bfs[0].counter =  BF_ALLOC;	/* pass out the first buffer */
106	current = 0;
107	bfs[1].counter = BF_FREE;
108	nextone = x;			/* ahead or behind? */
109
110	return ((struct tftphdr *)bfs[0].buf);
111}
112
113/*
114 * Have emptied current buffer by sending to net and getting ack.
115 * Free it and return next buffer filled with data.
116 */
117int
118readit(FILE *file, struct tftphdr **dpp, int convert)
119{
120	struct bf	*b;
121
122	bfs[current].counter = BF_FREE;		/* free old one */
123	current = !current;			/* "incr" current */
124
125	b = &bfs[current];			/* look at new buffer */
126	if (b->counter == BF_FREE)		/* if it's empty */
127		read_ahead(file, convert);	/* fill it */
128	/* assert(b->counter != BF_FREE); */	/* check */
129	*dpp = (struct tftphdr *)b->buf;	/* set caller's ptr */
130
131	return (b->counter);
132}
133
134/*
135 * Fill the input buffer, doing ascii conversions if requested.
136 * Conversions are lf -> cr, lf and cr -> cr, nul.
137 */
138void
139read_ahead(FILE *file, int convert)
140{
141	int		 i;
142	char		*p;
143	int		 c;
144	struct bf	*b;
145	struct tftphdr	*dp;
146
147	b = &bfs[nextone];			/* look at "next" buffer */
148	if (b->counter != BF_FREE)		/* nop if not free */
149		return;
150	nextone = !nextone;			/* "incr" next buffer ptr */
151
152	dp = (struct tftphdr *)b->buf;
153
154	if (convert == 0) {
155		b->counter = read(fileno(file), dp->th_data, SEGSIZE);
156		return;
157	}
158
159	p = dp->th_data;
160	for (i = 0; i < SEGSIZE; i++) {
161		if (newline) {
162			if (prevchar == '\n')
163				c = '\n';	/* lf to cr, lf */
164			else
165				c = '\0';	/* cr to cr, nul */
166			newline = 0;
167		} else {
168			c = getc(file);
169			if (c == EOF)
170				break;
171			if (c == '\n' || c == '\r') {
172				prevchar = c;
173				c = '\r';
174				newline = 1;
175			}
176		}
177	       *p++ = c;
178	}
179	b->counter = (int)(p - dp->th_data);
180}
181
182/*
183 * Update count associated with the buffer, get new buffer
184 * from the queue.  Calls write_behind only if next buffer not
185 * available.
186 */
187int
188writeit(FILE *file, struct tftphdr **dpp, int ct, int convert)
189{
190	bfs[current].counter = ct;		/* set size of data to write */
191	current = !current;			/* switch to other buffer */
192	if (bfs[current].counter != BF_FREE)	/* if not free */
193		/* flush it */
194		(void)write_behind(file, convert);
195	bfs[current].counter = BF_ALLOC;	/* mark as alloc'd */
196	*dpp =  (struct tftphdr *)bfs[current].buf;
197
198	return (ct);				/* this is a lie of course */
199}
200
201/*
202 * Output a buffer to a file, converting from netascii if requested.
203 * CR, NUL -> CR and CR, LF -> LF.
204 * Note spec is undefined if we get CR as last byte of file or a
205 * CR followed by anything else.  In this case we leave it alone.
206 */
207int
208write_behind(FILE *file, int convert)
209{
210	char		*buf;
211	int		 count;
212	int		 ct;
213	char		*p;
214	int		 c; /* current character */
215	struct bf	*b;
216	struct tftphdr	*dp;
217
218	b = &bfs[nextone];
219	if (b->counter < -1)		/* anything to flush? */
220		return (0);		/* just nop if nothing to do */
221
222	count = b->counter;		/* remember byte count */
223	b->counter = BF_FREE;		/* reset flag */
224	dp = (struct tftphdr *)b->buf;
225	nextone = !nextone;		/* incr for next time */
226	buf = dp->th_data;
227
228	if (count <= 0)			/* nak logic? */
229		return (-1);
230
231	if (convert == 0)
232		return (write(fileno(file), buf, count));
233
234	p = buf;
235	ct = count;
236	while (ct--) {				/* loop over the buffer */
237		c = *p++;			/* pick up a character */
238		if (prevchar == '\r') {		/* if prev char was cr */
239			if (c == '\n')		/* if have cr,lf then just */
240				/* smash lf on top of the cr */
241				fseek(file, -1, 1);
242			else if (c == '\0')	/* if have cr,nul then */
243				goto skipit;	/* just skip over the putc */
244			/* FALLTHROUGH */
245		}
246		putc(c, file);
247skipit:
248		prevchar = c;
249	}
250
251	return (count);
252}
253
254/*
255 * When an error has occurred, it is possible that the two sides
256 * are out of synch.  Ie: that what I think is the other side's
257 * response to packet N is really their response to packet N-1.
258 *
259 * So, to try to prevent that, we flush all the input queued up
260 * for us on the network connection on our host.
261 *
262 * We return the number of packets we flushed (mostly for reporting
263 * when trace is active).
264 */
265int
266synchnet(int f)
267{
268	int			i, j = 0;
269	char			rbuf[PKTSIZE];
270	struct sockaddr_in	from;
271	socklen_t		fromlen;
272
273	for (;;) {
274		(void)ioctl(f, FIONREAD, &i);
275		if (i) {
276			j++;
277			fromlen = sizeof(from);
278			(void)recvfrom(f, rbuf, sizeof(rbuf), 0,
279			    (struct sockaddr *)&from, &fromlen);
280		} else
281			return (j);
282	}
283}
284