Subversion Repositories RepoView

Rev

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

Rev Author Line No. Line
1 nishi 1
/* $Id: util.c 10 2024-08-21 02:13:48Z nishi $ */
2
 
3
#include "rv_util.h"
4
 
5
#include "../config.h"
6
 
7
#include "rv_version.h"
5 nishi 8
#include "rv_db.h"
1 nishi 9
 
10
#include <stdio.h>
11
#include <stdlib.h>
12
#include <string.h>
13
 
3 nishi 14
char* rv_strcat(const char* a, const char* b) {
1 nishi 15
	char* str = malloc(strlen(a) + strlen(b) + 1);
16
	memcpy(str, a, strlen(a));
17
	memcpy(str + strlen(a), b, strlen(b));
18
	str[strlen(a) + strlen(b)] = 0;
19
	return str;
20
}
21
 
3 nishi 22
char* rv_strcat3(const char* a, const char* b, const char* c) {
1 nishi 23
	char* tmp = rv_strcat(a, b);
24
	char* str = rv_strcat(tmp, c);
25
	free(tmp);
26
	return str;
27
}
28
 
3 nishi 29
char* rv_strdup(const char* str) { return rv_strcat(str, ""); }
1 nishi 30
 
3 nishi 31
void rv_error_http(void) {
1 nishi 32
	printf("Content-Type: text/plain\r\n");
33
	printf("Status: 500 Internal Server Error\r\n");
34
	printf("\r\n");
35
	printf("This is RepoView version %s, named `%s`.\n", rv_get_version(), INSTANCE_NAME);
36
	printf("Unrecoverable error has occured.\n");
37
	printf("Admin contact: %s\n", INSTANCE_ADMIN);
38
	printf("Developer contact: Nishi <nishi@nishi.boats>\n");
39
	printf("-----\n");
40
}
41
 
3 nishi 42
int hex_to_num(char c) {
43
	if('0' <= c && c <= '9') {
1 nishi 44
		return c - '0';
3 nishi 45
	} else if('a' <= c && c <= 'f') {
1 nishi 46
		return c - 'a' + 10;
3 nishi 47
	} else if('A' <= c && c <= 'F') {
1 nishi 48
		return c - 'A' + 10;
49
	}
50
	return 0;
51
}
52
 
3 nishi 53
char* rv_url_decode(const char* str) {
1 nishi 54
	char* r = malloc(1);
55
	r[0] = 0;
56
	int i;
57
	char cbuf[2];
58
	cbuf[1] = 0;
3 nishi 59
	for(i = 0; str[i] != 0; i++) {
60
		if(str[i] == '%') {
1 nishi 61
			if(str[i + 1] == 0) break;
62
			if(str[i + 2] == 0) break;
63
			cbuf[0] = (hex_to_num(str[i + 1]) << 4) | hex_to_num(str[i + 2]);
64
			char* tmp = r;
65
			r = rv_strcat(tmp, cbuf);
66
			free(tmp);
67
			i += 2;
3 nishi 68
		} else {
1 nishi 69
			cbuf[0] = str[i];
70
			char* tmp = r;
71
			r = rv_strcat(tmp, cbuf);
72
			free(tmp);
73
		}
74
	}
75
	return r;
76
}
5 nishi 77
 
10 nishi 78
char* rv_construct_repouser(const char* reponame, const char* username) {
79
	char cbuf[2];
80
	cbuf[0] = REPO_USER_DELIM;
81
	cbuf[1] = 0;
82
	return rv_strcat3(reponame, cbuf, username);
83
}
84
 
5 nishi 85
char* rv_new_token(const char* username) {
86
	const char tokenstr[] = "0123456789abcdefghijklmnopqrstuvwxyz";
87
	char* token = malloc(17);
88
	token[16] = 0;
89
	int i;
90
regenerate:
91
	for(i = 0; i < 16; i++) {
92
		token[i] = tokenstr[rand() % strlen(tokenstr)];
93
	}
94
	if(rv_has_token(token)) goto regenerate;
95
	rv_save_token(username, token);
96
	return token;
97
}