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