xref: /freebsd/usr.sbin/ngctl/main.c (revision 6990ffd8a95caaba6858ad44ff1b3157d1efba8f)
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  * $FreeBSD$
38  * $Whistle: main.c,v 1.12 1999/11/29 19:17:46 archie Exp $
39  */
40 
41 #include "ngctl.h"
42 
43 #define PROMPT			"+ "
44 #define MAX_ARGS		512
45 #define WHITESPACE		" \t\r\n\v\f"
46 #define DUMP_BYTES_PER_LINE	16
47 
48 /* Internal functions */
49 static int	ReadFile(FILE *fp);
50 static int	DoParseCommand(char *line);
51 static int	DoCommand(int ac, char **av);
52 static int	DoInteractive(void);
53 static const	struct ngcmd *FindCommand(const char *string);
54 static int	MatchCommand(const struct ngcmd *cmd, const char *s);
55 static void	Usage(const char *msg);
56 static int	ReadCmd(int ac, char **av);
57 static int	HelpCmd(int ac, char **av);
58 static int	QuitCmd(int ac, char **av);
59 
60 /* List of commands */
61 static const struct ngcmd *const cmds[] = {
62 	&config_cmd,
63 	&connect_cmd,
64 	&debug_cmd,
65 	&help_cmd,
66 	&list_cmd,
67 	&mkpeer_cmd,
68 	&msg_cmd,
69 	&name_cmd,
70 	&read_cmd,
71 	&rmhook_cmd,
72 	&show_cmd,
73 	&shutdown_cmd,
74 	&status_cmd,
75 	&types_cmd,
76 	&quit_cmd,
77 	NULL
78 };
79 
80 /* Commands defined in this file */
81 const struct ngcmd read_cmd = {
82 	ReadCmd,
83 	"read <filename>",
84 	"Read and execute commands from a file",
85 	NULL,
86 	{ "source", "." }
87 };
88 const struct ngcmd help_cmd = {
89 	HelpCmd,
90 	"help [command]",
91 	"Show command summary or get more help on a specific command",
92 	NULL,
93 	{ "?" }
94 };
95 const struct ngcmd quit_cmd = {
96 	QuitCmd,
97 	"quit",
98 	"Exit program",
99 	NULL,
100 	{ "exit" }
101 };
102 
103 /* Our control and data sockets */
104 int	csock, dsock;
105 
106 /*
107  * main()
108  */
109 int
110 main(int ac, char *av[])
111 {
112 	char	name[NG_NODELEN + 1];
113 	int	interactive = isatty(0) && isatty(1);
114 	FILE	*fp = NULL;
115 	int	ch, rtn = 0;
116 
117 	/* Set default node name */
118 	snprintf(name, sizeof(name), "ngctl%d", getpid());
119 
120 	/* Parse command line */
121 	while ((ch = getopt(ac, av, "df:n:")) != EOF) {
122 		switch (ch) {
123 		case 'd':
124 			NgSetDebug(NgSetDebug(-1) + 1);
125 			break;
126 		case 'f':
127 			if (strcmp(optarg, "-") == 0)
128 				fp = stdin;
129 			else if ((fp = fopen(optarg, "r")) == NULL)
130 				err(EX_NOINPUT, "%s", optarg);
131 			break;
132 		case 'n':
133 			snprintf(name, sizeof(name), "%s", optarg);
134 			break;
135 		case '?':
136 		default:
137 			Usage((char *)NULL);
138 			break;
139 		}
140 	}
141 	ac -= optind;
142 	av += optind;
143 
144 	/* Create a new socket node */
145 	if (NgMkSockNode(name, &csock, &dsock) < 0)
146 		err(EX_OSERR, "can't create node");
147 
148 	/* Do commands as requested */
149 	if (ac == 0) {
150 		if (fp != NULL) {
151 			rtn = ReadFile(fp);
152 		} else if (interactive) {
153 			rtn = DoInteractive();
154 		} else
155 			Usage("no command specified");
156 	} else {
157 		rtn = DoCommand(ac, av);
158 	}
159 
160 	/* Convert command return code into system exit code */
161 	switch (rtn) {
162 	case CMDRTN_OK:
163 	case CMDRTN_QUIT:
164 		rtn = 0;
165 		break;
166 	case CMDRTN_USAGE:
167 		rtn = EX_USAGE;
168 		break;
169 	case CMDRTN_ERROR:
170 		rtn = EX_OSERR;
171 		break;
172 	}
173 	return(rtn);
174 }
175 
176 /*
177  * Process commands from a file
178  */
179 static int
180 ReadFile(FILE *fp)
181 {
182 	char line[LINE_MAX];
183 	int num, rtn;
184 
185 	for (num = 1; fgets(line, sizeof(line), fp) != NULL; num++) {
186 		if (*line == '#')
187 			continue;
188 		if ((rtn = DoParseCommand(line)) != 0) {
189 			warnx("line %d: error in file", num);
190 			return(rtn);
191 		}
192 	}
193 	return(CMDRTN_OK);
194 }
195 
196 /*
197  * Interactive mode
198  */
199 static int
200 DoInteractive(void)
201 {
202 	const int maxfd = MAX(csock, dsock) + 1;
203 
204 	(*help_cmd.func)(0, NULL);
205 	while (1) {
206 		struct timeval tv;
207 		fd_set rfds;
208 
209 		/* See if any data or control messages are arriving */
210 		FD_ZERO(&rfds);
211 		FD_SET(csock, &rfds);
212 		FD_SET(dsock, &rfds);
213 		memset(&tv, 0, sizeof(tv));
214 		if (select(maxfd, &rfds, NULL, NULL, &tv) <= 0) {
215 
216 			/* Issue prompt and wait for anything to happen */
217 			printf("%s", PROMPT);
218 			fflush(stdout);
219 			FD_ZERO(&rfds);
220 			FD_SET(0, &rfds);
221 			FD_SET(csock, &rfds);
222 			FD_SET(dsock, &rfds);
223 			if (select(maxfd, &rfds, NULL, NULL, NULL) < 0)
224 				err(EX_OSERR, "select");
225 
226 			/* If not user input, print a newline first */
227 			if (!FD_ISSET(0, &rfds))
228 				printf("\n");
229 		}
230 
231 		/* Display any incoming control message */
232 		if (FD_ISSET(csock, &rfds))
233 			MsgRead();
234 
235 		/* Display any incoming data packet */
236 		if (FD_ISSET(dsock, &rfds)) {
237 			u_char buf[8192];
238 			char hook[NG_HOOKLEN + 1];
239 			int rl;
240 
241 			/* Read packet from socket */
242 			if ((rl = NgRecvData(dsock,
243 			    buf, sizeof(buf), hook)) < 0)
244 				err(EX_OSERR, "reading hook \"%s\"", hook);
245 			if (rl == 0)
246 				errx(EX_OSERR, "EOF from hook \"%s\"?", hook);
247 
248 			/* Write packet to stdout */
249 			printf("Rec'd data packet on hook \"%s\":\n", hook);
250 			DumpAscii(buf, rl);
251 		}
252 
253 		/* Get any user input */
254 		if (FD_ISSET(0, &rfds)) {
255 			char buf[LINE_MAX];
256 
257 			if (fgets(buf, sizeof(buf), stdin) == NULL) {
258 				printf("\n");
259 				break;
260 			}
261 			if (DoParseCommand(buf) == CMDRTN_QUIT)
262 				break;
263 		}
264 	}
265 	return(CMDRTN_QUIT);
266 }
267 
268 /*
269  * Parse a command line and execute the command
270  */
271 static int
272 DoParseCommand(char *line)
273 {
274 	char *av[MAX_ARGS];
275 	int ac;
276 
277 	/* Parse line */
278 	for (ac = 0, av[0] = strtok(line, WHITESPACE);
279 	    ac < MAX_ARGS - 1 && av[ac];
280 	    av[++ac] = strtok(NULL, WHITESPACE));
281 
282 	/* Do command */
283 	return(DoCommand(ac, av));
284 }
285 
286 /*
287  * Execute the command
288  */
289 static int
290 DoCommand(int ac, char **av)
291 {
292 	const struct ngcmd *cmd;
293 	int rtn;
294 
295 	if (ac == 0 || *av[0] == 0)
296 		return(CMDRTN_OK);
297 	if ((cmd = FindCommand(av[0])) == NULL)
298 		return(CMDRTN_ERROR);
299 	if ((rtn = (*cmd->func)(ac, av)) == CMDRTN_USAGE)
300 		warnx("usage: %s", cmd->cmd);
301 	return(rtn);
302 }
303 
304 /*
305  * Find a command
306  */
307 static const struct ngcmd *
308 FindCommand(const char *string)
309 {
310 	int k, found = -1;
311 
312 	for (k = 0; cmds[k] != NULL; k++) {
313 		if (MatchCommand(cmds[k], string)) {
314 			if (found != -1) {
315 				warnx("\"%s\": ambiguous command", string);
316 				return(NULL);
317 			}
318 			found = k;
319 		}
320 	}
321 	if (found == -1) {
322 		warnx("\"%s\": unknown command", string);
323 		return(NULL);
324 	}
325 	return(cmds[found]);
326 }
327 
328 /*
329  * See if string matches a prefix of "cmd" (or an alias) case insensitively
330  */
331 static int
332 MatchCommand(const struct ngcmd *cmd, const char *s)
333 {
334 	int a;
335 
336 	/* Try to match command, ignoring the usage stuff */
337 	if (strlen(s) <= strcspn(cmd->cmd, WHITESPACE)) {
338 		if (strncasecmp(s, cmd->cmd, strlen(s)) == 0)
339 			return (1);
340 	}
341 
342 	/* Try to match aliases */
343 	for (a = 0; a < MAX_CMD_ALIAS && cmd->aliases[a] != NULL; a++) {
344 		if (strlen(cmd->aliases[a]) >= strlen(s)) {
345 			if (strncasecmp(s, cmd->aliases[a], strlen(s)) == 0)
346 				return (1);
347 		}
348 	}
349 
350 	/* No match */
351 	return (0);
352 }
353 
354 /*
355  * ReadCmd()
356  */
357 static int
358 ReadCmd(int ac, char **av)
359 {
360 	FILE *fp;
361 	int rtn;
362 
363 	/* Open file */
364 	switch (ac) {
365 	case 2:
366 		if ((fp = fopen(av[1], "r")) == NULL) {
367 			warn("%s", av[1]);
368 			return(CMDRTN_ERROR);
369 		}
370 		break;
371 	default:
372 		return(CMDRTN_USAGE);
373 	}
374 
375 	/* Process it */
376 	rtn = ReadFile(fp);
377 	fclose(fp);
378 	return(rtn);
379 }
380 
381 /*
382  * HelpCmd()
383  */
384 static int
385 HelpCmd(int ac, char **av)
386 {
387 	const struct ngcmd *cmd;
388 	int k;
389 
390 	switch (ac) {
391 	case 0:
392 	case 1:
393 		/* Show all commands */
394 		printf("Available commands:\n");
395 		for (k = 0; cmds[k] != NULL; k++) {
396 			char *s, buf[100];
397 
398 			cmd = cmds[k];
399 			snprintf(buf, sizeof(buf), "%s", cmd->cmd);
400 			for (s = buf; *s != '\0' && !isspace(*s); s++);
401 			*s = '\0';
402 			printf("  %-10s %s\n", buf, cmd->desc);
403 		}
404 		return(CMDRTN_OK);
405 	default:
406 		/* Show help on a specific command */
407 		if ((cmd = FindCommand(av[1])) != NULL) {
408 			printf("Usage:    %s\n", cmd->cmd);
409 			if (cmd->aliases[0] != NULL) {
410 				int a = 0;
411 
412 				printf("Aliases:  ");
413 				while (1) {
414 					printf("%s", cmd->aliases[a++]);
415 					if (a == MAX_CMD_ALIAS
416 					    || cmd->aliases[a] == NULL) {
417 						printf("\n");
418 						break;
419 					}
420 					printf(", ");
421 				}
422 			}
423 			printf("Summary:  %s\n", cmd->desc);
424 			if (cmd->help != NULL) {
425 				const char *s;
426 				char buf[65];
427 				int tot, len, done;
428 
429 				printf("Description:\n");
430 				for (s = cmd->help; *s != '\0'; s += len) {
431 					while (isspace(*s))
432 						s++;
433 					tot = snprintf(buf,
434 					    sizeof(buf), "%s", s);
435 					len = strlen(buf);
436 					done = len == tot;
437 					if (!done) {
438 						while (len > 0
439 						    && !isspace(buf[len-1]))
440 							buf[--len] = '\0';
441 					}
442 					printf("  %s\n", buf);
443 				}
444 			}
445 		}
446 	}
447 	return(CMDRTN_OK);
448 }
449 
450 /*
451  * QuitCmd()
452  */
453 static int
454 QuitCmd(int ac, char **av)
455 {
456 	return(CMDRTN_QUIT);
457 }
458 
459 /*
460  * Dump data in hex and ASCII form
461  */
462 void
463 DumpAscii(const u_char *buf, int len)
464 {
465 	char ch, sbuf[100];
466 	int k, count;
467 
468 	for (count = 0; count < len; count += DUMP_BYTES_PER_LINE) {
469 		snprintf(sbuf, sizeof(sbuf), "%04x:  ", count);
470 		for (k = 0; k < DUMP_BYTES_PER_LINE; k++) {
471 			if (count + k < len) {
472 				snprintf(sbuf + strlen(sbuf),
473 				    sizeof(sbuf) - strlen(sbuf),
474 				    "%02x ", buf[count + k]);
475 			} else {
476 				snprintf(sbuf + strlen(sbuf),
477 				    sizeof(sbuf) - strlen(sbuf), "   ");
478 			}
479 		}
480 		snprintf(sbuf + strlen(sbuf), sizeof(sbuf) - strlen(sbuf), " ");
481 		for (k = 0; k < DUMP_BYTES_PER_LINE; k++) {
482 			if (count + k < len) {
483 				ch = isprint(buf[count + k]) ?
484 				    buf[count + k] : '.';
485 				snprintf(sbuf + strlen(sbuf),
486 				    sizeof(sbuf) - strlen(sbuf), "%c", ch);
487 			} else {
488 				snprintf(sbuf + strlen(sbuf),
489 				    sizeof(sbuf) - strlen(sbuf), " ");
490 			}
491 		}
492 		printf("%s\n", sbuf);
493 	}
494 }
495 
496 /*
497  * Usage()
498  */
499 static void
500 Usage(const char *msg)
501 {
502 	if (msg)
503 		warnx("%s", msg);
504 	errx(EX_USAGE, "usage: ngctl [-d] [-f file] [-n name] [command ...]");
505 }
506 
507