-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathirc_parser.c
More file actions
93 lines (72 loc) · 2.33 KB
/
irc_parser.c
File metadata and controls
93 lines (72 loc) · 2.33 KB
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
#include "irc_parser.h"
static void span_set(Span *s, const char *p, size_t n) {
s->ptr = p;
s->len = n;
}
static int span_eq(const Span *s, const char *str){
size_t i = 0;
while (str[i]) {
if (i >= s->len || s->ptr[i] != str[i])
return 0;
i++;
}
return i == s->len;
}
static int is_numeric(const Span *s){
if (s->len != 3)
return 0;
for (int i = 0; i < 3; i++)
if (s->ptr[i] < '0' || s->ptr[i] > '9')
return 0;
return 1;
}
static IRCCommand get_command(const Span *cmd){
if (span_eq(cmd, "PING")) return PING;
if (span_eq(cmd, "PRIVMSG")) return PRIVMSG;
if (span_eq(cmd, "JOIN")) return JOIN;
if (span_eq(cmd, "PART")) return PART;
if (span_eq(cmd, "NICK")) return NICK;
if (span_eq(cmd, "QUIT")) return QUIT;
if (is_numeric(cmd)) return NUMERIC;
return OTHER;
}
// https://datatracker.ietf.org/doc/html/rfc2812#section-2.3.1
int irc_parse(const char *buf, size_t len, IRCMessage *msg){
const char *p = buf;
const char *end = buf + len;
msg->prefix.len = 0;
msg->param_count = 0;
// message = [ ":" prefix SPACE ] command [ params ] crlf
// prefix = servername / ( nickname [ [ "!" user ] "@" host ] )
if (p < end && *p == ':') {
const char *start = ++p;
while (p < end && *p != ' ') p++;
if (p == end) return 0;
span_set(&msg->prefix, start, p - start);
p++;
}
// command = 1*letter / 3digit
{
const char *start = p;
while (p < end && *p != ' ') p++;
span_set(&msg->command_text, start, p - start);
msg->command = get_command(&msg->command_text);
}
// params = *14( SPACE middle ) [ SPACE ":" trailing ]
// =/ 14( SPACE middle ) [ SPACE [ ":" ] trailing ]
while (p < end && msg->param_count < IRC_MAX_PARAMS) {
if (p < end && *p == ' ') p++;
else break;
// while (p < end && *p == ' ') p++;
// if (p == end) break;
if (p < end && *p == ':') {
p++;
span_set(&msg->params[msg->param_count++], p, end - p);
break;
}
const char *start = p;
while (p < end && *p != ' ') p++;
span_set(&msg->params[msg->param_count++], start, p - start);
}
return 1;
}