]>
git.ipfire.org Git - thirdparty/systemd.git/blob - src/shared/uid-range.c
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/>.
26 #include "uid-range.h"
27 #include "user-util.h"
29 static bool uid_range_intersect(UidRange
*range
, uid_t start
, uid_t nr
) {
32 return range
->start
<= start
+ nr
&&
33 range
->start
+ range
->nr
>= start
;
36 static void uid_range_coalesce(UidRange
**p
, unsigned *n
) {
42 for (i
= 0; i
< *n
; i
++) {
43 for (j
= i
+ 1; j
< *n
; j
++) {
44 UidRange
*x
= (*p
)+i
, *y
= (*p
)+j
;
46 if (uid_range_intersect(x
, y
->start
, y
->nr
)) {
49 begin
= MIN(x
->start
, y
->start
);
50 end
= MAX(x
->start
+ x
->nr
, y
->start
+ y
->nr
);
56 memmove(y
, y
+1, sizeof(UidRange
) * (*n
- j
-1));
66 static int uid_range_compare(const void *a
, const void *b
) {
67 const UidRange
*x
= a
, *y
= b
;
69 if (x
->start
< y
->start
)
71 if (x
->start
> y
->start
)
82 int uid_range_add(UidRange
**p
, unsigned *n
, uid_t start
, uid_t nr
) {
93 for (i
= 0; i
< *n
; i
++) {
95 if (uid_range_intersect(x
, start
, nr
)) {
104 begin
= MIN(x
->start
, start
);
105 end
= MAX(x
->start
+ x
->nr
, start
+ nr
);
112 t
= realloc(*p
, sizeof(UidRange
) * (*n
+ 1));
123 qsort(*p
, *n
, sizeof(UidRange
), uid_range_compare
);
124 uid_range_coalesce(p
, n
);
129 int uid_range_add_str(UidRange
**p
, unsigned *n
, const char *s
) {
143 b
= strndupa(s
, t
- s
);
144 r
= parse_uid(b
, &start
);
148 r
= parse_uid(t
+1, &end
);
155 nr
= end
- start
+ 1;
157 r
= parse_uid(s
, &start
);
164 return uid_range_add(p
, n
, start
, nr
);
167 int uid_range_next_lower(const UidRange
*p
, unsigned n
, uid_t
*uid
) {
168 uid_t closest
= UID_INVALID
, candidate
;
174 candidate
= *uid
- 1;
176 for (i
= 0; i
< n
; i
++) {
180 end
= p
[i
].start
+ p
[i
].nr
- 1;
182 if (candidate
>= begin
&& candidate
<= end
) {
191 if (closest
== UID_INVALID
)
198 bool uid_range_contains(const UidRange
*p
, unsigned n
, uid_t uid
) {
204 for (i
= 0; i
< n
; i
++)
205 if (uid
>= p
[i
].start
&& uid
< p
[i
].start
+ p
[i
].nr
)