Coverage Report

Created: 2025-07-11 06:12

/src/openvswitch/lib/command-line.c
Line
Count
Source (jump to first uncovered line)
1
/*
2
 * Copyright (c) 2008, 2009, 2010, 2011, 2013, 2014 Nicira, Inc.
3
 *
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:
7
 *
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.
15
 */
16
17
#include <config.h>
18
#include "command-line.h"
19
#include <getopt.h>
20
#include <limits.h>
21
#include <stdlib.h>
22
#include "svec.h"
23
#include "openvswitch/dynamic-string.h"
24
#include "ovs-thread.h"
25
#include "util.h"
26
#include "openvswitch/vlog.h"
27
28
VLOG_DEFINE_THIS_MODULE(command_line);
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. */
33
char *
34
ovs_cmdl_long_options_to_short_options(const struct option options[])
35
0
{
36
0
    char short_options[UCHAR_MAX * 3 + 1];
37
0
    char *p = short_options;
38
39
0
    for (; options->name; options++) {
40
0
        const struct option *o = options;
41
0
        if (o->flag == NULL && o->val > 0 && o->val <= UCHAR_MAX) {
42
0
            *p++ = o->val;
43
0
            if (o->has_arg == required_argument) {
44
0
                *p++ = ':';
45
0
            } else if (o->has_arg == optional_argument) {
46
0
                *p++ = ':';
47
0
                *p++ = ':';
48
0
            }
49
0
        }
50
0
    }
51
0
    *p = '\0';
52
53
0
    return xstrdup(short_options);
54
0
}
55
56
static char * OVS_WARN_UNUSED_RESULT
57
build_short_options(const struct option *long_options)
58
0
{
59
0
    char *tmp, *short_options;
60
61
0
    tmp = ovs_cmdl_long_options_to_short_options(long_options);
62
0
    short_options = xasprintf("+:%s", tmp);
63
0
    free(tmp);
64
65
0
    return short_options;
66
0
}
67
68
static const struct option *
69
find_option_by_value(const struct option *options, int value)
70
0
{
71
0
    const struct option *o;
72
73
0
    for (o = options; o->name; o++) {
74
0
        if (o->val == value) {
75
0
            return o;
76
0
        }
77
0
    }
78
0
    return NULL;
79
0
}
80
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
 *  */
