13 int auth_set_password(const char *username, const char *password) {
17 if (!valid_name(username) || !blerg_exists(username))
20 snprintf(filename, 512, "%s/%s/password", DATA_PATH, username);
21 fd = open(filename, O_WRONLY | O_CREAT, 0600);
22 write(fd, password, strlen(password));
28 int auth_get_password(const char *username, char *password) {
33 if (!valid_name(username))
36 sprintf(filename, "%s/%s/password", DATA_PATH, username);
37 fd = open(filename, O_RDONLY);
40 len = read(fd, password, 32);
48 int auth_check_password(const char *username, const char *password) {
51 if (auth_get_password(username, epw) == 0)
54 if (strncmp(password, epw, 32) == 0)
60 void hexify(char *dst, char *src, int len) {
61 static char hex[] = "0123456789abcdef";
64 for (i = 0; i < len; i++) {
65 dst[i * 2] = hex[(src[i] & 0xF0) >> 4];
66 dst[i * 2 + 1] = hex[src[i] & 0xF];
70 char *create_random_token() {
71 unsigned char buf[TOKEN_SIZE];
75 rand_fd = open("/dev/urandom", O_RDONLY);
77 perror("Could not open /dev/urandom\n");
80 read(rand_fd, buf, TOKEN_SIZE);
83 token = malloc(TOKEN_SIZE * 2 + 1);
84 hexify(token, buf, TOKEN_SIZE);
85 token[TOKEN_SIZE * 2] = 0;
90 int auth_login(const char *username, const char *password) {
94 if (!auth_check_password(username, password))
97 sprintf(filename, "%s/%s/token", DATA_PATH, username);
98 token_fd = open(filename, O_WRONLY | O_CREAT, 0600);
100 perror("Could not open token");
104 char *token = create_random_token();
105 write(token_fd, token, TOKEN_SIZE * 2);
112 int auth_logout(const char *username) {
115 if (!valid_name(username))
118 sprintf(filename, "%s/%s/token", DATA_PATH, username);
119 if (unlink(filename) == -1)
125 char *auth_get_token(const char *username) {
130 if (!valid_name(username))
133 sprintf(filename, "%s/%s/token", DATA_PATH, username);
134 token_fd = open(filename, O_RDONLY, 0600);
135 if (token_fd == -1) {
136 perror("Could not open token");
140 token = malloc(TOKEN_SIZE * 2 + 1);
141 read(token_fd, token, TOKEN_SIZE * 2);
147 int auth_check_token(const char *username, const char *given_token) {
148 char *token = auth_get_token(username);
149 if (token != NULL && given_token != NULL) {
150 int ret = (strncmp(token, given_token, TOKEN_SIZE * 2) == 0);