Debian Codegraph @

src/shared/options.c

raw
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include "format-table.h"
4 #include "log.h"
5 #include "options.h"
6 #include "stdio-util.h"
7 #include "string-util.h"
8 #include "strv.h"
9
10 static bool option_takes_arg(const Option *opt) {
11 return ASSERT_PTR(opt)->metavar;
12 }
13
14 static bool option_arg_optional(const Option *opt) {
15 return option_takes_arg(opt) && FLAGS_SET(opt->flags, OPTION_OPTIONAL_ARG);
16 }
17
18 static bool option_arg_required(const Option *opt) {
19 return option_takes_arg(opt) && !FLAGS_SET(opt->flags, OPTION_OPTIONAL_ARG);
20 }
21
22 static bool option_is_metadata(const Option *opt) {
23 /* A metadata entry that is not a real option, like the group marker */
24 return ASSERT_PTR(opt)->flags & (OPTION_NAMESPACE_MARKER |
25 OPTION_GROUP_MARKER |
26 OPTION_POSITIONAL_ENTRY |
27 OPTION_HELP_ENTRY |
28 OPTION_HELP_ENTRY_VERBATIM);
29 }
30
31 static void shift_arg(char* argv[], int target, int source) {
32 assert(argv);
33 assert(target <= source);
34
35 /* Move argv[source] before argv[target], shifting the arguments in between. */
36 char *saved = argv[source];
37 memmove(argv + target + 1, argv + target, (source - target) * sizeof(char*));
38 argv[target] = saved;
39 }
40
41 static int partial_match_error(
42 const OptionParser *state,
43 const Option options[],
44 const Option options_end[],
45 const char *optname,
46 unsigned n_partial_matches) {
47 int r;
48
49 assert(startswith(ASSERT_PTR(optname), "--"));
50 assert(n_partial_matches >= 2);
51
52 /* Find options that match the prefix */
53 _cleanup_strv_free_ char **s = NULL;
54 for (const Option* option = options; option < options_end; option++)
55 if (!option_is_metadata(option) &&
56 option->long_code &&
57 startswith(option->long_code, optname + 2)) {
58
59 r = strv_extendf(&s, "--%s", option->long_code);
60 if (r < 0)
61 return log_full_errno(LOG_ERR + state->log_level_shift, r,
62 "Failed to format message: %m");
63 }
64
65 assert(strv_length(s) == n_partial_matches);
66
67 _cleanup_free_ char *p = strv_join_full(s, ", ", /* prefix= */ NULL, /* escape_separator= */ false);
68 return log_full_errno(LOG_ERR + state->log_level_shift,
69 SYNTHETIC_ERRNO(EINVAL),
70 "%s: option '%s' is ambiguous; possibilities: %s",
71 program_invocation_short_name, optname, strnull(p));
72 }
73
74 int option_parse(
75 const Option options[],
76 const Option options_end[],
77 OptionParser *state) {
78
79 /* We define this one early, since we use goto below, and need to guarantee its initialization */
80 _cleanup_free_ char *_optname = NULL; /* allocated option name */
81 int r;
82
83 assert(state);
84
85 /* Check and initialize */
86 switch (state->state) {
87
88 case OPTION_PARSER_INIT: {
89 assert(state->mode >= 0 && state->mode < _OPTION_PARSER_MODE_MAX);
90 /* Make sure the shifted log level is between LOG_EMERG/0 and LOG_DEBUG/7. */
91 assert(state->log_level_shift >= LOG_EMERG - LOG_ERR &&
92 state->log_level_shift <= LOG_DEBUG - LOG_ERR);
93
94 if (state->argc < 1) {
95 r = log_full_errno(LOG_ERR + state->log_level_shift,
96 SYNTHETIC_ERRNO(EUCLEAN),
97 "argv cannot be empty");
98 goto fail;
99 }
100
101 assert_se((size_t) state->argc == strv_length(state->argv)); /* Make sure argc/argv are consistent */
102
103 /* Figure out the right range of options */
104 bool in_ns = state->namespace == NULL; /* Are we currently in the section of the array that
105 * forms namespace <namespace>? The first part is the
106 * default unnamed namespace, so if the namespace was
107 * not specified, we are in it. */
108 if (in_ns)
109 state->namespace_start = options;
110
111 const Option *opt;
112
113 /* Verify that the option array didn't get mangled within a namespace. */
114 for (opt = options; opt < options_end; opt++)
115 if (opt + 1 < options_end && !FLAGS_SET((opt + 1)->flags, OPTION_NAMESPACE_MARKER))
116 assert_se(opt->id < (opt + 1)->id);
117
118 for (opt = options; opt < options_end; opt++) {
119 bool ns_marker = FLAGS_SET(opt->flags, OPTION_NAMESPACE_MARKER);
120 if (!in_ns) {
121 in_ns = ns_marker && streq(state->namespace, opt->long_code);
122 if (in_ns)
123 state->namespace_start = opt + 1;
124 continue;
125 }
126 if (ns_marker)
127 break; /* End of namespace */
128 }
129 assert(state->namespace_start);
130 state->namespace_end = opt;
131
132 state->optind = state->positional_offset = 1;
133 state->state = OPTION_PARSER_RUNNING;
134 break;
135 }
136
137 case OPTION_PARSER_RUNNING:
138 case OPTION_PARSER_STOPPING:
139 break;
140
141 case OPTION_PARSER_DONE:
142 goto done;
143
144 case OPTION_PARSER_FAILED:
145 return log_full_errno(LOG_ERR + state->log_level_shift,
146 SYNTHETIC_ERRNO(ESTALE),
147 "Option parser failed before, refusing.");
148
149 default:
150 assert_not_reached();
151 }
152
153 /* Look for the next option */
154
155 const Option *option = NULL; /* initialization to appease gcc 13 */
156 const char *optname = NULL, *optval = NULL;
157 bool separate_optval = false;
158 bool handling_positional_arg = false;
159
160 if (state->short_option_offset == 0) {
161 /* Handle non-option parameters */
162 for (;;) {
163 if (state->optind == state->argc)
164 goto done;
165
166 if (streq(state->argv[state->optind], "--")) {
167 /* No more options. Move "--" before positional args so that
168 * the list of positional args is clean. */
169 shift_arg(state->argv, state->positional_offset++, state->optind++);
170 goto done;
171 }
172
173 /* If we are in OPTION_PARSER_STOPPING state we only wanted to read one more "--" if
174 * there is one, nothing else, hence it's time to say goodbye now. */
175 if (state->state == OPTION_PARSER_STOPPING)
176 goto done;
177
178 if (state->argv[state->optind][0] == '-' &&
179 state->argv[state->optind][1] != '\0')
180 /* Looks like we found an option parameter */
181 break;
182
183 if (state->mode == OPTION_PARSER_STOP_AT_FIRST_NONOPTION)
184 goto done;
185
186 if (state->mode == OPTION_PARSER_RETURN_POSITIONAL_ARGS) {
187 handling_positional_arg = true;
188 optval = state->argv[state->optind];
189 break;
190 }
191
192 state->optind++;
193 }
194
195 /* Find matching option entry.
196 * First, figure out if we have a long option or a short option. */
197 assert(handling_positional_arg || state->argv[state->optind][0] == '-');
198
199 if (handling_positional_arg)
200 /* We are supposed to return the positional arg to be handled. */
201 for (option = state->namespace_start;; option++) {
202 /* If OPTION_PARSER_RETURN_POSITIONAL_ARGS is specified,
203 * OPTION_POSITIONAL must be used. */
204 assert(option < state->namespace_end);
205
206 if (FLAGS_SET(option->flags, OPTION_POSITIONAL_ENTRY))
207 break;
208 }
209
210 else if (state->argv[state->optind][1] == '-') {
211 /* We have a long option. */
212 char *eq = strchr(state->argv[state->optind], '=');
213 if (eq) {
214 optname = _optname = strndup(state->argv[state->optind], eq - state->argv[state->optind]);
215 if (!_optname) {
216 r = log_oom_full(LOG_ERR + state->log_level_shift);
217 goto fail;
218 }
219
220 /* joined argument */
221 optval = eq + 1;
222 } else
223 /* argument (if any) is separate */
224 optname = state->argv[state->optind];
225
226 const Option *last_partial = NULL;
227 unsigned n_partial_matches = 0; /* The commandline option matches a defined prefix. */
228
229 for (option = state->namespace_start;; option++) {
230 if (option >= state->namespace_end) {
231 if (n_partial_matches == 0) {
232 r = log_full_errno(LOG_ERR + state->log_level_shift,
233 SYNTHETIC_ERRNO(EINVAL),
234 "%s: unrecognized option '%s'",
235 program_invocation_short_name, optname);
236 goto fail;
237 }
238 if (n_partial_matches > 1) {
239 r = partial_match_error(
240 state,
241 state->namespace_start,
242 state->namespace_end,
243 optname,
244 n_partial_matches);
245 goto fail;
246 }
247
248 /* just one partial — good */
249 option = last_partial;
250 break;
251 }
252
253 if (option_is_metadata(option) || !option->long_code)
254 continue;
255
256 /* Check if the parameter forms a prefix of the option name */
257 const char *rest = startswith(option->long_code, optname + 2);
258 if (!rest)
259 continue;
260 if (isempty(rest))
261 /* exact match */
262 break;
263 /* partial match */
264 last_partial = option;
265 n_partial_matches++;
266 }
267 } else
268 /* We have a short option */
269 state->short_option_offset = 1;
270 }
271
272 if (state->short_option_offset > 0) {
273 char optchar = state->argv[state->optind][state->short_option_offset];
274
275 if (asprintf(&_optname, "-%c", optchar) < 0) {
276 r = log_oom_full(LOG_ERR + state->log_level_shift);
277 goto fail;
278 }
279 optname = _optname;
280
281 for (option = state->namespace_start;; option++) {
282 if (option >= state->namespace_end) {
283 r = log_full_errno(LOG_ERR + state->log_level_shift,
284 SYNTHETIC_ERRNO(EINVAL),
285 "%s: unrecognized option '%s'",
286 program_invocation_short_name, optname);
287 goto fail;
288 }
289
290 if (option_is_metadata(option) || optchar != option->short_code)
291 continue;
292
293 const char *rest = state->argv[state->optind] + state->short_option_offset + 1;
294
295 if (option_takes_arg(option) && !isempty(rest)) {
296 /* The rest of this parameter is the value. */
297 optval = rest;
298 state->short_option_offset = 0;
299 } else if (isempty(rest))
300 state->short_option_offset = 0;
301 else
302 state->short_option_offset++;
303
304 break;
305 }
306 }
307
308 assert(option);
309
310 if (!handling_positional_arg && optval && !option_takes_arg(option)) {
311 r = log_full_errno(LOG_ERR + state->log_level_shift,
312 SYNTHETIC_ERRNO(EINVAL),
313 "%s: option '%s' doesn't allow an argument",
314 program_invocation_short_name, optname);
315 goto fail;
316 }
317 if (!handling_positional_arg && !optval && option_arg_required(option)) {
318 if (!state->argv[state->optind + 1]) {
319 r = log_full_errno(LOG_ERR + state->log_level_shift,
320 SYNTHETIC_ERRNO(EINVAL),
321 "%s: option '%s' requires an argument",
322 program_invocation_short_name, optname);
323 goto fail;
324 }
325 optval = state->argv[state->optind + 1];
326 separate_optval = true;
327 }
328
329 if (state->short_option_offset == 0) {
330 /* We're done with this parameter. Adjust the array and position. */
331 if (handling_positional_arg) {
332 /* Sanity check */
333 assert(state->positional_offset == state->optind);
334 assert(!separate_optval);
335 }
336
337 shift_arg(state->argv, state->positional_offset++, state->optind++);
338 if (separate_optval)
339 shift_arg(state->argv, state->positional_offset++, state->optind++);
340 }
341
342 if (FLAGS_SET(option->flags, OPTION_STOPS_PARSING))
343 state->state = OPTION_PARSER_STOPPING;
344
345 state->opt = option;
346 state->arg = optval;
347 return option->id;
348
349 done:
350 state->state = OPTION_PARSER_DONE;
351 state->opt = NULL;
352 state->arg = NULL;
353 return 0;
354
355 fail:
356 /* Invalidate the object for good on the first error */
357 assert(r < 0);
358 state->state = OPTION_PARSER_FAILED;
359 return r;
360 }
361
362 char* option_parser_peek_next_arg(const OptionParser *state) {
363 /* Peek at the next argument, whatever it is (option or position arg).
364 * May return NULL. */
365
366 assert(state->optind > 0);
367 assert(state->positional_offset <= state->argc);
368
369 return state->optind < state->argc ? state->argv[state->optind] : NULL;
370 }
371
372 char* option_parser_consume_next_arg(OptionParser *state) {
373 /* "Take" the next argument, whatever it is (option or position arg).
374 * The argument remains in the array, but the optind pointer is moved
375 * so we won't try to interpret it as an option.
376 * May return NULL. */
377
378 char *t = option_parser_peek_next_arg(state);
379 if (t)
380 shift_arg(state->argv, state->positional_offset++, state->optind++);
381 return t;
382 }
383
384 char** option_parser_get_args(const OptionParser *state) {
385 /* Returns positional args as a strv.
386 * If "--" was found, it has been moved before state->positional_offset.
387 * The array is only valid, i.e. clean without any options, after parsing
388 * has naturally finished. The array that is returned is a slice of the
389 * original argv array, so it must not be freed or modified. */
390
391 assert(state->optind > 0);
392 assert(state->state == OPTION_PARSER_DONE);
393 assert(state->positional_offset <= state->argc);
394
395 return state->argv + state->positional_offset;
396 }
397
398 size_t option_parser_get_n_args(const OptionParser *state) {
399 assert(state->optind > 0);
400 assert(state->state == OPTION_PARSER_DONE);
401 assert(state->positional_offset <= state->argc);
402
403 return state->argc - state->positional_offset;
404 }
405
406 char* option_parser_get_arg(const OptionParser *state, size_t i) {
407 assert(state->optind > 0);
408 assert(state->state == OPTION_PARSER_DONE);
409 assert(state->positional_offset <= state->argc);
410
411 return (size_t) (state->argc - state->positional_offset) > i ? state->argv[state->positional_offset + i] : NULL;
412 }
413
414 char* option_get_synopsis(const Option *opt, const char *joiner, bool show_metavar) {
415 assert(opt);
416 assert(!(opt->flags & (OPTION_NAMESPACE_MARKER |
417 OPTION_GROUP_MARKER))); /* The markers should not be displayed */
418
419 if (opt->flags & (OPTION_HELP_ENTRY_VERBATIM | OPTION_POSITIONAL_ENTRY))
420 return strdup(ASSERT_PTR(opt->long_code));
421
422 /* The option formatted appropriately for --help strings, error messages, and similar:
423 * -<short><joiner>--<long>=[<metavar>]
424 * "=" is shown only when a long form is defined: -l --long=ARG, --long=ARG, -s ARG.
425 * The joiner arg is used between the short and long forms.
426 * As a special case, if the option has no long form and show_metavar is true,
427 * a space is used ('-a ARG' or '-a [ARG]').
428 */
429 assert(opt->short_code != 0 || opt->long_code);
430
431 char sc[3] = "";
432 if (opt->short_code != 0)
433 xsprintf(sc, "-%c", opt->short_code);
434
435 if (show_metavar && opt->metavar && !opt->long_code)
436 joiner = " "; /* Return '-x ARG', no matter what joiner was specified. */
437 else if (opt->short_code == 0 || !opt->long_code)
438 joiner = "";
439 else if (!joiner)
440 joiner = " ";
441
442 bool need_eq = option_takes_arg(opt) && opt->long_code;
443 if (!show_metavar)
444 return strjoin(sc,
445 joiner,
446 opt->long_code ? "--" : "",
447 strempty(opt->long_code),
448 need_eq ? "=" : "");
449
450 bool need_quote = opt->metavar && strchr(opt->metavar, ' ');
451 return strjoin(sc,
452 joiner,
453 opt->long_code ? "--" : "",
454 strempty(opt->long_code),
455 option_arg_optional(opt) ? "[" : "",
456 need_eq ? "=" : "",
457 need_quote ? "'" : "",
458 strempty(opt->metavar),
459 need_quote ? "'" : "",
460 option_arg_optional(opt) ? "]" : "");
461 }
462
463 int _option_parser_get_help_table_full(
464 const Option options[],
465 const Option options_end[],
466 const char *namespace,
467 const char *group,
468 Table **ret) {
469 int r;
470
471 assert(ret);
472
473 _cleanup_(table_unrefp) Table *table = table_new("names", "help");
474 if (!table)
475 return log_oom();
476
477 bool in_ns = namespace == NULL; /* Are we currently in the section of the array that forms namespace
478 * <namespace>? The first part is the default unnamed namespace, so
479 * if the namespace was not specified, we are in it. */
480
481 bool in_group = group == NULL; /* Are we currently in the section of the array that forms group
482 * <group>? The first part is the default group, so if the group was
483 * not specified, we are in it. */
484
485 for (const Option *opt = options; opt < options_end; opt++) {
486 bool ns_marker = FLAGS_SET(opt->flags, OPTION_NAMESPACE_MARKER);
487 if (!in_ns) {
488 in_ns = ns_marker && streq(namespace, opt->long_code);
489 continue;
490 }
491 if (ns_marker)
492 break; /* End of namespace */
493
494 bool group_marker = FLAGS_SET(opt->flags, OPTION_GROUP_MARKER);
495 if (!in_group) {
496 in_group = group_marker && streq(group, opt->long_code);
497 continue;
498 }
499 if (group_marker)
500 break; /* End of group */
501
502 if (!opt->help)
503 /* No help string — we do not show the option */
504 continue;
505
506 _cleanup_free_ char *s = option_get_synopsis(opt, " ", /* show_metavar= */ true);
507 if (!s)
508 return log_oom();
509
510 /* We indent the option string by two spaces. We could set the minimum cell width and
511 * right-align for a similar result, but that'd be more work. This is only used for
512 * display. */
513 bool shift_left = opt->short_code != 0 || FLAGS_SET(opt->flags, OPTION_HELP_ENTRY_VERBATIM);
514 const char *prefix = shift_left ? " " : " ";
515 _cleanup_free_ char *t = strjoin(prefix, s);
516 if (!t)
517 return log_oom();
518
519 r = table_add_many(table, TABLE_STRING, t);
520 if (r < 0)
521 return table_log_add_error(r);
522
523 _cleanup_strv_free_ char **split = strv_split(opt->help, /* separators= */ NULL);
524 if (!split)
525 return log_oom();
526
527 r = table_add_many(table, TABLE_STRV_WRAPPED, split);
528 if (r < 0)
529 return table_log_add_error(r);
530 }
531
532 assert(!table_isempty(table)); /* The namespace or group were not found. Something is off. */
533
534 table_set_header(table, false);
535 *ret = TAKE_PTR(table);
536 return 0;
537 }