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