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/param.h>
41 #include <sys/socket.h>
42 #include <sys/select.h>
65 #define WHITESPACE " \t\r\n\v\f"
66 #define DUMP_BYTES_PER_LINE 16
68 /* Internal functions */
69 static int ReadFile(FILE *fp);
70 static void ReadSockets(fd_set *);
71 static int DoParseCommand(const char *line);
72 static int DoCommand(int ac, char **av);
73 static int DoInteractive(void);
74 static const struct ngcmd *FindCommand(const char *string);
75 static int MatchCommand(const struct ngcmd *cmd, const char *s);
76 static void Usage(const char *msg);
77 static int ReadCmd(int ac, char **av);
78 static int HelpCmd(int ac, char **av);
79 static int QuitCmd(int ac, char **av);
81 static volatile sig_atomic_t unblock;
82 static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
83 static pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
86 /* List of commands */
87 static const struct ngcmd *const cmds[] = {
108 /* Commands defined in this file */
109 const struct ngcmd read_cmd = {
112 "Read and execute commands from a file",
116 const struct ngcmd help_cmd = {
119 "Show command summary or get more help on a specific command",
123 const struct ngcmd quit_cmd = {
131 /* Our control and data sockets */
138 main(int ac, char *av[])
140 char name[NG_NODESIZ];
141 int interactive = isatty(0) && isatty(1);
145 /* Set default node name */
146 snprintf(name, sizeof(name), "ngctl%d", getpid());
148 /* Parse command line */
149 while ((ch = getopt(ac, av, "df:n:")) != -1) {
152 NgSetDebug(NgSetDebug(-1) + 1);
155 if (strcmp(optarg, "-") == 0)
157 else if ((fp = fopen(optarg, "r")) == NULL)
158 err(EX_NOINPUT, "%s", optarg);
161 snprintf(name, sizeof(name), "%s", optarg);
172 /* Create a new socket node */
173 if (NgMkSockNode(name, &csock, &dsock) < 0)
174 err(EX_OSERR, "can't create node");
176 /* Do commands as requested */
180 } else if (interactive) {
181 rtn = DoInteractive();
183 Usage("no command specified");
185 rtn = DoCommand(ac, av);
188 /* Convert command return code into system exit code */
205 * Process commands from a file
213 for (num = 1; fgets(line, sizeof(line), fp) != NULL; num++) {
216 if ((rtn = DoParseCommand(line)) != 0) {
217 warnx("line %d: error in file", num);
225 /* Signal handler for Monitor() thread. */
227 Unblock(int signal __unused)
234 * Thread that monitors csock and dsock while main thread
235 * can be blocked in el_gets().
238 Monitor(void *v __unused)
240 struct sigaction act;
241 const int maxfd = MAX(csock, dsock) + 1;
243 act.sa_handler = Unblock;
244 sigemptyset(&act.sa_mask);
246 sigaction(SIGUSR1, &act, NULL);
248 pthread_mutex_lock(&mutex);
252 /* See if any data or control messages are arriving. */
254 FD_SET(csock, &rfds);
255 FD_SET(dsock, &rfds);
257 if (select(maxfd, &rfds, NULL, NULL, NULL) <= 0) {
258 if (errno == EINTR) {
260 pthread_cond_wait(&cond, &mutex);
263 err(EX_OSERR, "select");
272 Prompt(EditLine *el __unused)
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.
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
295 HistEvent hev = { 0, "" };
297 (*help_cmd.func)(0, NULL);
298 pthread_create(&monitor, NULL, Monitor, NULL);
299 el = el_init(getprogname(), stdin, stdout, stderr);
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();
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);
317 if ((buf = el_gets(el, &count)) == NULL) {
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);
328 pthread_cond_signal(&cond);
329 pthread_mutex_unlock(&mutex);
334 pthread_cancel(monitor);
336 return (CMDRTN_QUIT);
339 #else /* !EDITLINE */
342 * Interactive mode w/o libedit functionality.
347 const int maxfd = MAX(csock, dsock) + 1;
349 (*help_cmd.func)(0, NULL);
354 /* See if any data or control messages are arriving */
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) {
361 /* Issue prompt and wait for anything to happen */
362 printf("%s", PROMPT);
366 FD_SET(csock, &rfds);
367 FD_SET(dsock, &rfds);
368 if (select(maxfd, &rfds, NULL, NULL, NULL) < 0)
369 err(EX_OSERR, "select");
371 /* If not user input, print a newline first */
372 if (!FD_ISSET(0, &rfds))
378 /* Get any user input */
379 if (FD_ISSET(0, &rfds)) {
382 if (fgets(buf, sizeof(buf), stdin) == NULL) {
386 if (DoParseCommand(buf) == CMDRTN_QUIT)
390 return (CMDRTN_QUIT);
392 #endif /* !EDITLINE */
395 * Read and process data on netgraph control and data sockets.
398 ReadSockets(fd_set *rfds)
400 /* Display any incoming control message. */
401 if (FD_ISSET(csock, rfds))
404 /* Display any incoming data packet. */
405 if (FD_ISSET(dsock, rfds)) {
406 char hook[NG_HOOKSIZ];
410 /* Read packet from socket. */
411 if ((rl = NgAllocRecvData(dsock, &buf, hook)) < 0)
412 err(EX_OSERR, "reading hook \"%s\"", hook);
414 errx(EX_OSERR, "EOF from hook \"%s\"?", hook);
416 /* Write packet to stdout. */
417 printf("Rec'd data packet on hook \"%s\":\n", hook);
424 * Parse a command line and execute the command
427 DoParseCommand(const char *line)
433 for (ac = 0, av[0] = strtok((char *)line, WHITESPACE);
434 ac < MAX_ARGS - 1 && av[ac];
435 av[++ac] = strtok(NULL, WHITESPACE));
438 return (DoCommand(ac, av));
442 * Execute the command
445 DoCommand(int ac, char **av)
447 const struct ngcmd *cmd;
450 if (ac == 0 || *av[0] == 0)
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);
462 static const struct ngcmd *
463 FindCommand(const char *string)
467 for (k = 0; cmds[k] != NULL; k++) {
468 if (MatchCommand(cmds[k], string)) {
470 warnx("\"%s\": ambiguous command", string);
477 warnx("\"%s\": unknown command", string);
480 return (cmds[found]);
484 * See if string matches a prefix of "cmd" (or an alias) case insensitively
487 MatchCommand(const struct ngcmd *cmd, const char *s)
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)
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)
513 ReadCmd(int ac, char **av)
521 if ((fp = fopen(av[1], "r")) == NULL) {
523 return (CMDRTN_ERROR);
527 return (CMDRTN_USAGE);
540 HelpCmd(int ac, char **av)
542 const struct ngcmd *cmd;
548 /* Show all commands */
549 printf("Available commands:\n");
550 for (k = 0; cmds[k] != NULL; k++) {
554 snprintf(buf, sizeof(buf), "%s", cmd->cmd);
555 for (s = buf; *s != '\0' && !isspace(*s); s++);
557 printf(" %-10s %s\n", buf, cmd->desc);
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) {
569 printf("%s", cmd->aliases[a++]);
570 if (a == MAX_CMD_ALIAS
571 || cmd->aliases[a] == NULL) {
578 printf("Summary: %s\n", cmd->desc);
579 if (cmd->help != NULL) {
584 printf("Description:\n");
585 for (s = cmd->help; *s != '\0'; s += len) {
589 sizeof(buf), "%s", s);
594 && !isspace(buf[len-1]))
597 printf(" %s\n", buf);
609 QuitCmd(int ac __unused, char **av __unused)
611 return (CMDRTN_QUIT);
615 * Dump data in hex and ASCII form
618 DumpAscii(const u_char *buf, int len)
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]);
631 snprintf(sbuf + strlen(sbuf),
632 sizeof(sbuf) - strlen(sbuf), " ");
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);
643 snprintf(sbuf + strlen(sbuf),
644 sizeof(sbuf) - strlen(sbuf), " ");
647 printf("%s\n", sbuf);
655 Usage(const char *msg)
660 "usage: ngctl [-d] [-f file] [-n name] [command ...]\n");