Header cleanup.
[adu.git] / adu.c
1 #include "adu.h"
2 #include <dirent.h> /* readdir() */
3 #include <pwd.h>
4
5 #include "gcc-compat.h"
6 #include "cmdline.h"
7 #include "fd.h"
8 #include "string.h"
9 #include "error.h"
10 #include "portable_io.h"
11
12 DEFINE_ERRLIST;
13 int osl_errno;
14
15 /** In case a signal is received, its number is stored here. */
16 static int signum;
17
18 /** Command line and config file options. */
19 struct gengetopt_args_info conf;
20
21 /** The number of different uids found so far. */
22 uint32_t num_uids = 0;
23
24 /** This is always a power of two. It is set in create_hash_table(). */
25 static uint32_t uid_hash_table_size;
26
27 /**
28 * Contains info for each user that owns at least one regular file.
29 *
30 * Even users that are not taken into account because of the --uid
31 * option occupy a slot in this hash table. This allows to find out
32 * quicky whether a uid is admissible. And yes, this has to be fast.
33 */
34 static struct user_info *uid_hash_table;
35
36 static inline int ui_used(struct user_info *ui)
37 {
38 return ui->flags & UI_FL_SLOT_USED;
39 }
40
41 static inline int ui_admissible(struct user_info *ui)
42 {
43 return ui->flags & UI_FL_ADMISSIBLE;
44 }
45
46 /**
47 * The table containing the directory names and statistics.
48 */
49 struct osl_table *dir_table = NULL;
50
51 /**
52 * The array of all uid ranges that were given at the command line.
53 */
54 struct uid_range *admissible_uids;
55
56
57 /**
58 * Compare the size of two directories
59 *
60 * \param obj1 Pointer to the first object.
61 * \param obj2 Pointer to the second object.
62 *
63 * This function first compares the size values as usual integers. If they compare as
64 * equal, the address of \a obj1 and \a obj2 are compared. So this compare function
65 * returns zero if and only if \a obj1 and \a obj2 point to the same memory area.
66 */
67 static int size_compare(const struct osl_object *obj1, const struct osl_object *obj2)
68 {
69 uint64_t d1 = *(uint64_t *)obj1->data;
70 uint64_t d2 = *(uint64_t *)obj2->data;
71 int ret = NUM_COMPARE(d2, d1);
72
73 if (ret)
74 return ret;
75 //INFO_LOG("addresses: %p, %p\n", obj1->data, obj2->data);
76 return NUM_COMPARE(obj2->data, obj1->data);
77 }
78
79 /**
80 * Compare two osl objects pointing to unsigned integers of 64 bit size.
81 *
82 * \param obj1 Pointer to the first integer.
83 * \param obj2 Pointer to the second integer.
84 *
85 * \return The values required for an osl compare function.
86 *
87 * \sa osl_compare_func, osl_hash_compare().
88 */
89 static int uint64_compare(const struct osl_object *obj1,
90 const struct osl_object *obj2)
91 {
92 uint64_t d1 = read_u64((const char *)obj1->data);
93 uint64_t d2 = read_u64((const char *)obj2->data);
94
95 if (d1 < d2)
96 return 1;
97 if (d1 > d2)
98 return -1;
99 return 0;
100 }
101
102 static struct osl_column_description dir_table_cols[] = {
103 [DT_NAME] = {
104 .storage_type = OSL_MAPPED_STORAGE,
105 .storage_flags = 0,
106 .name = "dir",
107 },
108 [DT_NUM] = {
109 .storage_type = OSL_MAPPED_STORAGE,
110 .storage_flags = OSL_RBTREE | OSL_FIXED_SIZE | OSL_UNIQUE,
111 .name = "num",
112 .compare_function = uint64_compare,
113 .data_size = sizeof(uint64_t)
114 },
115 [DT_PARENT_NUM] = {
116 .storage_type = OSL_MAPPED_STORAGE,
117 .storage_flags = OSL_RBTREE | OSL_FIXED_SIZE | OSL_UNIQUE,
118 .name = "parent_num",
119 .compare_function = size_compare,
120 .data_size = sizeof(uint64_t)
121 },
122 [DT_BYTES] = {
123 .storage_type = OSL_MAPPED_STORAGE,
124 .storage_flags = OSL_RBTREE | OSL_FIXED_SIZE,
125 .compare_function = size_compare,
126 .name = "num_bytes",
127 .data_size = sizeof(uint64_t)
128 },
129 [DT_FILES] = {
130 .storage_type = OSL_MAPPED_STORAGE,
131 .storage_flags = OSL_RBTREE | OSL_FIXED_SIZE,
132 .compare_function = size_compare,
133 .name = "num_files",
134 .data_size = sizeof(uint64_t)
135 }
136 };
137
138 static struct osl_table_description dir_table_desc = {
139 .name = "dir_table",
140 .num_columns = NUM_DT_COLUMNS,
141 .flags = 0,
142 .column_descriptions = dir_table_cols,
143 };
144
145 static struct osl_column_description user_table_cols[] = {
146 [UT_DIR_NUM] = {
147 .storage_type = OSL_MAPPED_STORAGE,
148 .storage_flags = OSL_RBTREE | OSL_FIXED_SIZE | OSL_UNIQUE,
149 .name = "dir_num",
150 .compare_function = uint64_compare,
151 .data_size = sizeof(uint64_t)
152 },
153 [UT_BYTES] = {
154 .storage_type = OSL_MAPPED_STORAGE,
155 .storage_flags = OSL_RBTREE | OSL_FIXED_SIZE,
156 .compare_function = size_compare,
157 .name = "num_bytes",
158 .data_size = sizeof(uint64_t)
159 },
160 [UT_FILES] = {
161 .storage_type = OSL_MAPPED_STORAGE,
162 .storage_flags = OSL_RBTREE | OSL_FIXED_SIZE,
163 .compare_function = size_compare,
164 .name = "num_files",
165 .data_size = sizeof(uint64_t)
166 },
167 };
168
169 static int check_uid_arg(const char *arg, uint32_t *uid)
170 {
171 const uint32_t max = ~0U;
172 /*
173 * we need an 64-bit int for string -> uid conversion because strtoll()
174 * returns a signed value.
175 */
176 int64_t val;
177 int ret = atoi64(arg, &val);
178
179 if (ret < 0)
180 return ret;
181 if (val < 0 || val > max)
182 return -ERRNO_TO_ERROR(EINVAL);
183 *uid = val;
184 return 1;
185 }
186
187 static int parse_uid_range(const char *orig_arg, struct uid_range *ur)
188 {
189 int ret;
190 char *arg = adu_strdup(orig_arg), *p = strchr(arg, '-');
191
192 if (!p || p == arg) { /* -42 or 42 */
193 ret = check_uid_arg(p? p + 1 : arg, &ur->high);
194 if (ret < 0)
195 goto out;
196 ur->low = p? 0 : ur->high;
197 ret = 1;
198 goto out;
199 }
200 /* 42- or 42-4711 */
201 *p = '\0';
202 p++;
203 ret = check_uid_arg(arg, &ur->low);
204 if (ret < 0)
205 goto out;
206 ur->high = ~0U;
207 if (*p) { /* 42-4711 */
208 ret = check_uid_arg(p, &ur->high);
209 if (ret < 0)
210 goto out;
211 }
212 if (ur->low > ur->high)
213 ret = -ERRNO_TO_ERROR(EINVAL);
214 out:
215 if (ret < 0)
216 ERROR_LOG("bad uid option: %s\n", orig_arg);
217 else
218 INFO_LOG("admissible uid range: %u - %u\n", ur->low,
219 ur->high);
220 free(arg);
221 return ret;
222 }
223
224 /**
225 * The log function.
226 *
227 * \param ll Loglevel.
228 * \param fml Usual format string.
229 *
230 * All XXX_LOG() macros use this function.
231 */
232 __printf_2_3 void __log(int ll, const char* fmt,...)
233 {
234 va_list argp;
235 FILE *outfd;
236 struct tm *tm;
237 time_t t1;
238 char str[255] = "";
239
240 if (ll < conf.loglevel_arg)
241 return;
242 outfd = stderr;
243 time(&t1);
244 tm = localtime(&t1);
245 strftime(str, sizeof(str), "%b %d %H:%M:%S", tm);
246 fprintf(outfd, "%s ", str);
247 va_start(argp, fmt);
248 vfprintf(outfd, fmt, argp);
249 va_end(argp);
250 }
251
252 static int open_user_table(struct user_info *ui, int create)
253 {
254 int ret;
255 struct passwd *pw;
256
257 ui->desc = adu_malloc(sizeof(*ui->desc));
258 ui->desc->num_columns = NUM_UT_COLUMNS;
259 ui->desc->flags = 0;
260 ui->desc->column_descriptions = user_table_cols;
261 ui->desc->dir = adu_strdup(conf.database_dir_arg);
262 ui->desc->name = make_message("%u", (unsigned)ui->uid);
263 pw = getpwuid(ui->uid);
264 if (pw && pw->pw_name)
265 ui->pw_name = adu_strdup(pw->pw_name);
266
267 INFO_LOG(".............................uid #%u: %u\n",
268 (unsigned)num_uids, (unsigned)ui->uid);
269 if (create) {
270 ret = osl(osl_create_table(ui->desc));
271 if (ret < 0)
272 goto err;
273 num_uids++;
274 }
275 ret = osl(osl_open_table(ui->desc, &ui->table));
276 if (ret < 0)
277 goto err;
278 return 1;
279 err:
280 free((char *)ui->desc->name);
281 free((char *)ui->desc->dir);
282 free(ui->pw_name);
283 free(ui->desc);
284 ui->desc->name = NULL;
285 ui->desc->dir = NULL;
286 ui->desc = NULL;
287 ui->table = NULL;
288 ui->flags = 0;
289 return ret;
290 }
291
292 int for_each_admissible_user(int (*func)(struct user_info *, void *),
293 void *data)
294 {
295 struct user_info *ui = uid_hash_table;
296
297 if (!ui)
298 return -ERRNO_TO_ERROR(EFAULT);
299
300 for (; ui < uid_hash_table + uid_hash_table_size; ui++) {
301 int ret;
302
303 if (!ui_used(ui) || !ui_admissible(ui))
304 continue;
305 ret = func(ui, data);
306 if (ret < 0)
307 return ret;
308 }
309 return 1;
310 }
311
312 #define PRIME1 0x811c9dc5
313 #define PRIME2 0x01000193
314
315 void create_hash_table(unsigned bits)
316 {
317 uid_hash_table_size = 1 << bits;
318 uid_hash_table = adu_calloc(uid_hash_table_size *
319 sizeof(struct user_info));
320 }
321
322 static void free_hash_table(void)
323 {
324 free(uid_hash_table);
325 uid_hash_table = NULL;
326 }
327
328 static void close_dir_table(void)
329 {
330 int ret;
331
332 if (!dir_table)
333 return;
334 ret = osl(osl_close_table(dir_table, OSL_MARK_CLEAN));
335 if (ret < 0)
336 ERROR_LOG("failed to close dir table: %s\n", adu_strerror(-ret));
337 free((char *)dir_table_desc.dir);
338 dir_table = NULL;
339 }
340
341 static int close_user_table(struct user_info *ui, __a_unused void *data)
342 {
343 int ret;
344
345 ret = osl(osl_close_table(ui->table, OSL_MARK_CLEAN));
346 if (ret < 0)
347 ERROR_LOG("failed to close user table %u: %s\n",
348 (unsigned) ui->uid, adu_strerror(-ret));
349 free((char *)ui->desc->name);
350 ui->desc->name = NULL;
351 free((char *)ui->desc->dir);
352 ui->desc->dir = NULL;
353 free(ui->pw_name);
354 ui->pw_name = NULL;
355 free(ui->desc);
356 ui->desc = NULL;
357 ui->table = NULL;
358 ui->flags = 0;
359 return 1;
360 }
361
362 static void close_user_tables(void)
363 {
364 for_each_admissible_user(close_user_table, NULL);
365 }
366
367 void close_all_tables(void)
368 {
369 close_dir_table();
370 close_user_tables();
371 free_hash_table();
372 }
373
374 static void signal_handler(int s)
375 {
376 signum = s;
377 }
378
379 void check_signals(void)
380 {
381 if (likely(!signum))
382 return;
383 EMERG_LOG("caught signal %d\n", signum);
384 close_all_tables();
385 exit(EXIT_FAILURE);
386 }
387
388 static int init_signals(void)
389 {
390 if (signal(SIGINT, &signal_handler) == SIG_ERR)
391 return -E_SIGNAL_SIG_ERR;
392 if (signal(SIGTERM, &signal_handler) == SIG_ERR)
393 return -E_SIGNAL_SIG_ERR;
394 if (signal(SIGPIPE, &signal_handler) == SIG_ERR)
395 return -E_SIGNAL_SIG_ERR;
396 return 1;
397 }
398
399 /*
400 * We use a hash table of size s=2^uid_hash_bits to map the uids into the
401 * interval [0..s]. Hash collisions are treated by open addressing, i.e.
402 * unused slots in the table are used to store different uids that hash to the
403 * same slot.
404 *
405 * If a hash collision occurs, different slots are successively probed in order
406 * to find an unused slot for the new uid. Probing is implemented via a second
407 * hash function that maps the uid to h=(uid * PRIME2) | 1, which is always an
408 * odd number.
409 *
410 * An odd number is sufficient to make sure each entry of the hash table gets
411 * probed for probe_num between 0 and s-1 because s is a power of two, hence
412 * the second hash value has never a common divisor with the hash table size.
413 * IOW: h is invertible in the ring [0..s].
414 */
415 static uint32_t double_hash(uint32_t uid, uint32_t probe_num)
416 {
417 return (uid * PRIME1 + ((uid * PRIME2) | 1) * probe_num)
418 % uid_hash_table_size;
419 }
420
421 static int uid_is_admissible(uint32_t uid)
422 {
423 int i;
424
425 for (i = 0; i < conf.uid_given; i++) {
426 struct uid_range *ur = admissible_uids + i;
427
428 if (ur->low <= uid && ur->high >= uid)
429 break;
430 }
431 i = !conf.uid_given || i < conf.uid_given;
432 DEBUG_LOG("uid %u is %sadmissible\n", (unsigned)uid,
433 i? "" : "not ");
434 return i;
435 }
436
437 int search_uid(uint32_t uid, enum search_uid_flags flags,
438 struct user_info **ui_ptr)
439 {
440 uint32_t p;
441
442 for (p = 0; p < uid_hash_table_size; p++) {
443 struct user_info *ui = uid_hash_table + double_hash(uid, p);
444
445 if (!ui_used(ui)) {
446 int ret;
447 if (!flags)
448 return -E_BAD_UID;
449 ui->uid = uid;
450 ui->flags |= UI_FL_SLOT_USED;
451 if (!uid_is_admissible(uid))
452 return 0;
453 ui->flags |= UI_FL_ADMISSIBLE;
454 ret = open_user_table(ui, flags & CREATE_USER_TABLE);
455 if (ret < 0)
456 return ret;
457
458 if (ui_ptr)
459 *ui_ptr = ui;
460 return 1;
461 }
462 if (ui->uid != uid)
463 continue;
464 if (ui_ptr)
465 *ui_ptr = ui;
466 return 0;
467 }
468 return flags? -E_HASH_TABLE_OVERFLOW : -E_BAD_UID;
469 }
470
471 char *get_uid_list_name(void)
472 {
473 return make_message("%s/uid_list", conf.database_dir_arg);
474 }
475
476 void sort_hash_table(int (*comp)(const void *, const void *))
477 {
478 qsort(uid_hash_table, uid_hash_table_size, sizeof(struct user_info),
479 comp);
480 }
481
482 int open_dir_table(int create)
483 {
484 dir_table_desc.dir = adu_strdup(conf.database_dir_arg);
485
486 if (create) {
487 int ret = osl(osl_create_table(&dir_table_desc));
488 if (ret < 0) {
489 free((char *)dir_table_desc.dir);
490 return ret;
491 }
492 }
493 return osl(osl_open_table(&dir_table_desc, &dir_table));
494 }
495
496 static int check_args(void)
497 {
498 int i, ret;
499
500
501 if (conf.create_given && !conf.base_dir_given)
502 return -E_SYNTAX;
503
504 /* remove trailing slashes from base-dir arg */
505 if (conf.base_dir_given) {
506 size_t len = strlen(conf.base_dir_arg);
507 for (;;) {
508 if (!len) /* empty string */
509 return -ERRNO_TO_ERROR(EINVAL);
510 if (!--len) /* length 1 is always OK */
511 break;
512 if (conf.base_dir_arg[len] != '/')
513 break; /* no trailing slash, also OK */
514 conf.base_dir_arg[len] = '\0';
515 }
516 }
517 if (!conf.uid_given)
518 return 0;
519 admissible_uids = adu_malloc(conf.uid_given * sizeof(*admissible_uids));
520 for (i = 0; i < conf.uid_given; i++) {
521 ret = parse_uid_range(conf.uid_arg[i], admissible_uids + i);
522 if (ret < 0)
523 goto err;
524 }
525 return 1;
526 err:
527 free(admissible_uids);
528 admissible_uids = NULL;
529 return ret;
530 }
531
532 int main(int argc, char **argv)
533 {
534 int ret;
535 struct cmdline_parser_params params = {
536 .override = 0,
537 .initialize = 1,
538 .check_required = 1,
539 .check_ambiguity = 1,
540 .print_errors = 1
541 };
542
543 cmdline_parser_ext(argc, argv, &conf, &params); /* aborts on errors */
544 ret = check_args();
545 if (ret < 0)
546 goto out;
547 ret = init_signals();
548 if (ret < 0)
549 goto out;
550 ret = -E_SYNTAX;
551 if (conf.select_given)
552 ret = com_select();
553 else
554 ret = com_create();
555 if (ret < 0)
556 goto out;
557 out:
558 free(admissible_uids);
559 if (ret < 0) {
560 ERROR_LOG("%s\n", adu_strerror(-ret));
561 return -EXIT_FAILURE;
562 }
563 return EXIT_SUCCESS;
564 }