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