1 /* -*- mode: c; c-file-style: "openbsd" -*- */
3 * Copyright (c) 2008 Vincent Bernat <bernat@luffy.cx>
5 * Permission to use, copy, modify, and/or distribute this software for any
6 * purpose with or without fee is hereby granted, provided that the above
7 * copyright notice and this permission notice appear in all copies.
9 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
10 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
11 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
12 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
13 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
14 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
15 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
25 #include <sys/types.h>
27 #include <sys/socket.h>
29 #include <arpa/inet.h>
32 #include <sys/queue.h>
36 #ifdef HAVE___PROGNAME
37 extern const char *__progname
;
39 # define __progname "lldpcli"
42 /* Global for completion */
43 static struct cmd_node
*root
= NULL
;
44 const char *ctlname
= NULL
;
47 is_lldpctl(const char *name
)
49 static int last_result
= -1;
50 if (last_result
== -1 && name
) {
51 char *basec
= strdup(name
);
53 char *bname
= basename(basec
);
54 last_result
= (!strcmp(bname
, "lldpctl"));
57 return (last_result
== -1)?0:last_result
;
63 fprintf(stderr
, "Usage: %s [OPTIONS ...] [COMMAND ...]\n", __progname
);
64 fprintf(stderr
, "Version: %s\n", PACKAGE_STRING
);
66 fprintf(stderr
, "\n");
68 fprintf(stderr
, "-d Enable more debugging information.\n");
69 fprintf(stderr
, "-u Specify the Unix-domain socket used for communication with lldpd(8).\n");
70 fprintf(stderr
, "-f format Choose output format (plain, keyvalue or xml).\n");
71 if (!is_lldpctl(NULL
))
72 fprintf(stderr
, "-c Read the provided configuration file.\n");
74 fprintf(stderr
, "\n");
76 fprintf(stderr
, "see manual page lldpcli(8) for more information\n");
83 /* Check we can access the control socket with read/write
84 * privileges. The `access()` function uses the real UID and real GID,
85 * therefore we don't have to mangle with our identity. */
86 return (ctlname
&& access(ctlname
, R_OK
|W_OK
) == 0);
93 int privileged
= is_privileged();
94 if (isatty(STDIN_FILENO
)) {
96 return "[lldpcli] # ";
97 return "[lldpcli] $ ";
102 static int must_exit
= 0;
104 * Exit the interpreter.
107 cmd_exit(struct lldpctl_conn_t
*conn
, struct writer
*w
,
108 struct cmd_env
*env
, void *arg
)
110 log_info("lldpctl", "quit lldpcli");
116 * Send an "update" request.
119 cmd_update(struct lldpctl_conn_t
*conn
, struct writer
*w
,
120 struct cmd_env
*env
, void *arg
)
122 log_info("lldpctl", "ask for global update");
124 lldpctl_atom_t
*config
= lldpctl_get_configuration(conn
);
125 if (config
== NULL
) {
126 log_warnx("lldpctl", "unable to get configuration from lldpd. %s",
127 lldpctl_last_strerror(conn
));
130 if (lldpctl_atom_set_int(config
,
131 lldpctl_k_config_tx_interval
, -1) == NULL
) {
132 log_warnx("lldpctl", "unable to ask lldpd for immediate retransmission. %s",
133 lldpctl_last_strerror(conn
));
134 lldpctl_atom_dec_ref(config
);
137 log_info("lldpctl", "immediate retransmission requested successfuly");
138 lldpctl_atom_dec_ref(config
);
143 * Pause or resume execution of lldpd.
145 * @param conn The connection to lldpd.
146 * @param pause 1 if we want to pause lldpd, 0 otherwise
147 * @return 1 on success, 0 on error
150 cmd_pause_resume(lldpctl_conn_t
*conn
, int pause
)
152 lldpctl_atom_t
*config
= lldpctl_get_configuration(conn
);
153 if (config
== NULL
) {
154 log_warnx("lldpctl", "unable to get configuration from lldpd. %s",
155 lldpctl_last_strerror(conn
));
158 if (lldpctl_atom_get_int(config
, lldpctl_k_config_paused
) == pause
) {
159 log_info("lldpctl", "lldpd is already %s",
160 pause
?"paused":"resumed");
161 lldpctl_atom_dec_ref(config
);
164 if (lldpctl_atom_set_int(config
,
165 lldpctl_k_config_paused
, pause
) == NULL
) {
166 log_warnx("lldpctl", "unable to ask lldpd to %s operations. %s",
167 pause
?"pause":"resume",
168 lldpctl_last_strerror(conn
));
169 lldpctl_atom_dec_ref(config
);
172 log_info("lldpctl", "lldpd should %s operations",
173 pause
?"pause":"resume");
174 lldpctl_atom_dec_ref(config
);
178 cmd_pause(struct lldpctl_conn_t
*conn
, struct writer
*w
,
179 struct cmd_env
*env
, void *arg
) {
181 return cmd_pause_resume(conn
, 1);
184 cmd_resume(struct lldpctl_conn_t
*conn
, struct writer
*w
,
185 struct cmd_env
*env
, void *arg
) {
187 return cmd_pause_resume(conn
, 0);
191 #ifdef HAVE_LIBREADLINE
193 _cmd_complete(int all
)
198 size_t len
= strlen(rl_line_buffer
);
199 char *line
= malloc(len
+ 2);
200 if (!line
) return -1;
201 strlcpy(line
, rl_line_buffer
, len
+ 2);
202 line
[rl_point
] = 2; /* empty character, will force a word */
203 line
[rl_point
+1] = 0;
205 if (tokenize_line(line
, &argc
, &argv
) != 0)
208 char *compl = commands_complete(root
, argc
, (const char **)argv
, all
);
209 if (compl && strlen(argv
[argc
-1]) < strlen(compl)) {
210 if (rl_insert_text(compl + strlen(argv
[argc
-1])) < 0) {
218 /* No completion or several completion available. */
220 fprintf(stderr
, "\n");
221 rl_forced_update_display();
225 tokenize_free(argc
, argv
);
230 cmd_complete(int count
, int ch
)
232 return _cmd_complete(0);
236 cmd_help(int count
, int ch
)
238 return _cmd_complete(1);
242 readline(const char *p
)
244 static char line
[2048];
245 fprintf(stderr
, "%s", p
);
247 if (fgets(line
, sizeof(line
) - 2, stdin
) == NULL
)
254 * Execute a tokenized command and display its output.
256 * @param conn The connection to lldpd.
257 * @param fmt Output format.
258 * @param argc Number of arguments.
259 * @param argv Array of arguments.
260 * @return 0 if an error occurred, 1 otherwise
263 cmd_exec(lldpctl_conn_t
*conn
, const char *fmt
, int argc
, const char **argv
)
265 /* Init output formatter */
268 if (strcmp(fmt
, "plain") == 0) w
= txt_init(stdout
);
269 else if (strcmp(fmt
, "keyvalue") == 0) w
= kv_init(stdout
);
271 else if (strcmp(fmt
, "xml") == 0) w
= xml_init(stdout
);
274 else if (strcmp(fmt
, "json") == 0) w
= json_init(stdout
);
276 else w
= txt_init(stdout
);
278 /* Execute command */
279 int rc
= commands_execute(conn
, w
,
282 log_info("lldpctl", "an error occurred while executing last command");
291 * Execute a command line and display its output.
293 * @param conn The connection to lldpd.
294 * @param fmt Output format.
295 * @param line Line to execute.
296 * @return -1 if an error occurred, 0 if nothing was executed. 1 otherwise.
299 parse_and_exec(lldpctl_conn_t
*conn
, const char *fmt
, const char *line
)
301 int cargc
= 0; char **cargv
= NULL
;
303 log_debug("lldpctl", "tokenize command line");
304 n
= tokenize_line(line
, &cargc
, &cargv
);
307 log_warnx("lldpctl", "internal error while tokenizing");
310 log_warnx("lldpctl", "unmatched quotes");
314 n
= cmd_exec(conn
, fmt
, cargc
, (const char **)cargv
);
315 tokenize_free(cargc
, cargv
);
316 return (cargc
== 0)?0:
321 static struct cmd_node
*
324 root
= commands_root();
325 register_commands_show(root
);
326 register_commands_watch(root
);
327 if (is_privileged()) {
329 commands_new(root
, "update", "Update information and send LLDPU on all ports",
331 NEWLINE
, "Update information and send LLDPU on all ports",
332 NULL
, cmd_update
, NULL
);
333 register_commands_configure(root
);
335 commands_new(root
, "help", "Get help on a possible command",
336 NULL
, cmd_store_env_and_pop
, "help");
338 commands_new(root
, "pause", "Pause lldpd operations", NULL
, NULL
, NULL
),
339 NEWLINE
, "Pause lldpd operations", NULL
, cmd_pause
, NULL
);
341 commands_new(root
, "resume", "Resume lldpd operations", NULL
, NULL
, NULL
),
342 NEWLINE
, "Resume lldpd operations", NULL
, cmd_resume
, NULL
);
344 commands_new(root
, "exit", "Exit interpreter", NULL
, NULL
, NULL
),
345 NEWLINE
, "Exit interpreter", NULL
, cmd_exit
, NULL
);
350 TAILQ_ENTRY(input
) next
;
353 TAILQ_HEAD(inputs
, input
);
355 filter(const struct dirent
*dir
)
357 if (strlen(dir
->d_name
) < 5) return 0;
358 if (strcmp(dir
->d_name
+ strlen(dir
->d_name
) - 5, ".conf")) return 0;
363 * Append a new input file/directory to the list of inputs.
365 * @param arg Directory or file name to add.
366 * @param inputs List of inputs
367 * @param acceptdir 1 if we accept a directory, 0 otherwise
370 input_append(const char *arg
, struct inputs
*inputs
, int acceptdir
)
373 if (stat(arg
, &statbuf
) == -1) {
374 log_info("lldpctl", "cannot find configuration file/directory %s",
379 if (!S_ISDIR(statbuf
.st_mode
)) {
380 struct input
*input
= malloc(sizeof(struct input
));
382 log_warn("lldpctl", "not enough memory to process %s",
386 log_debug("lldpctl", "input: %s", arg
);
387 input
->name
= strdup(arg
);
388 TAILQ_INSERT_TAIL(inputs
, input
, next
);
392 log_debug("lldpctl", "skip directory %s",
397 struct dirent
**namelist
= NULL
;
398 int n
= scandir(arg
, &namelist
, filter
, alphasort
);
400 log_warnx("lldpctl", "unable to read directory %s",
404 for (int i
=0; i
< n
; i
++) {
406 if (asprintf(&fullname
, "%s/%s", arg
, namelist
[i
]->d_name
) != -1) {
407 input_append(fullname
, inputs
, 0);
416 main(int argc
, char *argv
[])
418 int ch
, debug
= 1, rc
= EXIT_FAILURE
;
419 const char *fmt
= "plain";
420 lldpctl_conn_t
*conn
= NULL
;
421 const char *options
= is_lldpctl(argv
[0])?"hdvf:":"hdsvf:c:u:";
424 struct inputs inputs
;
427 ctlname
= lldpctl_get_default_transport();
429 /* Initialize logging */
430 while ((ch
= getopt(argc
, argv
, options
)) != -1) {
432 case 'd': debug
++; break;
433 case 's': debug
--; break;
436 log_init(debug
, __progname
);
438 /* Get and parse command line options */
440 while ((ch
= getopt(argc
, argv
, options
)) != -1) {
451 fprintf(stdout
, "%s\n", PACKAGE_VERSION
);
459 input_append(optarg
, &inputs
, 1);
466 /* Register commands */
467 root
= register_commands();
469 /* Make a connection */
470 log_debug("lldpctl", "connect to lldpd");
471 conn
= lldpctl_new_name(ctlname
, NULL
, NULL
, NULL
);
472 if (conn
== NULL
) goto end
;
474 /* Process file inputs */
475 while (gotinputs
&& !TAILQ_EMPTY(&inputs
)) {
476 /* coverity[use_after_free]
477 TAILQ_REMOVE does the right thing */
478 struct input
*first
= TAILQ_FIRST(&inputs
);
479 log_debug("lldpctl", "process: %s", first
->name
);
480 FILE *file
= fopen(first
->name
, "r");
484 while ((line
= fgetln(file
, &len
))) {
485 line
= strndup(line
, len
);
486 if (line
[len
- 1] == '\n') {
487 line
[len
- 1] = '\0';
488 parse_and_exec(conn
, fmt
, line
);
494 log_warn("lldpctl", "unable to open %s",
497 TAILQ_REMOVE(&inputs
, first
, next
);
502 /* Process additional arguments. First if we are lldpctl (interfaces) */
503 if (is_lldpctl(NULL
)) {
505 for (int i
= optind
; i
< argc
; i
++) {
507 if (asprintf(&line
, "%s%s%s",
508 prev
?prev
:"show neigh ports ", argv
[i
],
509 (i
== argc
- 1)?" details":",") == -1) {
510 log_warnx("lldpctl", "not enough memory to build list of interfaces");
516 if (line
== NULL
&& (line
= strdup("show neigh details")) == NULL
) {
517 log_warnx("lldpctl", "not enough memory to build command line");
520 log_debug("lldpctl", "execute %s", line
);
521 if (parse_and_exec(conn
, fmt
, line
) != -1)
527 /* Then, if we are regular lldpcli (command line) */
531 cargv
= &((const char **)argv
)[optind
];
532 cargc
= argc
- optind
;
533 if (cmd_exec(conn
, fmt
, cargc
, cargv
) != -1)
538 if (gotinputs
) goto end
;
540 /* Interactive session */
541 #ifdef HAVE_LIBREADLINE
542 rl_bind_key('?', cmd_help
);
543 rl_bind_key('\t', cmd_complete
);
547 if ((line
= readline(prompt()))) {
548 int n
= parse_and_exec(conn
, fmt
, line
);
550 #ifdef HAVE_READLINE_HISTORY
551 if (n
!= 0) add_history(line
);
554 } while (!must_exit
&& line
!= NULL
);
558 while (!TAILQ_EMPTY(&inputs
)) {
559 /* coverity[use_after_free]
560 TAILQ_REMOVE does the right thing */
561 struct input
*first
= TAILQ_FIRST(&inputs
);
562 TAILQ_REMOVE(&inputs
, first
, next
);
566 if (conn
) lldpctl_release(conn
);
567 if (root
) commands_free(root
);