aboutsummaryrefslogtreecommitdiffstats
path: root/src/db.c
blob: f5f46da4f0adc970387ba557e384c60df22ec578 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
/*
 * Copyright (C) 2018 "IoT.bzh"
 * Author José Bollo <jose.bollo@iot.bzh>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */


#define _GNU_SOURCE


#include <assert.h>
#include <stdlib.h>
#include <stdint.h>
#include <stdbool.h>
#include <stdalign.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>

#include "fbuf.h"
#include "db.h"

#define NOIDX   0

#define ANYIDX  40
#define ANYSTR  "#"

#define WIDEIDX 42
#define WIDESTR "*"

/**
 * A rule is a set of 4 integers
 */
struct rule
{
	uint32_t client, user, permission, value;
};
typedef struct rule rule_t;

/**
 * Sessions
 */
struct session
{
	struct session *next, *prev;
	rule_t *rules;
	const char *name;
	uint32_t count;
};
typedef struct session session_t;

/*
 * The cynara-agl database is made of 2 memory mapped files:
 *  - names: the zero terminated names
 *  - rules: the rules based on name indexes as 32bits indexes
 * These files are normally in /var/lib/cynara
 */
#if !defined(DEFAULT_DB_DIR)
#    define  DEFAULT_DB_DIR  "/var/lib/cynara"
#endif
static const char db_default_directory[] = DEFAULT_DB_DIR;

/** the file for the names */
static fbuf_t fnames;

/** the file for the rules */
static fbuf_t frules;

/** identification of names version 1 (uuidgen --sha1 -n @url -N urn:AGL:cynara:db:names:1) */
static const char uuid_names_v1[] = "e9481f9e-b2f4-5716-90cf-c286d98d1868\n--\n";

/** identification of rules version 1 (uuidgen --sha1 -n @url -N urn:AGL:cynara:db:rules:1) */
static const char uuid_rules_v1[] = "8f7a5b21-48b1-57af-96c9-d5d7192be370\n--\n";

/** length of the identification */
static const int uuidlen = 40;

/** count of names */
static uint32_t names_count;

/** the name indexes sorted */
static uint32_t *names_sorted;

/** the sessions */
static session_t sessions = {
	.next = &sessions,
	.prev = &sessions,
	.name = WIDESTR
};

/** return the name of 'index' */
static
const char*
name_at(
	uint32_t index
) {
	return (const char*)(fnames.buffer + index);
}

/** compare names. used by qsort and bsearch */
static
int
cmpnames(
	const void *pa,
	const void *pb
) {
	uint32_t a = *(const uint32_t*)pa;
	uint32_t b = *(const uint32_t*)pb;
	return strcmp(name_at(a), name_at(b));
}

/** search the index of 'name' and create it if 'needed' */
int
db_get_name_index(
	uint32_t *index,
	const char *name,
	bool needed
) {
	uint32_t lo, up, m, i, *p;
	int c;
	const char *n;
	size_t len;

	/* special names */
	if (!name || !name[0])
		name = ANYSTR;

	/* dichotomic search */
	lo = 0;
	up = names_count;
	while(lo < up) {
		m = (lo + up) >> 1;
		i = names_sorted[m];
		n = name_at(i);
		c = strcmp(n, name);

		if (c == 0) {
			/* found */
			*index = i;
			return 0;
		}

		/* dichotomic iteration */
		if (c < 0)
			lo = m + 1;
		else
			up = m;
	}

	/* not found */
	if (!needed) {
		errno = ENOENT;
		return -1;
	}

	/* check length */
	len = strnlen(name, MAX_NAME_LENGTH + 1);
	if (len > MAX_NAME_LENGTH) {
		errno = EINVAL;
		return -1;
	}

	/* add the name in the file */
	i = fnames.used;
	c = fbuf_append(&fnames, name, 1 + (uint32_t)len);
	if (c < 0)
		return c;

	/* add the name in sorted array */
	up = names_count;
	if (!(up & 1023)) {
		p = realloc(names_sorted, (up + 1024) * sizeof *names_sorted);
		if (p == NULL) {
			fprintf(stderr, "out of memory");
			return -1;
		}
		names_sorted = p;
	}
	memmove(&names_sorted[lo + 1], &names_sorted[lo], (up - lo) * sizeof *names_sorted);
	names_count = up + 1;
	*index = names_sorted[lo] = i;
	return 0;
}

