5 * Copyright (c) 1996-1999 Whistle Communications, Inc.
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.
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
37 * $Whistle: main.c,v 1.12 1999/11/29 19:17:46 archie Exp $
40 #include <sys/cdefs.h>
41 __FBSDID("$FreeBSD$");
43 #include <sys/param.h>
44 #include <sys/socket.h>
45 #include <sys/select.h>
68 #define WHITESPACE " \t\r\n\v\f"
69 #define DUMP_BYTES_PER_LINE 16
71 /* Internal functions */
72 static int ReadFile(FILE *fp);
73 static void ReadSockets(fd_set *);
74 static int DoParseCommand(const char *line);
75 static int DoCommand(int ac, char **av);
76 static int DoInteractive(void);
77 static const struct ngcmd *FindCommand(const char *string);
78 static int MatchCommand(const struct ngcmd *cmd, const char *s);
79 static void Usage(const char *msg);
80 static int ReadCmd(int ac, char **av);
81 static int HelpCmd(int ac, char **av);
82 static int QuitCmd(int ac, char **av);
84 static volatile sig_atomic_t unblock;
85 static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
86 static pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
89 /* List of commands */
90 static const struct ngcmd *const cmds[] = {
111 /* Commands defined in this file */
112 const struct ngcmd read_cmd = {
115 "Read and execute commands from a file",
119 const struct ngcmd help_cmd = {
122 "Show command summary or get more help on a specific command",
126 const struct ngcmd quit_cmd = {
134 /* Our control and data sockets */
141 main(int ac, char *av[])
143 char name[NG_NODESIZ];
144 int interactive = isatty(0) && isatty(1);
148 /* Set default node name */
149 snprintf(name, sizeof(name), "ngctl%d", getpid());
151 /* Parse command line */
152 while ((ch = getopt(ac, av, "df:n:")) != -1) {
155 NgSetDebug(NgSetDebug(-1) + 1);
158 if (strcmp(optarg, "-") == 0)
160 else if ((fp = fopen(optarg, "r")) == NULL)
161 err(EX_NOINPUT, "%s", optarg);
164 snprintf(name, sizeof(name), "%s", optarg);
175 /* Create a new socket node */
176 if (NgMkSockNode(name, &csock, &dsock) < 0)
177 err(EX_OSERR, "can't create node");
179 /* Do commands as requested */
183 } else if (interactive) {
184 rtn = DoInteractive();
186 Usage("no command specified");
188 rtn = DoCommand(ac, av);
191 /* Convert command return code into system exit code */
208 * Process commands from a file
216 for (num = 1; fgets(line, sizeof(line), fp) != NULL; num++) {
219 if ((rtn = DoParseCommand(line)) != 0) {
220 warnx("line %d: error in file", num);
228 /* Signal handler for Monitor() thread. */
230 Unblock(int signal __unused)
237 * Thread that monitors csock and dsock while main thread
238 * can be blocked in el_gets().
241 Monitor(void *v __unused)
243 struct sigaction act;
244 const int maxfd = MAX(csock, dsock) + 1;
246 act.sa_handler = Unblock;
247 sigemptyset(&act.sa_mask);
249 sigaction(SIGUSR1, &act, NULL);
251 pthread_mutex_lock(&mutex);
255 /* See if any data or control messages are arriving. */
257 FD_SET(csock, &rfds);
258 FD_SET(dsock, &rfds);
260 if (select(maxfd, &rfds, NULL, NULL, NULL) <= 0) {
261 if (errno == EINTR) {
263 pthread_cond_wait(&cond, &mutex);
266 err(EX_OSERR, "select");
275 Prompt(EditLine *el __unused)
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.
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
298 HistEvent hev = { 0, "" };
300 (*help_cmd.func)(0, NULL);
301 pthread_create(&monitor, NULL, Monitor, NULL);
302 el = el_init(getprogname(), stdin, stdout, stderr);
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();
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);
320 if ((buf = el_gets(el, &count)) == NULL) {
324 history(hist, &hev, H_ENTER, buf);
325 pthread_kill(monitor, SIGUSR1);
326 pthread_mutex_lock(&mutex);
327 if (DoParseCommand(buf) == CMDRTN_QUIT)
329 pthread_cond_signal(&cond);
330 pthread_mutex_unlock(&mutex);
335 pthread_cancel(monitor);
337 return (CMDRTN_QUIT);
340 #else /* !EDITLINE */
343 * Interactive mode w/o libedit functionality.
348 const int maxfd = MAX(csock, dsock) + 1;
350 (*help_cmd.func)(0, NULL);
355 /* See if any data or control messages are arriving */
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) {
362 /* Issue prompt and wait for anything to happen */
363 printf("%s", PROMPT);
367 FD_SET(csock, &rfds);
368 FD_SET(dsock, &rfds);
369 if (select(maxfd, &rfds, NULL, NULL, NULL) < 0)
370 err(EX_OSERR, "select");
372 /* If not user input, print a newline first */
373 if (!FD_ISSET(0, &rfds))
379 /* Get any user input */
380 if (FD_ISSET(0, &rfds)) {
383 if (fgets(buf, sizeof(buf), stdin) == NULL) {
387 if (DoParseCommand(buf) == CMDRTN_QUIT)
391 return (CMDRTN_QUIT);
393 #endif /* !EDITLINE */
396 * Read and process data on netgraph control and data sockets.
399 ReadSockets(fd_set *rfds)
401 /* Display any incoming control message. */
402 if (FD_ISSET(csock, rfds))
405 /* Display any incoming data packet. */
406 if (FD_ISSET(dsock, rfds)) {
407 char hook[NG_HOOKSIZ];
411 /* Read packet from socket. */
412 if ((rl = NgAllocRecvData(dsock, &buf, hook)) < 0)
413 err(EX_OSERR, "reading hook \"%s\"", hook);
415 errx(EX_OSERR, "EOF from hook \"%s\"?", hook);
417 /* Write packet to stdout. */
418 printf("Rec'd data packet on hook \"%s\":\n", hook);
425 * Parse a command line and execute the command
428 DoParseCommand(const char *line)
434 for (ac = 0, av[0] = strtok((char *)line, WHITESPACE);
435 ac < MAX_ARGS - 1 && av[ac];
436 av[++ac] = strtok(NULL, WHITESPACE));
439 return (DoCommand(ac, av));
443 * Execute the command
446 DoCommand(int ac, char **av)
448 const struct ngcmd *cmd;
451 if (ac == 0 || *av[0] == 0)
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);
463 static const struct ngcmd *
464 FindCommand(const char *string)
468 for (k = 0; cmds[k] != NULL; k++) {
469 if (MatchCommand(cmds[k], string)) {
471 warnx("\"%s\": ambiguous command", string);
478 warnx("\"%s\": unknown command", string);
481 return (cmds[found]);
485 * See if string matches a prefix of "cmd" (or an alias) case insensitively
488 MatchCommand(const struct ngcmd *cmd, const char *s)
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)
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)
514 ReadCmd(int ac, char **av)
522 if ((fp = fopen(av[1], "r")) == NULL) {
524 return (CMDRTN_ERROR);
528 return (CMDRTN_USAGE);
541 HelpCmd(int ac, char **av)
543 const struct ngcmd *cmd;
549 /* Show all commands */
550 printf("Available commands:\n");
551 for (k = 0; cmds[k] != NULL; k++) {
555 snprintf(buf, sizeof(buf), "%s", cmd->cmd);
556 for (s = buf; *s != '\0' && !isspace(*s); s++);
558 printf(" %-10s %s\n", buf, cmd->desc);
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) {
570 printf("%s", cmd->aliases[a++]);
571 if (a == MAX_CMD_ALIAS
572 || cmd->aliases[a] == NULL) {
579 printf("Summary: %s\n", cmd->desc);
580 if (cmd->help != NULL) {
585 printf("Description:\n");
586 for (s = cmd->help; *s != '\0'; s += len) {
590 sizeof(buf), "%s", s);
595 && !isspace(buf[len-1]))
598 printf(" %s\n", buf);
610 QuitCmd(int ac __unused, char **av __unused)
612 return (CMDRTN_QUIT);
616 * Dump data in hex and ASCII form
619 DumpAscii(const u_char *buf, int len)
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]);
632 snprintf(sbuf + strlen(sbuf),
633 sizeof(sbuf) - strlen(sbuf), " ");
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);
644 snprintf(sbuf + strlen(sbuf),
645 sizeof(sbuf) - strlen(sbuf), " ");
648 printf("%s\n", sbuf);
656 Usage(const char *msg)
661 "usage: ngctl [-d] [-f file] [-n name] [command ...]\n");