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