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