Improve debugging for new IRCv3 functionality
[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     // 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     QList<Event*> events;
123     EventManager::EventType type = EventManager::Invalid;
124
125     QString messageTarget;
126     uint num = cmd.toUInt();
127     if (num > 0) {
128         // numeric reply
129         if (params.count() == 0) {
130             qWarning() << "Message received from server violates RFC and is ignored!" << rawMsg;
131             return;
132         }
133         // numeric replies have the target as first param (RFC 2812 - 2.4). this is usually our own nick. Remove this!
134         messageTarget = net->serverDecode(params.takeFirst());
135         type = EventManager::IrcEventNumeric;
136     }
137     else {
138         // any other irc command
139         QString typeName = QLatin1String("IrcEvent") + cmd.at(0).toUpper() + cmd.mid(1).toLower();
140         type = EventManager::eventTypeByName(typeName);
141         if (type == EventManager::Invalid) {
142             type = EventManager::eventTypeByName("IrcEventUnknown");
143             Q_ASSERT(type != EventManager::Invalid);
144         }
145     }
146
147     // Almost always, all params are server-encoded. There's a few exceptions, let's catch them here!
148     // Possibly not the best option, we might want something more generic? Maybe yet another layer of
149     // unencoded events with event handlers for the exceptions...
150     // Also, PRIVMSG and NOTICE need some special handling, we put this in here as well, so we get out
151     // nice pre-parsed events that the CTCP handler can consume.
152
153     QStringList decParams;
154     bool defaultHandling = true;  // whether to automatically copy the remaining params and send the event
155
156     switch (type) {
157     case EventManager::IrcEventPrivmsg:
158         defaultHandling = false;  // this might create a list of events
159
160         if (checkParamCount(cmd, params, 1)) {
161             QString senderNick = nickFromMask(prefix);
162             net->updateNickFromMask(prefix);
163             // Check if the sender is our own nick.  If so, treat message as if sent by ourself.
164             // See http://ircv3.net/specs/extensions/echo-message-3.2.html
165             // Cache the result to avoid multiple redundant comparisons
166             bool isSelfMessage = net->isMyNick(senderNick);
167
168             QByteArray msg = params.count() < 2 ? QByteArray() : params.at(1);
169
170             QStringList targets = net->serverDecode(params.at(0)).split(',', QString::SkipEmptyParts);
171             QStringList::const_iterator targetIter;
172             for (targetIter = targets.constBegin(); targetIter != targets.constEnd(); ++targetIter) {
173                 // For self-messages, keep the target, don't set it to the senderNick
174                 QString target = net->isChannelName(*targetIter) || net->isStatusMsg(*targetIter) || isSelfMessage ? *targetIter : senderNick;
175
176                 // Note: self-messages could be encrypted with a different key.  If issues arise,
177                 // consider including this within an if (!isSelfMessage) block
178                 msg = decrypt(net, target, msg);
179
180                 IrcEventRawMessage* rawMessage = new IrcEventRawMessage(EventManager::IrcEventRawPrivmsg,
181                                                                         net,
182                                                                         msg,
183                                                                         prefix,
184                                                                         target,
185                                                                         e->timestamp());
186                 if (isSelfMessage) {
187                     // Self-messages need processed differently, tag as such via flag.
188                     rawMessage->setFlag(EventManager::Self);
189                 }
190                 events << rawMessage;
191             }
192         }
193         break;
194
195     case EventManager::IrcEventNotice:
196         defaultHandling = false;
197
198         if (checkParamCount(cmd, params, 2)) {
199             // Check if the sender is our own nick.  If so, treat message as if sent by ourself.
200             // See http://ircv3.net/specs/extensions/echo-message-3.2.html
201             // Cache the result to avoid multiple redundant comparisons
202             bool isSelfMessage = net->isMyNick(nickFromMask(prefix));
203
204             QStringList targets = net->serverDecode(params.at(0)).split(',', QString::SkipEmptyParts);
205             QStringList::const_iterator targetIter;
206             for (targetIter = targets.constBegin(); targetIter != targets.constEnd(); ++targetIter) {
207                 QString target = *targetIter;
208
209                 // special treatment for welcome messages like:
210                 // :ChanServ!ChanServ@services. NOTICE egst :[#apache] Welcome, this is #apache. Please read the in-channel topic message.
211                 // This channel is being logged by IRSeekBot. If you have any question please see http://blog.freenode.net/?p=68
212                 if (!net->isChannelName(target)) {
213                     QString decMsg = net->serverDecode(params.at(1));
214                     QRegExp welcomeRegExp(R"(^\[([^\]]+)\] )");
215                     if (welcomeRegExp.indexIn(decMsg) != -1) {
216                         QString channelname = welcomeRegExp.cap(1);
217                         decMsg = decMsg.mid(welcomeRegExp.matchedLength());
218                         // we only have CoreIrcChannels in the core, so this cast is safe
219                         CoreIrcChannel* chan = static_cast<CoreIrcChannel*>(net->ircChannel(channelname)); // NOLINT(cppcoreguidelines-pro-type-static-cast-downcast)
220                         if (chan && !chan->receivedWelcomeMsg()) {
221                             chan->setReceivedWelcomeMsg();
222                             events << new MessageEvent(Message::Notice, net, decMsg, prefix, channelname, Message::None, e->timestamp());
223                             continue;
224                         }
225                     }
226                 }
227
228                 if (prefix.isEmpty() || target == "AUTH") {
229                     target = QString();
230                 }
231                 else {
232                     if (!target.isEmpty() && net->prefixes().contains(target.at(0)))
233                         target = target.mid(1);
234
235                     if (!net->isChannelName(target)) {
236                         // For self-messages, keep the target, don't set it to the sender prefix
237                         if (!isSelfMessage) {
238                             target = nickFromMask(prefix);
239                         }
240                         net->updateNickFromMask(prefix);
241                     }
242                 }
243
244 #ifdef HAVE_QCA2
245                 // Handle DH1080 key exchange
246                 // Don't allow key exchange in channels, and don't allow it for self-messages.
247                 bool keyExchangeAllowed = (!net->isChannelName(target) && !isSelfMessage);
248                 if (params[1].startsWith("DH1080_INIT") && keyExchangeAllowed) {
249                     events << new KeyEvent(EventManager::KeyEvent, net, prefix, target, KeyEvent::Init, params[1].mid(12));
250                 }
251                 else if (params[1].startsWith("DH1080_FINISH") && keyExchangeAllowed) {
252                     events << new KeyEvent(EventManager::KeyEvent, net, prefix, target, KeyEvent::Finish, params[1].mid(14));
253                 }
254                 else
255 #endif
256                 {
257                     IrcEventRawMessage* rawMessage = new IrcEventRawMessage(EventManager::IrcEventRawNotice,
258                                                                             net,
259                                                                             params[1],
260                                                                             prefix,
261                                                                             target,
262                                                                             e->timestamp());
263                     if (isSelfMessage) {
264                         // Self-messages need processed differently, tag as such via flag.
265                         rawMessage->setFlag(EventManager::Self);
266                     }
267                     events << rawMessage;
268                 }
269             }
270         }
271         break;
272
273     // the following events need only special casing for param decoding
274     case EventManager::IrcEventKick:
275         if (params.count() >= 3) {  // we have a reason
276             decParams << net->serverDecode(params.at(0)) << net->serverDecode(params.at(1));
277             decParams << net->channelDecode(decParams.first(), params.at(2));  // kick reason
278         }
279         break;
280
281     case EventManager::IrcEventPart:
282         if (params.count() >= 2) {
283             QString channel = net->serverDecode(params.at(0));
284             decParams << channel;
285             decParams << net->userDecode(nickFromMask(prefix), params.at(1));
286             net->updateNickFromMask(prefix);
287         }
288         break;
289
290     case EventManager::IrcEventQuit:
291         if (params.count() >= 1) {
292             decParams << net->userDecode(nickFromMask(prefix), params.at(0));
293             net->updateNickFromMask(prefix);
294         }
295         break;
296
297     case EventManager::IrcEventTopic:
298         if (params.count() >= 1) {
299             QString channel = net->serverDecode(params.at(0));
300             decParams << channel;
301             decParams << (params.count() >= 2 ? net->channelDecode(channel, decrypt(net, channel, params.at(1), true)) : QString());
302         }
303         break;
304
305     case EventManager::IrcEventAway: {
306         // Update hostmask info first.  This will create the nick if it doesn't exist, e.g.
307         // away-notify data being sent before JOIN messages.
308         net->updateNickFromMask(prefix);
309         // Separate nick in order to separate server and user decoding
310         QString nick = nickFromMask(prefix);
311         decParams << nick;
312         decParams << (params.count() >= 1 ? net->userDecode(nick, params.at(0)) : QString());
313     } break;
314
315     case EventManager::IrcEventNumeric:
316         switch (num) {
317         case 301: /* RPL_AWAY */
318             if (params.count() >= 2) {
319                 QString nick = net->serverDecode(params.at(0));
320                 decParams << nick;
321                 decParams << net->userDecode(nick, params.at(1));
322             }
323             break;
324
325         case 332: /* RPL_TOPIC */
326             if (params.count() >= 2) {
327                 QString channel = net->serverDecode(params.at(0));
328                 decParams << channel;
329                 decParams << net->channelDecode(channel, decrypt(net, channel, params.at(1), true));
330             }
331             break;
332
333         case 333: /* Topic set by... */
334             if (params.count() >= 3) {
335                 QString channel = net->serverDecode(params.at(0));
336                 decParams << channel << net->serverDecode(params.at(1));
337                 decParams << net->channelDecode(channel, params.at(2));
338             }
339             break;
340         case 451: /* You have not registered... */
341             if (messageTarget.compare("CAP", Qt::CaseInsensitive) == 0) {
342                 // :irc.server.com 451 CAP :You have not registered
343                 // If server doesn't support capabilities, it will report this message.  Turn it
344                 // into a nicer message since it's not a real error.
345                 defaultHandling = false;
346                 events << new MessageEvent(Message::Server,
347                                            e->network(),
348                                            tr("Capability negotiation not supported"),
349                                            QString(),
350                                            QString(),
351                                            Message::None,
352                                            e->timestamp());
353             }
354             break;
355         }
356
357     default:
358         break;
359     }
360
361     if (defaultHandling && type != EventManager::Invalid) {
362         for (int i = decParams.count(); i < params.count(); i++)
363             decParams << net->serverDecode(params.at(i));
364
365         // We want to trim the last param just in case, except for PRIVMSG and NOTICE
366         // ... but those happen to be the only ones not using defaultHandling anyway
367         if (!decParams.isEmpty() && decParams.last().endsWith(' '))
368             decParams.append(decParams.takeLast().trimmed());
369
370         IrcEvent* event;
371         if (type == EventManager::IrcEventNumeric)
372             event = new IrcEventNumeric(num, net, prefix, messageTarget);
373         else
374             event = new IrcEvent(type, net, prefix);
375         event->setParams(decParams);
376         event->setTimestamp(e->timestamp());
377         events << event;
378     }
379
380     foreach (Event* event, events) {
381         emit newEvent(event);
382     }
383 }