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