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