85
char **
86
ovs_cmdl_env_parse_all(int *argcp, char *argv[], const char *env_options)
87
0
{
88
0
    ovs_assert(*argcp > 0);
89
90
0
    struct svec args = SVEC_EMPTY_INITIALIZER;
91
0
    svec_add(&args, argv[0]);
92
0
    if (env_options) {
93
0
        svec_parse_words(&args, env_options);
94
0
    }
95
0
    for (int i = 1; i < *argcp; i++) {
96
0
        svec_add(&args, argv[i]);
97
0
    }
98
0
    svec_terminate(&args);
99
100
0
    *argcp = args.n;
101
0
    return args.names;
102
0
}
103
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)
112
0
{
113
    /* Count number of options so we can have better assertions later. */
114
0
    size_t n_options OVS_UNUSED = 0;
115
0
    while (options[n_options].name) {
116
0
        n_options++;
117
0
    }
118
119
0
    char *short_options = build_short_options(options);
120
121
0
    struct ovs_cmdl_parsed_option *po = NULL;
122
0
    size_t allocated_po = 0;
123
0
    size_t n_po = 0;
124
125
0
    char *error;
126
127
0
    optind = 0;
128
0
    opterr = 0;
129
0
    for (;;) {
130
0
        int idx = -1;
131
0
        int c = getopt_long(argc, argv, short_options, options, &idx);
132
0
        switch (c) {
133
0
        case -1:
134
0
            *pop = po;
135
0
            *n_pop = n_po;
136
0
            free(short_options);
137
0
            return NULL;
138
139
0
        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
0
            OVS_NOT_REACHED();
144
145
0
        case '?':
146
0
            if (optopt && find_option_by_value(options, optopt)) {
147
0
                error = xasprintf("option '%s' doesn't allow an argument",
148
0
                                  argv[optind - 1]);
149
0
            } else if (optopt) {
150
0
                error = xasprintf("unrecognized option '%c'", optopt);
151
0
            } else {
152
0
                error = xasprintf("unrecognized option '%s'",
153
0
                                  argv[optind - 1]);
154
0
            }
155
0
            goto error;
156
157
0
        case ':':
158
0
            error = xasprintf("option '%s' requires an argument",
159
0
                              argv[optind - 1]);
160
0
            goto error;
161
162
0
        default:
163
0
            if (n_po >= allocated_po) {
164
0
                po = x2nrealloc(po, &allocated_po, sizeof *po);
165
0
            }
166
0
            if (idx == -1) {
167
0
                po[n_po].o = find_option_by_value(options, c);
168
0
            } else {
169
0
                ovs_assert(idx >= 0 && idx < n_options);
170
0
                po[n_po].o = &options[idx];
171
0
            }
172
0
            po[n_po].arg = optarg;
173
0
            n_po++;
174
0
            break;
175
0
        }
176
0
    }
177
0
    OVS_NOT_REACHED();
178
179
0
error:
180
0
    free(po);
181
0
    *pop = NULL;
182
0
    *n_pop = 0;
183
0
    free(short_options);
184
0
    return error;
185
0
}
186
187
/* Given the 'struct ovs_cmdl_command' array, prints the usage of all commands. */
188
void
189
ovs_cmdl_print_commands(const struct ovs_cmdl_command commands[])
190
0
{
191
0
    struct ds ds = DS_EMPTY_INITIALIZER;
192
193
0
    ds_put_cstr(&ds, "The available commands are:\n");
194
0
    for (; commands->name; commands++) {
195
0
        const struct ovs_cmdl_command *c = commands;
196
0
        ds_put_format(&ds, "  %-23s %s\n", c->name, c->usage ? c->usage : "");
197
0
    }
198
0
    printf("%s", ds.string);
199
0
    ds_destroy(&ds);
200
0
}
201
202
/* Given the GNU-style options in 'options', prints all options. */
203
void
204
ovs_cmdl_print_options(const struct option options[])
205
0
{
206
0
    struct ds ds = DS_EMPTY_INITIALIZER;
207
208
0
    for (; options->name; options++) {
209
0
        const struct option *o = options;
210
0
        const char *arg = o->has_arg == required_argument ? "ARG" : "[ARG]";
211
212
0
        ds_put_format(&ds, "--%s%s%s\n", o->name, o->has_arg ? "=" : "",
213
0
                      o->has_arg ? arg : "");
214
0
        if (o->flag == NULL && o->val > 0 && o->val <= UCHAR_MAX) {
215
0
            ds_put_format(&ds, "-%c %s\n", o->val, o->has_arg ? arg : "");
216
0
        }
217
0
    }
218
0
    printf("%s", ds.string);
219
0
    ds_destroy(&ds);
220
0
}
221
222
static void
223
ovs_cmdl_run_command__(struct ovs_cmdl_context *ctx,
224
                       const struct ovs_cmdl_command commands[],
225
                       bool read_only)
226
0
{
227
0
    const struct ovs_cmdl_command *p;
228
229
0
    if (ctx->argc < 1) {
230
0
        ovs_fatal(0, "missing command name; use --help for help");
231
0
    }
232
233
0
    for (p = commands; p->name != NULL; p++) {
234
0
        if (!strcmp(p->name, ctx->argv[0])) {
235
0
            int n_arg = ctx->argc - 1;
236
0
            if (n_arg < p->min_args) {
237
0
                VLOG_FATAL( "'%s' command requires at least %d arguments",
238
0
                            p->name, p->min_args);
239
0
            } else if (n_arg > p->max_args) {
240
0
                VLOG_FATAL("'%s' command takes at most %d arguments",
241
0
                           p->name, p->max_args);
242
0
            } else {
243
0
                if (p->mode == OVS_RW && read_only) {
244
0
                    VLOG_FATAL("'%s' command does not work in read only mode",
245
0
                               p->name);
246
0
                }
247
0
                p->handler(ctx);
248
0
                if (ferror(stdout)) {
249
0
                    VLOG_FATAL("write to stdout failed");
250
0
                }
251
0
                if (ferror(stderr)) {
252
0
                    VLOG_FATAL("write to stderr failed");
253
0
                }
254
0
                return;
255
0
            }
256
0
        }
257
0
    }
258
259
0
    VLOG_FATAL("unknown command '%s'; use --help for help", ctx->argv[0]);
260
0
}
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
 * */
274
void
275
ovs_cmdl_run_command(struct ovs_cmdl_context *ctx,
276
                     const struct ovs_cmdl_command commands[])
277
0
{
278
0
    ovs_cmdl_run_command__(ctx, commands, false);
279
0
}
280
281
void
282
ovs_cmdl_run_command_read_only(struct ovs_cmdl_context *ctx,
283
                               const struct ovs_cmdl_command commands[])