/** initialize names */
static
int
init_names(
) {
	int rc;
	uint32_t pos, len, *ns, *p, all, nc;

	all = 0;
	nc = 0;
	ns = NULL;

	/* iterate over names */
	pos = uuidlen;
	while (pos < fnames.saved) {
		/* get name length */
		len = (uint32_t)strlen(name_at(pos));
		if (pos + len <= pos || pos + len > fnames.saved) {
			free(ns);
			goto bad_file;
		}
		/* store the position */
		if (all <= nc) {
			all += 1024;
			p = realloc(ns, all * sizeof *ns);
			if (p == NULL) {
				free(ns);
				fprintf(stderr, "out of memory");
				goto error;
			}
			ns = p;
		}
		ns[nc++] = pos;
		/* next */
		pos += len + 1;
	}

	/* sort and record */
	qsort(ns, nc, sizeof *ns, cmpnames);
	names_sorted = ns;
	names_count = nc;

	/* predefined symbols */
	rc = db_get_name_index(&pos, ANYSTR, true);
	if (rc < 0)
		goto error;
	if (pos != ANYIDX)
		goto bad_file;
	rc = db_get_name_index(&pos, WIDESTR, true);
	if (rc < 0)
		goto error;
	if (pos != WIDEIDX)
		goto bad_file;

	return 0;
bad_file:
	fprintf(stderr, "bad file %s", fnames.name);
	errno = ENOEXEC;
error:
	return -1;
}

/** check whether the 'text' fit ANYSTR, NULL or ""  */
static
bool
is_any(
	const char *text
) {
	return text == NULL || text[0] == 0 || 0 == strcmp(text, ANYSTR);
}

/** check whether the 'text' fit ANYSTR, WIDESTR, NULL or ""  */
static
bool
is_any_or_wide(
	const char *text
) {
	return is_any(text) || 0 == strcmp(text, WIDESTR);
}

/** get in 'session' the session for 'name' and create it if 'needed' */
static
int
get_session(
	const char *name,
	bool needed,
	session_t **session
) {
	session_t *s;
	size_t len;

	/* start on ANY sessions */
	s = &sessions;
	if (is_any_or_wide(name))
		goto found;

	/* look to other sessions */
	s = s->next;
	while(s != &sessions) {
		if (!strcmp(s->name, name))
			goto found;
		s = s->next;
	}

	/* not found */
	if (!needed) {
		errno = ENOENT;
		return -1;
	}

	/* check length */
	len = strnlen(name, MAX_NAME_LENGTH + 1);
	if (len > MAX_NAME_LENGTH) {
		errno = EINVAL;
		return -1;
	}

	/* create it */
	s = malloc(sizeof * s + len + 1);
	if (s == NULL)
		return -1; /* out of memory */

	/* init new session */
	s->rules = NULL;
	s->count = 0;
	s->name = strcpy((char*)(s + 1), name);
	s->next = &sessions;
	s->prev = sessions.prev;
	sessions.prev = s;
	s->prev->next = s;
found:
	*session = s;
	return 0;
}

/** for 'session' set the value the rule at 'index' */
static
void
session_set_at(
	session_t *session,
	uint32_t index,
	uint32_t value
) {
	uint32_t pos;

	assert(index < session->count);
	session->rules[index].value = value;
	if (session == &sessions) {
		pos = (uint32_t)(((void*)&session->rules[index]) - frules.buffer);
		if (pos < frules.saved)
			frules.saved = pos;
	}
}

/** drop of 'session' the rule at 'index' */
static
void
session_drop_at(
	session_t *session,
	uint32_t index
) {
	uint32_t pos;

	assert(index < session->count);
	if (index < --session->count)
		session->rules[index] = session->rules[session->count];
	if (session == &sessions) {
		pos = (uint32_t)(((void*)&session->rules[index]) - frules.buffer);
		if (pos < frules.saved)
			frules.saved = pos;
		pos = (uint32_t)(((void*)&session->rules[session->count]) - frules.buffer);
		frules.used = pos;
	}
}

