1 /***************************************************************************
2 * Copyright (C) 2005-2018 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"
25 #include "corenetwork.h"
26 #include "eventmanager.h"
28 #include "messageevent.h"
29 #include "networkevent.h"
33 # include "keyevent.h"
36 IrcParser::IrcParser(CoreSession *session) :
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();
44 connect(this, SIGNAL(newEvent(Event *)), coreSession()->eventManager(), SLOT(postEvent(Event *)));
48 bool IrcParser::checkParamCount(const QString &cmd, const QList<QByteArray> ¶ms, int minParams)
50 if (params.count() < minParams) {
51 qWarning() << "Expected" << minParams << "params for IRC command" << cmd << ", got:" << params;
58 QByteArray IrcParser::decrypt(Network *network, const QString &bufferName, const QByteArray &message, bool isTopic)
61 if (message.isEmpty())
64 if (!Cipher::neededFeaturesAvailable())
67 Cipher *cipher = qobject_cast<CoreNetwork *>(network)->cipher(bufferName);
68 if (!cipher || cipher->key().isEmpty())
71 return isTopic ? cipher->decryptTopic(message) : cipher->decrypt(message);
81 /* parse the raw server string and generate an appropriate event */
82 /* used to be handleServerMsg() */
83 void IrcParser::processNetworkIncoming(NetworkDataEvent *e)
85 auto *net = qobject_cast<CoreNetwork *>(e->network());
87 qWarning() << "Received network event without valid network pointer!";
91 // note that the IRC server is still alive
92 net->resetPingTimeout();
94 QByteArray msg = e->data();
96 qWarning() << "Received empty string from server!";
100 // Log the message if enabled and network ID matches or allows all
102 && (_debugLogRawNetId == -1 || net->networkId().toInt() == _debugLogRawNetId)) {
103 // Include network ID
104 qDebug() << "IRC net" << net->networkId() << "<<" << msg;
107 // Now we split the raw message into its various parts...
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(" :");
116 if (msg.length() > idx + 2)
117 trailing = msg.mid(idx + 2);
120 // OK, now it is safe to split...
121 QList<QByteArray> params = msg.split(' ');
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()) {
128 iter = params.erase(iter);
133 if (!trailing.isEmpty())
135 if (params.count() < 1) {
136 qWarning() << "Received invalid string from server!";
140 QString foo = net->serverDecode(params.takeFirst());
142 // a colon as the first chars indicates the existence of a prefix
146 if (params.count() < 1) {
147 qWarning() << "Received invalid string from server!";
150 foo = net->serverDecode(params.takeFirst());
153 // next string without a whitespace is the command
156 QList<Event *> events;
157 EventManager::EventType type = EventManager::Invalid;
159 uint num = cmd.toUInt();
162 if (params.count() == 0) {
163 qWarning() << "Message received from server violates RFC and is ignored!" << msg;
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;
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);
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.
187 QStringList decParams;
188 bool defaultHandling = true; // whether to automatically copy the remaining params and send the event
191 case EventManager::IrcEventPrivmsg:
192 defaultHandling = false; // this might create a list of events
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);
202 QByteArray msg = params.count() < 2 ? QByteArray() : params.at(1);
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;
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);
214 IrcEventRawMessage *rawMessage = new IrcEventRawMessage(EventManager::IrcEventRawPrivmsg, net, msg, prefix, target, e->timestamp());
216 // Self-messages need processed differently, tag as such via flag.
217 rawMessage->setFlag(EventManager::Self);
219 events << rawMessage;
224 case EventManager::IrcEventNotice:
225 defaultHandling = false;
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));
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;
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());
255 if (prefix.isEmpty() || target == "AUTH") {
259 if (!target.isEmpty() && net->prefixes().contains(target.at(0)))
260 target = target.mid(1);
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);
267 net->updateNickFromMask(prefix);
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));
282 IrcEventRawMessage *rawMessage = new IrcEventRawMessage(EventManager::IrcEventRawNotice, net, params[1], prefix, target, e->timestamp());
284 // Self-messages need processed differently, tag as such via flag.
285 rawMessage->setFlag(EventManager::Self);
287 events << rawMessage;
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
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);
310 case EventManager::IrcEventQuit:
311 if (params.count() >= 1) {
312 decParams << net->userDecode(nickFromMask(prefix), params.at(0));
313 net->updateNickFromMask(prefix);
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());
325 case EventManager::IrcEventAway:
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);
333 decParams << (params.count() >= 1 ? net->userDecode(nick, params.at(0)) : QString());
337 case EventManager::IrcEventNumeric:
339 case 301: /* RPL_AWAY */
340 if (params.count() >= 2) {
341 QString nick = net->serverDecode(params.at(0));
343 decParams << net->userDecode(nick, params.at(1));
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));
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));
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());
379 if (defaultHandling && type != EventManager::Invalid) {
380 for (int i = decParams.count(); i < params.count(); i++)
381 decParams << net->serverDecode(params.at(i));
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());
389 if (type == EventManager::IrcEventNumeric)
390 event = new IrcEventNumeric(num, net, prefix, target);
392 event = new IrcEvent(type, net, prefix);
393 event->setParams(decParams);
394 event->setTimestamp(e->timestamp());
398 foreach(Event *event, events) {
399 emit newEvent(event);