Debian Codegraph @

src/basic/parse-util.c

raw
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include <linux/ipv6.h>
4 #include <linux/netfilter/nf_tables.h>
5 #include <stdio.h>
6 #include <stdlib.h>
7 #include <sys/socket.h>
8
9 #include "alloc-util.h"
10 #include "capability-list.h"
11 #include "capability-util.h"
12 #include "errno-list.h"
13 #include "extract-word.h"
14 #include "locale-util.h"
15 #include "log.h"
16 #include "missing-network.h"
17 #include "parse-util.h"
18 #include "path-util.h"
19 #include "process-util.h"
20 #include "string-util.h"
21 #include "strv.h"
22
23 int parse_boolean(const char *v) {
24 if (!v)
25 return -EINVAL;
26
27 if (STRCASE_IN_SET(v,
28 "1",
29 "yes",
30 "y",
31 "true",
32 "t",
33 "on"))
34 return 1;
35
36 if (STRCASE_IN_SET(v,
37 "0",
38 "no",
39 "n",
40 "false",
41 "f",
42 "off"))
43 return 0;
44
45 return -EINVAL;
46 }
47
48 int parse_tristate_full(const char *v, const char *third, int *ret) {
49 int r;
50
51 if (isempty(v) || streq_ptr(v, third)) { /* Empty string is always taken as the third/invalid/auto state */
52 if (ret)
53 *ret = -1;
54 } else {
55 r = parse_boolean(v);
56 if (r < 0)
57 return r;
58
59 if (ret)
60 *ret = r;
61 }
62
63 return 0;
64 }
65
66 int parse_pid(const char *s, pid_t *ret) {
67 unsigned long ul = 0;
68 pid_t pid;
69 int r;
70
71 assert(s);
72
73 r = safe_atolu(s, &ul);
74 if (r < 0)
75 return r;
76
77 pid = (pid_t) ul;
78
79 if ((unsigned long) pid != ul)
80 return -ERANGE;
81
82 if (!pid_is_valid(pid))
83 return -ERANGE;
84
85 if (ret)
86 *ret = pid;
87 return 0;
88 }
89
90 int parse_mode(const char *s, mode_t *ret) {
91 unsigned m;
92 int r;
93
94 assert(s);
95
96 r = safe_atou_full(s, 8 |
97 SAFE_ATO_REFUSE_PLUS_MINUS, /* Leading '+' or even '-' char? that's just weird,
98 * refuse. User might have wanted to add mode flags or
99 * so, but this parser doesn't allow that, so let's
100 * better be safe. */
101 &m);
102 if (r < 0)
103 return r;
104 if (m > 07777)
105 return -ERANGE;
106
107 if (ret)
108 *ret = m;
109 return 0;
110 }
111
112 int parse_ifindex(const char *s) {
113 int ifi, r;
114
115 assert(s);
116
117 r = safe_atoi(s, &ifi);
118 if (r < 0)
119 return r;
120 if (ifi <= 0)
121 return -EINVAL;
122
123 return ifi;
124 }
125
126 int parse_mtu(int family, const char *s, uint32_t *ret) {
127 uint64_t u, m;
128 int r;
129
130 assert(ret);
131
132 r = parse_size(s, 1024, &u);
133 if (r < 0)
134 return r;
135
136 if (u > UINT32_MAX)
137 return -ERANGE;
138
139 switch (family) {
140 case AF_INET:
141 m = IPV4_MIN_MTU; /* This is 68 */
142 break;
143 case AF_INET6:
144 m = IPV6_MIN_MTU; /* This is 1280 */
145 break;
146 default:
147 m = 0;
148 }
149
150 if (u < m)
151 return -ERANGE;
152
153 *ret = (uint32_t) u;
154 return 0;
155 }
156
157 int parse_size(const char *t, uint64_t base, uint64_t *size) {
158
159 /* Soo, sometimes we want to parse IEC binary suffixes, and
160 * sometimes SI decimal suffixes. This function can parse
161 * both. Which one is the right way depends on the
162 * context. Wikipedia suggests that SI is customary for
163 * hardware metrics and network speeds, while IEC is
164 * customary for most data sizes used by software and volatile
165 * (RAM) memory. Hence be careful which one you pick!
166 *
167 * In either case we use just K, M, G as suffix, and not Ki,
168 * Mi, Gi or so (as IEC would suggest). That's because that's
169 * frickin' ugly. But this means you really need to make sure
170 * to document which base you are parsing when you use this
171 * call. */
172
173 struct table {
174 const char *suffix;
175 unsigned long long factor;
176 };
177
178 static const struct table iec[] = {
179 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
180 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
181 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
182 { "G", 1024ULL*1024ULL*1024ULL },
183 { "M", 1024ULL*1024ULL },
184 { "K", 1024ULL },
185 { "B", 1ULL },
186 { "", 1ULL },
187 };
188
189 static const struct table si[] = {
190 { "E", 1000ULL*1000ULL*1000ULL*1000ULL*1000ULL*1000ULL },
191 { "P", 1000ULL*1000ULL*1000ULL*1000ULL*1000ULL },
192 { "T", 1000ULL*1000ULL*1000ULL*1000ULL },
193 { "G", 1000ULL*1000ULL*1000ULL },
194 { "M", 1000ULL*1000ULL },
195 { "K", 1000ULL },
196 { "B", 1ULL },
197 { "", 1ULL },
198 };
199
200 const struct table *table;
201 const char *p;
202 unsigned long long r = 0;
203 unsigned n_entries, start_pos = 0;
204
205 assert(t);
206 assert(IN_SET(base, 1000, 1024));
207 assert(size);
208
209 if (base == 1000) {
210 table = si;
211 n_entries = ELEMENTSOF(si);
212 } else {
213 table = iec;
214 n_entries = ELEMENTSOF(iec);
215 }
216
217 p = t;
218 do {
219 unsigned long long l, tmp;
220 double frac = 0;
221 char *e;
222 unsigned i;
223
224 p += strspn(p, WHITESPACE);
225
226 errno = 0;
227 l = strtoull(p, &e, 10);
228 if (errno > 0)
229 return -errno;
230 if (e == p)
231 return -EINVAL;
232 if (*p == '-')
233 return -ERANGE;
234
235 if (*e == '.') {
236 e++;
237
238 /* strtoull() itself would accept space/+/- */
239 if (ascii_isdigit(*e)) {
240 unsigned long long l2;
241 char *e2;
242
243 l2 = strtoull(e, &e2, 10);
244 if (errno > 0)
245 return -errno;
246
247 /* Ignore failure. E.g. 10.M is valid */
248 frac = l2;
249 for (; e < e2; e++)
250 frac /= 10;
251 }
252 }
253
254 e += strspn(e, WHITESPACE);
255
256 for (i = start_pos; i < n_entries; i++)
257 if (startswith(e, table[i].suffix))
258 break;
259
260 if (i >= n_entries)
261 return -EINVAL;
262
263 if (l + (frac > 0) > ULLONG_MAX / table[i].factor)
264 return -ERANGE;
265
266 tmp = l * table[i].factor + (unsigned long long) (frac * table[i].factor);
267 if (tmp > ULLONG_MAX - r)
268 return -ERANGE;
269
270 r += tmp;
271 if ((unsigned long long) (uint64_t) r != r)
272 return -ERANGE;
273
274 p = e + strlen(table[i].suffix);
275
276 start_pos = i + 1;
277
278 } while (*p);
279
280 *size = r;
281
282 return 0;
283 }
284
285 int parse_sector_size(const char *t, uint64_t *ret) {
286 int r;
287
288 assert(t);
289 assert(ret);
290
291 uint64_t ss;
292
293 r = safe_atou64(t, &ss);
294 if (r < 0)
295 return log_error_errno(r, "Failed to parse sector size parameter %s", t);
296 if (ss < 512 || ss > 4096) /* Allow up to 4K due to dm-crypt support and 4K alignment by the homed LUKS backend */
297 return log_error_errno(SYNTHETIC_ERRNO(ERANGE), "Sector size not between 512 and 4096: %s", t);
298 if (!ISPOWEROF2(ss))
299 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Sector size not power of 2: %s", t);
300
301 *ret = ss;
302 return 0;
303 }
304
305 int parse_range(const char *t, unsigned *lower, unsigned *upper) {
306 _cleanup_free_ char *word = NULL;
307 unsigned l, u;
308 int r;
309
310 assert(lower);
311 assert(upper);
312
313 /* Extract the lower bound. */
314 r = extract_first_word(&t, &word, "-", EXTRACT_DONT_COALESCE_SEPARATORS);
315 if (r < 0)
316 return r;
317 if (r == 0)
318 return -EINVAL;
319
320 r = safe_atou(word, &l);
321 if (r < 0)
322 return r;
323
324 /* Check for the upper bound and extract it if needed */
325 if (!t)
326 /* Single number with no dashes. */
327 u = l;
328 else if (!*t)
329 /* Trailing dash is an error. */
330 return -EINVAL;
331 else {
332 r = safe_atou(t, &u);
333 if (r < 0)
334 return r;
335 }
336
337 *lower = l;
338 *upper = u;
339 return 0;
340 }
341
342 int parse_errno(const char *t) {
343 int r, e;
344
345 assert(t);
346
347 r = errno_from_name(t);
348 if (r > 0)
349 return r;
350
351 r = safe_atoi(t, &e);
352 if (r < 0)
353 return r;
354
355 /* 0 is also allowed here */
356 if (!errno_is_valid(e) && e != 0)
357 return -ERANGE;
358
359 return e;
360 }
361
362 int parse_fd(const char *t) {
363 int r, fd;
364
365 assert(t);
366
367 r = safe_atoi(t, &fd);
368 if (r < 0)
369 return r;
370
371 if (fd < 0)
372 return -EBADF;
373
374 return fd;
375 }
376
377 int parse_user_shell(const char *s, char **ret_sh, bool *ret_copy) {
378 char *sh;
379 int r;
380
381 assert(ret_sh);
382 assert(ret_copy);
383
384 if (path_is_absolute(s) && path_is_normalized(s)) {
385 sh = strdup(s);
386 if (!sh)
387 return -ENOMEM;
388
389 *ret_sh = sh;
390 *ret_copy = false;
391 } else {
392 r = parse_boolean(s);
393 if (r < 0)
394 return r;
395
396 *ret_sh = NULL;
397 *ret_copy = r;
398 }
399
400 return 0;
401 }
402
403 static const char *mangle_base(const char *s, unsigned *base) {
404 const char *k;
405
406 assert(s);
407 assert(base);
408
409 /* Base already explicitly specified, then don't do anything. */
410 if (SAFE_ATO_MASK_FLAGS(*base) != 0)
411 return s;
412
413 /* Support Python 3 style "0b" and 0x" prefixes, because they truly make sense, much more than C's "0" prefix for octal. */
414 k = STARTSWITH_SET(s, "0b", "0B");
415 if (k) {
416 *base = 2 | (*base & SAFE_ATO_ALL_FLAGS);
417 return k;
418 }
419
420 k = STARTSWITH_SET(s, "0o", "0O");
421 if (k) {
422 *base = 8 | (*base & SAFE_ATO_ALL_FLAGS);
423 return k;
424 }
425
426 return s;
427 }
428
429 int safe_atou_full(const char *s, unsigned base, unsigned *ret_u) {
430 char *x = NULL;
431 unsigned long l;
432
433 assert(s);
434 assert(SAFE_ATO_MASK_FLAGS(base) <= 16);
435
436 /* strtoul() is happy to parse negative values, and silently converts them to unsigned values without
437 * generating an error. We want a clean error, hence let's look for the "-" prefix on our own, and
438 * generate an error. But let's do so only after strtoul() validated that the string is clean
439 * otherwise, so that we return EINVAL preferably over ERANGE. */
440
441 if (FLAGS_SET(base, SAFE_ATO_REFUSE_LEADING_WHITESPACE) &&
442 strchr(WHITESPACE, s[0]))
443 return -EINVAL;
444
445 s += strspn(s, WHITESPACE);
446
447 if (FLAGS_SET(base, SAFE_ATO_REFUSE_PLUS_MINUS) &&
448 IN_SET(s[0], '+', '-'))
449 return -EINVAL; /* Note that we check the "-" prefix again a second time below, but return a
450 * different error. I.e. if the SAFE_ATO_REFUSE_PLUS_MINUS flag is set we
451 * blanket refuse +/- prefixed integers, while if it is missing we'll just
452 * return ERANGE, because the string actually parses correctly, but doesn't
453 * fit in the return type. */
454
455 if (FLAGS_SET(base, SAFE_ATO_REFUSE_LEADING_ZERO) &&
456 s[0] == '0' && !streq(s, "0"))
457 return -EINVAL; /* This is particularly useful to avoid ambiguities between C's octal
458 * notation and assumed-to-be-decimal integers with a leading zero. */
459
460 s = mangle_base(s, &base);
461
462 errno = 0;
463 l = strtoul(s, &x, SAFE_ATO_MASK_FLAGS(base) /* Let's mask off the flags bits so that only the actual
464 * base is left */);
465 if (errno > 0)
466 return -errno;
467 if (!x || x == s || *x != 0)
468 return -EINVAL;
469 if (l != 0 && s[0] == '-')
470 return -ERANGE;
471 if ((unsigned long) (unsigned) l != l)
472 return -ERANGE;
473
474 if (ret_u)
475 *ret_u = (unsigned) l;
476
477 return 0;
478 }
479
480 int safe_atou_bounded(const char *s, unsigned min, unsigned max, unsigned *ret) {
481 unsigned v;
482 int r;
483
484 assert(ret);
485
486 r = safe_atou(s, &v);
487 if (r < 0)
488 return r;
489
490 if (v < min || v > max)
491 return -ERANGE;
492
493 *ret = v;
494 return 0;
495 }
496
497 int safe_atoi(const char *s, int *ret_i) {
498 unsigned base = 0;
499 char *x = NULL;
500 long l;
501
502 assert(s);
503
504 s += strspn(s, WHITESPACE);
505 s = mangle_base(s, &base);
506
507 errno = 0;
508 l = strtol(s, &x, base);
509 if (errno > 0)
510 return -errno;
511 if (!x || x == s || *x != 0)
512 return -EINVAL;
513 if ((long) (int) l != l)
514 return -ERANGE;
515
516 if (ret_i)
517 *ret_i = (int) l;
518
519 return 0;
520 }
521
522 int safe_atollu_full(const char *s, unsigned base, unsigned long long *ret_llu) {
523 char *x = NULL;
524 unsigned long long l;
525
526 assert(s);
527 assert(SAFE_ATO_MASK_FLAGS(base) <= 16);
528
529 if (FLAGS_SET(base, SAFE_ATO_REFUSE_LEADING_WHITESPACE) &&
530 strchr(WHITESPACE, s[0]))
531 return -EINVAL;
532
533 s += strspn(s, WHITESPACE);
534
535 if (FLAGS_SET(base, SAFE_ATO_REFUSE_PLUS_MINUS) &&
536 IN_SET(s[0], '+', '-'))
537 return -EINVAL;
538
539 if (FLAGS_SET(base, SAFE_ATO_REFUSE_LEADING_ZERO) &&
540 s[0] == '0' && s[1] != 0)
541 return -EINVAL;
542
543 s = mangle_base(s, &base);
544
545 errno = 0;
546 l = strtoull(s, &x, SAFE_ATO_MASK_FLAGS(base));
547 if (errno > 0)
548 return -errno;
549 if (!x || x == s || *x != 0)
550 return -EINVAL;
551 if (l != 0 && s[0] == '-')
552 return -ERANGE;
553
554 if (ret_llu)
555 *ret_llu = l;
556
557 return 0;
558 }
559
560 int safe_atolli(const char *s, long long *ret_lli) {
561 unsigned base = 0;
562 char *x = NULL;
563 long long l;
564
565 assert(s);
566
567 s += strspn(s, WHITESPACE);
568 s = mangle_base(s, &base);
569
570 errno = 0;
571 l = strtoll(s, &x, base);
572 if (errno > 0)
573 return -errno;
574 if (!x || x == s || *x != 0)
575 return -EINVAL;
576
577 if (ret_lli)
578 *ret_lli = l;
579
580 return 0;
581 }
582
583 int safe_atou8_full(const char *s, unsigned base, uint8_t *ret) {
584 unsigned u;
585 int r;
586
587 assert(ret);
588
589 r = safe_atou_full(s, base, &u);
590 if (r < 0)
591 return r;
592 if (u > UINT8_MAX)
593 return -ERANGE;
594
595 *ret = (uint8_t) u;
596 return 0;
597 }
598
599 int safe_atou16_full(const char *s, unsigned base, uint16_t *ret) {
600 unsigned u;
601 int r;
602
603 assert(ret);
604
605 r = safe_atou_full(s, base, &u);
606 if (r < 0)
607 return r;
608 if (u > UINT16_MAX)
609 return -ERANGE;
610
611 *ret = (uint16_t) u;
612 return 0;
613 }
614
615 int safe_atoi16(const char *s, int16_t *ret) {
616 unsigned base = 0;
617 char *x = NULL;
618 long l;
619
620 assert(s);
621
622 s += strspn(s, WHITESPACE);
623 s = mangle_base(s, &base);
624
625 errno = 0;
626 l = strtol(s, &x, base);
627 if (errno > 0)
628 return -errno;
629 if (!x || x == s || *x != 0)
630 return -EINVAL;
631 if ((long) (int16_t) l != l)
632 return -ERANGE;
633
634 if (ret)
635 *ret = (int16_t) l;
636
637 return 0;
638 }
639
640 int safe_atod(const char *s, double *ret_d) {
641 _cleanup_(freelocalep) locale_t loc = (locale_t) 0;
642 char *x = NULL;
643 double d = 0;
644
645 assert(s);
646
647 loc = newlocale(LC_NUMERIC_MASK, "C", (locale_t) 0);
648 if (loc == (locale_t) 0)
649 return -errno;
650
651 errno = 0;
652 d = strtod_l(s, &x, loc);
653 if (errno > 0)
654 return -errno;
655 if (!x || x == s || *x != 0)
656 return -EINVAL;
657
658 if (ret_d)
659 *ret_d = d;
660
661 return 0;
662 }
663
664 int parse_fractional_part_u(const char **p, size_t digits, unsigned *res) {
665 unsigned val = 0;
666 const char *s;
667
668 assert(p);
669 assert(res);
670
671 s = *p;
672
673 /* accept any number of digits, strtoull is limited to 19 */
674 for (size_t i = 0; i < digits; i++, s++) {
675 if (!ascii_isdigit(*s)) {
676 if (i == 0)
677 return -EINVAL;
678
679 /* too few digits, pad with 0 */
680 for (; i < digits; i++)
681 val *= 10;
682
683 break;
684 }
685
686 val *= 10;
687 val += *s - '0';
688 }
689
690 /* maybe round up */
691 if (*s >= '5' && *s <= '9')
692 val++;
693
694 s += strspn(s, DIGITS);
695
696 *p = s;
697 *res = val;
698
699 return 0;
700 }
701
702 int parse_nice(const char *s, int *ret) {
703 int n, r;
704
705 assert(ret);
706
707 r = safe_atoi(s, &n);
708 if (r < 0)
709 return r;
710
711 if (!nice_is_valid(n))
712 return -ERANGE;
713
714 *ret = n;
715 return 0;
716 }
717
718 int parse_ip_port(const char *s, uint16_t *ret) {
719 uint16_t l;
720 int r;
721
722 assert(ret);
723
724 r = safe_atou16_full(s, SAFE_ATO_REFUSE_LEADING_WHITESPACE, &l);
725 if (r < 0)
726 return r;
727
728 if (l == 0)
729 return -EINVAL;
730
731 *ret = l;
732
733 return 0;
734 }
735
736 int parse_ip_port_range(const char *s, uint16_t *low, uint16_t *high, bool allow_zero) {
737 unsigned l, h;
738 int r;
739
740 assert(low);
741 assert(high);
742
743 r = parse_range(s, &l, &h);
744 if (r < 0)
745 return r;
746
747 if (l > 65535 || h > 65535)
748 return -EINVAL;
749
750 if (!allow_zero && (l == 0 || h == 0))
751 return -EINVAL;
752
753 if (h < l)
754 return -EINVAL;
755
756 *low = l;
757 *high = h;
758
759 return 0;
760 }
761
762 int parse_oom_score_adjust(const char *s, int *ret) {
763 int r, v;
764
765 assert(s);
766 assert(ret);
767
768 r = safe_atoi(s, &v);
769 if (r < 0)
770 return r;
771
772 if (!oom_score_adjust_is_valid(v))
773 return -ERANGE;
774
775 *ret = v;
776 return 0;
777 }
778
779 int store_loadavg_fixed_point(unsigned long i, unsigned long f, loadavg_t *ret) {
780 assert(ret);
781
782 if (i >= (~0UL << LOADAVG_PRECISION_BITS))
783 return -ERANGE;
784
785 i = i << LOADAVG_PRECISION_BITS;
786 f = DIV_ROUND_UP((f << LOADAVG_PRECISION_BITS), 100);
787
788 if (f >= LOADAVG_FIXED_POINT_1_0)
789 return -ERANGE;
790
791 *ret = i | f;
792 return 0;
793 }
794
795 int parse_loadavg_fixed_point(const char *s, loadavg_t *ret) {
796 const char *d, *f_str, *i_str;
797 unsigned long i, f;
798 int r;
799
800 assert(s);
801 assert(ret);
802
803 d = strchr(s, '.');
804 if (!d)
805 return -EINVAL;
806
807 i_str = strndupa_safe(s, d - s);
808 f_str = d + 1;
809
810 r = safe_atolu_full(i_str, 10, &i);
811 if (r < 0)
812 return r;
813
814 r = safe_atolu_full(f_str, 10, &f);
815 if (r < 0)
816 return r;
817
818 return store_loadavg_fixed_point(i, f, ret);
819 }
820
821 /* Limitations are described in https://www.netfilter.org/projects/nftables/manpage.html and
822 * https://bugzilla.netfilter.org/show_bug.cgi?id=1175 */
823 bool nft_identifier_valid(const char *id) {
824 if (isempty(id))
825 return false;
826
827 if (strlen(id) >= NFT_NAME_MAXLEN)
828 return false;
829
830 if (!ascii_isalpha(id[0]))
831 return false;
832
833 return in_charset(id + 1, ALPHANUMERICAL "/\\_.");
834 }
835
836 int parse_capability_set(const char *s, uint64_t initial, uint64_t *current) {
837 int r;
838
839 assert(s);
840 assert(current);
841
842 if (isempty(s)) {
843 *current = CAP_MASK_UNSET;
844 return 1;
845 }
846
847 bool invert = false;
848 if (s[0] == '~') {
849 invert = true;
850 s++;
851 }
852
853 uint64_t parsed;
854 r = capability_set_from_string(s, &parsed);
855 if (r < 0)
856 return r;
857
858 if (parsed == 0 || *current == initial)
859 /* "~" or uninitialized data -> replace */
860 *current = invert ? all_capabilities() & ~parsed : parsed;
861 else {
862 /* previous data -> merge */
863 if (invert)
864 *current &= ~parsed;
865 else
866 *current |= parsed;
867 }
868
869 return r;
870 }