]>
git.ipfire.org Git - thirdparty/systemd.git/blob - src/shared/uid-range.c
37d7c981f2b9cb3f6953aca7d8004347d58c56a6
1 /* SPDX-License-Identifier: LGPL-2.1+ */
3 This file is part of systemd.
5 Copyright 2014 Lennart Poettering
7 systemd is free software; you can redistribute it and/or modify it
8 under the terms of the GNU Lesser General Public License as published by
9 the Free Software Foundation; either version 2.1 of the License, or
10 (at your option) any later version.
12 systemd is distributed in the hope that it will be useful, but
13 WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 Lesser General Public License for more details.
17 You should have received a copy of the GNU Lesser General Public License
18 along with systemd; If not, see <http://www.gnu.org/licenses/>.
25 #include "alloc-util.h"
27 #include "uid-range.h"
28 #include "user-util.h"
30 static bool uid_range_intersect(UidRange
*range
, uid_t start
, uid_t nr
) {
33 return range
->start
<= start
+ nr
&&
34 range
->start
+ range
->nr
>= start
;
37 static void uid_range_coalesce(UidRange
**p
, unsigned *n
) {
43 for (i
= 0; i
< *n
; i
++) {
44 for (j
= i
+ 1; j
< *n
; j
++) {
45 UidRange
*x
= (*p
)+i
, *y
= (*p
)+j
;
47 if (uid_range_intersect(x
, y
->start
, y
->nr
)) {
50 begin
= MIN(x
->start
, y
->start
);
51 end
= MAX(x
->start
+ x
->nr
, y
->start
+ y
->nr
);
57 memmove(y
, y
+1, sizeof(UidRange
) * (*n
- j
-1));
67 static int uid_range_compare(const void *a
, const void *b
) {
68 const UidRange
*x
= a
, *y
= b
;
70 if (x
->start
< y
->start
)
72 if (x
->start
> y
->start
)
83 int uid_range_add(UidRange
**p
, unsigned *n
, uid_t start
, uid_t nr
) {
94 for (i
= 0; i
< *n
; i
++) {
96 if (uid_range_intersect(x
, start
, nr
)) {
105 begin
= MIN(x
->start
, start
);
106 end
= MAX(x
->start
+ x
->nr
, start
+ nr
);
113 t
= reallocarray(*p
, *n
+ 1, sizeof(UidRange
));
124 qsort(*p
, *n
, sizeof(UidRange
), uid_range_compare
);
125 uid_range_coalesce(p
, n
);
130 int uid_range_add_str(UidRange
**p
, unsigned *n
, const char *s
) {
144 b
= strndupa(s
, t
- s
);
145 r
= parse_uid(b
, &start
);
149 r
= parse_uid(t
+1, &end
);
156 nr
= end
- start
+ 1;
158 r
= parse_uid(s
, &start
);
165 return uid_range_add(p
, n
, start
, nr
);
168 int uid_range_next_lower(const UidRange
*p
, unsigned n
, uid_t
*uid
) {
169 uid_t closest
= UID_INVALID
, candidate
;
175 candidate
= *uid
- 1;
177 for (i
= 0; i
< n
; i
++) {
181 end
= p
[i
].start
+ p
[i
].nr
- 1;
183 if (candidate
>= begin
&& candidate
<= end
) {
192 if (closest
== UID_INVALID
)
199 bool uid_range_contains(const UidRange
*p
, unsigned n
, uid_t uid
) {
205 for (i
= 0; i
< n
; i
++)
206 if (uid
>= p
[i
].start
&& uid
< p
[i
].start
+ p
[i
].nr
)