Merge branch 'vendor/ZLIB'
[dragonfly.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  * 4. Neither the name of the University nor the names of its contributors
14  *    may be used to endorse or promote products derived from this software
15  *    without specific prior written permission.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  *
29  * @(#)tftpsubs.c       8.1 (Berkeley) 6/6/93
30  * $FreeBSD: src/usr.bin/tftp/tftpsubs.c,v 1.3.2.1 2002/04/26 17:22:43 ume Exp $
31  * $DragonFly: src/usr.bin/tftp/tftpsubs.c,v 1.4 2008/10/16 01:52:33 swildner Exp $
32  */
33
34 /* Simple minded read-ahead/write-behind subroutines for tftp user and
35    server.  Written originally with multiple buffers in mind, but current
36    implementation has two buffer logic wired in.
37
38    Todo:  add some sort of final error check so when the write-buffer
39    is finally flushed, the caller can detect if the disk filled up
40    (or had an i/o error) and return a nak to the other side.
41
42                         Jim Guyton 10/85
43  */
44
45 #include <sys/types.h>
46 #include <sys/socket.h>
47 #include <sys/ioctl.h>
48 #include <netinet/in.h>
49 #include <arpa/tftp.h>
50
51 #include <stdio.h>
52 #include <unistd.h>
53
54 #include "tftpsubs.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 static struct tftphdr *rw_init(int);
76
77 struct tftphdr *w_init(void) { return rw_init(0); }         /* write-behind */
78 struct tftphdr *r_init(void) { return rw_init(1); }         /* read-ahead */
79
80 static struct tftphdr *
81 rw_init(int x           /* zero for write-behind, one for read-head */
82         )                       /* init for either read-ahead or write-behind */
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 int
98 readit(FILE *file, /* file opened for read */
99        struct tftphdr **dpp,
100        int convert /* if true, convert to ascii */
101        )
102 {
103         struct bf *b;
104
105         bfs[current].counter = BF_FREE; /* free old one */
106         current = !current;             /* "incr" current */
107
108         b = &bfs[current];              /* look at new buffer */
109         if (b->counter == BF_FREE)      /* if it's empty */
110                 read_ahead(file, convert);      /* fill it */
111 /*      assert(b->counter != BF_FREE);*//* check */
112         *dpp = (struct tftphdr *)b->buf;        /* set caller's ptr */
113         return b->counter;
114 }
115
116 /*
117  * fill the input buffer, doing ascii conversions if requested
118  * conversions are  lf -> cr,lf  and cr -> cr, nul
119  */
120 void
121 read_ahead(FILE *file, int convert)
122 {
123         int i;
124         char *p;
125         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 int
168 writeit(FILE *file, struct tftphdr **dpp, int ct, int convert)
169 {
170         bfs[current].counter = ct;      /* set size of data to write */
171         current = !current;             /* switch to other buffer */
172         if (bfs[current].counter != BF_FREE)     /* if not free */
173                 (void)write_behind(file, convert); /* flush it */
174         bfs[current].counter = BF_ALLOC;        /* mark as alloc'd */
175         *dpp =  (struct tftphdr *)bfs[current].buf;
176         return ct;                      /* this is a lie of course */
177 }
178
179 /*
180  * Output a buffer to a file, converting from netascii if requested.
181  * CR,NUL -> CR  and CR,LF => LF.
182  * Note spec is undefined if we get CR as last byte of file or a
183  * CR followed by anything else.  In this case we leave it alone.
184  */
185 int
186 write_behind(FILE *file, int convert)
187 {
188         char *buf;
189         int count;
190         int ct;
191         char *p;
192         int c;                          /* current character */
193         struct bf *b;
194         struct tftphdr *dp;
195
196         b = &bfs[nextone];
197         if (b->counter < -1)            /* anything to flush? */
198                 return 0;               /* just nop if nothing to do */
199
200         count = b->counter;             /* remember byte count */
201         b->counter = BF_FREE;           /* reset flag */
202         dp = (struct tftphdr *)b->buf;
203         nextone = !nextone;             /* incr for next time */
204         buf = dp->th_data;
205
206         if (count <= 0) return -1;      /* nak logic? */
207
208         if (convert == 0)
209                 return write(fileno(file), buf, count);
210
211         p = buf;
212         ct = count;
213         while (ct--) {                  /* loop over the buffer */
214             c = *p++;                   /* pick up a character */
215             if (prevchar == '\r') {     /* if prev char was cr */
216                 if (c == '\n')          /* if have cr,lf then just */
217                    fseek(file, -1, 1);  /* smash lf on top of the cr */
218                 else
219                    if (c == '\0')       /* if have cr,nul then */
220                         goto skipit;    /* just skip over the putc */
221                 /* else just fall through and allow it */
222             }
223             putc(c, file);
224 skipit:
225             prevchar = c;
226         }
227         return count;
228 }
229
230
231 /* When an error has occurred, it is possible that the two sides
232  * are out of synch.  Ie: that what I think is the other side's
233  * response to packet N is really their response to packet N-1.
234  *
235  * So, to try to prevent that, we flush all the input queued up
236  * for us on the network connection on our host.
237  *
238  * We return the number of packets we flushed (mostly for reporting
239  * when trace is active).
240  */
241
242 int
243 synchnet(int f)
244 {
245         int i, j = 0;
246         char rbuf[PKTSIZE];
247         struct sockaddr_storage from;
248         int fromlen;
249
250         while (1) {
251                 (void) ioctl(f, FIONREAD, &i);
252                 if (i) {
253                         j++;
254                         fromlen = sizeof from;
255                         (void) recvfrom(f, rbuf, sizeof (rbuf), 0,
256                                 (struct sockaddr *)&from, &fromlen);
257                 } else {
258                         return(j);
259                 }
260         }
261 }