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
close_ng_socks()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
main(int ac,char * av[])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 #ifdef FSTACK
239 ff_ipc_exit();
240 #endif
241 return (rtn);
242 }
243
244 /*
245 * Process commands from a file
246 */
247 static int
248 ReadFile(FILE *fp)
249 {
250 char line[LINE_MAX];
251 int num, rtn;
252
253 for (num = 1; fgets(line, sizeof(line), fp) != NULL; num++) {
254 if (*line == '#')
255 continue;
256 if ((rtn = DoParseCommand(line)) != 0) {
257 warnx("line %d: error in file", num);
258 return (rtn);
259 }
260 }
261 return (CMDRTN_OK);
262 }
263
264 #ifdef EDITLINE
265 #ifndef FSTACK
266 /* Signal handler for Monitor() thread. */
267 static void
268 Unblock(int signal __unused)
269 {
270
271 unblock = 1;
272 }
273
274 /*
275 * Thread that monitors csock and dsock while main thread
276 * can be blocked in el_gets().
277 */
278 static void *
279 Monitor(void *v __unused)
280 {
281 struct sigaction act;
282 const int maxfd = MAX(csock, dsock) + 1;
283
284 act.sa_handler = Unblock;
285 sigemptyset(&act.sa_mask);
286 act.sa_flags = 0;
287 sigaction(SIGUSR1, &act, NULL);
288
289 pthread_mutex_lock(&mutex);
290 for (;;) {
291 fd_set rfds;
292
293 /* See if any data or control messages are arriving. */
294 FD_ZERO(&rfds);
295 FD_SET(csock, &rfds);
296 FD_SET(dsock, &rfds);
297 unblock = 0;
298 if (select(maxfd, &rfds, NULL, NULL, NULL) <= 0) {
299 if (errno == EINTR) {
300 if (unblock == 1)
301 pthread_cond_wait(&cond, &mutex);
302 continue;
303 }
304 err(EX_OSERR, "select");
305 }
306 ReadSockets(&rfds);
307 }
308
309 return (NULL);
310 }
311 #endif
312
313 static char *
314 Prompt(EditLine *el __unused)
315 {
316
317 return (PROMPT);
318 }
319
320 /*
321 * Here we start a thread, that will monitor the netgraph
322 * sockets and catch any unexpected messages or data on them,
323 * that can arrive while user edits his/her commands.
324 *
325 * Whenever we expect data on netgraph sockets, we send signal
326 * to monitoring thread. The signal forces it to exit select()
327 * system call and sleep on condvar until we wake it. While
328 * monitoring thread sleeps, we can do our work with netgraph
329 * sockets.
330 */
331 static int
332 DoInteractive(void)
333 {
334 #ifndef FSTACK
335 pthread_t monitor;
336 #endif
337 EditLine *el;
338 History *hist;
339 HistEvent hev = { 0, "" };
340
341 (*help_cmd.func)(0, NULL);
342 #ifndef FSTACK
343 pthread_create(&monitor, NULL, Monitor, NULL);
344 #endif
345 el = el_init(getprogname(), stdin, stdout, stderr);
346 if (el == NULL)
347 return (CMDRTN_ERROR);
348 el_set(el, EL_PROMPT, Prompt);
349 el_set(el, EL_SIGNAL, 1);
350 el_set(el, EL_EDITOR, "emacs");
351 hist = history_init();
352 if (hist == NULL)
353 return (CMDRTN_ERROR);
354 history(hist, &hev, H_SETSIZE, 100);
355 history(hist, &hev, H_SETUNIQUE, 1);
356 el_set(el, EL_HIST, history, (const char *)hist);
357 el_source(el, NULL);
358
359 for (;;) {
360 const char *buf;
361 int count;
362
363 if ((buf = el_gets(el, &count)) == NULL) {
364 printf("\n");
365 break;
366 }
367 history(hist, &hev, H_ENTER, buf);
368 #ifndef FSTACK
369 pthread_kill(monitor, SIGUSR1);
370 pthread_mutex_lock(&mutex);
371 #endif
372 if (DoParseCommand(buf) == CMDRTN_QUIT) {
373 #ifndef FSTACK
374 pthread_mutex_unlock(&mutex);
375 #endif
376 break;
377 }
378 #ifndef FSTACK
379 pthread_cond_signal(&cond);
380 pthread_mutex_unlock(&mutex);
381 #endif
382 }
383
384 history_end(hist);
385 el_end(el);
386 #ifndef FSTACK
387 pthread_cancel(monitor);
388 #endif
389
390 return (CMDRTN_QUIT);
391 }
392
393 #else /* !EDITLINE */
394
395 /*
396 * Interactive mode w/o libedit functionality.
397 */
398 static int
399 DoInteractive(void)
400 {
401 const int maxfd = MAX(csock, dsock) + 1;
402
403 (*help_cmd.func)(0, NULL);
404 while (1) {
405 struct timeval tv;
406 fd_set rfds;
407
408 /* See if any data or control messages are arriving */
409 FD_ZERO(&rfds);
410 #ifndef FSTACK
411 FD_SET(csock, &rfds);
412 FD_SET(dsock, &rfds);
413 #endif
414 memset(&tv, 0, sizeof(tv));
415 if (select(maxfd, &rfds, NULL, NULL, &tv) <= 0) {
416
417 /* Issue prompt and wait for anything to happen */
418 printf("%s", PROMPT);
419 fflush(stdout);
420 FD_ZERO(&rfds);
421 FD_SET(0, &rfds);
422 #ifndef FSTACK
423 FD_SET(csock, &rfds);
424 FD_SET(dsock, &rfds);
425 #endif
426 if (select(maxfd, &rfds, NULL, NULL, NULL) < 0)
427 err(EX_OSERR, "select");
428
429 /* If not user input, print a newline first */
430 if (!FD_ISSET(0, &rfds))
431 printf("\n");
432 }
433
434 #ifndef FSTACK
435 ReadSockets(&rfds);
436 #endif
437
438 /* Get any user input */
439 if (FD_ISSET(0, &rfds)) {
440 char buf[LINE_MAX];
441
442 if (fgets(buf, sizeof(buf), stdin) == NULL) {
443 printf("\n");
444 break;
445 }
446 if (DoParseCommand(buf) == CMDRTN_QUIT)
447 break;
448 }
449 }
450 return (CMDRTN_QUIT);
451 }
452 #endif /* !EDITLINE */
453
454 #ifndef FSTACK
455 /*
456 * Read and process data on netgraph control and data sockets.
457 */
458 static void
459 ReadSockets(fd_set *rfds)
460 {
461 /* Display any incoming control message. */
462 if (FD_ISSET(csock, rfds))
463 MsgRead();
464
465 /* Display any incoming data packet. */
466 if (FD_ISSET(dsock, rfds)) {
467 char hook[NG_HOOKSIZ];
468 u_char *buf;
469 int rl;
470
471 /* Read packet from socket. */
472 if ((rl = NgAllocRecvData(dsock, &buf, hook)) < 0)
473 err(EX_OSERR, "reading hook \"%s\"", hook);
474 if (rl == 0)
475 errx(EX_OSERR, "EOF from hook \"%s\"?", hook);
476
477 /* Write packet to stdout. */
478 printf("Rec'd data packet on hook \"%s\":\n", hook);
479 DumpAscii(buf, rl);
480 free(buf);
481 }
482 }
483 #endif
484
485 /*
486 * Parse a command line and execute the command
487 */
488 static int
489 DoParseCommand(const char *line)
490 {
491 char *av[MAX_ARGS];
492 int ac;
493
494 /* Parse line */
495 for (ac = 0, av[0] = strtok((char *)line, WHITESPACE);
496 ac < MAX_ARGS - 1 && av[ac];
497 av[++ac] = strtok(NULL, WHITESPACE));
498
499 /* Do command */
500 return (DoCommand(ac, av));
501 }
502
503 /*
504 * Execute the command
505 */
506 static int
507 DoCommand(int ac, char **av)
508 {
509 const struct ngcmd *cmd;
510 int rtn;
511
512 if (ac == 0 || *av[0] == 0)
513 return (CMDRTN_OK);
514 if ((cmd = FindCommand(av[0])) == NULL)
515 return (CMDRTN_ERROR);
516 if ((rtn = (*cmd->func)(ac, av)) == CMDRTN_USAGE)
517 warnx("usage: %s", cmd->cmd);
518 return (rtn);
519 }
520
521 /*
522 * Find a command
523 */
524 static const struct ngcmd *
525 FindCommand(const char *string)
526 {
527 int k, found = -1;
528
529 for (k = 0; cmds[k] != NULL; k++) {
530 if (MatchCommand(cmds[k], string)) {
531 if (found != -1) {
532 warnx("\"%s\": ambiguous command", string);
533 return (NULL);
534 }
535 found = k;
536 }
537 }
538 if (found == -1) {
539 warnx("\"%s\": unknown command", string);
540 return (NULL);
541 }
542 return (cmds[found]);
543 }
544
545 /*
546 * See if string matches a prefix of "cmd" (or an alias) case insensitively
547 */
548 static int
549 MatchCommand(const struct ngcmd *cmd, const char *s)
550 {
551 int a;
552
553 /* Try to match command, ignoring the usage stuff */
554 if (strlen(s) <= strcspn(cmd->cmd, WHITESPACE)) {
555 if (strncasecmp(s, cmd->cmd, strlen(s)) == 0)
556 return (1);
557 }
558
559 /* Try to match aliases */
560 for (a = 0; a < MAX_CMD_ALIAS && cmd->aliases[a] != NULL; a++) {
561 if (strlen(cmd->aliases[a]) >= strlen(s)) {
562 if (strncasecmp(s, cmd->aliases[a], strlen(s)) == 0)
563 return (1);
564 }
565 }
566
567 /* No match */
568 return (0);
569 }
570
571 /*
572 * ReadCmd()
573 */
574 static int
575 ReadCmd(int ac, char **av)
576 {
577 FILE *fp;
578 int rtn;
579
580 /* Open file */
581 switch (ac) {
582 case 2:
583 if ((fp = fopen(av[1], "r")) == NULL) {
584 warn("%s", av[1]);
585 return (CMDRTN_ERROR);
586 }
587 break;
588 default:
589 return (CMDRTN_USAGE);
590 }
591
592 /* Process it */
593 rtn = ReadFile(fp);
594 fclose(fp);
595 return (rtn);
596 }
597
598 /*
599 * HelpCmd()
600 */
601 static int
602 HelpCmd(int ac, char **av)
603 {
604 const struct ngcmd *cmd;
605 int k;
606
607 switch (ac) {
608 case 0:
609 case 1:
610 /* Show all commands */
611 printf("Available commands:\n");
612 for (k = 0; cmds[k] != NULL; k++) {
613 char *s, buf[100];
614
615 cmd = cmds[k];
616 snprintf(buf, sizeof(buf), "%s", cmd->cmd);
617 for (s = buf; *s != '\0' && !isspace(*s); s++);
618 *s = '\0';
619 printf(" %-10s %s\n", buf, cmd->desc);
620 }
621 return (CMDRTN_OK);
622 default:
623 /* Show help on a specific command */
624 if ((cmd = FindCommand(av[1])) != NULL) {
625 printf("usage: %s\n", cmd->cmd);
626 if (cmd->aliases[0] != NULL) {
627 int a = 0;
628
629 printf("Aliases: ");
630 while (1) {
631 printf("%s", cmd->aliases[a++]);
632 if (a == MAX_CMD_ALIAS
633 || cmd->aliases[a] == NULL) {
634 printf("\n");
635 break;
636 }
637 printf(", ");
638 }
639 }
640 printf("Summary: %s\n", cmd->desc);
641 if (cmd->help != NULL) {
642 const char *s;
643 char buf[65];
644 int tot, len, done;
645
646 printf("Description:\n");
647 for (s = cmd->help; *s != '\0'; s += len) {
648 while (isspace(*s))
649 s++;
650 tot = snprintf(buf,
651 sizeof(buf), "%s", s);
652 len = strlen(buf);
653 done = len == tot;
654 if (!done) {
655 while (len > 0
656 && !isspace(buf[len-1]))
657 buf[--len] = '\0';
658 }
659 printf(" %s\n", buf);
660 }
661 }
662 }
663 }
664 return (CMDRTN_OK);
665 }
666
667 /*
668 * QuitCmd()
669 */
670 static int
671 QuitCmd(int ac __unused, char **av __unused)
672 {
673 return (CMDRTN_QUIT);
674 }
675
676 /*
677 * Dump data in hex and ASCII form
678 */
679 void
680 DumpAscii(const u_char *buf, int len)
681 {
682 char ch, sbuf[100];
683 int k, count;
684
685 for (count = 0; count < len; count += DUMP_BYTES_PER_LINE) {
686 snprintf(sbuf, sizeof(sbuf), "%04x: ", count);
687 for (k = 0; k < DUMP_BYTES_PER_LINE; k++) {
688 if (count + k < len) {
689 snprintf(sbuf + strlen(sbuf),
690 sizeof(sbuf) - strlen(sbuf),
691 "%02x ", buf[count + k]);
692 } else {
693 snprintf(sbuf + strlen(sbuf),
694 sizeof(sbuf) - strlen(sbuf), " ");
695 }
696 }
697 snprintf(sbuf + strlen(sbuf), sizeof(sbuf) - strlen(sbuf), " ");
698 for (k = 0; k < DUMP_BYTES_PER_LINE; k++) {
699 if (count + k < len) {
700 ch = isprint(buf[count + k]) ?
701 buf[count + k] : '.';
702 snprintf(sbuf + strlen(sbuf),
703 sizeof(sbuf) - strlen(sbuf), "%c", ch);
704 } else {
705 snprintf(sbuf + strlen(sbuf),
706 sizeof(sbuf) - strlen(sbuf), " ");
707 }
708 }
709 printf("%s\n", sbuf);
710 }
711 }
712
713 /*
714 * Usage()
715 */
716 static void
717 Usage(const char *msg)
718 {
719 if (msg)
720 warnx("%s", msg);
721 fprintf(stderr,
722 #ifndef FSTACK
723 "usage: ngctl [-d] [-f file] [-n name] [command ...]\n");
724 #else
725 "usage: ngctl -p <f-stack proc_id> [-d] [-f file] [-n name] [command ...]\n");
726
727 ff_ipc_exit();
728 #endif
729 exit(EX_USAGE);
730 }
731