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