1 /***************************************************************************
2 * Copyright (C) 2005-2019 by the Quassel Project *
3 * devel@quassel-irc.org *
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) version 3. *
10 * This program is distributed in the hope that it will be useful, *
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
13 * GNU General Public License for more details. *
15 * You should have received a copy of the GNU General Public License *
16 * along with this program; if not, write to the *
17 * Free Software Foundation, Inc., *
18 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
19 ***************************************************************************/
21 #include "ircparser.h"
25 #include "corenetwork.h"
26 #include "eventmanager.h"
27 #include "ircdecoder.h"
29 #include "messageevent.h"
30 #include "networkevent.h"
34 # include "keyevent.h"
37 IrcParser::IrcParser(CoreSession* session)
39 , _coreSession(session)
41 // Check if raw IRC logging is enabled
42 _debugLogRawIrc = (Quassel::isOptionSet("debug-irc") || Quassel::isOptionSet("debug-irc-id"));
43 _debugLogRawNetId = Quassel::optionValue("debug-irc-id").toInt();
45 connect(this, &IrcParser::newEvent, coreSession()->eventManager(), &EventManager::postEvent);
48 bool IrcParser::checkParamCount(const QString& cmd, const QList<QByteArray>& params, int minParams)
50 if (params.count() < minParams) {
51 qWarning() << "Expected" << minParams << "params for IRC command" << cmd << ", got:" << params;
57 QByteArray IrcParser::decrypt(Network* network, const QString& bufferName, const QByteArray& message, bool isTopic)
60 if (message.isEmpty())
63 if (!Cipher::neededFeaturesAvailable())
66 Cipher* cipher = qobject_cast<CoreNetwork*>(network)->cipher(bufferName);
67 if (!cipher || cipher->key().isEmpty())
70 return isTopic ? cipher->decryptTopic(message) : cipher->decrypt(message);
79 /* parse the raw server string and generate an appropriate event */
80 /* used to be handleServerMsg() */
81 void IrcParser::processNetworkIncoming(NetworkDataEvent* e)
83 auto* net = qobject_cast<CoreNetwork*>(e->network());
85 qWarning() << "Received network event without valid network pointer!";
89 // note that the IRC server is still alive
90 net->resetPingTimeout();
92 const QByteArray rawMsg = e->data();
93 if (rawMsg.isEmpty()) {
94 qWarning() << "Received empty string from server!";
98 // Log the message if enabled and network ID matches or allows all
99 if (_debugLogRawIrc && (_debugLogRawNetId == -1 || net->networkId().toInt() == _debugLogRawNetId)) {
100 // Include network ID
101 qDebug() << "IRC net" << net->networkId() << "<<" << rawMsg;
104 QHash<IrcTagKey, QString> tags;
107 QList<QByteArray> params;
108 IrcDecoder::parseMessage([&net](const QByteArray& data) {
109 return net->serverDecode(data);
110 }, rawMsg, tags, prefix, cmd, params);
112 QList<Event*> events;
113 EventManager::EventType type = EventManager::Invalid;
115 QString messageTarget;
116 uint num = cmd.toUInt();
119 if (params.count() == 0) {
120 qWarning() << "Message received from server violates RFC and is ignored!" << rawMsg;
123 // numeric replies have the target as first param (RFC 2812 - 2.4). this is usually our own nick. Remove this!
124 messageTarget = net->serverDecode(params.takeFirst());
125 type = EventManager::IrcEventNumeric;
128 // any other irc command
129 QString typeName = QLatin1String("IrcEvent") + cmd.at(0).toUpper() + cmd.mid(1).toLower();
130 type = EventManager::eventTypeByName(typeName);
131 if (type == EventManager::Invalid) {
132 type = EventManager::eventTypeByName("IrcEventUnknown");
133 Q_ASSERT(type != EventManager::Invalid);
137 // Almost always, all params are server-encoded. There's a few exceptions, let's catch them here!
138 // Possibly not the best option, we might want something more generic? Maybe yet another layer of
139 // unencoded events with event handlers for the exceptions...
140 // Also, PRIVMSG and NOTICE need some special handling, we put this in here as well, so we get out
141 // nice pre-parsed events that the CTCP handler can consume.
143 QStringList decParams;
144 bool defaultHandling = true; // whether to automatically copy the remaining params and send the event
147 case EventManager::IrcEventPrivmsg:
148 defaultHandling = false; // this might create a list of events
150 if (checkParamCount(cmd, params, 1)) {
151 QString senderNick = nickFromMask(prefix);
152 net->updateNickFromMask(prefix);
153 // Check if the sender is our own nick. If so, treat message as if sent by ourself.
154 // See http://ircv3.net/specs/extensions/echo-message-3.2.html
155 // Cache the result to avoid multiple redundant comparisons
156 bool isSelfMessage = net->isMyNick(senderNick);
158 QByteArray msg = params.count() < 2 ? QByteArray() : params.at(1);
160 QStringList targets = net->serverDecode(params.at(0)).split(',', QString::SkipEmptyParts);
161 QStringList::const_iterator targetIter;
162 for (targetIter = targets.constBegin(); targetIter != targets.constEnd(); ++targetIter) {
163 // For self-messages, keep the target, don't set it to the senderNick
164 QString target = net->isChannelName(*targetIter) || net->isStatusMsg(*targetIter) || isSelfMessage ? *targetIter : senderNick;
166 // Note: self-messages could be encrypted with a different key. If issues arise,
167 // consider including this within an if (!isSelfMessage) block
168 msg = decrypt(net, target, msg);
170 IrcEventRawMessage* rawMessage = new IrcEventRawMessage(EventManager::IrcEventRawPrivmsg,
177 // Self-messages need processed differently, tag as such via flag.
178 rawMessage->setFlag(EventManager::Self);
180 events << rawMessage;
185 case EventManager::IrcEventNotice:
186 defaultHandling = false;
188 if (checkParamCount(cmd, params, 2)) {
189 // Check if the sender is our own nick. If so, treat message as if sent by ourself.
190 // See http://ircv3.net/specs/extensions/echo-message-3.2.html
191 // Cache the result to avoid multiple redundant comparisons
192 bool isSelfMessage = net->isMyNick(nickFromMask(prefix));
194 QStringList targets = net->serverDecode(params.at(0)).split(',', QString::SkipEmptyParts);
195 QStringList::const_iterator targetIter;
196 for (targetIter = targets.constBegin(); targetIter != targets.constEnd(); ++targetIter) {
197 QString target = *targetIter;
199 // special treatment for welcome messages like:
200 // :ChanServ!ChanServ@services. NOTICE egst :[#apache] Welcome, this is #apache. Please read the in-channel topic message.
201 // This channel is being logged by IRSeekBot. If you have any question please see http://blog.freenode.net/?p=68
202 if (!net->isChannelName(target)) {
203 QString decMsg = net->serverDecode(params.at(1));
204 QRegExp welcomeRegExp(R"(^\[([^\]]+)\] )");
205 if (welcomeRegExp.indexIn(decMsg) != -1) {
206 QString channelname = welcomeRegExp.cap(1);
207 decMsg = decMsg.mid(welcomeRegExp.matchedLength());
208 // we only have CoreIrcChannels in the core, so this cast is safe
209 CoreIrcChannel* chan = static_cast<CoreIrcChannel*>(net->ircChannel(channelname)); // NOLINT(cppcoreguidelines-pro-type-static-cast-downcast)
210 if (chan && !chan->receivedWelcomeMsg()) {
211 chan->setReceivedWelcomeMsg();
212 events << new MessageEvent(Message::Notice, net, decMsg, prefix, channelname, Message::None, e->timestamp());
218 if (prefix.isEmpty() || target == "AUTH") {
222 if (!target.isEmpty() && net->prefixes().contains(target.at(0)))
223 target = target.mid(1);
225 if (!net->isChannelName(target)) {
226 // For self-messages, keep the target, don't set it to the sender prefix
227 if (!isSelfMessage) {
228 target = nickFromMask(prefix);
230 net->updateNickFromMask(prefix);
235 // Handle DH1080 key exchange
236 // Don't allow key exchange in channels, and don't allow it for self-messages.
237 bool keyExchangeAllowed = (!net->isChannelName(target) && !isSelfMessage);
238 if (params[1].startsWith("DH1080_INIT") && keyExchangeAllowed) {
239 events << new KeyEvent(EventManager::KeyEvent, net, prefix, target, KeyEvent::Init, params[1].mid(12));
241 else if (params[1].startsWith("DH1080_FINISH") && keyExchangeAllowed) {
242 events << new KeyEvent(EventManager::KeyEvent, net, prefix, target, KeyEvent::Finish, params[1].mid(14));
247 IrcEventRawMessage* rawMessage = new IrcEventRawMessage(EventManager::IrcEventRawNotice,
254 // Self-messages need processed differently, tag as such via flag.
255 rawMessage->setFlag(EventManager::Self);
257 events << rawMessage;
263 // the following events need only special casing for param decoding
264 case EventManager::IrcEventKick:
265 if (params.count() >= 3) { // we have a reason
266 decParams << net->serverDecode(params.at(0)) << net->serverDecode(params.at(1));
267 decParams << net->channelDecode(decParams.first(), params.at(2)); // kick reason
271 case EventManager::IrcEventPart:
272 if (params.count() >= 2) {
273 QString channel = net->serverDecode(params.at(0));
274 decParams << channel;
275 decParams << net->userDecode(nickFromMask(prefix), params.at(1));
276 net->updateNickFromMask(prefix);
280 case EventManager::IrcEventQuit:
281 if (params.count() >= 1) {
282 decParams << net->userDecode(nickFromMask(prefix), params.at(0));
283 net->updateNickFromMask(prefix);
287 case EventManager::IrcEventTopic:
288 if (params.count() >= 1) {
289 QString channel = net->serverDecode(params.at(0));
290 decParams << channel;
291 decParams << (params.count() >= 2 ? net->channelDecode(channel, decrypt(net, channel, params.at(1), true)) : QString());
295 case EventManager::IrcEventAway: {
296 // Update hostmask info first. This will create the nick if it doesn't exist, e.g.
297 // away-notify data being sent before JOIN messages.
298 net->updateNickFromMask(prefix);
299 // Separate nick in order to separate server and user decoding
300 QString nick = nickFromMask(prefix);
302 decParams << (params.count() >= 1 ? net->userDecode(nick, params.at(0)) : QString());
305 case EventManager::IrcEventNumeric:
307 case 301: /* RPL_AWAY */
308 if (params.count() >= 2) {
309 QString nick = net->serverDecode(params.at(0));
311 decParams << net->userDecode(nick, params.at(1));
315 case 332: /* RPL_TOPIC */
316 if (params.count() >= 2) {
317 QString channel = net->serverDecode(params.at(0));
318 decParams << channel;
319 decParams << net->channelDecode(channel, decrypt(net, channel, params.at(1), true));
323 case 333: /* Topic set by... */
324 if (params.count() >= 3) {
325 QString channel = net->serverDecode(params.at(0));
326 decParams << channel << net->serverDecode(params.at(1));
327 decParams << net->channelDecode(channel, params.at(2));
330 case 451: /* You have not registered... */
331 if (messageTarget.compare("CAP", Qt::CaseInsensitive) == 0) {
332 // :irc.server.com 451 CAP :You have not registered
333 // If server doesn't support capabilities, it will report this message. Turn it
334 // into a nicer message since it's not a real error.
335 defaultHandling = false;
336 events << new MessageEvent(Message::Server,
338 tr("Capability negotiation not supported"),
351 if (defaultHandling && type != EventManager::Invalid) {
352 for (int i = decParams.count(); i < params.count(); i++)
353 decParams << net->serverDecode(params.at(i));
355 // We want to trim the last param just in case, except for PRIVMSG and NOTICE
356 // ... but those happen to be the only ones not using defaultHandling anyway
357 if (!decParams.isEmpty() && decParams.last().endsWith(' '))
358 decParams.append(decParams.takeLast().trimmed());
361 if (type == EventManager::IrcEventNumeric)
362 event = new IrcEventNumeric(num, net, prefix, messageTarget);
364 event = new IrcEvent(type, net, prefix);
365 event->setParams(decParams);
366 event->setTimestamp(e->timestamp());
370 foreach (Event* event, events) {
371 emit newEvent(event);