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