tried to fix parse_lines #3
[NeonServV5.git] / IRCParser.c
1
2 #include "IRCParser.h"
3 #include "ClientSocket.h"
4
5 struct irc_cmd *irc_commands = NULL;
6
7 static void parse_line(struct ClientSocket *client, char *line);
8 static void register_irc_function(char *command, irc_cmd_t *func);
9 static void parse_raw(struct ClientSocket *client, char *from, char *cmd, char **argv, int argc);
10
11 int parse_lines(struct ClientSocket *client, char *lines, int len) {
12     int i, startpos = 0;
13     printf("PARSE: %s %d\n", lines, len);
14     for(i = 0; i < len; i++) {
15         if(lines[i] == '\r') //just zero it out :D
16             lines[i] = 0;
17         if(lines[i] == '\n') {
18             lines[i] = 0;
19             startpos = strlen(lines); //save length of the current line
20             parse_line(client, lines);
21             lines += startpos+1;
22             printf("SKIP %d: %s\n", startpos+1, lines);
23             startpos = i+1;
24         }
25     }
26     return startpos;
27 }
28
29 static void parse_line(struct ClientSocket *client, char *line) {
30     int i = 0, argc = 0;
31     char *argv[MAXNUMPARAMS];
32     printf("[recv %lu] %s\n", (unsigned long) strlen(line), line);
33     if(line[0] == ':')
34         i = 1;
35     else
36         argv[argc++] = NULL;
37     while(*line) {
38         //skip leading spaces
39         while (*line == ' ')
40             *line++ = 0;
41         if (*line == ':') {
42            //the rest is a single parameter
43            argv[argc++] = line + 1;
44         }
45         argv[argc++] = line;
46         if (argc >= MAXNUMPARAMS)
47             break;
48         while (*line != ' ' && *line)
49             line++;
50     }
51     if(argc >= 2) {
52         parse_raw(client, argv[0], argv[1], argv+2, argc-2);
53     }
54 }
55
56 static void register_irc_function(char *command, irc_cmd_t *func) {
57     struct irc_cmd *irc_cmd = malloc(sizeof(*irc_cmd));
58     if (!irc_cmd)
59     {
60         perror("malloc() failed");
61         return;
62     }
63     irc_cmd->cmd = command;
64     irc_cmd->func = func;
65     irc_cmd->next = irc_commands;
66     irc_commands = irc_cmd;
67 }
68
69 static void parse_raw(struct ClientSocket *client, char *from, char *cmd, char **argv, int argc) {
70     struct irc_cmd *irc_cmd;
71     for(irc_cmd = irc_commands; irc_cmd; irc_cmd = irc_cmd->next) {
72         if(!stricmp(irc_cmd->cmd, cmd)) {
73             irc_cmd->func(client, from, argv, argc);
74             break;
75         }
76     }
77 }
78
79 static IRC_CMD(raw_001) {
80     client->flags |= SOCKET_FLAG_READY;
81     putsock(client, "PRIVMSG Watchcat :hi");
82     return 1;
83 }
84
85 static IRC_CMD(raw_ping) {
86     if(argc == 0) return 0;
87     putsock(client, "PONG :%s", argv[0]);
88     return 1;
89 }
90
91 void parser_init() {
92     //all the raws we receive...
93     register_irc_function("001", raw_001);
94     register_irc_function("PING", raw_ping);
95 }