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 #define MAX_PASSWORD_LENGTH 64
18 int auth_set_password(const char *username, const char *password) {
20 unsigned char md5pass[MD5_DIGEST_SIZE];
21 struct MD5Context ctx;
24 if (!valid_name(username) || !blerg_exists(username))
28 if (n > MAX_PASSWORD_LENGTH)
32 MD5Update(&ctx, username, strlen(username));
33 MD5Update(&ctx, password, n);
34 MD5Final(md5pass, &ctx);
36 snprintf(filename, 512, "%s/%s/password", DATA_PATH, username);
37 fd = open(filename, O_WRONLY | O_CREAT, 0600);
38 write(fd, md5pass, MD5_DIGEST_SIZE);
44 int auth_get_password(const char *username, char *password) {
49 if (!valid_name(username))
52 sprintf(filename, "%s/%s/password", DATA_PATH, username);
53 fd = open(filename, O_RDONLY);
56 len = read(fd, password, MD5_DIGEST_SIZE);
64 int auth_check_password(const char *username, const char *password) {
65 char epw[MD5_DIGEST_SIZE + 1];
66 unsigned char givenpw[MD5_DIGEST_SIZE];
67 struct MD5Context ctx;
69 if (auth_get_password(username, epw) == 0)
73 MD5Update(&ctx, username, strlen(username));
74 MD5Update(&ctx, password, strlen(password));
75 MD5Final(givenpw, &ctx);
77 if (strncmp(givenpw, epw, MD5_DIGEST_SIZE) == 0)
83 void hexify(char *dst, char *src, int len) {
84 static char hex[] = "0123456789abcdef";
87 for (i = 0; i < len; i++) {
88 dst[i * 2] = hex[(src[i] & 0xF0) >> 4];
89 dst[i * 2 + 1] = hex[src[i] & 0xF];
93 char *create_random_token() {
94 unsigned char buf[TOKEN_SIZE];
98 rand_fd = open("/dev/urandom", O_RDONLY);
100 perror("Could not open /dev/urandom\n");
103 read(rand_fd, buf, TOKEN_SIZE);
106 token = malloc(TOKEN_SIZE * 2 + 1);
107 hexify(token, buf, TOKEN_SIZE);
108 token[TOKEN_SIZE * 2] = 0;
113 char * auth_login(const char *username, const char *password) {
117 if (!auth_check_password(username, password))
120 char *token = create_random_token();
122 sprintf(filename, "%s/%s/tokens", DATA_PATH, username);
123 if (access(filename, F_OK) != 0) {
124 if (mkdir(filename, 0700) == -1) {
125 perror("Could not create auth token dir");
130 sprintf(filename, "%s/%s/tokens/%s", DATA_PATH, username, token);
131 token_fd = open(filename, O_WRONLY | O_CREAT, 0600);
132 if (token_fd == -1) {
133 perror("Could not open token");
141 int auth_logout(const char *username, const char *token) {
144 if (!valid_name(username))
147 sprintf(filename, "%s/%s/tokens", DATA_PATH, username);
148 if (access(filename, F_OK) != 0) {
152 sprintf(filename, "%s/%s/tokens/%s", DATA_PATH, username, token);
153 if (unlink(filename) == -1)
159 int auth_check_token(const char *username, const char *given_token) {
162 sprintf(filename, "%s/%s/tokens/%s", DATA_PATH, username, given_token);
164 return (access(filename, F_OK) == 0);