]> arthur.barton.de Git - ngircd-alex.git/blob - src/ngircd/irc.c
d5e4bde3d70cd1319b82f69641a6d993257be3bc
[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         /* Inform other servers */
366         IRC_WriteStrServersPrefix(From ? Client : NULL,
367                                   From ? From : Client_ThisServer(),
368                                   "KILL %s :%s", Nick, Reason);
369
370         if (Client_Type(c) != CLIENT_USER && Client_Type(c) != CLIENT_GOTNICK) {
371                 /* Target of this KILL is not a regular user, this is
372                  * invalid! So we ignore this case if we received a
373                  * regular KILL from the network and try to kill the
374                  * client/connection anyway (but log an error!) if the
375                  * origin is the local server. */
376
377                 if (Client != Client_ThisServer()) {
378                         /* Invalid KILL received from remote */
379                         if (Client_Type(c) == CLIENT_SERVER)
380                                 msg = ERR_CANTKILLSERVER_MSG;
381                         else
382                                 msg = ERR_NOPRIVILEGES_MSG;
383                         return IRC_WriteErrClient(Client, msg, Client_ID(Client));
384                 }
385
386                 Log(LOG_ERR,
387                     "Got KILL for invalid client type: %d, \"%s\"!",
388                     Client_Type(c), Nick);
389         }
390
391         /* Save ID of this connection */
392         if (Client)
393                 my_conn = Client_Conn(Client);
394
395         /* Kill the client NOW:
396          *  - Close the local connection (if there is one),
397          *  - Destroy the CLIENT structure for remote clients.
398          * Note: Conn_Close() removes the CLIENT structure as well. */
399         conn = Client_Conn(c);
400         if(conn > NONE)
401                 Conn_Close(conn, NULL, Reason, true);
402         else
403                 Client_Destroy(c, NULL, Reason, false);
404
405         /* Are we still connected or were we killed, too? */
406         if (my_conn > NONE && Conn_GetClient(my_conn))
407                 return CONNECTED;
408         else
409                 return DISCONNECTED;
410 }
411
412 /**
413  * Send help for a given topic to the client.
414  *
415  * @param Client The client requesting help.
416  * @param Topoc The help topic requested.
417  * @return CONNECTED or DISCONNECTED.
418  */
419 static bool
420 Help(CLIENT *Client, const char *Topic)
421 {
422         char *line;
423         size_t helptext_len, len_str, idx_start, lines = 0;
424         bool in_article = false;
425
426         assert(Client != NULL);
427         assert(Topic != NULL);
428
429         helptext_len = array_bytes(&Conf_Helptext);
430         line = array_start(&Conf_Helptext);
431         while (helptext_len > 0) {
432                 len_str = strlen(line) + 1;
433                 assert(helptext_len >= len_str);
434                 helptext_len -= len_str;
435
436                 if (in_article) {
437                         /* The first character in each article text line must
438                          * be a TAB (ASCII 9) character which will be stripped
439                          * in the output. If it is not a TAB, the end of the
440                          * article has been reached. */
441                         if (line[0] != '\t') {
442                                 if (lines > 0)
443                                         return CONNECTED;
444                                 else
445                                         break;
446                         }
447
448                         /* A single '.' character indicates an empty line */
449                         if (line[1] == '.' && line[2] == '\0')
450                                 idx_start = 2;
451                         else
452                                 idx_start = 1;
453
454                         if (!IRC_WriteStrClient(Client, "NOTICE %s :%s",
455                                                 Client_ID(Client),
456                                                 &line[idx_start]))
457                                 return DISCONNECTED;
458                         lines++;
459
460                 } else {
461                         if (line[0] == '-' && line[1] == ' '
462                             && strcasecmp(&line[2], Topic) == 0)
463                                 in_article = true;
464                 }
465
466                 line += len_str;
467         }
468
469         /* Help topic not found (or empty)! */
470         if (!IRC_WriteStrClient(Client, "NOTICE %s :No help for \"%s\" found!",
471                                 Client_ID(Client), Topic))
472                 return DISCONNECTED;
473
474         return CONNECTED;
475 }
476
477 /**
478  * Get pointer to a static string representing the connection "options".
479  *
480  * @param Idx Connection index.
481  * @return Pointer to static (global) string buffer.
482  */
483 static char *
484 #ifdef ZLIB
485 Option_String(CONN_ID Idx)
486 #else
487 Option_String(UNUSED CONN_ID Idx)
488 #endif
489 {
490         static char option_txt[8];
491         UINT16 options;
492
493         assert(Idx != NONE);
494
495         options = Conn_Options(Idx);
496         strcpy(option_txt, "F");        /* No idea what this means, but the
497                                          * original ircd sends it ... */
498 #ifdef SSL_SUPPORT
499         if(options & CONN_SSL)          /* SSL encrypted link */
500                 strlcat(option_txt, "s", sizeof(option_txt));
501 #endif
502 #ifdef ZLIB
503         if(options & CONN_ZIP)          /* zlib compression enabled */
504                 strlcat(option_txt, "z", sizeof(option_txt));
505 #endif
506
507         return option_txt;
508 } /* Option_String */
509
510 /**
511  * Send a message to target(s).
512  *
513  * This function is used by IRC_{PRIVMSG|NOTICE|SQUERY} to actualy
514  * send the message(s).
515  *
516  * @param Client The client from which this command has been received.
517  * @param Req Request structure with prefix and all parameters.
518  * @param ForceType Required type of the destination of the message(s).
519  * @param SendErrors Whether to report errors back to the client or not.
520  * @return CONNECTED or DISCONNECTED.
521  */
522 static bool
523 Send_Message(CLIENT * Client, REQUEST * Req, int ForceType, bool SendErrors)
524 {
525         CLIENT *cl, *from;
526         CL2CHAN *cl2chan;
527         CHANNEL *chan;
528         char *currentTarget = Req->argv[0];
529         char *strtok_last = NULL;
530         char *message = NULL;
531         char *targets[MAX_HNDL_TARGETS];
532         int i, target_nr = 0;
533
534         assert(Client != NULL);
535         assert(Req != NULL);
536
537         if (Req->argc == 0) {
538                 if (!SendErrors)
539                         return CONNECTED;
540                 return IRC_WriteErrClient(Client, ERR_NORECIPIENT_MSG,
541                                           Client_ID(Client), Req->command);
542         }
543         if (Req->argc == 1) {
544                 if (!SendErrors)
545                         return CONNECTED;
546                 return IRC_WriteErrClient(Client, ERR_NOTEXTTOSEND_MSG,
547                                           Client_ID(Client));
548         }
549         if (Req->argc > 2) {
550                 if (!SendErrors)
551                         return CONNECTED;
552                 return IRC_WriteErrClient(Client, ERR_NEEDMOREPARAMS_MSG,
553                                           Client_ID(Client), Req->command);
554         }
555
556         if (Client_Type(Client) == CLIENT_SERVER && Req->prefix)
557                 from = Client_Search(Req->prefix);
558         else
559                 from = Client;
560         if (!from)
561                 return IRC_WriteErrClient(Client, ERR_NOSUCHNICK_MSG,
562                                           Client_ID(Client), Req->prefix);
563
564 #ifdef ICONV
565         if (Client_Conn(Client) > NONE)
566                 message = Conn_EncodingFrom(Client_Conn(Client), Req->argv[1]);
567         else
568 #endif
569                 message = Req->argv[1];
570
571         /* handle msgtarget = msgto *("," msgto) */
572         currentTarget = strtok_r(currentTarget, ",", &strtok_last);
573         ngt_UpperStr(Req->command);
574
575         /* Please note that "currentTarget" is NULL when the target contains
576          * the separator character only, e. g. "," or ",,,," etc.! */
577         while (currentTarget) {
578                 /* Make sure that there hasn't been such a target already: */
579                 targets[target_nr++] = currentTarget;
580                 for(i = 0; i < target_nr - 1; i++) {
581                         if (strcasecmp(currentTarget, targets[i]) == 0)
582                                 goto send_next_target;
583                 }
584
585                 /* Check for and handle valid <msgto> of form:
586                  * RFC 2812 2.3.1:
587                  *   msgto =  channel / ( user [ "%" host ] "@" servername )
588                  *   msgto =/ ( user "%" host ) / targetmask
589                  *   msgto =/ nickname / ( nickname "!" user "@" host )
590                  */
591                 if (strchr(currentTarget, '!') == NULL)
592                         /* nickname */
593                         cl = Client_Search(currentTarget);
594                 else
595                         cl = NULL;
596
597                 if (cl == NULL) {
598                         /* If currentTarget isn't a nickname check for:
599                          * user ["%" host] "@" servername
600                          * user "%" host
601                          * nickname "!" user "@" host
602                          */
603                         char target[COMMAND_LEN];
604                         char * nick = NULL;
605                         char * user = NULL;
606                         char * host = NULL;
607                         char * server = NULL;
608
609                         strlcpy(target, currentTarget, COMMAND_LEN);
610                         server = strchr(target, '@');
611                         if (server) {
612                                 *server = '\0';
613                                 server++;
614                         }
615                         host = strchr(target, '%');
616                         if (host) {
617                                 *host = '\0';
618                                 host++;
619                         }
620                         user = strchr(target, '!');
621                         if (user) {
622                                 /* msgto form: nick!user@host */
623                                 *user = '\0';
624                                 user++;
625                                 nick = target;
626                                 host = server; /* not "@server" but "@host" */
627                         } else {
628                                 user = target;
629                         }
630
631                         for (cl = Client_First(); cl != NULL; cl = Client_Next(cl)) {
632                                 if (Client_Type(cl) != CLIENT_USER &&
633                                     Client_Type(cl) != CLIENT_SERVICE)
634                                         continue;
635                                 if (nick != NULL && host != NULL) {
636                                         if (strcasecmp(nick, Client_ID(cl)) == 0 &&
637                                             strcasecmp(user, Client_User(cl)) == 0 &&
638                                             strcasecmp(host, Client_HostnameDisplayed(cl)) == 0)
639                                                 break;
640                                         else
641                                                 continue;
642                                 }
643                                 if (strcasecmp(user, Client_User(cl)) != 0)
644                                         continue;
645                                 if (host != NULL && strcasecmp(host,
646                                                 Client_HostnameDisplayed(cl)) != 0)
647                                         continue;
648                                 if (server != NULL && strcasecmp(server,
649                                                 Client_ID(Client_Introducer(cl))) != 0)
650                                         continue;
651                                 break;
652                         }
653                 }
654
655                 if (cl) {
656                         /* Target is a user, enforce type */
657 #ifndef STRICT_RFC
658                         if (Client_Type(cl) != ForceType &&
659                             !(ForceType == CLIENT_USER &&
660                               (Client_Type(cl) == CLIENT_USER ||
661                                Client_Type(cl) == CLIENT_SERVICE))) {
662 #else
663                         if (Client_Type(cl) != ForceType) {
664 #endif
665                                 if (SendErrors && !IRC_WriteErrClient(
666                                     from, ERR_NOSUCHNICK_MSG,Client_ID(from),
667                                     currentTarget))
668                                         return DISCONNECTED;
669                                 goto send_next_target;
670                         }
671
672 #ifndef STRICT_RFC
673                         if (ForceType == CLIENT_SERVICE &&
674                             (Conn_Options(Client_Conn(Client_NextHop(cl)))
675                              & CONN_RFC1459)) {
676                                 /* SQUERY command but RFC 1459 link: convert
677                                  * request to PRIVMSG command */
678                                 Req->command = "PRIVMSG";
679                         }
680 #endif
681                         if (Client_HasMode(cl, 'b') &&
682                             !Client_HasMode(from, 'R') &&
683                             !Client_HasMode(from, 'o') &&
684                             !(Client_Type(from) == CLIENT_SERVER) &&
685                             !(Client_Type(from) == CLIENT_SERVICE)) {
686                                 if (SendErrors && !IRC_WriteErrClient(from,
687                                                 ERR_NONONREG_MSG,
688                                                 Client_ID(from), Client_ID(cl)))
689                                         return DISCONNECTED;
690                                 goto send_next_target;
691                         }
692
693                         if (Client_HasMode(cl, 'C')) {
694                                 cl2chan = Channel_FirstChannelOf(cl);
695                                 while (cl2chan) {
696                                         chan = Channel_GetChannel(cl2chan);
697                                         if (Channel_IsMemberOf(chan, from))
698                                                 break;
699                                         cl2chan = Channel_NextChannelOf(cl, cl2chan);
700                                 }
701                                 if (!cl2chan) {
702                                         if (SendErrors && !IRC_WriteErrClient(
703                                             from, ERR_NOTONSAMECHANNEL_MSG,
704                                             Client_ID(from), Client_ID(cl)))
705                                                 return DISCONNECTED;
706                                         goto send_next_target;
707                                 }
708                         }
709
710                         if (SendErrors && (Client_Type(Client) != CLIENT_SERVER)
711                             && Client_HasMode(cl, 'a')) {
712                                 /* Target is away */
713                                 if (!IRC_WriteStrClient(from, RPL_AWAY_MSG,
714                                                         Client_ID(from),
715                                                         Client_ID(cl),
716                                                         Client_Away(cl)))
717                                         return DISCONNECTED;
718                         }
719                         if (Client_Conn(from) > NONE) {
720                                 Conn_UpdateIdle(Client_Conn(from));
721                         }
722                         if (!IRC_WriteStrClientPrefix(cl, from, "%s %s :%s",
723                                                       Req->command, Client_ID(cl),
724                                                       message))
725                                 return DISCONNECTED;
726                 } else if (ForceType != CLIENT_SERVICE
727                            && (chan = Channel_Search(currentTarget))) {
728                         /* Target is a channel */
729                         if (!Channel_Write(chan, from, Client, Req->command,
730                                            SendErrors, message))
731                                         return DISCONNECTED;
732                 } else if (ForceType != CLIENT_SERVICE
733                            && strchr("$#", currentTarget[0])
734                            && strchr(currentTarget, '.')) {
735                         /* $#: server/host mask, RFC 2812, sec. 3.3.1 */
736                         if (!Send_Message_Mask(from, Req->command, currentTarget,
737                                                message, SendErrors))
738                                 return DISCONNECTED;
739                 } else {
740                         if (!SendErrors)
741                                 return CONNECTED;
742                         if (!IRC_WriteErrClient(from, ERR_NOSUCHNICK_MSG,
743                                                 Client_ID(from), currentTarget))
744                                 return DISCONNECTED;
745                 }
746
747         send_next_target:
748                 currentTarget = strtok_r(NULL, ",", &strtok_last);
749                 if (!currentTarget)
750                         break;
751
752                 Conn_SetPenalty(Client_Conn(Client), 1);
753
754                 if (target_nr >= MAX_HNDL_TARGETS) {
755                         /* Too many targets given! */
756                         return IRC_WriteErrClient(Client,
757                                                   ERR_TOOMANYTARGETS_MSG,
758                                                   currentTarget);
759                 }
760         }
761
762         return CONNECTED;
763 } /* Send_Message */
764
765 /**
766  * Send a message to "target mask" target(s).
767  *
768  * See RFC 2812, sec. 3.3.1 for details.
769  *
770  * @param from The client from which this command has been received.
771  * @param command The command to use (PRIVMSG, NOTICE, ...).
772  * @param targetMask The "target mask" (will be verified by this function).
773  * @param message The message to send.
774  * @param SendErrors Whether to report errors back to the client or not.
775  * @return CONNECTED or DISCONNECTED.
776  */
777 static bool
778 Send_Message_Mask(CLIENT * from, char * command, char * targetMask,
779                   char * message, bool SendErrors)
780 {
781         CLIENT *cl;
782         bool client_match;
783         char *mask = targetMask + 1;
784         const char *check_wildcards;
785
786         cl = NULL;
787
788         if (!Client_HasMode(from, 'o')) {
789                 if (!SendErrors)
790                         return true;
791                 return IRC_WriteErrClient(from, ERR_NOPRIVILEGES_MSG,
792                                           Client_ID(from));
793         }
794
795         /*
796          * RFC 2812, sec. 3.3.1 requires that targetMask have at least one
797          * dot (".") and no wildcards ("*", "?") following the last one.
798          */
799         check_wildcards = strrchr(targetMask, '.');
800         if (!check_wildcards || check_wildcards[strcspn(check_wildcards, "*?")]) {
801                 if (!SendErrors)
802                         return true;
803                 return IRC_WriteErrClient(from, ERR_WILDTOPLEVEL_MSG,
804                                           targetMask);
805         }
806
807         if (targetMask[0] == '#') {
808                 /* #: hostmask, see RFC 2812, sec. 3.3.1 */
809                 for (cl = Client_First(); cl != NULL; cl = Client_Next(cl)) {
810                         if (Client_Type(cl) != CLIENT_USER)
811                                 continue;
812                         client_match = MatchCaseInsensitive(mask, Client_Hostname(cl));
813                         if (client_match)
814                                 if (!IRC_WriteStrClientPrefix(cl, from, "%s %s :%s",
815                                                 command, Client_ID(cl), message))
816                                         return false;
817                 }
818         } else {
819                 /* $: server mask, see RFC 2812, sec. 3.3.1 */
820                 assert(targetMask[0] == '$');
821                 for (cl = Client_First(); cl != NULL; cl = Client_Next(cl)) {
822                         if (Client_Type(cl) != CLIENT_USER)
823                                 continue;
824                         client_match = MatchCaseInsensitive(mask,
825                                         Client_ID(Client_Introducer(cl)));
826                         if (client_match)
827                                 if (!IRC_WriteStrClientPrefix(cl, from, "%s %s :%s",
828                                                 command, Client_ID(cl), message))
829                                         return false;
830                 }
831         }
832         return CONNECTED;
833 } /* Send_Message_Mask */
834
835 /* -eof- */