aboutsummaryrefslogtreecommitdiffstats
path: root/librecrypt_find_first_algorithm_.c
blob: 6bbfe70009f85debc938bbf63f694d2f51fec54f (plain) (blame)
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
/* See LICENSE file for copyright and license details. */
#include "common.h"
#ifndef TEST


const struct algorithm *
librecrypt_find_first_algorithm_(const char *settings, size_t len)
{
	unsigned r, priority = 0;
	const struct algorithm *algo, *found = NULL;
	size_t i;

	for (i = 0u;; i++) {
		/* Get next algorithm in the list */
		algo = &librecrypt_algorithms_[i];
		if (IS_END_OF_ALGORITHMS(algo))
			break;

		/* Get match-priority, bigger is more prioritised,
		 * 0 is non-match, so we save if we get a bigger
		 * value then our current best (we start at 0
		 * (no match found)) */
		r = (*algo->is_algorithm)(settings, len);
		if (r > priority) {
			priority = r;
			found = algo;
		}
	}

	/* NULL if all `is_algorithm` returned 0 (including if the
	 * last was completly empty), otherwise the first one
	 * (actually an arbitrary one) that returned the greated
	 * match-priority (which doesn't necessarily mean it's better,
	 * which is why we don't just break at the first match
	 * (`librecrypt_algorithms_` is ordered by how good they are)) */
	return found;
}


#else


#define NSA "$~no~such~algorithm~$"


#define CHECK(ALGO)\
	do {\
		algo = librecrypt_find_first_algorithm_(ALGO, sizeof(ALGO) - 1u);\
		EXPECT(algo != NULL);\
		EXPECT((*algo->is_algorithm)(ALGO, sizeof(ALGO) - 1u) > 0u);\
		EXPECT(librecrypt_find_first_algorithm_(ALGO">"NSA, sizeof(ALGO">"NSA) - 1u) == algo);\
	} while (0)


int
main(void)
{
	const struct algorithm *algo;

	SET_UP_ALARM();
	INIT_RESOURCE_TEST();

	EXPECT(librecrypt_find_first_algorithm_(NSA, sizeof(NSA) - 1u) == NULL);
	EXPECT(librecrypt_find_first_algorithm_(NSA">", sizeof(NSA">") - 1u) == NULL);

	IF__argon2i__SUPPORTED(CHECK("$argon2i$"));
	IF__argon2d__SUPPORTED(CHECK("$argon2d$"));
	IF__argon2id__SUPPORTED(CHECK("$argon2id$"));
	IF__argon2ds__SUPPORTED(CHECK("$argon2ds$"));

	STOP_RESOURCE_TEST();
	return 0;
}


#endif