]>
git.ipfire.org Git - thirdparty/systemd.git/blob - src/shared/uid-range.c
2 This file is part of systemd.
4 Copyright 2014 Lennart Poettering
6 systemd is free software; you can redistribute it and/or modify it
7 under the terms of the GNU Lesser General Public License as published by
8 the Free Software Foundation; either version 2.1 of the License, or
9 (at your option) any later version.
11 systemd is distributed in the hope that it will be useful, but
12 WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 Lesser General Public License for more details.
16 You should have received a copy of the GNU Lesser General Public License
17 along with systemd; If not, see <http://www.gnu.org/licenses/>.
25 #include "uid-range.h"
26 #include "user-util.h"
28 static bool uid_range_intersect(UidRange
*range
, uid_t start
, uid_t nr
) {
31 return range
->start
<= start
+ nr
&&
32 range
->start
+ range
->nr
>= start
;
35 static void uid_range_coalesce(UidRange
**p
, unsigned *n
) {
41 for (i
= 0; i
< *n
; i
++) {
42 for (j
= i
+ 1; j
< *n
; j
++) {
43 UidRange
*x
= (*p
)+i
, *y
= (*p
)+j
;
45 if (uid_range_intersect(x
, y
->start
, y
->nr
)) {
48 begin
= MIN(x
->start
, y
->start
);
49 end
= MAX(x
->start
+ x
->nr
, y
->start
+ y
->nr
);
55 memmove(y
, y
+1, sizeof(UidRange
) * (*n
- j
-1));
65 static int uid_range_compare(const void *a
, const void *b
) {
66 const UidRange
*x
= a
, *y
= b
;
68 if (x
->start
< y
->start
)
70 if (x
->start
> y
->start
)
81 int uid_range_add(UidRange
**p
, unsigned *n
, uid_t start
, uid_t nr
) {
92 for (i
= 0; i
< *n
; i
++) {
94 if (uid_range_intersect(x
, start
, nr
)) {
103 begin
= MIN(x
->start
, start
);
104 end
= MAX(x
->start
+ x
->nr
, start
+ nr
);
111 t
= realloc(*p
, sizeof(UidRange
) * (*n
+ 1));
122 qsort(*p
, *n
, sizeof(UidRange
), uid_range_compare
);
123 uid_range_coalesce(p
, n
);
128 int uid_range_add_str(UidRange
**p
, unsigned *n
, const char *s
) {
142 b
= strndupa(s
, t
- s
);
143 r
= parse_uid(b
, &start
);
147 r
= parse_uid(t
+1, &end
);
154 nr
= end
- start
+ 1;
156 r
= parse_uid(s
, &start
);
163 return uid_range_add(p
, n
, start
, nr
);
166 int uid_range_next_lower(const UidRange
*p
, unsigned n
, uid_t
*uid
) {
167 uid_t closest
= UID_INVALID
, candidate
;
173 candidate
= *uid
- 1;
175 for (i
= 0; i
< n
; i
++) {
179 end
= p
[i
].start
+ p
[i
].nr
- 1;
181 if (candidate
>= begin
&& candidate
<= end
) {
190 if (closest
== UID_INVALID
)
197 bool uid_range_contains(const UidRange
*p
, unsigned n
, uid_t uid
) {
203 for (i
= 0; i
< n
; i
++)
204 if (uid
>= p
[i
].start
&& uid
< p
[i
].start
+ p
[i
].nr
)