1 // SPDX-License-Identifier: BSD-2-Clause
2 /*
3  * Copyright (c) 2019, Linaro Limited
4  */
5 
6 #include <ctype.h>
7 #include <stdint.h>
8 #include <string.h>
9 #include <tee_api_types.h>
10 #include <tee_internal_api_extensions.h>
11 
hex(char c)12 static int hex(char c)
13 {
14 	char lc = tolower(c);
15 
16 	if (isdigit(lc))
17 		return lc - '0';
18 	if (isxdigit(lc))
19 		return lc - 'a' + 10;
20 	return -1;
21 }
22 
parse_hex(const char * s,size_t nchars,uint32_t * res)23 static uint32_t parse_hex(const char *s, size_t nchars, uint32_t *res)
24 {
25 	uint32_t v = 0;
26 	size_t n = 0;
27 	int c = 0;
28 
29 	for (n = 0; n < nchars; n++) {
30 		c = hex(s[n]);
31 		if (c == -1) {
32 			*res = TEE_ERROR_BAD_FORMAT;
33 			goto out;
34 		}
35 		v = (v << 4) + c;
36 	}
37 	*res = TEE_SUCCESS;
38 out:
39 	return v;
40 }
41 
tee_uuid_from_str(TEE_UUID * uuid,const char * s)42 TEE_Result tee_uuid_from_str(TEE_UUID *uuid, const char *s)
43 {
44 	TEE_Result res = TEE_SUCCESS;
45 	TEE_UUID u = { };
46 	const char *p = s;
47 	size_t i = 0;
48 
49 	if (!p || strnlen(p, 37) != 36)
50 		return TEE_ERROR_BAD_FORMAT;
51 	if (p[8] != '-' || p[13] != '-' || p[18] != '-' || p[23] != '-')
52 		return TEE_ERROR_BAD_FORMAT;
53 
54 	u.timeLow = parse_hex(p, 8, &res);
55 	if (res)
56 		goto out;
57 	p += 9;
58 	u.timeMid = parse_hex(p, 4, &res);
59 	if (res)
60 		goto out;
61 	p += 5;
62 	u.timeHiAndVersion = parse_hex(p, 4, &res);
63 	if (res)
64 		goto out;
65 	p += 5;
66 	for (i = 0; i < 8; i++) {
67 		u.clockSeqAndNode[i] = parse_hex(p, 2, &res);
68 		if (res)
69 			goto out;
70 		if (i == 1)
71 			p += 3;
72 		else
73 			p += 2;
74 	}
75 	*uuid = u;
76 out:
77 	return res;
78 }
79