]> arthur.barton.de Git - ngircd-alex.git/blob - src/ngircd/parse.c
Implement new IRC+ "CHARCONV" command
[ngircd-alex.git] / src / ngircd / parse.c
1 /*
2  * ngIRCd -- The Next Generation IRC Daemon
3  * Copyright (c)2001-2010 Alexander Barton (alex@barton.de)
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 2 of the License, or
8  * (at your option) any later version.
9  * Please read the file COPYING, README and AUTHORS for more information.
10  */
11
12 #include "portab.h"
13
14 /**
15  * @file
16  * IRC command parser and validator.
17  */
18
19 #include "imp.h"
20 #include <assert.h>
21 #include <stdlib.h>
22 #include <stdio.h>
23 #include <string.h>
24 #include <strings.h>
25
26 #include "ngircd.h"
27 #include "defines.h"
28 #include "conn-func.h"
29 #include "channel.h"
30 #include "log.h"
31 #include "messages.h"
32 #include "tool.h"
33
34 #include "exp.h"
35 #include "parse.h"
36
37 #include "imp.h"
38 #include "irc.h"
39 #include "irc-cap.h"
40 #include "irc-channel.h"
41 #include "irc-encoding.h"
42 #include "irc-info.h"
43 #include "irc-login.h"
44 #include "irc-mode.h"
45 #include "irc-op.h"
46 #include "irc-oper.h"
47 #include "irc-server.h"
48 #include "irc-write.h"
49 #include "numeric.h"
50
51 #include "exp.h"
52 #include "conf.h"
53
54 struct _NUMERIC {
55         int numeric;
56         bool (*function) PARAMS(( CLIENT *Client, REQUEST *Request ));
57 };
58
59
60 static COMMAND My_Commands[] =
61 {
62         { "ADMIN", IRC_ADMIN, CLIENT_USER|CLIENT_SERVER, 0, 0, 0 },
63         { "AWAY", IRC_AWAY, CLIENT_USER, 0, 0, 0 },
64         { "CAP", IRC_CAP, 0xFFFF, 0, 0, 0 },
65         { "CONNECT", IRC_CONNECT, CLIENT_USER|CLIENT_SERVER, 0, 0, 0 },
66         { "DIE", IRC_DIE, CLIENT_USER, 0, 0, 0 },
67         { "DISCONNECT", IRC_DISCONNECT, CLIENT_USER, 0, 0, 0 },
68         { "ERROR", IRC_ERROR, 0xFFFF, 0, 0, 0 },
69         { "GLINE", IRC_xLINE, CLIENT_USER|CLIENT_SERVER, 0, 0, 0 },
70         { "HELP", IRC_HELP, CLIENT_USER, 0, 0, 0 },
71         { "INFO", IRC_INFO, CLIENT_USER|CLIENT_SERVER, 0, 0, 0 },
72         { "INVITE", IRC_INVITE, CLIENT_USER|CLIENT_SERVER, 0, 0, 0 },
73         { "ISON", IRC_ISON, CLIENT_USER, 0, 0, 0 },
74         { "JOIN", IRC_JOIN, CLIENT_USER|CLIENT_SERVER, 0, 0, 0 },
75         { "KICK", IRC_KICK, CLIENT_USER|CLIENT_SERVER, 0, 0, 0 },
76         { "KILL", IRC_KILL, CLIENT_USER|CLIENT_SERVER, 0, 0, 0 },
77         { "KLINE", IRC_xLINE, CLIENT_USER|CLIENT_SERVER, 0, 0, 0 },
78         { "LINKS", IRC_LINKS, CLIENT_USER|CLIENT_SERVER, 0, 0, 0 },
79         { "LIST", IRC_LIST, CLIENT_USER|CLIENT_SERVER, 0, 0, 0 },
80         { "LUSERS", IRC_LUSERS, CLIENT_USER|CLIENT_SERVER, 0, 0, 0 },
81         { "MODE", IRC_MODE, CLIENT_USER|CLIENT_SERVER, 0, 0, 0 },
82         { "MOTD", IRC_MOTD, CLIENT_USER|CLIENT_SERVER, 0, 0, 0 },
83         { "NAMES", IRC_NAMES, CLIENT_USER|CLIENT_SERVER, 0, 0, 0 },
84         { "NICK", IRC_NICK, 0xFFFF, 0, 0, 0 },
85         { "NJOIN", IRC_NJOIN, CLIENT_SERVER, 0, 0, 0 },
86         { "NOTICE", IRC_NOTICE, 0xFFFF, 0, 0, 0 },
87         { "OPER", IRC_OPER, CLIENT_USER, 0, 0, 0 },
88         { "PART", IRC_PART, CLIENT_USER|CLIENT_SERVER, 0, 0, 0 },
89         { "PASS", IRC_PASS, 0xFFFF, 0, 0, 0 },
90         { "PING", IRC_PING, CLIENT_USER|CLIENT_SERVER, 0, 0, 0 },
91         { "PONG", IRC_PONG, 0xFFFF, 0, 0, 0 },
92         { "PRIVMSG", IRC_PRIVMSG, CLIENT_USER|CLIENT_SERVER, 0, 0, 0 },
93         { "QUIT", IRC_QUIT, 0xFFFF, 0, 0, 0 },
94         { "REHASH", IRC_REHASH, CLIENT_USER, 0, 0, 0 },
95         { "RESTART", IRC_RESTART, CLIENT_USER, 0, 0, 0 },
96         { "SERVER", IRC_SERVER, 0xFFFF, 0, 0, 0 },
97         { "SERVICE", IRC_SERVICE, 0xFFFF, 0, 0, 0 },
98         { "SERVLIST", IRC_SERVLIST, CLIENT_USER, 0, 0, 0 },
99         { "SQUERY", IRC_SQUERY, CLIENT_USER|CLIENT_SERVER, 0, 0, 0 },
100         { "SQUIT", IRC_SQUIT, CLIENT_USER|CLIENT_SERVER, 0, 0, 0 },
101         { "STATS", IRC_STATS, CLIENT_USER|CLIENT_SERVER, 0, 0, 0 },
102         { "SUMMON", IRC_SUMMON, CLIENT_USER|CLIENT_SERVER, 0, 0, 0 },
103         { "TIME", IRC_TIME, CLIENT_USER|CLIENT_SERVER, 0, 0, 0 },
104         { "TOPIC", IRC_TOPIC, CLIENT_USER|CLIENT_SERVER, 0, 0, 0 },
105         { "TRACE", IRC_TRACE, CLIENT_USER|CLIENT_SERVER, 0, 0, 0 },
106         { "USER", IRC_USER, 0xFFFF, 0, 0, 0 },
107         { "USERHOST", IRC_USERHOST, CLIENT_USER, 0, 0, 0 },
108         { "USERS", IRC_USERS, CLIENT_USER|CLIENT_SERVER, 0, 0, 0 },
109         { "VERSION", IRC_VERSION, CLIENT_USER|CLIENT_SERVER, 0, 0, 0 },
110         { "WALLOPS", IRC_WALLOPS, CLIENT_USER|CLIENT_SERVER, 0, 0, 0 },
111         { "WEBIRC", IRC_WEBIRC, CLIENT_UNKNOWN, 0, 0, 0 },
112         { "WHO", IRC_WHO, CLIENT_USER, 0, 0, 0 },
113         { "WHOIS", IRC_WHOIS, CLIENT_USER|CLIENT_SERVER, 0, 0, 0 },
114         { "WHOWAS", IRC_WHOWAS, CLIENT_USER|CLIENT_SERVER, 0, 0, 0 },
115
116 #ifdef IRCPLUS
117         { "CHANINFO", IRC_CHANINFO, CLIENT_SERVER, 0, 0, 0 },
118 # ifdef ICONV
119         { "CHARCONV", IRC_CHARCONV, CLIENT_USER, 0, 0, 0 },
120 # endif
121 #endif
122
123 #ifndef STRICT_RFC
124         { "GET",  IRC_QUIT_HTTP, CLIENT_UNKNOWN, 0, 0, 0 },
125         { "POST", IRC_QUIT_HTTP, CLIENT_UNKNOWN, 0, 0, 0 },
126 #endif
127         { NULL, NULL, 0x0, 0, 0, 0 } /* Ende-Marke */
128 };
129
130 static void Init_Request PARAMS(( REQUEST *Req ));
131
132 static bool Validate_Prefix PARAMS(( CONN_ID Idx, REQUEST *Req, bool *Closed ));
133 static bool Validate_Command PARAMS(( CONN_ID Idx, REQUEST *Req, bool *Closed ));
134 static bool Validate_Args PARAMS(( CONN_ID Idx, REQUEST *Req, bool *Closed ));
135
136 static bool Handle_Request PARAMS(( CONN_ID Idx, REQUEST *Req ));
137
138 static bool ScrubCTCP PARAMS((char *Request));
139
140 /**
141  * Return the pointer to the global "IRC command structure".
142  * This structure, an array of type "COMMAND" describes all the IRC commands
143  * implemented by ngIRCd and how to handle them.
144  * @return Pointer to the global command structure.
145  */
146 GLOBAL COMMAND *
147 Parse_GetCommandStruct( void )
148 {
149         return My_Commands;
150 } /* Parse_GetCommandStruct */
151
152
153 /**
154  * Parse a command ("request") received from a client.
155  * 
156  * This function is called after the connection layer received a valid CR+LF
157  * terminated line of text: we asume that this is a valid IRC command and
158  * try to do something useful with it :-)
159  *
160  * All errors are reported to the client from which the command has been
161  * received, and if the error is fatal this connection is closed down.
162  *
163  * This function is able to parse the syntax as described in RFC 2812,
164  * section 2.3.
165  *
166  * @param Idx Index of the connection from which the command has been received.
167  * @param Request NULL terminated line of text (the "command").
168  * @return true on success (valid command or "regular" error), false if a
169  *      fatal error occured and the connection has been shut down.
170  */
171 GLOBAL bool
172 Parse_Request( CONN_ID Idx, char *Request )
173 {
174         REQUEST req;
175         char *start, *ptr;
176         bool closed;
177
178         assert( Idx >= 0 );
179         assert( Request != NULL );
180
181 #ifdef SNIFFER
182         if( NGIRCd_Sniffer ) Log( LOG_DEBUG, " <- connection %d: '%s'.", Idx, Request );
183 #endif
184
185         Init_Request( &req );
186
187         /* remove leading & trailing whitespace */
188         ngt_TrimStr( Request );
189
190         if (Conf_ScrubCTCP && ScrubCTCP(Request))
191                 return true;
192
193         if (Request[0] == ':') {
194                 /* Prefix */
195                 req.prefix = Request + 1;
196                 ptr = strchr( Request, ' ' );
197                 if( ! ptr )
198                 {
199                         LogDebug("Connection %d: Parse error: prefix without command!?", Idx);
200                         return Conn_WriteStr(Idx, "ERROR :Prefix without command");
201                 }
202                 *ptr = '\0';
203 #ifndef STRICT_RFC
204                 /* ignore multiple spaces between prefix and command */
205                 while( *(ptr + 1) == ' ' ) ptr++;
206 #endif
207                 start = ptr + 1;
208         }
209         else start = Request;
210
211         ptr = strchr( start, ' ' );
212         if( ptr )
213         {
214                 *ptr = '\0';
215 #ifndef STRICT_RFC
216                 /* ignore multiple spaces between parameters */
217                 while( *(ptr + 1) == ' ' ) ptr++;
218 #endif
219         }
220         req.command = start;
221
222         /* Arguments, Parameters */
223         if( ptr )
224         {
225                 start = ptr + 1;
226                 while( start )
227                 {
228                         if( start[0] == ':' )
229                         {
230                                 req.argv[req.argc] = start + 1;
231                                 ptr = NULL;
232                         }
233                         else
234                         {
235                                 req.argv[req.argc] = start;
236                                 ptr = strchr( start, ' ' );
237                                 if( ptr )
238                                 {
239                                         *ptr = '\0';
240 #ifndef STRICT_RFC
241                                         while( *(ptr + 1) == ' ' ) ptr++;
242 #endif
243                                 }
244                         }
245
246                         req.argc++;
247
248                         if( start[0] == ':' ) break;
249                         if( req.argc > 14 ) break;
250
251                         if( ptr ) start = ptr + 1;
252                         else start = NULL;
253                 }
254         }
255
256         if( ! Validate_Prefix( Idx, &req, &closed )) return ! closed;
257         if( ! Validate_Command( Idx, &req, &closed )) return ! closed;
258         if( ! Validate_Args( Idx, &req, &closed )) return ! closed;
259
260         return Handle_Request( Idx, &req );
261 } /* Parse_Request */
262
263
264 /**
265  * Initialize request structure.
266  * @param Req Request structure to be initialized.
267  */
268 static void
269 Init_Request( REQUEST *Req )
270 {
271         /* Neue Request-Struktur initialisieren */
272
273         int i;
274
275         assert( Req != NULL );
276
277         Req->prefix = NULL;
278         Req->command = NULL;
279         for( i = 0; i < 15; Req->argv[i++] = NULL );
280         Req->argc = 0;
281 } /* Init_Request */
282
283
284 static bool
285 Validate_Prefix( CONN_ID Idx, REQUEST *Req, bool *Closed )
286 {
287         CLIENT *client, *c;
288
289         assert( Idx >= 0 );
290         assert( Req != NULL );
291
292         *Closed = false;
293
294         client = Conn_GetClient( Idx );
295         assert( client != NULL );
296
297         if (!Req->prefix && Client_Type(client) == CLIENT_SERVER
298             && !(Conn_Options(Idx) & CONN_RFC1459)
299             && strcasecmp(Req->command, "ERROR") != 0
300             && strcasecmp(Req->command, "PING") != 0)
301         {
302                 Log(LOG_ERR,
303                     "Received command without prefix (connection %d, command \"%s\")!?",
304                     Idx, Req->command);
305                 if (!Conn_WriteStr(Idx, "ERROR :Prefix missing"))
306                         *Closed = true;
307                 return false;
308         }
309
310         if (!Req->prefix)
311                 return true;
312
313         /* only validate if this connection is already registered */
314         if (Client_Type(client) != CLIENT_USER
315             && Client_Type(client) != CLIENT_SERVER
316             && Client_Type(client) != CLIENT_SERVICE) {
317                 /* not registered, ignore prefix */
318                 Req->prefix = NULL;
319                 return true;
320         }
321
322         /* check if client in prefix is known */
323         c = Client_Search( Req->prefix );
324         if (!c) {
325                 Log(LOG_ERR,
326                     "Invalid prefix \"%s\", client not known (connection %d, command \"%s\")!?",
327                     Req->prefix, Idx, Req->command);
328                 if (!Conn_WriteStr(Idx,
329                                    "ERROR :Invalid prefix \"%s\", client not known",
330                                    Req->prefix))
331                         *Closed = true;
332                 return false;
333         }
334
335         /* check if the client named in the prefix is expected
336          * to come from that direction */
337         if (Client_NextHop(c) != client) {
338                 if (Client_Type(c) != CLIENT_SERVER) {
339                         Log(LOG_ERR,
340                             "Spoofed prefix \"%s\" from \"%s\" (connection %d, command \"%s\")!",
341                             Req->prefix, Client_Mask(Conn_GetClient(Idx)), Idx,
342                             Req->command);
343                         Conn_Close(Idx, NULL, "Spoofed prefix", true);
344                         *Closed = true;
345                 } else {
346                         Log(LOG_INFO,
347                             "Ignoring spoofed prefix \"%s\" from \"%s\" (connection %d, command \"%s\").",
348                             Req->prefix, Client_Mask(Conn_GetClient(Idx)), Idx,
349                             Req->command);
350                 }
351                 return false;
352
353         }
354
355         return true;
356 } /* Validate_Prefix */
357
358
359 static bool
360 Validate_Command( UNUSED CONN_ID Idx, UNUSED REQUEST *Req, bool *Closed )
361 {
362         assert( Idx >= 0 );
363         assert( Req != NULL );
364         *Closed = false;
365
366         return true;
367 } /* Validate_Comman */
368
369
370 static bool
371 #ifdef STRICT_RFC
372 Validate_Args(CONN_ID Idx, REQUEST *Req, bool *Closed)
373 #else
374 Validate_Args(UNUSED CONN_ID Idx, UNUSED REQUEST *Req, bool *Closed)
375 #endif
376 {
377 #ifdef STRICT_RFC
378         int i;
379 #endif
380
381         *Closed = false;
382
383 #ifdef STRICT_RFC
384         assert( Idx >= 0 );
385         assert( Req != NULL );
386
387         /* CR and LF are never allowed in command parameters.
388          * But since we do accept lines terminated only with CR or LF in
389          * "non-RFC-compliant mode" (besides the correct CR+LF combination),
390          * this check can only trigger in "strict RFC" mode; therefore we
391          * optimize it away otherwise ... */
392         for (i = 0; i < Req->argc; i++) {
393                 if (strchr(Req->argv[i], '\r') || strchr(Req->argv[i], '\n')) {
394                         Log(LOG_ERR,
395                             "Invalid character(s) in parameter (connection %d, command %s)!?",
396                             Idx, Req->command);
397                         if (!Conn_WriteStr(Idx,
398                                            "ERROR :Invalid character(s) in parameter!"))
399                                 *Closed = true;
400                         return false;
401                 }
402         }
403 #endif
404
405         return true;
406 } /* Validate_Args */
407
408
409 /* Command is a status code ("numeric") from another server */
410 static bool
411 Handle_Numeric(CLIENT *client, REQUEST *Req)
412 {
413         static const struct _NUMERIC Numerics[] = {
414                 {   5, IRC_Num_ISUPPORT },
415                 {  20, NULL },
416                 { 376, IRC_Num_ENDOFMOTD }
417         };
418         int i, num;
419         char str[LINE_LEN];
420         CLIENT *prefix, *target = NULL;
421
422         /* Determine target */
423         if (Req->argc > 0) {
424                 if (strcmp(Req->argv[0], "*") != 0)
425                         target = Client_Search(Req->argv[0]);
426                 else
427                         target = Client_ThisServer();
428         }
429
430         if (!target) {
431                 /* Status code without target!? */
432                 if (Req->argc > 0)
433                         Log(LOG_WARNING,
434                             "Unknown target for status code %s: \"%s\"",
435                             Req->command, Req->argv[0]);
436                 else
437                         Log(LOG_WARNING,
438                             "Unknown target for status code %s!",
439                             Req->command);
440                 return true;
441         }
442         if (target == Client_ThisServer()) {
443                 /* This server is the target of the numeric */
444                 num = atoi(Req->command);
445
446                 for (i = 0; i < (int) C_ARRAY_SIZE(Numerics); i++) {
447                         if (num == Numerics[i].numeric) {
448                                 if (!Numerics[i].function)
449                                         return CONNECTED;
450                                 return Numerics[i].function(client, Req);
451                         }
452                 }
453
454                 LogDebug("Ignored status code %s from \"%s\".",
455                          Req->command, Client_ID(client));
456                 return true;
457         }
458
459         /* Determine source */
460         if (! Req->prefix[0]) {
461                 /* Oops, no prefix!? */
462                 Log(LOG_WARNING, "Got status code %s from \"%s\" without prefix!?",
463                                                 Req->command, Client_ID(client));
464                 return true;
465         }
466
467         prefix = Client_Search(Req->prefix);
468         if (! prefix) { /* Oops, unknown prefix!? */
469                 Log(LOG_WARNING, "Got status code %s from unknown source: \"%s\"", Req->command, Req->prefix);
470                 return true;
471         }
472
473         /* Forward status code */
474         strlcpy(str, Req->command, sizeof(str));
475         for (i = 0; i < Req->argc; i++) {
476                 if (i < Req->argc - 1)
477                         strlcat(str, " ", sizeof(str));
478                 else
479                         strlcat(str, " :", sizeof(str));
480                 strlcat(str, Req->argv[i], sizeof(str));
481         }
482         return IRC_WriteStrClientPrefix(target, prefix, "%s", str);
483 }
484
485 static bool
486 Handle_Request( CONN_ID Idx, REQUEST *Req )
487 {
488         CLIENT *client;
489         bool result = true;
490         int client_type;
491         COMMAND *cmd;
492
493         assert( Idx >= 0 );
494         assert( Req != NULL );
495         assert( Req->command != NULL );
496
497         client = Conn_GetClient( Idx );
498         assert( client != NULL );
499
500         /* Numeric? */
501         client_type = Client_Type(client);
502         if ((client_type == CLIENT_SERVER ||
503              client_type == CLIENT_UNKNOWNSERVER)
504             && strlen(Req->command) == 3 && atoi(Req->command) > 1)
505                 return Handle_Numeric(client, Req);
506
507         cmd = My_Commands;
508         while (cmd->name) {
509                 if (strcasecmp(Req->command, cmd->name) != 0) {
510                         cmd++;
511                         continue;
512                 }
513
514                 if (!(client_type & cmd->type))
515                         return IRC_WriteStrClient(client, ERR_NOTREGISTERED_MSG, Client_ID(client));
516
517                 /* Command is allowed for this client: call it and count produced bytes */
518                 Conn_ResetWCounter();
519                 result = (cmd->function)(client, Req);
520                 cmd->bytes += Conn_WCounter();
521
522                 /* Adjust counters */
523                 if (client_type != CLIENT_SERVER)
524                         cmd->lcount++;
525                 else
526                         cmd->rcount++;
527                 return result;
528         }
529
530         if (client_type != CLIENT_USER &&
531             client_type != CLIENT_SERVER &&
532             client_type != CLIENT_SERVICE )
533                 return true;
534
535         /* Unknown command and registered connection: generate error: */
536         LogDebug("Connection %d: Unknown command \"%s\", %d %s,%s prefix.",
537                         Client_Conn( client ), Req->command, Req->argc,
538                         Req->argc == 1 ? "parameter" : "parameters",
539                         Req->prefix ? "" : " no" );
540
541         if (Client_Type(client) != CLIENT_SERVER) {
542                 result = IRC_WriteStrClient(client, ERR_UNKNOWNCOMMAND_MSG,
543                                 Client_ID(client), Req->command);
544                 Conn_SetPenalty(Idx, 1);
545         }
546         return result;
547 } /* Handle_Request */
548
549
550 /**
551  * Check if incoming messages contains CTCP commands and should be dropped.
552  *
553  * @param Request NULL terminated incoming command.
554  * @returns true, when the message should be dropped.
555  */
556 static bool
557 ScrubCTCP(char *Request)
558 {
559         static const char me_cmd[] = "ACTION ";
560         static const char ctcp_char = 0x1;
561         bool dropCommand = false;
562         char *ptr = Request;
563         char *ptrEnd = strchr(Request, '\0');
564
565         if (Request[0] == ':' && ptrEnd > ptr)
566                 ptr++;
567
568         while (ptr != ptrEnd && *ptr != ':')
569                 ptr++;
570
571         if ((ptrEnd - ptr) > 1) {
572                 ptr++;
573                 if (*ptr == ctcp_char) {
574                         dropCommand = true;
575                         ptr++;
576                         /* allow /me commands */
577                         if ((size_t)(ptrEnd - ptr) >= strlen(me_cmd)
578                             && !strncmp(ptr, me_cmd, strlen(me_cmd)))
579                                 dropCommand = false;
580                 }
581         }
582         return dropCommand;
583 }
584
585 /* -eof- */