xref: /netbsd/usr.bin/tftp/tftpsubs.c (revision 6550d01e)
1 /*	$NetBSD: tftpsubs.c,v 1.11 2009/01/18 07:11:45 lukem 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
35 static char sccsid[] = "@(#)tftpsubs.c	8.1 (Berkeley) 6/6/93";
36 #else
37 __RCSID("$NetBSD: tftpsubs.c,v 1.11 2009/01/18 07:11:45 lukem 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 
63 struct 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 
73 static int nextone;		/* index of next buffer to use */
74 static int current;		/* index of buffer in use */
75 
76 				/* control flags for crlf conversions */
77 int newline = 0;		/* fillbuf: in middle of newline expansion */
78 int prevchar = -1;		/* putbuf: previous char (cr check) */
79 
80 static struct tftphdr *rw_init __P((int));
81 
82 struct tftphdr *
83 w_init()		/* write-behind */
84 {
85 	return rw_init(0);
86 }
87 
88 struct tftphdr *
89 r_init()		/* read-ahead */
90 {
91 	return rw_init(1);
92 }
93 
94 static struct tftphdr *
95 rw_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 *)(void *)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  */
110 int
111 readit(file, dpp, amt, convert)
112 	FILE *file;                     /* file opened for read */
113 	struct tftphdr **dpp;
114 	size_t 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 *)(void *)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  */
134 void
135 read_ahead(file, amt, convert)
136 	FILE *file;                     /* file opened for read */
137 	size_t amt;			/* number of bytes to read */
138 	int convert;                    /* if true, convert to ascii */
139 {
140 	size_t 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 *)(void *)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  */
184 int
185 writeit(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 		if (write_behind(file, convert) == -1) /* flush it */
194 			return -1;
195 	bfs[current].counter = BF_ALLOC;        /* mark as alloc'd */
196 	*dpp =  (struct tftphdr *)(void *)bfs[current].buf;
197 	return ct;                      /* this is a lie of course */
198 }
199 
200 /*
201  * Output a buffer to a file, converting from netascii if requested.
202  * CR,NUL -> CR  and CR,LF => LF.
203  * Note spec is undefined if we get CR as last byte of file or a
204  * CR followed by anything else.  In this case we leave it alone.
205  */
206 int
207 write_behind(file, convert)
208 	FILE *file;
209 	int convert;
210 {
211 	char *buf;
212 	int count;
213 	int ct;
214 	char *p;
215 	int c;				/* current character */
216 	struct bf *b;
217 	struct tftphdr *dp;
218 
219 	b = &bfs[nextone];
220 	if (b->counter < -1)            /* anything to flush? */
221 		return 0;               /* just nop if nothing to do */
222 
223 	count = b->counter;             /* remember byte count */
224 	b->counter = BF_FREE;           /* reset flag */
225 	dp = (struct tftphdr *)(void *)b->buf;
226 	nextone = !nextone;             /* incr for next time */
227 	buf = dp->th_data;
228 
229 	if (count <= 0) return -1;      /* nak logic? */
230 
231 	if (convert == 0)
232 		return write(fileno(file), buf, (size_t)count);
233 
234 	p = buf;
235 	ct = count;
236 	while (ct--) {                  /* loop over the buffer */
237 	    c = *p++;                   /* pick up a character */
238 	    if (prevchar == '\r') {     /* if prev char was cr */
239 		if (c == '\n')          /* if have cr,lf then just */
240 		   (void)fseeko(file, (off_t)-1, 1);  /* smash lf on top of the cr */
241 		else
242 		   if (c == '\0')       /* if have cr,nul then */
243 			goto skipit;    /* just skip over the putc */
244 		/* else just fall through and allow it */
245 	    }
246 	    if (putc(c, file) == EOF)
247 		return -1;
248 skipit:
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 
266 int
267 /*ARGSUSED*/
268 synchnet(f, bsize)
269 	int	f;		/* socket to flush */
270 	size_t	bsize;		/* size of buffer to sync */
271 {
272 	int i, j = 0;
273 	char rbuf[PKTSIZE];
274 	struct sockaddr_storage from;
275 	socklen_t fromlen;
276 
277 	for (;;) {
278 		(void) ioctl(f, FIONREAD, &i);
279 		if (i) {
280 			j++;
281 			fromlen = sizeof from;
282 			(void) recvfrom(f, rbuf, sizeof (rbuf), 0,
283 				(struct sockaddr *)(void *)&from, &fromlen);
284 		} else {
285 			return(j);
286 		}
287 	}
288 }
289