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