File: token.c

package info (click to toggle)
wlroots 0.19.1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 4,592 kB
  • sloc: ansic: 75,754; xml: 2,739; sh: 33; makefile: 23
file content (39 lines) | stat: -rw-r--r-- 945 bytes parent folder | download | duplicates (3)
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
#include "util/token.h"
#include "wlr/util/log.h"

#include <fcntl.h>
#include <inttypes.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>

bool generate_token(char out[static TOKEN_SIZE]) {
	static FILE *urandom = NULL;
	uint64_t data[2];

	if (!urandom) {
		int fd = open("/dev/urandom", O_RDONLY | O_CLOEXEC);
		if (fd < 0) {
			wlr_log_errno(WLR_ERROR, "Failed to open random device");
			return false;
		}
		if (!(urandom = fdopen(fd, "r"))) {
			wlr_log_errno(WLR_ERROR, "fdopen failed");
			close(fd);
			return false;
		}
	}
	if (fread(data, sizeof(data), 1, urandom) != 1) {
		wlr_log_errno(WLR_ERROR, "Failed to read from random device");
		return false;
	}
	if (snprintf(out, TOKEN_SIZE, "%016" PRIx64 "%016" PRIx64, data[0], data[1]) != TOKEN_SIZE - 1) {
		wlr_log_errno(WLR_ERROR, "Failed to format hex string token");
		return false;
	}
	return true;
}