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>
33 #include <sys/queue.h>
37 #ifdef HAVE___PROGNAME
38 extern const char *__progname
;
40 # define __progname "lldpcli"
43 /* Global for completion */
44 static struct cmd_node
*root
= NULL
;
45 const char *ctlname
= NULL
;
48 is_lldpctl(const char *name
)
50 static int last_result
= -1;
51 if (last_result
== -1 && name
) {
52 char *basec
= strdup(name
);
54 char *bname
= basename(basec
);
55 last_result
= (!strcmp(bname
, "lldpctl"));
58 return (last_result
== -1)?0:last_result
;
64 fprintf(stderr
, "Usage: %s [OPTIONS ...] [COMMAND ...]\n", __progname
);
65 fprintf(stderr
, "Version: %s\n", PACKAGE_STRING
);
67 fprintf(stderr
, "\n");
69 fprintf(stderr
, "-d Enable more debugging information.\n");
70 fprintf(stderr
, "-u socket Specify the Unix-domain socket used for communication with lldpd(8).\n");
71 fprintf(stderr
, "-f format Choose output format (plain, keyvalue"
75 #if defined USE_JANSSON || defined USE_JSONC
79 if (!is_lldpctl(NULL
))
80 fprintf(stderr
, "-c conf Read the provided configuration file.\n");
82 fprintf(stderr
, "\n");
84 fprintf(stderr
, "see manual page lldpcli(8) for more information\n");
91 /* Check we can access the control socket with read/write
92 * privileges. The `access()` function uses the real UID and real GID,
93 * therefore we don't have to mangle with our identity. */
94 return (ctlname
&& access(ctlname
, R_OK
|W_OK
) == 0);
101 int privileged
= is_privileged();
102 if (isatty(STDIN_FILENO
)) {
104 return "[lldpcli] # ";
105 return "[lldpcli] $ ";
110 static int must_exit
= 0;
112 * Exit the interpreter.
115 cmd_exit(struct lldpctl_conn_t
*conn
, struct writer
*w
,
116 struct cmd_env
*env
, void *arg
)
118 log_info("lldpctl", "quit lldpcli");
124 * Send an "update" request.
127 cmd_update(struct lldpctl_conn_t
*conn
, struct writer
*w
,
128 struct cmd_env
*env
, void *arg
)
130 log_info("lldpctl", "ask for global update");
132 lldpctl_atom_t
*config
= lldpctl_get_configuration(conn
);
133 if (config
== NULL
) {
134 log_warnx("lldpctl", "unable to get configuration from lldpd. %s",
135 lldpctl_last_strerror(conn
));
138 if (lldpctl_atom_set_int(config
,
139 lldpctl_k_config_tx_interval
, -1) == NULL
) {
140 log_warnx("lldpctl", "unable to ask lldpd for immediate retransmission. %s",
141 lldpctl_last_strerror(conn
));
142 lldpctl_atom_dec_ref(config
);
145 log_info("lldpctl", "immediate retransmission requested successfuly");
146 lldpctl_atom_dec_ref(config
);
151 * Pause or resume execution of lldpd.
153 * @param conn The connection to lldpd.
154 * @param pause 1 if we want to pause lldpd, 0 otherwise
155 * @return 1 on success, 0 on error
158 cmd_pause_resume(lldpctl_conn_t
*conn
, int pause
)
160 lldpctl_atom_t
*config
= lldpctl_get_configuration(conn
);
161 if (config
== NULL
) {
162 log_warnx("lldpctl", "unable to get configuration from lldpd. %s",
163 lldpctl_last_strerror(conn
));
166 if (lldpctl_atom_get_int(config
, lldpctl_k_config_paused
) == pause
) {
167 log_debug("lldpctl", "lldpd is already %s",
168 pause
?"paused":"resumed");
169 lldpctl_atom_dec_ref(config
);
172 if (lldpctl_atom_set_int(config
,
173 lldpctl_k_config_paused
, pause
) == NULL
) {
174 log_warnx("lldpctl", "unable to ask lldpd to %s operations. %s",
175 pause
?"pause":"resume",
176 lldpctl_last_strerror(conn
));
177 lldpctl_atom_dec_ref(config
);
180 log_info("lldpctl", "lldpd should %s operations",
181 pause
?"pause":"resume");
182 lldpctl_atom_dec_ref(config
);
186 cmd_pause(struct lldpctl_conn_t
*conn
, struct writer
*w
,
187 struct cmd_env
*env
, void *arg
) {
189 return cmd_pause_resume(conn
, 1);
192 cmd_resume(struct lldpctl_conn_t
*conn
, struct writer
*w
,
193 struct cmd_env
*env
, void *arg
) {
195 return cmd_pause_resume(conn
, 0);
199 #ifdef HAVE_LIBREADLINE
201 _cmd_complete(int all
)
206 size_t len
= strlen(rl_line_buffer
);
207 char *line
= malloc(len
+ 2);
208 if (!line
) return -1;
209 strlcpy(line
, rl_line_buffer
, len
+ 2);
210 line
[rl_point
] = 2; /* empty character, will force a word */
211 line
[rl_point
+1] = 0;
213 if (tokenize_line(line
, &argc
, &argv
) != 0)
216 char *compl = commands_complete(root
, argc
, (const char **)argv
, all
, is_privileged());
217 if (compl && strlen(argv
[argc
-1]) < strlen(compl)) {
218 if (rl_insert_text(compl + strlen(argv
[argc
-1])) < 0) {
226 /* No completion or several completion available. */
228 fprintf(stderr
, "\n");
229 rl_forced_update_display();
233 tokenize_free(argc
, argv
);
238 cmd_complete(int count
, int ch
)
240 return _cmd_complete(0);
244 cmd_help(int count
, int ch
)
246 return _cmd_complete(1);
250 readline(const char *p
)
252 static char line
[2048];
253 fprintf(stderr
, "%s", p
);
255 if (fgets(line
, sizeof(line
) - 2, stdin
) == NULL
)
262 * Execute a tokenized command and display its output.
264 * @param conn The connection to lldpd.
265 * @param fmt Output format.
266 * @param argc Number of arguments.
267 * @param argv Array of arguments.
268 * @return 0 if an error occurred, 1 otherwise
271 cmd_exec(lldpctl_conn_t
*conn
, const char *fmt
, int argc
, const char **argv
)
273 /* Init output formatter */
276 if (strcmp(fmt
, "plain") == 0) w
= txt_init(stdout
);
277 else if (strcmp(fmt
, "keyvalue") == 0) w
= kv_init(stdout
);
279 else if (strcmp(fmt
, "xml") == 0) w
= xml_init(stdout
);
282 else if (strcmp(fmt
, "json") == 0) w
= jansson_init(stdout
);
285 else if (strcmp(fmt
, "json") == 0) w
= jsonc_init(stdout
);
288 log_warnx("lldpctl", "unknown output format \"%s\"", fmt
);
289 w
= txt_init(stdout
);
292 /* Execute command */
293 int rc
= commands_execute(conn
, w
,
294 root
, argc
, argv
, is_privileged());
296 log_info("lldpctl", "an error occurred while executing last command");
305 * Execute a command line and display its output.
307 * @param conn The connection to lldpd.
308 * @param fmt Output format.
309 * @param line Line to execute.
310 * @return -1 if an error occurred, 0 if nothing was executed. 1 otherwise.
313 parse_and_exec(lldpctl_conn_t
*conn
, const char *fmt
, const char *line
)
315 int cargc
= 0; char **cargv
= NULL
;
317 log_debug("lldpctl", "tokenize command line");
318 n
= tokenize_line(line
, &cargc
, &cargv
);
321 log_warnx("lldpctl", "internal error while tokenizing");
324 log_warnx("lldpctl", "unmatched quotes");
328 n
= cmd_exec(conn
, fmt
, cargc
, (const char **)cargv
);
329 tokenize_free(cargc
, cargv
);
330 return (cargc
== 0)?0:
335 static struct cmd_node
*
338 root
= commands_root();
339 register_commands_show(root
);
340 register_commands_watch(root
);
341 commands_privileged(commands_new(
342 commands_new(root
, "update", "Update information and send LLDPU on all ports",
344 NEWLINE
, "Update information and send LLDPU on all ports",
345 NULL
, cmd_update
, NULL
));
346 register_commands_configure(root
);
347 commands_hidden(commands_new(root
, "complete", "Get possible completions from a given command",
348 NULL
, cmd_store_env_and_pop
, "complete"));
349 commands_new(root
, "help", "Get help on a possible command",
350 NULL
, cmd_store_env_and_pop
, "help");
352 commands_new(root
, "pause", "Pause lldpd operations", NULL
, NULL
, NULL
),
353 NEWLINE
, "Pause lldpd operations", NULL
, cmd_pause
, NULL
);
355 commands_new(root
, "resume", "Resume lldpd operations", NULL
, NULL
, NULL
),
356 NEWLINE
, "Resume lldpd operations", NULL
, cmd_resume
, NULL
);
358 commands_new(root
, "exit", "Exit interpreter", NULL
, NULL
, NULL
),
359 NEWLINE
, "Exit interpreter", NULL
, cmd_exit
, NULL
);
364 TAILQ_ENTRY(input
) next
;
367 TAILQ_HEAD(inputs
, input
);
369 filter(const struct dirent
*dir
)
371 if (strlen(dir
->d_name
) < 5) return 0;
372 if (strcmp(dir
->d_name
+ strlen(dir
->d_name
) - 5, ".conf")) return 0;
377 * Append a new input file/directory to the list of inputs.
379 * @param arg Directory or file name to add.
380 * @param inputs List of inputs
381 * @param acceptdir 1 if we accept a directory, 0 otherwise
384 input_append(const char *arg
, struct inputs
*inputs
, int acceptdir
)
387 if (stat(arg
, &statbuf
) == -1) {
388 log_warn("lldpctl", "cannot find configuration file/directory %s",
393 if (!S_ISDIR(statbuf
.st_mode
)) {
394 struct input
*input
= malloc(sizeof(struct input
));
396 log_warn("lldpctl", "not enough memory to process %s",
400 log_debug("lldpctl", "input: %s", arg
);
401 input
->name
= strdup(arg
);
402 TAILQ_INSERT_TAIL(inputs
, input
, next
);
406 log_debug("lldpctl", "skip directory %s",
411 struct dirent
**namelist
= NULL
;
412 int n
= scandir(arg
, &namelist
, filter
, alphasort
);
414 log_warnx("lldpctl", "unable to read directory %s",
418 for (int i
=0; i
< n
; i
++) {
420 if (asprintf(&fullname
, "%s/%s", arg
, namelist
[i
]->d_name
) != -1) {
421 input_append(fullname
, inputs
, 0);
430 main(int argc
, char *argv
[])
432 int ch
, debug
= 0, use_syslog
= 0, rc
= EXIT_FAILURE
;
433 const char *fmt
= "plain";
434 lldpctl_conn_t
*conn
= NULL
;
435 const char *options
= is_lldpctl(argv
[0])?"hdvf:u:":"hdsvf:c:u:";
438 struct inputs inputs
;
441 ctlname
= lldpctl_get_default_transport();
443 signal(SIGHUP
, SIG_IGN
);
445 /* Get and parse command line options */
447 while ((ch
= getopt(argc
, argv
, options
)) != -1) {
468 fprintf(stdout
, "%s\n", PACKAGE_VERSION
);
476 log_init(use_syslog
, debug
, __progname
);
477 lldpctl_log_level(debug
+ 1);
480 input_append(optarg
, &inputs
, 1);
488 log_init(use_syslog
, debug
, __progname
);
489 lldpctl_log_level(debug
+ 1);
492 /* Disable SIGPIPE */
493 signal(SIGPIPE
, SIG_IGN
);
495 /* Register commands */
496 root
= register_commands();
498 /* Make a connection */
499 log_debug("lldpctl", "connect to lldpd");
500 conn
= lldpctl_new_name(ctlname
, NULL
, NULL
, NULL
);
501 if (conn
== NULL
) goto end
;
503 /* Process file inputs */
504 while (gotinputs
&& !TAILQ_EMPTY(&inputs
)) {
505 /* coverity[use_after_free]
506 TAILQ_REMOVE does the right thing */
507 struct input
*first
= TAILQ_FIRST(&inputs
);
508 log_debug("lldpctl", "process: %s", first
->name
);
509 FILE *file
= fopen(first
->name
, "r");
513 while ((line
= fgetln(file
, &len
))) {
514 line
= strndup(line
, len
);
515 if (line
[len
- 1] == '\n') {
516 line
[len
- 1] = '\0';
517 parse_and_exec(conn
, fmt
, line
);
523 log_warn("lldpctl", "unable to open %s",
526 TAILQ_REMOVE(&inputs
, first
, next
);
531 /* Process additional arguments. First if we are lldpctl (interfaces) */
532 if (is_lldpctl(NULL
)) {
534 for (int i
= optind
; i
< argc
; i
++) {
536 if (asprintf(&line
, "%s%s%s",
537 prev
?prev
:"show neigh ports ", argv
[i
],
538 (i
== argc
- 1)?" details":",") == -1) {
539 log_warnx("lldpctl", "not enough memory to build list of interfaces");
545 if (line
== NULL
&& (line
= strdup("show neigh details")) == NULL
) {
546 log_warnx("lldpctl", "not enough memory to build command line");
549 log_debug("lldpctl", "execute %s", line
);
550 if (parse_and_exec(conn
, fmt
, line
) != -1)
556 /* Then, if we are regular lldpcli (command line) */
560 cargv
= &((const char **)argv
)[optind
];
561 cargc
= argc
- optind
;
562 if (cmd_exec(conn
, fmt
, cargc
, cargv
) != -1)
572 /* Interactive session */
573 #ifdef HAVE_LIBREADLINE
574 rl_bind_key('?', cmd_help
);
575 rl_bind_key('\t', cmd_complete
);
579 if ((line
= readline(prompt()))) {
580 int n
= parse_and_exec(conn
, fmt
, line
);
582 #ifdef HAVE_READLINE_HISTORY
583 if (n
!= 0) add_history(line
);
586 } while (!must_exit
&& line
!= NULL
);
590 while (!TAILQ_EMPTY(&inputs
)) {
591 /* coverity[use_after_free]
592 TAILQ_REMOVE does the right thing */
593 struct input
*first
= TAILQ_FIRST(&inputs
);
594 TAILQ_REMOVE(&inputs
, first
, next
);
598 if (conn
) lldpctl_release(conn
);
599 if (root
) commands_free(root
);