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