1 /***************************************************************************
2 * Copyright (C) 2005-2020 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"
30 #include "messageevent.h"
31 #include "networkevent.h"
35 # include "keyevent.h"
38 IrcParser::IrcParser(CoreSession* session)
40 , _coreSession(session)
42 // Check if raw IRC logging is enabled
43 _debugLogRawIrc = (Quassel::isOptionSet("debug-irc") || Quassel::isOptionSet("debug-irc-id"));
44 _debugLogRawNetId = Quassel::optionValue("debug-irc-id").toInt();
45 // Check if parsed IRC logging is enabled
46 _debugLogParsedIrc = (Quassel::isOptionSet("debug-irc-parsed") || Quassel::isOptionSet("debug-irc-parsed-id"));
47 _debugLogParsedNetId = Quassel::optionValue("debug-irc-parsed-id").toInt();
49 connect(this, &IrcParser::newEvent, coreSession()->eventManager(), &EventManager::postEvent);
52 bool IrcParser::checkParamCount(const QString& cmd, const QList<QByteArray>& params, int minParams)
54 if (params.count() < minParams) {
55 qWarning() << "Expected" << minParams << "params for IRC command" << cmd << ", got:" << params;
61 QByteArray IrcParser::decrypt(Network* network, const QString& bufferName, const QByteArray& message, bool isTopic)
64 if (message.isEmpty())
67 if (!Cipher::neededFeaturesAvailable())
70 Cipher* cipher = qobject_cast<CoreNetwork*>(network)->cipher(bufferName);
71 if (!cipher || cipher->key().isEmpty())
74 return isTopic ? cipher->decryptTopic(message) : cipher->decrypt(message);
83 /* parse the raw server string and generate an appropriate event */
84 /* used to be handleServerMsg() */
85 void IrcParser::processNetworkIncoming(NetworkDataEvent* e)
87 auto* net = qobject_cast<CoreNetwork*>(e->network());
89 qWarning() << "Received network event without valid network pointer!";
93 // note that the IRC server is still alive
94 net->resetPingTimeout();
96 const QByteArray rawMsg = e->data();
97 if (rawMsg.isEmpty()) {
98 qWarning() << "Received empty string from server!";
102 // Log the message if enabled and network ID matches or allows all
103 if (_debugLogRawIrc && (_debugLogRawNetId == -1 || net->networkId().toInt() == _debugLogRawNetId)) {
104 // Include network ID
105 qDebug() << "IRC net" << net->networkId() << "<<" << rawMsg;
108 QHash<IrcTagKey, QString> tags;
111 QList<QByteArray> params;
112 IrcDecoder::parseMessage([&net](const QByteArray& data) {
113 return net->serverDecode(data);
114 }, rawMsg, tags, prefix, cmd, params);
116 // Log the message if enabled and network ID matches or allows all
117 if (_debugLogParsedIrc && (_debugLogParsedNetId == -1 || net->networkId().toInt() == _debugLogParsedNetId)) {
118 // Include network ID
119 qDebug() << "IRC net" << net->networkId() << "<<" << tags << prefix << cmd << params;
122 if (net->capEnabled(IrcCap::SERVER_TIME) && tags.contains(IrcTags::SERVER_TIME)) {
123 QDateTime serverTime = QDateTime::fromString(tags[IrcTags::SERVER_TIME], "yyyy-MM-ddThh:mm:ss.zzzZ");
124 serverTime.setTimeSpec(Qt::UTC);
125 if (serverTime.isValid()) {
126 e->setTimestamp(serverTime);
128 qDebug() << "Invalid timestamp from server-time tag:" << tags[IrcTags::SERVER_TIME];
132 QList<Event*> events;
133 EventManager::EventType type = EventManager::Invalid;
135 QString messageTarget;
136 uint num = cmd.toUInt();
139 if (params.count() == 0) {
140 qWarning() << "Message received from server violates RFC and is ignored!" << rawMsg;
143 // numeric replies have the target as first param (RFC 2812 - 2.4). this is usually our own nick. Remove this!
144 messageTarget = net->serverDecode(params.takeFirst());
145 type = EventManager::IrcEventNumeric;
148 // any other irc command
149 QString typeName = QLatin1String("IrcEvent") + cmd.at(0).toUpper() + cmd.mid(1).toLower();
150 type = EventManager::eventTypeByName(typeName);
151 if (type == EventManager::Invalid) {
152 type = EventManager::eventTypeByName("IrcEventUnknown");
153 Q_ASSERT(type != EventManager::Invalid);
157 // Almost always, all params are server-encoded. There's a few exceptions, let's catch them here!
158 // Possibly not the best option, we might want something more generic? Maybe yet another layer of
159 // unencoded events with event handlers for the exceptions...
160 // Also, PRIVMSG and NOTICE need some special handling, we put this in here as well, so we get out
161 // nice pre-parsed events that the CTCP handler can consume.
163 QStringList decParams;
164 bool defaultHandling = true; // whether to automatically copy the remaining params and send the event
167 case EventManager::IrcEventPrivmsg:
168 defaultHandling = false; // this might create a list of events
170 if (checkParamCount(cmd, params, 1)) {
171 QString senderNick = nickFromMask(prefix);
172 net->updateNickFromMask(prefix);
173 // Check if the sender is our own nick. If so, treat message as if sent by ourself.
174 // See http://ircv3.net/specs/extensions/echo-message-3.2.html
175 // Cache the result to avoid multiple redundant comparisons
176 bool isSelfMessage = net->isMyNick(senderNick);
178 QByteArray msg = params.count() < 2 ? QByteArray() : params.at(1);
180 QStringList targets = net->serverDecode(params.at(0)).split(',', QString::SkipEmptyParts);
181 QStringList::const_iterator targetIter;
182 for (targetIter = targets.constBegin(); targetIter != targets.constEnd(); ++targetIter) {
183 // For self-messages, keep the target, don't set it to the senderNick
184 QString target = net->isChannelName(*targetIter) || net->isStatusMsg(*targetIter) || isSelfMessage ? *targetIter : senderNick;
186 // Note: self-messages could be encrypted with a different key. If issues arise,
187 // consider including this within an if (!isSelfMessage) block
188 msg = decrypt(net, target, msg);
190 IrcEventRawMessage* rawMessage = new IrcEventRawMessage(EventManager::IrcEventRawPrivmsg,
198 // Self-messages need processed differently, tag as such via flag.
199 rawMessage->setFlag(EventManager::Self);
201 events << rawMessage;
206 case EventManager::IrcEventNotice:
207 defaultHandling = false;
209 if (checkParamCount(cmd, params, 2)) {
210 // Check if the sender is our own nick. If so, treat message as if sent by ourself.
211 // See http://ircv3.net/specs/extensions/echo-message-3.2.html
212 // Cache the result to avoid multiple redundant comparisons
213 bool isSelfMessage = net->isMyNick(nickFromMask(prefix));
215 QStringList targets = net->serverDecode(params.at(0)).split(',', QString::SkipEmptyParts);
216 QStringList::const_iterator targetIter;
217 for (targetIter = targets.constBegin(); targetIter != targets.constEnd(); ++targetIter) {
218 QString target = *targetIter;
220 // special treatment for welcome messages like:
221 // :ChanServ!ChanServ@services. NOTICE egst :[#apache] Welcome, this is #apache. Please read the in-channel topic message.
222 // This channel is being logged by IRSeekBot. If you have any question please see http://blog.freenode.net/?p=68
223 if (!net->isChannelName(target)) {
224 QString decMsg = net->serverDecode(params.at(1));
225 QRegExp welcomeRegExp(R"(^\[([^\]]+)\] )");
226 if (welcomeRegExp.indexIn(decMsg) != -1) {
227 QString channelname = welcomeRegExp.cap(1);
228 decMsg = decMsg.mid(welcomeRegExp.matchedLength());
229 // we only have CoreIrcChannels in the core, so this cast is safe
230 CoreIrcChannel* chan = static_cast<CoreIrcChannel*>(net->ircChannel(channelname)); // NOLINT(cppcoreguidelines-pro-type-static-cast-downcast)
231 if (chan && !chan->receivedWelcomeMsg()) {
232 chan->setReceivedWelcomeMsg();
233 events << new MessageEvent(Message::Notice, net, decMsg, prefix, channelname, Message::None, e->timestamp());
239 if (prefix.isEmpty() || target == "AUTH") {
243 if (!target.isEmpty() && net->prefixes().contains(target.at(0)))
244 target = target.mid(1);
246 if (!net->isChannelName(target)) {
247 // For self-messages, keep the target, don't set it to the sender prefix
248 if (!isSelfMessage) {
249 target = nickFromMask(prefix);
251 net->updateNickFromMask(prefix);
256 // Handle DH1080 key exchange
257 // Don't allow key exchange in channels, and don't allow it for self-messages.
258 bool keyExchangeAllowed = (!net->isChannelName(target) && !isSelfMessage);
259 if (params[1].startsWith("DH1080_INIT") && keyExchangeAllowed) {
260 events << new KeyEvent(EventManager::KeyEvent, net, tags, prefix, target, KeyEvent::Init, params[1].mid(12));
262 else if (params[1].startsWith("DH1080_FINISH") && keyExchangeAllowed) {
263 events << new KeyEvent(EventManager::KeyEvent, net, tags, prefix, target, KeyEvent::Finish, params[1].mid(14));
268 IrcEventRawMessage* rawMessage = new IrcEventRawMessage(EventManager::IrcEventRawNotice,
276 // Self-messages need processed differently, tag as such via flag.
277 rawMessage->setFlag(EventManager::Self);
279 events << rawMessage;
285 // the following events need only special casing for param decoding
286 case EventManager::IrcEventKick:
287 if (params.count() >= 3) { // we have a reason
288 decParams << net->serverDecode(params.at(0)) << net->serverDecode(params.at(1));
289 decParams << net->channelDecode(decParams.first(), params.at(2)); // kick reason
293 case EventManager::IrcEventPart:
294 if (params.count() >= 2) {
295 QString channel = net->serverDecode(params.at(0));
296 decParams << channel;
297 decParams << net->userDecode(nickFromMask(prefix), params.at(1));
298 net->updateNickFromMask(prefix);
302 case EventManager::IrcEventQuit:
303 if (params.count() >= 1) {
304 decParams << net->userDecode(nickFromMask(prefix), params.at(0));
305 net->updateNickFromMask(prefix);
309 case EventManager::IrcEventTagmsg:
310 defaultHandling = false; // this might create a list of events
312 if (checkParamCount(cmd, params, 1)) {
313 QString senderNick = nickFromMask(prefix);
314 net->updateNickFromMask(prefix);
315 // Check if the sender is our own nick. If so, treat message as if sent by ourself.
316 // See http://ircv3.net/specs/extensions/echo-message-3.2.html
317 // Cache the result to avoid multiple redundant comparisons
318 bool isSelfMessage = net->isMyNick(senderNick);
320 QStringList targets = net->serverDecode(params.at(0)).split(',', QString::SkipEmptyParts);
321 QStringList::const_iterator targetIter;
322 for (targetIter = targets.constBegin(); targetIter != targets.constEnd(); ++targetIter) {
323 // For self-messages, keep the target, don't set it to the senderNick
324 QString target = net->isChannelName(*targetIter) || net->isStatusMsg(*targetIter) || isSelfMessage ? *targetIter : senderNick;
326 IrcEvent* tagMsg = new IrcEvent(EventManager::IrcEventTagmsg, net, tags, prefix, {target});
328 // Self-messages need processed differently, tag as such via flag.
329 tagMsg->setFlag(EventManager::Self);
331 tagMsg->setTimestamp(e->timestamp());
337 case EventManager::IrcEventTopic:
338 if (params.count() >= 1) {
339 QString channel = net->serverDecode(params.at(0));
340 decParams << channel;
341 decParams << (params.count() >= 2 ? net->channelDecode(channel, decrypt(net, channel, params.at(1), true)) : QString());
345 case EventManager::IrcEventAway:
347 // Update hostmask info first. This will create the nick if it doesn't exist, e.g.
348 // away-notify data being sent before JOIN messages.
349 net->updateNickFromMask(prefix);
350 // Separate nick in order to separate server and user decoding
351 QString nick = nickFromMask(prefix);
353 decParams << (params.count() >= 1 ? net->userDecode(nick, params.at(0)) : QString());
357 case EventManager::IrcEventNumeric:
359 case 301: /* RPL_AWAY */
360 if (params.count() >= 2) {
361 QString nick = net->serverDecode(params.at(0));
363 decParams << net->userDecode(nick, params.at(1));
367 case 332: /* RPL_TOPIC */
368 if (params.count() >= 2) {
369 QString channel = net->serverDecode(params.at(0));
370 decParams << channel;
371 decParams << net->channelDecode(channel, decrypt(net, channel, params.at(1), true));
375 case 333: /* Topic set by... */
376 if (params.count() >= 3) {
377 QString channel = net->serverDecode(params.at(0));
378 decParams << channel << net->serverDecode(params.at(1));
379 decParams << net->channelDecode(channel, params.at(2));
382 case 451: /* You have not registered... */
383 if (messageTarget.compare("CAP", Qt::CaseInsensitive) == 0) {
384 // :irc.server.com 451 CAP :You have not registered
385 // If server doesn't support capabilities, it will report this message. Turn it
386 // into a nicer message since it's not a real error.
387 defaultHandling = false;
388 events << new MessageEvent(Message::Server,
390 tr("Capability negotiation not supported"),
403 if (defaultHandling && type != EventManager::Invalid) {
404 for (int i = decParams.count(); i < params.count(); i++)
405 decParams << net->serverDecode(params.at(i));
407 // We want to trim the last param just in case, except for PRIVMSG and NOTICE
408 // ... but those happen to be the only ones not using defaultHandling anyway
409 if (!decParams.isEmpty() && decParams.last().endsWith(' '))
410 decParams.append(decParams.takeLast().trimmed());
413 if (type == EventManager::IrcEventNumeric)
414 event = new IrcEventNumeric(num, net, tags, prefix, messageTarget);
416 event = new IrcEvent(type, net, tags, prefix);
417 event->setParams(decParams);
418 event->setTimestamp(e->timestamp());
422 for (Event* event : events) {
423 emit newEvent(event);