]> git.proxmox.com Git - mirror_ovs.git/blame - lib/command-line.c
cirrus: Use FreeBSD 12.2.
[mirror_ovs.git] / lib / command-line.c
CommitLineData
064af421 1/*
2f51a7eb 2 * Copyright (c) 2008, 2009, 2010, 2011, 2013, 2014 Nicira, Inc.
064af421 3 *
a14bc59f
BP
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at:
064af421 7 *
a14bc59f
BP
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
064af421
BP
15 */
16
17#include <config.h>
18#include "command-line.h"
19#include <getopt.h>
20#include <limits.h>
675febfa 21#include <stdlib.h>
6e26ff63 22#include "svec.h"
3e8a2ad1 23#include "openvswitch/dynamic-string.h"
728a8b14 24#include "ovs-thread.h"
064af421 25#include "util.h"
e6211adc 26#include "openvswitch/vlog.h"
279c9e03
BP
27
28VLOG_DEFINE_THIS_MODULE(command_line);
064af421
BP
29
30/* Given the GNU-style long options in 'options', returns a string that may be
31 * passed to getopt() with the corresponding short options. The caller is
32 * responsible for freeing the string. */
33char *
5f383751 34ovs_cmdl_long_options_to_short_options(const struct option options[])
064af421
BP
35{
36 char short_options[UCHAR_MAX * 3 + 1];
37 char *p = short_options;
d295e8e9 38
064af421
BP
39 for (; options->name; options++) {
40 const struct option *o = options;
41 if (o->flag == NULL && o->val > 0 && o->val <= UCHAR_MAX) {
42 *p++ = o->val;
43 if (o->has_arg == required_argument) {
44 *p++ = ':';
45 } else if (o->has_arg == optional_argument) {
46 *p++ = ':';
47 *p++ = ':';
48 }
49 }
50 }
51 *p = '\0';
d295e8e9 52
064af421
BP
53 return xstrdup(short_options);
54}
55
1830add6
BP
56static char * OVS_WARN_UNUSED_RESULT
57build_short_options(const struct option *long_options)
58{
59 char *tmp, *short_options;
60
61 tmp = ovs_cmdl_long_options_to_short_options(long_options);
62 short_options = xasprintf("+:%s", tmp);
63 free(tmp);
64
65 return short_options;
66}
67
68static const struct option *
69find_option_by_value(const struct option *options, int value)
70{
71 const struct option *o;
72
73 for (o = options; o->name; o++) {
74 if (o->val == value) {
75 return o;
76 }
77 }
78 return NULL;
79}
80
6e26ff63
AG
81/* Parses options set using environment variable. The caller specifies the
82 * supported options in environment variable. On success, adds the parsed
83 * env variables in 'argv', the number of options in 'argc', and returns argv.
84 * */
85char **
86ovs_cmdl_env_parse_all(int *argcp, char *argv[], const char *env_options)
87{
88 ovs_assert(*argcp > 0);
89
90 struct svec args = SVEC_EMPTY_INITIALIZER;
91 svec_add(&args, argv[0]);
92 if (env_options) {
93 svec_parse_words(&args, env_options);
94 }
95 for (int i = 1; i < *argcp; i++) {
96 svec_add(&args, argv[i]);
97 }
98 svec_terminate(&args);
99
100 *argcp = args.n;
101 return args.names;
102}
103
1830add6
BP
104/* Parses the command-line options in 'argc' and 'argv'. The caller specifies
105 * the supported options in 'options'. On success, stores the parsed options
106 * in '*pop', the number of options in '*n_pop', and returns NULL. On failure,
107 * returns an error message and zeros the output arguments. */
108char * OVS_WARN_UNUSED_RESULT
109ovs_cmdl_parse_all(int argc, char *argv[],
110 const struct option *options,
111 struct ovs_cmdl_parsed_option **pop, size_t *n_pop)
112{
113 /* Count number of options so we can have better assertions later. */
114 size_t n_options OVS_UNUSED = 0;
115 while (options[n_options].name) {
116 n_options++;
117 }
118
119 char *short_options = build_short_options(options);
120
121 struct ovs_cmdl_parsed_option *po = NULL;
122 size_t allocated_po = 0;
123 size_t n_po = 0;
124
125 char *error;
126
127 optind = 0;
128 opterr = 0;
129 for (;;) {
130 int idx = -1;
131 int c = getopt_long(argc, argv, short_options, options, &idx);
132 switch (c) {
133 case -1:
134 *pop = po;
135 *n_pop = n_po;
136 free(short_options);
137 return NULL;
138
139 case 0:
140 /* getopt_long() processed the option directly by setting a flag
141 * variable. This is probably undesirable for use with this
142 * function. */
143 OVS_NOT_REACHED();
144
145 case '?':
146 if (optopt && find_option_by_value(options, optopt)) {
147 error = xasprintf("option '%s' doesn't allow an argument",
148 argv[optind - 1]);
149 } else if (optopt) {
150 error = xasprintf("unrecognized option '%c'", optopt);
151 } else {
152 error = xasprintf("unrecognized option '%s'",
153 argv[optind - 1]);
154 }
155 goto error;
156
157 case ':':
158 error = xasprintf("option '%s' requires an argument",
159 argv[optind - 1]);
160 goto error;
161
162 default:
163 if (n_po >= allocated_po) {
164 po = x2nrealloc(po, &allocated_po, sizeof *po);
165 }
166 if (idx == -1) {
167 po[n_po].o = find_option_by_value(options, c);
168 } else {
169 ovs_assert(idx >= 0 && idx < n_options);
170 po[n_po].o = &options[idx];
171 }
172 po[n_po].arg = optarg;
173 n_po++;
174 break;
175 }
176 }
177 OVS_NOT_REACHED();
178
179error:
180 free(po);
181 *pop = NULL;
182 *n_pop = 0;
183 free(short_options);
184 return error;
185}
186
5f383751 187/* Given the 'struct ovs_cmdl_command' array, prints the usage of all commands. */
451de37e 188void
5f383751 189ovs_cmdl_print_commands(const struct ovs_cmdl_command commands[])
451de37e
AW
190{
191 struct ds ds = DS_EMPTY_INITIALIZER;
192
193 ds_put_cstr(&ds, "The available commands are:\n");
194 for (; commands->name; commands++) {
5f383751 195 const struct ovs_cmdl_command *c = commands;
451de37e
AW
196 ds_put_format(&ds, " %-23s %s\n", c->name, c->usage ? c->usage : "");
197 }
198 printf("%s", ds.string);
199 ds_destroy(&ds);
200}
201
66fa2c88
AW
202/* Given the GNU-style options in 'options', prints all options. */
203void
5f383751 204ovs_cmdl_print_options(const struct option options[])
66fa2c88
AW
205{
206 struct ds ds = DS_EMPTY_INITIALIZER;
207
208 for (; options->name; options++) {
209 const struct option *o = options;
210 const char *arg = o->has_arg == required_argument ? "ARG" : "[ARG]";
211
212 ds_put_format(&ds, "--%s%s%s\n", o->name, o->has_arg ? "=" : "",
213 o->has_arg ? arg : "");
214 if (o->flag == NULL && o->val > 0 && o->val <= UCHAR_MAX) {
215 ds_put_format(&ds, "-%c %s\n", o->val, o->has_arg ? arg : "");
216 }
217 }
218 printf("%s", ds.string);
219 ds_destroy(&ds);
220}
221
1f4a7252
RM
222static void
223ovs_cmdl_run_command__(struct ovs_cmdl_context *ctx,
224 const struct ovs_cmdl_command commands[],
225 bool read_only)
675febfa 226{
5f383751 227 const struct ovs_cmdl_command *p;
675febfa 228
1636c761 229 if (ctx->argc < 1) {
675febfa
BP
230 ovs_fatal(0, "missing command name; use --help for help");
231 }
232
233 for (p = commands; p->name != NULL; p++) {
1636c761
RB
234 if (!strcmp(p->name, ctx->argv[0])) {
235 int n_arg = ctx->argc - 1;
675febfa 236 if (n_arg < p->min_args) {
279c9e03
BP
237 VLOG_FATAL( "'%s' command requires at least %d arguments",
238 p->name, p->min_args);
675febfa 239 } else if (n_arg > p->max_args) {
279c9e03
BP
240 VLOG_FATAL("'%s' command takes at most %d arguments",
241 p->name, p->max_args);
675febfa 242 } else {
1f4a7252
RM
243 if (p->mode == OVS_RW && read_only) {
244 VLOG_FATAL("'%s' command does not work in read only mode",
245 p->name);
246 }
1636c761 247 p->handler(ctx);
675febfa 248 if (ferror(stdout)) {
279c9e03 249 VLOG_FATAL("write to stdout failed");
675febfa
BP
250 }
251 if (ferror(stderr)) {
279c9e03 252 VLOG_FATAL("write to stderr failed");
675febfa
BP
253 }
254 return;
255 }
256 }
257 }
258
1636c761 259 VLOG_FATAL("unknown command '%s'; use --help for help", ctx->argv[0]);
675febfa 260}
1f4a7252
RM
261
262/* Runs the command designated by argv[0] within the command table specified by
263 * 'commands', which must be terminated by a command whose 'name' member is a
264 * null pointer.
265 *
266 * Command-line options should be stripped off, so that a typical invocation
267 * looks like:
268 * struct ovs_cmdl_context ctx = {
269 * .argc = argc - optind,
270 * .argv = argv + optind,
271 * };
272 * ovs_cmdl_run_command(&ctx, my_commands);
273 * */
274void
275ovs_cmdl_run_command(struct ovs_cmdl_context *ctx,
276 const struct ovs_cmdl_command commands[])
277{
278 ovs_cmdl_run_command__(ctx, commands, false);
279}
280
281void
282ovs_cmdl_run_command_read_only(struct ovs_cmdl_context *ctx,
283 const struct ovs_cmdl_command commands[])
284{
285 ovs_cmdl_run_command__(ctx, commands, true);
286}
40f0707c
BP
287\f
288/* Process title. */
289
2f51a7eb 290#ifdef __linux__
97be1538
EJ
291static struct ovs_mutex proctitle_mutex = OVS_MUTEX_INITIALIZER;
292
293/* Start of command-line arguments in memory. */
294static char *argv_start OVS_GUARDED_BY(proctitle_mutex);
295
296/* Number of bytes of command-line arguments. */
297static size_t argv_size OVS_GUARDED_BY(proctitle_mutex);
298
299/* Saved command-line arguments. */
300static char *saved_proctitle OVS_GUARDED_BY(proctitle_mutex);
40f0707c
BP
301
302/* Prepares the process so that proctitle_set() can later succeed.
303 *
304 * This modifies the argv[] array so that it no longer points into the memory
305 * that it originally does. Later, proctitle_set() might overwrite that
306 * memory. That means that this function should be called before anything else
307 * that accesses the process's argv[] array. Ideally, it should be called
308 * before anything else, period, at the very beginning of program
309 * execution. */
310void
5f383751 311ovs_cmdl_proctitle_init(int argc, char **argv)
40f0707c
BP
312{
313 int i;
314
728a8b14 315 assert_single_threaded();
40f0707c
BP
316 if (!argc || !argv[0]) {
317 /* This situation should never occur, but... */
318 return;
319 }
320
97be1538 321 ovs_mutex_lock(&proctitle_mutex);
40f0707c
BP
322 /* Specialized version of first loop iteration below. */
323 argv_start = argv[0];
324 argv_size = strlen(argv[0]) + 1;
325 argv[0] = xstrdup(argv[0]);
326
327 for (i = 1; i < argc; i++) {
328 size_t size = strlen(argv[i]) + 1;
329
330 /* Add (argv[i], strlen(argv[i])+1) to (argv_start, argv_size). */
331 if (argv[i] + size == argv_start) {
332 /* Arguments grow downward in memory. */
333 argv_start -= size;
334 argv_size += size;
335 } else if (argv[i] == argv_start + argv_size) {
336 /* Arguments grow upward in memory. */
337 argv_size += size;
338 } else {
339 /* Arguments not contiguous. (Is this really Linux?) */
340 }
341
342 /* Copy out the old argument so we can reuse the space. */
343 argv[i] = xstrdup(argv[i]);
344 }
97be1538 345 ovs_mutex_unlock(&proctitle_mutex);
40f0707c
BP
346}
347
d86a6c09
EM
348/* Changes the name of the process, as shown by "ps", to the program name
349 * followed by 'format', which is formatted as if by printf(). */
40f0707c 350void
5f383751 351ovs_cmdl_proctitle_set(const char *format, ...)
40f0707c
BP
352{
353 va_list args;
354 int n;
355
97be1538 356 ovs_mutex_lock(&proctitle_mutex);
40f0707c 357 if (!argv_start || argv_size < 8) {
97be1538 358 goto out;
40f0707c
BP
359 }
360
361 if (!saved_proctitle) {
362 saved_proctitle = xmemdup(argv_start, argv_size);
363 }
364
365 va_start(args, format);
d86a6c09
EM
366 n = snprintf(argv_start, argv_size, "%s: ", program_name);
367 if (n < argv_size) {
368 n += vsnprintf(argv_start + n, argv_size - n, format, args);
369 }
40f0707c
BP
370 if (n >= argv_size) {
371 /* The name is too long, so add an ellipsis at the end. */
372 strcpy(&argv_start[argv_size - 4], "...");
373 } else {
374 /* Fill the extra space with null bytes, so that trailing bytes don't
375 * show up in the command line. */
376 memset(&argv_start[n], '\0', argv_size - n);
377 }
378 va_end(args);
97be1538
EJ
379
380out:
381 ovs_mutex_unlock(&proctitle_mutex);
40f0707c
BP
382}
383
384/* Restores the process's original command line, as seen by "ps". */
385void
5f383751 386ovs_cmdl_proctitle_restore(void)
40f0707c 387{
97be1538 388 ovs_mutex_lock(&proctitle_mutex);
40f0707c
BP
389 if (saved_proctitle) {
390 memcpy(argv_start, saved_proctitle, argv_size);
391 free(saved_proctitle);
392 saved_proctitle = NULL;
393 }
97be1538 394 ovs_mutex_unlock(&proctitle_mutex);
40f0707c 395}
2f51a7eb 396#else /* !__linux__ */
40f0707c
BP
397/* Stubs that don't do anything on non-Linux systems. */
398
399void
5f383751 400ovs_cmdl_proctitle_init(int argc OVS_UNUSED, char **argv OVS_UNUSED)
40f0707c
BP
401{
402}
403
666afb55
YT
404#if !(defined(__FreeBSD__) || defined(__NetBSD__))
405/* On these platforms we #define this to setproctitle. */
40f0707c 406void
5f383751 407ovs_cmdl_proctitle_set(const char *format OVS_UNUSED, ...)
40f0707c
BP
408{
409}
fb301c74 410#endif
40f0707c
BP
411
412void
5f383751 413ovs_cmdl_proctitle_restore(void)
40f0707c
BP
414{
415}
2f51a7eb 416#endif /* !__linux__ */