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