1 /***************************************************************************
2 * Copyright (C) 2005-2015 by the Quassel Project *
3 * devel@quassel-irc.org *
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. *
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. *
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 ***************************************************************************/
21 #include "ircparser.h"
23 #include "corenetwork.h"
24 #include "eventmanager.h"
26 #include "messageevent.h"
27 #include "networkevent.h"
31 # include "keyevent.h"
34 IrcParser::IrcParser(CoreSession *session) :
38 connect(this, SIGNAL(newEvent(Event *)), coreSession()->eventManager(), SLOT(postEvent(Event *)));
42 bool IrcParser::checkParamCount(const QString &cmd, const QList<QByteArray> ¶ms, int minParams)
44 if (params.count() < minParams) {
45 qWarning() << "Expected" << minParams << "params for IRC command" << cmd << ", got:" << params;
52 QByteArray IrcParser::decrypt(Network *network, const QString &bufferName, const QByteArray &message, bool isTopic)
55 if (message.isEmpty())
58 if (!Cipher::neededFeaturesAvailable())
61 Cipher *cipher = qobject_cast<CoreNetwork *>(network)->cipher(bufferName);
62 if (!cipher || cipher->key().isEmpty())
65 return isTopic ? cipher->decryptTopic(message) : cipher->decrypt(message);
75 /* parse the raw server string and generate an appropriate event */
76 /* used to be handleServerMsg() */
77 void IrcParser::processNetworkIncoming(NetworkDataEvent *e)
79 CoreNetwork *net = qobject_cast<CoreNetwork *>(e->network());
81 qWarning() << "Received network event without valid network pointer!";
85 // note that the IRC server is still alive
86 net->resetPingTimeout();
88 QByteArray msg = e->data();
90 qWarning() << "Received empty string from server!";
94 // Now we split the raw message into its various parts...
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(" :");
103 if (msg.length() > idx + 2)
104 trailing = msg.mid(idx + 2);
107 // OK, now it is safe to split...
108 QList<QByteArray> params = msg.split(' ');
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()) {
115 iter = params.erase(iter);
120 if (!trailing.isEmpty())
122 if (params.count() < 1) {
123 qWarning() << "Received invalid string from server!";
127 QString foo = net->serverDecode(params.takeFirst());
129 // a colon as the first chars indicates the existence of a prefix
133 if (params.count() < 1) {
134 qWarning() << "Received invalid string from server!";
137 foo = net->serverDecode(params.takeFirst());
140 // next string without a whitespace is the command
143 QList<Event *> events;
144 EventManager::EventType type = EventManager::Invalid;
146 uint num = cmd.toUInt();
149 if (params.count() == 0) {
150 qWarning() << "Message received from server violates RFC and is ignored!" << msg;
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;
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);
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.
174 QStringList decParams;
175 bool defaultHandling = true; // whether to automatically copy the remaining params and send the event
178 case EventManager::IrcEventPrivmsg:
179 defaultHandling = false; // this might create a list of events
181 if (checkParamCount(cmd, params, 1)) {
182 QString senderNick = nickFromMask(prefix);
183 net->updateNickFromMask(prefix);
184 QByteArray msg = params.count() < 2 ? QByteArray() : params.at(1);
186 QStringList targets = net->serverDecode(params.at(0)).split(',', QString::SkipEmptyParts);
187 QStringList::const_iterator targetIter;
188 for (targetIter = targets.constBegin(); targetIter != targets.constEnd(); ++targetIter) {
189 QString target = net->isChannelName(*targetIter) ? *targetIter : senderNick;
191 msg = decrypt(net, target, msg);
193 events << new IrcEventRawMessage(EventManager::IrcEventRawPrivmsg, net, msg, prefix, target, e->timestamp());
198 case EventManager::IrcEventNotice:
199 defaultHandling = false;
201 if (checkParamCount(cmd, params, 2)) {
202 QStringList targets = net->serverDecode(params.at(0)).split(',', QString::SkipEmptyParts);
203 QStringList::const_iterator targetIter;
204 for (targetIter = targets.constBegin(); targetIter != targets.constEnd(); ++targetIter) {
205 QString target = *targetIter;
207 // special treatment for welcome messages like:
208 // :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
209 if (!net->isChannelName(target)) {
210 QString decMsg = net->serverDecode(params.at(1));
211 QRegExp welcomeRegExp("^\\[([^\\]]+)\\] ");
212 if (welcomeRegExp.indexIn(decMsg) != -1) {
213 QString channelname = welcomeRegExp.cap(1);
214 decMsg = decMsg.mid(welcomeRegExp.matchedLength());
215 CoreIrcChannel *chan = static_cast<CoreIrcChannel *>(net->ircChannel(channelname)); // we only have CoreIrcChannels in the core, so this cast is safe
216 if (chan && !chan->receivedWelcomeMsg()) {
217 chan->setReceivedWelcomeMsg();
218 events << new MessageEvent(Message::Notice, net, decMsg, prefix, channelname, Message::None, e->timestamp());
224 if (prefix.isEmpty() || target == "AUTH") {
228 if (!target.isEmpty() && net->prefixes().contains(target.at(0)))
229 target = target.mid(1);
230 if (!net->isChannelName(target)) {
231 target = nickFromMask(prefix);
232 net->updateNickFromMask(prefix);
237 // Handle DH1080 key exchange
238 if (params[1].startsWith("DH1080_INIT") && !net->isChannelName(target)) {
239 events << new KeyEvent(EventManager::KeyEvent, net, prefix, target, KeyEvent::Init, params[1].mid(12));
240 } else if (params[1].startsWith("DH1080_FINISH") && !net->isChannelName(target)) {
241 events << new KeyEvent(EventManager::KeyEvent, net, prefix, target, KeyEvent::Finish, params[1].mid(14));
244 events << new IrcEventRawMessage(EventManager::IrcEventRawNotice, net, params[1], prefix, target, e->timestamp());
249 // the following events need only special casing for param decoding
250 case EventManager::IrcEventKick:
251 if (params.count() >= 3) { // we have a reason
252 decParams << net->serverDecode(params.at(0)) << net->serverDecode(params.at(1));
253 decParams << net->channelDecode(decParams.first(), params.at(2)); // kick reason
257 case EventManager::IrcEventPart:
258 if (params.count() >= 2) {
259 QString channel = net->serverDecode(params.at(0));
260 decParams << channel;
261 decParams << net->userDecode(nickFromMask(prefix), params.at(1));
262 net->updateNickFromMask(prefix);
266 case EventManager::IrcEventQuit:
267 if (params.count() >= 1) {
268 decParams << net->userDecode(nickFromMask(prefix), params.at(0));
269 net->updateNickFromMask(prefix);
273 case EventManager::IrcEventTopic:
274 if (params.count() >= 1) {
275 QString channel = net->serverDecode(params.at(0));
276 decParams << channel;
277 decParams << (params.count() >= 2 ? net->channelDecode(channel, decrypt(net, channel, params.at(1), true)) : QString());
281 case EventManager::IrcEventAway:
283 QString nick = nickFromMask(prefix);
285 decParams << (params.count() >= 1 ? net->userDecode(nick, params.at(0)) : QString());
286 net->updateNickFromMask(prefix);
290 case EventManager::IrcEventNumeric:
292 case 301: /* RPL_AWAY */
293 if (params.count() >= 2) {
294 QString nick = net->serverDecode(params.at(0));
296 decParams << net->userDecode(nick, params.at(1));
300 case 332: /* RPL_TOPIC */
301 if (params.count() >= 2) {
302 QString channel = net->serverDecode(params.at(0));
303 decParams << channel;
304 decParams << net->channelDecode(channel, decrypt(net, channel, params.at(1), true));
308 case 333: /* Topic set by... */
309 if (params.count() >= 3) {
310 QString channel = net->serverDecode(params.at(0));
311 decParams << channel << net->serverDecode(params.at(1));
312 decParams << net->channelDecode(channel, params.at(2));
315 case 451: /* You have not registered... */
316 if (target.compare("CAP", Qt::CaseInsensitive) == 0) {
317 // :irc.server.com 451 CAP :You have not registered
318 // If server doesn't support capabilities, it will report this message. Turn it
319 // into a nicer message since it's not a real error.
320 defaultHandling = false;
321 events << new MessageEvent(Message::Server, e->network(),
322 tr("Capability negotiation not supported"),
323 QString(), QString(), Message::None, e->timestamp());
332 if (defaultHandling && type != EventManager::Invalid) {
333 for (int i = decParams.count(); i < params.count(); i++)
334 decParams << net->serverDecode(params.at(i));
336 // We want to trim the last param just in case, except for PRIVMSG and NOTICE
337 // ... but those happen to be the only ones not using defaultHandling anyway
338 if (!decParams.isEmpty() && decParams.last().endsWith(' '))
339 decParams.append(decParams.takeLast().trimmed());
342 if (type == EventManager::IrcEventNumeric)
343 event = new IrcEventNumeric(num, net, prefix, target);
345 event = new IrcEvent(type, net, prefix);
346 event->setParams(decParams);
347 event->setTimestamp(e->timestamp());
351 foreach(Event *event, events) {
352 emit newEvent(event);