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: src/usr.bin/tftp/tftpsubs.c,v 1.6 2005/02/14 17:42:58 stefanf Exp $");
37
38#ifndef lint
39static const char sccsid[] = "@(#)tftpsubs.c	8.1 (Berkeley) 6/6/93";
40#endif
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#include <netinet/in.h>
57#include <arpa/tftp.h>
58
59#include <stdio.h>
60#include <unistd.h>
61
62#include "tftpsubs.h"
63
64#ifdef __APPLE__
65struct bf {
66	int counter;            /* size of data in buffer, or flag */
67	char buf[MAXPKTSIZE];   /* room for data packet */
68} bfs[2];
69#else
70#define PKTSIZE SEGSIZE+4       /* should be moved to tftp.h */
71
72struct bf {
73	int counter;            /* size of data in buffer, or flag */
74	char buf[PKTSIZE];      /* room for data packet */
75} bfs[2];
76#endif
77
78				/* Values for bf.counter  */
79#define BF_ALLOC -3             /* alloc'd but not yet filled */
80#define BF_FREE  -2             /* free */
81/* [-1 .. SEGSIZE] = size of data in the data buffer */
82
83static int nextone;		/* index of next buffer to use */
84static int current;		/* index of buffer in use */
85
86				/* control flags for crlf conversions */
87int newline = 0;		/* fillbuf: in middle of newline expansion */
88int prevchar = -1;		/* putbuf: previous char (cr check) */
89
90static struct tftphdr *rw_init(int);
91
92struct tftphdr *w_init(void) { return rw_init(0); }         /* write-behind */
93struct tftphdr *r_init(void) { return rw_init(1); }         /* read-ahead */
94
95static struct tftphdr *
96rw_init(x)			/* init for either read-ahead or write-behind */
97	int x;			/* zero for write-behind, one for read-head */
98{
99	newline = 0;		/* init crlf flag */
100	prevchar = -1;
101	bfs[0].counter =  BF_ALLOC;     /* pass out the first buffer */
102	current = 0;
103	bfs[1].counter = BF_FREE;
104	nextone = x;                    /* ahead or behind? */
105	return (struct tftphdr *)bfs[0].buf;
106}
107
108
109/* Have emptied current buffer by sending to net and getting ack.
110   Free it and return next buffer filled with data.
111 */
112int
113readit(file, dpp, amt, convert)
114	FILE *file;                     /* file opened for read */
115	struct tftphdr **dpp;
116	int amt;
117	int convert;                    /* if true, convert to ascii */
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, amt, convert);      /* fill it */
127/*      assert(b->counter != BF_FREE);*//* check */
128	*dpp = (struct tftphdr *)b->buf;        /* set caller's ptr */
129	return b->counter;
130}
131
132/*
133 * fill the input buffer, doing ascii conversions if requested
134 * conversions are  lf -> cr,lf  and cr -> cr, nul
135 */
136void
137read_ahead(file, amt, convert)
138	FILE *file;                     /* file opened for read */
139	int amt;			/* number of bytes to read */
140	int convert;                    /* if true, convert to ascii */
141{
142	int i;
143	char *p;
144	int c;
145	struct bf *b;
146	struct tftphdr *dp;
147
148	b = &bfs[nextone];              /* look at "next" buffer */
149	if (b->counter != BF_FREE)      /* nop if not free */
150		return;
151	nextone = !nextone;             /* "incr" next buffer ptr */
152
153	dp = (struct tftphdr *)b->buf;
154
155	if (convert == 0) {
156		b->counter = read(fileno(file), dp->th_data, amt);
157		return;
158	}
159
160	p = dp->th_data;
161	for (i = 0 ; i < amt; i++) {
162		if (newline) {
163			if (prevchar == '\n')
164				c = '\n';       /* lf to cr,lf */
165			else    c = '\0';       /* cr to cr,nul */
166			newline = 0;
167		}
168		else {
169			c = getc(file);
170			if (c == EOF) 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/* 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, dpp, ct, convert)
188	FILE *file;
189	struct tftphdr **dpp;
190	int ct, convert;
191{
192	bfs[current].counter = ct;      /* set size of data to write */
193	current = !current;             /* switch to other buffer */
194	if (bfs[current].counter != BF_FREE)     /* if not free */
195		(void)write_behind(file, convert); /* flush it */
196	bfs[current].counter = BF_ALLOC;        /* mark as alloc'd */
197	*dpp =  (struct tftphdr *)bfs[current].buf;
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, convert)
209	FILE *file;
210	int convert;
211{
212	char *buf;
213	int count;
214	int ct;
215	char *p;
216	int c;                 /* current character */
217	struct bf *b;
218	struct tftphdr *dp;
219
220	b = &bfs[nextone];
221	if (b->counter < -1)            /* anything to flush? */
222		return 0;               /* just nop if nothing to do */
223
224	count = b->counter;             /* remember byte count */
225	b->counter = BF_FREE;           /* reset flag */
226	dp = (struct tftphdr *)b->buf;
227	nextone = !nextone;             /* incr for next time */
228	buf = dp->th_data;
229
230	if (count <= 0) return -1;      /* nak logic? */
231
232	if (convert == 0)
233		return write(fileno(file), buf, count);
234
235	p = buf;
236	ct = count;
237	while (ct--) {                  /* loop over the buffer */
238	    c = *p++;                   /* pick up a character */
239	    if (prevchar == '\r') {     /* if prev char was cr */
240		if (c == '\n')          /* if have cr,lf then just */
241		   fseek(file, -1, 1);  /* smash lf on top of the cr */
242		else
243		   if (c == '\0')       /* if have cr,nul then */
244			goto skipit;    /* just skip over the putc */
245		/* else just fall through and allow it */
246	    }
247	    putc(c, file);
248skipit:
249	    prevchar = c;
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 */
265
266int
267synchnet(f)
268	int	f;		/* socket to flush */
269{
270	int i, j = 0;
271	char rbuf[PKTSIZE];
272	struct sockaddr_storage from;
273	socklen_t fromlen;
274
275	while (1) {
276		(void) ioctl(f, FIONREAD, &i);
277		if (i) {
278			j++;
279			fromlen = sizeof from;
280			(void) recvfrom(f, rbuf, sizeof (rbuf), 0,
281				(struct sockaddr *)&from, &fromlen);
282		} else {
283			return(j);
284		}
285	}
286}
287