core: Remove slots from storage APIs
[quassel.git] / src / core / ircparser.cpp
1 /***************************************************************************
2  *   Copyright (C) 2005-2020 by the Quassel Project                        *
3  *   devel@quassel-irc.org                                                 *
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) version 3.                                           *
9  *                                                                         *
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.                          *
14  *                                                                         *
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  ***************************************************************************/
20
21 #include "ircparser.h"
22
23 #include <QDebug>
24
25 #include "corenetwork.h"
26 #include "eventmanager.h"
27 #include "ircdecoder.h"
28 #include "ircevent.h"
29 #include "irctags.h"
30 #include "messageevent.h"
31 #include "networkevent.h"
32
33 #ifdef HAVE_QCA2
34 #    include "cipher.h"
35 #    include "keyevent.h"
36 #endif
37
38 IrcParser::IrcParser(CoreSession* session)
39     : QObject(session)
40     , _coreSession(session)
41 {
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();
48
49     connect(this, &IrcParser::newEvent, coreSession()->eventManager(), &EventManager::postEvent);
50 }
51
52 bool IrcParser::checkParamCount(const QString& cmd, const QList<QByteArray>& params, int minParams)
53 {
54     if (params.count() < minParams) {
55         qWarning() << "Expected" << minParams << "params for IRC command" << cmd << ", got:" << params;
56         return false;
57     }
58     return true;
59 }
60
61 QByteArray IrcParser::decrypt(Network* network, const QString& bufferName, const QByteArray& message, bool isTopic)
62 {
63 #ifdef HAVE_QCA2
64     if (message.isEmpty())
65         return message;
66
67     if (!Cipher::neededFeaturesAvailable())
68         return message;
69
70     Cipher* cipher = qobject_cast<CoreNetwork*>(network)->cipher(bufferName);
71     if (!cipher || cipher->key().isEmpty())
72         return message;
73
74     return isTopic ? cipher->decryptTopic(message) : cipher->decrypt(message);
75 #else
76     Q_UNUSED(network);
77     Q_UNUSED(bufferName);
78     Q_UNUSED(isTopic);
79     return message;
80 #endif
81 }
82
83 /* parse the raw server string and generate an appropriate event */
84 /* used to be handleServerMsg()                                  */
85 void IrcParser::processNetworkIncoming(NetworkDataEvent* e)
86 {
87     auto* net = qobject_cast<CoreNetwork*>(e->network());
88     if (!net) {
89         qWarning() << "Received network event without valid network pointer!";
90         return;
91     }
92
93     // note that the IRC server is still alive
94     net->resetPingTimeout();
95
96     const QByteArray rawMsg = e->data();
97     if (rawMsg.isEmpty()) {
98         qWarning() << "Received empty string from server!";
99         return;
100     }
101
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;
106     }
107
108     QHash<IrcTagKey, QString> tags;
109     QString prefix;
110     QString cmd;
111     QList<QByteArray> params;
112     IrcDecoder::parseMessage([&net](const QByteArray& data) {
113         return net->serverDecode(data);
114     }, rawMsg, tags, prefix, cmd, params);
115
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;
120     }
121
122     IrcTagKey serverTimeTag{"", "time", false};
123     if (tags.contains(serverTimeTag)) {
124         QDateTime serverTime = QDateTime::fromString(tags[serverTimeTag], "yyyy-MM-ddThh:mm:ss.zzzZ");
125         serverTime.setTimeSpec(Qt::UTC);
126         if (serverTime.isValid()) {
127             e->setTimestamp(serverTime);
128         } else {
129             qDebug() << "Invalid timestamp from server-time tag:" << tags[serverTimeTag];
130         }
131     }
132
133     QList<Event*> events;
134     EventManager::EventType type = EventManager::Invalid;
135
136     QString messageTarget;
137     uint num = cmd.toUInt();
138     if (num > 0) {
139         // numeric reply
140         if (params.count() == 0) {
141             qWarning() << "Message received from server violates RFC and is ignored!" << rawMsg;
142             return;
143         }
144         // numeric replies have the target as first param (RFC 2812 - 2.4). this is usually our own nick. Remove this!
145         messageTarget = net->serverDecode(params.takeFirst());
146         type = EventManager::IrcEventNumeric;
147     }
148     else {
149         // any other irc command
150         QString typeName = QLatin1String("IrcEvent") + cmd.at(0).toUpper() + cmd.mid(1).toLower();
151         type = EventManager::eventTypeByName(typeName);
152         if (type == EventManager::Invalid) {
153             type = EventManager::eventTypeByName("IrcEventUnknown");
154             Q_ASSERT(type != EventManager::Invalid);
155         }
156     }
157
158     // Almost always, all params are server-encoded. There's a few exceptions, let's catch them here!
159     // Possibly not the best option, we might want something more generic? Maybe yet another layer of
160     // unencoded events with event handlers for the exceptions...
161     // Also, PRIVMSG and NOTICE need some special handling, we put this in here as well, so we get out
162     // nice pre-parsed events that the CTCP handler can consume.
163
164     QStringList decParams;
165     bool defaultHandling = true;  // whether to automatically copy the remaining params and send the event
166
167     switch (type) {
168     case EventManager::IrcEventPrivmsg:
169         defaultHandling = false;  // this might create a list of events
170
171         if (checkParamCount(cmd, params, 1)) {
172             QString senderNick = nickFromMask(prefix);
173             net->updateNickFromMask(prefix);
174             // Check if the sender is our own nick.  If so, treat message as if sent by ourself.
175             // See http://ircv3.net/specs/extensions/echo-message-3.2.html
176             // Cache the result to avoid multiple redundant comparisons
177             bool isSelfMessage = net->isMyNick(senderNick);
178
179             QByteArray msg = params.count() < 2 ? QByteArray() : params.at(1);
180
181             QStringList targets = net->serverDecode(params.at(0)).split(',', QString::SkipEmptyParts);
182             QStringList::const_iterator targetIter;
183             for (targetIter = targets.constBegin(); targetIter != targets.constEnd(); ++targetIter) {
184                 // For self-messages, keep the target, don't set it to the senderNick
185                 QString target = net->isChannelName(*targetIter) || net->isStatusMsg(*targetIter) || isSelfMessage ? *targetIter : senderNick;
186
187                 // Note: self-messages could be encrypted with a different key.  If issues arise,
188                 // consider including this within an if (!isSelfMessage) block
189                 msg = decrypt(net, target, msg);
190
191                 IrcEventRawMessage* rawMessage = new IrcEventRawMessage(EventManager::IrcEventRawPrivmsg,
192                                                                         net,
193                                                                         tags,
194                                                                         msg,
195                                                                         prefix,
196                                                                         target,
197                                                                         e->timestamp());
198                 if (isSelfMessage) {
199                     // Self-messages need processed differently, tag as such via flag.
200                     rawMessage->setFlag(EventManager::Self);
201                 }
202                 events << rawMessage;
203             }
204         }
205         break;
206
207     case EventManager::IrcEventNotice:
208         defaultHandling = false;
209
210         if (checkParamCount(cmd, params, 2)) {
211             // Check if the sender is our own nick.  If so, treat message as if sent by ourself.
212             // See http://ircv3.net/specs/extensions/echo-message-3.2.html
213             // Cache the result to avoid multiple redundant comparisons
214             bool isSelfMessage = net->isMyNick(nickFromMask(prefix));
215
216             QStringList targets = net->serverDecode(params.at(0)).split(',', QString::SkipEmptyParts);
217             QStringList::const_iterator targetIter;
218             for (targetIter = targets.constBegin(); targetIter != targets.constEnd(); ++targetIter) {
219                 QString target = *targetIter;
220
221                 // special treatment for welcome messages like:
222                 // :ChanServ!ChanServ@services. NOTICE egst :[#apache] Welcome, this is #apache. Please read the in-channel topic message.
223                 // This channel is being logged by IRSeekBot. If you have any question please see http://blog.freenode.net/?p=68
224                 if (!net->isChannelName(target)) {
225                     QString decMsg = net->serverDecode(params.at(1));
226                     QRegExp welcomeRegExp(R"(^\[([^\]]+)\] )");
227                     if (welcomeRegExp.indexIn(decMsg) != -1) {
228                         QString channelname = welcomeRegExp.cap(1);
229                         decMsg = decMsg.mid(welcomeRegExp.matchedLength());
230                         // we only have CoreIrcChannels in the core, so this cast is safe
231                         CoreIrcChannel* chan = static_cast<CoreIrcChannel*>(net->ircChannel(channelname)); // NOLINT(cppcoreguidelines-pro-type-static-cast-downcast)
232                         if (chan && !chan->receivedWelcomeMsg()) {
233                             chan->setReceivedWelcomeMsg();
234                             events << new MessageEvent(Message::Notice, net, decMsg, prefix, channelname, Message::None, e->timestamp());
235                             continue;
236                         }
237                     }
238                 }
239
240                 if (prefix.isEmpty() || target == "AUTH") {
241                     target = QString();
242                 }
243                 else {
244                     if (!target.isEmpty() && net->prefixes().contains(target.at(0)))
245                         target = target.mid(1);
246
247                     if (!net->isChannelName(target)) {
248                         // For self-messages, keep the target, don't set it to the sender prefix
249                         if (!isSelfMessage) {
250                             target = nickFromMask(prefix);
251                         }
252                         net->updateNickFromMask(prefix);
253                     }
254                 }
255
256 #ifdef HAVE_QCA2
257                 // Handle DH1080 key exchange
258                 // Don't allow key exchange in channels, and don't allow it for self-messages.
259                 bool keyExchangeAllowed = (!net->isChannelName(target) && !isSelfMessage);
260                 if (params[1].startsWith("DH1080_INIT") && keyExchangeAllowed) {
261                     events << new KeyEvent(EventManager::KeyEvent, net, tags, prefix, target, KeyEvent::Init, params[1].mid(12));
262                 }
263                 else if (params[1].startsWith("DH1080_FINISH") && keyExchangeAllowed) {
264                     events << new KeyEvent(EventManager::KeyEvent, net, tags, prefix, target, KeyEvent::Finish, params[1].mid(14));
265                 }
266                 else
267 #endif
268                 {
269                     IrcEventRawMessage* rawMessage = new IrcEventRawMessage(EventManager::IrcEventRawNotice,
270                                                                             net,
271                                                                             tags,
272                                                                             params[1],
273                                                                             prefix,
274                                                                             target,
275                                                                             e->timestamp());
276                     if (isSelfMessage) {
277                         // Self-messages need processed differently, tag as such via flag.
278                         rawMessage->setFlag(EventManager::Self);
279                     }
280                     events << rawMessage;
281                 }
282             }
283         }
284         break;
285
286         // the following events need only special casing for param decoding
287     case EventManager::IrcEventKick:
288         if (params.count() >= 3) {  // we have a reason
289             decParams << net->serverDecode(params.at(0)) << net->serverDecode(params.at(1));
290             decParams << net->channelDecode(decParams.first(), params.at(2));  // kick reason
291         }
292         break;
293
294     case EventManager::IrcEventPart:
295         if (params.count() >= 2) {
296             QString channel = net->serverDecode(params.at(0));
297             decParams << channel;
298             decParams << net->userDecode(nickFromMask(prefix), params.at(1));
299             net->updateNickFromMask(prefix);
300         }
301         break;
302
303     case EventManager::IrcEventQuit:
304         if (params.count() >= 1) {
305             decParams << net->userDecode(nickFromMask(prefix), params.at(0));
306             net->updateNickFromMask(prefix);
307         }
308         break;
309
310     case EventManager::IrcEventTagmsg:
311         defaultHandling = false;  // this might create a list of events
312
313         if (checkParamCount(cmd, params, 1)) {
314             QString senderNick = nickFromMask(prefix);
315             net->updateNickFromMask(prefix);
316             // Check if the sender is our own nick.  If so, treat message as if sent by ourself.
317             // See http://ircv3.net/specs/extensions/echo-message-3.2.html
318             // Cache the result to avoid multiple redundant comparisons
319             bool isSelfMessage = net->isMyNick(senderNick);
320
321             QStringList targets = net->serverDecode(params.at(0)).split(',', QString::SkipEmptyParts);
322             QStringList::const_iterator targetIter;
323             for (targetIter = targets.constBegin(); targetIter != targets.constEnd(); ++targetIter) {
324                 // For self-messages, keep the target, don't set it to the senderNick
325                 QString target = net->isChannelName(*targetIter) || net->isStatusMsg(*targetIter) || isSelfMessage ? *targetIter : senderNick;
326
327                 IrcEvent* tagMsg = new IrcEvent(EventManager::IrcEventTagmsg, net, tags, prefix, {target});
328                 if (isSelfMessage) {
329                     // Self-messages need processed differently, tag as such via flag.
330                     tagMsg->setFlag(EventManager::Self);
331                 }
332                 tagMsg->setTimestamp(e->timestamp());
333                 events << tagMsg;
334             }
335         }
336         break;
337
338     case EventManager::IrcEventTopic:
339         if (params.count() >= 1) {
340             QString channel = net->serverDecode(params.at(0));
341             decParams << channel;
342             decParams << (params.count() >= 2 ? net->channelDecode(channel, decrypt(net, channel, params.at(1), true)) : QString());
343         }
344         break;
345
346     case EventManager::IrcEventAway:
347         {
348             // Update hostmask info first.  This will create the nick if it doesn't exist, e.g.
349             // away-notify data being sent before JOIN messages.
350             net->updateNickFromMask(prefix);
351             // Separate nick in order to separate server and user decoding
352             QString nick = nickFromMask(prefix);
353             decParams << nick;
354             decParams << (params.count() >= 1 ? net->userDecode(nick, params.at(0)) : QString());
355         }
356         break;
357
358     case EventManager::IrcEventNumeric:
359         switch (num) {
360         case 301: /* RPL_AWAY */
361             if (params.count() >= 2) {
362                 QString nick = net->serverDecode(params.at(0));
363                 decParams << nick;
364                 decParams << net->userDecode(nick, params.at(1));
365             }
366             break;
367
368         case 332: /* RPL_TOPIC */
369             if (params.count() >= 2) {
370                 QString channel = net->serverDecode(params.at(0));
371                 decParams << channel;
372                 decParams << net->channelDecode(channel, decrypt(net, channel, params.at(1), true));
373             }
374             break;
375
376         case 333: /* Topic set by... */
377             if (params.count() >= 3) {
378                 QString channel = net->serverDecode(params.at(0));
379                 decParams << channel << net->serverDecode(params.at(1));
380                 decParams << net->channelDecode(channel, params.at(2));
381             }
382             break;
383         case 451: /* You have not registered... */
384             if (messageTarget.compare("CAP", Qt::CaseInsensitive) == 0) {
385                 // :irc.server.com 451 CAP :You have not registered
386                 // If server doesn't support capabilities, it will report this message.  Turn it
387                 // into a nicer message since it's not a real error.
388                 defaultHandling = false;
389                 events << new MessageEvent(Message::Server,
390                                            e->network(),
391                                            tr("Capability negotiation not supported"),
392                                            QString(),
393                                            QString(),
394                                            Message::None,
395                                            e->timestamp());
396             }
397             break;
398         }
399
400     default:
401         break;
402     }
403
404     if (defaultHandling && type != EventManager::Invalid) {
405         for (int i = decParams.count(); i < params.count(); i++)
406             decParams << net->serverDecode(params.at(i));
407
408         // We want to trim the last param just in case, except for PRIVMSG and NOTICE
409         // ... but those happen to be the only ones not using defaultHandling anyway
410         if (!decParams.isEmpty() && decParams.last().endsWith(' '))
411             decParams.append(decParams.takeLast().trimmed());
412
413         IrcEvent* event;
414         if (type == EventManager::IrcEventNumeric)
415             event = new IrcEventNumeric(num, net, tags, prefix, messageTarget);
416         else
417             event = new IrcEvent(type, net, tags, prefix);
418         event->setParams(decParams);
419         event->setTimestamp(e->timestamp());
420         events << event;
421     }
422
423     for (Event* event : events) {
424         emit newEvent(event);
425     }
426 }