2 * ngIRCd -- The Next Generation IRC Daemon
3 * Copyright (c)2001-2015 Alexander Barton (alex@barton.de) and Contributors.
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.
26 #include "conn-func.h"
30 # include "conn-encoding.h"
32 #include "irc-macros.h"
33 #include "irc-write.h"
42 static char *Option_String PARAMS((CONN_ID Idx));
43 static bool Send_Message PARAMS((CLIENT *Client, REQUEST *Req, int ForceType,
45 static bool Send_Message_Mask PARAMS((CLIENT *from, char *command,
46 char *targetMask, char *message,
48 static bool Help PARAMS((CLIENT *Client, const char *Topic));
51 * Check if a list limit is reached and inform client accordingly.
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.
60 IRC_CheckListTooBig(CLIENT *From, const int Count, const int Limit,
71 (void)IRC_WriteStrClient(From,
72 "NOTICE %s :%s list limit (%d) reached!",
73 Client_ID(From), Name, Limit);
74 IRC_SetPenalty(From, 2);
79 * Handler for the IRC "ERROR" command.
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.
86 IRC_ERROR(CLIENT *Client, REQUEST *Req)
90 assert( Client != NULL );
91 assert( Req != NULL );
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\" ...",
100 IRC_SetPenalty(Client, 2);
105 msg = "Got ERROR command";
106 Log(LOG_NOTICE, "Got ERROR from \"%s\"!",
107 Client_Mask(Client));
110 Log(LOG_NOTICE, "Got ERROR from \"%s\": \"%s\"!",
111 Client_Mask(Client), msg);
114 if (Client_Conn(Client) != NONE) {
115 Client_Destroy(Client, NULL, msg, false);
123 * Handler for the IRC "KILL" command.
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.
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.
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.
139 IRC_KILL(CLIENT *Client, REQUEST *Req)
142 char reason[COMMAND_LEN];
144 assert (Client != NULL);
145 assert (Req != NULL);
147 if (Client_Type(Client) != CLIENT_SERVER && !Op_Check(Client, Req))
148 return Op_NoPrivileges(Client, Req);
150 /* Get prefix (origin); use the client if no prefix is given. */
152 prefix = Client_Search(Req->prefix);
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! */
160 Log(LOG_WARNING, "Got KILL with invalid prefix: \"%s\"!",
162 prefix = Client_ThisServer();
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]);
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]);
176 strlcpy(reason, Req->argv[1], sizeof(reason));
178 return IRC_KillClient(Client, prefix, Req->argv[0], reason);
182 * Handler for the IRC "NOTICE" command.
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.
189 IRC_NOTICE(CLIENT *Client, REQUEST *Req)
191 return Send_Message(Client, Req, CLIENT_USER, false);
195 * Handler for the IRC "PRIVMSG" command.
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.
202 IRC_PRIVMSG(CLIENT *Client, REQUEST *Req)
204 return Send_Message(Client, Req, CLIENT_USER, true);
208 * Handler for the IRC "SQUERY" command.
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.
215 IRC_SQUERY(CLIENT *Client, REQUEST *Req)
217 return Send_Message(Client, Req, CLIENT_SERVICE, true);
221 * Handler for the IRC "TRACE" command.
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.
228 IRC_TRACE(CLIENT *Client, REQUEST *Req)
230 CLIENT *from, *target, *c;
232 char user[CLIENT_USER_LEN];
234 assert(Client != NULL);
237 _IRC_GET_SENDER_OR_RETURN_(from, Req, Client)
238 _IRC_GET_TARGET_SERVER_OR_RETURN_(target, Req, 0, from)
240 /* Forward command to other server? */
241 if (target != Client_ThisServer()) {
242 /* Send RPL_TRACELINK back to initiator */
243 idx = Client_Conn(Client);
245 idx2 = Client_Conn(Client_NextHop(target));
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)),
253 (long)(time(NULL) - Conn_StartTime(idx2)),
254 Conn_SendQ(idx), Conn_SendQ(idx2)))
257 /* Forward command */
258 IRC_WriteStrClientPrefix(target, from, "TRACE %s", Req->argv[0]);
262 /* Infos about all connected servers */
265 if (Client_Conn(c) > NONE) {
267 if (Client_Type(c) == CLIENT_SERVER) {
269 strlcpy(user, Client_User(c), sizeof(user));
271 strlcpy(user, "unknown", sizeof(user));
272 if (!IRC_WriteStrClient(from,
274 Client_ID(from), Client_ID(c),
275 user, Client_Hostname(c),
276 Client_Mask(Client_ThisServer()),
277 Option_String(Client_Conn(c))))
280 if (Client_Type(c) == CLIENT_USER
281 && Client_HasMode(c, 'o')) {
283 if (!IRC_WriteStrClient(from,
284 RPL_TRACEOPERATOR_MSG,
285 Client_ID(from), Client_ID(c)))
289 c = Client_Next( c );
292 return IRC_WriteStrClient(from, RPL_TRACEEND_MSG, Client_ID(from),
293 Conf_ServerName, PACKAGE_NAME,
294 PACKAGE_VERSION, NGIRCd_DebugLevel);
298 * Handler for the IRC "HELP" command.
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.
305 IRC_HELP(CLIENT *Client, REQUEST *Req)
309 assert(Client != NULL);
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 */
316 return Help(Client, Req->argv[0]);
318 if (!Help(Client, "Intro"))
323 cmd = Parse_GetCommandStruct();
325 if (!IRC_WriteStrClient(Client, "NOTICE %s :%s",
326 Client_ID(Client), cmd->name))
334 * Kill an client identified by its nick name.
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!
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
345 * @param Nick The nick name to kill.
346 * @param Reason Text to send as reason to the client and other servers.
349 IRC_KillClient(CLIENT *Client, CLIENT *From, const char *Nick, const char *Reason)
352 CONN_ID my_conn = NONE, conn;
355 assert(Nick != NULL);
356 assert(Reason != NULL);
358 /* Do we know such a client in the network? */
359 c = Client_Search(Nick);
361 LogDebug("Client with nick \"%s\" is unknown, not forwaring.", Nick);
365 if (Client_Type(c) != CLIENT_USER && Client_Type(c) != CLIENT_GOTNICK
366 && Client_Type(c) != CLIENT_SERVICE) {
367 /* Target of this KILL is not a regular user, this is
368 * invalid! So we ignore this case if we received a
369 * regular KILL from the network and try to kill the
370 * client/connection anyway (but log an error!) if the
371 * origin is the local server. */
373 if (Client != Client_ThisServer()) {
374 /* Invalid KILL received from remote */
375 if (Client_Type(c) == CLIENT_SERVER)
376 msg = ERR_CANTKILLSERVER_MSG;
378 msg = ERR_NOPRIVILEGES_MSG;
379 return IRC_WriteErrClient(Client, msg, Client_ID(Client));
383 "Got KILL for invalid client type: %d, \"%s\"!",
384 Client_Type(c), Nick);
387 /* Inform other servers */
388 IRC_WriteStrServersPrefix(From ? Client : NULL,
389 From ? From : Client_ThisServer(),
390 "KILL %s :%s", Nick, Reason);
393 /* Save ID of this connection */
395 my_conn = Client_Conn(Client);
397 /* Kill the client NOW:
398 * - Close the local connection (if there is one),
399 * - Destroy the CLIENT structure for remote clients.
400 * Note: Conn_Close() removes the CLIENT structure as well. */
401 conn = Client_Conn(c);
403 Conn_Close(conn, NULL, Reason, true);
405 Client_Destroy(c, NULL, Reason, false);
407 /* Are we still connected or were we killed, too? */
408 if (my_conn > NONE && Conn_GetClient(my_conn))
415 * Send help for a given topic to the client.
417 * @param Client The client requesting help.
418 * @param Topoc The help topic requested.
419 * @return CONNECTED or DISCONNECTED.
422 Help(CLIENT *Client, const char *Topic)
425 size_t helptext_len, len_str, idx_start, lines = 0;
426 bool in_article = false;
428 assert(Client != NULL);
429 assert(Topic != NULL);
431 helptext_len = array_bytes(&Conf_Helptext);
432 line = array_start(&Conf_Helptext);
433 while (helptext_len > 0) {
434 len_str = strlen(line) + 1;
435 assert(helptext_len >= len_str);
436 helptext_len -= len_str;
439 /* The first character in each article text line must
440 * be a TAB (ASCII 9) character which will be stripped
441 * in the output. If it is not a TAB, the end of the
442 * article has been reached. */
443 if (line[0] != '\t') {
450 /* A single '.' character indicates an empty line */
451 if (line[1] == '.' && line[2] == '\0')
456 if (!IRC_WriteStrClient(Client, "NOTICE %s :%s",
463 if (line[0] == '-' && line[1] == ' '
464 && strcasecmp(&line[2], Topic) == 0)
471 /* Help topic not found (or empty)! */
472 if (!IRC_WriteStrClient(Client, "NOTICE %s :No help for \"%s\" found!",
473 Client_ID(Client), Topic))
480 * Get pointer to a static string representing the connection "options".
482 * @param Idx Connection index.
483 * @return Pointer to static (global) string buffer.
487 Option_String(CONN_ID Idx)
489 Option_String(UNUSED CONN_ID Idx)
492 static char option_txt[8];
497 options = Conn_Options(Idx);
498 strcpy(option_txt, "F"); /* No idea what this means, but the
499 * original ircd sends it ... */
501 if(options & CONN_SSL) /* SSL encrypted link */
502 strlcat(option_txt, "s", sizeof(option_txt));
505 if(options & CONN_ZIP) /* zlib compression enabled */
506 strlcat(option_txt, "z", sizeof(option_txt));
510 } /* Option_String */
513 * Send a message to target(s).
515 * This function is used by IRC_{PRIVMSG|NOTICE|SQUERY} to actualy
516 * send the message(s).
518 * @param Client The client from which this command has been received.
519 * @param Req Request structure with prefix and all parameters.
520 * @param ForceType Required type of the destination of the message(s).
521 * @param SendErrors Whether to report errors back to the client or not.
522 * @return CONNECTED or DISCONNECTED.
525 Send_Message(CLIENT * Client, REQUEST * Req, int ForceType, bool SendErrors)
530 char *currentTarget = Req->argv[0];
531 char *strtok_last = NULL;
532 char *message = NULL;
533 char *targets[MAX_HNDL_TARGETS];
534 int i, target_nr = 0;
536 assert(Client != NULL);
539 if (Req->argc == 0) {
542 return IRC_WriteErrClient(Client, ERR_NORECIPIENT_MSG,
543 Client_ID(Client), Req->command);
545 if (Req->argc == 1) {
548 return IRC_WriteErrClient(Client, ERR_NOTEXTTOSEND_MSG,
554 return IRC_WriteErrClient(Client, ERR_NEEDMOREPARAMS_MSG,
555 Client_ID(Client), Req->command);
558 if (Client_Type(Client) == CLIENT_SERVER && Req->prefix)
559 from = Client_Search(Req->prefix);
563 return IRC_WriteErrClient(Client, ERR_NOSUCHNICK_MSG,
564 Client_ID(Client), Req->prefix);
567 if (Client_Conn(Client) > NONE)
568 message = Conn_EncodingFrom(Client_Conn(Client), Req->argv[1]);
571 message = Req->argv[1];
573 /* handle msgtarget = msgto *("," msgto) */
574 currentTarget = strtok_r(currentTarget, ",", &strtok_last);
575 ngt_UpperStr(Req->command);
577 /* Please note that "currentTarget" is NULL when the target contains
578 * the separator character only, e. g. "," or ",,,," etc.! */
579 while (currentTarget) {
580 /* Make sure that there hasn't been such a target already: */
581 targets[target_nr++] = currentTarget;
582 for(i = 0; i < target_nr - 1; i++) {
583 if (strcasecmp(currentTarget, targets[i]) == 0)
584 goto send_next_target;
587 /* Check for and handle valid <msgto> of form:
589 * msgto = channel / ( user [ "%" host ] "@" servername )
590 * msgto =/ ( user "%" host ) / targetmask
591 * msgto =/ nickname / ( nickname "!" user "@" host )
593 if (strchr(currentTarget, '!') == NULL)
595 cl = Client_Search(currentTarget);
600 /* If currentTarget isn't a nickname check for:
601 * user ["%" host] "@" servername
603 * nickname "!" user "@" host
605 char target[COMMAND_LEN];
609 char * server = NULL;
611 strlcpy(target, currentTarget, COMMAND_LEN);
612 server = strchr(target, '@');
617 host = strchr(target, '%');
622 user = strchr(target, '!');
624 /* msgto form: nick!user@host */
628 host = server; /* not "@server" but "@host" */
633 for (cl = Client_First(); cl != NULL; cl = Client_Next(cl)) {
634 if (Client_Type(cl) != CLIENT_USER &&
635 Client_Type(cl) != CLIENT_SERVICE)
637 if (nick != NULL && host != NULL) {
638 if (strcasecmp(nick, Client_ID(cl)) == 0 &&
639 strcasecmp(user, Client_User(cl)) == 0 &&
640 strcasecmp(host, Client_HostnameDisplayed(cl)) == 0)
645 if (strcasecmp(user, Client_User(cl)) != 0)
647 if (host != NULL && strcasecmp(host,
648 Client_HostnameDisplayed(cl)) != 0)
650 if (server != NULL && strcasecmp(server,
651 Client_ID(Client_Introducer(cl))) != 0)
658 /* Target is a user, enforce type */
660 if (Client_Type(cl) != ForceType &&
661 !(ForceType == CLIENT_USER &&
662 (Client_Type(cl) == CLIENT_USER ||
663 Client_Type(cl) == CLIENT_SERVICE))) {
665 if (Client_Type(cl) != ForceType) {
667 if (SendErrors && !IRC_WriteErrClient(
668 from, ERR_NOSUCHNICK_MSG,Client_ID(from),
671 goto send_next_target;
675 if (ForceType == CLIENT_SERVICE &&
676 (Conn_Options(Client_Conn(Client_NextHop(cl)))
678 /* SQUERY command but RFC 1459 link: convert
679 * request to PRIVMSG command */
680 Req->command = "PRIVMSG";
683 if (Client_HasMode(cl, 'b') &&
684 !Client_HasMode(from, 'R') &&
685 !Client_HasMode(from, 'o') &&
686 !(Client_Type(from) == CLIENT_SERVER) &&
687 !(Client_Type(from) == CLIENT_SERVICE)) {
688 if (SendErrors && !IRC_WriteErrClient(from,
690 Client_ID(from), Client_ID(cl)))
692 goto send_next_target;
695 if (Client_HasMode(cl, 'C')) {
696 cl2chan = Channel_FirstChannelOf(cl);
698 chan = Channel_GetChannel(cl2chan);
699 if (Channel_IsMemberOf(chan, from))
701 cl2chan = Channel_NextChannelOf(cl, cl2chan);
704 if (SendErrors && !IRC_WriteErrClient(
705 from, ERR_NOTONSAMECHANNEL_MSG,
706 Client_ID(from), Client_ID(cl)))
708 goto send_next_target;
712 if (SendErrors && (Client_Type(Client) != CLIENT_SERVER)
713 && Client_HasMode(cl, 'a')) {
715 if (!IRC_WriteStrClient(from, RPL_AWAY_MSG,
721 if (Client_Conn(from) > NONE) {
722 Conn_UpdateIdle(Client_Conn(from));
724 if (!IRC_WriteStrClientPrefix(cl, from, "%s %s :%s",
725 Req->command, Client_ID(cl),
728 } else if (ForceType != CLIENT_SERVICE
729 && (chan = Channel_Search(currentTarget))) {
730 /* Target is a channel */
731 if (!Channel_Write(chan, from, Client, Req->command,
732 SendErrors, message))
734 } else if (ForceType != CLIENT_SERVICE
735 && strchr("$#", currentTarget[0])
736 && strchr(currentTarget, '.')) {
737 /* $#: server/host mask, RFC 2812, sec. 3.3.1 */
738 if (!Send_Message_Mask(from, Req->command, currentTarget,
739 message, SendErrors))
744 if (!IRC_WriteErrClient(from, ERR_NOSUCHNICK_MSG,
745 Client_ID(from), currentTarget))
750 currentTarget = strtok_r(NULL, ",", &strtok_last);
754 Conn_SetPenalty(Client_Conn(Client), 1);
756 if (target_nr >= MAX_HNDL_TARGETS) {
757 /* Too many targets given! */
758 return IRC_WriteErrClient(Client,
759 ERR_TOOMANYTARGETS_MSG,
768 * Send a message to "target mask" target(s).
770 * See RFC 2812, sec. 3.3.1 for details.
772 * @param from The client from which this command has been received.
773 * @param command The command to use (PRIVMSG, NOTICE, ...).
774 * @param targetMask The "target mask" (will be verified by this function).
775 * @param message The message to send.
776 * @param SendErrors Whether to report errors back to the client or not.
777 * @return CONNECTED or DISCONNECTED.
780 Send_Message_Mask(CLIENT * from, char * command, char * targetMask,
781 char * message, bool SendErrors)
785 char *mask = targetMask + 1;
786 const char *check_wildcards;
790 if (!Client_HasMode(from, 'o')) {
793 return IRC_WriteErrClient(from, ERR_NOPRIVILEGES_MSG,
798 * RFC 2812, sec. 3.3.1 requires that targetMask have at least one
799 * dot (".") and no wildcards ("*", "?") following the last one.
801 check_wildcards = strrchr(targetMask, '.');
802 if (!check_wildcards || check_wildcards[strcspn(check_wildcards, "*?")]) {
805 return IRC_WriteErrClient(from, ERR_WILDTOPLEVEL_MSG,
809 if (targetMask[0] == '#') {
810 /* #: hostmask, see RFC 2812, sec. 3.3.1 */
811 for (cl = Client_First(); cl != NULL; cl = Client_Next(cl)) {
812 if (Client_Type(cl) != CLIENT_USER)
814 client_match = MatchCaseInsensitive(mask, Client_Hostname(cl));
816 if (!IRC_WriteStrClientPrefix(cl, from, "%s %s :%s",
817 command, Client_ID(cl), message))
821 /* $: server mask, see RFC 2812, sec. 3.3.1 */
822 assert(targetMask[0] == '$');
823 for (cl = Client_First(); cl != NULL; cl = Client_Next(cl)) {
824 if (Client_Type(cl) != CLIENT_USER)
826 client_match = MatchCaseInsensitive(mask,
827 Client_ID(Client_Introducer(cl)));
829 if (!IRC_WriteStrClientPrefix(cl, from, "%s %s :%s",
830 command, Client_ID(cl), message))
835 } /* Send_Message_Mask */