1
2/*
3 * main.c
4 *
5 * Copyright (c) 1996-1999 Whistle Communications, Inc.
6 * All rights reserved.
7 *
8 * Subject to the following obligations and disclaimer of warranty, use and
9 * redistribution of this software, in source or object code forms, with or
10 * without modifications are expressly permitted by Whistle Communications;
11 * provided, however, that:
12 * 1. Any and all reproductions of the source or object code must include the
13 *    copyright notice above and the following disclaimer of warranties; and
14 * 2. No rights are granted, in any manner or form, to use Whistle
15 *    Communications, Inc. trademarks, including the mark "WHISTLE
16 *    COMMUNICATIONS" on advertising, endorsements, or otherwise except as
17 *    such appears in the above copyright notice or in the software.
18 *
19 * THIS SOFTWARE IS BEING PROVIDED BY WHISTLE COMMUNICATIONS "AS IS", AND
20 * TO THE MAXIMUM EXTENT PERMITTED BY LAW, WHISTLE COMMUNICATIONS MAKES NO
21 * REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED, REGARDING THIS SOFTWARE,
22 * INCLUDING WITHOUT LIMITATION, ANY AND ALL IMPLIED WARRANTIES OF
23 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT.
24 * WHISTLE COMMUNICATIONS DOES NOT WARRANT, GUARANTEE, OR MAKE ANY
25 * REPRESENTATIONS REGARDING THE USE OF, OR THE RESULTS OF THE USE OF THIS
26 * SOFTWARE IN TERMS OF ITS CORRECTNESS, ACCURACY, RELIABILITY OR OTHERWISE.
27 * IN NO EVENT SHALL WHISTLE COMMUNICATIONS BE LIABLE FOR ANY DAMAGES
28 * RESULTING FROM OR ARISING OUT OF ANY USE OF THIS SOFTWARE, INCLUDING
29 * WITHOUT LIMITATION, ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
30 * PUNITIVE, OR CONSEQUENTIAL DAMAGES, PROCUREMENT OF SUBSTITUTE GOODS OR
31 * SERVICES, LOSS OF USE, DATA OR PROFITS, HOWEVER CAUSED AND UNDER ANY
32 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
33 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
34 * THIS SOFTWARE, EVEN IF WHISTLE COMMUNICATIONS IS ADVISED OF THE POSSIBILITY
35 * OF SUCH DAMAGE.
36 *
37 * $Whistle: main.c,v 1.12 1999/11/29 19:17:46 archie Exp $
38 */
39
40#include <sys/cdefs.h>
41__FBSDID("$FreeBSD$");
42
43#include <sys/param.h>
44#include <sys/socket.h>
45#include <sys/select.h>
46
47#include <ctype.h>
48#include <err.h>
49#include <errno.h>
50#include <limits.h>
51#include <stdio.h>
52#include <stdlib.h>
53#include <string.h>
54#include <sysexits.h>
55#include <unistd.h>
56#ifdef EDITLINE
57#include <signal.h>
58#include <histedit.h>
59#include <pthread.h>
60#endif
61
62#include <netgraph.h>
63
64#include "ngctl.h"
65
66#define PROMPT			"+ "
67#define MAX_ARGS		512
68#define WHITESPACE		" \t\r\n\v\f"
69#define DUMP_BYTES_PER_LINE	16
70
71/* Internal functions */
72static int	ReadFile(FILE *fp);
73static void	ReadSockets(fd_set *);
74static int	DoParseCommand(const char *line);
75static int	DoCommand(int ac, char **av);
76static int	DoInteractive(void);
77static const	struct ngcmd *FindCommand(const char *string);
78static int	MatchCommand(const struct ngcmd *cmd, const char *s);
79static void	Usage(const char *msg);
80static int	ReadCmd(int ac, char **av);
81static int	HelpCmd(int ac, char **av);
82static int	QuitCmd(int ac, char **av);
83#ifdef EDITLINE
84static volatile sig_atomic_t unblock;
85static pthread_mutex_t	mutex = PTHREAD_MUTEX_INITIALIZER;
86static pthread_cond_t	cond = PTHREAD_COND_INITIALIZER;
87#endif
88
89/* List of commands */
90static const struct ngcmd *const cmds[] = {
91	&config_cmd,
92	&connect_cmd,
93	&debug_cmd,
94	&dot_cmd,
95	&help_cmd,
96	&list_cmd,
97	&mkpeer_cmd,
98	&msg_cmd,
99	&name_cmd,
100	&read_cmd,
101	&rmhook_cmd,
102	&show_cmd,
103	&shutdown_cmd,
104	&status_cmd,
105	&types_cmd,
106	&write_cmd,
107	&quit_cmd,
108	NULL
109};
110
111/* Commands defined in this file */
112const struct ngcmd read_cmd = {
113	ReadCmd,
114	"read <filename>",
115	"Read and execute commands from a file",
116	NULL,
117	{ "source", "." }
118};
119const struct ngcmd help_cmd = {
120	HelpCmd,
121	"help [command]",
122	"Show command summary or get more help on a specific command",
123	NULL,
124	{ "?" }
125};
126const struct ngcmd quit_cmd = {
127	QuitCmd,
128	"quit",
129	"Exit program",
130	NULL,
131	{ "exit" }
132};
133
134/* Our control and data sockets */
135int	csock, dsock;
136
137/*
138 * main()
139 */
140int
141main(int ac, char *av[])
142{
143	char	name[NG_NODESIZ];
144	int	interactive = isatty(0) && isatty(1);
145	FILE	*fp = NULL;
146	int	ch, rtn = 0;
147
148	/* Set default node name */
149	snprintf(name, sizeof(name), "ngctl%d", getpid());
150
151	/* Parse command line */
152	while ((ch = getopt(ac, av, "df:n:")) != -1) {
153		switch (ch) {
154		case 'd':
155			NgSetDebug(NgSetDebug(-1) + 1);
156			break;
157		case 'f':
158			if (strcmp(optarg, "-") == 0)
159				fp = stdin;
160			else if ((fp = fopen(optarg, "r")) == NULL)
161				err(EX_NOINPUT, "%s", optarg);
162			break;
163		case 'n':
164			snprintf(name, sizeof(name), "%s", optarg);
165			break;
166		case '?':
167		default:
168			Usage((char *)NULL);
169			break;
170		}
171	}
172	ac -= optind;
173	av += optind;
174
175	/* Create a new socket node */
176	if (NgMkSockNode(name, &csock, &dsock) < 0)
177		err(EX_OSERR, "can't create node");
178
179	/* Do commands as requested */
180	if (ac == 0) {
181		if (fp != NULL) {
182			rtn = ReadFile(fp);
183		} else if (interactive) {
184			rtn = DoInteractive();
185		} else
186			Usage("no command specified");
187	} else {
188		rtn = DoCommand(ac, av);
189	}
190
191	/* Convert command return code into system exit code */
192	switch (rtn) {
193	case CMDRTN_OK:
194	case CMDRTN_QUIT:
195		rtn = 0;
196		break;
197	case CMDRTN_USAGE:
198		rtn = EX_USAGE;
199		break;
200	case CMDRTN_ERROR:
201		rtn = EX_OSERR;
202		break;
203	}
204	return (rtn);
205}
206
207/*
208 * Process commands from a file
209 */
210static int
211ReadFile(FILE *fp)
212{
213	char line[LINE_MAX];
214	int num, rtn;
215
216	for (num = 1; fgets(line, sizeof(line), fp) != NULL; num++) {
217		if (*line == '#')
218			continue;
219		if ((rtn = DoParseCommand(line)) != 0) {
220			warnx("line %d: error in file", num);
221			return (rtn);
222		}
223	}
224	return (CMDRTN_OK);
225}
226
227#ifdef EDITLINE
228/* Signal handler for Monitor() thread. */
229static void
230Unblock(int signal __unused)
231{
232
233	unblock = 1;
234}
235
236/*
237 * Thread that monitors csock and dsock while main thread
238 * can be blocked in el_gets().
239 */
240static void *
241Monitor(void *v __unused)
242{
243	struct sigaction act;
244	const int maxfd = MAX(csock, dsock) + 1;
245
246	act.sa_handler = Unblock;
247	sigemptyset(&act.sa_mask);
248	act.sa_flags = 0;
249	sigaction(SIGUSR1, &act, NULL);
250
251	pthread_mutex_lock(&mutex);
252	for (;;) {
253		fd_set rfds;
254
255		/* See if any data or control messages are arriving. */
256		FD_ZERO(&rfds);
257		FD_SET(csock, &rfds);
258		FD_SET(dsock, &rfds);
259		unblock = 0;
260		if (select(maxfd, &rfds, NULL, NULL, NULL) <= 0) {
261			if (errno == EINTR) {
262				if (unblock == 1)
263					pthread_cond_wait(&cond, &mutex);
264				continue;
265			}
266			err(EX_OSERR, "select");
267		}
268		ReadSockets(&rfds);
269	}
270
271	return (NULL);
272}
273
274static char *
275Prompt(EditLine *el __unused)
276{
277
278	return (PROMPT);
279}
280
281/*
282 * Here we start a thread, that will monitor the netgraph
283 * sockets and catch any unexpected messages or data on them,
284 * that can arrive while user edits his/her commands.
285 *
286 * Whenever we expect data on netgraph sockets, we send signal
287 * to monitoring thread. The signal forces it to exit select()
288 * system call and sleep on condvar until we wake it. While
289 * monitoring thread sleeps, we can do our work with netgraph
290 * sockets.
291 */
292static int
293DoInteractive(void)
294{
295	pthread_t monitor;
296	EditLine *el;
297	History *hist;
298	HistEvent hev = { 0, "" };
299
300	(*help_cmd.func)(0, NULL);
301	pthread_create(&monitor, NULL, Monitor, NULL);
302	el = el_init(getprogname(), stdin, stdout, stderr);
303	if (el == NULL)
304		return (CMDRTN_ERROR);
305	el_set(el, EL_PROMPT, Prompt);
306	el_set(el, EL_SIGNAL, 1);
307	el_set(el, EL_EDITOR, "emacs");
308	hist = history_init();
309	if (hist == NULL)
310		return (CMDRTN_ERROR);
311	history(hist, &hev, H_SETSIZE, 100);
312	history(hist, &hev, H_SETUNIQUE, 1);
313	el_set(el, EL_HIST, history, (const char *)hist);
314	el_source(el, NULL);
315
316	for (;;) {
317		const char *buf;
318		int count;
319
320		if ((buf = el_gets(el, &count)) == NULL) {
321			printf("\n");
322			break;
323		}
324		history(hist, &hev, H_ENTER, buf);
325		pthread_kill(monitor, SIGUSR1);
326		pthread_mutex_lock(&mutex);
327		if (DoParseCommand(buf) == CMDRTN_QUIT) {
328			pthread_mutex_unlock(&mutex);
329			break;
330		}
331		pthread_cond_signal(&cond);
332		pthread_mutex_unlock(&mutex);
333	}
334
335	history_end(hist);
336	el_end(el);
337	pthread_cancel(monitor);
338
339	return (CMDRTN_QUIT);
340}
341
342#else /* !EDITLINE */
343
344/*
345 * Interactive mode w/o libedit functionality.
346 */
347static int
348DoInteractive(void)
349{
350	const int maxfd = MAX(csock, dsock) + 1;
351
352	(*help_cmd.func)(0, NULL);
353	while (1) {
354		struct timeval tv;
355		fd_set rfds;
356
357		/* See if any data or control messages are arriving */
358		FD_ZERO(&rfds);
359		FD_SET(csock, &rfds);
360		FD_SET(dsock, &rfds);
361		memset(&tv, 0, sizeof(tv));
362		if (select(maxfd, &rfds, NULL, NULL, &tv) <= 0) {
363
364			/* Issue prompt and wait for anything to happen */
365			printf("%s", PROMPT);
366			fflush(stdout);
367			FD_ZERO(&rfds);
368			FD_SET(0, &rfds);
369			FD_SET(csock, &rfds);
370			FD_SET(dsock, &rfds);
371			if (select(maxfd, &rfds, NULL, NULL, NULL) < 0)
372				err(EX_OSERR, "select");
373
374			/* If not user input, print a newline first */
375			if (!FD_ISSET(0, &rfds))
376				printf("\n");
377		}
378
379		ReadSockets(&rfds);
380
381		/* Get any user input */
382		if (FD_ISSET(0, &rfds)) {
383			char buf[LINE_MAX];
384
385			if (fgets(buf, sizeof(buf), stdin) == NULL) {
386				printf("\n");
387				break;
388			}
389			if (DoParseCommand(buf) == CMDRTN_QUIT)
390				break;
391		}
392	}
393	return (CMDRTN_QUIT);
394}
395#endif /* !EDITLINE */
396
397/*
398 * Read and process data on netgraph control and data sockets.
399 */
400static void
401ReadSockets(fd_set *rfds)
402{
403	/* Display any incoming control message. */
404	if (FD_ISSET(csock, rfds))
405		MsgRead();
406
407	/* Display any incoming data packet. */
408	if (FD_ISSET(dsock, rfds)) {
409		char hook[NG_HOOKSIZ];
410		u_char *buf;
411		int rl;
412
413		/* Read packet from socket. */
414		if ((rl = NgAllocRecvData(dsock, &buf, hook)) < 0)
415			err(EX_OSERR, "reading hook \"%s\"", hook);
416		if (rl == 0)
417			errx(EX_OSERR, "EOF from hook \"%s\"?", hook);
418
419		/* Write packet to stdout. */
420		printf("Rec'd data packet on hook \"%s\":\n", hook);
421		DumpAscii(buf, rl);
422		free(buf);
423	}
424}
425
426/*
427 * Parse a command line and execute the command
428 */
429static int
430DoParseCommand(const char *line)
431{
432	char *av[MAX_ARGS];
433	int ac;
434
435	/* Parse line */
436	for (ac = 0, av[0] = strtok((char *)line, WHITESPACE);
437	    ac < MAX_ARGS - 1 && av[ac];
438	    av[++ac] = strtok(NULL, WHITESPACE));
439
440	/* Do command */
441	return (DoCommand(ac, av));
442}
443
444/*
445 * Execute the command
446 */
447static int
448DoCommand(int ac, char **av)
449{
450	const struct ngcmd *cmd;
451	int rtn;
452
453	if (ac == 0 || *av[0] == 0)
454		return (CMDRTN_OK);
455	if ((cmd = FindCommand(av[0])) == NULL)
456		return (CMDRTN_ERROR);
457	if ((rtn = (*cmd->func)(ac, av)) == CMDRTN_USAGE)
458		warnx("usage: %s", cmd->cmd);
459	return (rtn);
460}
461
462/*
463 * Find a command
464 */
465static const struct ngcmd *
466FindCommand(const char *string)
467{
468	int k, found = -1;
469
470	for (k = 0; cmds[k] != NULL; k++) {
471		if (MatchCommand(cmds[k], string)) {
472			if (found != -1) {
473				warnx("\"%s\": ambiguous command", string);
474				return (NULL);
475			}
476			found = k;
477		}
478	}
479	if (found == -1) {
480		warnx("\"%s\": unknown command", string);
481		return (NULL);
482	}
483	return (cmds[found]);
484}
485
486/*
487 * See if string matches a prefix of "cmd" (or an alias) case insensitively
488 */
489static int
490MatchCommand(const struct ngcmd *cmd, const char *s)
491{
492	int a;
493
494	/* Try to match command, ignoring the usage stuff */
495	if (strlen(s) <= strcspn(cmd->cmd, WHITESPACE)) {
496		if (strncasecmp(s, cmd->cmd, strlen(s)) == 0)
497			return (1);
498	}
499
500	/* Try to match aliases */
501	for (a = 0; a < MAX_CMD_ALIAS && cmd->aliases[a] != NULL; a++) {
502		if (strlen(cmd->aliases[a]) >= strlen(s)) {
503			if (strncasecmp(s, cmd->aliases[a], strlen(s)) == 0)
504				return (1);
505		}
506	}
507
508	/* No match */
509	return (0);
510}
511
512/*
513 * ReadCmd()
514 */
515static int
516ReadCmd(int ac, char **av)
517{
518	FILE *fp;
519	int rtn;
520
521	/* Open file */
522	switch (ac) {
523	case 2:
524		if ((fp = fopen(av[1], "r")) == NULL) {
525			warn("%s", av[1]);
526			return (CMDRTN_ERROR);
527		}
528		break;
529	default:
530		return (CMDRTN_USAGE);
531	}
532
533	/* Process it */
534	rtn = ReadFile(fp);
535	fclose(fp);
536	return (rtn);
537}
538
539/*
540 * HelpCmd()
541 */
542static int
543HelpCmd(int ac, char **av)
544{
545	const struct ngcmd *cmd;
546	int k;
547
548	switch (ac) {
549	case 0:
550	case 1:
551		/* Show all commands */
552		printf("Available commands:\n");
553		for (k = 0; cmds[k] != NULL; k++) {
554			char *s, buf[100];
555
556			cmd = cmds[k];
557			snprintf(buf, sizeof(buf), "%s", cmd->cmd);
558			for (s = buf; *s != '\0' && !isspace(*s); s++);
559			*s = '\0';
560			printf("  %-10s %s\n", buf, cmd->desc);
561		}
562		return (CMDRTN_OK);
563	default:
564		/* Show help on a specific command */
565		if ((cmd = FindCommand(av[1])) != NULL) {
566			printf("usage:    %s\n", cmd->cmd);
567			if (cmd->aliases[0] != NULL) {
568				int a = 0;
569
570				printf("Aliases:  ");
571				while (1) {
572					printf("%s", cmd->aliases[a++]);
573					if (a == MAX_CMD_ALIAS
574					    || cmd->aliases[a] == NULL) {
575						printf("\n");
576						break;
577					}
578					printf(", ");
579				}
580			}
581			printf("Summary:  %s\n", cmd->desc);
582			if (cmd->help != NULL) {
583				const char *s;
584				char buf[65];
585				int tot, len, done;
586
587				printf("Description:\n");
588				for (s = cmd->help; *s != '\0'; s += len) {
589					while (isspace(*s))
590						s++;
591					tot = snprintf(buf,
592					    sizeof(buf), "%s", s);
593					len = strlen(buf);
594					done = len == tot;
595					if (!done) {
596						while (len > 0
597						    && !isspace(buf[len-1]))
598							buf[--len] = '\0';
599					}
600					printf("  %s\n", buf);
601				}
602			}
603		}
604	}
605	return (CMDRTN_OK);
606}
607
608/*
609 * QuitCmd()
610 */
611static int
612QuitCmd(int ac __unused, char **av __unused)
613{
614	return (CMDRTN_QUIT);
615}
616
617/*
618 * Dump data in hex and ASCII form
619 */
620void
621DumpAscii(const u_char *buf, int len)
622{
623	char ch, sbuf[100];
624	int k, count;
625
626	for (count = 0; count < len; count += DUMP_BYTES_PER_LINE) {
627		snprintf(sbuf, sizeof(sbuf), "%04x:  ", count);
628		for (k = 0; k < DUMP_BYTES_PER_LINE; k++) {
629			if (count + k < len) {
630				snprintf(sbuf + strlen(sbuf),
631				    sizeof(sbuf) - strlen(sbuf),
632				    "%02x ", buf[count + k]);
633			} else {
634				snprintf(sbuf + strlen(sbuf),
635				    sizeof(sbuf) - strlen(sbuf), "   ");
636			}
637		}
638		snprintf(sbuf + strlen(sbuf), sizeof(sbuf) - strlen(sbuf), " ");
639		for (k = 0; k < DUMP_BYTES_PER_LINE; k++) {
640			if (count + k < len) {
641				ch = isprint(buf[count + k]) ?
642				    buf[count + k] : '.';
643				snprintf(sbuf + strlen(sbuf),
644				    sizeof(sbuf) - strlen(sbuf), "%c", ch);
645			} else {
646				snprintf(sbuf + strlen(sbuf),
647				    sizeof(sbuf) - strlen(sbuf), " ");
648			}
649		}
650		printf("%s\n", sbuf);
651	}
652}
653
654/*
655 * Usage()
656 */
657static void
658Usage(const char *msg)
659{
660	if (msg)
661		warnx("%s", msg);
662	fprintf(stderr,
663		"usage: ngctl [-d] [-f file] [-n name] [command ...]\n");
664	exit(EX_USAGE);
665}
666