xref: /freebsd-13-stable/libexec/tftpd/tftp-utils.c (revision 3d497e17ebd33fe0f58d773e35ab994d750258d6)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause
3  *
4  * Copyright (C) 2008 Edwin Groothuis. All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY AUTHOR AND CONTRIBUTORS ``AS IS'' AND
16  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18  * ARE DISCLAIMED.  IN NO EVENT SHALL AUTHOR OR CONTRIBUTORS BE LIABLE
19  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
21  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
25  * SUCH DAMAGE.
26  */
27 
28 #include <sys/cdefs.h>
29 #include <sys/socket.h>
30 #include <sys/stat.h>
31 
32 #include <netinet/in.h>
33 #include <arpa/tftp.h>
34 
35 #include <stdarg.h>
36 #include <stdio.h>
37 #include <stdlib.h>
38 #include <string.h>
39 #include <syslog.h>
40 
41 #include "tftp-utils.h"
42 #include "tftp-io.h"
43 
44 /*
45  * Default values, can be changed later via the TFTP Options
46  */
47 int		timeoutpacket = TIMEOUT;
48 int		timeoutnetwork = MAX_TIMEOUTS * TIMEOUT;
49 int		maxtimeouts = MAX_TIMEOUTS;
50 uint16_t	segsize = SEGSIZE;
51 uint16_t	pktsize = SEGSIZE + 4;
52 uint16_t	windowsize = WINDOWSIZE;
53 
54 int	acting_as_client;
55 
56 
57 /*
58  * Set timeout values for packet reception. The idea is that you
59  * get 'maxtimeouts' of 5 seconds between 'timeoutpacket' (i.e. the
60  * first timeout) to 'timeoutnetwork' (i.e. the last timeout)
61  */
62 int
settimeouts(int _timeoutpacket,int _timeoutnetwork,int _maxtimeouts __unused)63 settimeouts(int _timeoutpacket, int _timeoutnetwork, int _maxtimeouts __unused)
64 {
65 	int i;
66 
67 	/* We cannot do impossible things */
68 	if (_timeoutpacket >= _timeoutnetwork)
69 		return (0);
70 
71 	maxtimeouts = 0;
72 	i = _timeoutpacket;
73 	while (i < _timeoutnetwork || maxtimeouts < MIN_TIMEOUTS) {
74 		maxtimeouts++;
75 		i += 5;
76 	}
77 
78 	timeoutpacket = _timeoutpacket;
79 	timeoutnetwork = i;
80 	return (1);
81 }
82 
83 /* translate IPv4 mapped IPv6 address to IPv4 address */
84 void
unmappedaddr(struct sockaddr_in6 * sin6)85 unmappedaddr(struct sockaddr_in6 *sin6)
86 {
87 	struct sockaddr_in *sin4;
88 	u_int32_t addr;
89 	int port;
90 
91 	if (sin6->sin6_family != AF_INET6 ||
92 	    !IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr))
93 		return;
94 	sin4 = (struct sockaddr_in *)sin6;
95 	memcpy(&addr, &sin6->sin6_addr.s6_addr[12], sizeof(addr));
96 	port = sin6->sin6_port;
97 	memset(sin4, 0, sizeof(struct sockaddr_in));
98 	sin4->sin_addr.s_addr = addr;
99 	sin4->sin_port = port;
100 	sin4->sin_family = AF_INET;
101 	sin4->sin_len = sizeof(struct sockaddr_in);
102 }
103 
104 /* Get a field from a \0 separated string */
105 ssize_t
get_field(int peer,char * buffer,ssize_t size)106 get_field(int peer, char *buffer, ssize_t size)
107 {
108 	char *cp = buffer;
109 
110 	while (cp < buffer + size) {
111 		if (*cp == '\0') break;
112 		cp++;
113 	}
114 	if (*cp != '\0') {
115 		tftp_log(LOG_ERR, "Bad option - no trailing \\0 found");
116 		send_error(peer, EBADOP);
117 		exit(1);
118 	}
119 	return (cp - buffer + 1);
120 }
121 
122 /*
123  * Logging functions
124  */
125 static int _tftp_logtostdout = 1;
126 
127 void
tftp_openlog(const char * ident,int logopt,int facility)128 tftp_openlog(const char *ident, int logopt, int facility)
129 {
130 
131 	_tftp_logtostdout = (ident == NULL);
132 	if (_tftp_logtostdout == 0)
133 		openlog(ident, logopt, facility);
134 }
135 
136 void
tftp_closelog(void)137 tftp_closelog(void)
138 {
139 
140 	if (_tftp_logtostdout == 0)
141 		closelog();
142 }
143 
144 void
tftp_log(int priority,const char * message,...)145 tftp_log(int priority, const char *message, ...)
146 {
147 	va_list ap;
148 	char *s;
149 
150 	va_start(ap, message);
151 	if (_tftp_logtostdout == 0) {
152 		vasprintf(&s, message, ap);
153 		syslog(priority, "%s", s);
154 	} else {
155 		vprintf(message, ap);
156 		printf("\n");
157 	}
158 	va_end(ap);
159 }
160 
161 /*
162  * Packet types
163  */
164 struct packettypes packettypes[] = {
165 	{ RRQ,		"RRQ"	},
166 	{ WRQ,		"WRQ"	},
167 	{ DATA,		"DATA"	},
168 	{ ACK,		"ACK"	},
169 	{ ERROR,	"ERROR"	},
170 	{ OACK,		"OACK"	},
171 	{ 0,		NULL	},
172 };
173 
174 const char *
packettype(int type)175 packettype(int type)
176 {
177 	static char failed[100];
178 	int i = 0;
179 
180 	while (packettypes[i].name != NULL) {
181 		if (packettypes[i].value == type)
182 			break;
183 		i++;
184 	}
185 	if (packettypes[i].name != NULL)
186 		return packettypes[i].name;
187 	sprintf(failed, "unknown (type: %d)", type);
188 	return (failed);
189 }
190 
191 /*
192  * Debugs
193  */
194 int	debug = DEBUG_NONE;
195 struct debugs debugs[] = {
196 	{ DEBUG_PACKETS,	"packet",	"Packet debugging"	},
197 	{ DEBUG_SIMPLE,		"simple",	"Simple debugging"	},
198 	{ DEBUG_OPTIONS,	"options",	"Options debugging"	},
199 	{ DEBUG_ACCESS,		"access",	"TCPd access debugging"	},
200 	{ DEBUG_NONE,		NULL,		"No debugging"		},
201 };
202 int	packetdroppercentage = 0;
203 
204 int
debug_find(char * s)205 debug_find(char *s)
206 {
207 	int i = 0;
208 
209 	while (debugs[i].name != NULL) {
210 		if (strcasecmp(debugs[i].name, s) == 0)
211 			break;
212 		i++;
213 	}
214 	return (debugs[i].value);
215 }
216 
217 int
debug_finds(char * s)218 debug_finds(char *s)
219 {
220 	int i = 0;
221 	char *ps = s;
222 
223 	while (s != NULL) {
224 		ps = strchr(s, ' ');
225 		if (ps != NULL)
226 			*ps = '\0';
227 		i += debug_find(s);
228 		if (ps != NULL)
229 			*ps = ' ';
230 		s = ps;
231 	}
232 	return (i);
233 }
234 
235 const char *
debug_show(int d)236 debug_show(int d)
237 {
238 	static char s[100];
239 	size_t space = sizeof(s);
240 	int i = 0;
241 
242 	s[0] = '\0';
243 	while (debugs[i].name != NULL) {
244 		if (d&debugs[i].value) {
245 			if (s[0] != '\0')
246 				strlcat(s, " ", space);
247 			strlcat(s, debugs[i].name, space);
248 		}
249 		i++;
250 	}
251 	if (s[0] != '\0')
252 		return (s);
253 	return ("none");
254 }
255 
256 /*
257  * RP_
258  */
259 struct rp_errors rp_errors[] = {
260 	{ RP_TIMEOUT,		"Network timeout" },
261 	{ RP_TOOSMALL,		"Not enough data bytes" },
262 	{ RP_WRONGSOURCE,	"Invalid IP address of UDP port" },
263 	{ RP_ERROR,		"Error packet" },
264 	{ RP_RECVFROM,		"recvfrom() complained" },
265 	{ RP_TOOBIG,		"Too many data bytes" },
266 	{ RP_NONE,		NULL }
267 };
268 
269 char *
rp_strerror(int error)270 rp_strerror(int error)
271 {
272 	static char s[100];
273 	size_t space = sizeof(s);
274 	int i = 0;
275 
276 	while (rp_errors[i].desc != NULL) {
277 		if (rp_errors[i].error == error) {
278 			strlcpy(s, rp_errors[i].desc, space);
279 			space -= strlen(rp_errors[i].desc);
280 		}
281 		i++;
282 	}
283 	if (s[0] == '\0')
284 		sprintf(s, "unknown (error=%d)", error);
285 	return (s);
286 }
287 
288 /*
289  * Performance figures
290  */
291 
292 void
stats_init(struct tftp_stats * ts)293 stats_init(struct tftp_stats *ts)
294 {
295 
296 	ts->amount = 0;
297 	ts->rollovers = 0;
298 	ts->retries = 0;
299 	ts->blocks = 0;
300 	ts->amount = 0;
301 	gettimeofday(&(ts->tstart), NULL);
302 }
303 
304 void
printstats(const char * direction,int verbose,struct tftp_stats * ts)305 printstats(const char *direction, int verbose, struct tftp_stats *ts)
306 {
307 	double delta;	/* compute delta in 1/10's second units */
308 
309 	delta = ((ts->tstop.tv_sec*10.)+(ts->tstop.tv_usec/100000)) -
310 		((ts->tstart.tv_sec*10.)+(ts->tstart.tv_usec/100000));
311 	delta = delta/10.;      /* back to seconds */
312 
313 	printf("%s %zu bytes during %.1f seconds in %u blocks",
314 	    direction, ts->amount, delta, ts->blocks);
315 
316 	if (ts->rollovers != 0)
317 		printf(" with %d rollover%s",
318 		    ts->rollovers, ts->rollovers != 1 ? "s" : "");
319 
320 	if (verbose)
321 		printf(" [%.0f bits/sec]", (ts->amount*8.)/delta);
322 	putchar('\n');
323 }
324