1/*
2 * Copyright (c) 1983 Regents of the University of California.
3 * 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#ifndef lint
35/*static char sccsid[] = "from: @(#)tftpsubs.c	5.6 (Berkeley) 2/28/91";*/
36/* static char rcsid[] = "$Id: tftpsubs.c,v 1.2 1993/08/01 18:07:04 mycroft Exp $"; */
37#endif /* not lint */
38
39/* Simple minded read-ahead/write-behind subroutines for tftp user and
40   server.  Written originally with multiple buffers in mind, but current
41   implementation has two buffer logic wired in.
42
43   Todo:  add some sort of final error check so when the write-buffer
44   is finally flushed, the caller can detect if the disk filled up
45   (or had an i/o error) and return a nak to the other side.
46
47			Jim Guyton 10/85
48 */
49
50#include <sys/types.h>
51#include <sys/socket.h>
52#include <sys/ioctl.h>
53#include <netinet/in.h>
54#include <unistd.h>
55#include <stdio.h>
56
57#include "tftp.h"
58
59#define PKTSIZE SEGSIZE+4       /* should be moved to tftp.h */
60
61struct bf {
62	int counter;            /* size of data in buffer, or flag */
63	char buf[PKTSIZE];      /* room for data packet */
64} bfs[2];
65
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 int nextone;     /* index of next buffer to use */
72static int current;     /* index of buffer in use */
73
74			/* control flags for crlf conversions */
75int newline = 0;        /* fillbuf: in middle of newline expansion */
76int prevchar = -1;      /* putbuf: previous char (cr check) */
77
78struct tftphdr *rw_init(int);
79
80struct tftphdr *w_init() { return rw_init(0); }         /* write-behind */
81struct tftphdr *r_init() { return rw_init(1); }         /* read-ahead */
82
83/* init for either read-ahead or write-behind */
84/* x is zero for write-behind, one for read-head */
85struct tftphdr *rw_init(int x)
86{
87	newline = 0;            /* init crlf flag */
88	prevchar = -1;
89	bfs[0].counter =  BF_ALLOC;     /* pass out the first buffer */
90	current = 0;
91	bfs[1].counter = BF_FREE;
92	nextone = x;                    /* ahead or behind? */
93	return (struct tftphdr *)bfs[0].buf;
94}
95
96
97/* Have emptied current buffer by sending to net and getting ack.
98   Free it and return next buffer filled with data.
99 */
100int readit(FILE * file, struct tftphdr **dpp, int convert)
101{
102	struct bf *b;
103
104	bfs[current].counter = BF_FREE; /* free old one */
105	current = !current;             /* "incr" current */
106
107	b = &bfs[current];              /* look at new buffer */
108	if (b->counter == BF_FREE)      /* if it's empty */
109		read_ahead(file, convert);      /* fill it */
110#if 0
111	assert(b->counter != BF_FREE);  /* check */
112#endif
113	*dpp = (struct tftphdr *)b->buf;        /* set caller's ptr */
114	return b->counter;
115}
116
117/*
118 * fill the input buffer, doing ascii conversions if requested
119 * conversions are  lf -> cr,lf  and cr -> cr, nul
120 */
121void read_ahead(FILE *file, int convert)
122{
123	register int i;
124	register char *p;
125	register int c;
126	struct bf *b;
127	struct tftphdr *dp;
128
129	b = &bfs[nextone];              /* look at "next" buffer */
130	if (b->counter != BF_FREE)      /* nop if not free */
131		return;
132	nextone = !nextone;             /* "incr" next buffer ptr */
133
134	dp = (struct tftphdr *)b->buf;
135
136	if (convert == 0) {
137		b->counter = read(fileno(file), dp->th_data, SEGSIZE);
138		return;
139	}
140
141	p = dp->th_data;
142	for (i = 0 ; i < SEGSIZE; i++) {
143		if (newline) {
144			if (prevchar == '\n')
145				c = '\n';       /* lf to cr,lf */
146			else    c = '\0';       /* cr to cr,nul */
147			newline = 0;
148		}
149		else {
150			c = getc(file);
151			if (c == EOF) break;
152			if (c == '\n' || c == '\r') {
153				prevchar = c;
154				c = '\r';
155				newline = 1;
156			}
157		}
158	       *p++ = c;
159	}
160	b->counter = (int)(p - dp->th_data);
161}
162
163/* Update count associated with the buffer, get new buffer
164   from the queue.  Calls write_behind only if next buffer not
165   available.
166 */
167int writeit(FILE *file, struct tftphdr **dpp, int ct, int convert)
168{
169	bfs[current].counter = ct;      /* set size of data to write */
170	current = !current;             /* switch to other buffer */
171	if (bfs[current].counter != BF_FREE)     /* if not free */
172		write_behind(file, convert);     /* flush it */
173	bfs[current].counter = BF_ALLOC;        /* mark as alloc'd */
174	*dpp =  (struct tftphdr *)bfs[current].buf;
175	return ct;                      /* this is a lie of course */
176}
177
178/*
179 * Output a buffer to a file, converting from netascii if requested.
180 * CR,NUL -> CR  and CR,LF => LF.
181 * Note spec is undefined if we get CR as last byte of file or a
182 * CR followed by anything else.  In this case we leave it alone.
183 */
184int write_behind(FILE *file, int convert)
185{
186	char *buf;
187	int count;
188	register int ct;
189	register char *p;
190	register int c;                 /* current character */
191	struct bf *b;
192	struct tftphdr *dp;
193
194	b = &bfs[nextone];
195	if (b->counter < -1)            /* anything to flush? */
196		return 0;               /* just nop if nothing to do */
197
198	count = b->counter;             /* remember byte count */
199	b->counter = BF_FREE;           /* reset flag */
200	dp = (struct tftphdr *)b->buf;
201	nextone = !nextone;             /* incr for next time */
202	buf = dp->th_data;
203
204	if (count <= 0) return -1;      /* nak logic? */
205
206	if (convert == 0)
207		return write(fileno(file), buf, count);
208
209	p = buf;
210	ct = count;
211	while (ct--) {                  /* loop over the buffer */
212	    c = *p++;                   /* pick up a character */
213	    if (prevchar == '\r') {     /* if prev char was cr */
214		if (c == '\n')          /* if have cr,lf then just */
215		   fseek(file, -1, 1);  /* smash lf on top of the cr */
216		else
217		   if (c == '\0')       /* if have cr,nul then */
218			goto skipit;    /* just skip over the putc */
219		/* else just fall through and allow it */
220	    }
221	    putc(c, file);
222skipit:
223	    prevchar = c;
224	}
225	return count;
226}
227
228
229/* When an error has occurred, it is possible that the two sides
230 * are out of synch.  Ie: that what I think is the other side's
231 * response to packet N is really their response to packet N-1.
232 *
233 * So, to try to prevent that, we flush all the input queued up
234 * for us on the network connection on our host.
235 *
236 * We return the number of packets we flushed (mostly for reporting
237 * when trace is active).
238 */
239
240int synchnet(int f)
241{
242	int j = 0;
243	char dummy;
244
245	while (1) {
246		if (recv(f, &dummy, 1, MSG_DONTWAIT) < 0)
247			break;
248		j++;
249	}
250	return j;
251}
252