284
0
{
285
0
    ovs_cmdl_run_command__(ctx, commands, true);
286
0
}
287

288
/* Process title. */
289
290
#ifdef __linux__
291
static struct ovs_mutex proctitle_mutex = OVS_MUTEX_INITIALIZER;
292
293
/* Start of command-line arguments in memory. */
294
static char *argv_start OVS_GUARDED_BY(proctitle_mutex);
295
296
/* Number of bytes of command-line arguments. */
297
static size_t argv_size OVS_GUARDED_BY(proctitle_mutex);
298
299
/* Saved command-line arguments. */
300
static char *saved_proctitle OVS_GUARDED_BY(proctitle_mutex);
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.  */
310
void
311
ovs_cmdl_proctitle_init(int argc, char **argv)
312
0
{
313
0
    int i;
314
315
0
    assert_single_threaded();
316
0
    if (!argc || !argv[0]) {
317
        /* This situation should never occur, but... */
318
0
        return;
319
0
    }
320
321
0
    ovs_mutex_lock(&proctitle_mutex);
322
    /* Specialized version of first loop iteration below. */
323
0
    argv_start = argv[0];
324
0
    argv_size = strlen(argv[0]) + 1;
325
0
    argv[0] = xstrdup(argv[0]);
326
327
0
    for (i = 1; i < argc; i++) {
328
0
        size_t size = strlen(argv[i]) + 1;
329
330
        /* Add (argv[i], strlen(argv[i])+1) to (argv_start, argv_size). */
331
0
        if (argv[i] + size == argv_start) {
332
            /* Arguments grow downward in memory. */
333
0
            argv_start -= size;
334
0
            argv_size += size;
335
0
        } else if (argv[i] == argv_start + argv_size) {
336
            /* Arguments grow upward in memory. */
337
0
            argv_size += size;
338
0
        } else {
339
            /* Arguments not contiguous.  (Is this really Linux?) */
340
0
        }
341
342
        /* Copy out the old argument so we can reuse the space. */
343
0
        argv[i] = xstrdup(argv[i]);
344
0
    }
345
0
    ovs_mutex_unlock(&proctitle_mutex);
346
0
}
347
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(). */
350
void
351
ovs_cmdl_proctitle_set(const char *format, ...)
352
0
{
353
0
    va_list args;
354
0
    int n;
355
356
0
    ovs_mutex_lock(&proctitle_mutex);
357
0
    if (!argv_start || argv_size < 8) {
358
0
        goto out;
359
0
    }
360
361
0
    if (!saved_proctitle) {
362
0
        saved_proctitle = xmemdup(argv_start, argv_size);
363
0
    }
364
365
0
    va_start(args, format);
366
0
    n = snprintf(argv_start, argv_size, "%s: ", program_name);
367
0
    if (n < argv_size) {
368
0
        n += vsnprintf(argv_start + n, argv_size - n, format, args);
369
0
    }
370
0
    if (n >= argv_size) {
371
        /* The name is too long, so add an ellipsis at the end. */
372
0
        strcpy(&argv_start[argv_size - 4], "...");
373
0
    } else {
374
        /* Fill the extra space with null bytes, so that trailing bytes don't
375
         * show up in the command line. */
376
0
        memset(&argv_start[n], '\0', argv_size - n);
377
0
    }
378
0
    va_end(args);
379
380
0
out:
381
0
    ovs_mutex_unlock(&proctitle_mutex);
382
0
}
383
384
/* Restores the process's original command line, as seen by "ps". */
385
void
386
ovs_cmdl_proctitle_restore(void)
387
0
{
388
0
    ovs_mutex_lock(&proctitle_mutex);
389
0
    if (saved_proctitle) {
390
0
        memcpy(argv_start, saved_proctitle, argv_size);
391
0
        free(saved_proctitle);
392
0
        saved_proctitle = NULL;
393
0
    }
394
0
    ovs_mutex_unlock(&proctitle_mutex);
395
0
}
396
#else  /* !__linux__ */
397
/* Stubs that don't do anything on non-Linux systems. */
398
399
void
400
ovs_cmdl_proctitle_init(int argc OVS_UNUSED, char **argv OVS_UNUSED)
401
{
402
}
403
404
#if !(defined(__FreeBSD__) || defined(__NetBSD__))
405
/* On these platforms we #define this to setproctitle. */
406
void
407
ovs_cmdl_proctitle_set(const char *format OVS_UNUSED, ...)
408
{
409
}
410
#endif
411
412
void
413
ovs_cmdl_proctitle_restore(void)
414
{
415
}
416
#endif  /* !__linux__ */