main.c revision 339060
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
31static 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
38static char sccsid[] = "@(#)main.c	8.1 (Berkeley) 6/6/93";
39#endif
40#endif
41
42#include <sys/cdefs.h>
43__FBSDID("$FreeBSD: stable/10/usr.bin/tftp/main.c 339060 2018-10-01 16:09:20Z asomers $");
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		200
78#define	TIMEOUT		5		/* secs between rexmt's */
79
80typedef struct	sockaddr_storage peeraddr;
81static int	connected;
82static char	mode[32];
83static jmp_buf	toplevel;
84volatile int	txrx_error;
85static int	peer;
86
87#define	MAX_MARGV	20
88static int	margc;
89static char	*margv[MAX_MARGV];
90
91int		verbose;
92static char	*port = NULL;
93
94static void	get(int, char **);
95static void	help(int, char **);
96static void	intr(int);
97static void	modecmd(int, char **);
98static void	put(int, char **);
99static void	quit(int, char **);
100static void	setascii(int, char **);
101static void	setbinary(int, char **);
102static void	setpeer0(char *, const char *);
103static void	setpeer(int, char **);
104static void	settimeoutpacket(int, char **);
105static void	settimeoutnetwork(int, char **);
106static void	setdebug(int, char **);
107static void	setverbose(int, char **);
108static void	showstatus(int, char **);
109static void	setblocksize(int, char **);
110static void	setblocksize2(int, char **);
111static void	setoptions(int, char **);
112static void	setrollover(int, char **);
113static void	setpacketdrop(int, char **);
114
115static void command(void) __dead2;
116static const char *command_prompt(void);
117
118static void urihandling(char *URI);
119static void getusage(char *);
120static void makeargv(char *line);
121static void putusage(char *);
122static void settftpmode(const char *);
123
124static char	*tail(char *);
125static struct	cmd *getcmd(char *);
126
127#define HELPINDENT (sizeof("connect"))
128
129struct cmd {
130	const char	*name;
131	void	(*handler)(int, char **);
132	const char	*help;
133};
134
135static 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
162static 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
174int
175main(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 */
214static void
215urihandling(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
266static char    hostname[MAXHOSTNAMELEN];
267
268static void
269setpeer0(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
333static void
334setpeer(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
357static void
358modecmd(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
390static void
391setbinary(int argc __unused, char *argv[] __unused)
392{
393
394	settftpmode("octet");
395}
396
397static void
398setascii(int argc __unused, char *argv[] __unused)
399{
400
401	settftpmode("netascii");
402}
403
404static void
405settftpmode(const char *newmode)
406{
407
408	strlcpy(mode, newmode, sizeof(mode));
409	if (verbose)
410		printf("mode set to %s\n", mode);
411}
412
413
414/*
415 * Send file(s).
416 */
417static void
418put(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		if (fstat(fd, &sb) < 0) {
469			warn("%s", cp);
470			return;
471		}
472		asprintf(&options[OPT_TSIZE].o_request, "%ju", sb.st_size);
473
474		if (verbose)
475			printf("putting %s to %s:%s [%s]\n",
476			    cp, hostname, targ, mode);
477		xmitfile(peer, port, fd, targ, mode);
478		return;
479	}
480				/* this assumes the target is a directory */
481				/* on a remote unix system.  hmmmm.  */
482	cp = strchr(targ, '\0');
483	*cp++ = '/';
484	for (n = 1; n < argc - 1; n++) {
485		strcpy(cp, tail(argv[n]));
486		fd = open(argv[n], O_RDONLY);
487		if (fd < 0) {
488			warn("%s", argv[n]);
489			continue;
490		}
491
492		if (fstat(fd, &sb) < 0) {
493			warn("%s", argv[n]);
494			continue;
495		}
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
505static void
506putusage(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 */
517static void
518get(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 (strrchr(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 = strrchr(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
590static void
591getusage(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
599static void
600settimeoutpacket(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
626static void
627settimeoutnetwork(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
653static void
654showstatus(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
674static void
675intr(int dummy __unused)
676{
677
678	signal(SIGALRM, SIG_IGN);
679	alarm(0);
680	longjmp(toplevel, -1);
681}
682
683static char *
684tail(char *filename)
685{
686	char *s;
687
688	while (*filename) {
689		s = strrchr(filename, '/');
690		if (s == NULL)
691			break;
692		if (s[1])
693			return (s + 1);
694		*s = '\0';
695	}
696	return (filename);
697}
698
699static const char *
700command_prompt(void)
701{
702
703	return ("tftp> ");
704}
705
706/*
707 * Command parser.
708 */
709static void
710command(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) == NULL) {
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
770static struct cmd *
771getcmd(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 */
801static void
802makeargv(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
826static void
827quit(int argc __unused, char *argv[] __unused)
828{
829
830	exit(txrx_error);
831}
832
833/*
834 * Help command.
835 */
836static void
837help(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("[*] : RFC2347 options support required.\n");
848		printf("[**] : Non-standard RFC2347 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
864static void
865setverbose(int argc __unused, char *argv[] __unused)
866{
867
868	verbose = !verbose;
869	printf("Verbose mode %s.\n", verbose ? "on" : "off");
870}
871
872static void
873setoptions(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
902static void
903setrollover(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
936static void
937setdebug(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
956static void
957setblocksize(int argc, char *argv[])
958{
959
960	if (!options_rfc_enabled)
961		printf("RFC2347 style options are not enabled "
962		    "(but proceeding anyway)\n");
963
964	if (argc != 1) {
965		int size = atoi(argv[1]);
966		size_t max;
967		u_long maxdgram;
968
969		max = sizeof(maxdgram);
970		if (sysctlbyname("net.inet.udp.maxdgram",
971			&maxdgram, &max, NULL, 0) < 0) {
972			perror("sysctl: net.inet.udp.maxdgram");
973			return;
974		}
975
976		if (size < BLKSIZE_MIN || size > BLKSIZE_MAX) {
977			printf("Blocksize should be between %d and %d bytes.\n",
978				BLKSIZE_MIN, BLKSIZE_MAX);
979			return;
980		} else if (size > (int)maxdgram - 4) {
981			printf("Blocksize can't be bigger than %ld bytes due "
982			    "to the net.inet.udp.maxdgram sysctl limitation.\n",
983			    maxdgram - 4);
984			asprintf(&options[OPT_BLKSIZE].o_request,
985			    "%ld", maxdgram - 4);
986		} else {
987			asprintf(&options[OPT_BLKSIZE].o_request, "%d", size);
988		}
989	}
990	printf("Blocksize is now %s bytes.\n", options[OPT_BLKSIZE].o_request);
991}
992
993static void
994setblocksize2(int argc, char *argv[])
995{
996
997	if (!options_rfc_enabled || !options_extra_enabled)
998		printf(
999		    "RFC2347 style or non-RFC defined options are not enabled "
1000		    "(but proceeding anyway)\n");
1001
1002	if (argc != 1) {
1003		int size = atoi(argv[1]);
1004		int i;
1005		size_t max;
1006		u_long maxdgram;
1007
1008		int sizes[] = {
1009			8, 16, 32, 64, 128, 256, 512, 1024,
1010			2048, 4096, 8192, 16384, 32768, 0
1011		};
1012
1013		max = sizeof(maxdgram);
1014		if (sysctlbyname("net.inet.udp.maxdgram",
1015			&maxdgram, &max, NULL, 0) < 0) {
1016			perror("sysctl: net.inet.udp.maxdgram");
1017			return;
1018		}
1019
1020		for (i = 0; sizes[i] != 0; i++) {
1021			if (sizes[i] == size) break;
1022		}
1023		if (sizes[i] == 0) {
1024			printf("Blocksize2 should be a power of two between "
1025			    "8 and 32768.\n");
1026			return;
1027		}
1028
1029		if (size < BLKSIZE_MIN || size > BLKSIZE_MAX) {
1030			printf("Blocksize2 should be between "
1031			    "%d and %d bytes.\n", BLKSIZE_MIN, BLKSIZE_MAX);
1032			return;
1033		} else if (size > (int)maxdgram - 4) {
1034			printf("Blocksize2 can't be bigger than %ld bytes due "
1035			    "to the net.inet.udp.maxdgram sysctl limitation.\n",
1036			    maxdgram - 4);
1037			for (i = 0; sizes[i+1] != 0; i++) {
1038				if ((int)maxdgram < sizes[i+1]) break;
1039			}
1040			asprintf(&options[OPT_BLKSIZE2].o_request,
1041			    "%d", sizes[i]);
1042		} else {
1043			asprintf(&options[OPT_BLKSIZE2].o_request, "%d", size);
1044		}
1045	}
1046	printf("Blocksize2 is now %s bytes.\n",
1047	    options[OPT_BLKSIZE2].o_request);
1048}
1049
1050static void
1051setpacketdrop(int argc, char *argv[])
1052{
1053
1054	if (argc != 1)
1055		packetdroppercentage = atoi(argv[1]);
1056
1057	printf("Randomly %d in 100 packets will be dropped\n",
1058	    packetdroppercentage);
1059}
1060