Blob


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 */
12 #include "portab.h"
14 /**
15 * @file
16 * IRC command parser and validator.
17 */
19 #include "imp.h"
20 #include <assert.h>
21 #include <stdlib.h>
22 #include <stdio.h>
23 #include <string.h>
24 #include <strings.h>
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"
35 #include "exp.h"
36 #include "parse.h"
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"
50 #include "exp.h"
52 struct _NUMERIC {
53 int numeric;
54 bool (*function) PARAMS(( CLIENT *Client, REQUEST *Request ));
55 };
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 };
115 static void Init_Request PARAMS(( REQUEST *Req ));
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 ));
121 static bool Handle_Request PARAMS(( CONN_ID Idx, REQUEST *Req ));
123 #define ARRAY_SIZE(x) (sizeof(x)/sizeof((x)[0]))
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 )
134 return My_Commands;
135 } /* Parse_GetCommandStruct */
138 /**
139 * Parse a command ("request") received from a client.
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 :-)
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.
148 * This function is able to parse the syntax as described in RFC 2812,
149 * section 2.3.
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 )
159 REQUEST req;
160 char *start, *ptr;
161 bool closed;
163 assert( Idx >= 0 );
164 assert( Request != NULL );
166 #ifdef SNIFFER
167 if( NGIRCd_Sniffer ) Log( LOG_DEBUG, " <- connection %d: '%s'.", Idx, Request );
168 #endif
170 Init_Request( &req );
172 /* Fuehrendes und folgendes "Geraffel" verwerfen */
173 ngt_TrimStr( Request );
175 /* gibt es ein Prefix? */
176 if( Request[0] == ':' )
178 /* Prefix vorhanden */
179 req.prefix = Request + 1;
180 ptr = strchr( Request, ' ' );
181 if( ! ptr )
183 Log( LOG_DEBUG, "Connection %d: Parse error: prefix without command!?", Idx );
184 return Conn_WriteStr( Idx, "ERROR :Prefix without command!?" );
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;
194 else start = Request;
196 /* Befehl */
197 ptr = strchr( start, ' ' );
198 if( ptr )
200 *ptr = '\0';
201 #ifndef STRICT_RFC
202 /* multiple Leerzeichen als Trenner vor
203 * Parametern ignorieren */
204 while( *(ptr + 1) == ' ' ) ptr++;
205 #endif
207 req.command = start;
209 /* Argumente, Parameter */
210 if( ptr )
212 /* Prinzipiell gibt es welche :-) */
213 start = ptr + 1;
214 while( start )
216 /* Parameter-String "zerlegen" */
217 if( start[0] == ':' )
219 req.argv[req.argc] = start + 1;
220 ptr = NULL;
222 else
224 req.argv[req.argc] = start;
225 ptr = strchr( start, ' ' );
226 if( ptr )
228 *ptr = '\0';
229 #ifndef STRICT_RFC
230 /* multiple Leerzeichen als
231 * Parametertrenner ignorieren */
232 while( *(ptr + 1) == ' ' ) ptr++;
233 #endif
237 req.argc++;
239 if( start[0] == ':' ) break;
240 if( req.argc > 14 ) break;
242 if( ptr ) start = ptr + 1;
243 else start = NULL;
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;
252 return Handle_Request( Idx, &req );
253 } /* Parse_Request */
256 /**
257 * Initialize request structure.
258 * @param Req Request structure to be initialized.
259 */
260 static void
261 Init_Request( REQUEST *Req )
263 /* Neue Request-Struktur initialisieren */
265 int i;
267 assert( Req != NULL );
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 */
276 static bool
277 Validate_Prefix( CONN_ID Idx, REQUEST *Req, bool *Closed )
279 CLIENT *client, *c;
281 assert( Idx >= 0 );
282 assert( Req != NULL );
284 *Closed = false;
286 /* ist ueberhaupt ein Prefix vorhanden? */
287 if( ! Req->prefix ) return true;
289 /* Client-Struktur der Connection ermitteln */
290 client = Conn_GetClient( Idx );
291 assert( client != NULL );
293 /* nur validieren, wenn bereits registrierte Verbindung */
294 if(( Client_Type( client ) != CLIENT_USER ) && ( Client_Type( client ) != CLIENT_SERVER ) && ( Client_Type( client ) != CLIENT_SERVICE ))
296 /* noch nicht registrierte Verbindung.
297 * Das Prefix wird ignoriert. */
298 Req->prefix = NULL;
299 return true;
302 /* pruefen, ob der im Prefix angegebene Client bekannt ist */
303 c = Client_Search( Req->prefix );
304 if( ! c )
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;
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 )
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;
325 return true;
326 } /* Validate_Prefix */
329 static bool
330 Validate_Command( UNUSED CONN_ID Idx, UNUSED REQUEST *Req, bool *Closed )
332 assert( Idx >= 0 );
333 assert( Req != NULL );
334 *Closed = false;
336 return true;
337 } /* Validate_Comman */
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
347 #ifdef STRICT_RFC
348 int i;
349 #endif
351 *Closed = false;
353 #ifdef STRICT_RFC
354 assert( Idx >= 0 );
355 assert( Req != NULL );
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;
373 #endif
375 return true;
376 } /* Validate_Args */
379 /* Command is a status code ("numeric") from another server */
380 static bool
381 Handle_Numeric(CLIENT *client, REQUEST *Req)
383 static const struct _NUMERIC Numerics[] = {
384 { 005, IRC_Num_ISUPPORT },
385 { 376, IRC_Num_ENDOFMOTD }
386 };
387 int i, num;
388 char str[LINE_LEN];
389 CLIENT *prefix, *target = NULL;
391 /* Determine target */
392 if (Req->argc > 0)
393 target = Client_Search(Req->argv[0]);
395 if (!target) {
396 /* Status code without target!? */
397 if (Req->argc > 0)
398 Log(LOG_WARNING,
399 "Unknown target for status code %s: \"%s\"",
400 Req->command, Req->argv[0]);
401 else
402 Log(LOG_WARNING,
403 "Unknown target for status code %s!",
404 Req->command);
405 return true;
407 if (target == Client_ThisServer()) {
408 /* This server is the target of the numeric */
409 num = atoi(Req->command);
411 for (i = 0; i < (int) ARRAY_SIZE(Numerics); i++) {
412 if (num == Numerics[i].numeric)
413 return Numerics[i].function(client, Req);
416 LogDebug("Ignored status code %s from \"%s\".",
417 Req->command, Client_ID(client));
418 return true;
421 /* Determine source */
422 if (! Req->prefix[0]) {
423 /* Oops, no prefix!? */
424 Log(LOG_WARNING, "Got status code %s from \"%s\" without prefix!?",
425 Req->command, Client_ID(client));
426 return true;
429 prefix = Client_Search(Req->prefix);
430 if (! prefix) { /* Oops, unknown prefix!? */
431 Log(LOG_WARNING, "Got status code %s from unknown source: \"%s\"", Req->command, Req->prefix);
432 return true;
435 /* Forward status code */
436 strlcpy(str, Req->command, sizeof(str));
437 for (i = 0; i < Req->argc; i++) {
438 if (i < Req->argc - 1)
439 strlcat(str, " ", sizeof(str));
440 else
441 strlcat(str, " :", sizeof(str));
442 strlcat(str, Req->argv[i], sizeof(str));
444 return IRC_WriteStrClientPrefix(target, prefix, "%s", str);
448 static bool
449 Handle_Request( CONN_ID Idx, REQUEST *Req )
451 /* Client-Request verarbeiten. Bei einem schwerwiegenden Fehler
452 * wird die Verbindung geschlossen und false geliefert. */
453 CLIENT *client;
454 bool result = true;
455 int client_type;
456 COMMAND *cmd;
458 assert( Idx >= 0 );
459 assert( Req != NULL );
460 assert( Req->command != NULL );
462 client = Conn_GetClient( Idx );
463 assert( client != NULL );
465 /* Numeric? */
466 client_type = Client_Type(client);
467 if ((client_type == CLIENT_SERVER ||
468 client_type == CLIENT_UNKNOWNSERVER)
469 && strlen(Req->command) == 3 && atoi(Req->command) > 1)
470 return Handle_Numeric(client, Req);
472 cmd = My_Commands;
473 while (cmd->name) {
474 /* Befehl suchen */
475 if (strcasecmp(Req->command, cmd->name) != 0) {
476 cmd++;
477 continue;
480 if (!(client_type & cmd->type))
481 return IRC_WriteStrClient(client, ERR_NOTREGISTERED_MSG, Client_ID(client));
483 /* Command is allowed for this client: call it and count produced bytes */
484 Conn_ResetWCounter();
485 result = (cmd->function)(client, Req);
486 cmd->bytes += Conn_WCounter();
488 /* Adjust counters */
489 if (client_type != CLIENT_SERVER)
490 cmd->lcount++;
491 else
492 cmd->rcount++;
493 return result;
496 if (client_type != CLIENT_USER &&
497 client_type != CLIENT_SERVER &&
498 client_type != CLIENT_SERVICE )
499 return true;
501 /* Unknown command and registered connection: generate error: */
502 LogDebug("Connection %d: Unknown command \"%s\", %d %s,%s prefix.",
503 Client_Conn( client ), Req->command, Req->argc,
504 Req->argc == 1 ? "parameter" : "parameters",
505 Req->prefix ? "" : " no" );
507 if (Client_Type(client) != CLIENT_SERVER) {
508 result = IRC_WriteStrClient(client, ERR_UNKNOWNCOMMAND_MSG,
509 Client_ID(client), Req->command);
510 Conn_SetPenalty(Idx, 1);
512 return result;
513 } /* Handle_Request */
516 /* -eof- */