xref: /freebsd/usr.bin/tftp/main.c (revision d8a0fe102c0cfdfcd5b818f850eff09d8536c9bc)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
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 #ifndef lint
33 static const char copyright[] =
34 "@(#) Copyright (c) 1983, 1993\n\
35 	The Regents of the University of California.  All rights reserved.\n";
36 #endif
37 
38 #if 0
39 #ifndef lint
40 static char sccsid[] = "@(#)main.c	8.1 (Berkeley) 6/6/93";
41 #endif
42 #endif
43 
44 #include <sys/cdefs.h>
45 __FBSDID("$FreeBSD$");
46 
47 /* Many bug fixes are from Jim Guyton <guyton@rand-unix> */
48 
49 /*
50  * TFTP User Program -- Command Interface.
51  */
52 #include <sys/param.h>
53 #include <sys/types.h>
54 #include <sys/socket.h>
55 #include <sys/sysctl.h>
56 #include <sys/file.h>
57 #include <sys/stat.h>
58 
59 #include <netinet/in.h>
60 #include <arpa/inet.h>
61 #include <arpa/tftp.h>
62 
63 #include <ctype.h>
64 #include <err.h>
65 #include <histedit.h>
66 #include <netdb.h>
67 #include <setjmp.h>
68 #include <signal.h>
69 #include <stdio.h>
70 #include <stdlib.h>
71 #include <string.h>
72 #include <unistd.h>
73 
74 #include "tftp-utils.h"
75 #include "tftp-io.h"
76 #include "tftp-options.h"
77 #include "tftp.h"
78 
79 #define	MAXLINE		(2 * MAXPATHLEN)
80 #define	TIMEOUT		5		/* secs between rexmt's */
81 
82 typedef struct	sockaddr_storage peeraddr;
83 static int	connected;
84 static char	mode[32];
85 static jmp_buf	toplevel;
86 volatile int	txrx_error;
87 static int	peer;
88 
89 #define	MAX_MARGV	20
90 static int	margc;
91 static char	*margv[MAX_MARGV];
92 
93 int		verbose;
94 static char	*port = NULL;
95 
96 static void	get(int, char **);
97 static void	help(int, char **);
98 static void	intr(int);
99 static void	modecmd(int, char **);
100 static void	put(int, char **);
101 static void	quit(int, char **);
102 static void	setascii(int, char **);
103 static void	setbinary(int, char **);
104 static void	setpeer0(char *, const char *);
105 static void	setpeer(int, char **);
106 static void	settimeoutpacket(int, char **);
107 static void	settimeoutnetwork(int, char **);
108 static void	setdebug(int, char **);
109 static void	setverbose(int, char **);
110 static void	showstatus(int, char **);
111 static void	setblocksize(int, char **);
112 static void	setblocksize2(int, char **);
113 static void	setoptions(int, char **);
114 static void	setrollover(int, char **);
115 static void	setpacketdrop(int, char **);
116 
117 static void command(void) __dead2;
118 static const char *command_prompt(void);
119 
120 static void urihandling(char *URI);
121 static void getusage(char *);
122 static void makeargv(char *line);
123 static void putusage(char *);
124 static void settftpmode(const char *);
125 
126 static char	*tail(char *);
127 static struct	cmd *getcmd(char *);
128 
129 #define HELPINDENT (sizeof("connect"))
130 
131 struct cmd {
132 	const char	*name;
133 	void	(*handler)(int, char **);
134 	const char	*help;
135 };
136 
137 static struct cmd cmdtab[] = {
138 	{ "connect",	setpeer,	"connect to remote tftp"	},
139 	{ "mode",	modecmd,	"set file transfer mode"	},
140 	{ "put",	put,		"send file"			},
141 	{ "get",	get,		"receive file"			},
142 	{ "quit",	quit,		"exit tftp"			},
143 	{ "verbose",	setverbose,	"toggle verbose mode"		},
144 	{ "status",	showstatus,	"show current status"		},
145 	{ "binary",     setbinary,	"set mode to octet"		},
146 	{ "ascii",      setascii,	"set mode to netascii"		},
147 	{ "rexmt",	settimeoutpacket,
148 	  "set per-packet retransmission timeout[-]" },
149 	{ "timeout",	settimeoutnetwork,
150 	  "set total retransmission timeout" },
151 	{ "trace",	setdebug,	"enable 'debug packet'[-]"	},
152 	{ "debug",	setdebug,	"enable verbose output"		},
153 	{ "blocksize",	setblocksize,	"set blocksize[*]"		},
154 	{ "blocksize2",	setblocksize2,	"set blocksize as a power of 2[**]" },
155 	{ "rollover",	setrollover,	"rollover after 64K packets[**]" },
156 	{ "options",	setoptions,
157 	  "enable or disable RFC2347 style options" },
158 	{ "help",	help,		"print help information"	},
159 	{ "packetdrop",	setpacketdrop,	"artificial packetloss feature"	},
160 	{ "?",		help,		"print help information"	},
161 	{ NULL,		NULL,		NULL				}
162 };
163 
164 static struct	modes {
165 	const char *m_name;
166 	const char *m_mode;
167 } modes[] = {
168 	{ "ascii",	"netascii" },
169 	{ "netascii",	"netascii" },
170 	{ "binary",	"octet" },
171 	{ "image",	"octet" },
172 	{ "octet",	"octet" },
173 	{ NULL,		NULL }
174 };
175 
176 int
177 main(int argc, char *argv[])
178 {
179 
180 	acting_as_client = 1;
181 	peer = -1;
182 	strcpy(mode, "netascii");
183 	signal(SIGINT, intr);
184 	if (argc > 1) {
185 		if (setjmp(toplevel) != 0)
186 			exit(txrx_error);
187 
188 		if (strncmp(argv[1], "tftp://", 7) == 0) {
189 			urihandling(argv[1]);
190 			exit(txrx_error);
191 		}
192 
193 		setpeer(argc, argv);
194 	}
195 	if (setjmp(toplevel) != 0)
196 		(void)putchar('\n');
197 
198 	init_options();
199 	command();
200 }
201 
202 /*
203  * RFC3617 handling of TFTP URIs:
204  *
205  *    tftpURI         = "tftp://" host "/" file [ mode ]
206  *    mode            = ";"  "mode=" ( "netascii" / "octet" )
207  *    file            = *( unreserved / escaped )
208  *    host            = <as specified by RFC 2732>
209  *    unreserved      = <as specified in RFC 2396>
210  *    escaped         = <as specified in RFC 2396>
211  *
212  * We are cheating a little bit by allowing any mode as specified in the
213  * modes table defined earlier on in this file and mapping it on the real
214  * mode.
215  */
216 static void
217 urihandling(char *URI)
218 {
219 	char	uri[ARG_MAX];
220 	char	*host = NULL;
221 	char	*path = NULL;
222 	char	*opts = NULL;
223 	const char *tmode = "octet";
224 	char	*s;
225 	char	line[MAXLINE];
226 	int	i;
227 
228 	strlcpy(uri, URI, ARG_MAX);
229 	host = uri + 7;
230 
231 	if ((s = strchr(host, '/')) == NULL) {
232 		fprintf(stderr,
233 		    "Invalid URI: Couldn't find / after hostname\n");
234 		exit(1);
235 	}
236 	*s = '\0';
237 	path = s + 1;
238 
239 	if ((s = strchr(path, ';')) != NULL) {
240 		*s = '\0';
241 		opts = s + 1;
242 
243 		if (strncmp(opts, "mode=", 5) == 0) {
244 			tmode = opts;
245 			tmode += 5;
246 
247 			for (i = 0; modes[i].m_name != NULL; i++) {
248 				if (strcmp(modes[i].m_name, tmode) == 0)
249 					break;
250 			}
251 			if (modes[i].m_name == NULL) {
252 				fprintf(stderr, "Invalid mode: '%s'\n", mode);
253 				exit(1);
254 			}
255 			settftpmode(modes[i].m_mode);
256 		}
257 	} else {
258 		settftpmode("octet");
259 	}
260 
261 	setpeer0(host, NULL);
262 
263 	sprintf(line, "get %s", path);
264 	makeargv(line);
265 	get(margc, margv);
266 }
267 
268 static char    hostname[MAXHOSTNAMELEN];
269 
270 static void
271 setpeer0(char *host, const char *lport)
272 {
273 	struct addrinfo hints, *res0, *res;
274 	int error;
275 	const char *cause = "unknown";
276 
277 	if (connected) {
278 		close(peer);
279 		peer = -1;
280 	}
281 	connected = 0;
282 
283 	memset(&hints, 0, sizeof(hints));
284 	hints.ai_family = PF_UNSPEC;
285 	hints.ai_socktype = SOCK_DGRAM;
286 	hints.ai_protocol = IPPROTO_UDP;
287 	hints.ai_flags = AI_CANONNAME;
288 	if (!lport)
289 		lport = "tftp";
290 	error = getaddrinfo(host, lport, &hints, &res0);
291 	if (error) {
292 		warnx("%s", gai_strerror(error));
293 		return;
294 	}
295 
296 	for (res = res0; res; res = res->ai_next) {
297 		if (res->ai_addrlen > sizeof(peeraddr))
298 			continue;
299 		peer = socket(res->ai_family, res->ai_socktype,
300 			res->ai_protocol);
301 		if (peer < 0) {
302 			cause = "socket";
303 			continue;
304 		}
305 
306 		memset(&peer_sock, 0, sizeof(peer_sock));
307 		peer_sock.ss_family = res->ai_family;
308 		peer_sock.ss_len = res->ai_addrlen;
309 		if (bind(peer, (struct sockaddr *)&peer_sock, peer_sock.ss_len) < 0) {
310 			cause = "bind";
311 			close(peer);
312 			peer = -1;
313 			continue;
314 		}
315 
316 		break;
317 	}
318 
319 	if (peer < 0)
320 		warn("%s", cause);
321 	else {
322 		/* res->ai_addr <= sizeof(peeraddr) is guaranteed */
323 		memcpy(&peer_sock, res->ai_addr, res->ai_addrlen);
324 		if (res->ai_canonname) {
325 			(void) strlcpy(hostname, res->ai_canonname,
326 				sizeof(hostname));
327 		} else
328 			(void) strlcpy(hostname, host, sizeof(hostname));
329 		connected = 1;
330 	}
331 
332 	freeaddrinfo(res0);
333 }
334 
335 static void
336 setpeer(int argc, char *argv[])
337 {
338 	char	line[MAXLINE];
339 
340 	if (argc < 2) {
341 		strcpy(line, "Connect ");
342 		printf("(to) ");
343 		fgets(&line[strlen(line)], sizeof line - strlen(line), stdin);
344 		makeargv(line);
345 		argc = margc;
346 		argv = margv;
347 	}
348 	if ((argc < 2) || (argc > 3)) {
349 		printf("usage: %s [host [port]]\n", argv[0]);
350 		return;
351 	}
352 	if (argc == 3) {
353 		port = argv[2];
354 		setpeer0(argv[1], argv[2]);
355 	} else
356 		setpeer0(argv[1], NULL);
357 }
358 
359 static void
360 modecmd(int argc, char *argv[])
361 {
362 	struct modes *p;
363 	const char *sep;
364 
365 	if (argc < 2) {
366 		printf("Using %s mode to transfer files.\n", mode);
367 		return;
368 	}
369 	if (argc == 2) {
370 		for (p = modes; p->m_name; p++)
371 			if (strcmp(argv[1], p->m_name) == 0)
372 				break;
373 		if (p->m_name) {
374 			settftpmode(p->m_mode);
375 			return;
376 		}
377 		printf("%s: unknown mode\n", argv[1]);
378 		/* drop through and print usage message */
379 	}
380 
381 	printf("usage: %s [", argv[0]);
382 	sep = " ";
383 	for (p = modes; p->m_name != NULL; p++) {
384 		printf("%s%s", sep, p->m_name);
385 		if (*sep == ' ')
386 			sep = " | ";
387 	}
388 	printf(" ]\n");
389 	return;
390 }
391 
392 static void
393 setbinary(int argc __unused, char *argv[] __unused)
394 {
395 
396 	settftpmode("octet");
397 }
398 
399 static void
400 setascii(int argc __unused, char *argv[] __unused)
401 {
402 
403 	settftpmode("netascii");
404 }
405 
406 static void
407 settftpmode(const char *newmode)
408 {
409 
410 	strcpy(mode, newmode);
411 	if (verbose)
412 		printf("mode set to %s\n", mode);
413 }
414 
415 
416 /*
417  * Send file(s).
418  */
419 static void
420 put(int argc, char *argv[])
421 {
422 	int	fd;
423 	int	n;
424 	char	*cp, *targ;
425 	char	line[MAXLINE];
426 	struct stat sb;
427 
428 	if (argc < 2) {
429 		strcpy(line, "send ");
430 		printf("(file) ");
431 		fgets(&line[strlen(line)], sizeof line - strlen(line), stdin);
432 		makeargv(line);
433 		argc = margc;
434 		argv = margv;
435 	}
436 	if (argc < 2) {
437 		putusage(argv[0]);
438 		return;
439 	}
440 	targ = argv[argc - 1];
441 	if (strrchr(argv[argc - 1], ':')) {
442 		char *lcp;
443 
444 		for (n = 1; n < argc - 1; n++)
445 			if (strchr(argv[n], ':')) {
446 				putusage(argv[0]);
447 				return;
448 			}
449 		lcp = argv[argc - 1];
450 		targ = strrchr(lcp, ':');
451 		*targ++ = 0;
452 		if (lcp[0] == '[' && lcp[strlen(lcp) - 1] == ']') {
453 			lcp[strlen(lcp) - 1] = '\0';
454 			lcp++;
455 		}
456 		setpeer0(lcp, NULL);
457 	}
458 	if (!connected) {
459 		printf("No target machine specified.\n");
460 		return;
461 	}
462 	if (argc < 4) {
463 		cp = argc == 2 ? tail(targ) : argv[1];
464 		fd = open(cp, O_RDONLY);
465 		if (fd < 0) {
466 			warn("%s", cp);
467 			return;
468 		}
469 
470 		stat(cp, &sb);
471 		asprintf(&options[OPT_TSIZE].o_request, "%ju", sb.st_size);
472 
473 		if (verbose)
474 			printf("putting %s to %s:%s [%s]\n",
475 			    cp, hostname, targ, mode);
476 		xmitfile(peer, port, fd, targ, mode);
477 		return;
478 	}
479 				/* this assumes the target is a directory */
480 				/* on a remote unix system.  hmmmm.  */
481 	cp = strchr(targ, '\0');
482 	*cp++ = '/';
483 	for (n = 1; n < argc - 1; n++) {
484 		strcpy(cp, tail(argv[n]));
485 		fd = open(argv[n], O_RDONLY);
486 		if (fd < 0) {
487 			warn("%s", argv[n]);
488 			continue;
489 		}
490 
491 		stat(cp, &sb);
492 		asprintf(&options[OPT_TSIZE].o_request, "%ju", sb.st_size);
493 
494 		if (verbose)
495 			printf("putting %s to %s:%s [%s]\n",
496 			    argv[n], hostname, targ, mode);
497 		xmitfile(peer, port, fd, targ, mode);
498 	}
499 }
500 
501 static void
502 putusage(char *s)
503 {
504 
505 	printf("usage: %s file [remotename]\n", s);
506 	printf("       %s file host:remotename\n", s);
507 	printf("       %s file1 file2 ... fileN [[host:]remote-directory]\n", s);
508 }
509 
510 /*
511  * Receive file(s).
512  */
513 static void
514 get(int argc, char *argv[])
515 {
516 	int fd;
517 	int n;
518 	char *cp;
519 	char *src;
520 	char	line[MAXLINE];
521 
522 	if (argc < 2) {
523 		strcpy(line, "get ");
524 		printf("(files) ");
525 		fgets(&line[strlen(line)], sizeof line - strlen(line), stdin);
526 		makeargv(line);
527 		argc = margc;
528 		argv = margv;
529 	}
530 	if (argc < 2) {
531 		getusage(argv[0]);
532 		return;
533 	}
534 	if (!connected) {
535 		for (n = 1; n < argc ; n++)
536 			if (strrchr(argv[n], ':') == 0) {
537 				printf("No remote host specified and "
538 				    "no host given for file '%s'\n", argv[n]);
539 				getusage(argv[0]);
540 				return;
541 			}
542 	}
543 	for (n = 1; n < argc ; n++) {
544 		src = strrchr(argv[n], ':');
545 		if (src == NULL)
546 			src = argv[n];
547 		else {
548 			char *lcp;
549 
550 			*src++ = 0;
551 			lcp = argv[n];
552 			if (lcp[0] == '[' && lcp[strlen(lcp) - 1] == ']') {
553 				lcp[strlen(lcp) - 1] = '\0';
554 				lcp++;
555 			}
556 			setpeer0(lcp, NULL);
557 			if (!connected)
558 				continue;
559 		}
560 		if (argc < 4) {
561 			cp = argc == 3 ? argv[2] : tail(src);
562 			fd = creat(cp, 0644);
563 			if (fd < 0) {
564 				warn("%s", cp);
565 				return;
566 			}
567 			if (verbose)
568 				printf("getting from %s:%s to %s [%s]\n",
569 				    hostname, src, cp, mode);
570 			recvfile(peer, port, fd, src, mode);
571 			break;
572 		}
573 		cp = tail(src);         /* new .. jdg */
574 		fd = creat(cp, 0644);
575 		if (fd < 0) {
576 			warn("%s", cp);
577 			continue;
578 		}
579 		if (verbose)
580 			printf("getting from %s:%s to %s [%s]\n",
581 			    hostname, src, cp, mode);
582 		recvfile(peer, port, fd, src, mode);
583 	}
584 }
585 
586 static void
587 getusage(char *s)
588 {
589 
590 	printf("usage: %s file [localname]\n", s);
591 	printf("       %s [host:]file [localname]\n", s);
592 	printf("       %s [host1:]file1 [host2:]file2 ... [hostN:]fileN\n", s);
593 }
594 
595 static void
596 settimeoutpacket(int argc, char *argv[])
597 {
598 	int t;
599 	char	line[MAXLINE];
600 
601 	if (argc < 2) {
602 		strcpy(line, "Packet timeout ");
603 		printf("(value) ");
604 		fgets(&line[strlen(line)], sizeof line - strlen(line), stdin);
605 		makeargv(line);
606 		argc = margc;
607 		argv = margv;
608 	}
609 	if (argc != 2) {
610 		printf("usage: %s value\n", argv[0]);
611 		return;
612 	}
613 	t = atoi(argv[1]);
614 	if (t < 0) {
615 		printf("%s: bad value\n", argv[1]);
616 		return;
617 	}
618 
619 	settimeouts(t, timeoutnetwork, maxtimeouts);
620 }
621 
622 static void
623 settimeoutnetwork(int argc, char *argv[])
624 {
625 	int t;
626 	char	line[MAXLINE];
627 
628 	if (argc < 2) {
629 		strcpy(line, "Network timeout ");
630 		printf("(value) ");
631 		fgets(&line[strlen(line)], sizeof line - strlen(line), stdin);
632 		makeargv(line);
633 		argc = margc;
634 		argv = margv;
635 	}
636 	if (argc != 2) {
637 		printf("usage: %s value\n", argv[0]);
638 		return;
639 	}
640 	t = atoi(argv[1]);
641 	if (t < 0) {
642 		printf("%s: bad value\n", argv[1]);
643 		return;
644 	}
645 
646 	settimeouts(timeoutpacket, t, maxtimeouts);
647 }
648 
649 static void
650 showstatus(int argc __unused, char *argv[] __unused)
651 {
652 
653 	printf("Remote host: %s\n",
654 	    connected ? hostname : "none specified yet");
655 	printf("RFC2347 Options support: %s\n",
656 	    options_rfc_enabled ? "enabled" : "disabled");
657 	printf("Non-RFC defined options support: %s\n",
658 	    options_extra_enabled ? "enabled" : "disabled");
659 	printf("Mode: %s\n", mode);
660 	printf("Verbose: %s\n", verbose ? "on" : "off");
661 	printf("Debug: %s\n", debug_show(debug));
662 	printf("Artificial packetloss: %d in 100 packets\n",
663 	    packetdroppercentage);
664 	printf("Segment size: %d bytes\n", segsize);
665 	printf("Network timeout: %d seconds\n", timeoutpacket);
666 	printf("Maximum network timeout: %d seconds\n", timeoutnetwork);
667 	printf("Maximum timeouts: %d \n", maxtimeouts);
668 }
669 
670 static void
671 intr(int dummy __unused)
672 {
673 
674 	signal(SIGALRM, SIG_IGN);
675 	alarm(0);
676 	longjmp(toplevel, -1);
677 }
678 
679 static char *
680 tail(char *filename)
681 {
682 	char *s;
683 
684 	while (*filename) {
685 		s = strrchr(filename, '/');
686 		if (s == NULL)
687 			break;
688 		if (s[1])
689 			return (s + 1);
690 		*s = '\0';
691 	}
692 	return (filename);
693 }
694 
695 static const char *
696 command_prompt(void)
697 {
698 
699 	return ("tftp> ");
700 }
701 
702 /*
703  * Command parser.
704  */
705 static void
706 command(void)
707 {
708 	HistEvent he;
709 	struct cmd *c;
710 	static EditLine *el;
711 	static History *hist;
712 	const char *bp;
713 	char *cp;
714 	int len, num, vrbose;
715 	char	line[MAXLINE];
716 
717 	vrbose = isatty(0);
718 	if (vrbose) {
719 		el = el_init("tftp", stdin, stdout, stderr);
720 		hist = history_init();
721 		history(hist, &he, H_SETSIZE, 100);
722 		el_set(el, EL_HIST, history, hist);
723 		el_set(el, EL_EDITOR, "emacs");
724 		el_set(el, EL_PROMPT, command_prompt);
725 		el_set(el, EL_SIGNAL, 1);
726 		el_source(el, NULL);
727 	}
728 	for (;;) {
729 		if (vrbose) {
730                         if ((bp = el_gets(el, &num)) == NULL || num == 0)
731                                 exit(0);
732                         len = MIN(MAXLINE, num);
733                         memcpy(line, bp, len);
734                         line[len] = '\0';
735                         history(hist, &he, H_ENTER, bp);
736 		} else {
737 			line[0] = 0;
738 			if (fgets(line, sizeof line , stdin) == NULL) {
739 				if (feof(stdin)) {
740 					exit(txrx_error);
741 				} else {
742 					continue;
743 				}
744 			}
745 		}
746 		if ((cp = strchr(line, '\n')))
747 			*cp = '\0';
748 		if (line[0] == 0)
749 			continue;
750 		makeargv(line);
751 		if (margc == 0)
752 			continue;
753 		c = getcmd(margv[0]);
754 		if (c == (struct cmd *)-1) {
755 			printf("?Ambiguous command\n");
756 			continue;
757 		}
758 		if (c == NULL) {
759 			printf("?Invalid command\n");
760 			continue;
761 		}
762 		(*c->handler)(margc, margv);
763 	}
764 }
765 
766 static struct cmd *
767 getcmd(char *name)
768 {
769 	const char *p, *q;
770 	struct cmd *c, *found;
771 	int nmatches, longest;
772 
773 	longest = 0;
774 	nmatches = 0;
775 	found = 0;
776 	for (c = cmdtab; (p = c->name) != NULL; c++) {
777 		for (q = name; *q == *p++; q++)
778 			if (*q == 0)		/* exact match? */
779 				return (c);
780 		if (!*q) {			/* the name was a prefix */
781 			if (q - name > longest) {
782 				longest = q - name;
783 				nmatches = 1;
784 				found = c;
785 			} else if (q - name == longest)
786 				nmatches++;
787 		}
788 	}
789 	if (nmatches > 1)
790 		return ((struct cmd *)-1);
791 	return (found);
792 }
793 
794 /*
795  * Slice a string up into argc/argv.
796  */
797 static void
798 makeargv(char *line)
799 {
800 	char *cp;
801 	char **argp = margv;
802 
803 	margc = 0;
804 	if ((cp = strchr(line, '\n')) != NULL)
805 		*cp = '\0';
806 	for (cp = line; margc < MAX_MARGV - 1 && *cp != '\0';) {
807 		while (isspace(*cp))
808 			cp++;
809 		if (*cp == '\0')
810 			break;
811 		*argp++ = cp;
812 		margc += 1;
813 		while (*cp != '\0' && !isspace(*cp))
814 			cp++;
815 		if (*cp == '\0')
816 			break;
817 		*cp++ = '\0';
818 	}
819 	*argp++ = 0;
820 }
821 
822 static void
823 quit(int argc __unused, char *argv[] __unused)
824 {
825 
826 	exit(txrx_error);
827 }
828 
829 /*
830  * Help command.
831  */
832 static void
833 help(int argc, char *argv[])
834 {
835 	struct cmd *c;
836 
837 	if (argc == 1) {
838 		printf("Commands may be abbreviated.  Commands are:\n\n");
839 		for (c = cmdtab; c->name; c++)
840 			printf("%-*s\t%s\n", (int)HELPINDENT, c->name, c->help);
841 
842 		printf("\n[-] : You shouldn't use these ones anymore.\n");
843 		printf("[*] : RFC2347 options support required.\n");
844 		printf("[**] : Non-standard RFC2347 option.\n");
845 		return;
846 	}
847 	while (--argc > 0) {
848 		char *arg;
849 		arg = *++argv;
850 		c = getcmd(arg);
851 		if (c == (struct cmd *)-1)
852 			printf("?Ambiguous help command: %s\n", arg);
853 		else if (c == (struct cmd *)0)
854 			printf("?Invalid help command: %s\n", arg);
855 		else
856 			printf("%s\n", c->help);
857 	}
858 }
859 
860 static void
861 setverbose(int argc __unused, char *argv[] __unused)
862 {
863 
864 	verbose = !verbose;
865 	printf("Verbose mode %s.\n", verbose ? "on" : "off");
866 }
867 
868 static void
869 setoptions(int argc, char *argv[])
870 {
871 
872 	if (argc == 2) {
873 		if (strcasecmp(argv[1], "enable") == 0 ||
874 		    strcasecmp(argv[1], "on") == 0) {
875 			options_extra_enabled = 1;
876 			options_rfc_enabled = 1;
877 		}
878 		if (strcasecmp(argv[1], "disable") == 0 ||
879 		    strcasecmp(argv[1], "off") == 0) {
880 			options_extra_enabled = 0;
881 			options_rfc_enabled = 0;
882 		}
883 		if (strcasecmp(argv[1], "extra") == 0)
884 			options_extra_enabled = !options_extra_enabled;
885 	}
886 	printf("Support for RFC2347 style options are now %s.\n",
887 	    options_rfc_enabled ? "enabled" : "disabled");
888 	printf("Support for non-RFC defined options are now %s.\n",
889 	    options_extra_enabled ? "enabled" : "disabled");
890 
891 	printf("\nThe following options are available:\n"
892 	    "\toptions on	: enable support for RFC2347 style options\n"
893 	    "\toptions off	: disable support for RFC2347 style options\n"
894 	    "\toptions extra	: toggle support for non-RFC defined options\n"
895 	);
896 }
897 
898 static void
899 setrollover(int argc, char *argv[])
900 {
901 
902 	if (argc == 2) {
903 		if (strcasecmp(argv[1], "never") == 0 ||
904 		    strcasecmp(argv[1], "none") == 0) {
905 			free(options[OPT_ROLLOVER].o_request);
906 			options[OPT_ROLLOVER].o_request = NULL;
907 		}
908 		if (strcasecmp(argv[1], "1") == 0) {
909 			free(options[OPT_ROLLOVER].o_request);
910 			options[OPT_ROLLOVER].o_request = strdup("1");
911 		}
912 		if (strcasecmp(argv[1], "0") == 0) {
913 			free(options[OPT_ROLLOVER].o_request);
914 			options[OPT_ROLLOVER].o_request = strdup("0");
915 		}
916 	}
917 	printf("Support for the rollover options is %s.\n",
918 	    options[OPT_ROLLOVER].o_request != NULL ? "enabled" : "disabled");
919 	if (options[OPT_ROLLOVER].o_request != NULL)
920 		printf("Block rollover will be to block %s.\n",
921 		    options[OPT_ROLLOVER].o_request);
922 
923 
924 	printf("\nThe following rollover options are available:\n"
925 	    "\trollover 0	: rollover to block zero (default)\n"
926 	    "\trollover 1	: rollover to block one\n"
927 	    "\trollover never	: do not support the rollover option\n"
928 	    "\trollover none	: do not support the rollover option\n"
929 	);
930 }
931 
932 static void
933 setdebug(int argc, char *argv[])
934 {
935 	int i;
936 
937 	if (argc != 1) {
938 		i = 1;
939 		while (i < argc)
940 			debug ^= debug_find(argv[i++]);
941 	}
942 	printf("The following debugging is enabled: %s\n", debug_show(debug));
943 
944 	printf("\nThe following debugs are available:\n");
945 	i = 0;
946 	while (debugs[i].name != NULL) {
947 		printf("\t%s\t%s\n", debugs[i].name, debugs[i].desc);
948 		i++;
949 	}
950 }
951 
952 static void
953 setblocksize(int argc, char *argv[])
954 {
955 
956 	if (!options_rfc_enabled)
957 		printf("RFC2347 style options are not enabled "
958 		    "(but proceeding anyway)\n");
959 
960 	if (argc != 1) {
961 		int size = atoi(argv[1]);
962 		size_t max;
963 		u_long maxdgram;
964 
965 		max = sizeof(maxdgram);
966 		if (sysctlbyname("net.inet.udp.maxdgram",
967 			&maxdgram, &max, NULL, 0) < 0) {
968 			perror("sysctl: net.inet.udp.maxdgram");
969 			return;
970 		}
971 
972 		if (size < BLKSIZE_MIN || size > BLKSIZE_MAX) {
973 			printf("Blocksize should be between %d and %d bytes.\n",
974 				BLKSIZE_MIN, BLKSIZE_MAX);
975 			return;
976 		} else if (size > (int)maxdgram - 4) {
977 			printf("Blocksize can't be bigger than %ld bytes due "
978 			    "to the net.inet.udp.maxdgram sysctl limitation.\n",
979 			    maxdgram - 4);
980 			asprintf(&options[OPT_BLKSIZE].o_request,
981 			    "%ld", maxdgram - 4);
982 		} else {
983 			asprintf(&options[OPT_BLKSIZE].o_request, "%d", size);
984 		}
985 	}
986 	printf("Blocksize is now %s bytes.\n", options[OPT_BLKSIZE].o_request);
987 }
988 
989 static void
990 setblocksize2(int argc, char *argv[])
991 {
992 
993 	if (!options_rfc_enabled || !options_extra_enabled)
994 		printf(
995 		    "RFC2347 style or non-RFC defined options are not enabled "
996 		    "(but proceeding anyway)\n");
997 
998 	if (argc != 1) {
999 		int size = atoi(argv[1]);
1000 		int i;
1001 		size_t max;
1002 		u_long maxdgram;
1003 
1004 		int sizes[] = {
1005 			8, 16, 32, 64, 128, 256, 512, 1024,
1006 			2048, 4096, 8192, 16384, 32768, 0
1007 		};
1008 
1009 		max = sizeof(maxdgram);
1010 		if (sysctlbyname("net.inet.udp.maxdgram",
1011 			&maxdgram, &max, NULL, 0) < 0) {
1012 			perror("sysctl: net.inet.udp.maxdgram");
1013 			return;
1014 		}
1015 
1016 		for (i = 0; sizes[i] != 0; i++) {
1017 			if (sizes[i] == size) break;
1018 		}
1019 		if (sizes[i] == 0) {
1020 			printf("Blocksize2 should be a power of two between "
1021 			    "8 and 32768.\n");
1022 			return;
1023 		}
1024 
1025 		if (size < BLKSIZE_MIN || size > BLKSIZE_MAX) {
1026 			printf("Blocksize2 should be between "
1027 			    "%d and %d bytes.\n", BLKSIZE_MIN, BLKSIZE_MAX);
1028 			return;
1029 		} else if (size > (int)maxdgram - 4) {
1030 			printf("Blocksize2 can't be bigger than %ld bytes due "
1031 			    "to the net.inet.udp.maxdgram sysctl limitation.\n",
1032 			    maxdgram - 4);
1033 			for (i = 0; sizes[i+1] != 0; i++) {
1034 				if ((int)maxdgram < sizes[i+1]) break;
1035 			}
1036 			asprintf(&options[OPT_BLKSIZE2].o_request,
1037 			    "%d", sizes[i]);
1038 		} else {
1039 			asprintf(&options[OPT_BLKSIZE2].o_request, "%d", size);
1040 		}
1041 	}
1042 	printf("Blocksize2 is now %s bytes.\n",
1043 	    options[OPT_BLKSIZE2].o_request);
1044 }
1045 
1046 static void
1047 setpacketdrop(int argc, char *argv[])
1048 {
1049 
1050 	if (argc != 1)
1051 		packetdroppercentage = atoi(argv[1]);
1052 
1053 	printf("Randomly %d in 100 packets will be dropped\n",
1054 	    packetdroppercentage);
1055 }
1056