2 * @brief Generate UUIDs by reading from a pseudo-file under /proc
4 * Especially useful when building for Android, as it avoids having to
5 * cross-build a UUID library.
7 /* Copyright (C) 2008 Lemur Consulting Ltd
8 * Copyright (C) 2013,2015,2016,2017 Olly Betts
10 * This program is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU General Public License as published by
12 * the Free Software Foundation; either version 2 of the License, or
13 * (at your option) any later version.
15 * This program is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU General Public License for more details.
20 * You should have received a copy of the GNU General Public License
21 * along with this program; if not, write to the Free Software
22 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
27 #include "proc_uuid.h"
29 #include "xapian/error.h"
32 #include "stringutils.h"
34 #include <sys/types.h>
35 #include "safesysstat.h"
36 #include "safeerrno.h"
37 #include "safefcntl.h"
38 #include "safeunistd.h"
42 /// The size of a UUID in bytes.
43 const size_t UUID_SIZE
= 16;
45 /// The size of a UUID string in bytes (not including trailing '\0').
46 const size_t UUID_STRING_SIZE
= 36;
49 uuid_generate(uuid_t uu
)
51 char buf
[UUID_STRING_SIZE
];
52 int fd
= open("/proc/sys/kernel/random/uuid", O_RDONLY
);
54 throw Xapian::DatabaseCreateError("Opening UUID generator failed", errno
);
56 if (read(fd
, buf
, UUID_STRING_SIZE
) != UUID_STRING_SIZE
) {
58 throw Xapian::DatabaseCreateError("Generating UUID failed");
65 uuid_parse(const char * in
, uuid_t uu
)
67 for (unsigned i
= 0; i
!= UUID_SIZE
; ++i
) {
68 uu
[i
] = hex_digit(in
[0]) << 4 | hex_digit(in
[1]);
69 in
+= ((0x2a8 >> i
) & 1) | 2;
74 void uuid_unparse_lower(const uuid_t uu
, char * out
)
76 for (unsigned i
= 0; i
!= UUID_SIZE
; ++i
) {
77 unsigned char ch
= uu
[i
];
78 *out
++ = "0123456789abcdef"[ch
>> 4];
79 *out
++ = "0123456789abcdef"[ch
& 0x0f];
86 void uuid_clear(uuid_t uu
)
88 memset(uu
, 0, UUID_SIZE
);
91 int uuid_is_null(const uuid_t uu
)
94 while (i
< UUID_SIZE
) {