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