1 /***************************************************************************
2 * Copyright (C) 2005-2019 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)
38 , _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, &IrcParser::newEvent, coreSession()->eventManager(), &EventManager::postEvent);
47 bool IrcParser::checkParamCount(const QString& cmd, const QList<QByteArray>& params, int minParams)
49 if (params.count() < minParams) {
50 qWarning() << "Expected" << minParams << "params for IRC command" << cmd << ", got:" << params;
56 QByteArray IrcParser::decrypt(Network* network, const QString& bufferName, const QByteArray& message, bool isTopic)
59 if (message.isEmpty())
62 if (!Cipher::neededFeaturesAvailable())
65 Cipher* cipher = qobject_cast<CoreNetwork*>(network)->cipher(bufferName);
66 if (!cipher || cipher->key().isEmpty())
69 return isTopic ? cipher->decryptTopic(message) : cipher->decrypt(message);
78 /* parse the raw server string and generate an appropriate event */
79 /* used to be handleServerMsg() */
80 void IrcParser::processNetworkIncoming(NetworkDataEvent* e)
82 auto* net = qobject_cast<CoreNetwork*>(e->network());
84 qWarning() << "Received network event without valid network pointer!";
88 // note that the IRC server is still alive
89 net->resetPingTimeout();
91 QByteArray msg = e->data();
93 qWarning() << "Received empty string from server!";
97 // Log the message if enabled and network ID matches or allows all
98 if (_debugLogRawIrc && (_debugLogRawNetId == -1 || net->networkId().toInt() == _debugLogRawNetId)) {
100 qDebug() << "IRC net" << net->networkId() << "<<" << msg;
103 // Now we split the raw message into its various parts...
108 // First, check for a trailing parameter introduced by " :", since this might screw up splitting the msg
109 // NOTE: This assumes that this is true in raw encoding, but well, hopefully there are no servers running in japanese on protocol level...
110 int idx = msg.indexOf(" :");
112 if (msg.length() > idx + 2)
113 trailing = msg.mid(idx + 2);
116 // OK, now it is safe to split...
117 QList<QByteArray> params = msg.split(' ');
119 // This could still contain empty elements due to (faulty?) ircds sending multiple spaces in a row
120 // Also, QByteArray is not nearly as convenient to work with as QString for such things :)
121 QList<QByteArray>::iterator iter = params.begin();
122 while (iter != params.end()) {
124 iter = params.erase(iter);
129 if (!trailing.isEmpty())
131 if (params.count() < 1) {
132 qWarning() << "Received invalid string from server!";
136 QString foo = net->serverDecode(params.takeFirst());
138 // a colon as the first chars indicates the existence of a prefix
142 if (params.count() < 1) {
143 qWarning() << "Received invalid string from server!";
146 foo = net->serverDecode(params.takeFirst());
149 // next string without a whitespace is the command
152 QList<Event*> events;
153 EventManager::EventType type = EventManager::Invalid;
155 uint num = cmd.toUInt();
158 if (params.count() == 0) {
159 qWarning() << "Message received from server violates RFC and is ignored!" << msg;
162 // numeric replies have the target as first param (RFC 2812 - 2.4). this is usually our own nick. Remove this!
163 target = net->serverDecode(params.takeFirst());
164 type = EventManager::IrcEventNumeric;
167 // any other irc command
168 QString typeName = QLatin1String("IrcEvent") + cmd.at(0).toUpper() + cmd.mid(1).toLower();
169 type = eventManager()->eventTypeByName(typeName);
170 if (type == EventManager::Invalid) {
171 type = eventManager()->eventTypeByName("IrcEventUnknown");
172 Q_ASSERT(type != EventManager::Invalid);
177 // Almost always, all params are server-encoded. There's a few exceptions, let's catch them here!
178 // Possibly not the best option, we might want something more generic? Maybe yet another layer of
179 // unencoded events with event handlers for the exceptions...
180 // Also, PRIVMSG and NOTICE need some special handling, we put this in here as well, so we get out
181 // nice pre-parsed events that the CTCP handler can consume.
183 QStringList decParams;
184 bool defaultHandling = true; // whether to automatically copy the remaining params and send the event
187 case EventManager::IrcEventPrivmsg:
188 defaultHandling = false; // this might create a list of events
190 if (checkParamCount(cmd, params, 1)) {
191 QString senderNick = nickFromMask(prefix);
192 net->updateNickFromMask(prefix);
193 // Check if the sender is our own nick. If so, treat message as if sent by ourself.
194 // See http://ircv3.net/specs/extensions/echo-message-3.2.html
195 // Cache the result to avoid multiple redundant comparisons
196 bool isSelfMessage = net->isMyNick(senderNick);
198 QByteArray msg = params.count() < 2 ? QByteArray() : params.at(1);
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 // For self-messages, keep the target, don't set it to the senderNick
204 QString target = net->isChannelName(*targetIter) || net->isStatusMsg(*targetIter) || isSelfMessage ? *targetIter : senderNick;
206 // Note: self-messages could be encrypted with a different key. If issues arise,
207 // consider including this within an if (!isSelfMessage) block
208 msg = decrypt(net, target, msg);
210 IrcEventRawMessage* rawMessage = new IrcEventRawMessage(EventManager::IrcEventRawPrivmsg,
217 // Self-messages need processed differently, tag as such via flag.
218 rawMessage->setFlag(EventManager::Self);
220 events << rawMessage;
225 case EventManager::IrcEventNotice:
226 defaultHandling = false;
228 if (checkParamCount(cmd, params, 2)) {
229 // Check if the sender is our own nick. If so, treat message as if sent by ourself.
230 // See http://ircv3.net/specs/extensions/echo-message-3.2.html
231 // Cache the result to avoid multiple redundant comparisons
232 bool isSelfMessage = net->isMyNick(nickFromMask(prefix));
234 QStringList targets = net->serverDecode(params.at(0)).split(',', QString::SkipEmptyParts);
235 QStringList::const_iterator targetIter;
236 for (targetIter = targets.constBegin(); targetIter != targets.constEnd(); ++targetIter) {
237 QString target = *targetIter;
239 // special treatment for welcome messages like:
240 // :ChanServ!ChanServ@services. NOTICE egst :[#apache] Welcome, this is #apache. Please read the in-channel topic message.
241 // This channel is being logged by IRSeekBot. If you have any question please see http://blog.freenode.net/?p=68
242 if (!net->isChannelName(target)) {
243 QString decMsg = net->serverDecode(params.at(1));
244 QRegExp welcomeRegExp(R"(^\[([^\]]+)\] )");
245 if (welcomeRegExp.indexIn(decMsg) != -1) {
246 QString channelname = welcomeRegExp.cap(1);
247 decMsg = decMsg.mid(welcomeRegExp.matchedLength());
248 CoreIrcChannel* chan = static_cast<CoreIrcChannel*>(
249 net->ircChannel(channelname)); // we only have CoreIrcChannels in the core, so this cast is safe
250 if (chan && !chan->receivedWelcomeMsg()) {
251 chan->setReceivedWelcomeMsg();
252 events << new MessageEvent(Message::Notice, net, decMsg, prefix, channelname, Message::None, e->timestamp());
258 if (prefix.isEmpty() || target == "AUTH") {
262 if (!target.isEmpty() && net->prefixes().contains(target.at(0)))
263 target = target.mid(1);
265 if (!net->isChannelName(target)) {
266 // For self-messages, keep the target, don't set it to the sender prefix
267 if (!isSelfMessage) {
268 target = nickFromMask(prefix);
270 net->updateNickFromMask(prefix);
275 // Handle DH1080 key exchange
276 // Don't allow key exchange in channels, and don't allow it for self-messages.
277 bool keyExchangeAllowed = (!net->isChannelName(target) && !isSelfMessage);
278 if (params[1].startsWith("DH1080_INIT") && keyExchangeAllowed) {
279 events << new KeyEvent(EventManager::KeyEvent, net, prefix, target, KeyEvent::Init, params[1].mid(12));
281 else if (params[1].startsWith("DH1080_FINISH") && keyExchangeAllowed) {
282 events << new KeyEvent(EventManager::KeyEvent, net, prefix, target, KeyEvent::Finish, params[1].mid(14));
287 IrcEventRawMessage* rawMessage = new IrcEventRawMessage(EventManager::IrcEventRawNotice,
294 // Self-messages need processed differently, tag as such via flag.
295 rawMessage->setFlag(EventManager::Self);
297 events << rawMessage;
303 // the following events need only special casing for param decoding
304 case EventManager::IrcEventKick:
305 if (params.count() >= 3) { // we have a reason
306 decParams << net->serverDecode(params.at(0)) << net->serverDecode(params.at(1));
307 decParams << net->channelDecode(decParams.first(), params.at(2)); // kick reason
311 case EventManager::IrcEventPart:
312 if (params.count() >= 2) {
313 QString channel = net->serverDecode(params.at(0));
314 decParams << channel;
315 decParams << net->userDecode(nickFromMask(prefix), params.at(1));
316 net->updateNickFromMask(prefix);
320 case EventManager::IrcEventQuit:
321 if (params.count() >= 1) {
322 decParams << net->userDecode(nickFromMask(prefix), params.at(0));
323 net->updateNickFromMask(prefix);
327 case EventManager::IrcEventTopic:
328 if (params.count() >= 1) {
329 QString channel = net->serverDecode(params.at(0));
330 decParams << channel;
331 decParams << (params.count() >= 2 ? net->channelDecode(channel, decrypt(net, channel, params.at(1), true)) : QString());
335 case EventManager::IrcEventAway: {
336 // Update hostmask info first. This will create the nick if it doesn't exist, e.g.
337 // away-notify data being sent before JOIN messages.
338 net->updateNickFromMask(prefix);
339 // Separate nick in order to separate server and user decoding
340 QString nick = nickFromMask(prefix);
342 decParams << (params.count() >= 1 ? net->userDecode(nick, params.at(0)) : QString());
345 case EventManager::IrcEventNumeric:
347 case 301: /* RPL_AWAY */
348 if (params.count() >= 2) {
349 QString nick = net->serverDecode(params.at(0));
351 decParams << net->userDecode(nick, params.at(1));
355 case 332: /* RPL_TOPIC */
356 if (params.count() >= 2) {
357 QString channel = net->serverDecode(params.at(0));
358 decParams << channel;
359 decParams << net->channelDecode(channel, decrypt(net, channel, params.at(1), true));
363 case 333: /* Topic set by... */
364 if (params.count() >= 3) {
365 QString channel = net->serverDecode(params.at(0));
366 decParams << channel << net->serverDecode(params.at(1));
367 decParams << net->channelDecode(channel, params.at(2));
370 case 451: /* You have not registered... */
371 if (target.compare("CAP", Qt::CaseInsensitive) == 0) {
372 // :irc.server.com 451 CAP :You have not registered
373 // If server doesn't support capabilities, it will report this message. Turn it
374 // into a nicer message since it's not a real error.
375 defaultHandling = false;
376 events << new MessageEvent(Message::Server,
378 tr("Capability negotiation not supported"),
391 if (defaultHandling && type != EventManager::Invalid) {
392 for (int i = decParams.count(); i < params.count(); i++)
393 decParams << net->serverDecode(params.at(i));
395 // We want to trim the last param just in case, except for PRIVMSG and NOTICE
396 // ... but those happen to be the only ones not using defaultHandling anyway
397 if (!decParams.isEmpty() && decParams.last().endsWith(' '))
398 decParams.append(decParams.takeLast().trimmed());
401 if (type == EventManager::IrcEventNumeric)
402 event = new IrcEventNumeric(num, net, prefix, target);
404 event = new IrcEvent(type, net, prefix);
405 event->setParams(decParams);
406 event->setTimestamp(e->timestamp());
410 foreach (Event* event, events) {
411 emit newEvent(event);