/** add to 'session' the rule 'client' x 'user' x 'permission' x 'value' */
static
int
session_add(
	session_t *session,
	uint32_t client,
	uint32_t user,
	uint32_t permission,
	uint32_t value
) {
	int rc;
	uint32_t c;
	rule_t *rule;

	if (session == &sessions) {
		c = frules.used + (uint32_t)sizeof *rule;
		rc = fbuf_ensure_capacity(&frules, c);
		if (rc)
			return rc;
		frules.used = c;
		session->rules = (rule_t*)(frules.buffer + uuidlen);
	} else {
		c = session->count + 32 - (session->count & 31);
		rule = realloc(session->rules, c * sizeof *rule);
		if (rule == NULL)
			return -ENOMEM;
		session->rules = rule;
	}
	rule = &session->rules[session->count++];
	rule->client = client;
	rule->user = user;
	rule->permission = permission;
	rule->value = value;
	return 0;
}

/** init the rules from the file */
static
void
init_rules(
) {
	sessions.rules = (rule_t*)(frules.buffer + uuidlen);
	sessions.count = (frules.used - uuidlen) / sizeof *sessions.rules;
}

/** open a fbuf */
static
int
open_identify(
	fbuf_t	*fb,
	const char *directory,
	const char *name,
	const char *id,
	uint32_t idlen
) {
	int rc;
	char *file, *backup;

	rc = asprintf(&file, "%s/%s", directory, name);
	if (rc < 0)
		rc = -ENOMEM;
	else {
		rc = asprintf(&backup, "%s~", file);
		if (rc < 0)
			rc = -ENOMEM;
		else {
			rc = fbuf_open_identify(fb, file, backup, id, idlen);
			free(backup);
		}
		free(file);
	}
	return rc;
}

/** open the database for files 'names' and 'rules' (can be NULL) */
int
db_open(
	const char *directory
) {
	int rc;

	/* provide default directory */
	if (directory == NULL)
		directory = db_default_directory;

	/* open the names */
	rc = open_identify(&fnames, directory, "cynara.names", uuid_names_v1, uuidlen);
	if (rc < 0)
		goto error;

	/* open the rules */
	rc = open_identify(&frules, directory, "cynara.rules", uuid_rules_v1, uuidlen);
	if (rc < 0)
		goto error;

	/* connect internals */
	rc = init_names();
	if (rc < 0)
		goto error;

	init_rules();
	return 0;
error:
	return -1;
}

/** close the database */
void
db_close(
) {
	assert(fnames.name && frules.name);
	fbuf_close(&fnames);
	fbuf_close(&frules);
}

/** is the database empty */
bool
db_is_empty(
) {
	return !sessions.count;
}

/** synchronize db on files */
int
db_sync(
) {
	int rc;

	assert(fnames.name && frules.name);
	rc = fbuf_sync(&fnames);
	if (rc == 0)
		rc = fbuf_sync(&frules);
	return rc;
}

/** make a backup of the database */
int
db_backup(
) {
	int rc;

	assert(fnames.name && frules.name);
	rc = fbuf_backup(&fnames);
	if (rc == 0)
		rc = fbuf_backup(&frules);
	return rc;
}

/** recover the database from latest backup */
int
db_recover(
) {
	int rc;

	assert(fnames.name && frules.name);

	rc = fbuf_recover(&fnames);
	if (rc < 0)
		goto error;

	rc = fbuf_recover(&frules);
	if (rc < 0)
		goto error;

	rc = init_names();
	if (rc < 0)
		goto error;

	init_rules();
	return 0;
error:
	fprintf(stderr, "db recovering impossible: %m");
	exit(5);
	return rc;
}

/** enumerate */
void
db_for_all(
	void *closure,
	void (*callback)(
		void *closure,
		const char *client,
		const char *session,
		const char *user,
		const char *permission,
		uint32_t value),
	const char *client,
	const char *session,
	const char *user,
	const char *permission
) {
	uint32_t ucli, uusr, i;
	bool anyperm, anysession;
	session_t *ses;

	if (db_get_name_index(&ucli, client, false)
	 || db_get_name_index(&uusr, user, false))
		return; /* nothing to do! */

	anyperm = is_any(permission);
	anysession = is_any(session);
	if (anysession)
		ses = &sessions;
	else {
		if (get_session(session, false, &ses))
			return; /* ignore if no session */
	}
	for(;;) {
		for (i = 0; i < ses->count; i++) {
			if ((ucli == ANYIDX || ucli == ses->rules[i].client)
			 && (uusr == ANYIDX || uusr == ses->rules[i].user)
			 && (anyperm || !strcasecmp(permission, name_at(ses->rules[i].permission)))) {
				callback(closure,
					name_at(ses->rules[i].client),
					ses->name,
					name_at(ses->rules[i].user),
					name_at(ses->rules[i].permission),
					ses->rules[i].value);
			}
		}
		if (!anysession)
			break;
		ses = ses->next;
		if (ses == &sessions)
			break;
	}
}

