tftpsubs.c revision 1.13
1/*	$OpenBSD: tftpsubs.c,v 1.13 2007/09/10 14:29:53 tobias 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.13 2007/09/10 14:29:53 tobias 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					/* values for bf.counter */
66#define BF_ALLOC	-3		/* alloc'd but not yet filled */
67#define BF_FREE		-2		/* free */
68/* [-1 .. SEGSIZE] = size of data in the data buffer */
69
70static struct tftphdr	*rw_init(int);
71
72struct bf {
73	int	counter;		/* size of data in buffer, or flag */
74	char	buf[SEGSIZE_MAX + 4];	/* room for data packet */
75} bfs[2];
76
77static int	nextone;	/* index of next buffer to use */
78static int	current;	/* index of buffer in use */
79				/* control flags for crlf conversions */
80int		newline = 0;	/* fillbuf: in middle of newline expansion */
81int		prevchar = -1;	/* putbuf: previous char (cr check) */
82
83struct tftphdr *
84w_init(void)
85{
86	return (rw_init(0));	/* write-behind */
87}
88
89struct tftphdr *
90r_init(void)
91{
92	return (rw_init(1));	/* read-ahead */
93}
94
95/*
96 * Init for either read-ahead or write-behind.
97 * Zero for write-behind, one for read-head.
98 */
99static struct tftphdr *
100rw_init(int x)
101{
102	newline = 0;			/* init crlf flag */
103	prevchar = -1;
104	bfs[0].counter = BF_ALLOC;	/* pass out the first buffer */
105	current = 0;
106	bfs[1].counter = BF_FREE;
107	nextone = x;			/* ahead or behind? */
108
109	return ((struct tftphdr *)bfs[0].buf);
110}
111
112/*
113 * Have emptied current buffer by sending to net and getting ack.
114 * Free it and return next buffer filled with data.
115 */
116int
117readit(FILE *file, struct tftphdr **dpp, int convert, int segment_size)
118{
119	struct bf	*b;
120
121	bfs[current].counter = BF_FREE;		/* free old one */
122	current = !current;			/* "incr" current */
123
124	b = &bfs[current];			/* look at new buffer */
125	if (b->counter == BF_FREE)		/* if it's empty */
126		read_ahead(file, convert, segment_size);	/* fill it */
127	/* assert(b->counter != BF_FREE); */	/* check */
128	*dpp = (struct tftphdr *)b->buf;	/* set caller's ptr */
129
130	return (b->counter);
131}
132
133/*
134 * Fill the input buffer, doing ascii conversions if requested.
135 * Conversions are lf -> cr, lf and cr -> cr, nul.
136 */
137void
138read_ahead(FILE *file, int convert, int segment_size)
139{
140	int		 i;
141	char		*p;
142	int		 c;
143	struct bf	*b;
144	struct tftphdr	*dp;
145
146	b = &bfs[nextone];			/* look at "next" buffer */
147	if (b->counter != BF_FREE)		/* nop if not free */
148		return;
149	nextone = !nextone;			/* "incr" next buffer ptr */
150
151	dp = (struct tftphdr *)b->buf;
152
153	if (convert == 0) {
154		b->counter = read(fileno(file), dp->th_data, segment_size);
155		return;
156	}
157
158	p = dp->th_data;
159	for (i = 0; i < segment_size; i++) {
160		if (newline) {
161			if (prevchar == '\n')
162				c = '\n';	/* lf to cr, lf */
163			else
164				c = '\0';	/* cr to cr, nul */
165			newline = 0;
166		} else {
167			c = getc(file);
168			if (c == EOF)
169				break;
170			if (c == '\n' || c == '\r') {
171				prevchar = c;
172				c = '\r';
173				newline = 1;
174			}
175		}
176	       *p++ = c;
177	}
178	b->counter = (int)(p - dp->th_data);
179}
180
181/*
182 * Update count associated with the buffer, get new buffer
183 * from the queue.  Calls write_behind only if next buffer not
184 * available.
185 */
186int
187writeit(FILE *file, struct tftphdr **dpp, int ct, int convert)
188{
189	bfs[current].counter = ct;		/* set size of data to write */
190	current = !current;			/* switch to other buffer */
191	if (bfs[current].counter != BF_FREE)	/* if not free */
192		/* flush it */
193		(void)write_behind(file, convert);
194	bfs[current].counter = BF_ALLOC;	/* mark as alloc'd */
195	*dpp =  (struct tftphdr *)bfs[current].buf;
196
197	return (ct);				/* this is a lie of course */
198}
199
200/*
201 * Output a buffer to a file, converting from netascii if requested.
202 * CR, NUL -> CR and CR, LF -> LF.
203 * Note spec is undefined if we get CR as last byte of file or a
204 * CR followed by anything else.  In this case we leave it alone.
205 */
206int
207write_behind(FILE *file, int convert)
208{
209	char		*buf;
210	int		 count;
211	int		 ct;
212	char		*p;
213	int		 c; /* current character */
214	struct bf	*b;
215	struct tftphdr	*dp;
216
217	b = &bfs[nextone];
218	if (b->counter < -1)		/* anything to flush? */
219		return (0);		/* just nop if nothing to do */
220
221	count = b->counter;		/* remember byte count */
222	b->counter = BF_FREE;		/* reset flag */
223	dp = (struct tftphdr *)b->buf;
224	nextone = !nextone;		/* incr for next time */
225	buf = dp->th_data;
226
227	if (count <= 0)			/* nak logic? */
228		return (-1);
229
230	if (convert == 0)
231		return (write(fileno(file), buf, count));
232
233	p = buf;
234	ct = count;
235	while (ct--) {				/* loop over the buffer */
236		c = *p++;			/* pick up a character */
237		if (prevchar == '\r') {		/* if prev char was cr */
238			if (c == '\n')		/* if have cr,lf then just */
239				/* smash lf on top of the cr */
240				fseek(file, -1, SEEK_CUR);
241			else if (c == '\0')	/* if have cr,nul then */
242				goto skipit;	/* just skip over the putc */
243			/* FALLTHROUGH */
244		}
245		putc(c, file);
246skipit:
247		prevchar = c;
248	}
249
250	return (count);
251}
252
253/*
254 * When an error has occurred, it is possible that the two sides
255 * are out of synch.  Ie: that what I think is the other side's
256 * response to packet N is really their response to packet N-1.
257 *
258 * So, to try to prevent that, we flush all the input queued up
259 * for us on the network connection on our host.
260 *
261 * We return the number of packets we flushed (mostly for reporting
262 * when trace is active).
263 */
264int
265synchnet(int f)
266{
267	int			i, j = 0;
268	char			rbuf[SEGSIZE_MIN];
269	struct sockaddr_in	from;
270	socklen_t		fromlen;
271
272	for (;;) {
273		(void)ioctl(f, FIONREAD, &i);
274		if (i) {
275			j++;
276			fromlen = sizeof(from);
277			(void)recvfrom(f, rbuf, sizeof(rbuf), 0,
278			    (struct sockaddr *)&from, &fromlen);
279		} else
280			return (j);
281	}
282}
283