]> arthur.barton.de Git - ngircd-alex.git/blob - src/ngircd/irc.c
Don't forward KILLs to other servers if they've been blocked locally
[ngircd-alex.git] / src / ngircd / irc.c
1 /*
2  * ngIRCd -- The Next Generation IRC Daemon
3  * Copyright (c)2001-2015 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 <assert.h>
20 #include <stdio.h>
21 #include <string.h>
22 #include <strings.h>
23 #include <time.h>
24
25 #include "ngircd.h"
26 #include "conn-func.h"
27 #include "conf.h"
28 #include "channel.h"
29 #ifdef ICONV
30 # include "conn-encoding.h"
31 #endif
32 #include "irc-macros.h"
33 #include "irc-write.h"
34 #include "log.h"
35 #include "match.h"
36 #include "messages.h"
37 #include "parse.h"
38 #include "op.h"
39
40 #include "irc.h"
41
42 static char *Option_String PARAMS((CONN_ID Idx));
43 static bool Send_Message PARAMS((CLIENT *Client, REQUEST *Req, int ForceType,
44                                  bool SendErrors));
45 static bool Send_Message_Mask PARAMS((CLIENT *from, char *command,
46                                       char *targetMask, char *message,
47                                       bool SendErrors));
48 static bool Help PARAMS((CLIENT *Client, const char *Topic));
49
50 /**
51  * Check if a list limit is reached and inform client accordingly.
52  *
53  * @param From The client.
54  * @param Count Reply item count.
55  * @param Limit Reply limit.
56  * @param Name Name of the list.
57  * @return true if list limit has been reached; false otherwise.
58  */
59 GLOBAL bool
60 IRC_CheckListTooBig(CLIENT *From, const int Count, const int Limit,
61                     const char *Name)
62 {
63         assert(From != NULL);
64         assert(Count >= 0);
65         assert(Limit > 0);
66         assert(Name != NULL);
67
68         if (Count < Limit)
69                 return false;
70
71         (void)IRC_WriteStrClient(From,
72                                  "NOTICE %s :%s list limit (%d) reached!",
73                                  Client_ID(From), Name, Limit);
74         IRC_SetPenalty(From, 2);
75         return true;
76 }
77
78 /**
79  * Handler for the IRC "ERROR" command.
80  *
81  * @param Client The client from which this command has been received.
82  * @param Req Request structure with prefix and all parameters.
83  * @return CONNECTED or DISCONNECTED.
84 */
85 GLOBAL bool
86 IRC_ERROR(CLIENT *Client, REQUEST *Req)
87 {
88         char *msg;
89
90         assert( Client != NULL );
91         assert( Req != NULL );
92
93         if (Client_Type(Client) != CLIENT_GOTPASS
94             && Client_Type(Client) != CLIENT_GOTPASS_2813
95             && Client_Type(Client) != CLIENT_UNKNOWNSERVER
96             && Client_Type(Client) != CLIENT_SERVER
97             && Client_Type(Client) != CLIENT_SERVICE) {
98                 LogDebug("Ignored ERROR command from \"%s\" ...",
99                          Client_Mask(Client));
100                 IRC_SetPenalty(Client, 2);
101                 return CONNECTED;
102         }
103
104         if (Req->argc < 1) {
105                 msg = "Got ERROR command";
106                 Log(LOG_NOTICE, "Got ERROR from \"%s\"!",
107                     Client_Mask(Client));
108         } else {
109                 msg = Req->argv[0];
110                 Log(LOG_NOTICE, "Got ERROR from \"%s\": \"%s\"!",
111                     Client_Mask(Client), msg);
112         }
113
114         if (Client_Conn(Client) != NONE) {
115                 Client_Destroy(Client, NULL, msg, false);
116                 return DISCONNECTED;
117         }
118
119         return CONNECTED;
120 } /* IRC_ERROR */
121
122 /**
123  * Handler for the IRC "KILL" command.
124  *
125  * This function implements the IRC command "KILL" which is used to selectively
126  * disconnect clients. It can be used by IRC operators and servers, for example
127  * to "solve" nick collisions after netsplits. See RFC 2812 section 3.7.1.
128  *
129  * Please note that this function is also called internally, without a real
130  * KILL command being received over the network! Client is Client_ThisServer()
131  * in this case, and the prefix in Req is NULL.
132  *
133  * @param Client The client from which this command has been received or
134  * Client_ThisServer() when generated interanlly.
135  * @param Req Request structure with prefix and all parameters.
136  * @return CONNECTED or DISCONNECTED.
137  */
138 GLOBAL bool
139 IRC_KILL(CLIENT *Client, REQUEST *Req)
140 {
141         CLIENT *prefix;
142         char reason[COMMAND_LEN];
143
144         assert (Client != NULL);
145         assert (Req != NULL);
146
147         if (Client_Type(Client) != CLIENT_SERVER && !Op_Check(Client, Req))
148                 return Op_NoPrivileges(Client, Req);
149
150         /* Get prefix (origin); use the client if no prefix is given. */
151         if (Req->prefix)
152                 prefix = Client_Search(Req->prefix);
153         else
154                 prefix = Client;
155
156         /* Log a warning message and use this server as origin when the
157          * prefix (origin) is invalid. And this is the reason why we don't
158          * use the _IRC_GET_SENDER_OR_RETURN_ macro above! */
159         if (!prefix) {
160                 Log(LOG_WARNING, "Got KILL with invalid prefix: \"%s\"!",
161                     Req->prefix );
162                 prefix = Client_ThisServer();
163         }
164
165         if (Client != Client_ThisServer())
166                 Log(LOG_NOTICE|LOG_snotice,
167                     "Got KILL command from \"%s\" for \"%s\": \"%s\".",
168                     Client_Mask(prefix), Req->argv[0], Req->argv[1]);
169
170         /* Build reason string: Prefix the "reason" if the originator is a
171          * regular user, so users can't spoof KILLs of servers. */
172         if (Client_Type(Client) == CLIENT_USER)
173                 snprintf(reason, sizeof(reason), "KILLed by %s: %s",
174                          Client_ID(Client), Req->argv[1]);
175         else
176                 strlcpy(reason, Req->argv[1], sizeof(reason));
177
178         return IRC_KillClient(Client, prefix, Req->argv[0], reason);
179 }
180
181 /**
182  * Handler for the IRC "NOTICE" command.
183  *
184  * @param Client The client from which this command has been received.
185  * @param Req Request structure with prefix and all parameters.
186  * @return CONNECTED or DISCONNECTED.
187 */
188 GLOBAL bool
189 IRC_NOTICE(CLIENT *Client, REQUEST *Req)
190 {
191         return Send_Message(Client, Req, CLIENT_USER, false);
192 } /* IRC_NOTICE */
193
194 /**
195  * Handler for the IRC "PRIVMSG" command.
196  *
197  * @param Client The client from which this command has been received.
198  * @param Req Request structure with prefix and all parameters.
199  * @return CONNECTED or DISCONNECTED.
200  */
201 GLOBAL bool
202 IRC_PRIVMSG(CLIENT *Client, REQUEST *Req)
203 {
204         return Send_Message(Client, Req, CLIENT_USER, true);
205 } /* IRC_PRIVMSG */
206
207 /**
208  * Handler for the IRC "SQUERY" command.
209  *
210  * @param Client The client from which this command has been received.
211  * @param Req Request structure with prefix and all parameters.
212  * @return CONNECTED or DISCONNECTED.
213  */
214 GLOBAL bool
215 IRC_SQUERY(CLIENT *Client, REQUEST *Req)
216 {
217         return Send_Message(Client, Req, CLIENT_SERVICE, true);
218 } /* IRC_SQUERY */
219
220 /*
221  * Handler for the IRC "TRACE" command.
222  *
223  * @param Client The client from which this command has been received.
224  * @param Req Request structure with prefix and all parameters.
225  * @return CONNECTED or DISCONNECTED.
226  */
227  GLOBAL bool
228 IRC_TRACE(CLIENT *Client, REQUEST *Req)
229 {
230         CLIENT *from, *target, *c;
231         CONN_ID idx, idx2;
232         char user[CLIENT_USER_LEN];
233
234         assert(Client != NULL);
235         assert(Req != NULL);
236
237         _IRC_GET_SENDER_OR_RETURN_(from, Req, Client)
238         _IRC_GET_TARGET_SERVER_OR_RETURN_(target, Req, 0, from)
239
240         /* Forward command to other server? */
241         if (target != Client_ThisServer()) {
242                 /* Send RPL_TRACELINK back to initiator */
243                 idx = Client_Conn(Client);
244                 assert(idx > NONE);
245                 idx2 = Client_Conn(Client_NextHop(target));
246                 assert(idx2 > NONE);
247
248                 if (!IRC_WriteStrClient(from, RPL_TRACELINK_MSG,
249                                         Client_ID(from), PACKAGE_NAME,
250                                         PACKAGE_VERSION, Client_ID(target),
251                                         Client_ID(Client_NextHop(target)),
252                                         Option_String(idx2),
253                                         (long)(time(NULL) - Conn_StartTime(idx2)),
254                                         Conn_SendQ(idx), Conn_SendQ(idx2)))
255                         return DISCONNECTED;
256
257                 /* Forward command */
258                 IRC_WriteStrClientPrefix(target, from, "TRACE %s", Req->argv[0]);
259                 return CONNECTED;
260         }
261
262         /* Infos about all connected servers */
263         c = Client_First();
264         while (c) {
265                 if (Client_Conn(c) > NONE) {
266                         /* Local client */
267                         if (Client_Type(c) == CLIENT_SERVER) {
268                                 /* Server link */
269                                 strlcpy(user, Client_User(c), sizeof(user));
270                                 if (user[0] == '~')
271                                         strlcpy(user, "unknown", sizeof(user));
272                                 if (!IRC_WriteStrClient(from,
273                                                 RPL_TRACESERVER_MSG,
274                                                 Client_ID(from), Client_ID(c),
275                                                 user, Client_Hostname(c),
276                                                 Client_Mask(Client_ThisServer()),
277                                                 Option_String(Client_Conn(c))))
278                                         return DISCONNECTED;
279                         }
280                         if (Client_Type(c) == CLIENT_USER
281                             && Client_HasMode(c, 'o')) {
282                                 /* IRC Operator */
283                                 if (!IRC_WriteStrClient(from,
284                                                 RPL_TRACEOPERATOR_MSG,
285                                                 Client_ID(from), Client_ID(c)))
286                                         return DISCONNECTED;
287                         }
288                 }
289                 c = Client_Next( c );
290         }
291
292         return IRC_WriteStrClient(from, RPL_TRACEEND_MSG, Client_ID(from),
293                                   Conf_ServerName, PACKAGE_NAME,
294                                   PACKAGE_VERSION, NGIRCd_DebugLevel);
295 } /* IRC_TRACE */
296
297 /**
298  * Handler for the IRC "HELP" command.
299  *
300  * @param Client The client from which this command has been received.
301  * @param Req Request structure with prefix and all parameters.
302  * @return CONNECTED or DISCONNECTED.
303  */
304 GLOBAL bool
305 IRC_HELP(CLIENT *Client, REQUEST *Req)
306 {
307         COMMAND *cmd;
308
309         assert(Client != NULL);
310         assert(Req != NULL);
311
312         if ((Req->argc == 0 && array_bytes(&Conf_Helptext) > 0)
313             || (Req->argc >= 1 && strcasecmp(Req->argv[0], "Commands") != 0)) {
314                 /* Help text available and requested */
315                 if (Req->argc >= 1)
316                         return Help(Client, Req->argv[0]);
317
318                 if (!Help(Client, "Intro"))
319                         return DISCONNECTED;
320                 return CONNECTED;
321         }
322
323         cmd = Parse_GetCommandStruct();
324         while(cmd->name) {
325                 if (!IRC_WriteStrClient(Client, "NOTICE %s :%s",
326                                         Client_ID(Client), cmd->name))
327                         return DISCONNECTED;
328                 cmd++;
329         }
330         return CONNECTED;
331 } /* IRC_HELP */
332
333 /**
334  * Kill an client identified by its nick name.
335  *
336  * Please note that after killig a client, its CLIENT cond CONNECTION
337  * structures are invalid. So the caller must make sure on its own not to
338  * access data of probably killed clients after calling this function!
339  *
340  * @param Client The client from which the command leading to the KILL has
341  *              been received, or NULL. The KILL will no be forwarded in this
342  *              direction. Only relevant when From is set, too.
343  * @param From The client from which the command originated, or NULL for
344                 the local server.
345  * @param Nick The nick name to kill.
346  * @param Reason Text to send as reason to the client and other servers.
347  */
348 GLOBAL bool
349 IRC_KillClient(CLIENT *Client, CLIENT *From, const char *Nick, const char *Reason)
350 {
351         const char *msg;
352         CONN_ID my_conn = NONE, conn;
353         CLIENT *c;
354
355         assert(Nick != NULL);
356         assert(Reason != NULL);
357
358         /* Do we know such a client in the network? */
359         c = Client_Search(Nick);
360         if (!c) {
361                 LogDebug("Client with nick \"%s\" is unknown, not forwaring.", Nick);
362                 return CONNECTED;
363         }
364
365         if (Client_Type(c) != CLIENT_USER && Client_Type(c) != CLIENT_GOTNICK) {
366                 /* Target of this KILL is not a regular user, this is
367                  * invalid! So we ignore this case if we received a
368                  * regular KILL from the network and try to kill the
369                  * client/connection anyway (but log an error!) if the
370                  * origin is the local server. */
371
372                 if (Client != Client_ThisServer()) {
373                         /* Invalid KILL received from remote */
374                         if (Client_Type(c) == CLIENT_SERVER)
375                                 msg = ERR_CANTKILLSERVER_MSG;
376                         else
377                                 msg = ERR_NOPRIVILEGES_MSG;
378                         return IRC_WriteErrClient(Client, msg, Client_ID(Client));
379                 }
380
381                 Log(LOG_ERR,
382                     "Got KILL for invalid client type: %d, \"%s\"!",
383                     Client_Type(c), Nick);
384         }
385
386         /* Inform other servers */
387         IRC_WriteStrServersPrefix(From ? Client : NULL,
388                                   From ? From : Client_ThisServer(),
389                                   "KILL %s :%s", Nick, Reason);
390
391
392         /* Save ID of this connection */
393         if (Client)
394                 my_conn = Client_Conn(Client);
395
396         /* Kill the client NOW:
397          *  - Close the local connection (if there is one),
398          *  - Destroy the CLIENT structure for remote clients.
399          * Note: Conn_Close() removes the CLIENT structure as well. */
400         conn = Client_Conn(c);
401         if(conn > NONE)
402                 Conn_Close(conn, NULL, Reason, true);
403         else
404                 Client_Destroy(c, NULL, Reason, false);
405
406         /* Are we still connected or were we killed, too? */
407         if (my_conn > NONE && Conn_GetClient(my_conn))
408                 return CONNECTED;
409         else
410                 return DISCONNECTED;
411 }
412
413 /**
414  * Send help for a given topic to the client.
415  *
416  * @param Client The client requesting help.
417  * @param Topoc The help topic requested.
418  * @return CONNECTED or DISCONNECTED.
419  */
420 static bool
421 Help(CLIENT *Client, const char *Topic)
422 {
423         char *line;
424         size_t helptext_len, len_str, idx_start, lines = 0;
425         bool in_article = false;
426
427         assert(Client != NULL);
428         assert(Topic != NULL);
429
430         helptext_len = array_bytes(&Conf_Helptext);
431         line = array_start(&Conf_Helptext);
432         while (helptext_len > 0) {
433                 len_str = strlen(line) + 1;
434                 assert(helptext_len >= len_str);
435                 helptext_len -= len_str;
436
437                 if (in_article) {
438                         /* The first character in each article text line must
439                          * be a TAB (ASCII 9) character which will be stripped
440                          * in the output. If it is not a TAB, the end of the
441                          * article has been reached. */
442                         if (line[0] != '\t') {
443                                 if (lines > 0)
444                                         return CONNECTED;
445                                 else
446                                         break;
447                         }
448
449                         /* A single '.' character indicates an empty line */
450                         if (line[1] == '.' && line[2] == '\0')
451                                 idx_start = 2;
452                         else
453                                 idx_start = 1;
454
455                         if (!IRC_WriteStrClient(Client, "NOTICE %s :%s",
456                                                 Client_ID(Client),
457                                                 &line[idx_start]))
458                                 return DISCONNECTED;
459                         lines++;
460
461                 } else {
462                         if (line[0] == '-' && line[1] == ' '
463                             && strcasecmp(&line[2], Topic) == 0)
464                                 in_article = true;
465                 }
466
467                 line += len_str;
468         }
469
470         /* Help topic not found (or empty)! */
471         if (!IRC_WriteStrClient(Client, "NOTICE %s :No help for \"%s\" found!",
472                                 Client_ID(Client), Topic))
473                 return DISCONNECTED;
474
475         return CONNECTED;
476 }
477
478 /**
479  * Get pointer to a static string representing the connection "options".
480  *
481  * @param Idx Connection index.
482  * @return Pointer to static (global) string buffer.
483  */
484 static char *
485 #ifdef ZLIB
486 Option_String(CONN_ID Idx)
487 #else
488 Option_String(UNUSED CONN_ID Idx)
489 #endif
490 {
491         static char option_txt[8];
492         UINT16 options;
493
494         assert(Idx != NONE);
495
496         options = Conn_Options(Idx);
497         strcpy(option_txt, "F");        /* No idea what this means, but the
498                                          * original ircd sends it ... */
499 #ifdef SSL_SUPPORT
500         if(options & CONN_SSL)          /* SSL encrypted link */
501                 strlcat(option_txt, "s", sizeof(option_txt));
502 #endif
503 #ifdef ZLIB
504         if(options & CONN_ZIP)          /* zlib compression enabled */
505                 strlcat(option_txt, "z", sizeof(option_txt));
506 #endif
507
508         return option_txt;
509 } /* Option_String */
510
511 /**
512  * Send a message to target(s).
513  *
514  * This function is used by IRC_{PRIVMSG|NOTICE|SQUERY} to actualy
515  * send the message(s).
516  *
517  * @param Client The client from which this command has been received.
518  * @param Req Request structure with prefix and all parameters.
519  * @param ForceType Required type of the destination of the message(s).
520  * @param SendErrors Whether to report errors back to the client or not.
521  * @return CONNECTED or DISCONNECTED.
522  */
523 static bool
524 Send_Message(CLIENT * Client, REQUEST * Req, int ForceType, bool SendErrors)
525 {
526         CLIENT *cl, *from;
527         CL2CHAN *cl2chan;
528         CHANNEL *chan;
529         char *currentTarget = Req->argv[0];
530         char *strtok_last = NULL;
531         char *message = NULL;
532         char *targets[MAX_HNDL_TARGETS];
533         int i, target_nr = 0;
534
535         assert(Client != NULL);
536         assert(Req != NULL);
537
538         if (Req->argc == 0) {
539                 if (!SendErrors)
540                         return CONNECTED;
541                 return IRC_WriteErrClient(Client, ERR_NORECIPIENT_MSG,
542                                           Client_ID(Client), Req->command);
543         }
544         if (Req->argc == 1) {
545                 if (!SendErrors)
546                         return CONNECTED;
547                 return IRC_WriteErrClient(Client, ERR_NOTEXTTOSEND_MSG,
548                                           Client_ID(Client));
549         }
550         if (Req->argc > 2) {
551                 if (!SendErrors)
552                         return CONNECTED;
553                 return IRC_WriteErrClient(Client, ERR_NEEDMOREPARAMS_MSG,
554                                           Client_ID(Client), Req->command);
555         }
556
557         if (Client_Type(Client) == CLIENT_SERVER && Req->prefix)
558                 from = Client_Search(Req->prefix);
559         else
560                 from = Client;
561         if (!from)
562                 return IRC_WriteErrClient(Client, ERR_NOSUCHNICK_MSG,
563                                           Client_ID(Client), Req->prefix);
564
565 #ifdef ICONV
566         if (Client_Conn(Client) > NONE)
567                 message = Conn_EncodingFrom(Client_Conn(Client), Req->argv[1]);
568         else
569 #endif
570                 message = Req->argv[1];
571
572         /* handle msgtarget = msgto *("," msgto) */
573         currentTarget = strtok_r(currentTarget, ",", &strtok_last);
574         ngt_UpperStr(Req->command);
575
576         /* Please note that "currentTarget" is NULL when the target contains
577          * the separator character only, e. g. "," or ",,,," etc.! */
578         while (currentTarget) {
579                 /* Make sure that there hasn't been such a target already: */
580                 targets[target_nr++] = currentTarget;
581                 for(i = 0; i < target_nr - 1; i++) {
582                         if (strcasecmp(currentTarget, targets[i]) == 0)
583                                 goto send_next_target;
584                 }
585
586                 /* Check for and handle valid <msgto> of form:
587                  * RFC 2812 2.3.1:
588                  *   msgto =  channel / ( user [ "%" host ] "@" servername )
589                  *   msgto =/ ( user "%" host ) / targetmask
590                  *   msgto =/ nickname / ( nickname "!" user "@" host )
591                  */
592                 if (strchr(currentTarget, '!') == NULL)
593                         /* nickname */
594                         cl = Client_Search(currentTarget);
595                 else
596                         cl = NULL;
597
598                 if (cl == NULL) {
599                         /* If currentTarget isn't a nickname check for:
600                          * user ["%" host] "@" servername
601                          * user "%" host
602                          * nickname "!" user "@" host
603                          */
604                         char target[COMMAND_LEN];
605                         char * nick = NULL;
606                         char * user = NULL;
607                         char * host = NULL;
608                         char * server = NULL;
609
610                         strlcpy(target, currentTarget, COMMAND_LEN);
611                         server = strchr(target, '@');
612                         if (server) {
613                                 *server = '\0';
614                                 server++;
615                         }
616                         host = strchr(target, '%');
617                         if (host) {
618                                 *host = '\0';
619                                 host++;
620                         }
621                         user = strchr(target, '!');
622                         if (user) {
623                                 /* msgto form: nick!user@host */
624                                 *user = '\0';
625                                 user++;
626                                 nick = target;
627                                 host = server; /* not "@server" but "@host" */
628                         } else {
629                                 user = target;
630                         }
631
632                         for (cl = Client_First(); cl != NULL; cl = Client_Next(cl)) {
633                                 if (Client_Type(cl) != CLIENT_USER &&
634                                     Client_Type(cl) != CLIENT_SERVICE)
635                                         continue;
636                                 if (nick != NULL && host != NULL) {
637                                         if (strcasecmp(nick, Client_ID(cl)) == 0 &&
638                                             strcasecmp(user, Client_User(cl)) == 0 &&
639                                             strcasecmp(host, Client_HostnameDisplayed(cl)) == 0)
640                                                 break;
641                                         else
642                                                 continue;
643                                 }
644                                 if (strcasecmp(user, Client_User(cl)) != 0)
645                                         continue;
646                                 if (host != NULL && strcasecmp(host,
647                                                 Client_HostnameDisplayed(cl)) != 0)
648                                         continue;
649                                 if (server != NULL && strcasecmp(server,
650                                                 Client_ID(Client_Introducer(cl))) != 0)
651                                         continue;
652                                 break;
653                         }
654                 }
655
656                 if (cl) {
657                         /* Target is a user, enforce type */
658 #ifndef STRICT_RFC
659                         if (Client_Type(cl) != ForceType &&
660                             !(ForceType == CLIENT_USER &&
661                               (Client_Type(cl) == CLIENT_USER ||
662                                Client_Type(cl) == CLIENT_SERVICE))) {
663 #else
664                         if (Client_Type(cl) != ForceType) {
665 #endif
666                                 if (SendErrors && !IRC_WriteErrClient(
667                                     from, ERR_NOSUCHNICK_MSG,Client_ID(from),
668                                     currentTarget))
669                                         return DISCONNECTED;
670                                 goto send_next_target;
671                         }
672
673 #ifndef STRICT_RFC
674                         if (ForceType == CLIENT_SERVICE &&
675                             (Conn_Options(Client_Conn(Client_NextHop(cl)))
676                              & CONN_RFC1459)) {
677                                 /* SQUERY command but RFC 1459 link: convert
678                                  * request to PRIVMSG command */
679                                 Req->command = "PRIVMSG";
680                         }
681 #endif
682                         if (Client_HasMode(cl, 'b') &&
683                             !Client_HasMode(from, 'R') &&
684                             !Client_HasMode(from, 'o') &&
685                             !(Client_Type(from) == CLIENT_SERVER) &&
686                             !(Client_Type(from) == CLIENT_SERVICE)) {
687                                 if (SendErrors && !IRC_WriteErrClient(from,
688                                                 ERR_NONONREG_MSG,
689                                                 Client_ID(from), Client_ID(cl)))
690                                         return DISCONNECTED;
691                                 goto send_next_target;
692                         }
693
694                         if (Client_HasMode(cl, 'C')) {
695                                 cl2chan = Channel_FirstChannelOf(cl);
696                                 while (cl2chan) {
697                                         chan = Channel_GetChannel(cl2chan);
698                                         if (Channel_IsMemberOf(chan, from))
699                                                 break;
700                                         cl2chan = Channel_NextChannelOf(cl, cl2chan);
701                                 }
702                                 if (!cl2chan) {
703                                         if (SendErrors && !IRC_WriteErrClient(
704                                             from, ERR_NOTONSAMECHANNEL_MSG,
705                                             Client_ID(from), Client_ID(cl)))
706                                                 return DISCONNECTED;
707                                         goto send_next_target;
708                                 }
709                         }
710
711                         if (SendErrors && (Client_Type(Client) != CLIENT_SERVER)
712                             && Client_HasMode(cl, 'a')) {
713                                 /* Target is away */
714                                 if (!IRC_WriteStrClient(from, RPL_AWAY_MSG,
715                                                         Client_ID(from),
716                                                         Client_ID(cl),
717                                                         Client_Away(cl)))
718                                         return DISCONNECTED;
719                         }
720                         if (Client_Conn(from) > NONE) {
721                                 Conn_UpdateIdle(Client_Conn(from));
722                         }
723                         if (!IRC_WriteStrClientPrefix(cl, from, "%s %s :%s",
724                                                       Req->command, Client_ID(cl),
725                                                       message))
726                                 return DISCONNECTED;
727                 } else if (ForceType != CLIENT_SERVICE
728                            && (chan = Channel_Search(currentTarget))) {
729                         /* Target is a channel */
730                         if (!Channel_Write(chan, from, Client, Req->command,
731                                            SendErrors, message))
732                                         return DISCONNECTED;
733                 } else if (ForceType != CLIENT_SERVICE
734                            && strchr("$#", currentTarget[0])
735                            && strchr(currentTarget, '.')) {
736                         /* $#: server/host mask, RFC 2812, sec. 3.3.1 */
737                         if (!Send_Message_Mask(from, Req->command, currentTarget,
738                                                message, SendErrors))
739                                 return DISCONNECTED;
740                 } else {
741                         if (!SendErrors)
742                                 return CONNECTED;
743                         if (!IRC_WriteErrClient(from, ERR_NOSUCHNICK_MSG,
744                                                 Client_ID(from), currentTarget))
745                                 return DISCONNECTED;
746                 }
747
748         send_next_target:
749                 currentTarget = strtok_r(NULL, ",", &strtok_last);
750                 if (!currentTarget)
751                         break;
752
753                 Conn_SetPenalty(Client_Conn(Client), 1);
754
755                 if (target_nr >= MAX_HNDL_TARGETS) {
756                         /* Too many targets given! */
757                         return IRC_WriteErrClient(Client,
758                                                   ERR_TOOMANYTARGETS_MSG,
759                                                   currentTarget);
760                 }
761         }
762
763         return CONNECTED;
764 } /* Send_Message */
765
766 /**
767  * Send a message to "target mask" target(s).
768  *
769  * See RFC 2812, sec. 3.3.1 for details.
770  *
771  * @param from The client from which this command has been received.
772  * @param command The command to use (PRIVMSG, NOTICE, ...).
773  * @param targetMask The "target mask" (will be verified by this function).
774  * @param message The message to send.
775  * @param SendErrors Whether to report errors back to the client or not.
776  * @return CONNECTED or DISCONNECTED.
777  */
778 static bool
779 Send_Message_Mask(CLIENT * from, char * command, char * targetMask,
780                   char * message, bool SendErrors)
781 {
782         CLIENT *cl;
783         bool client_match;
784         char *mask = targetMask + 1;
785         const char *check_wildcards;
786
787         cl = NULL;
788
789         if (!Client_HasMode(from, 'o')) {
790                 if (!SendErrors)
791                         return true;
792                 return IRC_WriteErrClient(from, ERR_NOPRIVILEGES_MSG,
793                                           Client_ID(from));
794         }
795
796         /*
797          * RFC 2812, sec. 3.3.1 requires that targetMask have at least one
798          * dot (".") and no wildcards ("*", "?") following the last one.
799          */
800         check_wildcards = strrchr(targetMask, '.');
801         if (!check_wildcards || check_wildcards[strcspn(check_wildcards, "*?")]) {
802                 if (!SendErrors)
803                         return true;
804                 return IRC_WriteErrClient(from, ERR_WILDTOPLEVEL_MSG,
805                                           targetMask);
806         }
807
808         if (targetMask[0] == '#') {
809                 /* #: hostmask, see RFC 2812, sec. 3.3.1 */
810                 for (cl = Client_First(); cl != NULL; cl = Client_Next(cl)) {
811                         if (Client_Type(cl) != CLIENT_USER)
812                                 continue;
813                         client_match = MatchCaseInsensitive(mask, Client_Hostname(cl));
814                         if (client_match)
815                                 if (!IRC_WriteStrClientPrefix(cl, from, "%s %s :%s",
816                                                 command, Client_ID(cl), message))
817                                         return false;
818                 }
819         } else {
820                 /* $: server mask, see RFC 2812, sec. 3.3.1 */
821                 assert(targetMask[0] == '$');
822                 for (cl = Client_First(); cl != NULL; cl = Client_Next(cl)) {
823                         if (Client_Type(cl) != CLIENT_USER)
824                                 continue;
825                         client_match = MatchCaseInsensitive(mask,
826                                         Client_ID(Client_Introducer(cl)));
827                         if (client_match)
828                                 if (!IRC_WriteStrClientPrefix(cl, from, "%s %s :%s",
829                                                 command, Client_ID(cl), message))
830                                         return false;
831                 }
832         }
833         return CONNECTED;
834 } /* Send_Message_Mask */
835
836 /* -eof- */