summaryrefslogtreecommitdiff
path: root/usr/src/cmd/cmd-inet/usr.bin/tftp/tftpsubs.c
blob: e24bd0c8baabd3ab93c20da058c2d8f4708eec53 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License, Version 1.0 only
 * (the "License").  You may not use this file except in compliance
 * with the License.
 *
 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
 * or http://www.opensolaris.org/os/licensing.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
 * If applicable, add the following below this CDDL HEADER, with the
 * fields enclosed by brackets "[]" replaced with your own identifying
 * information: Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 */
/*
 * Copyright 2003 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

/*	Copyright (c) 1983, 1984, 1985, 1986, 1987, 1988, 1989 AT&T	*/
/*	  All Rights Reserved  	*/

/*
 * University Copyright- Copyright (c) 1982, 1986, 1988
 * The Regents of the University of California
 * All Rights Reserved
 *
 * University Acknowledgment- Portions of this document are derived from
 * software developed by the University of California, Berkeley, and its
 * contributors.
 */

#pragma ident	"%Z%%M%	%I%	%E% SMI"

/*
 * Simple minded read-ahead/write-behind subroutines for tftp user and
 * server.  Written originally with multiple buffers in mind, but current
 * implementation has two buffer logic wired in.
 *
 * Todo:  add some sort of final error check so when the write-buffer
 * is finally flushed, the caller can detect if the disk filled up
 * (or had an i/o error) and return a nak to the other side.
 */

#include <sys/types.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <sys/filio.h>

#include <netinet/in.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include <errno.h>
#include <poll.h>
#include <string.h>

#include "tftpcommon.h"

struct errmsg errmsgs[] = {
	{ EUNDEF,	"Undefined error code" },
	{ ENOTFOUND,	"File not found" },
	{ EACCESS,	"Access violation" },
	{ ENOSPACE,	"Disk full or allocation exceeded" },
	{ EBADOP,	"Illegal TFTP operation" },
	{ EBADID,	"Unknown transfer ID" },
	{ EEXISTS,	"File already exists" },
	{ ENOUSER,	"No such user" },
	{ EOPTNEG,	"Option negotiation error" },
	{ -1,		NULL }
};

static struct bf {
	int	counter;	/* size of data in buffer, or flag */
	tftpbuf	buf;		/* room for data packet */
} bfs[2];

extern int blocksize;		/* Number of data bytes in a DATA packet */
				/* Values for bf.counter  */
#define	BF_ALLOC -3	/* alloc'd but not yet filled */
#define	BF_FREE  -2	/* free */
/* [-1 .. blocksize] = size of data in the data buffer */

static int nextone;	/* index of next buffer to use */
static int current;	/* index of buffer in use */

			/* control flags for crlf conversions */
static int newline = 0;	/* fillbuf: in middle of newline expansion */
static int prevchar = -1;	/* putbuf: previous char (cr check) */

static struct tftphdr *rw_init(int);

struct tftphdr *w_init() { return (rw_init(0)); }	/* write-behind */
struct tftphdr *r_init() { return (rw_init(1)); }	/* read-ahead */

/*
 * Init for either read-ahead or write-behind.
 * x is zero for write-behind, one for read-head.
 */
static struct tftphdr *
rw_init(int x)
{
	newline = 0;	/* init crlf flag */
	prevchar = -1;
	bfs[0].counter = BF_ALLOC;	/* pass out the first buffer */
	current = 0;
	bfs[1].counter = BF_FREE;
	nextone = x;	/* ahead or behind? */
	return (&bfs[0].buf.tb_hdr);
}


/*
 * Have emptied current buffer by sending to net and getting ack.
 * Free it and return next buffer filled with data.
 */
int
readit(FILE *file, struct tftphdr **dpp, int convert)
{
	struct bf *b;

	bfs[current].counter = BF_FREE; /* free old one */
	current = !current;	/* "incr" current */

	b = &bfs[current];	/* look at new buffer */
	if (b->counter == BF_FREE)	/* if it's empty */
		read_ahead(file, convert);	/* fill it */
	*dpp = &b->buf.tb_hdr;	/* set caller's ptr */
	return (b->counter);
}

/*
 * fill the input buffer, doing ascii conversions if requested
 * conversions are  lf -> cr,lf  and cr -> cr, nul
 */
void
read_ahead(FILE *file, int convert)
{
	int i;
	char *p;
	int c;
	struct bf *b;
	struct tftphdr *dp;

	b = &bfs[nextone];	/* look at "next" buffer */
	if (b->counter != BF_FREE)	/* nop if not free */
		return;
	nextone = !nextone;	/* "incr" next buffer ptr */

	dp = &b->buf.tb_hdr;

	if (!convert) {
		b->counter = fread(dp->th_data, sizeof (char), blocksize,
		    file);
		if (ferror(file))
			b->counter = -1;
		return;
	}

	p = dp->th_data;
	for (i = 0; i < blocksize; i++) {
		if (newline) {
			if (prevchar == '\n')
				c = '\n';	/* lf to cr,lf */
			else    c = '\0';	/* cr to cr,nul */
			newline = 0;
		} else {
			c = getc(file);
			if (c == EOF) break;
			if (c == '\n' || c == '\r') {
				prevchar = c;
				c = '\r';
				newline = 1;
			}
		}
		*p++ = c;
	}
	b->counter = (int)(p - dp->th_data);
}

