Minor cleanup of messages handling
[quassel.git] / src / core / ircparser.cpp
1 /***************************************************************************
2  *   Copyright (C) 2005-2019 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
46     connect(this, &IrcParser::newEvent, coreSession()->eventManager(), &EventManager::postEvent);
47 }
48
49 bool IrcParser::checkParamCount(const QString& cmd, const QList<QByteArray>& params, int minParams)
50 {
51     if (params.count() < minParams) {
52         qWarning() << "Expected" << minParams << "params for IRC command" << cmd << ", got:" << params;
53         return false;
54     }
55     return true;
56 }
57
58 QByteArray IrcParser::decrypt(Network* network, const QString& bufferName, const QByteArray& message, bool isTopic)
59 {
60 #ifdef HAVE_QCA2
61     if (message.isEmpty())
62         return message;
63
64     if (!Cipher::neededFeaturesAvailable())
65         return message;
66
67     Cipher* cipher = qobject_cast<CoreNetwork*>(network)->cipher(bufferName);
68     if (!cipher || cipher->key().isEmpty())
69         return message;
70
71     return isTopic ? cipher->decryptTopic(message) : cipher->decrypt(message);
72 #else
73     Q_UNUSED(network);
74     Q_UNUSED(bufferName);
75     Q_UNUSED(isTopic);
76     return message;
77 #endif
78 }
79
80 /* parse the raw server string and generate an appropriate event */
81 /* used to be handleServerMsg()                                  */
82 void IrcParser::processNetworkIncoming(NetworkDataEvent* e)
83 {
84     auto* net = qobject_cast<CoreNetwork*>(e->network());
85     if (!net) {
86         qWarning() << "Received network event without valid network pointer!";
87         return;
88     }
89
90     // note that the IRC server is still alive
91     net->resetPingTimeout();
92
93     const QByteArray rawMsg = e->data();
94     if (rawMsg.isEmpty()) {
95         qWarning() << "Received empty string from server!";
96         return;
97     }
98
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;
103     }
104
105     QHash<IrcTagKey, QString> tags;
106     QString prefix;
107     QString cmd;
108     QList<QByteArray> params;
109     IrcDecoder::parseMessage([&net](const QByteArray& data) {
110         return net->serverDecode(data);
111     }, rawMsg, tags, prefix, cmd, params);
112
113     QList<Event*> events;
114     EventManager::EventType type = EventManager::Invalid;
115
116     QString messageTarget;
117     uint num = cmd.toUInt();
118     if (num > 0) {
119         // numeric reply
120         if (params.count() == 0) {
121             qWarning() << "Message received from server violates RFC and is ignored!" << rawMsg;
122             return;
123         }
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;
127     }
128     else {
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);
135         }
136     }
137
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.
143
144     QStringList decParams;
145     bool defaultHandling = true;  // whether to automatically copy the remaining params and send the event
146
147     switch (type) {
148     case EventManager::IrcEventPrivmsg:
149         defaultHandling = false;  // this might create a list of events
150
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);
158
159             QByteArray msg = params.count() < 2 ? QByteArray() : params.at(1);
160
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;
166
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);
170
171                 IrcEventRawMessage* rawMessage = new IrcEventRawMessage(EventManager::IrcEventRawPrivmsg,
172                                                                         net,
173                                                                         msg,
174                                                                         prefix,
175                                                                         target,
176                                                                         e->timestamp());
177                 if (isSelfMessage) {
178                     // Self-messages need processed differently, tag as such via flag.
179                     rawMessage->setFlag(EventManager::Self);
180                 }
181                 events << rawMessage;
182             }
183         }
184         break;
185
186     case EventManager::IrcEventNotice:
187         defaultHandling = false;
188
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));
194
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;
199
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());
214                             continue;
215                         }
216                     }
217                 }
218
219                 if (prefix.isEmpty() || target == "AUTH") {
220                     target = QString();
221                 }
222                 else {
223                     if (!target.isEmpty() && net->prefixes().contains(target.at(0)))
224                         target = target.mid(1);
225
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);
230                         }
231                         net->updateNickFromMask(prefix);
232                     }
233                 }
234
235 #ifdef HAVE_QCA2
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));
241                 }
242                 else if (params[1].startsWith("DH1080_FINISH") && keyExchangeAllowed) {
243                     events << new KeyEvent(EventManager::KeyEvent, net, prefix, target, KeyEvent::Finish, params[1].mid(14));
244                 }
245                 else
246 #endif
247                 {
248                     IrcEventRawMessage* rawMessage = new IrcEventRawMessage(EventManager::IrcEventRawNotice,
249                                                                             net,
250                                                                             params[1],
251                                                                             prefix,
252                                                                             target,
253                                                                             e->timestamp());
254                     if (isSelfMessage) {
255                         // Self-messages need processed differently, tag as such via flag.
256                         rawMessage->setFlag(EventManager::Self);
257                     }
258                     events << rawMessage;
259                 }
260             }
261         }
262         break;
263
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
269         }
270         break;
271
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);
278         }
279         break;
280
281     case EventManager::IrcEventQuit:
282         if (params.count() >= 1) {
283             decParams << net->userDecode(nickFromMask(prefix), params.at(0));
284             net->updateNickFromMask(prefix);
285         }
286         break;
287
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());
293         }
294         break;
295
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);
302         decParams << nick;
303         decParams << (params.count() >= 1 ? net->userDecode(nick, params.at(0)) : QString());
304     } break;
305
306     case EventManager::IrcEventNumeric:
307         switch (num) {
308         case 301: /* RPL_AWAY */
309             if (params.count() >= 2) {
310                 QString nick = net->serverDecode(params.at(0));
311                 decParams << nick;
312                 decParams << net->userDecode(nick, params.at(1));
313             }
314             break;
315
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));
321             }
322             break;
323
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));
329             }
330             break;
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,
338                                            e->network(),
339                                            tr("Capability negotiation not supported"),
340                                            QString(),
341                                            QString(),
342                                            Message::None,
343                                            e->timestamp());
344             }
345             break;
346         }
347
348     default:
349         break;
350     }
351
352     if (defaultHandling && type != EventManager::Invalid) {
353         for (int i = decParams.count(); i < params.count(); i++)
354             decParams << net->serverDecode(params.at(i));
355
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());
360
361         IrcEvent* event;
362         if (type == EventManager::IrcEventNumeric)
363             event = new IrcEventNumeric(num, net, prefix, messageTarget);
364         else
365             event = new IrcEvent(type, net, prefix);
366         event->setParams(decParams);
367         event->setTimestamp(e->timestamp());
368         events << event;
369     }
370
371     foreach (Event* event, events) {
372         emit newEvent(event);
373     }
374 }