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