main.c revision 213099
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
35static 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
42static char sccsid[] = "@(#)main.c	8.1 (Berkeley) 6/6/93";
43#endif
44#endif
45
46#include <sys/cdefs.h>
47__FBSDID("$FreeBSD: head/usr.bin/tftp/main.c 213099 2010-09-24 10:40:17Z marius $");
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
85static struct	sockaddr_storage peeraddr;
86static int	connected;
87static char	mode[32];
88jmp_buf		toplevel;
89volatile int	txrx_error;
90static int	peer;
91
92#define	MAX_MARGV	20
93static int	margc;
94static char	*margv[MAX_MARGV];
95
96int		verbose;
97char		*port = NULL;
98
99static void	get(int, char **);
100static void	help(int, char **);
101static void	intr(int);
102static void	modecmd(int, char **);
103static void	put(int, char **);
104static void	quit(int, char **);
105static void	setascii(int, char **);
106static void	setbinary(int, char **);
107static void	setpeer0(char *, const char *);
108static void	setpeer(int, char **);
109static void	settimeoutpacket(int, char **);
110static void	settimeoutnetwork(int, char **);
111static void	setdebug(int, char **);
112static void	setverbose(int, char **);
113static void	showstatus(int, char **);
114static void	setblocksize(int, char **);
115static void	setblocksize2(int, char **);
116static void	setoptions(int, char **);
117static void	setrollover(int, char **);
118static void	setpacketdrop(int, char **);
119
120static void command(void) __dead2;
121static const char *command_prompt(void);
122
123static void urihandling(char *URI);
124static void getusage(char *);
125static void makeargv(char *line);
126static void putusage(char *);
127static void settftpmode(const char *);
128
129static char	*tail(char *);
130static struct	cmd *getcmd(char *);
131
132#define HELPINDENT (sizeof("connect"))
133
134struct cmd {
135	const char	*name;
136	void	(*handler)(int, char **);
137	const char	*help;
138};
139
140static 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
167static 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
179int
180main(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 */
219static void
220urihandling(char *URI)
221{
222	char	uri[ARG_MAX];
223	char	*host = NULL;
224	char	*path = NULL;
225	char	*opts = NULL;
226	const char *tmode = "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		opts = s + 1;
245
246		if (strncmp(opts, "mode=", 5) == 0) {
247			tmode = opts;
248			tmode += 5;
249
250			for (i = 0; modes[i].m_name != NULL; i++) {
251				if (strcmp(modes[i].m_name, tmode) == 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
271static char    hostname[MAXHOSTNAMELEN];
272
273static void
274setpeer0(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
339static void
340setpeer(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
363static void
364modecmd(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
396static void
397setbinary(int argc __unused, char *argv[] __unused)
398{
399
400	settftpmode("octet");
401}
402
403static void
404setascii(int argc __unused, char *argv[] __unused)
405{
406
407	settftpmode("netascii");
408}
409
410static void
411settftpmode(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 */
423static void
424put(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
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 (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
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 = 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
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) == 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
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("[*] : 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
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 proceding 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 proceding 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