~ysu/gemini-chatroom

ref: 91028756563599c78745ae4d5447ab09b88a7403 gemini-chatroom/bin/chat0/post.c -rw-r--r-- 2.0 KiB
91028756 — vps rewrote in c 2 months ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

#include "config.h"

char *
removeExtraChars(char user[9])
{
	static char nUser[9];
	unsigned int nUserLen = 0;

	for (unsigned int i = 0; i < 9; i++) {
		if ((user[i] >= 'a' && user[i] <= 'z') || (user[i] >= 'A' && user[i] <= 'Z') || (user[i] >= '0' && user[i] <= '9'))
			nUser[nUserLen++] = user[i];
		else if (user[i] == '\0')
			break;
	}
	return nUser;
}

void
convert(char *str, char **nstr)
{ /* free ret after */
	size_t strsize = strlen(str), retsize = 0;
	char *ret = malloc(strsize);
	char tmp[2];

	for (unsigned int i = 0; i < strsize; i++) {
		if (str[i] == '%') {
			ret = realloc(ret, ++retsize);
			tmp[0] = str[++i];
			tmp[1] = str[++i];
			sscanf(tmp, "%x", (unsigned int *)&ret[retsize - 1]);
		} else  ret[retsize++] = str[i];
	}
	ret[retsize] = '\0';
	*nstr = ret;
}

void
getTime(char **timestr)
{
	time_t t = time(NULL);
	struct tm tm = *localtime(&t);
	sprintf(*timestr, "(%d/%02d/%02d %02d:%02d)", tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min);
}

int
main()
{
	/* variables */
	char *PATH_INFO = getenv("PATH_INFO");
	char *QUERY_STRING = getenv("QUERY_STRING");
	char user[9];
	FILE *ml;

	/* get username */
	if (PATH_INFO == NULL || !strcmp(PATH_INFO, ""))
		memcpy(user, "anon\0", 5);
	else {
		if (strlen(PATH_INFO) > 9) {
			puts("40 Message failed! Reason: Username must be below 9 characters\r");
			exit(0);
		} else memcpy(user, removeExtraChars(PATH_INFO), 9);
	}

	/* get input */
	if (QUERY_STRING == NULL)
		puts("10 Message\r");
	if (QUERY_STRING == NULL)
		exit(0);

	/* 
	 * write message to file
	 */
	ml = fopen("message_log", "a");
	/* get time */
	char *timestr = malloc(19);
	getTime(&timestr);

	/* replace % with \x */
	char *message;
	convert(QUERY_STRING, &message);

	/* print to file */
	fprintf(ml, "%s %8s: %s\n", timestr, user, message);
	free(timestr);
	free(message);
	fclose(ml);

	/* redirect back to messages */
	puts("30 /bin/chat"CHAT_NUM"/\r");
}