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