cmake: avoid de-duplication of user's CXXFLAGS
[quassel.git] / src / core / ircparser.cpp
1 /***************************************************************************
2  *   Copyright (C) 2005-2022 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     if (net->capEnabled(IrcCap::SERVER_TIME) && tags.contains(IrcTags::SERVER_TIME)) {
123         QDateTime serverTime = QDateTime::fromString(tags[IrcTags::SERVER_TIME], "yyyy-MM-ddThh:mm:ss.zzzZ");
124         serverTime.setTimeSpec(Qt::UTC);
125         if (serverTime.isValid()) {
126             e->setTimestamp(serverTime);
127         } else {
128             qDebug() << "Invalid timestamp from server-time tag:" << tags[IrcTags::SERVER_TIME];
129         }
130     }
131
132     if (net->capEnabled(IrcCap::ACCOUNT_TAG) && tags.contains(IrcTags::ACCOUNT)) {
133         // Whenever account-tag is specified, update the relevant IrcUser if it exists
134         // Logged-out status is handled in specific commands (PRIVMSG, NOTICE, etc)
135         //
136         // Don't use "updateNickFromMask" here to ensure this only updates existing IrcUsers and
137         // won't create a new IrcUser.  This guards against an IRC server setting "account" tag in
138         // nonsensical places, e.g. for messages that are not user sent.
139         IrcUser* ircuser = net->ircUser(prefix);
140         if (ircuser) {
141             ircuser->setAccount(tags[IrcTags::ACCOUNT]);
142         }
143
144         // NOTE: if "account-tag" is enabled and no "account" tag is sent, the given user isn't
145         // logged in ONLY IF it is a user-initiated command.  Quassel follows a mixture of what
146         // other clients do here - only marking as logged out via PRIVMSG/NOTICE, but marking logged
147         // in via any message.
148         //
149         // See https://ircv3.net/specs/extensions/account-tag-3.2
150     }
151
152     QList<Event*> events;
153     EventManager::EventType type = EventManager::Invalid;
154
155     QString messageTarget;
156     uint num = cmd.toUInt();
157     if (num > 0) {
158         // numeric reply
159         if (params.count() == 0) {
160             qWarning() << "Message received from server violates RFC and is ignored!" << rawMsg;
161             return;
162         }
163         // numeric replies have the target as first param (RFC 2812 - 2.4). this is usually our own nick. Remove this!
164         messageTarget = net->serverDecode(params.takeFirst());
165         type = EventManager::IrcEventNumeric;
166     }
167     else {
168         // any other irc command
169         QString typeName = QLatin1String("IrcEvent") + cmd.at(0).toUpper() + cmd.mid(1).toLower();
170         type = EventManager::eventTypeByName(typeName);
171         if (type == EventManager::Invalid) {
172             type = EventManager::eventTypeByName("IrcEventUnknown");
173             Q_ASSERT(type != EventManager::Invalid);
174         }
175     }
176
177     // Almost always, all params are server-encoded. There's a few exceptions, let's catch them here!
178     // Possibly not the best option, we might want something more generic? Maybe yet another layer of
179     // unencoded events with event handlers for the exceptions...
180     // Also, PRIVMSG and NOTICE need some special handling, we put this in here as well, so we get out
181     // nice pre-parsed events that the CTCP handler can consume.
182
183     QStringList decParams;
184     bool defaultHandling = true;  // whether to automatically copy the remaining params and send the event
185
186     switch (type) {
187     case EventManager::IrcEventPrivmsg:
188         defaultHandling = false;  // this might create a list of events
189
190         if (checkParamCount(cmd, params, 1)) {
191             QString senderNick = nickFromMask(prefix);
192             // Fetch/create the relevant IrcUser, and store it for later updates
193             IrcUser* ircuser = net->updateNickFromMask(prefix);
194
195             // Handle account-tag
196             if (ircuser && net->capEnabled(IrcCap::ACCOUNT_TAG)) {
197                 if (tags.contains(IrcTags::ACCOUNT)) {
198                     // Account tag available, set account.
199                     // This duplicates the generic account-tag handling in case a new IrcUser object
200                     // was just created.
201                     ircuser->setAccount(tags[IrcTags::ACCOUNT]);
202                 }
203                 else {
204                     // PRIVMSG is user sent; it's safe to assume the user has logged out.
205                     // "*" is used to represent logged-out.
206                     ircuser->setAccount("*");
207                 }
208             }
209
210             // Check if the sender is our own nick.  If so, treat message as if sent by ourself.
211             // See http://ircv3.net/specs/extensions/echo-message-3.2.html
212             // Cache the result to avoid multiple redundant comparisons
213             bool isSelfMessage = net->isMyNick(senderNick);
214
215             QByteArray msg = params.count() < 2 ? QByteArray() : params.at(1);
216
217             QStringList targets = net->serverDecode(params.at(0)).split(',', QString::SkipEmptyParts);
218             QStringList::const_iterator targetIter;
219             for (targetIter = targets.constBegin(); targetIter != targets.constEnd(); ++targetIter) {
220                 // For self-messages, keep the target, don't set it to the senderNick
221                 QString target = net->isChannelName(*targetIter) || net->isStatusMsg(*targetIter) || isSelfMessage ? *targetIter : senderNick;
222
223                 // Note: self-messages could be encrypted with a different key.  If issues arise,
224                 // consider including this within an if (!isSelfMessage) block
225                 msg = decrypt(net, target, msg);
226
227                 IrcEventRawMessage* rawMessage = new IrcEventRawMessage(EventManager::IrcEventRawPrivmsg,
228                                                                         net,
229                                                                         tags,
230                                                                         msg,
231                                                                         prefix,
232                                                                         target,
233                                                                         e->timestamp());
234                 if (isSelfMessage) {
235                     // Self-messages need processed differently, tag as such via flag.
236                     rawMessage->setFlag(EventManager::Self);
237                 }
238                 events << rawMessage;
239             }
240         }
241         break;
242
243     case EventManager::IrcEventNotice:
244         defaultHandling = false;
245
246         if (checkParamCount(cmd, params, 2)) {
247             // Check if the sender is our own nick.  If so, treat message as if sent by ourself.
248             // See http://ircv3.net/specs/extensions/echo-message-3.2.html
249             // Cache the result to avoid multiple redundant comparisons
250             bool isSelfMessage = net->isMyNick(nickFromMask(prefix));
251
252             // Only update from the prefix once during the loop
253             bool updatedFromPrefix = false;
254
255             QStringList targets = net->serverDecode(params.at(0)).split(',', QString::SkipEmptyParts);
256             QStringList::const_iterator targetIter;
257             for (targetIter = targets.constBegin(); targetIter != targets.constEnd(); ++targetIter) {
258                 QString target = *targetIter;
259
260                 // special treatment for welcome messages like:
261                 // :ChanServ!ChanServ@services. NOTICE egst :[#apache] Welcome, this is #apache. Please read the in-channel topic message.
262                 // This channel is being logged by IRSeekBot. If you have any question please see http://blog.freenode.net/?p=68
263                 if (!net->isChannelName(target)) {
264                     QString decMsg = net->serverDecode(params.at(1));
265                     QRegExp welcomeRegExp(R"(^\[([^\]]+)\] )");
266                     if (welcomeRegExp.indexIn(decMsg) != -1) {
267                         QString channelname = welcomeRegExp.cap(1);
268                         decMsg = decMsg.mid(welcomeRegExp.matchedLength());
269                         // we only have CoreIrcChannels in the core, so this cast is safe
270                         CoreIrcChannel* chan = static_cast<CoreIrcChannel*>(net->ircChannel(channelname)); // NOLINT(cppcoreguidelines-pro-type-static-cast-downcast)
271                         if (chan && !chan->receivedWelcomeMsg()) {
272                             chan->setReceivedWelcomeMsg();
273                             events << new MessageEvent(Message::Notice, net, decMsg, prefix, channelname, Message::None, e->timestamp());
274                             continue;
275                         }
276                     }
277                 }
278
279                 if (prefix.isEmpty() || target == "AUTH") {
280                     target = QString();
281                 }
282                 else {
283                     if (!target.isEmpty() && net->prefixes().contains(target.at(0)))
284                         target = target.mid(1);
285
286                     if (!net->isChannelName(target)) {
287                         // For self-messages, keep the target, don't set it to the sender prefix
288                         if (!isSelfMessage) {
289                             target = nickFromMask(prefix);
290                         }
291
292                         if (!updatedFromPrefix) {
293                             // Don't repeat this within the loop, the prefix doesn't change
294                             updatedFromPrefix = true;
295
296                             // Fetch/create the relevant IrcUser, and store it for later updates
297                             IrcUser* ircuser = net->updateNickFromMask(prefix);
298
299                             // Handle account-tag
300                             if (ircuser && net->capEnabled(IrcCap::ACCOUNT_TAG)) {
301                                 if (tags.contains(IrcTags::ACCOUNT)) {
302                                     // Account tag available, set account.
303                                     // This duplicates the generic account-tag handling in case a
304                                     // new IrcUser object was just created.
305                                     ircuser->setAccount(tags[IrcTags::ACCOUNT]);
306                                 }
307                                 else {
308                                     // NOTICE is user sent; it's safe to assume the user has
309                                     // logged out.  "*" is used to represent logged-out.
310                                     ircuser->setAccount("*");
311                                 }
312                             }
313                         }
314                     }
315                 }
316
317 #ifdef HAVE_QCA2
318                 // Handle DH1080 key exchange
319                 // Don't allow key exchange in channels, and don't allow it for self-messages.
320                 bool keyExchangeAllowed = (!net->isChannelName(target) && !isSelfMessage);
321                 if (params[1].startsWith("DH1080_INIT") && keyExchangeAllowed) {
322                     events << new KeyEvent(EventManager::KeyEvent, net, tags, prefix, target, KeyEvent::Init, params[1].mid(12));
323                 }
324                 else if (params[1].startsWith("DH1080_FINISH") && keyExchangeAllowed) {
325                     events << new KeyEvent(EventManager::KeyEvent, net, tags, prefix, target, KeyEvent::Finish, params[1].mid(14));
326                 }
327                 else
328 #endif
329                 {
330                     IrcEventRawMessage* rawMessage = new IrcEventRawMessage(EventManager::IrcEventRawNotice,
331                                                                             net,
332                                                                             tags,
333                                                                             params[1],
334                                                                             prefix,
335                                                                             target,
336                                                                             e->timestamp());
337                     if (isSelfMessage) {
338                         // Self-messages need processed differently, tag as such via flag.
339                         rawMessage->setFlag(EventManager::Self);
340                     }
341                     events << rawMessage;
342                 }
343             }
344         }
345         break;
346
347         // the following events need only special casing for param decoding
348     case EventManager::IrcEventKick:
349         if (params.count() >= 3) {  // we have a reason
350             decParams << net->serverDecode(params.at(0)) << net->serverDecode(params.at(1));
351             decParams << net->channelDecode(decParams.first(), params.at(2));  // kick reason
352         }
353         break;
354
355     case EventManager::IrcEventPart:
356         if (params.count() >= 2) {
357             QString channel = net->serverDecode(params.at(0));
358             decParams << channel;
359             decParams << net->userDecode(nickFromMask(prefix), params.at(1));
360             net->updateNickFromMask(prefix);
361         }
362         break;
363
364     case EventManager::IrcEventQuit:
365         if (params.count() >= 1) {
366             decParams << net->userDecode(nickFromMask(prefix), params.at(0));
367             net->updateNickFromMask(prefix);
368         }
369         break;
370
371     case EventManager::IrcEventTagmsg:
372         defaultHandling = false;  // this might create a list of events
373
374         if (checkParamCount(cmd, params, 1)) {
375             QString senderNick = nickFromMask(prefix);
376             net->updateNickFromMask(prefix);
377             // Check if the sender is our own nick.  If so, treat message as if sent by ourself.
378             // See http://ircv3.net/specs/extensions/echo-message-3.2.html
379             // Cache the result to avoid multiple redundant comparisons
380             bool isSelfMessage = net->isMyNick(senderNick);
381
382             QStringList targets = net->serverDecode(params.at(0)).split(',', QString::SkipEmptyParts);
383             QStringList::const_iterator targetIter;
384             for (targetIter = targets.constBegin(); targetIter != targets.constEnd(); ++targetIter) {
385                 // For self-messages, keep the target, don't set it to the senderNick
386                 QString target = net->isChannelName(*targetIter) || net->isStatusMsg(*targetIter) || isSelfMessage ? *targetIter : senderNick;
387
388                 IrcEvent* tagMsg = new IrcEvent(EventManager::IrcEventTagmsg, net, tags, prefix, {target});
389                 if (isSelfMessage) {
390                     // Self-messages need processed differently, tag as such via flag.
391                     tagMsg->setFlag(EventManager::Self);
392                 }
393                 tagMsg->setTimestamp(e->timestamp());
394                 events << tagMsg;
395             }
396         }
397         break;
398
399     case EventManager::IrcEventTopic:
400         if (params.count() >= 1) {
401             QString channel = net->serverDecode(params.at(0));
402             decParams << channel;
403             decParams << (params.count() >= 2 ? net->channelDecode(channel, decrypt(net, channel, params.at(1), true)) : QString());
404         }
405         break;
406
407     case EventManager::IrcEventAway:
408         {
409             // Update hostmask info first.  This will create the nick if it doesn't exist, e.g.
410             // away-notify data being sent before JOIN messages.
411             net->updateNickFromMask(prefix);
412             // Separate nick in order to separate server and user decoding
413             QString nick = nickFromMask(prefix);
414             decParams << nick;
415             decParams << (params.count() >= 1 ? net->userDecode(nick, params.at(0)) : QString());
416         }
417         break;
418
419     case EventManager::IrcEventNumeric:
420         switch (num) {
421         case 301: /* RPL_AWAY */
422             if (params.count() >= 2) {
423                 QString nick = net->serverDecode(params.at(0));
424                 decParams << nick;
425                 decParams << net->userDecode(nick, params.at(1));
426             }
427             break;
428
429         case 332: /* RPL_TOPIC */
430             if (params.count() >= 2) {
431                 QString channel = net->serverDecode(params.at(0));
432                 decParams << channel;
433                 decParams << net->channelDecode(channel, decrypt(net, channel, params.at(1), true));
434             }
435             break;
436
437         case 333: /* Topic set by... */
438             if (params.count() >= 3) {
439                 QString channel = net->serverDecode(params.at(0));
440                 decParams << channel << net->serverDecode(params.at(1));
441                 decParams << net->channelDecode(channel, params.at(2));
442             }
443             break;
444         case 451: /* You have not registered... */
445             if (messageTarget.compare("CAP", Qt::CaseInsensitive) == 0) {
446                 // :irc.server.com 451 CAP :You have not registered
447                 // If server doesn't support capabilities, it will report this message.  Turn it
448                 // into a nicer message since it's not a real error.
449                 defaultHandling = false;
450                 events << new MessageEvent(Message::Server,
451                                            e->network(),
452                                            tr("Capability negotiation not supported"),
453                                            QString(),
454                                            QString(),
455                                            Message::None,
456                                            e->timestamp());
457             }
458             break;
459         }
460
461     default:
462         break;
463     }
464
465     if (defaultHandling && type != EventManager::Invalid) {
466         for (int i = decParams.count(); i < params.count(); i++)
467             decParams << net->serverDecode(params.at(i));
468
469         // We want to trim the last param just in case, except for PRIVMSG and NOTICE
470         // ... but those happen to be the only ones not using defaultHandling anyway
471         if (!decParams.isEmpty() && decParams.last().endsWith(' '))
472             decParams.append(decParams.takeLast().trimmed());
473
474         IrcEvent* event;
475         if (type == EventManager::IrcEventNumeric)
476             event = new IrcEventNumeric(num, net, tags, prefix, messageTarget);
477         else
478             event = new IrcEvent(type, net, tags, prefix);
479         event->setParams(decParams);
480         event->setTimestamp(e->timestamp());
481         events << event;
482     }
483
484     for (Event* event : events) {
485         emit newEvent(event);
486     }
487 }