]> arthur.barton.de Git - ngircd-alex.git/blob - src/ngircd/parse.c
2c28a309a0bebf39076b06450a98ac0d5fdc1265
[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|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, 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_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         { "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         /* remove leading & trailing whitespace */
173         ngt_TrimStr( Request );
174
175         if( Request[0] == ':' )
176         {
177                 /* Prefix */
178                 req.prefix = Request + 1;
179                 ptr = strchr( Request, ' ' );
180                 if( ! ptr )
181                 {
182                         LogDebug("Connection %d: Parse error: prefix without command!?", Idx);
183                         return Conn_WriteStr( Idx, "ERROR :Prefix without command!?" );
184                 }
185                 *ptr = '\0';
186 #ifndef STRICT_RFC
187                 /* ignore multiple spaces between prefix and command */
188                 while( *(ptr + 1) == ' ' ) ptr++;
189 #endif
190                 start = ptr + 1;
191         }
192         else start = Request;
193
194         ptr = strchr( start, ' ' );
195         if( ptr )
196         {
197                 *ptr = '\0';
198 #ifndef STRICT_RFC
199                 /* ignore multiple spaces between parameters */
200                 while( *(ptr + 1) == ' ' ) ptr++;
201 #endif
202         }
203         req.command = start;
204
205         /* Arguments, Parameters */
206         if( ptr )
207         {
208                 start = ptr + 1;
209                 while( start )
210                 {
211                         if( start[0] == ':' )
212                         {
213                                 req.argv[req.argc] = start + 1;
214                                 ptr = NULL;
215                         }
216                         else
217                         {
218                                 req.argv[req.argc] = start;
219                                 ptr = strchr( start, ' ' );
220                                 if( ptr )
221                                 {
222                                         *ptr = '\0';
223 #ifndef STRICT_RFC
224                                         while( *(ptr + 1) == ' ' ) ptr++;
225 #endif
226                                 }
227                         }
228
229                         req.argc++;
230
231                         if( start[0] == ':' ) break;
232                         if( req.argc > 14 ) break;
233
234                         if( ptr ) start = ptr + 1;
235                         else start = NULL;
236                 }
237         }
238
239         if( ! Validate_Prefix( Idx, &req, &closed )) return ! closed;
240         if( ! Validate_Command( Idx, &req, &closed )) return ! closed;
241         if( ! Validate_Args( Idx, &req, &closed )) return ! closed;
242
243         return Handle_Request( Idx, &req );
244 } /* Parse_Request */
245
246
247 /**
248  * Initialize request structure.
249  * @param Req Request structure to be initialized.
250  */
251 static void
252 Init_Request( REQUEST *Req )
253 {
254         /* Neue Request-Struktur initialisieren */
255
256         int i;
257
258         assert( Req != NULL );
259
260         Req->prefix = NULL;
261         Req->command = NULL;
262         for( i = 0; i < 15; Req->argv[i++] = NULL );
263         Req->argc = 0;
264 } /* Init_Request */
265
266
267 static bool
268 Validate_Prefix( CONN_ID Idx, REQUEST *Req, bool *Closed )
269 {
270         CLIENT *client, *c;
271
272         assert( Idx >= 0 );
273         assert( Req != NULL );
274
275         *Closed = false;
276
277         if( ! Req->prefix ) return true;
278
279         client = Conn_GetClient( Idx );
280         assert( client != NULL );
281
282         /* only validate if this connection is already registered */
283         if(( Client_Type( client ) != CLIENT_USER ) && ( Client_Type( client ) != CLIENT_SERVER ) && ( Client_Type( client ) != CLIENT_SERVICE ))
284         {
285                 /* not registered, ignore prefix */
286                 Req->prefix = NULL;
287                 return true;
288         }
289
290         /* check if client in prefix is known */
291         c = Client_Search( Req->prefix );
292         if( ! c )
293         {
294                 Log( LOG_ERR, "Invalid prefix \"%s\", client not known (connection %d, command %s)!?", Req->prefix, Idx, Req->command );
295                 if( ! Conn_WriteStr( Idx, "ERROR :Invalid prefix \"%s\", client not known!?", Req->prefix )) *Closed = true;
296                 return false;
297         }
298
299         /* check if the client named in the prefix is expected
300          * to come from that direction */
301         if( Client_NextHop( c ) != client )
302         {
303                 Log( LOG_ERR, "Spoofed prefix \"%s\" from \"%s\" (connection %d, command %s)!", Req->prefix, Client_Mask( Conn_GetClient( Idx )), Idx, Req->command );
304                 Conn_Close( Idx, NULL, "Spoofed prefix", true);
305                 *Closed = true;
306                 return false;
307         }
308
309         return true;
310 } /* Validate_Prefix */
311
312
313 static bool
314 Validate_Command( UNUSED CONN_ID Idx, UNUSED REQUEST *Req, bool *Closed )
315 {
316         assert( Idx >= 0 );
317         assert( Req != NULL );
318         *Closed = false;
319
320         return true;
321 } /* Validate_Comman */
322
323
324 static bool
325 #ifdef STRICT_RFC
326 Validate_Args(CONN_ID Idx, REQUEST *Req, bool *Closed)
327 #else
328 Validate_Args(UNUSED CONN_ID Idx, UNUSED REQUEST *Req, bool *Closed)
329 #endif
330 {
331 #ifdef STRICT_RFC
332         int i;
333 #endif
334
335         *Closed = false;
336
337 #ifdef STRICT_RFC
338         assert( Idx >= 0 );
339         assert( Req != NULL );
340
341         /* CR and LF are never allowed in command parameters.
342          * But since we do accept lines terminated only with CR or LF in
343          * "non-RFC-compliant mode" (besides the correct CR+LF combination),
344          * this check can only trigger in "strict RFC" mode; therefore we
345          * optimize it away otherwise ... */
346         for (i = 0; i < Req->argc; i++) {
347                 if (strchr(Req->argv[i], '\r') || strchr(Req->argv[i], '\n')) {
348                         Log(LOG_ERR,
349                             "Invalid character(s) in parameter (connection %d, command %s)!?",
350                             Idx, Req->command);
351                         if (!Conn_WriteStr(Idx,
352                                            "ERROR :Invalid character(s) in parameter!"))
353                                 *Closed = true;
354                         return false;
355                 }
356         }
357 #endif
358
359         return true;
360 } /* Validate_Args */
361
362
363 /* Command is a status code ("numeric") from another server */
364 static bool
365 Handle_Numeric(CLIENT *client, REQUEST *Req)
366 {
367         static const struct _NUMERIC Numerics[] = {
368                 {   5, IRC_Num_ISUPPORT },
369                 {  20, NULL },
370                 { 376, IRC_Num_ENDOFMOTD }
371         };
372         int i, num;
373         char str[LINE_LEN];
374         CLIENT *prefix, *target = NULL;
375
376         /* Determine target */
377         if (Req->argc > 0) {
378                 if (strcmp(Req->argv[0], "*") != 0)
379                         target = Client_Search(Req->argv[0]);
380                 else
381                         target = Client_ThisServer();
382         }
383
384         if (!target) {
385                 /* Status code without target!? */
386                 if (Req->argc > 0)
387                         Log(LOG_WARNING,
388                             "Unknown target for status code %s: \"%s\"",
389                             Req->command, Req->argv[0]);
390                 else
391                         Log(LOG_WARNING,
392                             "Unknown target for status code %s!",
393                             Req->command);
394                 return true;
395         }
396         if (target == Client_ThisServer()) {
397                 /* This server is the target of the numeric */
398                 num = atoi(Req->command);
399
400                 for (i = 0; i < (int) ARRAY_SIZE(Numerics); i++) {
401                         if (num == Numerics[i].numeric) {
402                                 if (!Numerics[i].function)
403                                         return CONNECTED;
404                                 return Numerics[i].function(client, Req);
405                         }
406                 }
407
408                 LogDebug("Ignored status code %s from \"%s\".",
409                          Req->command, Client_ID(client));
410                 return true;
411         }
412
413         /* Determine source */
414         if (! Req->prefix[0]) {
415                 /* Oops, no prefix!? */
416                 Log(LOG_WARNING, "Got status code %s from \"%s\" without prefix!?",
417                                                 Req->command, Client_ID(client));
418                 return true;
419         }
420
421         prefix = Client_Search(Req->prefix);
422         if (! prefix) { /* Oops, unknown prefix!? */
423                 Log(LOG_WARNING, "Got status code %s from unknown source: \"%s\"", Req->command, Req->prefix);
424                 return true;
425         }
426
427         /* Forward status code */
428         strlcpy(str, Req->command, sizeof(str));
429         for (i = 0; i < Req->argc; i++) {
430                 if (i < Req->argc - 1)
431                         strlcat(str, " ", sizeof(str));
432                 else
433                         strlcat(str, " :", sizeof(str));
434                 strlcat(str, Req->argv[i], sizeof(str));
435         }
436         return IRC_WriteStrClientPrefix(target, prefix, "%s", str);
437 }
438
439
440 static bool
441 Handle_Request( CONN_ID Idx, REQUEST *Req )
442 {
443         CLIENT *client;
444         bool result = true;
445         int client_type;
446         COMMAND *cmd;
447
448         assert( Idx >= 0 );
449         assert( Req != NULL );
450         assert( Req->command != NULL );
451
452         client = Conn_GetClient( Idx );
453         assert( client != NULL );
454
455         /* Numeric? */
456         client_type = Client_Type(client);
457         if ((client_type == CLIENT_SERVER ||
458              client_type == CLIENT_UNKNOWNSERVER)
459             && strlen(Req->command) == 3 && atoi(Req->command) > 1)
460                 return Handle_Numeric(client, Req);
461
462         cmd = My_Commands;
463         while (cmd->name) {
464                 if (strcasecmp(Req->command, cmd->name) != 0) {
465                         cmd++;
466                         continue;
467                 }
468
469                 if (!(client_type & cmd->type))
470                         return IRC_WriteStrClient(client, ERR_NOTREGISTERED_MSG, Client_ID(client));
471
472                 /* Command is allowed for this client: call it and count produced bytes */
473                 Conn_ResetWCounter();
474                 result = (cmd->function)(client, Req);
475                 cmd->bytes += Conn_WCounter();
476
477                 /* Adjust counters */
478                 if (client_type != CLIENT_SERVER)
479                         cmd->lcount++;
480                 else
481                         cmd->rcount++;
482                 return result;
483         }
484
485         if (client_type != CLIENT_USER &&
486             client_type != CLIENT_SERVER &&
487             client_type != CLIENT_SERVICE )
488                 return true;
489
490         /* Unknown command and registered connection: generate error: */
491         LogDebug("Connection %d: Unknown command \"%s\", %d %s,%s prefix.",
492                         Client_Conn( client ), Req->command, Req->argc,
493                         Req->argc == 1 ? "parameter" : "parameters",
494                         Req->prefix ? "" : " no" );
495
496         if (Client_Type(client) != CLIENT_SERVER) {
497                 result = IRC_WriteStrClient(client, ERR_UNKNOWNCOMMAND_MSG,
498                                 Client_ID(client), Req->command);
499                 Conn_SetPenalty(Idx, 1);
500         }
501         return result;
502 } /* Handle_Request */
503
504
505 /* -eof- */