]>
git.ipfire.org Git - thirdparty/systemd.git/blob - src/shared/uid-range.c
1 /*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
4 This file is part of systemd.
6 Copyright 2014 Lennart Poettering
8 systemd is free software; you can redistribute it and/or modify it
9 under the terms of the GNU Lesser General Public License as published by
10 the Free Software Foundation; either version 2.1 of the License, or
11 (at your option) any later version.
13 systemd is distributed in the hope that it will be useful, but
14 WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 Lesser General Public License for more details.
18 You should have received a copy of the GNU Lesser General Public License
19 along with systemd; If not, see <http://www.gnu.org/licenses/>.
22 #include "uid-range.h"
23 #include "user-util.h"
26 static bool uid_range_intersect(UidRange
*range
, uid_t start
, uid_t nr
) {
29 return range
->start
<= start
+ nr
&&
30 range
->start
+ range
->nr
>= start
;
33 static void uid_range_coalesce(UidRange
**p
, unsigned *n
) {
39 for (i
= 0; i
< *n
; i
++) {
40 for (j
= i
+ 1; j
< *n
; j
++) {
41 UidRange
*x
= (*p
)+i
, *y
= (*p
)+j
;
43 if (uid_range_intersect(x
, y
->start
, y
->nr
)) {
46 begin
= MIN(x
->start
, y
->start
);
47 end
= MAX(x
->start
+ x
->nr
, y
->start
+ y
->nr
);
53 memmove(y
, y
+1, sizeof(UidRange
) * (*n
- j
-1));
63 static int uid_range_compare(const void *a
, const void *b
) {
64 const UidRange
*x
= a
, *y
= b
;
66 if (x
->start
< y
->start
)
68 if (x
->start
> y
->start
)
79 int uid_range_add(UidRange
**p
, unsigned *n
, uid_t start
, uid_t nr
) {
90 for (i
= 0; i
< *n
; i
++) {
92 if (uid_range_intersect(x
, start
, nr
)) {
101 begin
= MIN(x
->start
, start
);
102 end
= MAX(x
->start
+ x
->nr
, start
+ nr
);
109 t
= realloc(*p
, sizeof(UidRange
) * (*n
+ 1));
120 qsort(*p
, *n
, sizeof(UidRange
), uid_range_compare
);
121 uid_range_coalesce(p
, n
);
126 int uid_range_add_str(UidRange
**p
, unsigned *n
, const char *s
) {
140 b
= strndupa(s
, t
- s
);
141 r
= parse_uid(b
, &start
);
145 r
= parse_uid(t
+1, &end
);
152 nr
= end
- start
+ 1;
154 r
= parse_uid(s
, &start
);
161 return uid_range_add(p
, n
, start
, nr
);
164 int uid_range_next_lower(const UidRange
*p
, unsigned n
, uid_t
*uid
) {
165 uid_t closest
= UID_INVALID
, candidate
;
171 candidate
= *uid
- 1;
173 for (i
= 0; i
< n
; i
++) {
177 end
= p
[i
].start
+ p
[i
].nr
- 1;
179 if (candidate
>= begin
&& candidate
<= end
) {
188 if (closest
== UID_INVALID
)
195 bool uid_range_contains(const UidRange
*p
, unsigned n
, uid_t uid
) {
201 for (i
= 0; i
< n
; i
++)
202 if (uid
>= p
[i
].start
&& uid
< p
[i
].start
+ p
[i
].nr
)