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