1 /***************************************************************************
2 * Copyright (C) 2005-2022 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 "coresessioneventprocessor.h"
25 #include "coreirclisthelper.h"
26 #include "corenetwork.h"
27 #include "coresession.h"
28 #include "coretransfer.h"
29 #include "coretransfermanager.h"
30 #include "ctcpevent.h"
33 #include "messageevent.h"
38 # include "keyevent.h"
44 CoreSessionEventProcessor::CoreSessionEventProcessor(CoreSession* session)
45 : BasicHandler("handleCtcp", session)
46 , _coreSession(session)
48 connect(coreSession(), &CoreSession::networkDisconnected, this, &CoreSessionEventProcessor::destroyNetsplits);
49 connect(this, &CoreSessionEventProcessor::newEvent, coreSession()->eventManager(), &EventManager::postEvent);
52 bool CoreSessionEventProcessor::checkParamCount(IrcEvent* e, int minParams)
54 if (e->params().count() < minParams) {
55 if (e->type() == EventManager::IrcEventNumeric) {
56 qWarning() << "Command " << static_cast<IrcEventNumeric*>(e)->number() << " requires " << minParams
57 << "params, got: " << e->params();
60 QString name = coreSession()->eventManager()->enumName(e->type());
61 qWarning() << qPrintable(name) << "requires" << minParams << "params, got:" << e->params();
69 void CoreSessionEventProcessor::tryNextNick(NetworkEvent* e, const QString& errnick, bool erroneus)
71 QStringList desiredNicks = coreSession()->identity(e->network()->identity())->nicks();
72 int nextNickIdx = desiredNicks.indexOf(errnick) + 1;
74 if (nextNickIdx > 0 && desiredNicks.size() > nextNickIdx) {
75 nextNick = desiredNicks[nextNickIdx];
79 // FIXME Make this an ErrorEvent or something like that, so it's translated in the client
80 MessageEvent* msgEvent = new MessageEvent(Message::Error,
82 tr("No free and valid nicks in nicklist found. use: /nick <othernick> to continue"),
87 emit newEvent(msgEvent);
91 nextNick = errnick + "_";
94 // FIXME Use a proper output event for this
95 coreNetwork(e)->putRawLine("NICK " + coreNetwork(e)->encodeServerString(nextNick));
98 void CoreSessionEventProcessor::processIrcEventNumeric(IrcEventNumeric* e)
100 switch (e->number()) {
101 // SASL authentication replies
102 // See: http://ircv3.net/specs/extensions/sasl-3.1.html
104 // case 900: // RPL_LOGGEDIN
105 // case 901: // RPL_LOGGEDOUT
106 // Don't use 900 or 901 for updating the local hostmask. Unreal 3.2 gives it as the IP address
107 // even when cloaked.
108 // Every other reply should result in moving on
109 // TODO Handle errors to stop connection if appropriate
110 case 902: // ERR_NICKLOCKED
111 case 903: // RPL_SASLSUCCESS
112 case 904: // ERR_SASLFAIL
113 case 905: // ERR_SASLTOOLONG
114 case 906: // ERR_SASLABORTED
115 case 907: // ERR_SASLALREADY
116 // Move on to the next capability
117 coreNetwork(e)->sendNextCap();
125 void CoreSessionEventProcessor::processIrcEventAuthenticate(IrcEvent* e)
127 if (!checkParamCount(e, 1))
130 if (e->params().at(0) != "+") {
131 qWarning() << "Invalid AUTHENTICATE" << e;
135 CoreNetwork* net = coreNetwork(e);
137 if (net->identityPtr()->sslCert().isNull()) {
138 QString construct = net->saslAccount();
139 construct.append(QChar(QChar::Null));
140 construct.append(net->saslAccount());
141 construct.append(QChar(QChar::Null));
142 construct.append(net->saslPassword());
143 QByteArray saslData = QByteArray(construct.toLatin1().toBase64());
144 saslData.prepend("AUTHENTICATE ");
145 net->putRawLine(saslData);
148 net->putRawLine("AUTHENTICATE +");
152 void CoreSessionEventProcessor::processIrcEventCap(IrcEvent* e)
154 // Handle capability negotiation
155 // See: http://ircv3.net/specs/core/capability-negotiation-3.2.html
156 // And: http://ircv3.net/specs/core/capability-negotiation-3.1.html
158 // All commands require at least 2 parameters
159 if (!checkParamCount(e, 2))
162 CoreNetwork* coreNet = coreNetwork(e);
163 QString capCommand = e->params().at(1).trimmed().toUpper();
164 if (capCommand == "LS" || capCommand == "NEW") {
165 // Either we've gotten a list of capabilities, or new capabilities we may want
166 // Server: CAP * LS * :multi-prefix extended-join account-notify batch invite-notify tls
167 // Server: CAP * LS * :cap-notify server-time example.org/dummy-cap=dummyvalue example.org/second-dummy-cap
168 // Server: CAP * LS :userhost-in-names sasl=EXTERNAL,DH-AES,DH-BLOWFISH,ECDSA-NIST256P-CHALLENGE,PLAIN
169 bool capListFinished;
170 QStringList availableCaps;
171 if (e->params().count() == 4) {
172 // Middle of multi-line reply, ignore the asterisk
173 capListFinished = false;
174 availableCaps = e->params().at(3).split(' ');
178 capListFinished = true;
179 if (e->params().count() >= 3) {
180 // Some capabilities are specified, add them
181 availableCaps = e->params().at(2).split(' ');
184 // No capabilities available, add an empty list
185 availableCaps = QStringList();
188 // Sort capabilities before requesting for consistency among networks. This may avoid
189 // unexpected cases when some networks offer capabilities in a different order than
190 // others. It also looks nicer in logs. Not required.
191 availableCaps.sort();
192 // Store what capabilities are available
193 QString availableCapName, availableCapValue;
194 for (int i = 0; i < availableCaps.count(); ++i) {
195 // Capability may include values, e.g. CAP * LS :multi-prefix sasl=EXTERNAL
196 // Capability name comes before the first '='. If no '=' exists, this gets the
197 // whole string instead.
198 availableCapName = availableCaps[i].section('=', 0, 0).trimmed();
199 // Some capabilities include multiple key=value pairs in the listing,
200 // e.g. "sts=duration=31536000,port=6697"
201 // Include everything after the first equal sign as part of the value. If no '='
202 // exists, this gets an empty string.
203 availableCapValue = availableCaps[i].section('=', 1).trimmed();
204 // Only add the capability if it's non-empty
205 if (!availableCapName.isEmpty()) {
206 coreNet->addCap(availableCapName, availableCapValue);
210 // Begin capability requests when capability listing complete
212 coreNet->beginCapNegotiation();
214 else if (capCommand == "ACK") {
215 // CAP ACK requires at least 3 parameters (no empty response allowed)
216 if (!checkParamCount(e, 3)) {
217 // If an invalid reply is sent, try to continue rather than getting stuck.
218 coreNet->sendNextCap();
222 // Server: CAP * ACK :multi-prefix sasl
223 // Got the capabilities we want, handle as needed.
224 QStringList acceptedCaps;
225 acceptedCaps = e->params().at(2).split(' ');
227 // Store what capability was acknowledged
230 // Keep track of whether or not a capability requires further configuration. Due to queuing
231 // logic in CoreNetwork::queueCap(), this shouldn't ever happen when more than one
232 // capability is requested, but it's better to handle edge cases or faulty servers.
233 bool capsRequireConfiguration = false;
235 for (int i = 0; i < acceptedCaps.count(); ++i) {
236 acceptedCap = acceptedCaps[i].trimmed().toLower();
237 // Mark this cap as accepted
238 coreNet->acknowledgeCap(acceptedCap);
239 if (!capsRequireConfiguration && coreNet->capsRequiringConfiguration.contains(acceptedCap)) {
240 capsRequireConfiguration = true;
241 // Some capabilities (e.g. SASL) require further messages to finish. If so, do NOT
242 // send the next capability; it will be handled elsewhere in CoreNetwork.
243 // Otherwise, allow moving on to the next capability.
247 if (!capsRequireConfiguration) {
248 // No additional configuration required, move on to the next capability
249 coreNet->sendNextCap();
252 else if (capCommand == "NAK" || capCommand == "DEL") {
253 // CAP NAK/DEL require at least 3 parameters (no empty response allowed)
254 if (!checkParamCount(e, 3)) {
255 if (capCommand == "NAK") {
256 // If an invalid reply is sent, try to continue rather than getting stuck. This
257 // only matters for denied caps, not removed caps.
258 coreNet->sendNextCap();
263 // Either something went wrong with the capabilities, or they are no longer supported
265 // Server: CAP * NAK :multi-prefix sasl
267 // Server: :irc.example.com CAP modernclient DEL :multi-prefix sasl
268 // CAP NAK and CAP DEL replies are always single-line
270 QStringList removedCaps;
271 removedCaps = e->params().at(2).split(' ');
273 // Store the capabilities that were denied or removed
275 for (int i = 0; i < removedCaps.count(); ++i) {
276 removedCap = removedCaps[i].trimmed().toLower();
277 // Mark this cap as removed.
278 // For CAP DEL, removes it from use.
279 // For CAP NAK when received before negotiation enabled these capabilities, removeCap()
280 // should do nothing. This merely guards against non-spec servers sending an
281 // unsolicited CAP ACK then later removing that capability.
282 coreNet->removeCap(removedCap);
285 if (capCommand == "NAK") {
286 // Continue negotiation only if this is the result of denied caps, not removed caps
287 if (removedCaps.count() > 1) {
288 // We've received a CAP NAK reply to multiple capabilities at once. Unfortunately,
289 // we don't know which capability failed and which ones are valid to re-request, so
290 // individually retry each capability from the failed bundle.
291 // See CoreNetwork::retryCapsIndividually() for more details.
292 coreNet->retryCapsIndividually();
293 // Still need to call sendNextCap() to carry on.
295 // Carry on with negotiation
296 coreNet->sendNextCap();
301 /* IRCv3 account-notify
302 * Log in: ":nick!user@host ACCOUNT accountname"
303 * Log out: ":nick!user@host ACCOUNT *" */
304 void CoreSessionEventProcessor::processIrcEventAccount(IrcEvent* e)
306 if (!checkParamCount(e, 1))
309 IrcUser* ircuser = e->network()->updateNickFromMask(e->prefix());
311 // WHOX uses '0' to indicate logged-out, account-notify and extended-join uses '*'.
312 // As '*' is used internally to represent logged-out, no need to handle that differently.
313 ircuser->setAccount(e->params().at(0));
316 qDebug() << "Received account-notify data for unknown user" << e->prefix();
320 /* IRCv3 away-notify - ":nick!user@host AWAY [:message]" */
321 void CoreSessionEventProcessor::processIrcEventAway(IrcEvent* e)
323 if (!checkParamCount(e, 1))
325 // Don't use checkParamCount(e, 2) since the message is optional. Some servers respond in a way
326 // that it counts as two parameters, but we shouldn't rely on that.
328 // Nick is sent as part of parameters in order to split user/server decoding
329 IrcUser* ircuser = e->network()->ircUser(e->params().at(0));
331 // If two parameters are sent -and- the second parameter isn't empty, then user is away.
332 // Otherwise, mark them as not away.
333 if (e->params().count() >= 2 && !e->params().at(1).isEmpty()) {
334 ircuser->setAway(true);
335 ircuser->setAwayMessage(e->params().at(1));
338 ircuser->setAway(false);
342 qDebug() << "Received away-notify data for unknown user" << e->params().at(0);
346 /* IRCv3 chghost - ":nick!user@host CHGHOST newuser new.host.goes.here" */
347 void CoreSessionEventProcessor::processIrcEventChghost(IrcEvent* e)
349 if (!checkParamCount(e, 2))
352 IrcUser* ircuser = e->network()->updateNickFromMask(e->prefix());
354 // Update with new user/hostname information. setUser/setHost handles checking what
356 ircuser->setUser(e->params().at(0));
357 ircuser->setHost(e->params().at(1));
360 qDebug() << "Received chghost data for unknown user" << e->prefix();
364 // IRCv3 INVITE - ":<inviter> INVITE <target> <channel>"
365 // Example: :ChanServ!ChanServ@example.com INVITE Attila #channel
367 // See https://ircv3.net/specs/extensions/invite-notify-3.2
368 void CoreSessionEventProcessor::processIrcEventInvite(IrcEvent* e)
370 if (checkParamCount(e, 2)) {
371 e->network()->updateNickFromMask(e->prefix());
375 /* JOIN: ":<nick!user@host> JOIN <channel>" */
376 void CoreSessionEventProcessor::processIrcEventJoin(IrcEvent* e)
378 if (e->testFlag(EventManager::Fake)) // generated by handleEarlyNetsplitJoin
381 if (!checkParamCount(e, 1))
384 CoreNetwork* net = coreNetwork(e);
385 QString channel = e->params()[0];
386 IrcUser* ircuser = net->updateNickFromMask(e->prefix());
388 if (net->capEnabled(IrcCap::EXTENDED_JOIN)) {
389 if (e->params().count() < 3) {
390 // Some IRC servers don't send extended-join events in all situations. Rather than
391 // ignore the join entirely, treat it as a regular join with a debug-level log entry.
392 // See: https://github.com/inspircd/inspircd/issues/821
393 qDebug() << "extended-join requires 3 params, got:" << e->params()
394 << ", handling as a "
398 // If logged in, :nick!user@host JOIN #channelname accountname :Real Name
399 // If logged out, :nick!user@host JOIN #channelname * :Real Name
400 // See: http://ircv3.net/specs/extensions/extended-join-3.1.html
401 // WHOX uses '0' to indicate logged-out, account-notify and extended-join uses '*'.
402 // As '*' is used internally to represent logged-out, no need to handle that differently.
403 ircuser->setAccount(e->params()[1]);
404 // Update the user's real name, too
405 ircuser->setRealName(e->params()[2]);
408 // Else :nick!user@host JOIN #channelname
410 bool handledByNetsplit = false;
411 for (Netsplit* n : _netsplits.value(e->network())) {
412 handledByNetsplit = n->userJoined(e->prefix(), channel);
413 if (handledByNetsplit)
417 // With "away-notify" enabled, some IRC servers forget to send :away messages for users who join
418 // channels while away. Unfortunately, working around this involves WHO'ng every single user as
419 // they join, which is not very efficient. If at all possible, it's better to get the issue
420 // fixed in the IRC server instead.
422 // If pursuing a workaround instead, this is where you'd do it. Check the version control
423 // history for the commit that added this comment to see how to implement it - there's some
424 // unexpected situations to watch out for!
426 // See https://ircv3.net/specs/extensions/away-notify-3.1.html
428 if (!handledByNetsplit)
429 ircuser->joinChannel(channel);
431 e->setFlag(EventManager::Netsplit);
433 if (net->isMe(ircuser)) {
434 net->setChannelJoined(channel);
435 // Mark the message as Self
436 e->setFlag(EventManager::Self);
438 net->putRawLine(net->serverEncode("MODE " + channel)); // we want to know the modes of the channel we just joined, so we ask politely
442 void CoreSessionEventProcessor::lateProcessIrcEventKick(IrcEvent* e)
444 if (checkParamCount(e, 2)) {
445 e->network()->updateNickFromMask(e->prefix());
446 IrcUser* victim = e->network()->ircUser(e->params().at(1));
448 victim->partChannel(e->params().at(0));
449 // if(e->network()->isMe(victim)) e->network()->setKickedFromChannel(channel);
454 void CoreSessionEventProcessor::processIrcEventMode(IrcEvent* e)
456 if (!checkParamCount(e, 2))
459 if (e->network()->isChannelName(e->params().first())) {
462 IrcChannel* channel = e->network()->ircChannel(e->params()[0]);
464 // we received mode information for a channel we're not in. that means probably we've just been kicked out or something like
465 // that anyways: we don't have a place to store the data --> discard the info.
469 QString modes = e->params()[1];
472 for (auto mode : modes) {
482 if (e->network()->prefixModes().contains(mode)) {
483 // user channel modes (op, voice, etc...)
484 if (paramOffset < e->params().count()) {
485 IrcUser* ircUser = e->network()->ircUser(e->params()[paramOffset]);
487 qWarning() << Q_FUNC_INFO << "Unknown IrcUser:" << e->params()[paramOffset];
491 bool handledByNetsplit = false;
492 QHash<QString, Netsplit*> splits = _netsplits.value(e->network());
493 for (Netsplit* n : _netsplits.value(e->network())) {
494 handledByNetsplit = n->userAlreadyJoined(ircUser->hostmask(), channel->name());
495 if (handledByNetsplit) {
496 n->addMode(ircUser->hostmask(), channel->name(), QString(mode));
500 if (!handledByNetsplit)
501 channel->addUserMode(ircUser, QString(mode));
504 channel->removeUserMode(ircUser, QString(mode));
508 qWarning() << "Received MODE with too few parameters:" << e->params();
513 // regular channel modes
515 Network::ChannelModeType modeType = e->network()->channelModeType(mode);
516 if (modeType == Network::A_CHANMODE || modeType == Network::B_CHANMODE || (modeType == Network::C_CHANMODE && add)) {
517 if (paramOffset < e->params().count()) {
518 value = e->params()[paramOffset];
521 qWarning() << "Received MODE with too few parameters:" << e->params();
527 channel->addChannelMode(mode, value);
529 channel->removeChannelMode(mode, value);
535 IrcUser* ircUser = e->network()->newIrcUser(e->params().first());
536 QString modeString(e->params()[1]);
540 for (int c = 0; c < modeString.count(); c++) {
541 if (modeString[c] == '+') {
545 if (modeString[c] == '-') {
550 addModes += modeString[c];
552 removeModes += modeString[c];
554 if (!addModes.isEmpty())
555 ircUser->addUserModes(addModes);
556 if (!removeModes.isEmpty())
557 ircUser->removeUserModes(removeModes);
559 if (e->network()->isMe(ircUser)) {
560 // Mark the message as Self
561 e->setFlag(EventManager::Self);
562 coreNetwork(e)->updatePersistentModes(addModes, removeModes);
567 void CoreSessionEventProcessor::processIrcEventNick(IrcEvent* e)
569 if (checkParamCount(e, 1)) {
570 IrcUser* ircuser = e->network()->updateNickFromMask(e->prefix());
572 qWarning() << Q_FUNC_INFO << "Unknown IrcUser!";
576 if (e->network()->isMe(ircuser)) {
577 // Mark the message as Self
578 e->setFlag(EventManager::Self);
581 // Actual processing is handled in lateProcessIrcEventNick(), this just sets the event flag
585 void CoreSessionEventProcessor::lateProcessIrcEventNick(IrcEvent* e)
587 if (checkParamCount(e, 1)) {
588 IrcUser* ircuser = e->network()->updateNickFromMask(e->prefix());
590 qWarning() << Q_FUNC_INFO << "Unknown IrcUser!";
593 QString newnick = e->params().at(0);
594 QString oldnick = ircuser->nick();
596 // the order is cruicial
597 // otherwise the client would rename the buffer, see that the assigned ircuser doesn't match anymore
598 // and remove the ircuser from the querybuffer leading to a wrong on/offline state
599 ircuser->setNick(newnick);
600 coreSession()->renameBuffer(e->networkId(), newnick, oldnick);
604 void CoreSessionEventProcessor::processIrcEventPart(IrcEvent* e)
606 if (checkParamCount(e, 1)) {
607 IrcUser* ircuser = e->network()->updateNickFromMask(e->prefix());
609 qWarning() << Q_FUNC_INFO << "Unknown IrcUser!";
613 if (e->network()->isMe(ircuser)) {
614 // Mark the message as Self
615 e->setFlag(EventManager::Self);
618 // Actual processing is handled in lateProcessIrcEventNick(), this just sets the event flag
622 void CoreSessionEventProcessor::lateProcessIrcEventPart(IrcEvent* e)
624 if (checkParamCount(e, 1)) {
625 IrcUser* ircuser = e->network()->updateNickFromMask(e->prefix());
627 qWarning() << Q_FUNC_INFO << "Unknown IrcUser!";
630 QString channel = e->params().at(0);
631 ircuser->partChannel(channel);
632 if (e->network()->isMe(ircuser)) {
633 qobject_cast<CoreNetwork*>(e->network())->setChannelParted(channel);
638 void CoreSessionEventProcessor::processIrcEventPing(IrcEvent* e)
640 QString param = e->params().count() ? e->params().first() : QString();
642 // Take priority so this won't get stuck behind other queued messages.
643 coreNetwork(e)->putRawLine("PONG " + coreNetwork(e)->serverEncode(param), true);
646 void CoreSessionEventProcessor::processIrcEventPong(IrcEvent* e)
648 // Ensure we get at least one parameter
649 if (!checkParamCount(e, 1))
652 // Some IRC servers respond with only one parameter, others respond with two, with the latter
653 // being the text sent. Handle both situations.
655 if (e->params().count() < 2) {
656 // Only one parameter received
657 // :localhost PONG 02:43:49.565
658 timestamp = e->params().at(0);
661 // Two parameters received, pick the second
662 // :localhost PONG localhost :02:43:49.565
663 timestamp = e->params().at(1);
666 // The server is supposed to send back what we passed as parameter, and we send a timestamp.
667 // However, using quote and whatnot, one can send arbitrary pings, and IRC servers may decide to
668 // ignore our requests entirely and send whatever they want, so we have to do some sanity
671 // Attempt to parse the timestamp
672 QTime sendTime = QTime::fromString(timestamp, "hh:mm:ss.zzz");
673 if (sendTime.isValid()) {
674 // Mark IRC server as sending valid ping replies
675 if (!coreNetwork(e)->isPongTimestampValid()) {
676 coreNetwork(e)->setPongTimestampValid(true);
677 // Add a message the first time it happens
678 qDebug().nospace() << "Received PONG with valid timestamp, marking pong replies on "
680 << "\"" << qPrintable(e->network()->networkName())
681 << "\" (ID: " << qPrintable(QString::number(e->network()->networkId().toInt()))
682 << ") as usable for latency measurement";
684 // Remove pending flag
685 coreNetwork(e)->resetPongReplyPending();
687 // Don't show this in the UI
688 e->setFlag(EventManager::Silent);
689 // TODO: To allow for a user-sent /ping (without arguments, so default timestamp is used),
690 // this could track how many automated PINGs have been sent by the core and subtract one
691 // each time, only marking the PING as silent if there's pending automated pong replies.
692 // However, that's a behavior change which warrants further testing. For now, take the
693 // simpler, previous approach that errs on the side of silencing too much.
695 // Calculate latency from time difference, divided by 2 to account for round-trip time
696 e->network()->setLatency(sendTime.msecsTo(QTime::currentTime()) / 2);
698 else if (coreNetwork(e)->isPongReplyPending() && !coreNetwork(e)->isPongTimestampValid()) {
699 // There's an auto-PING reply pending and we've not yet received a PONG reply with a valid
700 // timestamp. It's possible this server will never respond with a valid timestamp, and thus
701 // any automated PINGs will result in unwanted spamming of the server buffer.
703 // Don't show this in the UI
704 e->setFlag(EventManager::Silent);
705 // Remove pending flag
706 coreNetwork(e)->resetPongReplyPending();
709 qDebug().nospace() << "Received PONG with invalid timestamp from network "
710 << "\"" << qPrintable(e->network()->networkName())
711 << "\" (ID: " << qPrintable(QString::number(e->network()->networkId().toInt()))
712 << "), silencing, parameters are " << e->params();
714 // else: We're not expecting a PONG reply and timestamp is not valid, assume it's from the user
717 void CoreSessionEventProcessor::processIrcEventQuit(IrcEvent* e)
719 IrcUser* ircuser = e->network()->updateNickFromMask(e->prefix());
723 if (e->network()->isMe(ircuser)) {
724 // Mark the message as Self
725 e->setFlag(EventManager::Self);
729 if (e->params().count() > 0)
730 msg = e->params()[0];
733 if (Netsplit::isNetsplit(msg)) {
735 if (!_netsplits[e->network()].contains(msg)) {
736 n = new Netsplit(e->network(), this);
737 connect(n, &Netsplit::finished, this, &CoreSessionEventProcessor::handleNetsplitFinished);
738 connect(n, &Netsplit::netsplitJoin, this, &CoreSessionEventProcessor::handleNetsplitJoin);
739 connect(n, &Netsplit::netsplitQuit, this, &CoreSessionEventProcessor::handleNetsplitQuit);
740 connect(n, &Netsplit::earlyJoin, this, &CoreSessionEventProcessor::handleEarlyNetsplitJoin);
741 _netsplits[e->network()].insert(msg, n);
744 n = _netsplits[e->network()][msg];
746 // add this user to the netsplit
747 n->userQuit(e->prefix(), ircuser->channels(), msg);
748 e->setFlag(EventManager::Netsplit);
750 // normal quit is handled in lateProcessIrcEventQuit()
753 void CoreSessionEventProcessor::lateProcessIrcEventQuit(IrcEvent* e)
755 if (e->testFlag(EventManager::Netsplit))
758 IrcUser* ircuser = e->network()->updateNickFromMask(e->prefix());
765 void CoreSessionEventProcessor::processIrcEventTopic(IrcEvent* e)
767 if (checkParamCount(e, 2)) {
768 IrcUser* ircuser = e->network()->updateNickFromMask(e->prefix());
770 if (e->network()->isMe(ircuser)) {
771 // Mark the message as Self
772 e->setFlag(EventManager::Self);
775 IrcChannel* channel = e->network()->ircChannel(e->params().at(0));
777 channel->setTopic(e->params().at(1));
781 /* ERROR - "ERROR :reason"
782 Example: ERROR :Closing Link: nickname[xxx.xxx.xxx.xxx] (Large base64 image paste.)
783 See https://tools.ietf.org/html/rfc2812#section-3.7.4 */
784 void CoreSessionEventProcessor::processIrcEventError(IrcEvent* e)
786 if (!checkParamCount(e, 1))
789 if (coreNetwork(e)->disconnectExpected()) {
790 // During QUIT, the server should send an error (often, but not always, "Closing Link"). As
791 // we're expecting it, don't show this to the user.
792 e->setFlag(EventManager::Silent);
797 // IRCv3 SETNAME - ":nick!user@host SETNAME :realname goes here"
798 // Example: :batman!~batman@bat.cave SETNAME :Bruce Wayne <bruce@wayne.enterprises>
800 // See https://ircv3.net/specs/extensions/setname
801 void CoreSessionEventProcessor::processIrcEventSetname(IrcEvent* e)
803 if (checkParamCount(e, 1)) {
804 IrcUser* ircuser = e->network()->updateNickFromMask(e->prefix());
806 qWarning() << Q_FUNC_INFO << "Unknown IrcUser!";
810 QString newname = e->params().at(0);
811 ircuser->setRealName(newname);
816 void CoreSessionEventProcessor::processKeyEvent(KeyEvent* e)
818 if (!Cipher::neededFeaturesAvailable()) {
819 emit newEvent(new MessageEvent(Message::Error,
821 tr("Unable to perform key exchange, missing qca-ossl plugin."),
828 auto* net = qobject_cast<CoreNetwork*>(e->network());
829 Cipher* c = net->cipher(e->target());
830 if (!c) // happens when there is no CoreIrcChannel for the target (i.e. never?)
833 if (e->exchangeType() == KeyEvent::Init) {
834 QByteArray pubKey = c->parseInitKeyX(e->key());
835 if (pubKey.isEmpty()) {
836 emit newEvent(new MessageEvent(Message::Error,
838 tr("Unable to parse the DH1080_INIT. Key exchange failed."),
846 net->setCipherKey(e->target(), c->key());
847 emit newEvent(new MessageEvent(Message::Info,
849 tr("Your key is set and messages will be encrypted."),
855 p << net->serverEncode(e->target()) << net->serverEncode("DH1080_FINISH ") + pubKey;
856 net->putCmd("NOTICE", p);
860 if (c->parseFinishKeyX(e->key())) {
861 net->setCipherKey(e->target(), c->key());
862 emit newEvent(new MessageEvent(Message::Info,
864 tr("Your key is set and messages will be encrypted."),
871 emit newEvent(new MessageEvent(Message::Info,
873 tr("Failed to parse DH1080_FINISH. Key exchange failed."),
884 void CoreSessionEventProcessor::processIrcEvent001(IrcEventNumeric* e)
886 e->network()->setCurrentServer(e->prefix());
887 e->network()->setMyNick(e->target());
891 // TODO Complete 005 handling, also use sensible defaults for non-sent stuff
892 void CoreSessionEventProcessor::processIrcEvent005(IrcEvent* e)
894 if (!checkParamCount(e, 1))
898 for (int i = 0; i < e->params().count() - 1; i++) {
899 QString key = e->params()[i].section("=", 0, 0);
900 QString value = e->params()[i].section("=", 1);
901 e->network()->addSupport(key, value);
904 /* determine our prefixes here to get an accurate result */
905 e->network()->determinePrefixes();
908 /* RPL_UMODEIS - "<user_modes> [<user_mode_params>]" */
909 void CoreSessionEventProcessor::processIrcEvent221(IrcEvent*)
911 // TODO: save information in network object
914 /* RPL_STATSCONN - "Highest connection cout: 8000 (7999 clients)" */
915 void CoreSessionEventProcessor::processIrcEvent250(IrcEvent*)
917 // TODO: save information in network object
920 /* RPL_LOCALUSERS - "Current local user: 5024 Max: 7999 */
921 void CoreSessionEventProcessor::processIrcEvent265(IrcEvent*)
923 // TODO: save information in network object
926 /* RPL_GLOBALUSERS - "Current global users: 46093 Max: 47650" */
927 void CoreSessionEventProcessor::processIrcEvent266(IrcEvent*)
929 // TODO: save information in network object
934 Replies 311 - 313, 317 - 319 are all replies generated in response to a WHOIS message.
936 "<nick> :<away message>"
938 Replies 352 and 315 paired are used to answer a WHO message.
941 Replies 314 and 369 are responses to a WHOWAS message.
945 /* RPL_AWAY - "<nick> :<away message>" */
946 void CoreSessionEventProcessor::processIrcEvent301(IrcEvent* e)
948 if (!checkParamCount(e, 2))
951 IrcUser* ircuser = e->network()->ircUser(e->params().at(0));
953 ircuser->setAway(true);
954 ircuser->setAwayMessage(e->params().at(1));
955 // lastAwayMessageTime is set in EventStringifier::processIrcEvent301(), no need to set it
957 // ircuser->setLastAwayMessageTime(now);
961 /* RPL_UNAWAY - ":You are no longer marked as being away" */
962 void CoreSessionEventProcessor::processIrcEvent305(IrcEvent* e)
964 IrcUser* me = e->network()->me();
968 if (e->network()->autoAwayActive()) {
969 e->network()->setAutoAwayActive(false);
970 e->setFlag(EventManager::Silent);
974 /* RPL_NOWAWAY - ":You have been marked as being away" */
975 void CoreSessionEventProcessor::processIrcEvent306(IrcEvent* e)
977 IrcUser* me = e->network()->me();
982 /* RPL_WHOISSERVICE - "<user> is registered nick" */
983 void CoreSessionEventProcessor::processIrcEvent307(IrcEvent* e)
985 if (!checkParamCount(e, 1))
988 IrcUser* ircuser = e->network()->ircUser(e->params().at(0));
990 ircuser->setWhoisServiceReply(e->params().join(" "));
993 /* RPL_SUSERHOST - "<user> is available for help." */
994 void CoreSessionEventProcessor::processIrcEvent310(IrcEvent* e)
996 if (!checkParamCount(e, 1))
999 IrcUser* ircuser = e->network()->ircUser(e->params().at(0));
1001 ircuser->setSuserHost(e->params().join(" "));
1004 /* RPL_WHOISUSER - "<nick> <user> <host> * :<real name>" */
1005 void CoreSessionEventProcessor::processIrcEvent311(IrcEvent* e)
1007 if (!checkParamCount(e, 3))
1010 IrcUser* ircuser = e->network()->ircUser(e->params().at(0));
1012 ircuser->setUser(e->params().at(1));
1013 ircuser->setHost(e->params().at(2));
1014 ircuser->setRealName(e->params().last());
1018 /* RPL_WHOISSERVER - "<nick> <server> :<server info>" */
1019 void CoreSessionEventProcessor::processIrcEvent312(IrcEvent* e)
1021 if (!checkParamCount(e, 2))
1024 IrcUser* ircuser = e->network()->ircUser(e->params().at(0));
1026 ircuser->setServer(e->params().at(1));
1029 /* RPL_WHOISOPERATOR - "<nick> :is an IRC operator" */
1030 void CoreSessionEventProcessor::processIrcEvent313(IrcEvent* e)
1032 if (!checkParamCount(e, 1))
1035 IrcUser* ircuser = e->network()->ircUser(e->params().at(0));
1037 ircuser->setIrcOperator(e->params().last());
1040 /* RPL_ENDOFWHO: "<name> :End of WHO list" */
1041 void CoreSessionEventProcessor::processIrcEvent315(IrcEvent* e)
1043 if (!checkParamCount(e, 1))
1046 if (coreNetwork(e)->setAutoWhoDone(e->params()[0]))
1047 e->setFlag(EventManager::Silent);
1050 /* RPL_WHOISIDLE - "<nick> <integer> :seconds idle"
1051 (real life: "<nick> <integer> <integer> :seconds idle, signon time) */
1052 void CoreSessionEventProcessor::processIrcEvent317(IrcEvent* e)
1054 if (!checkParamCount(e, 2))
1057 QDateTime loginTime;
1059 int idleSecs = e->params()[1].toInt();
1060 if (e->params().count() > 3) { // if we have more then 3 params we have the above mentioned "real life" situation
1061 // Allow for 64-bit time
1062 qint64 logintime = e->params()[2].toLongLong();
1063 // Time in IRC protocol is defined as seconds. Convert from seconds instead.
1064 // See https://doc.qt.io/qt-5/qdatetime.html#fromSecsSinceEpoch
1065 #if QT_VERSION >= 0x050800
1066 loginTime = QDateTime::fromSecsSinceEpoch(logintime);
1068 // fromSecsSinceEpoch() was added in Qt 5.8. Manually downconvert to seconds for
1070 // See https://doc.qt.io/qt-5/qdatetime.html#fromMSecsSinceEpoch
1071 loginTime = QDateTime::fromMSecsSinceEpoch((qint64)(logintime * 1000));
1075 IrcUser* ircuser = e->network()->ircUser(e->params()[0]);
1077 ircuser->setIdleTime(e->timestamp().addSecs(-idleSecs));
1078 if (loginTime.isValid())
1079 ircuser->setLoginTime(loginTime);
1083 /* RPL_LIST - "<channel> <# visible> :<topic>" */
1084 void CoreSessionEventProcessor::processIrcEvent322(IrcEvent* e)
1086 if (!checkParamCount(e, 1))
1089 QString channelName;
1090 quint32 userCount = 0;
1093 switch (e->params().count()) {
1095 topic = e->params()[2];
1098 userCount = e->params()[1].toUInt();
1101 channelName = e->params()[0];
1106 if (coreSession()->ircListHelper()->addChannel(e->networkId(), channelName, userCount, topic))
1107 e->stop(); // consumed by IrcListHelper, so don't further process/show this event
1110 /* RPL_LISTEND ":End of LIST" */
1111 void CoreSessionEventProcessor::processIrcEvent323(IrcEvent* e)
1113 if (!checkParamCount(e, 1))
1116 if (coreSession()->ircListHelper()->endOfChannelList(e->networkId()))
1117 e->stop(); // consumed by IrcListHelper, so don't further process/show this event
1120 /* RPL_CHANNELMODEIS - "<channel> <mode> <mode params>" */
1121 void CoreSessionEventProcessor::processIrcEvent324(IrcEvent* e)
1123 processIrcEventMode(e);
1126 /* RPL_WHOISACCOUNT - "<nick> <account> :is authed as" */
1127 void CoreSessionEventProcessor::processIrcEvent330(IrcEvent* e)
1129 // Though the ":is authed as" remark should always be there, we should handle cases when it's
1130 // not included, too.
1131 if (!checkParamCount(e, 2))
1134 IrcUser* ircuser = e->network()->ircUser(e->params().at(0));
1136 ircuser->setAccount(e->params().at(1));
1141 void CoreSessionEventProcessor::processIrcEvent331(IrcEvent* e)
1143 if (!checkParamCount(e, 1))
1146 IrcChannel* chan = e->network()->ircChannel(e->params()[0]);
1148 chan->setTopic(QString());
1152 void CoreSessionEventProcessor::processIrcEvent332(IrcEvent* e)
1154 if (!checkParamCount(e, 2))
1157 IrcChannel* chan = e->network()->ircChannel(e->params()[0]);
1159 chan->setTopic(e->params()[1]);
1162 /* RPL_WHOREPLY: "<channel> <user> <host> <server> <nick>
1163 ( "H" / "G" > ["*"] [ ( "@" / "+" ) ] :<hopcount> <real name>" */
1164 void CoreSessionEventProcessor::processIrcEvent352(IrcEvent* e)
1166 if (!checkParamCount(e, 6))
1169 QString channel = e->params()[0];
1170 IrcUser* ircuser = e->network()->ircUser(e->params()[4]);
1172 // Only process the WHO information if an IRC user exists. Don't create an IRC user here;
1173 // there's no way to track when the user quits, which would leave a phantom IrcUser lying
1175 // NOTE: Whenever MONITOR support is introduced, the IrcUser will be created by an
1176 // RPL_MONONLINE numeric before any WHO commands are run.
1177 processWhoInformation(e->network(),
1184 e->params().last().section(" ", 1));
1187 // Check if channel name has a who in progress.
1188 if (coreNetwork(e)->isAutoWhoInProgress(channel)) {
1189 e->setFlag(EventManager::Silent);
1194 void CoreSessionEventProcessor::processIrcEvent353(IrcEvent* e)
1196 if (!checkParamCount(e, 3))
1199 // param[0] is either "=", "*" or "@" indicating a public, private or secret channel
1200 // we don't use this information at the time being
1201 QString channelname = e->params()[1];
1203 IrcChannel* channel = e->network()->ircChannel(channelname);
1205 qWarning() << Q_FUNC_INFO << "Received unknown target channel:" << channelname;
1212 // Cache result of multi-prefix to avoid unneeded casts and lookups with each iteration.
1213 bool _useCapMultiPrefix = coreNetwork(e)->capEnabled(IrcCap::MULTI_PREFIX);
1215 for (QString nick : e->params()[2].split(' ', QString::SkipEmptyParts)) {
1218 if (_useCapMultiPrefix) {
1219 // If multi-prefix is enabled, all modes will be sent in NAMES replies.
1220 // :hades.arpa 353 guest = #tethys :~&@%+aji &@Attila @+alyx +KindOne Argure
1221 // See: http://ircv3.net/specs/extensions/multi-prefix-3.1.html
1222 while (e->network()->prefixes().contains(nick[0])) {
1223 // Mode found in 1 left-most character, add it to the list.
1224 // Note: sending multiple modes may cause a warning in older clients.
1225 // In testing, the clients still seemed to function fine.
1226 mode.append(e->network()->prefixToMode(nick[0]));
1227 // Remove this mode from the nick
1228 nick = nick.remove(0, 1);
1231 else if (e->network()->prefixes().contains(nick[0])) {
1232 // Multi-prefix is disabled and a mode prefix was found.
1233 mode = e->network()->prefixToMode(nick[0]);
1237 // If userhost-in-names capability is enabled, the following will be
1238 // in the form "nick!user@host" rather than "nick". This works without
1239 // special handling as the following use nickFromHost() as needed.
1240 // See: http://ircv3.net/specs/extensions/userhost-in-names-3.2.html
1246 channel->joinIrcUsers(nicks, modes);
1249 /* RPL_WHOSPCRPL: "<yournick> 152 #<channel> ~<ident> <host> <servname> <nick>
1250 ("H"/ "G") <account> :<realname>"
1251 <channel> is * if not specific to any channel
1252 <account> is * if not logged in
1253 Follows HexChat's usage of 'whox'
1254 See https://github.com/hexchat/hexchat/blob/c874a9525c9b66f1d5ddcf6c4107d046eba7e2c5/src/common/proto-irc.c#L750
1255 And http://faerion.sourceforge.net/doc/irc/whox.var*/
1256 void CoreSessionEventProcessor::processIrcEvent354(IrcEvent* e)
1258 // First only check if at least one parameter exists. Otherwise, it'll stop the result from
1259 // being shown if the user chooses different parameters.
1260 if (!checkParamCount(e, 1))
1263 if (e->params()[0].toUInt() != IrcCap::ACCOUNT_NOTIFY_WHOX_NUM) {
1264 // Ignore WHOX replies without expected number for we have no idea what fields are specified
1268 // Now we're fairly certain this is supposed to be an automated WHOX. Bail out if it doesn't
1269 // match what we require - 9 parameters.
1270 if (!checkParamCount(e, 9))
1273 QString channel = e->params()[1];
1274 IrcUser* ircuser = e->network()->ircUser(e->params()[5]);
1276 // Only process the WHO information if an IRC user exists. Don't create an IRC user here;
1277 // there's no way to track when the user quits, which would leave a phantom IrcUser lying
1279 // NOTE: Whenever MONITOR support is introduced, the IrcUser will be created by an
1280 // RPL_MONONLINE numeric before any WHO commands are run.
1281 processWhoInformation(e->network(), channel, ircuser, e->params()[4], e->params()[2], e->params()[3], e->params()[6], e->params().last());
1282 // Don't use .section(" ", 1) with WHOX replies, for there's no hopcount to trim out
1284 // As part of IRCv3 account-notify, check account name
1285 // WHOX uses '0' to indicate logged-out, account-notify and extended-join uses '*'.
1286 QString newAccount = e->params()[7];
1287 if (newAccount != "0") {
1288 // Account logged in, set account name
1289 ircuser->setAccount(newAccount);
1292 // Account logged out, set account name to logged-out
1293 ircuser->setAccount("*");
1297 // Check if channel name has a who in progress.
1298 if (coreNetwork(e)->isAutoWhoInProgress(channel)) {
1299 e->setFlag(EventManager::Silent);
1303 void CoreSessionEventProcessor::processWhoInformation(Network* net,
1304 const QString& targetChannel,
1306 const QString& server,
1307 const QString& user,
1308 const QString& host,
1309 const QString& awayStateAndModes,
1310 const QString& realname)
1312 ircUser->setUser(user);
1313 ircUser->setHost(host);
1314 ircUser->setServer(server);
1315 ircUser->setRealName(realname);
1317 bool away = awayStateAndModes.contains("G", Qt::CaseInsensitive);
1318 ircUser->setAway(away);
1320 if (net->capEnabled(IrcCap::MULTI_PREFIX)) {
1321 // If multi-prefix is enabled, all modes will be sent in WHO replies.
1322 // :kenny.chatspike.net 352 guest #test grawity broken.symlink *.chatspike.net grawity H@%+ :0 Mantas M.
1323 // See: http://ircv3.net/specs/extensions/multi-prefix-3.1.html
1324 QString uncheckedModes = awayStateAndModes;
1325 QString validModes = QString();
1326 while (!uncheckedModes.isEmpty()) {
1327 // Mode found in 1 left-most character, add it to the list
1328 if (net->prefixes().contains(uncheckedModes[0])) {
1329 validModes.append(net->prefixToMode(uncheckedModes[0]));
1331 // Remove this mode from the list of unchecked modes
1332 uncheckedModes = uncheckedModes.remove(0, 1);
1335 // Some IRC servers decide to not follow the spec, returning only -some- of the user
1336 // modes in WHO despite listing them all in NAMES. For now, assume it can only add
1337 // and not take away. *sigh*
1338 if (!validModes.isEmpty()) {
1339 if (targetChannel != "*") {
1340 // Channel-specific modes received, apply to given channel only
1341 IrcChannel* ircChan = net->ircChannel(targetChannel);
1343 // Do one mode at a time
1344 // TODO Better way of syncing this without breaking protocol?
1345 for (int i = 0; i < validModes.count(); ++i) {
1346 ircChan->addUserMode(ircUser, validModes.at(i));
1351 // Modes apply to the user everywhere
1352 ircUser->addUserModes(validModes);
1358 /* ERR_NOSUCHCHANNEL - "<channel name> :No such channel" */
1359 void CoreSessionEventProcessor::processIrcEvent403(IrcEventNumeric* e)
1361 // If this is the result of an AutoWho, hide it. It's confusing to show to the user.
1362 // Though the ":No such channel" remark should always be there, we should handle cases when it's
1363 // not included, too.
1364 if (!checkParamCount(e, 1))
1367 QString channelOrNick = e->params()[0];
1368 // Check if channel name has a who in progress.
1369 // If not, then check if user nick exists and has a who in progress.
1370 if (coreNetwork(e)->isAutoWhoInProgress(channelOrNick)) {
1371 qDebug() << "Channel/nick" << channelOrNick << "no longer exists during AutoWho, ignoring";
1372 e->setFlag(EventManager::Silent);
1376 /* ERR_ERRONEUSNICKNAME */
1377 void CoreSessionEventProcessor::processIrcEvent432(IrcEventNumeric* e)
1379 if (!checkParamCount(e, 1))
1383 if (e->params().count() < 2) {
1384 // handle unreal-ircd bug, where unreal ircd doesn't supply a TARGET in ERR_ERRONEUSNICKNAME during registration phase:
1386 // :irc.scortum.moep.net 432 @@@ :Erroneous Nickname: Illegal characters
1387 // correct server reply:
1388 // :irc.scortum.moep.net 432 * @@@ :Erroneous Nickname: Illegal characters
1389 e->params().prepend(e->target());
1392 errnick = e->params()[0];
1394 tryNextNick(e, errnick, true /* erroneus */);
1397 /* ERR_NICKNAMEINUSE */
1398 void CoreSessionEventProcessor::processIrcEvent433(IrcEventNumeric* e)
1400 if (!checkParamCount(e, 1))
1403 QString errnick = e->params().first();
1405 // if there is a problem while connecting to the server -> we handle it
1406 // but only if our connection has not been finished yet...
1407 if (!e->network()->currentServer().isEmpty())
1410 tryNextNick(e, errnick);
1413 /* ERR_UNAVAILRESOURCE */
1414 void CoreSessionEventProcessor::processIrcEvent437(IrcEventNumeric* e)
1416 if (!checkParamCount(e, 1))
1419 QString errnick = e->params().first();
1421 // if there is a problem while connecting to the server -> we handle it
1422 // but only if our connection has not been finished yet...
1423 if (!e->network()->currentServer().isEmpty())
1426 if (!e->network()->isChannelName(errnick))
1427 tryNextNick(e, errnick);
1431 void CoreSessionEventProcessor::processIrcEvent(IrcEvent *e) {
1432 if(!checkParamCount(e, 1))
1438 /* Handle signals from Netsplit objects */
1440 void CoreSessionEventProcessor::handleNetsplitJoin(
1441 Network* net, const QString& channel, const QStringList& users, const QStringList& modes, const QString& quitMessage)
1443 IrcChannel* ircChannel = net->ircChannel(channel);
1447 QList<IrcUser*> ircUsers;
1448 QStringList newModes = modes;
1449 QStringList newUsers = users;
1451 for (const QString& user : users) {
1452 IrcUser* iu = net->ircUser(nickFromMask(user));
1454 ircUsers.append(iu);
1455 else { // the user already quit
1456 int idx = users.indexOf(user);
1457 newUsers.removeAt(idx);
1458 newModes.removeAt(idx);
1462 ircChannel->joinIrcUsers(ircUsers, newModes);
1463 NetworkSplitEvent* event = new NetworkSplitEvent(EventManager::NetworkSplitJoin, net, channel, newUsers, quitMessage);
1464 emit newEvent(event);
1467 void CoreSessionEventProcessor::handleNetsplitQuit(Network* net, const QString& channel, const QStringList& users, const QString& quitMessage)
1469 NetworkSplitEvent* event = new NetworkSplitEvent(EventManager::NetworkSplitQuit, net, channel, users, quitMessage);
1470 emit newEvent(event);
1471 for (const QString& user : users) {
1472 IrcUser* ircUser = net->ircUser(nickFromMask(user));
1473 if (ircUser) ircUser->quit();
1477 void CoreSessionEventProcessor::handleEarlyNetsplitJoin(Network* net, const QString& channel, const QStringList& users, const QStringList& modes)
1479 IrcChannel* ircChannel = net->ircChannel(channel);
1481 qDebug() << "handleEarlyNetsplitJoin(): channel " << channel << " invalid";
1484 QList<NetworkEvent*> events;
1485 QList<IrcUser*> ircUsers;
1486 QStringList newModes = modes;
1488 for (const QString& user : users) {
1489 IrcUser* ircUser = net->updateNickFromMask(user);
1491 ircUsers.append(ircUser);
1492 // fake event for scripts that consume join events
1493 events << new IrcEvent(EventManager::IrcEventJoin, net, {}, ircUser->hostmask(), QStringList() << channel);
1496 newModes.removeAt(users.indexOf(user));
1499 ircChannel->joinIrcUsers(ircUsers, newModes);
1500 for (NetworkEvent* event : events) {
1501 event->setFlag(EventManager::Fake); // ignore this in here!
1502 emit newEvent(event);
1506 void CoreSessionEventProcessor::handleNetsplitFinished()
1508 auto* n = qobject_cast<Netsplit*>(sender());
1510 QHash<QString, Netsplit*> splithash = _netsplits.take(n->network());
1511 splithash.remove(splithash.key(n));
1512 if (splithash.count())
1513 _netsplits[n->network()] = splithash;
1517 void CoreSessionEventProcessor::destroyNetsplits(NetworkId netId)
1519 Network* net = coreSession()->network(netId);
1523 QHash<QString, Netsplit*> splits = _netsplits.take(net);
1527 /*******************************/
1528 /******** CTCP HANDLING ********/
1529 /*******************************/
1531 void CoreSessionEventProcessor::processCtcpEvent(CtcpEvent* e)
1533 if (e->testFlag(EventManager::Self))
1534 return; // ignore ctcp events generated by user input
1536 if (e->type() != EventManager::CtcpEvent || e->ctcpType() != CtcpEvent::Query)
1539 handle(e->ctcpCmd(), Q_ARG(CtcpEvent*, e));
1542 void CoreSessionEventProcessor::defaultHandler(const QString& ctcpCmd, CtcpEvent* e)
1544 // This handler is only there to avoid warnings for unknown CTCPs
1549 void CoreSessionEventProcessor::handleCtcpAction(CtcpEvent* e)
1551 // This handler is only there to feed CLIENTINFO
1555 void CoreSessionEventProcessor::handleCtcpClientinfo(CtcpEvent* e)
1557 QStringList supportedHandlers;
1558 for (const QString& handler : providesHandlers())
1559 supportedHandlers << handler.toUpper();
1560 std::sort(supportedHandlers.begin(), supportedHandlers.end());
1561 e->setReply(supportedHandlers.join(" "));
1564 // http://www.irchelp.org/irchelp/rfc/ctcpspec.html
1565 // http://en.wikipedia.org/wiki/Direct_Client-to-Client
1566 void CoreSessionEventProcessor::handleCtcpDcc(CtcpEvent* e)
1568 // DCC support is unfinished, experimental and potentially dangerous, so make it opt-in
1569 if (!Quassel::isOptionSet("enable-experimental-dcc")) {
1570 qInfo() << "DCC disabled, start core with --enable-experimental-dcc if you really want to try it out";
1574 // normal: SEND <filename> <ip> <port> [<filesize>]
1575 // reverse: SEND <filename> <ip> 0 <filesize> <token>
1576 QStringList params = e->param().split(' ');
1577 if (params.count()) {
1578 QString cmd = params[0].toUpper();
1579 if (cmd == "SEND") {
1580 if (params.count() < 4) {
1581 qWarning() << "Invalid DCC SEND request:" << e; // TODO emit proper error to client
1584 QString filename = params[1];
1585 QHostAddress address;
1586 quint16 port = params[3].toUShort();
1588 QString numIp = params[2]; // this is either IPv4 as a 32 bit value, or IPv6 (which always contains a colon)
1589 if (numIp.contains(':')) { // IPv6
1590 if (!address.setAddress(numIp)) {
1591 qWarning() << "Invalid IPv6:" << numIp;
1596 address.setAddress(numIp.toUInt());
1599 if (port == 0) { // Reverse DCC is indicated by a 0 port
1600 emit newEvent(new MessageEvent(Message::Error,
1602 tr("Reverse DCC SEND not supported"),
1610 qWarning() << "Privileged port requested:" << port; // FIXME ask user if this is ok
1613 if (params.count() > 4) { // filesize is optional
1614 size = params[4].toULong();
1617 // TODO: check if target is the right thing to use for the partner
1618 CoreTransfer* transfer = new CoreTransfer(Transfer::Direction::Receive, e->target(), filename, address, port, size, this);
1619 coreSession()->signalProxy()->synchronize(transfer);
1620 coreSession()->transferManager()->addTransfer(transfer);
1623 emit newEvent(new MessageEvent(Message::Error,
1625 tr("DCC %1 not supported").arg(cmd),
1635 void CoreSessionEventProcessor::handleCtcpPing(CtcpEvent* e)
1637 e->setReply(e->param().isNull() ? "" : e->param());
1640 void CoreSessionEventProcessor::handleCtcpTime(CtcpEvent* e)
1642 // Use the ISO standard to avoid locale-specific translated names
1643 // Include timezone offset data to show which timezone a user's in, otherwise we're providing
1644 // NTP-over-IRC with terrible accuracy.
1645 e->setReply(formatDateTimeToOffsetISO(QDateTime::currentDateTime()));
1648 void CoreSessionEventProcessor::handleCtcpVersion(CtcpEvent* e)
1650 // Deliberately do not translate project name
1651 // Use the ISO standard to avoid locale-specific translated names
1652 // Use UTC time to provide a consistent string regardless of timezone
1653 // (Statistics tracking tools usually only group client versions by exact string matching)
1654 e->setReply(QString("Quassel IRC %1 (version date %2) -- https://www.quassel-irc.org")
1655 .arg(Quassel::buildInfo().plainVersionString)
1656 .arg(Quassel::buildInfo().commitDate.isEmpty()
1658 : tryFormatUnixEpoch(Quassel::buildInfo().commitDate, Qt::DateFormat::ISODate, true)));