Refactor Cipher related things.
[quassel.git] / src / core / ircparser.cpp
1 /***************************************************************************
2  *   Copyright (C) 2005-2012 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 #endif
32
33 IrcParser::IrcParser(CoreSession *session) :
34     QObject(session),
35     _coreSession(session)
36 {
37     connect(this, SIGNAL(newEvent(Event *)), coreSession()->eventManager(), SLOT(postEvent(Event *)));
38 }
39
40
41 bool IrcParser::checkParamCount(const QString &cmd, const QList<QByteArray> &params, int minParams)
42 {
43     if (params.count() < minParams) {
44         qWarning() << "Expected" << minParams << "params for IRC command" << cmd << ", got:" << params;
45         return false;
46     }
47     return true;
48 }
49
50
51 QByteArray IrcParser::decrypt(Network *network, const QString &bufferName, const QByteArray &message, bool isTopic)
52 {
53 #ifdef HAVE_QCA2
54     if (message.isEmpty())
55         return message;
56
57     if (!Cipher::neededFeaturesAvailable())
58         return message;
59
60     Cipher *cipher = qobject_cast<CoreNetwork *>(network)->cipher(bufferName);
61     if (!cipher || cipher->key().isEmpty())
62         return message;
63
64     return isTopic ? cipher->decryptTopic(message) : cipher->decrypt(message);
65 #else
66     Q_UNUSED(network);
67     Q_UNUSED(bufferName);
68     Q_UNUSED(isTopic);
69     return message;
70 #endif
71 }
72
73
74 /* parse the raw server string and generate an appropriate event */
75 /* used to be handleServerMsg()                                  */
76 void IrcParser::processNetworkIncoming(NetworkDataEvent *e)
77 {
78     CoreNetwork *net = qobject_cast<CoreNetwork *>(e->network());
79     if (!net) {
80         qWarning() << "Received network event without valid network pointer!";
81         return;
82     }
83
84     // note that the IRC server is still alive
85     net->resetPingTimeout();
86
87     QByteArray msg = e->data();
88     if (msg.isEmpty()) {
89         qWarning() << "Received empty string from server!";
90         return;
91     }
92
93     // Now we split the raw message into its various parts...
94     QString prefix;
95     QByteArray trailing;
96     QString cmd, target;
97
98     // First, check for a trailing parameter introduced by " :", since this might screw up splitting the msg
99     // NOTE: This assumes that this is true in raw encoding, but well, hopefully there are no servers running in japanese on protocol level...
100     int idx = msg.indexOf(" :");
101     if (idx >= 0) {
102         if (msg.length() > idx + 2)
103             trailing = msg.mid(idx + 2);
104         msg = msg.left(idx);
105     }
106     // OK, now it is safe to split...
107     QList<QByteArray> params = msg.split(' ');
108
109     // This could still contain empty elements due to (faulty?) ircds sending multiple spaces in a row
110     // Also, QByteArray is not nearly as convenient to work with as QString for such things :)
111     QList<QByteArray>::iterator iter = params.begin();
112     while (iter != params.end()) {
113         if (iter->isEmpty())
114             iter = params.erase(iter);
115         else
116             ++iter;
117     }
118
119     if (!trailing.isEmpty())
120         params << trailing;
121     if (params.count() < 1) {
122         qWarning() << "Received invalid string from server!";
123         return;
124     }
125
126     QString foo = net->serverDecode(params.takeFirst());
127
128     // a colon as the first chars indicates the existence of a prefix
129     if (foo[0] == ':') {
130         foo.remove(0, 1);
131         prefix = foo;
132         if (params.count() < 1) {
133             qWarning() << "Received invalid string from server!";
134             return;
135         }
136         foo = net->serverDecode(params.takeFirst());
137     }
138
139     // next string without a whitespace is the command
140     cmd = foo.trimmed();
141
142     QList<Event *> events;
143     EventManager::EventType type = EventManager::Invalid;
144
145     uint num = cmd.toUInt();
146     if (num > 0) {
147         // numeric reply
148         if (params.count() == 0) {
149             qWarning() << "Message received from server violates RFC and is ignored!" << msg;
150             return;
151         }
152         // numeric replies have the target as first param (RFC 2812 - 2.4). this is usually our own nick. Remove this!
153         target = net->serverDecode(params.takeFirst());
154         type = EventManager::IrcEventNumeric;
155     }
156     else {
157         // any other irc command
158         QString typeName = QLatin1String("IrcEvent") + cmd.at(0).toUpper() + cmd.mid(1).toLower();
159         type = eventManager()->eventTypeByName(typeName);
160         if (type == EventManager::Invalid) {
161             type = eventManager()->eventTypeByName("IrcEventUnknown");
162             Q_ASSERT(type != EventManager::Invalid);
163         }
164         target = QString();
165     }
166
167     // Almost always, all params are server-encoded. There's a few exceptions, let's catch them here!
168     // Possibly not the best option, we might want something more generic? Maybe yet another layer of
169     // unencoded events with event handlers for the exceptions...
170     // Also, PRIVMSG and NOTICE need some special handling, we put this in here as well, so we get out
171     // nice pre-parsed events that the CTCP handler can consume.
172
173     QStringList decParams;
174     bool defaultHandling = true; // whether to automatically copy the remaining params and send the event
175
176     switch (type) {
177     case EventManager::IrcEventPrivmsg:
178         defaultHandling = false; // this might create a list of events
179
180         if (checkParamCount(cmd, params, 1)) {
181             QString senderNick = nickFromMask(prefix);
182             QByteArray msg = params.count() < 2 ? QByteArray() : params.at(1);
183
184             QStringList targets = net->serverDecode(params.at(0)).split(',', QString::SkipEmptyParts);
185             QStringList::const_iterator targetIter;
186             for (targetIter = targets.constBegin(); targetIter != targets.constEnd(); ++targetIter) {
187                 QString target = net->isChannelName(*targetIter) ? *targetIter : senderNick;
188
189                 msg = decrypt(net, target, msg);
190
191                 events << new IrcEventRawMessage(EventManager::IrcEventRawPrivmsg, net, msg, prefix, target, e->timestamp());
192             }
193         }
194         break;
195
196     case EventManager::IrcEventNotice:
197         defaultHandling = false;
198
199         if (checkParamCount(cmd, params, 2)) {
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                 QString target = *targetIter;
204
205                 // special treatment for welcome messages like:
206                 // :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
207                 if (!net->isChannelName(target)) {
208                     QString decMsg = net->serverDecode(params.at(1));
209                     QRegExp welcomeRegExp("^\\[([^\\]]+)\\] ");
210                     if (welcomeRegExp.indexIn(decMsg) != -1) {
211                         QString channelname = welcomeRegExp.cap(1);
212                         decMsg = decMsg.mid(welcomeRegExp.matchedLength());
213                         CoreIrcChannel *chan = static_cast<CoreIrcChannel *>(net->ircChannel(channelname)); // we only have CoreIrcChannels in the core, so this cast is safe
214                         if (chan && !chan->receivedWelcomeMsg()) {
215                             chan->setReceivedWelcomeMsg();
216                             events << new MessageEvent(Message::Notice, net, decMsg, prefix, channelname, Message::None, e->timestamp());
217                             continue;
218                         }
219                     }
220                 }
221
222                 if (prefix.isEmpty() || target == "AUTH") {
223                     target = QString();
224                 }
225                 else {
226                     if (!target.isEmpty() && net->prefixes().contains(target.at(0)))
227                         target = target.mid(1);
228                     if (!net->isChannelName(target))
229                         target = nickFromMask(prefix);
230                 }
231                 events << new IrcEventRawMessage(EventManager::IrcEventRawNotice, net, params[1], prefix, target, e->timestamp());
232             }
233         }
234         break;
235
236     // the following events need only special casing for param decoding
237     case EventManager::IrcEventKick:
238         if (params.count() >= 3) { // we have a reason
239             decParams << net->serverDecode(params.at(0)) << net->serverDecode(params.at(1));
240             decParams << net->channelDecode(decParams.first(), params.at(2)); // kick reason
241         }
242         break;
243
244     case EventManager::IrcEventPart:
245         if (params.count() >= 2) {
246             QString channel = net->serverDecode(params.at(0));
247             decParams << channel;
248             decParams << net->userDecode(nickFromMask(prefix), params.at(1));
249         }
250         break;
251
252     case EventManager::IrcEventQuit:
253         if (params.count() >= 1) {
254             decParams << net->userDecode(nickFromMask(prefix), params.at(0));
255         }
256         break;
257
258     case EventManager::IrcEventTopic:
259         if (params.count() >= 1) {
260             QString channel = net->serverDecode(params.at(0));
261             decParams << channel;
262             decParams << (params.count() >= 2 ? net->channelDecode(channel, decrypt(net, channel, params.at(1), true)) : QString());
263         }
264         break;
265
266     case EventManager::IrcEventNumeric:
267         switch (num) {
268         case 301: /* RPL_AWAY */
269             if (params.count() >= 2) {
270                 QString nick = net->serverDecode(params.at(0));
271                 decParams << nick;
272                 decParams << net->userDecode(nick, params.at(1));
273             }
274             break;
275
276         case 332: /* RPL_TOPIC */
277             if (params.count() >= 2) {
278                 QString channel = net->serverDecode(params.at(0));
279                 decParams << channel;
280                 decParams << net->channelDecode(channel, decrypt(net, channel, params.at(1), true));
281             }
282             break;
283
284         case 333: /* Topic set by... */
285             if (params.count() >= 3) {
286                 QString channel = net->serverDecode(params.at(0));
287                 decParams << channel << net->serverDecode(params.at(1));
288                 decParams << net->channelDecode(channel, params.at(2));
289             }
290             break;
291         }
292
293     default:
294         break;
295     }
296
297     if (defaultHandling && type != EventManager::Invalid) {
298         for (int i = decParams.count(); i < params.count(); i++)
299             decParams << net->serverDecode(params.at(i));
300
301         IrcEvent *event;
302         if (type == EventManager::IrcEventNumeric)
303             event = new IrcEventNumeric(num, net, prefix, target);
304         else
305             event = new IrcEvent(type, net, prefix);
306         event->setParams(decParams);
307         event->setTimestamp(e->timestamp());
308         events << event;
309     }
310
311     foreach(Event *event, events) {
312         emit newEvent(event);
313     }
314 }