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