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.
15 #define MAX_PASSWORD_LENGTH 64
17 int auth_set_password(const char *username, const char *password) {
21 if (!valid_name(username) || !blerg_exists(username))
25 if (n > MAX_PASSWORD_LENGTH)
28 snprintf(filename, 512, "%s/%s/password", DATA_PATH, username);
29 fd = open(filename, O_WRONLY | O_CREAT, 0600);
30 write(fd, password, n);
36 int auth_get_password(const char *username, char *password) {
41 if (!valid_name(username))
44 sprintf(filename, "%s/%s/password", DATA_PATH, username);
45 fd = open(filename, O_RDONLY);
48 len = read(fd, password, MAX_PASSWORD_LENGTH);
56 int auth_check_password(const char *username, const char *password) {
59 if (auth_get_password(username, epw) == 0)
62 if (strncmp(password, epw, MAX_PASSWORD_LENGTH) == 0)
68 void hexify(char *dst, char *src, int len) {
69 static char hex[] = "0123456789abcdef";
72 for (i = 0; i < len; i++) {
73 dst[i * 2] = hex[(src[i] & 0xF0) >> 4];
74 dst[i * 2 + 1] = hex[src[i] & 0xF];
78 char *create_random_token() {
79 unsigned char buf[TOKEN_SIZE];
83 rand_fd = open("/dev/urandom", O_RDONLY);
85 perror("Could not open /dev/urandom\n");
88 read(rand_fd, buf, TOKEN_SIZE);
91 token = malloc(TOKEN_SIZE * 2 + 1);
92 hexify(token, buf, TOKEN_SIZE);
93 token[TOKEN_SIZE * 2] = 0;
98 int auth_login(const char *username, const char *password) {
102 if (!auth_check_password(username, password))
105 sprintf(filename, "%s/%s/token", DATA_PATH, username);
106 token_fd = open(filename, O_WRONLY | O_CREAT, 0600);
107 if (token_fd == -1) {
108 perror("Could not open token");
112 char *token = create_random_token();
113 write(token_fd, token, TOKEN_SIZE * 2);
120 int auth_logout(const char *username) {
123 if (!valid_name(username))
126 sprintf(filename, "%s/%s/token", DATA_PATH, username);
127 if (unlink(filename) == -1)
133 char *auth_get_token(const char *username) {
138 if (!valid_name(username))
141 sprintf(filename, "%s/%s/token", DATA_PATH, username);
142 token_fd = open(filename, O_RDONLY, 0600);
143 if (token_fd == -1) {
144 perror("Could not open token");
148 token = malloc(TOKEN_SIZE * 2 + 1);
149 read(token_fd, token, TOKEN_SIZE * 2);
155 int auth_check_token(const char *username, const char *given_token) {
156 char *token = auth_get_token(username);
157 if (token != NULL && given_token != NULL) {
158 int ret = (strncmp(token, given_token, TOKEN_SIZE * 2) == 0);