2 * Copyright (c) 2008, 2009, 2010, 2011, 2013, 2014 Nicira, Inc.
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:
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
18 #include "command-line.h"
23 #include "openvswitch/dynamic-string.h"
24 #include "ovs-thread.h"
26 #include "openvswitch/vlog.h"
28 VLOG_DEFINE_THIS_MODULE(command_line
);
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. */
34 ovs_cmdl_long_options_to_short_options(const struct option options
[])
36 char short_options
[UCHAR_MAX
* 3 + 1];
37 char *p
= short_options
;
39 for (; options
->name
; options
++) {
40 const struct option
*o
= options
;
41 if (o
->flag
== NULL
&& o
->val
> 0 && o
->val
<= UCHAR_MAX
) {
43 if (o
->has_arg
== required_argument
) {
45 } else if (o
->has_arg
== optional_argument
) {
53 return xstrdup(short_options
);
56 static char * OVS_WARN_UNUSED_RESULT
57 build_short_options(const struct option
*long_options
)
59 char *tmp
, *short_options
;
61 tmp
= ovs_cmdl_long_options_to_short_options(long_options
);
62 short_options
= xasprintf("+:%s", tmp
);
68 static const struct option
*
69 find_option_by_value(const struct option
*options
, int value
)
71 const struct option
*o
;
73 for (o
= options
; o
->name
; o
++) {
74 if (o
->val
== value
) {
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.
86 ovs_cmdl_env_parse_all(int *argcp
, char *argv
[], const char *env_options
)
88 ovs_assert(*argcp
> 0);
90 struct svec args
= SVEC_EMPTY_INITIALIZER
;
91 svec_add(&args
, argv
[0]);
93 svec_parse_words(&args
, env_options
);
95 for (int i
= 1; i
< *argcp
; i
++) {
96 svec_add(&args
, argv
[i
]);
98 svec_terminate(&args
);
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. */
108 char * OVS_WARN_UNUSED_RESULT
109 ovs_cmdl_parse_all(int argc
, char *argv
[],
110 const struct option
*options
,
111 struct ovs_cmdl_parsed_option
**pop
, size_t *n_pop
)
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
) {
119 char *short_options
= build_short_options(options
);
121 struct ovs_cmdl_parsed_option
*po
= NULL
;
122 size_t allocated_po
= 0;
131 int c
= getopt_long(argc
, argv
, short_options
, options
, &idx
);
140 /* getopt_long() processed the option directly by setting a flag
141 * variable. This is probably undesirable for use with this
146 if (optopt
&& find_option_by_value(options
, optopt
)) {
147 error
= xasprintf("option '%s' doesn't allow an argument",
150 error
= xasprintf("unrecognized option '%c'", optopt
);
152 error
= xasprintf("unrecognized option '%s'",
158 error
= xasprintf("option '%s' requires an argument",
163 if (n_po
>= allocated_po
) {
164 po
= x2nrealloc(po
, &allocated_po
, sizeof *po
);
167 po
[n_po
].o
= find_option_by_value(options
, c
);
169 ovs_assert(idx
>= 0 && idx
< n_options
);
170 po
[n_po
].o
= &options
[idx
];
172 po
[n_po
].arg
= optarg
;
187 /* Given the 'struct ovs_cmdl_command' array, prints the usage of all commands. */
189 ovs_cmdl_print_commands(const struct ovs_cmdl_command commands
[])
191 struct ds ds
= DS_EMPTY_INITIALIZER
;
193 ds_put_cstr(&ds
, "The available commands are:\n");
194 for (; commands
->name
; commands
++) {
195 const struct ovs_cmdl_command
*c
= commands
;
196 ds_put_format(&ds
, " %-23s %s\n", c
->name
, c
->usage
? c
->usage
: "");
198 printf("%s", ds
.string
);
202 /* Given the GNU-style options in 'options', prints all options. */
204 ovs_cmdl_print_options(const struct option options
[])
206 struct ds ds
= DS_EMPTY_INITIALIZER
;
208 for (; options
->name
; options
++) {
209 const struct option
*o
= options
;
210 const char *arg
= o
->has_arg
== required_argument
? "ARG" : "[ARG]";
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
: "");
218 printf("%s", ds
.string
);
223 ovs_cmdl_run_command__(struct ovs_cmdl_context
*ctx
,
224 const struct ovs_cmdl_command commands
[],
227 const struct ovs_cmdl_command
*p
;
230 ovs_fatal(0, "missing command name; use --help for help");
233 for (p
= commands
; p
->name
!= NULL
; p
++) {
234 if (!strcmp(p
->name
, ctx
->argv
[0])) {
235 int n_arg
= ctx
->argc
- 1;
236 if (n_arg
< p
->min_args
) {
237 VLOG_FATAL( "'%s' command requires at least %d arguments",
238 p
->name
, p
->min_args
);
239 } else if (n_arg
> p
->max_args
) {
240 VLOG_FATAL("'%s' command takes at most %d arguments",
241 p
->name
, p
->max_args
);
243 if (p
->mode
== OVS_RW
&& read_only
) {
244 VLOG_FATAL("'%s' command does not work in read only mode",
248 if (ferror(stdout
)) {
249 VLOG_FATAL("write to stdout failed");
251 if (ferror(stderr
)) {
252 VLOG_FATAL("write to stderr failed");
259 VLOG_FATAL("unknown command '%s'; use --help for help", ctx
->argv
[0]);
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
266 * Command-line options should be stripped off, so that a typical invocation
268 * struct ovs_cmdl_context ctx = {
269 * .argc = argc - optind,
270 * .argv = argv + optind,
272 * ovs_cmdl_run_command(&ctx, my_commands);
275 ovs_cmdl_run_command(struct ovs_cmdl_context
*ctx
,
276 const struct ovs_cmdl_command commands
[])
278 ovs_cmdl_run_command__(ctx
, commands
, false);
282 ovs_cmdl_run_command_read_only(struct ovs_cmdl_context
*ctx
,
283 const struct ovs_cmdl_command commands
[])
285 ovs_cmdl_run_command__(ctx
, commands
, true);
291 static struct ovs_mutex proctitle_mutex
= OVS_MUTEX_INITIALIZER
;
293 /* Start of command-line arguments in memory. */
294 static char *argv_start
OVS_GUARDED_BY(proctitle_mutex
);
296 /* Number of bytes of command-line arguments. */
297 static size_t argv_size
OVS_GUARDED_BY(proctitle_mutex
);
299 /* Saved command-line arguments. */
300 static char *saved_proctitle
OVS_GUARDED_BY(proctitle_mutex
);
302 /* Prepares the process so that proctitle_set() can later succeed.
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
311 ovs_cmdl_proctitle_init(int argc
, char **argv
)
315 assert_single_threaded();
316 if (!argc
|| !argv
[0]) {
317 /* This situation should never occur, but... */
321 ovs_mutex_lock(&proctitle_mutex
);
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]);
327 for (i
= 1; i
< argc
; i
++) {
328 size_t size
= strlen(argv
[i
]) + 1;
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. */
335 } else if (argv
[i
] == argv_start
+ argv_size
) {
336 /* Arguments grow upward in memory. */
339 /* Arguments not contiguous. (Is this really Linux?) */
342 /* Copy out the old argument so we can reuse the space. */
343 argv
[i
] = xstrdup(argv
[i
]);
345 ovs_mutex_unlock(&proctitle_mutex
);
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(). */
351 ovs_cmdl_proctitle_set(const char *format
, ...)
356 ovs_mutex_lock(&proctitle_mutex
);
357 if (!argv_start
|| argv_size
< 8) {
361 if (!saved_proctitle
) {
362 saved_proctitle
= xmemdup(argv_start
, argv_size
);
365 va_start(args
, format
);
366 n
= snprintf(argv_start
, argv_size
, "%s: ", program_name
);
368 n
+= vsnprintf(argv_start
+ n
, argv_size
- n
, format
, args
);
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], "...");
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
);
381 ovs_mutex_unlock(&proctitle_mutex
);
384 /* Restores the process's original command line, as seen by "ps". */
386 ovs_cmdl_proctitle_restore(void)
388 ovs_mutex_lock(&proctitle_mutex
);
389 if (saved_proctitle
) {
390 memcpy(argv_start
, saved_proctitle
, argv_size
);
391 free(saved_proctitle
);
392 saved_proctitle
= NULL
;
394 ovs_mutex_unlock(&proctitle_mutex
);
396 #else /* !__linux__ */
397 /* Stubs that don't do anything on non-Linux systems. */
400 ovs_cmdl_proctitle_init(int argc OVS_UNUSED
, char **argv OVS_UNUSED
)
404 #if !(defined(__FreeBSD__) || defined(__NetBSD__))
405 /* On these platforms we #define this to setproctitle. */
407 ovs_cmdl_proctitle_set(const char *format OVS_UNUSED
, ...)
413 ovs_cmdl_proctitle_restore(void)
416 #endif /* !__linux__ */