xref: /freebsd-14.2/libexec/tftpd/tftp-io.c (revision 626ee3ca)
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/types.h>
30 #include <sys/socket.h>
31 #include <sys/stat.h>
32 
33 #include <netinet/in.h>
34 #include <arpa/inet.h>
35 #include <arpa/tftp.h>
36 
37 #include <assert.h>
38 #include <errno.h>
39 #include <poll.h>
40 #include <stddef.h>
41 #include <stdio.h>
42 #include <stdlib.h>
43 #include <string.h>
44 #include <syslog.h>
45 #include <unistd.h>
46 
47 #include "tftp-file.h"
48 #include "tftp-io.h"
49 #include "tftp-utils.h"
50 #include "tftp-options.h"
51 
52 struct sockaddr_storage peer_sock;
53 struct sockaddr_storage me_sock;
54 
55 static int send_packet(int peer, uint16_t block, char *pkt, int size);
56 
57 static struct errmsg {
58 	int	e_code;
59 	const char	*e_msg;
60 } errmsgs[] = {
61 	{ EUNDEF,	"Undefined error code" },
62 	{ ENOTFOUND,	"File not found" },
63 	{ EACCESS,	"Access violation" },
64 	{ ENOSPACE,	"Disk full or allocation exceeded" },
65 	{ EBADOP,	"Illegal TFTP operation" },
66 	{ EBADID,	"Unknown transfer ID" },
67 	{ EEXISTS,	"File already exists" },
68 	{ ENOUSER,	"No such user" },
69 	{ EOPTNEG,	"Option negotiation" },
70 	{ -1,		NULL }
71 };
72 
73 #define DROPPACKET(s)							\
74 	if (packetdroppercentage != 0 &&				\
75 	    arc4random()%100 < packetdroppercentage) {			\
76 		tftp_log(LOG_DEBUG, "Artificial packet drop in %s", s);	\
77 		return;							\
78 	}
79 #define DROPPACKETn(s,n)						\
80 	if (packetdroppercentage != 0 &&				\
81 	    arc4random()%100 < packetdroppercentage) {			\
82 		tftp_log(LOG_DEBUG, "Artificial packet drop in %s", s);	\
83 		return (n);						\
84 	}
85 
86 const char *
errtomsg(int error)87 errtomsg(int error)
88 {
89 	static char ebuf[40];
90 	struct errmsg *pe;
91 
92 	if (error == 0)
93 		return ("success");
94 	for (pe = errmsgs; pe->e_code >= 0; pe++)
95 		if (pe->e_code == error)
96 			return (pe->e_msg);
97 	snprintf(ebuf, sizeof(ebuf), "error %d", error);
98 	return (ebuf);
99 }
100 
101 static int
send_packet(int peer,uint16_t block,char * pkt,int size)102 send_packet(int peer, uint16_t block, char *pkt, int size)
103 {
104 	int i;
105 	int t = 1;
106 
107 	for (i = 0; i < 12 ; i++) {
108 		DROPPACKETn("send_packet", 0);
109 
110 		if (sendto(peer, pkt, size, 0, (struct sockaddr *)&peer_sock,
111 		    peer_sock.ss_len) == size) {
112 			if (i)
113 				tftp_log(LOG_ERR,
114 				    "%s block %d, attempt %d successful",
115 		    		    packettype(ntohs(((struct tftphdr *)
116 				    (pkt))->th_opcode)), block, i);
117 			return (0);
118 		}
119 		tftp_log(LOG_ERR,
120 		    "%s block %d, attempt %d failed (Error %d: %s)",
121 		    packettype(ntohs(((struct tftphdr *)(pkt))->th_opcode)),
122 		    block, i, errno, strerror(errno));
123 		sleep(t);
124 		if (t < 32)
125 			t <<= 1;
126 	}
127 	tftp_log(LOG_ERR, "send_packet: %s", strerror(errno));
128 	return (1);
129 }
130 
131 /*
132  * Send an ERROR packet (error message).
133  * Error code passed in is one of the
134  * standard TFTP codes, or a UNIX errno
135  * offset by 100.
136  */
137 void
send_error(int peer,int error)138 send_error(int peer, int error)
139 {
140 	struct tftphdr *tp;
141 	int length;
142 	struct errmsg *pe;
143 	char buf[MAXPKTSIZE];
144 
145 	if (debug & DEBUG_PACKETS)
146 		tftp_log(LOG_DEBUG, "Sending ERROR %d", error);
147 
148 	DROPPACKET("send_error");
149 
150 	tp = (struct tftphdr *)buf;
151 	tp->th_opcode = htons((u_short)ERROR);
152 	tp->th_code = htons((u_short)error);
153 	for (pe = errmsgs; pe->e_code >= 0; pe++)
154 		if (pe->e_code == error)
155 			break;
156 	if (pe->e_code < 0) {
157 		pe->e_msg = strerror(error - 100);
158 		tp->th_code = EUNDEF;   /* set 'undef' errorcode */
159 	}
160 	snprintf(tp->th_msg, MAXPKTSIZE - 4, "%s%n", pe->e_msg, &length);
161 	length += 5; /* header and terminator */
162 
163 	if (debug & DEBUG_PACKETS)
164 		tftp_log(LOG_DEBUG, "Sending ERROR %d: %s", error, tp->th_msg);
165 
166 	if (sendto(peer, buf, length, 0,
167 		(struct sockaddr *)&peer_sock, peer_sock.ss_len) != length)
168 		tftp_log(LOG_ERR, "send_error: %s", strerror(errno));
169 }
170 
171 /*
172  * Send an WRQ packet (write request).
173  */
174 int
send_wrq(int peer,char * filename,char * mode)175 send_wrq(int peer, char *filename, char *mode)
176 {
177 	int n;
178 	struct tftphdr *tp;
179 	char *bp;
180 	char buf[MAXPKTSIZE];
181 	int size;
182 
183 	if (debug & DEBUG_PACKETS)
184 		tftp_log(LOG_DEBUG, "Sending WRQ: filename: '%s', mode '%s'",
185 			filename, mode
186 		);
187 
188 	DROPPACKETn("send_wrq", 0);
189 
190 	tp = (struct tftphdr *)buf;
191 	tp->th_opcode = htons((u_short)WRQ);
192 	size = offsetof(struct tftphdr, th_stuff);
193 
194 	bp = tp->th_stuff;
195 	strlcpy(bp, filename, sizeof(buf) - size);
196 	bp += strlen(filename);
197 	*bp = 0;
198 	bp++;
199 	size += strlen(filename) + 1;
200 
201 	strlcpy(bp, mode, sizeof(buf) - size);
202 	bp += strlen(mode);
203 	*bp = 0;
204 	bp++;
205 	size += strlen(mode) + 1;
206 
207 	if (options_rfc_enabled)
208 		size += make_options(peer, bp, sizeof(buf) - size);
209 
210 	n = sendto(peer, buf, size, 0,
211 	    (struct sockaddr *)&peer_sock, peer_sock.ss_len);
212 	if (n != size) {
213 		tftp_log(LOG_ERR, "send_wrq: %s", strerror(errno));
214 		return (1);
215 	}
216 	return (0);
217 }
218 
219 /*
220  * Send an RRQ packet (write request).
221  */
222 int
send_rrq(int peer,char * filename,char * mode)223 send_rrq(int peer, char *filename, char *mode)
224 {
225 	int n;
226 	struct tftphdr *tp;
227 	char *bp;
228 	char buf[MAXPKTSIZE];
229 	int size;
230 
231 	if (debug & DEBUG_PACKETS)
232 		tftp_log(LOG_DEBUG, "Sending RRQ: filename: '%s', mode '%s'",
233 			filename, mode
234 		);
235 
236 	DROPPACKETn("send_rrq", 0);
237 
238 	tp = (struct tftphdr *)buf;
239 	tp->th_opcode = htons((u_short)RRQ);
240 	size = offsetof(struct tftphdr, th_stuff);
241 
242 	bp = tp->th_stuff;
243 	strlcpy(bp, filename, sizeof(buf) - size);
244 	bp += strlen(filename);
245 	*bp = 0;
246 	bp++;
247 	size += strlen(filename) + 1;
248 
249 	strlcpy(bp, mode, sizeof(buf) - size);
250 	bp += strlen(mode);
251 	*bp = 0;
252 	bp++;
253 	size += strlen(mode) + 1;
254 
255 	if (options_rfc_enabled) {
256 		options_set_request(OPT_TSIZE, "0");
257 		size += make_options(peer, bp, sizeof(buf) - size);
258 	}
259 
260 	n = sendto(peer, buf, size, 0,
261 	    (struct sockaddr *)&peer_sock, peer_sock.ss_len);
262 	if (n != size) {
263 		tftp_log(LOG_ERR, "send_rrq: %d %s", n, strerror(errno));
264 		return (1);
265 	}
266 	return (0);
267 }
268 
269 /*
270  * Send an OACK packet (option acknowledgement).
271  */
272 int
send_oack(int peer)273 send_oack(int peer)
274 {
275 	struct tftphdr *tp;
276 	int size, i, n;
277 	char *bp;
278 	char buf[MAXPKTSIZE];
279 
280 	if (debug & DEBUG_PACKETS)
281 		tftp_log(LOG_DEBUG, "Sending OACK");
282 
283 	DROPPACKETn("send_oack", 0);
284 
285 	/*
286 	 * Send back an options acknowledgement (only the ones with
287 	 * a reply for)
288 	 */
289 	tp = (struct tftphdr *)buf;
290 	bp = buf + 2;
291 	size = sizeof(buf) - 2;
292 	tp->th_opcode = htons((u_short)OACK);
293 	for (i = 0; options[i].o_type != NULL; i++) {
294 		if (options[i].o_reply != NULL) {
295 			n = snprintf(bp, size, "%s%c%s", options[i].o_type,
296 				     0, options[i].o_reply);
297 			bp += n+1;
298 			size -= n+1;
299 			if (size < 0) {
300 				tftp_log(LOG_ERR, "oack: buffer overflow");
301 				exit(1);
302 			}
303 		}
304 	}
305 	size = bp - buf;
306 
307 	if (sendto(peer, buf, size, 0,
308 		(struct sockaddr *)&peer_sock, peer_sock.ss_len) != size) {
309 		tftp_log(LOG_INFO, "send_oack: %s", strerror(errno));
310 		return (1);
311 	}
312 
313 	return (0);
314 }
315 
316 /*
317  * Send an ACK packet (acknowledgement).
318  */
319 int
send_ack(int fp,uint16_t block)320 send_ack(int fp, uint16_t block)
321 {
322 	struct tftphdr *tp;
323 	int size;
324 	char buf[MAXPKTSIZE];
325 
326 	if (debug & DEBUG_PACKETS)
327 		tftp_log(LOG_DEBUG, "Sending ACK for block %d", block);
328 
329 	DROPPACKETn("send_ack", 0);
330 
331 	tp = (struct tftphdr *)buf;
332 	tp->th_opcode = htons((u_short)ACK);
333 	tp->th_block = htons((u_short)block);
334 	size = 4;
335 
336 	if (sendto(fp, buf, size, 0,
337 	    (struct sockaddr *)&peer_sock, peer_sock.ss_len) != size) {
338 		tftp_log(LOG_INFO, "send_ack: %s", strerror(errno));
339 		return (1);
340 	}
341 
342 	return (0);
343 }
344 
345 /*
346  * Send a DATA packet
347  */
348 int
send_data(int peer,uint16_t block,char * data,int size)349 send_data(int peer, uint16_t block, char *data, int size)
350 {
351 	char buf[MAXPKTSIZE];
352 	struct tftphdr *pkt;
353 	int n;
354 
355 	if (debug & DEBUG_PACKETS)
356 		tftp_log(LOG_DEBUG, "Sending DATA packet %d of %d bytes",
357 			block, size);
358 
359 	DROPPACKETn("send_data", 0);
360 
361 	pkt = (struct tftphdr *)buf;
362 
363 	pkt->th_opcode = htons((u_short)DATA);
364 	pkt->th_block = htons((u_short)block);
365 	memcpy(pkt->th_data, data, size);
366 
367 	n = send_packet(peer, block, (char *)pkt, size + 4);
368 	return (n);
369 }
370 
371 
372 /*
373  * Receive a packet
374  *
375  * If timeout is negative, no error will be logged on timeout.
376  */
377 int
receive_packet(int peer,char * data,int size,struct sockaddr_storage * from,int timeout)378 receive_packet(int peer, char *data, int size, struct sockaddr_storage *from,
379     int timeout)
380 {
381 	struct pollfd pfd;
382 	struct tftphdr *pkt;
383 	struct sockaddr_storage from_local;
384 	struct sockaddr_storage *pfrom;
385 	socklen_t fromlen;
386 	int n;
387 
388 	if (debug & DEBUG_PACKETS)
389 		tftp_log(LOG_DEBUG,
390 		    "Waiting %d seconds for packet", timeoutpacket);
391 
392 	pkt = (struct tftphdr *)data;
393 
394 	pfd.fd = peer;
395 	pfd.events = POLLIN;
396 	if (poll(&pfd, 1, 1000 * (timeout < 0 ? -timeout : timeout)) < 1) {
397 		if (timeout > 0)
398 			tftp_log(LOG_ERR, "receive_packet: timeout");
399 		return (RP_TIMEOUT);
400 	}
401 
402 	pfrom = (from == NULL) ? &from_local : from;
403 	fromlen = sizeof(*pfrom);
404 	n = recvfrom(peer, data, size, 0, (struct sockaddr *)pfrom, &fromlen);
405 
406 	DROPPACKETn("receive_packet", RP_TIMEOUT);
407 
408 	if (n < 0) {
409 		/* No idea what could have happened if it isn't a timeout */
410 		tftp_log(LOG_ERR, "receive_packet: %s", strerror(errno));
411 		return (RP_RECVFROM);
412 	}
413 	if (n < 4) {
414 		tftp_log(LOG_ERR,
415 		    "receive_packet: packet too small (%d bytes)", n);
416 		return (RP_TOOSMALL);
417 	}
418 
419 	pkt->th_opcode = ntohs((u_short)pkt->th_opcode);
420 	if (pkt->th_opcode == DATA ||
421 	    pkt->th_opcode == ACK)
422 		pkt->th_block = ntohs((u_short)pkt->th_block);
423 
424 	if (pkt->th_opcode == DATA && n > pktsize) {
425 		tftp_log(LOG_ERR, "receive_packet: packet too big");
426 		return (RP_TOOBIG);
427 	}
428 
429 	if (((struct sockaddr_in *)(pfrom))->sin_addr.s_addr !=
430 	    ((struct sockaddr_in *)(&peer_sock))->sin_addr.s_addr) {
431 		tftp_log(LOG_ERR,
432 			"receive_packet: received packet from wrong source");
433 		return (RP_WRONGSOURCE);
434 	}
435 
436 	if (pkt->th_opcode == ERROR) {
437 		tftp_log(pkt->th_code == EUNDEF ? LOG_DEBUG : LOG_ERR,
438 		    "Got ERROR packet: %s", pkt->th_msg);
439 		return (RP_ERROR);
440 	}
441 
442 	if (debug & DEBUG_PACKETS)
443 		tftp_log(LOG_DEBUG, "Received %d bytes in a %s packet",
444 			n, packettype(pkt->th_opcode));
445 
446 	return n - 4;
447 }
448