Subversion Repositories IRC-Archiver

Rev

Go to most recent revision | Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
8 nishi 1
/* $Id: db.c 8 2024-08-30 03:46:36Z nishi $ */
2
 
3
#include "ia_db.h"
4
 
5
#include "ia_util.h"
6
 
7
#include <stddef.h>
8
#include <stdio.h>
9
#include <stdlib.h>
10
#include <time.h>
11
#include <string.h>
12
 
13
#include <sqlite3.h>
14
 
15
sqlite3* sql;
16
 
17
extern char* database;
18
 
19
int ia_db_init(void) {
20
	int ret;
21
	ret = sqlite3_open(database, &sql);
22
	if(ret != SQLITE_OK) {
23
		return 1;
24
	}
25
	ret = sqlite3_exec(sql, "create table if not exists log(user text, channel text, message text, date number)", NULL, NULL, NULL);
26
	if(ret != SQLITE_OK) {
27
		return 1;
28
	}
29
	return 0;
30
}
31
 
32
char* escape_sql(const char* stuff) {
33
	char* str = malloc(strlen(stuff) * 2 + 1);
34
	int incr = 0;
35
	int i;
36
	for(i = 0; stuff[i] != 0; i++) {
37
		if(stuff[i] == '\'') {
38
			str[incr++] = '\'';
39
			str[incr++] = '\'';
40
		} else {
41
			str[incr++] = stuff[i];
42
		}
43
	}
44
	str[incr] = 0;
45
	return str;
46
}
47
 
48
int ia_db_put(const char* user, const char* channel, const char* message) {
49
	char* eusr = escape_sql(user);
50
	char* echn = escape_sql(channel);
51
	char* emsg = escape_sql(message);
52
 
53
	char* date = malloc(512);
54
	sprintf(date, "%llu", (unsigned long long)time(NULL));
55
 
56
	char* tmp;
57
	char* str;
58
	tmp = ia_strcat("insert into log values('", eusr);
59
	str = ia_strcat(tmp, "', '");
60
	free(tmp);
61
 
62
	tmp = str;
63
	str = ia_strcat(tmp, echn);
64
	free(tmp);
65
 
66
	tmp = str;
67
	str = ia_strcat(tmp, "', '");
68
	free(tmp);
69
 
70
	tmp = str;
71
	str = ia_strcat(tmp, emsg);
72
	free(tmp);
73
 
74
	tmp = str;
75
	str = ia_strcat(tmp, "', ");
76
	free(tmp);
77
 
78
	tmp = str;
79
	str = ia_strcat(tmp, date);
80
	free(tmp);
81
 
82
	tmp = str;
83
	str = ia_strcat(tmp, ")");
84
	free(tmp);
85
 
86
	free(date);
87
	free(eusr);
88
	free(echn);
89
	free(emsg);
90
 
91
	int ret = sqlite3_exec(sql, str, NULL, NULL, NULL);
92
 
93
	return ret == SQLITE_OK ? 0 : 1;
94
}