Subversion Repositories RepoView

Rev

Rev 5 | Rev 7 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
1 nishi 1
/* $Id: cookie.c 6 2024-08-21 00:44:17Z nishi $ */
3 nishi 2
 
3
#include "rv_auth.h"
4
 
5
#include "rv_util.h"
5 nishi 6
#include "rv_db.h"
3 nishi 7
 
5 nishi 8
#include <string.h>
3 nishi 9
#include <stdio.h>
10
#include <stdlib.h>
11
 
12
extern char** environ;
13
 
14
struct cookie_entry {
15
	char* key;
16
	char* value;
17
};
18
 
19
struct cookie_entry** cookie_entries;
20
 
21
void parse_cookie(void) {
22
	cookie_entries = malloc(sizeof(*cookie_entries));
23
	cookie_entries[0] = NULL;
24
	char* cookie = getenv("HTTP_COOKIE");
25
	if(cookie != NULL) {
26
		cookie = rv_strdup(cookie);
27
		int i;
28
		int incr = 0;
29
		for(i = 0;; i++) {
30
			if(cookie[i] == 0 || cookie[i] == ';') {
31
				char oldc = cookie[i];
32
				cookie[i] = 0;
33
 
34
				char* key = cookie + incr;
35
				char* value = "";
36
 
37
				int j;
38
				for(j = 0; key[j] != 0; j++) {
39
					if(key[j] == '=') {
40
						key[j] = 0;
41
						value = key + j + 1;
42
						break;
43
					}
44
				}
45
				struct cookie_entry* entry = malloc(sizeof(*entry));
46
				entry->key = rv_strdup(key);
47
				entry->value = rv_strdup(value);
48
 
49
				struct cookie_entry** old_entries = cookie_entries;
50
				for(j = 0; old_entries[j] != NULL; j++)
51
					;
52
				cookie_entries = malloc(sizeof(*cookie_entries) * (j + 2));
53
				for(j = 0; old_entries[j] != NULL; j++) {
54
					cookie_entries[j] = old_entries[j];
55
				}
56
				cookie_entries[j] = entry;
57
				cookie_entries[j + 1] = NULL;
58
 
59
				int oldi = i;
60
				i++;
61
				for(; cookie[i] != 0 && (cookie[i] == ' ' || cookie[i] == '\t'); i++)
62
					;
63
				i--;
64
				incr = i + 1;
65
				if(oldc == 0) break;
66
			}
67
		}
68
		free(cookie);
69
	}
70
}
71
 
72
char* rv_logged_in(void) {
5 nishi 73
	int i;
74
	for(i = 0; cookie_entries[i] != NULL; i++) {
75
		if(strcmp(cookie_entries[i]->key, "token") == 0) {
6 nishi 76
			char* who = rv_who_has_token(cookie_entries[i]->value);
77
			if(who == NULL) {
78
				printf("Set-Cookie: token=; HttpOnly; Expires=0; SameSite=Strict\r\n");
79
			}
80
			return who;
5 nishi 81
			break;
82
		}
83
	}
3 nishi 84
	return NULL;
85
}
86
 
5 nishi 87
void rv_save_login(const char* username) {
88
	char* token = rv_new_token(username);
6 nishi 89
	printf("Set-Cookie: token=%s; HttpOnly; SameSite=Strict\r\n", token);
5 nishi 90
	free(token);
91
}
92
 
93
void rv_init_auth(void) { parse_cookie(); }
94
 
3 nishi 95
void rv_free_auth(void) {
96
	int i;
97
	for(i = 0; cookie_entries[i] != NULL; i++) {
98
		free(cookie_entries[i]->key);
99
		free(cookie_entries[i]->value);
100
		free(cookie_entries[i]);
101
	}
102
	free(cookie_entries);
103
}