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"
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();
46 connect(this, &IrcParser::newEvent, coreSession()->eventManager(), &EventManager::postEvent);
49 bool IrcParser::checkParamCount(const QString& cmd, const QList<QByteArray>& params, int minParams)
51 if (params.count() < minParams) {
52 qWarning() << "Expected" << minParams << "params for IRC command" << cmd << ", got:" << params;
58 QByteArray IrcParser::decrypt(Network* network, const QString& bufferName, const QByteArray& message, bool isTopic)
61 if (message.isEmpty())
64 if (!Cipher::neededFeaturesAvailable())
67 Cipher* cipher = qobject_cast<CoreNetwork*>(network)->cipher(bufferName);
68 if (!cipher || cipher->key().isEmpty())
71 return isTopic ? cipher->decryptTopic(message) : cipher->decrypt(message);
80 /* parse the raw server string and generate an appropriate event */
81 /* used to be handleServerMsg() */
82 void IrcParser::processNetworkIncoming(NetworkDataEvent* e)
84 auto* net = qobject_cast<CoreNetwork*>(e->network());
86 qWarning() << "Received network event without valid network pointer!";
90 // note that the IRC server is still alive
91 net->resetPingTimeout();
93 const QByteArray rawMsg = e->data();
94 if (rawMsg.isEmpty()) {
95 qWarning() << "Received empty string from server!";
99 // Log the message if enabled and network ID matches or allows all
100 if (_debugLogRawIrc && (_debugLogRawNetId == -1 || net->networkId().toInt() == _debugLogRawNetId)) {
101 // Include network ID
102 qDebug() << "IRC net" << net->networkId() << "<<" << rawMsg;
105 QHash<IrcTagKey, QString> tags;
108 QList<QByteArray> params;
109 IrcDecoder::parseMessage([&net](const QByteArray& data) {
110 return net->serverDecode(data);
111 }, rawMsg, tags, prefix, cmd, params);
113 QList<Event*> events;
114 EventManager::EventType type = EventManager::Invalid;
116 QString messageTarget;
117 uint num = cmd.toUInt();
120 if (params.count() == 0) {
121 qWarning() << "Message received from server violates RFC and is ignored!" << rawMsg;
124 // numeric replies have the target as first param (RFC 2812 - 2.4). this is usually our own nick. Remove this!
125 messageTarget = net->serverDecode(params.takeFirst());
126 type = EventManager::IrcEventNumeric;
129 // any other irc command
130 QString typeName = QLatin1String("IrcEvent") + cmd.at(0).toUpper() + cmd.mid(1).toLower();
131 type = EventManager::eventTypeByName(typeName);
132 if (type == EventManager::Invalid) {
133 type = EventManager::eventTypeByName("IrcEventUnknown");
134 Q_ASSERT(type != EventManager::Invalid);
138 // Almost always, all params are server-encoded. There's a few exceptions, let's catch them here!
139 // Possibly not the best option, we might want something more generic? Maybe yet another layer of
140 // unencoded events with event handlers for the exceptions...
141 // Also, PRIVMSG and NOTICE need some special handling, we put this in here as well, so we get out
142 // nice pre-parsed events that the CTCP handler can consume.
144 QStringList decParams;
145 bool defaultHandling = true; // whether to automatically copy the remaining params and send the event
148 case EventManager::IrcEventPrivmsg:
149 defaultHandling = false; // this might create a list of events
151 if (checkParamCount(cmd, params, 1)) {
152 QString senderNick = nickFromMask(prefix);
153 net->updateNickFromMask(prefix);
154 // Check if the sender is our own nick. If so, treat message as if sent by ourself.
155 // See http://ircv3.net/specs/extensions/echo-message-3.2.html
156 // Cache the result to avoid multiple redundant comparisons
157 bool isSelfMessage = net->isMyNick(senderNick);
159 QByteArray msg = params.count() < 2 ? QByteArray() : params.at(1);
161 QStringList targets = net->serverDecode(params.at(0)).split(',', QString::SkipEmptyParts);
162 QStringList::const_iterator targetIter;
163 for (targetIter = targets.constBegin(); targetIter != targets.constEnd(); ++targetIter) {
164 // For self-messages, keep the target, don't set it to the senderNick
165 QString target = net->isChannelName(*targetIter) || net->isStatusMsg(*targetIter) || isSelfMessage ? *targetIter : senderNick;
167 // Note: self-messages could be encrypted with a different key. If issues arise,
168 // consider including this within an if (!isSelfMessage) block
169 msg = decrypt(net, target, msg);
171 IrcEventRawMessage* rawMessage = new IrcEventRawMessage(EventManager::IrcEventRawPrivmsg,
178 // Self-messages need processed differently, tag as such via flag.
179 rawMessage->setFlag(EventManager::Self);
181 events << rawMessage;
186 case EventManager::IrcEventNotice:
187 defaultHandling = false;
189 if (checkParamCount(cmd, params, 2)) {
190 // Check if the sender is our own nick. If so, treat message as if sent by ourself.
191 // See http://ircv3.net/specs/extensions/echo-message-3.2.html
192 // Cache the result to avoid multiple redundant comparisons
193 bool isSelfMessage = net->isMyNick(nickFromMask(prefix));
195 QStringList targets = net->serverDecode(params.at(0)).split(',', QString::SkipEmptyParts);
196 QStringList::const_iterator targetIter;
197 for (targetIter = targets.constBegin(); targetIter != targets.constEnd(); ++targetIter) {
198 QString target = *targetIter;
200 // special treatment for welcome messages like:
201 // :ChanServ!ChanServ@services. NOTICE egst :[#apache] Welcome, this is #apache. Please read the in-channel topic message.
202 // This channel is being logged by IRSeekBot. If you have any question please see http://blog.freenode.net/?p=68
203 if (!net->isChannelName(target)) {
204 QString decMsg = net->serverDecode(params.at(1));
205 QRegExp welcomeRegExp(R"(^\[([^\]]+)\] )");
206 if (welcomeRegExp.indexIn(decMsg) != -1) {
207 QString channelname = welcomeRegExp.cap(1);
208 decMsg = decMsg.mid(welcomeRegExp.matchedLength());
209 // we only have CoreIrcChannels in the core, so this cast is safe
210 CoreIrcChannel* chan = static_cast<CoreIrcChannel*>(net->ircChannel(channelname)); // NOLINT(cppcoreguidelines-pro-type-static-cast-downcast)
211 if (chan && !chan->receivedWelcomeMsg()) {
212 chan->setReceivedWelcomeMsg();
213 events << new MessageEvent(Message::Notice, net, decMsg, prefix, channelname, Message::None, e->timestamp());
219 if (prefix.isEmpty() || target == "AUTH") {
223 if (!target.isEmpty() && net->prefixes().contains(target.at(0)))
224 target = target.mid(1);
226 if (!net->isChannelName(target)) {
227 // For self-messages, keep the target, don't set it to the sender prefix
228 if (!isSelfMessage) {
229 target = nickFromMask(prefix);
231 net->updateNickFromMask(prefix);
236 // Handle DH1080 key exchange
237 // Don't allow key exchange in channels, and don't allow it for self-messages.
238 bool keyExchangeAllowed = (!net->isChannelName(target) && !isSelfMessage);
239 if (params[1].startsWith("DH1080_INIT") && keyExchangeAllowed) {
240 events << new KeyEvent(EventManager::KeyEvent, net, prefix, target, KeyEvent::Init, params[1].mid(12));
242 else if (params[1].startsWith("DH1080_FINISH") && keyExchangeAllowed) {
243 events << new KeyEvent(EventManager::KeyEvent, net, prefix, target, KeyEvent::Finish, params[1].mid(14));
248 IrcEventRawMessage* rawMessage = new IrcEventRawMessage(EventManager::IrcEventRawNotice,
255 // Self-messages need processed differently, tag as such via flag.
256 rawMessage->setFlag(EventManager::Self);
258 events << rawMessage;
264 // the following events need only special casing for param decoding
265 case EventManager::IrcEventKick:
266 if (params.count() >= 3) { // we have a reason
267 decParams << net->serverDecode(params.at(0)) << net->serverDecode(params.at(1));
268 decParams << net->channelDecode(decParams.first(), params.at(2)); // kick reason
272 case EventManager::IrcEventPart:
273 if (params.count() >= 2) {
274 QString channel = net->serverDecode(params.at(0));
275 decParams << channel;
276 decParams << net->userDecode(nickFromMask(prefix), params.at(1));
277 net->updateNickFromMask(prefix);
281 case EventManager::IrcEventQuit:
282 if (params.count() >= 1) {
283 decParams << net->userDecode(nickFromMask(prefix), params.at(0));
284 net->updateNickFromMask(prefix);
288 case EventManager::IrcEventTopic:
289 if (params.count() >= 1) {
290 QString channel = net->serverDecode(params.at(0));
291 decParams << channel;
292 decParams << (params.count() >= 2 ? net->channelDecode(channel, decrypt(net, channel, params.at(1), true)) : QString());
296 case EventManager::IrcEventAway: {
297 // Update hostmask info first. This will create the nick if it doesn't exist, e.g.
298 // away-notify data being sent before JOIN messages.
299 net->updateNickFromMask(prefix);
300 // Separate nick in order to separate server and user decoding
301 QString nick = nickFromMask(prefix);
303 decParams << (params.count() >= 1 ? net->userDecode(nick, params.at(0)) : QString());
306 case EventManager::IrcEventNumeric:
308 case 301: /* RPL_AWAY */
309 if (params.count() >= 2) {
310 QString nick = net->serverDecode(params.at(0));
312 decParams << net->userDecode(nick, params.at(1));
316 case 332: /* RPL_TOPIC */
317 if (params.count() >= 2) {
318 QString channel = net->serverDecode(params.at(0));
319 decParams << channel;
320 decParams << net->channelDecode(channel, decrypt(net, channel, params.at(1), true));
324 case 333: /* Topic set by... */
325 if (params.count() >= 3) {
326 QString channel = net->serverDecode(params.at(0));
327 decParams << channel << net->serverDecode(params.at(1));
328 decParams << net->channelDecode(channel, params.at(2));
331 case 451: /* You have not registered... */
332 if (messageTarget.compare("CAP", Qt::CaseInsensitive) == 0) {
333 // :irc.server.com 451 CAP :You have not registered
334 // If server doesn't support capabilities, it will report this message. Turn it
335 // into a nicer message since it's not a real error.
336 defaultHandling = false;
337 events << new MessageEvent(Message::Server,
339 tr("Capability negotiation not supported"),
352 if (defaultHandling && type != EventManager::Invalid) {
353 for (int i = decParams.count(); i < params.count(); i++)
354 decParams << net->serverDecode(params.at(i));
356 // We want to trim the last param just in case, except for PRIVMSG and NOTICE
357 // ... but those happen to be the only ones not using defaultHandling anyway
358 if (!decParams.isEmpty() && decParams.last().endsWith(' '))
359 decParams.append(decParams.takeLast().trimmed());
362 if (type == EventManager::IrcEventNumeric)
363 event = new IrcEventNumeric(num, net, prefix, messageTarget);
365 event = new IrcEvent(type, net, prefix);
366 event->setParams(decParams);
367 event->setTimestamp(e->timestamp());
371 foreach (Event* event, events) {
372 emit newEvent(event);