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