PRIVMSG/NOTICE: don't stop list processing on invalid target
[ngircd-alex.git] / src / ngircd / irc.c
1 /*
2  * ngIRCd -- The Next Generation IRC Daemon
3  * Copyright (c)2001-2012 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 commands
17  */
18
19 #include "imp.h"
20 #include <assert.h>
21 #include <stdio.h>
22 #include <string.h>
23
24 #include "ngircd.h"
25 #include "conn-func.h"
26 #include "conf.h"
27 #include "channel.h"
28 #include "defines.h"
29 #include "irc-write.h"
30 #include "log.h"
31 #include "match.h"
32 #include "messages.h"
33 #include "parse.h"
34 #include "tool.h"
35
36 #include "exp.h"
37 #include "irc.h"
38
39
40 static char *Option_String PARAMS((CONN_ID Idx));
41 static bool Send_Message PARAMS((CLIENT *Client, REQUEST *Req, int ForceType,
42                                  bool SendErrors));
43 static bool Send_Message_Mask PARAMS((CLIENT *from, char *command,
44                                       char *targetMask, char *message,
45                                       bool SendErrors));
46
47
48 /**
49  * Check if a list limit is reached and inform client accordingly.
50  *
51  * @param From The client.
52  * @param Count Reply item count.
53  * @param Limit Reply limit.
54  * @param Name Name of the list.
55  * @return true if list limit has been reached; false otherwise.
56  */
57 GLOBAL bool
58 IRC_CheckListTooBig(CLIENT *From, const int Count, const int Limit,
59                     const char *Name)
60 {
61         assert(From != NULL);
62         assert(Count >= 0);
63         assert(Limit > 0);
64         assert(Name != NULL);
65
66         if (Count < Limit)
67                 return false;
68
69         (void)IRC_WriteStrClient(From,
70                                  "NOTICE %s :%s list limit (%d) reached!",
71                                  Client_ID(From), Name, Limit);
72         IRC_SetPenalty(From, 2);
73         return true;
74 }
75
76
77 GLOBAL bool
78 IRC_ERROR( CLIENT *Client, REQUEST *Req )
79 {
80         assert( Client != NULL );
81         assert( Req != NULL );
82
83         if (Req->argc < 1)
84                 Log(LOG_NOTICE, "Got ERROR from \"%s\"!",
85                     Client_Mask(Client));
86         else
87                 Log(LOG_NOTICE, "Got ERROR from \"%s\": \"%s\"!",
88                     Client_Mask(Client), Req->argv[0]);
89
90         return CONNECTED;
91 } /* IRC_ERROR */
92
93
94 /**
95  * Handler for the IRC "KILL" command.
96  *
97  * This function implements the IRC command "KILL" wich is used to selectively
98  * disconnect clients. It can be used by IRC operators and servers, for example
99  * to "solve" nick collisions after netsplits. See RFC 2812 section 3.7.1.
100  *
101  * Please note that this function is also called internally, without a real
102  * KILL command being received over the network! Client is Client_ThisServer()
103  * in this case, and the prefix in Req is NULL.
104  *
105  * @param Client        The client from which this command has been received
106  *                      or Client_ThisServer() when generated interanlly.
107  * @param Req           Request structure with prefix and all parameters.
108  * @returns             CONNECTED or DISCONNECTED.
109  */
110 GLOBAL bool
111 IRC_KILL( CLIENT *Client, REQUEST *Req )
112 {
113         CLIENT *prefix, *c;
114         char reason[COMMAND_LEN], *msg;
115         CONN_ID my_conn, conn;
116
117         assert (Client != NULL);
118         assert (Req != NULL);
119
120         if (Client_Type(Client) != CLIENT_SERVER && !Client_OperByMe(Client))
121                 return IRC_WriteStrClient(Client, ERR_NOPRIVILEGES_MSG,
122                                           Client_ID(Client));
123
124         if (Req->argc != 2)
125                 return IRC_WriteStrClient(Client, ERR_NEEDMOREPARAMS_MSG,
126                                           Client_ID(Client), Req->command);
127
128         /* Get prefix (origin); use the client if no prefix is given. */
129         if (Req->prefix)
130                 prefix = Client_Search(Req->prefix);
131         else
132                 prefix = Client;
133
134         /* Log a warning message and use this server as origin when the
135          * prefix (origin) is invalid. */
136         if (!prefix) {
137                 Log(LOG_WARNING, "Got KILL with invalid prefix: \"%s\"!",
138                     Req->prefix );
139                 prefix = Client_ThisServer();
140         }
141
142         if (Client != Client_ThisServer())
143                 Log(LOG_NOTICE|LOG_snotice,
144                     "Got KILL command from \"%s\" for \"%s\": %s",
145                     Client_Mask(prefix), Req->argv[0], Req->argv[1]);
146
147         /* Build reason string: Prefix the "reason" if the originator is a
148          * regular user, so users can't spoof KILLs of servers. */
149         if (Client_Type(Client) == CLIENT_USER)
150                 snprintf(reason, sizeof(reason), "KILLed by %s: %s",
151                          Client_ID(Client), Req->argv[1]);
152         else
153                 strlcpy(reason, Req->argv[1], sizeof(reason));
154
155         /* Inform other servers */
156         IRC_WriteStrServersPrefix(Client, prefix, "KILL %s :%s",
157                                   Req->argv[0], reason);
158
159         /* Save ID of this connection */
160         my_conn = Client_Conn( Client );
161
162         /* Do we host such a client? */
163         c = Client_Search( Req->argv[0] );
164         if( c )
165         {
166                 if(( Client_Type( c ) != CLIENT_USER ) &&
167                    ( Client_Type( c ) != CLIENT_GOTNICK ))
168                 {
169                         /* Target of this KILL is not a regular user, this is
170                          * invalid! So we ignore this case if we received a
171                          * regular KILL from the network and try to kill the
172                          * client/connection anyway (but log an error!) if the
173                          * origin is the local server. */
174
175                         if( Client != Client_ThisServer( ))
176                         {
177                                 /* Invalid KILL received from remote */
178                                 if( Client_Type( c ) == CLIENT_SERVER )
179                                         msg = ERR_CANTKILLSERVER_MSG;
180                                 else
181                                         msg = ERR_NOPRIVILEGES_MSG;
182                                 return IRC_WriteStrClient( Client, msg,
183                                         Client_ID( Client ));
184                         }
185
186                         Log( LOG_ERR, "Got KILL for invalid client type: %d, \"%s\"!",
187                              Client_Type( c ), Req->argv[0] );
188                 }
189
190                 /* Kill the client NOW:
191                  *  - Close the local connection (if there is one),
192                  *  - Destroy the CLIENT structure for remote clients.
193                  * Note: Conn_Close() removes the CLIENT structure as well. */
194                 conn = Client_Conn( c );
195                 if(conn > NONE)
196                         Conn_Close(conn, NULL, reason, true);
197                 else
198                         Client_Destroy(c, NULL, reason, false);
199         }
200         else
201                 Log( LOG_NOTICE, "Client with nick \"%s\" is unknown here.", Req->argv[0] );
202
203         /* Are we still connected or were we killed, too? */
204         if(( my_conn > NONE ) && ( Conn_GetClient( my_conn )))
205                 return CONNECTED;
206         else
207                 return DISCONNECTED;
208 } /* IRC_KILL */
209
210
211 /**
212  * Handler for the IRC command NOTICE.
213  */
214 GLOBAL bool
215 IRC_NOTICE(CLIENT *Client, REQUEST *Req)
216 {
217         return Send_Message(Client, Req, CLIENT_USER, false);
218 } /* IRC_NOTICE */
219
220
221 /**
222  * Handler for the IRC command PRIVMSG.
223  */
224 GLOBAL bool
225 IRC_PRIVMSG(CLIENT *Client, REQUEST *Req)
226 {
227         return Send_Message(Client, Req, CLIENT_USER, true);
228 } /* IRC_PRIVMSG */
229
230
231 /**
232  * Handler for the IRC command SQUERY.
233  */
234 GLOBAL bool
235 IRC_SQUERY(CLIENT *Client, REQUEST *Req)
236 {
237         return Send_Message(Client, Req, CLIENT_SERVICE, true);
238 } /* IRC_SQUERY */
239
240
241 GLOBAL bool
242 IRC_TRACE( CLIENT *Client, REQUEST *Req )
243 {
244         CLIENT *from, *target, *c;
245         CONN_ID idx, idx2;
246         char user[CLIENT_USER_LEN];
247
248         assert( Client != NULL );
249         assert( Req != NULL );
250
251         /* Bad number of arguments? */
252         if( Req->argc > 1 ) return IRC_WriteStrClient( Client, ERR_NORECIPIENT_MSG, Client_ID( Client ), Req->command );
253
254         /* Search sender */
255         if( Client_Type( Client ) == CLIENT_SERVER ) from = Client_Search( Req->prefix );
256         else from = Client;
257         if( ! from ) return IRC_WriteStrClient( Client, ERR_NOSUCHNICK_MSG, Client_ID( Client ), Req->prefix );
258
259         /* Search target */
260         if( Req->argc == 1 ) target = Client_Search( Req->argv[0] );
261         else target = Client_ThisServer( );
262         
263         /* Forward command to other server? */
264         if( target != Client_ThisServer( ))
265         {
266                 if(( ! target ) || ( Client_Type( target ) != CLIENT_SERVER )) return IRC_WriteStrClient( from, ERR_NOSUCHSERVER_MSG, Client_ID( from ), Req->argv[0] );
267
268                 /* Send RPL_TRACELINK back to initiator */
269                 idx = Client_Conn( Client ); assert( idx > NONE );
270                 idx2 = Client_Conn( Client_NextHop( target )); assert( idx2 > NONE );
271                 if( ! IRC_WriteStrClient( from, RPL_TRACELINK_MSG, Client_ID( from ), PACKAGE_NAME, PACKAGE_VERSION, Client_ID( target ), Client_ID( Client_NextHop( target )), Option_String( idx2 ), time( NULL ) - Conn_StartTime( idx2 ), Conn_SendQ( idx ), Conn_SendQ( idx2 ))) return DISCONNECTED;
272
273                 /* Forward command */
274                 IRC_WriteStrClientPrefix( target, from, "TRACE %s", Req->argv[0] );
275                 return CONNECTED;
276         }
277
278         /* Infos about all connected servers */
279         c = Client_First( );
280         while( c )
281         {
282                 if( Client_Conn( c ) > NONE )
283                 {
284                         /* Local client */
285                         if( Client_Type( c ) == CLIENT_SERVER )
286                         {
287                                 /* Server link */
288                                 strlcpy( user, Client_User( c ), sizeof( user ));
289                                 if( user[0] == '~' ) strlcpy( user, "unknown", sizeof( user ));
290                                 if( ! IRC_WriteStrClient( from, RPL_TRACESERVER_MSG, Client_ID( from ), Client_ID( c ), user, Client_Hostname( c ), Client_Mask( Client_ThisServer( )), Option_String( Client_Conn( c )))) return DISCONNECTED;
291                         }
292                         if(( Client_Type( c ) == CLIENT_USER ) && ( strchr( Client_Modes( c ), 'o' )))
293                         {
294                                 /* IRC Operator */
295                                 if( ! IRC_WriteStrClient( from, RPL_TRACEOPERATOR_MSG, Client_ID( from ), Client_ID( c ))) return DISCONNECTED;
296                         }
297                 }
298                 c = Client_Next( c );
299         }
300
301         IRC_SetPenalty( Client, 3 );
302         return IRC_WriteStrClient( from, RPL_TRACEEND_MSG, Client_ID( from ), Conf_ServerName, PACKAGE_NAME, PACKAGE_VERSION, NGIRCd_DebugLevel );
303 } /* IRC_TRACE */
304
305
306 GLOBAL bool
307 IRC_HELP( CLIENT *Client, REQUEST *Req )
308 {
309         COMMAND *cmd;
310
311         assert( Client != NULL );
312         assert( Req != NULL );
313
314         /* Bad number of arguments? */
315         if( Req->argc > 0 ) return IRC_WriteStrClient( Client, ERR_NORECIPIENT_MSG, Client_ID( Client ), Req->command );
316
317         cmd = Parse_GetCommandStruct( );
318         while( cmd->name )
319         {
320                 if( ! IRC_WriteStrClient( Client, "NOTICE %s :%s", Client_ID( Client ), cmd->name )) return DISCONNECTED;
321                 cmd++;
322         }
323         
324         IRC_SetPenalty( Client, 2 );
325         return CONNECTED;
326 } /* IRC_HELP */
327
328
329 static char *
330 Option_String( CONN_ID Idx )
331 {
332         static char option_txt[8];
333         UINT16 options;
334
335         options = Conn_Options(Idx);
336
337         strcpy(option_txt, "F");        /* No idea what this means, but the
338                                          * original ircd sends it ... */
339 #ifdef ZLIB
340         if(options & CONN_ZIP)          /* zlib compression supported. */
341                 strcat(option_txt, "z");
342 #endif
343
344         return option_txt;
345 } /* Option_String */
346
347
348 static bool
349 Send_Message(CLIENT * Client, REQUEST * Req, int ForceType, bool SendErrors)
350 {
351         CLIENT *cl, *from;
352         CL2CHAN *cl2chan;
353         CHANNEL *chan;
354         char *currentTarget = Req->argv[0];
355         char *lastCurrentTarget = NULL;
356
357         assert(Client != NULL);
358         assert(Req != NULL);
359
360         if (Req->argc == 0) {
361                 if (!SendErrors)
362                         return CONNECTED;
363                 return IRC_WriteStrClient(Client, ERR_NORECIPIENT_MSG,
364                                           Client_ID(Client), Req->command);
365         }
366         if (Req->argc == 1) {
367                 if (!SendErrors)
368                         return CONNECTED;
369                 return IRC_WriteStrClient(Client, ERR_NOTEXTTOSEND_MSG,
370                                           Client_ID(Client));
371         }
372         if (Req->argc > 2) {
373                 if (!SendErrors)
374                         return CONNECTED;
375                 return IRC_WriteStrClient(Client, ERR_NEEDMOREPARAMS_MSG,
376                                           Client_ID(Client), Req->command);
377         }
378
379         if (Client_Type(Client) == CLIENT_SERVER)
380                 from = Client_Search(Req->prefix);
381         else
382                 from = Client;
383         if (!from)
384                 return IRC_WriteStrClient(Client, ERR_NOSUCHNICK_MSG,
385                                           Client_ID(Client), Req->prefix);
386
387         /* handle msgtarget = msgto *("," msgto) */
388         currentTarget = strtok_r(currentTarget, ",", &lastCurrentTarget);
389         ngt_UpperStr(Req->command);
390
391         while (currentTarget) {
392                 /* Check for and handle valid <msgto> of form:
393                  * RFC 2812 2.3.1:
394                  *   msgto =  channel / ( user [ "%" host ] "@" servername )
395                  *   msgto =/ ( user "%" host ) / targetmask
396                  *   msgto =/ nickname / ( nickname "!" user "@" host )
397                  */
398                 if (strchr(currentTarget, '!') == NULL)
399                         /* nickname */
400                         cl = Client_Search(currentTarget);
401                 else
402                         cl = NULL;
403
404                 if (cl == NULL) {
405                         /* If currentTarget isn't a nickname check for:
406                          * user ["%" host] "@" servername
407                          * user "%" host
408                          * nickname "!" user "@" host
409                          */
410                         char target[COMMAND_LEN];
411                         char * nick = NULL;
412                         char * user = NULL;
413                         char * host = NULL;
414                         char * server = NULL;
415
416                         strlcpy(target, currentTarget, COMMAND_LEN);
417                         server = strchr(target, '@');
418                         if (server) {
419                                 *server = '\0';
420                                 server++;
421                         }
422                         host = strchr(target, '%');
423                         if (host) {
424                                 *host = '\0';
425                                 host++;
426                         }
427                         user = strchr(target, '!');
428                         if (user) {
429                                 /* msgto form: nick!user@host */
430                                 *user = '\0';
431                                 user++;
432                                 nick = target;
433                                 host = server; /* not "@server" but "@host" */
434                         } else {
435                                 user = target;
436                         }
437
438                         for (cl = Client_First(); cl != NULL; cl = Client_Next(cl)) {
439                                 if (Client_Type(cl) != CLIENT_USER &&
440                                     Client_Type(cl) != CLIENT_SERVICE)
441                                         continue;
442                                 if (nick != NULL && host != NULL) {
443                                         if (strcmp(nick, Client_ID(cl)) == 0 &&
444                                             strcmp(user, Client_User(cl)) == 0 &&
445                                             strcasecmp(host, Client_HostnameCloaked(cl)) == 0)
446                                                 break;
447                                         else
448                                                 continue;
449                                 }
450                                 if (strcasecmp(user, Client_User(cl)) != 0)
451                                         continue;
452                                 if (host != NULL && strcasecmp(host,
453                                                 Client_HostnameCloaked(cl)) != 0)
454                                         continue;
455                                 if (server != NULL && strcasecmp(server,
456                                                 Client_ID(Client_Introducer(cl))) != 0)
457                                         continue;
458                                 break;
459                         }
460                 }
461
462                 if (cl) {
463                         /* Target is a user, enforce type */
464 #ifndef STRICT_RFC
465                         if (Client_Type(cl) != ForceType &&
466                             !(ForceType == CLIENT_USER &&
467                               (Client_Type(cl) == CLIENT_USER ||
468                                Client_Type(cl) == CLIENT_SERVICE))) {
469 #else
470                         if (Client_Type(cl) != ForceType) {
471 #endif
472                                 if (SendErrors && !IRC_WriteStrClient(
473                                     from, ERR_NOSUCHNICK_MSG,Client_ID(from),
474                                     currentTarget))
475                                         return DISCONNECTED;
476                                 goto send_next_target;
477                         }
478
479 #ifndef STRICT_RFC
480                         if (ForceType == CLIENT_SERVICE &&
481                             (Conn_Options(Client_Conn(Client_NextHop(cl)))
482                              & CONN_RFC1459)) {
483                                 /* SQUERY command but RFC 1459 link: convert
484                                  * request to PRIVMSG command */
485                                 Req->command = "PRIVMSG";
486                         }
487 #endif
488
489                         if (Client_HasMode(cl, 'C')) {
490                                 cl2chan = Channel_FirstChannelOf(cl);
491                                 while (cl2chan) {
492                                         chan = Channel_GetChannel(cl2chan);
493                                         if (Channel_IsMemberOf(chan, from))
494                                                 break;
495                                         cl2chan = Channel_NextChannelOf(cl, cl2chan);
496                                 }
497                                 if (!cl2chan) {
498                                         if (SendErrors && !IRC_WriteStrClient(
499                                             from, ERR_NOTONSAMECHANNEL_MSG,
500                                             Client_ID(from), Client_ID(cl)))
501                                                 return DISCONNECTED;
502                                         goto send_next_target;
503                                 }
504                         }
505
506                         if (SendErrors && (Client_Type(Client) != CLIENT_SERVER)
507                             && strchr(Client_Modes(cl), 'a')) {
508                                 /* Target is away */
509                                 if (!IRC_WriteStrClient(from, RPL_AWAY_MSG,
510                                                         Client_ID(from),
511                                                         Client_ID(cl),
512                                                         Client_Away(cl)))
513                                         return DISCONNECTED;
514                         }
515                         if (Client_Conn(from) > NONE) {
516                                 Conn_UpdateIdle(Client_Conn(from));
517                         }
518                         if (!IRC_WriteStrClientPrefix(cl, from, "%s %s :%s",
519                                                       Req->command, Client_ID(cl),
520                                                       Req->argv[1]))
521                                 return DISCONNECTED;
522                 } else if (ForceType != CLIENT_SERVICE
523                            && (chan = Channel_Search(currentTarget))) {
524                         if (!Channel_Write(chan, from, Client, Req->command,
525                                            SendErrors, Req->argv[1]))
526                                         return DISCONNECTED;
527                 } else if (ForceType != CLIENT_SERVICE
528                         /* $#: server/target mask, RFC 2812, sec. 3.3.1 */
529                            && strchr("$#", currentTarget[0])
530                            && strchr(currentTarget, '.')) {
531                         /* targetmask */
532                         if (!Send_Message_Mask(from, Req->command, currentTarget,
533                                                Req->argv[1], SendErrors))
534                                 return DISCONNECTED;
535                 } else {
536                         if (!SendErrors)
537                                 return CONNECTED;
538                         if (!IRC_WriteStrClient(from, ERR_NOSUCHNICK_MSG,
539                                                 Client_ID(from), currentTarget))
540                                 return DISCONNECTED;
541                 }
542
543         send_next_target:
544                 currentTarget = strtok_r(NULL, ",", &lastCurrentTarget);
545                 if (currentTarget)
546                         Conn_SetPenalty(Client_Conn(Client), 1);
547         }
548
549         return CONNECTED;
550 } /* Send_Message */
551
552
553 static bool
554 Send_Message_Mask(CLIENT * from, char * command, char * targetMask,
555                   char * message, bool SendErrors)
556 {
557         CLIENT *cl;
558         bool client_match;
559         char *mask = targetMask + 1;
560         const char *check_wildcards;
561
562         cl = NULL;
563
564         if (strchr(Client_Modes(from), 'o') == NULL) {
565                 if (!SendErrors)
566                         return true;
567                 return IRC_WriteStrClient(from, ERR_NOPRIVILEGES_MSG,
568                                           Client_ID(from));
569         }
570
571         /*
572          * RFC 2812, sec. 3.3.1 requires that targetMask have at least one
573          * dot (".") and no wildcards ("*", "?") following the last one.
574          */
575         check_wildcards = strrchr(targetMask, '.');
576         assert(check_wildcards != NULL);
577         if (check_wildcards &&
578                 check_wildcards[strcspn(check_wildcards, "*?")])
579         {
580                 if (!SendErrors)
581                         return true;
582                 return IRC_WriteStrClient(from, ERR_WILDTOPLEVEL, targetMask);
583         }
584
585         /* #: hostmask, see RFC 2812, sec. 3.3.1 */
586         if (targetMask[0] == '#') {
587                 for (cl = Client_First(); cl != NULL; cl = Client_Next(cl)) {
588                         if (Client_Type(cl) != CLIENT_USER)
589                                 continue;
590                         client_match = MatchCaseInsensitive(mask, Client_Hostname(cl));
591                         if (client_match)
592                                 if (!IRC_WriteStrClientPrefix(cl, from, "%s %s :%s",
593                                                 command, Client_ID(cl), message))
594                                         return false;
595                 }
596         } else {
597                 assert(targetMask[0] == '$'); /* $: server mask, see RFC 2812, sec. 3.3.1 */
598                 for (cl = Client_First(); cl != NULL; cl = Client_Next(cl)) {
599                         if (Client_Type(cl) != CLIENT_USER)
600                                 continue;
601                         client_match = MatchCaseInsensitive(mask,
602                                         Client_ID(Client_Introducer(cl)));
603                         if (client_match)
604                                 if (!IRC_WriteStrClientPrefix(cl, from, "%s %s :%s",
605                                                 command, Client_ID(cl), message))
606                                         return false;
607                 }
608         }
609         return CONNECTED;
610 } /* Send_Message_Mask */
611
612
613 /* -eof- */