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