1 /* Blerg is (C) 2011 The Dominion of Awesome, and is distributed under a
2 * BSD-style license. Please see the COPYING file for details.
16 int auth_set_password(const char *username, const char *password) {
20 if (!valid_name(username) || !blerg_exists(username))
23 snprintf(filename, 512, "%s/%s/password", DATA_PATH, username);
24 fd = open(filename, O_WRONLY | O_CREAT, 0600);
25 write(fd, password, strlen(password));
31 int auth_get_password(const char *username, char *password) {
36 if (!valid_name(username))
39 sprintf(filename, "%s/%s/password", DATA_PATH, username);
40 fd = open(filename, O_RDONLY);
43 len = read(fd, password, 32);
51 int auth_check_password(const char *username, const char *password) {
54 if (auth_get_password(username, epw) == 0)
57 if (strncmp(password, epw, 32) == 0)
63 void hexify(char *dst, char *src, int len) {
64 static char hex[] = "0123456789abcdef";
67 for (i = 0; i < len; i++) {
68 dst[i * 2] = hex[(src[i] & 0xF0) >> 4];
69 dst[i * 2 + 1] = hex[src[i] & 0xF];
73 char *create_random_token() {
74 unsigned char buf[TOKEN_SIZE];
78 rand_fd = open("/dev/urandom", O_RDONLY);
80 perror("Could not open /dev/urandom\n");
83 read(rand_fd, buf, TOKEN_SIZE);
86 token = malloc(TOKEN_SIZE * 2 + 1);
87 hexify(token, buf, TOKEN_SIZE);
88 token[TOKEN_SIZE * 2] = 0;
93 int auth_login(const char *username, const char *password) {
97 if (!auth_check_password(username, password))
100 sprintf(filename, "%s/%s/token", DATA_PATH, username);
101 token_fd = open(filename, O_WRONLY | O_CREAT, 0600);
102 if (token_fd == -1) {
103 perror("Could not open token");
107 char *token = create_random_token();
108 write(token_fd, token, TOKEN_SIZE * 2);
115 int auth_logout(const char *username) {
118 if (!valid_name(username))
121 sprintf(filename, "%s/%s/token", DATA_PATH, username);
122 if (unlink(filename) == -1)
128 char *auth_get_token(const char *username) {
133 if (!valid_name(username))
136 sprintf(filename, "%s/%s/token", DATA_PATH, username);
137 token_fd = open(filename, O_RDONLY, 0600);
138 if (token_fd == -1) {
139 perror("Could not open token");
143 token = malloc(TOKEN_SIZE * 2 + 1);
144 read(token_fd, token, TOKEN_SIZE * 2);
150 int auth_check_token(const char *username, const char *given_token) {
151 char *token = auth_get_token(username);
152 if (token != NULL && given_token != NULL) {
153 int ret = (strncmp(token, given_token, TOKEN_SIZE * 2) == 0);