Home | History | Annotate | Line # | Download | only in tftp
      1 /*	$NetBSD: tftpsubs.c,v 1.12 2011/09/17 15:15:46 christos 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.12 2011/09/17 15:15:46 christos 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 static 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 static int newline = 0;		/* fillbuf: in middle of newline expansion */
     78 static int prevchar = -1;	/* putbuf: previous char (cr check) */
     79 
     80 static struct tftphdr *rw_init(int);
     81 
     82 struct tftphdr *
     83 w_init(void)		/* write-behind */
     84 {
     85 	return rw_init(0);
     86 }
     87 
     88 struct tftphdr *
     89 r_init(void)		/* read-ahead */
     90 {
     91 	return rw_init(1);
     92 }
     93 
     94 static struct tftphdr *
     95 rw_init(int x)			/* init for either read-ahead or write-behind */
     96 				/* 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(
    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(
    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 *file, struct tftphdr **dpp, int ct, int convert)
    186 {
    187 	bfs[current].counter = ct;      /* set size of data to write */
    188 	current = !current;             /* switch to other buffer */
    189 	if (bfs[current].counter != BF_FREE)     /* if not free */
    190 		if (write_behind(file, convert) == -1) /* flush it */
    191 			return -1;
    192 	bfs[current].counter = BF_ALLOC;        /* mark as alloc'd */
    193 	*dpp =  (struct tftphdr *)(void *)bfs[current].buf;
    194 	return ct;                      /* this is a lie of course */
    195 }
    196 
    197 /*
    198  * Output a buffer to a file, converting from netascii if requested.
    199  * CR,NUL -> CR  and CR,LF => LF.
    200  * Note spec is undefined if we get CR as last byte of file or a
    201  * CR followed by anything else.  In this case we leave it alone.
    202  */
    203 int
    204 write_behind(FILE *file, int convert)
    205 {
    206 	char *buf;
    207 	int count;
    208 	int ct;
    209 	char *p;
    210 	int c;				/* current character */
    211 	struct bf *b;
    212 	struct tftphdr *dp;
    213 
    214 	b = &bfs[nextone];
    215 	if (b->counter < -1)            /* anything to flush? */
    216 		return 0;               /* just nop if nothing to do */
    217 
    218 	count = b->counter;             /* remember byte count */
    219 	b->counter = BF_FREE;           /* reset flag */
    220 	dp = (struct tftphdr *)(void *)b->buf;
    221 	nextone = !nextone;             /* incr for next time */
    222 	buf = dp->th_data;
    223 
    224 	if (count <= 0) return -1;      /* nak logic? */
    225 
    226 	if (convert == 0)
    227 		return write(fileno(file), buf, (size_t)count);
    228 
    229 	p = buf;
    230 	ct = count;
    231 	while (ct--) {                  /* loop over the buffer */
    232 	    c = *p++;                   /* pick up a character */
    233 	    if (prevchar == '\r') {     /* if prev char was cr */
    234 		if (c == '\n')          /* if have cr,lf then just */
    235 		   (void)fseeko(file, (off_t)-1, 1);  /* smash lf on top of the cr */
    236 		else
    237 		   if (c == '\0')       /* if have cr,nul then */
    238 			goto skipit;    /* just skip over the putc */
    239 		/* else just fall through and allow it */
    240 	    }
    241 	    if (putc(c, file) == EOF)
    242 		return -1;
    243 skipit:
    244 	    prevchar = c;
    245 	}
    246 	return count;
    247 }
    248 
    249 
    250 /* When an error has occurred, it is possible that the two sides
    251  * are out of synch.  Ie: that what I think is the other side's
    252  * response to packet N is really their response to packet N-1.
    253  *
    254  * So, to try to prevent that, we flush all the input queued up
    255  * for us on the network connection on our host.
    256  *
    257  * We return the number of packets we flushed (mostly for reporting
    258  * when trace is active).
    259  */
    260 
    261 int
    262 /*ARGSUSED*/
    263 synchnet(
    264     int	f,		/* socket to flush */
    265     size_t bsize)	/* size of buffer to sync */
    266 {
    267 	int i, j = 0;
    268 	char rbuf[PKTSIZE];
    269 	struct sockaddr_storage from;
    270 	socklen_t fromlen;
    271 
    272 	for (;;) {
    273 		(void) ioctl(f, FIONREAD, &i);
    274 		if (i) {
    275 			j++;
    276 			fromlen = sizeof from;
    277 			(void)recvfrom(f, rbuf, sizeof (rbuf), 0,
    278 			    (struct sockaddr *)(void *)&from, &fromlen);
    279 		} else {
    280 			return j;
    281 		}
    282 	}
    283 }
    284