/** drop rules */
int
db_drop(
	const char *client,
	const char *session,
	const char *user,
	const char *permission
) {
	uint32_t ucli, uusr, i;
	bool anyperm, anysession;
	session_t *ses;

	if (db_get_name_index(&ucli, client, false)
	 || db_get_name_index(&uusr, user, false))
		return 0; /* nothing to do! */

	anyperm = is_any(permission);
	anysession = is_any(session);
	if (anysession)
		ses = &sessions;
	else {
		if (get_session(session, false, &ses))
			return 0; /* ignore if no session */
	}
	for(;;) {
		i = 0;
		while (i < ses->count) {
			if ((ucli == ANYIDX || ucli == ses->rules[i].client)
			 && (uusr == ANYIDX || uusr == ses->rules[i].user)
			 && (anyperm || !strcasecmp(permission, name_at(ses->rules[i].permission))))
				session_drop_at(ses, i);
			else
				i++;
		}
		if (!anysession)
			break;
		ses = ses->next;
		if (ses == &sessions)
			break;
	}
	return 0;
}

/** set rules */
int
db_set(
	const char *client,
	const char *session,
	const char *user,
	const char *permission,
	uint32_t value
) {
	int rc;
	uint32_t ucli, uusr, uperm, i;
	session_t *ses;

	/* normalize */
	client = is_any_or_wide(client) ? WIDESTR : client;
	session = is_any_or_wide(session) ? WIDESTR : session;
	user = is_any_or_wide(user) ? WIDESTR : user;
	permission = is_any_or_wide(permission) ? WIDESTR : permission;

	/* get the session */
	rc = get_session(session, true, &ses);
	if (rc)
		goto error;

	/* get/create strings */
	rc = db_get_name_index(&ucli, client, true);
	if (rc)
		goto error;
	rc = db_get_name_index(&uusr, user, true);
	if (rc)
		goto error;

	/* search the existing rule */
	for (i = 0 ; i < ses->count ; i++) {
		if (ucli == ses->rules[i].client
		 && uusr == ses->rules[i].user
		 && !strcasecmp(permission, name_at(ses->rules[i].permission))) {
			/* found */
			session_set_at(ses, i, value);
			return 0;
		}
	}

	/* create the rule */
	rc = db_get_name_index(&uperm, permission, true);
	if (rc)
		goto error;

	rc = session_add(ses, ucli, uusr, uperm, value);

	return 0;
error:
	return rc;
}

/** check rules */
int
db_test(
	const char *client,
	const char *session,
	const char *user,
	const char *permission,
	uint32_t *value
) {
	uint32_t ucli, uusr, i, val, score, sc;
	session_t *ses;
	rule_t *rule;

	/* check */
	client = is_any_or_wide(client) ? WIDESTR : client;
	session = is_any_or_wide(session) ? WIDESTR : session;
	user = is_any_or_wide(user) ? WIDESTR : user;
	permission = is_any_or_wide(permission) ? WIDESTR : permission;

	/* search the items */
	val = score = 0;
#define NOIDX   0
	if (db_get_name_index(&ucli, client, false))
		ucli = NOIDX;
	if (db_get_name_index(&uusr, user, false))
		uusr = NOIDX;

	/* get the session */
	if (get_session(session, false, &ses))
		ses = &sessions;

retry:
	/* search the existing rule */
	for (i = 0 ; i < ses->count ; i++) {
		rule = &ses->rules[i];
		if ((ucli == rule->client || WIDEIDX == rule->client)
		 && (uusr == rule->user || WIDEIDX == rule->user)
		 && (WIDEIDX == rule->permission
			|| !strcasecmp(permission, name_at(rule->permission)))) {
			/* found */
			sc = 1 + (rule->client != WIDEIDX)
				+ (rule->user != WIDEIDX) + (rule->permission != WIDEIDX);
			if (sc > score) {
				score = sc;
				val = rule->value;
			}
		}
	}
	if (!score && ses != &sessions) {
		ses = &sessions;
		goto retry;
	}

	if (score)
		*value = val;
	return score > 0;
}