]> arthur.barton.de Git - ngircd-alex.git/blob - src/ngircd/parse.c
Allow pre-defined server local channels ("&").
[ngircd-alex.git] / src / ngircd / parse.c
1 /*
2  * ngIRCd -- The Next Generation IRC Daemon
3  * Copyright (c)2001-2008 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 "client.h"
30 #include "channel.h"
31 #include "log.h"
32 #include "messages.h"
33 #include "tool.h"
34
35 #include "exp.h"
36 #include "parse.h"
37
38 #include "imp.h"
39 #include "irc.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
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, 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, CLIENT_USER|CLIENT_SERVER, 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_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         { "WHO", IRC_WHO, CLIENT_USER, 0, 0, 0 },
107         { "WHOIS", IRC_WHOIS, CLIENT_USER|CLIENT_SERVER, 0, 0, 0 },
108         { "WHOWAS", IRC_WHOWAS, CLIENT_USER|CLIENT_SERVER, 0, 0, 0 },
109 #ifdef IRCPLUS
110         { "CHANINFO", IRC_CHANINFO, CLIENT_SERVER, 0, 0, 0 },
111 #endif
112         { NULL, NULL, 0x0, 0, 0, 0 } /* Ende-Marke */
113 };
114
115 static void Init_Request PARAMS(( REQUEST *Req ));
116
117 static bool Validate_Prefix PARAMS(( CONN_ID Idx, REQUEST *Req, bool *Closed ));
118 static bool Validate_Command PARAMS(( CONN_ID Idx, REQUEST *Req, bool *Closed ));
119 static bool Validate_Args PARAMS(( CONN_ID Idx, REQUEST *Req, bool *Closed ));
120
121 static bool Handle_Request PARAMS(( CONN_ID Idx, REQUEST *Req ));
122
123 #define ARRAY_SIZE(x)   (sizeof(x)/sizeof((x)[0]))
124
125 /**
126  * Return the pointer to the global "IRC command structure".
127  * This structure, an array of type "COMMAND" describes all the IRC commands
128  * implemented by ngIRCd and how to handle them.
129  * @return Pointer to the global command structure.
130  */
131 GLOBAL COMMAND *
132 Parse_GetCommandStruct( void )
133 {
134         return My_Commands;
135 } /* Parse_GetCommandStruct */
136
137
138 /**
139  * Parse a command ("request") received from a client.
140  * 
141  * This function is called after the connection layer received a valid CR+LF
142  * terminated line of text: we asume that this is a valid IRC command and
143  * try to do something useful with it :-)
144  *
145  * All errors are reported to the client from which the command has been
146  * received, and if the error is fatal this connection is closed down.
147  *
148  * This function is able to parse the syntax as described in RFC 2812,
149  * section 2.3.
150  *
151  * @param Idx Index of the connection from which the command has been received.
152  * @param Request NULL terminated line of text (the "command").
153  * @return true on success (valid command or "regular" error), false if a
154  *      fatal error occured and the connection has been shut down.
155  */
156 GLOBAL bool
157 Parse_Request( CONN_ID Idx, char *Request )
158 {
159         REQUEST req;
160         char *start, *ptr;
161         bool closed;
162
163         assert( Idx >= 0 );
164         assert( Request != NULL );
165
166 #ifdef SNIFFER
167         if( NGIRCd_Sniffer ) Log( LOG_DEBUG, " <- connection %d: '%s'.", Idx, Request );
168 #endif
169
170         Init_Request( &req );
171
172         /* Fuehrendes und folgendes "Geraffel" verwerfen */
173         ngt_TrimStr( Request );
174
175         /* gibt es ein Prefix? */
176         if( Request[0] == ':' )
177         {
178                 /* Prefix vorhanden */
179                 req.prefix = Request + 1;
180                 ptr = strchr( Request, ' ' );
181                 if( ! ptr )
182                 {
183                         Log( LOG_DEBUG, "Connection %d: Parse error: prefix without command!?", Idx );
184                         return Conn_WriteStr( Idx, "ERROR :Prefix without command!?" );
185                 }
186                 *ptr = '\0';
187 #ifndef STRICT_RFC
188                 /* multiple Leerzeichen als Trenner zwischen
189                  * Prefix und Befehl ignorieren */
190                 while( *(ptr + 1) == ' ' ) ptr++;
191 #endif
192                 start = ptr + 1;
193         }
194         else start = Request;
195
196         /* Befehl */
197         ptr = strchr( start, ' ' );
198         if( ptr )
199         {
200                 *ptr = '\0';
201 #ifndef STRICT_RFC
202                 /* multiple Leerzeichen als Trenner vor
203                  * Parametern ignorieren */
204                 while( *(ptr + 1) == ' ' ) ptr++;
205 #endif
206         }
207         req.command = start;
208
209         /* Argumente, Parameter */
210         if( ptr )
211         {
212                 /* Prinzipiell gibt es welche :-) */
213                 start = ptr + 1;
214                 while( start )
215                 {
216                         /* Parameter-String "zerlegen" */
217                         if( start[0] == ':' )
218                         {
219                                 req.argv[req.argc] = start + 1;
220                                 ptr = NULL;
221                         }
222                         else
223                         {
224                                 req.argv[req.argc] = start;
225                                 ptr = strchr( start, ' ' );
226                                 if( ptr )
227                                 {
228                                         *ptr = '\0';
229 #ifndef STRICT_RFC
230                                         /* multiple Leerzeichen als
231                                          * Parametertrenner ignorieren */
232                                         while( *(ptr + 1) == ' ' ) ptr++;
233 #endif
234                                 }
235                         }
236
237                         req.argc++;
238
239                         if( start[0] == ':' ) break;
240                         if( req.argc > 14 ) break;
241
242                         if( ptr ) start = ptr + 1;
243                         else start = NULL;
244                 }
245         }
246
247         /* Daten validieren */
248         if( ! Validate_Prefix( Idx, &req, &closed )) return ! closed;
249         if( ! Validate_Command( Idx, &req, &closed )) return ! closed;
250         if( ! Validate_Args( Idx, &req, &closed )) return ! closed;
251
252         return Handle_Request( Idx, &req );
253 } /* Parse_Request */
254
255
256 /**
257  * Initialize request structure.
258  * @param Req Request structure to be initialized.
259  */
260 static void
261 Init_Request( REQUEST *Req )
262 {
263         /* Neue Request-Struktur initialisieren */
264
265         int i;
266
267         assert( Req != NULL );
268
269         Req->prefix = NULL;
270         Req->command = NULL;
271         for( i = 0; i < 15; Req->argv[i++] = NULL );
272         Req->argc = 0;
273 } /* Init_Request */
274
275
276 static bool
277 Validate_Prefix( CONN_ID Idx, REQUEST *Req, bool *Closed )
278 {
279         CLIENT *client, *c;
280
281         assert( Idx >= 0 );
282         assert( Req != NULL );
283
284         *Closed = false;
285
286         /* ist ueberhaupt ein Prefix vorhanden? */
287         if( ! Req->prefix ) return true;
288
289         /* Client-Struktur der Connection ermitteln */
290         client = Conn_GetClient( Idx );
291         assert( client != NULL );
292
293         /* nur validieren, wenn bereits registrierte Verbindung */
294         if(( Client_Type( client ) != CLIENT_USER ) && ( Client_Type( client ) != CLIENT_SERVER ) && ( Client_Type( client ) != CLIENT_SERVICE ))
295         {
296                 /* noch nicht registrierte Verbindung.
297                  * Das Prefix wird ignoriert. */
298                 Req->prefix = NULL;
299                 return true;
300         }
301
302         /* pruefen, ob der im Prefix angegebene Client bekannt ist */
303         c = Client_Search( Req->prefix );
304         if( ! c )
305         {
306                 /* im Prefix angegebener Client ist nicht bekannt */
307                 Log( LOG_ERR, "Invalid prefix \"%s\", client not known (connection %d, command %s)!?", Req->prefix, Idx, Req->command );
308                 if( ! Conn_WriteStr( Idx, "ERROR :Invalid prefix \"%s\", client not known!?", Req->prefix )) *Closed = true;
309                 return false;
310         }
311
312         /* pruefen, ob der Client mit dem angegebenen Prefix in Richtung
313          * des Senders liegt, d.h. sicherstellen, dass das Prefix nicht
314          * gefaelscht ist */
315         if( Client_NextHop( c ) != client )
316         {
317                 /* das angegebene Prefix ist aus dieser Richtung, also
318                  * aus der gegebenen Connection, ungueltig! */
319                 Log( LOG_ERR, "Spoofed prefix \"%s\" from \"%s\" (connection %d, command %s)!", Req->prefix, Client_Mask( Conn_GetClient( Idx )), Idx, Req->command );
320                 Conn_Close( Idx, NULL, "Spoofed prefix", true);
321                 *Closed = true;
322                 return false;
323         }
324
325         return true;
326 } /* Validate_Prefix */
327
328
329 static bool
330 Validate_Command( UNUSED CONN_ID Idx, UNUSED REQUEST *Req, bool *Closed )
331 {
332         assert( Idx >= 0 );
333         assert( Req != NULL );
334         *Closed = false;
335
336         return true;
337 } /* Validate_Comman */
338
339
340 static bool
341 #ifdef STRICT_RFC
342 Validate_Args(CONN_ID Idx, REQUEST *Req, bool *Closed)
343 #else
344 Validate_Args(UNUSED CONN_ID Idx, UNUSED REQUEST *Req, bool *Closed)
345 #endif
346 {
347 #ifdef STRICT_RFC
348         int i;
349 #endif
350
351         *Closed = false;
352
353 #ifdef STRICT_RFC
354         assert( Idx >= 0 );
355         assert( Req != NULL );
356
357         /* CR and LF are never allowed in command parameters.
358          * But since we do accept lines terminated only with CR or LF in
359          * "non-RFC-compliant mode" (besides the correct CR+LF combination),
360          * this check can only trigger in "strict RFC" mode; therefore we
361          * optimize it away otherwise ... */
362         for (i = 0; i < Req->argc; i++) {
363                 if (strchr(Req->argv[i], '\r') || strchr(Req->argv[i], '\n')) {
364                         Log(LOG_ERR,
365                             "Invalid character(s) in parameter (connection %d, command %s)!?",
366                             Idx, Req->command);
367                         if (!Conn_WriteStr(Idx,
368                                            "ERROR :Invalid character(s) in parameter!"))
369                                 *Closed = true;
370                         return false;
371                 }
372         }
373 #endif
374
375         return true;
376 } /* Validate_Args */
377
378
379 /* Command is a status code ("numeric") from another server */
380 static bool
381 Handle_Numeric(CLIENT *client, REQUEST *Req)
382 {
383         static const struct _NUMERIC Numerics[] = {
384                 {   5, IRC_Num_ISUPPORT },
385                 {  20, NULL },
386                 { 376, IRC_Num_ENDOFMOTD }
387         };
388         int i, num;
389         char str[LINE_LEN];
390         CLIENT *prefix, *target = NULL;
391
392         /* Determine target */
393         if (Req->argc > 0) {
394                 if (strcmp(Req->argv[0], "*") != 0)
395                         target = Client_Search(Req->argv[0]);
396                 else
397                         target = Client_ThisServer();
398         }
399
400         if (!target) {
401                 /* Status code without target!? */
402                 if (Req->argc > 0)
403                         Log(LOG_WARNING,
404                             "Unknown target for status code %s: \"%s\"",
405                             Req->command, Req->argv[0]);
406                 else
407                         Log(LOG_WARNING,
408                             "Unknown target for status code %s!",
409                             Req->command);
410                 return true;
411         }
412         if (target == Client_ThisServer()) {
413                 /* This server is the target of the numeric */
414                 num = atoi(Req->command);
415
416                 for (i = 0; i < (int) ARRAY_SIZE(Numerics); i++) {
417                         if (num == Numerics[i].numeric) {
418                                 if (!Numerics[i].function)
419                                         return CONNECTED;
420                                 return Numerics[i].function(client, Req);
421                         }
422                 }
423
424                 LogDebug("Ignored status code %s from \"%s\".",
425                          Req->command, Client_ID(client));
426                 return true;
427         }
428
429         /* Determine source */
430         if (! Req->prefix[0]) {
431                 /* Oops, no prefix!? */
432                 Log(LOG_WARNING, "Got status code %s from \"%s\" without prefix!?",
433                                                 Req->command, Client_ID(client));
434                 return true;
435         }
436
437         prefix = Client_Search(Req->prefix);
438         if (! prefix) { /* Oops, unknown prefix!? */
439                 Log(LOG_WARNING, "Got status code %s from unknown source: \"%s\"", Req->command, Req->prefix);
440                 return true;
441         }
442
443         /* Forward status code */
444         strlcpy(str, Req->command, sizeof(str));
445         for (i = 0; i < Req->argc; i++) {
446                 if (i < Req->argc - 1)
447                         strlcat(str, " ", sizeof(str));
448                 else
449                         strlcat(str, " :", sizeof(str));
450                 strlcat(str, Req->argv[i], sizeof(str));
451         }
452         return IRC_WriteStrClientPrefix(target, prefix, "%s", str);
453 }
454
455
456 static bool
457 Handle_Request( CONN_ID Idx, REQUEST *Req )
458 {
459         /* Client-Request verarbeiten. Bei einem schwerwiegenden Fehler
460          * wird die Verbindung geschlossen und false geliefert. */
461         CLIENT *client;
462         bool result = true;
463         int client_type;
464         COMMAND *cmd;
465
466         assert( Idx >= 0 );
467         assert( Req != NULL );
468         assert( Req->command != NULL );
469
470         client = Conn_GetClient( Idx );
471         assert( client != NULL );
472
473         /* Numeric? */
474         client_type = Client_Type(client);
475         if ((client_type == CLIENT_SERVER ||
476              client_type == CLIENT_UNKNOWNSERVER)
477             && strlen(Req->command) == 3 && atoi(Req->command) > 1)
478                 return Handle_Numeric(client, Req);
479
480         cmd = My_Commands;
481         while (cmd->name) {
482                 /* Befehl suchen */
483                 if (strcasecmp(Req->command, cmd->name) != 0) {
484                         cmd++;
485                         continue;
486                 }
487
488                 if (!(client_type & cmd->type))
489                         return IRC_WriteStrClient(client, ERR_NOTREGISTERED_MSG, Client_ID(client));
490
491                 /* Command is allowed for this client: call it and count produced bytes */
492                 Conn_ResetWCounter();
493                 result = (cmd->function)(client, Req);
494                 cmd->bytes += Conn_WCounter();
495
496                 /* Adjust counters */
497                 if (client_type != CLIENT_SERVER)
498                         cmd->lcount++;
499                 else
500                         cmd->rcount++;
501                 return result;
502         }
503
504         if (client_type != CLIENT_USER &&
505             client_type != CLIENT_SERVER &&
506             client_type != CLIENT_SERVICE )
507                 return true;
508
509         /* Unknown command and registered connection: generate error: */
510         LogDebug("Connection %d: Unknown command \"%s\", %d %s,%s prefix.",
511                         Client_Conn( client ), Req->command, Req->argc,
512                         Req->argc == 1 ? "parameter" : "parameters",
513                         Req->prefix ? "" : " no" );
514
515         if (Client_Type(client) != CLIENT_SERVER) {
516                 result = IRC_WriteStrClient(client, ERR_UNKNOWNCOMMAND_MSG,
517                                 Client_ID(client), Req->command);
518                 Conn_SetPenalty(Idx, 1);
519         }
520         return result;
521 } /* Handle_Request */
522
523
524 /* -eof- */