[ci] Enable IRC notifications from travis
[xapian.git] / xapian-core / common / proc_uuid.cc
blob1ecdb6c359fc9f7d3a3d7d185f9c115fc860b618
1 /** @file proc_uuid.cc
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.
6 */
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
25 #include <config.h>
27 #include "proc_uuid.h"
29 #include "xapian/error.h"
31 #include <cstring>
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"
40 using namespace std;
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;
48 void
49 uuid_generate(uuid_t uu)
51 char buf[UUID_STRING_SIZE];
52 int fd = open("/proc/sys/kernel/random/uuid", O_RDONLY);
53 if (rare(fd == -1)) {
54 throw Xapian::DatabaseCreateError("Opening UUID generator failed", errno);
56 if (read(fd, buf, UUID_STRING_SIZE) != UUID_STRING_SIZE) {
57 close(fd);
58 throw Xapian::DatabaseCreateError("Generating UUID failed");
60 close(fd);
61 uuid_parse(buf, uu);
64 int
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;
71 return 0;
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];
80 if ((0x2a8 >> i) & 1)
81 *out++ = '-';
83 *out = '\0';
86 void uuid_clear(uuid_t uu)
88 memset(uu, 0, UUID_SIZE);
91 int uuid_is_null(const uuid_t uu)
93 unsigned i = 0;
94 while (i < UUID_SIZE) {
95 if (uu[i++])
96 return 0;
98 return 1;