-
Notifications
You must be signed in to change notification settings - Fork 3
/
airscan-uuid.c
123 lines (99 loc) · 2.45 KB
/
airscan-uuid.c
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
/* AirScan (a.k.a. eSCL) backend for SANE
*
* Copyright (C) 2019 and up by Alexander Pevzner (pzz@apevzner.com)
* See LICENSE for license terms and conditions
*
* UUID utilities
*/
#include "airscan.h"
#include <ctype.h>
#include <stdio.h>
#include <string.h>
#include <gnutls/gnutls.h>
#include <gnutls/crypto.h>
#pragma GCC diagnostic ignored "-Wunused-result"
/* Invalid uuid
*/
static uuid uuid_invalid;
/* Format UUID from 16-byte binary representation into
* the following form:
* urn:uuid:ede05377-460e-4b4a-a5c0-423f9e02e8fa
*/
static uuid
uuid_format (uint8_t in[16])
{
uuid u;
sprintf(u.text,
"urn:uuid:"
"%.2x%.2x%.2x%.2x-%.2x%.2x-%.2x%.2x-%.2x%.2x-%.2x%.2x%.2x%.2x%.2x%.2x",
in[0], in[1], in[2], in[3], in[4], in[5], in[6], in[7],
in[8], in[9], in[10], in[11], in[12], in[13], in[14], in[15]);
return u;
}
/* Generate random UUID. Generated UUID has a following form:
* urn:uuid:ede05377-460e-4b4a-a5c0-423f9e02e8fa
*/
uuid
uuid_rand (void)
{
uint8_t rnd[16];
rand_bytes(rnd, sizeof(rnd));
return uuid_format(rnd);
}
/* Parse UUID. This function ignores all "decorations", like
* urn:uuid: prefix and so on, and takes only hexadecimal digits
* into considerations
*
* Check the returned uuid with uuid_valid() for possible parse errors
*/
uuid
uuid_parse (const char *in)
{
uint8_t buf[16];
unsigned int cnt = 0;
unsigned char c;
if (!strncasecmp(in, "urn:", 4)) {
in += 4;
}
if (!strncasecmp(in, "uuid:", 5)) {
in += 5;
}
while ((c = *in ++) != '\0') {
if (isxdigit(c)) {
unsigned int v;
if (cnt == 32) {
return uuid_invalid;
}
if (isdigit(c)) {
v = c - '0';
} else if (isupper(c)) {
v = c - 'A' + 10;
} else {
v = c - 'a' + 10;
}
if ((cnt & 1) == 0) {
buf[cnt / 2] = v << 4;
} else {
buf[cnt / 2] |= v;
}
cnt ++;
}
}
if (cnt != 32) {
return uuid_invalid;
}
return uuid_format(buf);
}
/* Generate uuid by cryptographically cacheing input string
*/
uuid
uuid_hash (const char *s)
{
uint8_t buf[32];
int rc;
rc = gnutls_hash_fast(GNUTLS_DIG_SHA256, s, strlen(s), buf);
log_assert(NULL, rc == 0);
return uuid_format(buf);
}
/* vim:ts=8:sw=4:et
*/