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
39__attribute__((__used__))
40static const char sccsid[] = "@(#)tftpsubs.c	8.1 (Berkeley) 6/6/93";
41#endif
42
43/* Simple minded read-ahead/write-behind subroutines for tftp user and
44   server.  Written originally with multiple buffers in mind, but current
45   implementation has two buffer logic wired in.
46
47   Todo:  add some sort of final error check so when the write-buffer
48   is finally flushed, the caller can detect if the disk filled up
49   (or had an i/o error) and return a nak to the other side.
50
51			Jim Guyton 10/85
52 */
53
54#include <sys/types.h>
55#include <sys/socket.h>
56#include <sys/ioctl.h>
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#ifdef __APPLE__
66struct bf {
67	int counter;            /* size of data in buffer, or flag */
68	char buf[MAXPKTSIZE];   /* room for data packet */
69} bfs[2];
70#else
71#define PKTSIZE SEGSIZE+4       /* should be moved to tftp.h */
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#endif
78
79				/* Values for bf.counter  */
80#define BF_ALLOC -3             /* alloc'd but not yet filled */
81#define BF_FREE  -2             /* free */
82/* [-1 .. SEGSIZE] = size of data in the data buffer */
83
84static int nextone;		/* index of next buffer to use */
85static int current;		/* index of buffer in use */
86
87				/* control flags for crlf conversions */
88int newline = 0;		/* fillbuf: in middle of newline expansion */
89int prevchar = -1;		/* putbuf: previous char (cr check) */
90
91static struct tftphdr *rw_init(int);
92
93struct tftphdr *w_init(void) { return rw_init(0); }         /* write-behind */
94struct tftphdr *r_init(void) { return rw_init(1); }         /* read-ahead */
95
96static struct tftphdr *
97rw_init(x)			/* init for either read-ahead or write-behind */
98	int x;			/* zero for write-behind, one for read-head */
99{
100	newline = 0;		/* init crlf flag */
101	prevchar = -1;
102	bfs[0].counter =  BF_ALLOC;     /* pass out the first buffer */
103	current = 0;
104	bfs[1].counter = BF_FREE;
105	nextone = x;                    /* ahead or behind? */
106	return (struct tftphdr *)bfs[0].buf;
107}
108
109
110/* Have emptied current buffer by sending to net and getting ack.
111   Free it and return next buffer filled with data.
112 */
113int
114readit(file, dpp, amt, convert)
115	FILE *file;                     /* file opened for read */
116	struct tftphdr **dpp;
117	int amt;
118	int convert;                    /* if true, convert to ascii */
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, amt, convert);      /* fill it */
128/*      assert(b->counter != BF_FREE);*//* check */
129	*dpp = (struct tftphdr *)b->buf;        /* set caller's ptr */
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, amt, convert)
139	FILE *file;                     /* file opened for read */
140	int amt;			/* number of bytes to read */
141	int convert;                    /* if true, convert to ascii */
142{
143	int i;
144	char *p;
145	int c;
146	struct bf *b;
147	struct tftphdr *dp;
148
149	b = &bfs[nextone];              /* look at "next" buffer */
150	if (b->counter != BF_FREE)      /* nop if not free */
151		return;
152	nextone = !nextone;             /* "incr" next buffer ptr */
153
154	dp = (struct tftphdr *)b->buf;
155
156	if (convert == 0) {
157		b->counter = read(fileno(file), dp->th_data, amt);
158		return;
159	}
160
161	p = dp->th_data;
162	for (i = 0 ; i < amt; i++) {
163		if (newline) {
164			if (prevchar == '\n')
165				c = '\n';       /* lf to cr,lf */
166			else    c = '\0';       /* cr to cr,nul */
167			newline = 0;
168		}
169		else {
170			c = getc(file);
171			if (c == EOF) break;
172			if (c == '\n' || c == '\r') {
173				prevchar = c;
174				c = '\r';
175				newline = 1;
176			}
177		}
178	       *p++ = c;
179	}
180	b->counter = (int)(p - dp->th_data);
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, dpp, ct, convert)
189	FILE *file;
190	struct tftphdr **dpp;
191	int ct, convert;
192{
193	bfs[current].counter = ct;      /* set size of data to write */
194	current = !current;             /* switch to other buffer */
195	if (bfs[current].counter != BF_FREE)     /* if not free */
196		(void)write_behind(file, convert); /* flush it */
197	bfs[current].counter = BF_ALLOC;        /* mark as alloc'd */
198	*dpp =  (struct tftphdr *)bfs[current].buf;
199	return ct;                      /* this is a lie of course */
200}
201
202/*
203 * Output a buffer to a file, converting from netascii if requested.
204 * CR,NUL -> CR  and CR,LF => LF.
205 * Note spec is undefined if we get CR as last byte of file or a
206 * CR followed by anything else.  In this case we leave it alone.
207 */
208int
209write_behind(file, convert)
210	FILE *file;
211	int convert;
212{
213	char *buf;
214	int count;
215	int ct;
216	char *p;
217	int c;                 /* current character */
218	struct bf *b;
219	struct tftphdr *dp;
220
221	b = &bfs[nextone];
222	if (b->counter < -1)            /* anything to flush? */
223		return 0;               /* just nop if nothing to do */
224
225	count = b->counter;             /* remember byte count */
226	b->counter = BF_FREE;           /* reset flag */
227	dp = (struct tftphdr *)b->buf;
228	nextone = !nextone;             /* incr for next time */
229	buf = dp->th_data;
230
231	if (count <= 0) return -1;      /* nak logic? */
232
233	if (convert == 0)
234		return write(fileno(file), buf, count);
235
236	p = buf;
237	ct = count;
238	while (ct--) {                  /* loop over the buffer */
239	    c = *p++;                   /* pick up a character */
240	    if (prevchar == '\r') {     /* if prev char was cr */
241		if (c == '\n')          /* if have cr,lf then just */
242		   fseek(file, -1, 1);  /* smash lf on top of the cr */
243		else
244		   if (c == '\0')       /* if have cr,nul then */
245			goto skipit;    /* just skip over the putc */
246		/* else just fall through and allow it */
247	    }
248	    putc(c, file);
249skipit:
250	    prevchar = c;
251	}
252	return count;
253}
254
255
256/* When an error has occurred, it is possible that the two sides
257 * are out of synch.  Ie: that what I think is the other side's
258 * response to packet N is really their response to packet N-1.
259 *
260 * So, to try to prevent that, we flush all the input queued up
261 * for us on the network connection on our host.
262 *
263 * We return the number of packets we flushed (mostly for reporting
264 * when trace is active).
265 */
266
267int
268synchnet(f)
269	int	f;		/* socket to flush */
270{
271	int i, j = 0;
272	char rbuf[PKTSIZE];
273	struct sockaddr_storage from;
274	socklen_t fromlen;
275
276	while (1) {
277		(void) ioctl(f, FIONREAD, &i);
278		if (i) {
279			j++;
280			fromlen = sizeof from;
281			(void) recvfrom(f, rbuf, sizeof (rbuf), 0,
282				(struct sockaddr *)&from, &fromlen);
283		} else {
284			return(j);
285		}
286	}
287}
288