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