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