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/>.
23 #include "uid-range.h"
25 static bool uid_range_intersect(UidRange *range, uid_t start, uid_t nr) {
28 return range->start <= start + nr &&
29 range->start + range->nr >= start;
32 static void uid_range_coalesce(UidRange **p, unsigned *n) {
38 for (i = 0; i < *n; i++) {
39 for (j = i + 1; j < *n; j++) {
40 UidRange *x = (*p)+i, *y = (*p)+j;
42 if (uid_range_intersect(x, y->start, y->nr)) {
45 begin = MIN(x->start, y->start);
46 end = MAX(x->start + x->nr, y->start + y->nr);
52 memmove(y, y+1, sizeof(UidRange) * (*n - j -1));
62 static int uid_range_compare(const void *a, const void *b) {
63 const UidRange *x = a, *y = b;
65 if (x->start < y->start)
67 if (x->start > y->start)
78 int uid_range_add(UidRange **p, unsigned *n, uid_t start, uid_t nr) {
89 for (i = 0; i < *n; i++) {
91 if (uid_range_intersect(x, start, nr)) {
100 begin = MIN(x->start, start);
101 end = MAX(x->start + x->nr, start + nr);
108 t = realloc(*p, sizeof(UidRange) * (*n + 1));
119 qsort(*p, *n, sizeof(UidRange), uid_range_compare);
120 uid_range_coalesce(p, n);
125 int uid_range_add_str(UidRange **p, unsigned *n, const char *s) {
139 b = strndupa(s, t - s);
140 r = parse_uid(b, &start);
144 r = parse_uid(t+1, &end);
151 nr = end - start + 1;
153 r = parse_uid(s, &start);
160 return uid_range_add(p, n, start, nr);
163 int uid_range_next_lower(const UidRange *p, unsigned n, uid_t *uid) {
164 uid_t closest = UID_INVALID, candidate;
170 candidate = *uid - 1;
172 for (i = 0; i < n; i++) {
176 end = p[i].start + p[i].nr - 1;
178 if (candidate >= begin && candidate <= end) {
187 if (closest == UID_INVALID)
194 bool uid_range_contains(const UidRange *p, unsigned n, uid_t uid) {
200 for (i = 0; i < n; i++)
201 if (uid >= p[i].start && uid < p[i].start + p[i].nr)