/*
 * Update count associated with the buffer, get new buffer
 * from the queue.  Calls write_behind only if next buffer not
 * available.
 */
int
writeit(FILE *file, struct tftphdr **dpp, int ct, int convert)
{
	bfs[current].counter = ct;	/* set size of data to write */
	current = !current;		/* switch to other buffer */
	if (bfs[current].counter != BF_FREE)	/* if not free */
		if (write_behind(file, convert) < 0)	/* flush it */
			ct = -1;
	bfs[current].counter = BF_ALLOC;	/* mark as alloc'd */
	*dpp = &bfs[current].buf.tb_hdr;
	return (ct);	/* this is a lie of course */
}

/*
 * Output a buffer to a file, converting from netascii if requested.
 * CR,NUL -> CR  and CR,LF => LF.
 * Note spec is undefined if we get CR as last byte of file or a
 * CR followed by anything else.  In this case we leave it alone.
 */
int
write_behind(FILE *file, int convert)
{
	char *buf;
	int count;
	int ct;
	char *p;
	int c;	/* current character */
	struct bf *b;
	struct tftphdr *dp;

	b = &bfs[nextone];
	if (b->counter < -1)	/* anything to flush? */
		return (0);	/* just nop if nothing to do */

	count = b->counter;	/* remember byte count */
	b->counter = BF_FREE;	/* reset flag */
	dp = &b->buf.tb_hdr;
	nextone = !nextone;	/* incr for next time */
	buf = dp->th_data;

	if (count <= 0)
		return (0);	/* nak logic? */

	if (!convert) {
		size_t	left = count;

		while (left > 0) {
			size_t	written;

			written = fwrite(buf, sizeof (char), left, file);
			if (ferror(file)) {
				/* Retry if we were interrupted by a signal. */
				if (errno == EINTR)
					continue;
				return (-1);
			}
			if (written == 0)
				return (-1);

			left -= written;
			buf += written;
		}

		return (count);
	}

	p = buf;
	ct = count;
	while (ct--) {	/* loop over the buffer */
		c = *p++;	/* pick up a character */
		if (prevchar == '\r') {	/* if prev char was cr */
			if (c == '\n') { /* if have cr,lf then just */
				/* smash lf on top of the cr */
				if (fseek(file, -1, SEEK_CUR) < 0)
					return (-1);
			} else {
				if (c == '\0') {
					/*
					 * If we have cr,nul then
					 * just skip over the putc.
					 */
					prevchar = 0;
					continue;
				}
			}
			/* else just fall through and allow it */
		}
		if (putc(c, file) == EOF)
			return (-1);
		prevchar = c;
	}
	return (count);
}


/*
 * When an error has occurred, it is possible that the two sides
 * are out of synch.  Ie: that what I think is the other side's
 * response to packet N is really their response to packet N-1.
 *
 * So, to try to prevent that, we flush all the input queued up
 * for us on the network connection on our host.
 *
 * We return the number of packets we flushed (mostly for reporting
 * when trace is active) or -1 in case of an error.
 */

int
synchnet(int socket)
{
	struct pollfd	pfd;
	int 		packets;

	pfd.fd = socket;
	pfd.events = POLLRDNORM;
	for (packets = 0; ; packets++) {
		char			buf;
		struct sockaddr_in6	from;
		socklen_t		fromlen;

		if (poll(&pfd, 1, 0) <= 0)
			break;

		/*
		 * A one byte buffer is enough because recvfrom() will
		 * discard the remaining data of the packet.
		 */
		fromlen = sizeof (from);
		if (recvfrom(socket, &buf, sizeof (buf), 0,
		    (struct sockaddr *)&from, &fromlen) < 0)
			return (-1);
	}

	return (packets);
}

/*
 * Return a pointer to the next field in string s, or return NULL if no
 * terminating NUL is found for the current field before end.
 */
char *
next_field(const char *s, const char *end)
{
	if (s < end) {
		s = memchr(s, 0, end - s);
		if (s != NULL)
			return ((char *)s + 1);
	}
	return (NULL);
}

/*
 * Print to stream options in the format option_name=option_value
 */
void
print_options(FILE *stream, char *opts, int len)
{
	char *cp, *optname, *optval;
	char *endopts = opts + len;
	int first = 1;

	/*
	 * Ignore null padding, appended by broken TFTP clients to
	 * requests which don't include options.
	 */
	cp = opts;
	while ((cp < endopts) && (*cp == '\0'))
		cp++;
	if (cp == endopts)
		return;

	while (opts < endopts) {
		optname = opts;
		if ((optval = next_field(optname, endopts)) == NULL) {
			(void) putc('?', stream);
			return;
		}
		if (first)
			first = 0;
		else
			(void) putc(' ', stream);
		(void) fputs(optname, stream);
		if ((opts = next_field(optval, endopts)) == NULL) {
			(void) putc('?', stream);
			return;
		}
		(void) fprintf(stream, "=%s", optval);
	}
}

/*
 * Turn off the alarm timer and ensure any pending SIGALRM signal is ignored.
 */
void
cancel_alarm(void)
{
	(void) alarm(0);
	(void) signal(SIGALRM, SIG_IGN);
	(void) sigrelse(SIGALRM);
}