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 "coresessioneventprocessor.h"
23 #include "coreirclisthelper.h"
24 #include "corenetwork.h"
25 #include "coresession.h"
26 #include "coretransfer.h"
27 #include "coretransfermanager.h"
28 #include "ctcpevent.h"
31 #include "messageevent.h"
36 # include "keyevent.h"
42 CoreSessionEventProcessor::CoreSessionEventProcessor(CoreSession* session)
43 : BasicHandler("handleCtcp", session)
44 , _coreSession(session)
46 connect(coreSession(), &CoreSession::networkDisconnected, this, &CoreSessionEventProcessor::destroyNetsplits);
47 connect(this, &CoreSessionEventProcessor::newEvent, coreSession()->eventManager(), &EventManager::postEvent);
50 bool CoreSessionEventProcessor::checkParamCount(IrcEvent* e, int minParams)
52 if (e->params().count() < minParams) {
53 if (e->type() == EventManager::IrcEventNumeric) {
54 qWarning() << "Command " << static_cast<IrcEventNumeric*>(e)->number() << " requires " << minParams
55 << "params, got: " << e->params();
58 QString name = coreSession()->eventManager()->enumName(e->type());
59 qWarning() << qPrintable(name) << "requires" << minParams << "params, got:" << e->params();
67 void CoreSessionEventProcessor::tryNextNick(NetworkEvent* e, const QString& errnick, bool erroneus)
69 QStringList desiredNicks = coreSession()->identity(e->network()->identity())->nicks();
70 int nextNickIdx = desiredNicks.indexOf(errnick) + 1;
72 if (nextNickIdx > 0 && desiredNicks.size() > nextNickIdx) {
73 nextNick = desiredNicks[nextNickIdx];
77 // FIXME Make this an ErrorEvent or something like that, so it's translated in the client
78 MessageEvent* msgEvent = new MessageEvent(Message::Error,
80 tr("No free and valid nicks in nicklist found. use: /nick <othernick> to continue"),
85 emit newEvent(msgEvent);
89 nextNick = errnick + "_";
92 // FIXME Use a proper output event for this
93 coreNetwork(e)->putRawLine("NICK " + coreNetwork(e)->encodeServerString(nextNick));
96 void CoreSessionEventProcessor::processIrcEventNumeric(IrcEventNumeric* e)
98 switch (e->number()) {
99 // SASL authentication replies
100 // See: http://ircv3.net/specs/extensions/sasl-3.1.html
102 // case 900: // RPL_LOGGEDIN
103 // case 901: // RPL_LOGGEDOUT
104 // Don't use 900 or 901 for updating the local hostmask. Unreal 3.2 gives it as the IP address
105 // even when cloaked.
106 // Every other reply should result in moving on
107 // TODO Handle errors to stop connection if appropriate
108 case 902: // ERR_NICKLOCKED
109 case 903: // RPL_SASLSUCCESS
110 case 904: // ERR_SASLFAIL
111 case 905: // ERR_SASLTOOLONG
112 case 906: // ERR_SASLABORTED
113 case 907: // ERR_SASLALREADY
114 // Move on to the next capability
115 coreNetwork(e)->sendNextCap();
123 void CoreSessionEventProcessor::processIrcEventAuthenticate(IrcEvent* e)
125 if (!checkParamCount(e, 1))
128 if (e->params().at(0) != "+") {
129 qWarning() << "Invalid AUTHENTICATE" << e;
133 CoreNetwork* net = coreNetwork(e);
136 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);
149 net->putRawLine("AUTHENTICATE +");
154 void CoreSessionEventProcessor::processIrcEventCap(IrcEvent* e)
156 // Handle capability negotiation
157 // See: http://ircv3.net/specs/core/capability-negotiation-3.2.html
158 // And: http://ircv3.net/specs/core/capability-negotiation-3.1.html
160 // All commands require at least 2 parameters
161 if (!checkParamCount(e, 2))
164 CoreNetwork* coreNet = coreNetwork(e);
165 QString capCommand = e->params().at(1).trimmed().toUpper();
166 if (capCommand == "LS" || capCommand == "NEW") {
167 // Either we've gotten a list of capabilities, or new capabilities we may want
168 // Server: CAP * LS * :multi-prefix extended-join account-notify batch invite-notify tls
169 // Server: CAP * LS * :cap-notify server-time example.org/dummy-cap=dummyvalue example.org/second-dummy-cap
170 // Server: CAP * LS :userhost-in-names sasl=EXTERNAL,DH-AES,DH-BLOWFISH,ECDSA-NIST256P-CHALLENGE,PLAIN
171 bool capListFinished;
172 QStringList availableCaps;
173 if (e->params().count() == 4) {
174 // Middle of multi-line reply, ignore the asterisk
175 capListFinished = false;
176 availableCaps = e->params().at(3).split(' ');
180 capListFinished = true;
181 if (e->params().count() >= 3) {
182 // Some capabilities are specified, add them
183 availableCaps = e->params().at(2).split(' ');
186 // No capabilities available, add an empty list
187 availableCaps = QStringList();
190 // Sort capabilities before requesting for consistency among networks. This may avoid
191 // unexpected cases when some networks offer capabilities in a different order than
192 // others. It also looks nicer in logs. Not required.
193 availableCaps.sort();
194 // Store what capabilities are available
195 QString availableCapName, availableCapValue;
196 for (int i = 0; i < availableCaps.count(); ++i) {
197 // Capability may include values, e.g. CAP * LS :multi-prefix sasl=EXTERNAL
198 // Capability name comes before the first '='. If no '=' exists, this gets the
199 // whole string instead.
200 availableCapName = availableCaps[i].section('=', 0, 0).trimmed();
201 // Some capabilities include multiple key=value pairs in the listing,
202 // e.g. "sts=duration=31536000,port=6697"
203 // Include everything after the first equal sign as part of the value. If no '='
204 // exists, this gets an empty string.
205 availableCapValue = availableCaps[i].section('=', 1).trimmed();
206 // Only add the capability if it's non-empty
207 if (!availableCapName.isEmpty()) {
208 coreNet->addCap(availableCapName, availableCapValue);
212 // Begin capability requests when capability listing complete
214 coreNet->beginCapNegotiation();
216 else if (capCommand == "ACK") {
217 // CAP ACK requires at least 3 parameters (no empty response allowed)
218 if (!checkParamCount(e, 3)) {
219 // If an invalid reply is sent, try to continue rather than getting stuck.
220 coreNet->sendNextCap();
224 // Server: CAP * ACK :multi-prefix sasl
225 // Got the capabilities we want, handle as needed.
226 QStringList acceptedCaps;
227 acceptedCaps = e->params().at(2).split(' ');
229 // Store what capability was acknowledged
232 // Keep track of whether or not a capability requires further configuration. Due to queuing
233 // logic in CoreNetwork::queueCap(), this shouldn't ever happen when more than one
234 // capability is requested, but it's better to handle edge cases or faulty servers.
235 bool capsRequireConfiguration = false;
237 for (int i = 0; i < acceptedCaps.count(); ++i) {
238 acceptedCap = acceptedCaps[i].trimmed().toLower();
239 // Mark this cap as accepted
240 coreNet->acknowledgeCap(acceptedCap);
241 if (!capsRequireConfiguration && coreNet->capsRequiringConfiguration.contains(acceptedCap)) {
242 capsRequireConfiguration = true;
243 // Some capabilities (e.g. SASL) require further messages to finish. If so, do NOT
244 // send the next capability; it will be handled elsewhere in CoreNetwork.
245 // Otherwise, allow moving on to the next capability.
249 if (!capsRequireConfiguration) {
250 // No additional configuration required, move on to the next capability
251 coreNet->sendNextCap();
254 else if (capCommand == "NAK" || capCommand == "DEL") {
255 // CAP NAK/DEL require at least 3 parameters (no empty response allowed)
256 if (!checkParamCount(e, 3)) {
257 if (capCommand == "NAK") {
258 // If an invalid reply is sent, try to continue rather than getting stuck. This
259 // only matters for denied caps, not removed caps.
260 coreNet->sendNextCap();
265 // Either something went wrong with the capabilities, or they are no longer supported
267 // Server: CAP * NAK :multi-prefix sasl
269 // Server: :irc.example.com CAP modernclient DEL :multi-prefix sasl
270 // CAP NAK and CAP DEL replies are always single-line
272 QStringList removedCaps;
273 removedCaps = e->params().at(2).split(' ');
275 // Store the capabilities that were denied or removed
277 for (int i = 0; i < removedCaps.count(); ++i) {
278 removedCap = removedCaps[i].trimmed().toLower();
279 // Mark this cap as removed.
280 // For CAP DEL, removes it from use.
281 // For CAP NAK when received before negotiation enabled these capabilities, removeCap()
282 // should do nothing. This merely guards against non-spec servers sending an
283 // unsolicited CAP ACK then later removing that capability.
284 coreNet->removeCap(removedCap);
287 if (capCommand == "NAK") {
288 // Continue negotiation only if this is the result of denied caps, not removed caps
289 if (removedCaps.count() > 1) {
290 // We've received a CAP NAK reply to multiple capabilities at once. Unfortunately,
291 // we don't know which capability failed and which ones are valid to re-request, so
292 // individually retry each capability from the failed bundle.
293 // See CoreNetwork::retryCapsIndividually() for more details.
294 coreNet->retryCapsIndividually();
295 // Still need to call sendNextCap() to carry on.
297 // Carry on with negotiation
298 coreNet->sendNextCap();
303 /* IRCv3 account-notify
304 * Log in: ":nick!user@host ACCOUNT accountname"
305 * Log out: ":nick!user@host ACCOUNT *" */
306 void CoreSessionEventProcessor::processIrcEventAccount(IrcEvent* e)
308 if (!checkParamCount(e, 1))
311 IrcUser* ircuser = e->network()->updateNickFromMask(e->prefix());
313 // WHOX uses '0' to indicate logged-out, account-notify and extended-join uses '*'.
314 // As '*' is used internally to represent logged-out, no need to handle that differently.
315 ircuser->setAccount(e->params().at(0));
318 qDebug() << "Received account-notify data for unknown user" << e->prefix();
322 /* IRCv3 away-notify - ":nick!user@host AWAY [:message]" */
323 void CoreSessionEventProcessor::processIrcEventAway(IrcEvent* e)
325 if (!checkParamCount(e, 1))
327 // Don't use checkParamCount(e, 2) since the message is optional. Some servers respond in a way
328 // that it counts as two parameters, but we shouldn't rely on that.
330 // Nick is sent as part of parameters in order to split user/server decoding
331 IrcUser* ircuser = e->network()->ircUser(e->params().at(0));
333 // If two parameters are sent -and- the second parameter isn't empty, then user is away.
334 // Otherwise, mark them as not away.
335 if (e->params().count() >= 2 && !e->params().at(1).isEmpty()) {
336 ircuser->setAway(true);
337 ircuser->setAwayMessage(e->params().at(1));
340 ircuser->setAway(false);
344 qDebug() << "Received away-notify data for unknown user" << e->params().at(0);
348 /* IRCv3 chghost - ":nick!user@host CHGHOST newuser new.host.goes.here" */
349 void CoreSessionEventProcessor::processIrcEventChghost(IrcEvent* e)
351 if (!checkParamCount(e, 2))
354 IrcUser* ircuser = e->network()->updateNickFromMask(e->prefix());
356 // Update with new user/hostname information. setUser/setHost handles checking what
358 ircuser->setUser(e->params().at(0));
359 ircuser->setHost(e->params().at(1));
362 qDebug() << "Received chghost data for unknown user" << e->prefix();
366 void CoreSessionEventProcessor::processIrcEventInvite(IrcEvent* e)
368 if (checkParamCount(e, 2)) {
369 e->network()->updateNickFromMask(e->prefix());
373 /* JOIN: ":<nick!user@host> JOIN <channel>" */
374 void CoreSessionEventProcessor::processIrcEventJoin(IrcEvent* e)
376 if (e->testFlag(EventManager::Fake)) // generated by handleEarlyNetsplitJoin
379 if (!checkParamCount(e, 1))
382 CoreNetwork* net = coreNetwork(e);
383 QString channel = e->params()[0];
384 IrcUser* ircuser = net->updateNickFromMask(e->prefix());
386 if (net->capEnabled(IrcCap::EXTENDED_JOIN)) {
387 if (e->params().count() < 3) {
388 // Some IRC servers don't send extended-join events in all situations. Rather than
389 // ignore the join entirely, treat it as a regular join with a debug-level log entry.
390 // See: https://github.com/inspircd/inspircd/issues/821
391 qDebug() << "extended-join requires 3 params, got:" << e->params()
392 << ", handling as a "
396 // If logged in, :nick!user@host JOIN #channelname accountname :Real Name
397 // If logged out, :nick!user@host JOIN #channelname * :Real Name
398 // See: http://ircv3.net/specs/extensions/extended-join-3.1.html
399 // WHOX uses '0' to indicate logged-out, account-notify and extended-join uses '*'.
400 // As '*' is used internally to represent logged-out, no need to handle that differently.
401 ircuser->setAccount(e->params()[1]);
402 // Update the user's real name, too
403 ircuser->setRealName(e->params()[2]);
406 // Else :nick!user@host JOIN #channelname
408 bool handledByNetsplit = false;
409 foreach (Netsplit* n, _netsplits.value(e->network())) {
410 handledByNetsplit = n->userJoined(e->prefix(), channel);
411 if (handledByNetsplit)
415 // With "away-notify" enabled, some IRC servers forget to send :away messages for users who join
416 // channels while away. Unfortunately, working around this involves WHO'ng every single user as
417 // they join, which is not very efficient. If at all possible, it's better to get the issue
418 // fixed in the IRC server instead.
420 // If pursuing a workaround instead, this is where you'd do it. Check the version control
421 // history for the commit that added this comment to see how to implement it - there's some
422 // unexpected situations to watch out for!
424 // See https://ircv3.net/specs/extensions/away-notify-3.1.html
426 if (!handledByNetsplit)
427 ircuser->joinChannel(channel);
429 e->setFlag(EventManager::Netsplit);
431 if (net->isMe(ircuser)) {
432 net->setChannelJoined(channel);
433 // Mark the message as Self
434 e->setFlag(EventManager::Self);
436 net->putRawLine(net->serverEncode("MODE " + channel)); // we want to know the modes of the channel we just joined, so we ask politely
440 void CoreSessionEventProcessor::lateProcessIrcEventKick(IrcEvent* e)
442 if (checkParamCount(e, 2)) {
443 e->network()->updateNickFromMask(e->prefix());
444 IrcUser* victim = e->network()->ircUser(e->params().at(1));
446 victim->partChannel(e->params().at(0));
447 // if(e->network()->isMe(victim)) e->network()->setKickedFromChannel(channel);
452 void CoreSessionEventProcessor::processIrcEventMode(IrcEvent* e)
454 if (!checkParamCount(e, 2))
457 if (e->network()->isChannelName(e->params().first())) {
460 IrcChannel* channel = e->network()->ircChannel(e->params()[0]);
462 // we received mode information for a channel we're not in. that means probably we've just been kicked out or something like
463 // that anyways: we don't have a place to store the data --> discard the info.
467 QString modes = e->params()[1];
470 for (auto mode : modes) {
480 if (e->network()->prefixModes().contains(mode)) {
481 // user channel modes (op, voice, etc...)
482 if (paramOffset < e->params().count()) {
483 IrcUser* ircUser = e->network()->ircUser(e->params()[paramOffset]);
485 qWarning() << Q_FUNC_INFO << "Unknown IrcUser:" << e->params()[paramOffset];
489 bool handledByNetsplit = false;
490 QHash<QString, Netsplit*> splits = _netsplits.value(e->network());
491 foreach (Netsplit* n, _netsplits.value(e->network())) {
492 handledByNetsplit = n->userAlreadyJoined(ircUser->hostmask(), channel->name());
493 if (handledByNetsplit) {
494 n->addMode(ircUser->hostmask(), channel->name(), QString(mode));
498 if (!handledByNetsplit)
499 channel->addUserMode(ircUser, QString(mode));
502 channel->removeUserMode(ircUser, QString(mode));
506 qWarning() << "Received MODE with too few parameters:" << e->params();
511 // regular channel modes
513 Network::ChannelModeType modeType = e->network()->channelModeType(mode);
514 if (modeType == Network::A_CHANMODE || modeType == Network::B_CHANMODE || (modeType == Network::C_CHANMODE && add)) {
515 if (paramOffset < e->params().count()) {
516 value = e->params()[paramOffset];
519 qWarning() << "Received MODE with too few parameters:" << e->params();
525 channel->addChannelMode(mode, value);
527 channel->removeChannelMode(mode, value);
533 IrcUser* ircUser = e->network()->newIrcUser(e->params().first());
534 QString modeString(e->params()[1]);
538 for (int c = 0; c < modeString.count(); c++) {
539 if (modeString[c] == '+') {
543 if (modeString[c] == '-') {
548 addModes += modeString[c];
550 removeModes += modeString[c];
552 if (!addModes.isEmpty())
553 ircUser->addUserModes(addModes);
554 if (!removeModes.isEmpty())
555 ircUser->removeUserModes(removeModes);
557 if (e->network()->isMe(ircUser)) {
558 // Mark the message as Self
559 e->setFlag(EventManager::Self);
560 coreNetwork(e)->updatePersistentModes(addModes, removeModes);
565 void CoreSessionEventProcessor::processIrcEventNick(IrcEvent* e)
567 if (checkParamCount(e, 1)) {
568 IrcUser* ircuser = e->network()->updateNickFromMask(e->prefix());
570 qWarning() << Q_FUNC_INFO << "Unknown IrcUser!";
574 if (e->network()->isMe(ircuser)) {
575 // Mark the message as Self
576 e->setFlag(EventManager::Self);
579 // Actual processing is handled in lateProcessIrcEventNick(), this just sets the event flag
583 void CoreSessionEventProcessor::lateProcessIrcEventNick(IrcEvent* e)
585 if (checkParamCount(e, 1)) {
586 IrcUser* ircuser = e->network()->updateNickFromMask(e->prefix());
588 qWarning() << Q_FUNC_INFO << "Unknown IrcUser!";
591 QString newnick = e->params().at(0);
592 QString oldnick = ircuser->nick();
594 // the order is cruicial
595 // otherwise the client would rename the buffer, see that the assigned ircuser doesn't match anymore
596 // and remove the ircuser from the querybuffer leading to a wrong on/offline state
597 ircuser->setNick(newnick);
598 coreSession()->renameBuffer(e->networkId(), newnick, oldnick);
602 void CoreSessionEventProcessor::processIrcEventPart(IrcEvent* e)
604 if (checkParamCount(e, 1)) {
605 IrcUser* ircuser = e->network()->updateNickFromMask(e->prefix());
607 qWarning() << Q_FUNC_INFO << "Unknown IrcUser!";
611 if (e->network()->isMe(ircuser)) {
612 // Mark the message as Self
613 e->setFlag(EventManager::Self);
616 // Actual processing is handled in lateProcessIrcEventNick(), this just sets the event flag
620 void CoreSessionEventProcessor::lateProcessIrcEventPart(IrcEvent* e)
622 if (checkParamCount(e, 1)) {
623 IrcUser* ircuser = e->network()->updateNickFromMask(e->prefix());
625 qWarning() << Q_FUNC_INFO << "Unknown IrcUser!";
628 QString channel = e->params().at(0);
629 ircuser->partChannel(channel);
630 if (e->network()->isMe(ircuser)) {
631 qobject_cast<CoreNetwork*>(e->network())->setChannelParted(channel);
636 void CoreSessionEventProcessor::processIrcEventPing(IrcEvent* e)
638 QString param = e->params().count() ? e->params().first() : QString();
640 // Take priority so this won't get stuck behind other queued messages.
641 coreNetwork(e)->putRawLine("PONG " + coreNetwork(e)->serverEncode(param), true);
644 void CoreSessionEventProcessor::processIrcEventPong(IrcEvent* e)
646 // Ensure we get at least one parameter
647 if (!checkParamCount(e, 1))
650 // Some IRC servers respond with only one parameter, others respond with two, with the latter
651 // being the text sent. Handle both situations.
653 if (e->params().count() < 2) {
654 // Only one parameter received
655 // :localhost PONG 02:43:49.565
656 timestamp = e->params().at(0);
659 // Two parameters received, pick the second
660 // :localhost PONG localhost :02:43:49.565
661 timestamp = e->params().at(1);
664 // The server is supposed to send back what we passed as parameter, and we send a timestamp.
665 // However, using quote and whatnot, one can send arbitrary pings, and IRC servers may decide to
666 // ignore our requests entirely and send whatever they want, so we have to do some sanity
669 // Attempt to parse the timestamp
670 QTime sendTime = QTime::fromString(timestamp, "hh:mm:ss.zzz");
671 if (sendTime.isValid()) {
672 // Mark IRC server as sending valid ping replies
673 if (!coreNetwork(e)->isPongTimestampValid()) {
674 coreNetwork(e)->setPongTimestampValid(true);
675 // Add a message the first time it happens
676 qDebug().nospace() << "Received PONG with valid timestamp, marking pong replies on "
678 << "\"" << qPrintable(e->network()->networkName())
679 << "\" (ID: " << qPrintable(QString::number(e->network()->networkId().toInt()))
680 << ") as usable for latency measurement";
682 // Remove pending flag
683 coreNetwork(e)->resetPongReplyPending();
685 // Don't show this in the UI
686 e->setFlag(EventManager::Silent);
687 // TODO: To allow for a user-sent /ping (without arguments, so default timestamp is used),
688 // this could track how many automated PINGs have been sent by the core and subtract one
689 // each time, only marking the PING as silent if there's pending automated pong replies.
690 // However, that's a behavior change which warrants further testing. For now, take the
691 // simpler, previous approach that errs on the side of silencing too much.
693 // Calculate latency from time difference, divided by 2 to account for round-trip time
694 e->network()->setLatency(sendTime.msecsTo(QTime::currentTime()) / 2);
696 else if (coreNetwork(e)->isPongReplyPending() && !coreNetwork(e)->isPongTimestampValid()) {
697 // There's an auto-PING reply pending and we've not yet received a PONG reply with a valid
698 // timestamp. It's possible this server will never respond with a valid timestamp, and thus
699 // any automated PINGs will result in unwanted spamming of the server buffer.
701 // Don't show this in the UI
702 e->setFlag(EventManager::Silent);
703 // Remove pending flag
704 coreNetwork(e)->resetPongReplyPending();
707 qDebug().nospace() << "Received PONG with invalid timestamp from network "
708 << "\"" << qPrintable(e->network()->networkName())
709 << "\" (ID: " << qPrintable(QString::number(e->network()->networkId().toInt()))
710 << "), silencing, parameters are " << e->params();
712 // else: We're not expecting a PONG reply and timestamp is not valid, assume it's from the user
715 void CoreSessionEventProcessor::processIrcEventQuit(IrcEvent* e)
717 IrcUser* ircuser = e->network()->updateNickFromMask(e->prefix());
721 if (e->network()->isMe(ircuser)) {
722 // Mark the message as Self
723 e->setFlag(EventManager::Self);
727 if (e->params().count() > 0)
728 msg = e->params()[0];
731 if (Netsplit::isNetsplit(msg)) {
733 if (!_netsplits[e->network()].contains(msg)) {
734 n = new Netsplit(e->network(), this);
735 connect(n, &Netsplit::finished, this, &CoreSessionEventProcessor::handleNetsplitFinished);
736 connect(n, &Netsplit::netsplitJoin, this, &CoreSessionEventProcessor::handleNetsplitJoin);
737 connect(n, &Netsplit::netsplitQuit, this, &CoreSessionEventProcessor::handleNetsplitQuit);
738 connect(n, &Netsplit::earlyJoin, this, &CoreSessionEventProcessor::handleEarlyNetsplitJoin);
739 _netsplits[e->network()].insert(msg, n);
742 n = _netsplits[e->network()][msg];
744 // add this user to the netsplit
745 n->userQuit(e->prefix(), ircuser->channels(), msg);
746 e->setFlag(EventManager::Netsplit);
748 // normal quit is handled in lateProcessIrcEventQuit()
751 void CoreSessionEventProcessor::lateProcessIrcEventQuit(IrcEvent* e)
753 if (e->testFlag(EventManager::Netsplit))
756 IrcUser* ircuser = e->network()->updateNickFromMask(e->prefix());
763 void CoreSessionEventProcessor::processIrcEventTopic(IrcEvent* e)
765 if (checkParamCount(e, 2)) {
766 IrcUser* ircuser = e->network()->updateNickFromMask(e->prefix());
768 if (e->network()->isMe(ircuser)) {
769 // Mark the message as Self
770 e->setFlag(EventManager::Self);
773 IrcChannel* channel = e->network()->ircChannel(e->params().at(0));
775 channel->setTopic(e->params().at(1));
779 /* ERROR - "ERROR :reason"
780 Example: ERROR :Closing Link: nickname[xxx.xxx.xxx.xxx] (Large base64 image paste.)
781 See https://tools.ietf.org/html/rfc2812#section-3.7.4 */
782 void CoreSessionEventProcessor::processIrcEventError(IrcEvent* e)
784 if (!checkParamCount(e, 1))
787 if (coreNetwork(e)->disconnectExpected()) {
788 // During QUIT, the server should send an error (often, but not always, "Closing Link"). As
789 // we're expecting it, don't show this to the user.
790 e->setFlag(EventManager::Silent);
795 void CoreSessionEventProcessor::processKeyEvent(KeyEvent* e)
797 if (!Cipher::neededFeaturesAvailable()) {
798 emit newEvent(new MessageEvent(Message::Error,
800 tr("Unable to perform key exchange, missing qca-ossl plugin."),
807 auto* net = qobject_cast<CoreNetwork*>(e->network());
808 Cipher* c = net->cipher(e->target());
809 if (!c) // happens when there is no CoreIrcChannel for the target (i.e. never?)
812 if (e->exchangeType() == KeyEvent::Init) {
813 QByteArray pubKey = c->parseInitKeyX(e->key());
814 if (pubKey.isEmpty()) {
815 emit newEvent(new MessageEvent(Message::Error,
817 tr("Unable to parse the DH1080_INIT. Key exchange failed."),
825 net->setCipherKey(e->target(), c->key());
826 emit newEvent(new MessageEvent(Message::Info,
828 tr("Your key is set and messages will be encrypted."),
834 p << net->serverEncode(e->target()) << net->serverEncode("DH1080_FINISH ") + pubKey;
835 net->putCmd("NOTICE", p);
839 if (c->parseFinishKeyX(e->key())) {
840 net->setCipherKey(e->target(), c->key());
841 emit newEvent(new MessageEvent(Message::Info,
843 tr("Your key is set and messages will be encrypted."),
850 emit newEvent(new MessageEvent(Message::Info,
852 tr("Failed to parse DH1080_FINISH. Key exchange failed."),
863 void CoreSessionEventProcessor::processIrcEvent001(IrcEventNumeric* e)
865 e->network()->setCurrentServer(e->prefix());
866 e->network()->setMyNick(e->target());
870 // TODO Complete 005 handling, also use sensible defaults for non-sent stuff
871 void CoreSessionEventProcessor::processIrcEvent005(IrcEvent* e)
873 if (!checkParamCount(e, 1))
877 for (int i = 0; i < e->params().count() - 1; i++) {
878 QString key = e->params()[i].section("=", 0, 0);
879 QString value = e->params()[i].section("=", 1);
880 e->network()->addSupport(key, value);
883 /* determine our prefixes here to get an accurate result */
884 e->network()->determinePrefixes();
887 /* RPL_UMODEIS - "<user_modes> [<user_mode_params>]" */
888 void CoreSessionEventProcessor::processIrcEvent221(IrcEvent*)
890 // TODO: save information in network object
893 /* RPL_STATSCONN - "Highest connection cout: 8000 (7999 clients)" */
894 void CoreSessionEventProcessor::processIrcEvent250(IrcEvent*)
896 // TODO: save information in network object
899 /* RPL_LOCALUSERS - "Current local user: 5024 Max: 7999 */
900 void CoreSessionEventProcessor::processIrcEvent265(IrcEvent*)
902 // TODO: save information in network object
905 /* RPL_GLOBALUSERS - "Current global users: 46093 Max: 47650" */
906 void CoreSessionEventProcessor::processIrcEvent266(IrcEvent*)
908 // TODO: save information in network object
913 Replies 311 - 313, 317 - 319 are all replies generated in response to a WHOIS message.
915 "<nick> :<away message>"
917 Replies 352 and 315 paired are used to answer a WHO message.
920 Replies 314 and 369 are responses to a WHOWAS message.
924 /* RPL_AWAY - "<nick> :<away message>" */
925 void CoreSessionEventProcessor::processIrcEvent301(IrcEvent* e)
927 if (!checkParamCount(e, 2))
930 IrcUser* ircuser = e->network()->ircUser(e->params().at(0));
932 ircuser->setAway(true);
933 ircuser->setAwayMessage(e->params().at(1));
934 // lastAwayMessageTime is set in EventStringifier::processIrcEvent301(), no need to set it
936 // ircuser->setLastAwayMessageTime(now);
940 /* RPL_UNAWAY - ":You are no longer marked as being away" */
941 void CoreSessionEventProcessor::processIrcEvent305(IrcEvent* e)
943 IrcUser* me = e->network()->me();
947 if (e->network()->autoAwayActive()) {
948 e->network()->setAutoAwayActive(false);
949 e->setFlag(EventManager::Silent);
953 /* RPL_NOWAWAY - ":You have been marked as being away" */
954 void CoreSessionEventProcessor::processIrcEvent306(IrcEvent* e)
956 IrcUser* me = e->network()->me();
961 /* RPL_WHOISSERVICE - "<user> is registered nick" */
962 void CoreSessionEventProcessor::processIrcEvent307(IrcEvent* e)
964 if (!checkParamCount(e, 1))
967 IrcUser* ircuser = e->network()->ircUser(e->params().at(0));
969 ircuser->setWhoisServiceReply(e->params().join(" "));
972 /* RPL_SUSERHOST - "<user> is available for help." */
973 void CoreSessionEventProcessor::processIrcEvent310(IrcEvent* e)
975 if (!checkParamCount(e, 1))
978 IrcUser* ircuser = e->network()->ircUser(e->params().at(0));
980 ircuser->setSuserHost(e->params().join(" "));
983 /* RPL_WHOISUSER - "<nick> <user> <host> * :<real name>" */
984 void CoreSessionEventProcessor::processIrcEvent311(IrcEvent* e)
986 if (!checkParamCount(e, 3))
989 IrcUser* ircuser = e->network()->ircUser(e->params().at(0));
991 ircuser->setUser(e->params().at(1));
992 ircuser->setHost(e->params().at(2));
993 ircuser->setRealName(e->params().last());
997 /* RPL_WHOISSERVER - "<nick> <server> :<server info>" */
998 void CoreSessionEventProcessor::processIrcEvent312(IrcEvent* e)
1000 if (!checkParamCount(e, 2))
1003 IrcUser* ircuser = e->network()->ircUser(e->params().at(0));
1005 ircuser->setServer(e->params().at(1));
1008 /* RPL_WHOISOPERATOR - "<nick> :is an IRC operator" */
1009 void CoreSessionEventProcessor::processIrcEvent313(IrcEvent* e)
1011 if (!checkParamCount(e, 1))
1014 IrcUser* ircuser = e->network()->ircUser(e->params().at(0));
1016 ircuser->setIrcOperator(e->params().last());
1019 /* RPL_ENDOFWHO: "<name> :End of WHO list" */
1020 void CoreSessionEventProcessor::processIrcEvent315(IrcEvent* e)
1022 if (!checkParamCount(e, 1))
1025 if (coreNetwork(e)->setAutoWhoDone(e->params()[0]))
1026 e->setFlag(EventManager::Silent);
1029 /* RPL_WHOISIDLE - "<nick> <integer> :seconds idle"
1030 (real life: "<nick> <integer> <integer> :seconds idle, signon time) */
1031 void CoreSessionEventProcessor::processIrcEvent317(IrcEvent* e)
1033 if (!checkParamCount(e, 2))
1036 QDateTime loginTime;
1038 int idleSecs = e->params()[1].toInt();
1039 if (e->params().count() > 3) { // if we have more then 3 params we have the above mentioned "real life" situation
1040 // Allow for 64-bit time
1041 qint64 logintime = e->params()[2].toLongLong();
1042 // Time in IRC protocol is defined as seconds. Convert from seconds instead.
1043 // See https://doc.qt.io/qt-5/qdatetime.html#fromSecsSinceEpoch
1044 #if QT_VERSION >= 0x050800
1045 loginTime = QDateTime::fromSecsSinceEpoch(logintime);
1047 // fromSecsSinceEpoch() was added in Qt 5.8. Manually downconvert to seconds for
1049 // See https://doc.qt.io/qt-5/qdatetime.html#fromMSecsSinceEpoch
1050 loginTime = QDateTime::fromMSecsSinceEpoch((qint64)(logintime * 1000));
1054 IrcUser* ircuser = e->network()->ircUser(e->params()[0]);
1056 ircuser->setIdleTime(e->timestamp().addSecs(-idleSecs));
1057 if (loginTime.isValid())
1058 ircuser->setLoginTime(loginTime);
1062 /* RPL_LIST - "<channel> <# visible> :<topic>" */
1063 void CoreSessionEventProcessor::processIrcEvent322(IrcEvent* e)
1065 if (!checkParamCount(e, 1))
1068 QString channelName;
1069 quint32 userCount = 0;
1072 switch (e->params().count()) {
1074 topic = e->params()[2];
1077 userCount = e->params()[1].toUInt();
1080 channelName = e->params()[0];
1085 if (coreSession()->ircListHelper()->addChannel(e->networkId(), channelName, userCount, topic))
1086 e->stop(); // consumed by IrcListHelper, so don't further process/show this event
1089 /* RPL_LISTEND ":End of LIST" */
1090 void CoreSessionEventProcessor::processIrcEvent323(IrcEvent* e)
1092 if (!checkParamCount(e, 1))
1095 if (coreSession()->ircListHelper()->endOfChannelList(e->networkId()))
1096 e->stop(); // consumed by IrcListHelper, so don't further process/show this event
1099 /* RPL_CHANNELMODEIS - "<channel> <mode> <mode params>" */
1100 void CoreSessionEventProcessor::processIrcEvent324(IrcEvent* e)
1102 processIrcEventMode(e);
1105 /* RPL_WHOISACCOUNT - "<nick> <account> :is authed as" */
1106 void CoreSessionEventProcessor::processIrcEvent330(IrcEvent* e)
1108 // Though the ":is authed as" remark should always be there, we should handle cases when it's
1109 // not included, too.
1110 if (!checkParamCount(e, 2))
1113 IrcUser* ircuser = e->network()->ircUser(e->params().at(0));
1115 ircuser->setAccount(e->params().at(1));
1120 void CoreSessionEventProcessor::processIrcEvent331(IrcEvent* e)
1122 if (!checkParamCount(e, 1))
1125 IrcChannel* chan = e->network()->ircChannel(e->params()[0]);
1127 chan->setTopic(QString());
1131 void CoreSessionEventProcessor::processIrcEvent332(IrcEvent* e)
1133 if (!checkParamCount(e, 2))
1136 IrcChannel* chan = e->network()->ircChannel(e->params()[0]);
1138 chan->setTopic(e->params()[1]);
1141 /* RPL_WHOREPLY: "<channel> <user> <host> <server> <nick>
1142 ( "H" / "G" > ["*"] [ ( "@" / "+" ) ] :<hopcount> <real name>" */
1143 void CoreSessionEventProcessor::processIrcEvent352(IrcEvent* e)
1145 if (!checkParamCount(e, 6))
1148 QString channel = e->params()[0];
1149 IrcUser* ircuser = e->network()->ircUser(e->params()[4]);
1151 // Only process the WHO information if an IRC user exists. Don't create an IRC user here;
1152 // there's no way to track when the user quits, which would leave a phantom IrcUser lying
1154 // NOTE: Whenever MONITOR support is introduced, the IrcUser will be created by an
1155 // RPL_MONONLINE numeric before any WHO commands are run.
1156 processWhoInformation(e->network(),
1163 e->params().last().section(" ", 1));
1166 // Check if channel name has a who in progress.
1167 if (coreNetwork(e)->isAutoWhoInProgress(channel)) {
1168 e->setFlag(EventManager::Silent);
1173 void CoreSessionEventProcessor::processIrcEvent353(IrcEvent* e)
1175 if (!checkParamCount(e, 3))
1178 // param[0] is either "=", "*" or "@" indicating a public, private or secret channel
1179 // we don't use this information at the time beeing
1180 QString channelname = e->params()[1];
1182 IrcChannel* channel = e->network()->ircChannel(channelname);
1184 qWarning() << Q_FUNC_INFO << "Received unknown target channel:" << channelname;
1191 // Cache result of multi-prefix to avoid unneeded casts and lookups with each iteration.
1192 bool _useCapMultiPrefix = coreNetwork(e)->capEnabled(IrcCap::MULTI_PREFIX);
1194 foreach (QString nick, e->params()[2].split(' ', QString::SkipEmptyParts)) {
1197 if (_useCapMultiPrefix) {
1198 // If multi-prefix is enabled, all modes will be sent in NAMES replies.
1199 // :hades.arpa 353 guest = #tethys :~&@%+aji &@Attila @+alyx +KindOne Argure
1200 // See: http://ircv3.net/specs/extensions/multi-prefix-3.1.html
1201 while (e->network()->prefixes().contains(nick[0])) {
1202 // Mode found in 1 left-most character, add it to the list.
1203 // Note: sending multiple modes may cause a warning in older clients.
1204 // In testing, the clients still seemed to function fine.
1205 mode.append(e->network()->prefixToMode(nick[0]));
1206 // Remove this mode from the nick
1207 nick = nick.remove(0, 1);
1210 else if (e->network()->prefixes().contains(nick[0])) {
1211 // Multi-prefix is disabled and a mode prefix was found.
1212 mode = e->network()->prefixToMode(nick[0]);
1216 // If userhost-in-names capability is enabled, the following will be
1217 // in the form "nick!user@host" rather than "nick". This works without
1218 // special handling as the following use nickFromHost() as needed.
1219 // See: http://ircv3.net/specs/extensions/userhost-in-names-3.2.html
1225 channel->joinIrcUsers(nicks, modes);
1228 /* RPL_WHOSPCRPL: "<yournick> 152 #<channel> ~<ident> <host> <servname> <nick>
1229 ("H"/ "G") <account> :<realname>"
1230 <channel> is * if not specific to any channel
1231 <account> is * if not logged in
1232 Follows HexChat's usage of 'whox'
1233 See https://github.com/hexchat/hexchat/blob/c874a9525c9b66f1d5ddcf6c4107d046eba7e2c5/src/common/proto-irc.c#L750
1234 And http://faerion.sourceforge.net/doc/irc/whox.var*/
1235 void CoreSessionEventProcessor::processIrcEvent354(IrcEvent* e)
1237 // First only check if at least one parameter exists. Otherwise, it'll stop the result from
1238 // being shown if the user chooses different parameters.
1239 if (!checkParamCount(e, 1))
1242 if (e->params()[0].toUInt() != IrcCap::ACCOUNT_NOTIFY_WHOX_NUM) {
1243 // Ignore WHOX replies without expected number for we have no idea what fields are specified
1247 // Now we're fairly certain this is supposed to be an automated WHOX. Bail out if it doesn't
1248 // match what we require - 9 parameters.
1249 if (!checkParamCount(e, 9))
1252 QString channel = e->params()[1];
1253 IrcUser* ircuser = e->network()->ircUser(e->params()[5]);
1255 // Only process the WHO information if an IRC user exists. Don't create an IRC user here;
1256 // there's no way to track when the user quits, which would leave a phantom IrcUser lying
1258 // NOTE: Whenever MONITOR support is introduced, the IrcUser will be created by an
1259 // RPL_MONONLINE numeric before any WHO commands are run.
1260 processWhoInformation(e->network(), channel, ircuser, e->params()[4], e->params()[2], e->params()[3], e->params()[6], e->params().last());
1261 // Don't use .section(" ", 1) with WHOX replies, for there's no hopcount to trim out
1263 // As part of IRCv3 account-notify, check account name
1264 // WHOX uses '0' to indicate logged-out, account-notify and extended-join uses '*'.
1265 QString newAccount = e->params()[7];
1266 if (newAccount != "0") {
1267 // Account logged in, set account name
1268 ircuser->setAccount(newAccount);
1271 // Account logged out, set account name to logged-out
1272 ircuser->setAccount("*");
1276 // Check if channel name has a who in progress.
1277 if (coreNetwork(e)->isAutoWhoInProgress(channel)) {
1278 e->setFlag(EventManager::Silent);
1282 void CoreSessionEventProcessor::processWhoInformation(Network* net,
1283 const QString& targetChannel,
1285 const QString& server,
1286 const QString& user,
1287 const QString& host,
1288 const QString& awayStateAndModes,
1289 const QString& realname)
1291 ircUser->setUser(user);
1292 ircUser->setHost(host);
1293 ircUser->setServer(server);
1294 ircUser->setRealName(realname);
1296 bool away = awayStateAndModes.contains("G", Qt::CaseInsensitive);
1297 ircUser->setAway(away);
1299 if (net->capEnabled(IrcCap::MULTI_PREFIX)) {
1300 // If multi-prefix is enabled, all modes will be sent in WHO replies.
1301 // :kenny.chatspike.net 352 guest #test grawity broken.symlink *.chatspike.net grawity H@%+ :0 Mantas M.
1302 // See: http://ircv3.net/specs/extensions/multi-prefix-3.1.html
1303 QString uncheckedModes = awayStateAndModes;
1304 QString validModes = QString();
1305 while (!uncheckedModes.isEmpty()) {
1306 // Mode found in 1 left-most character, add it to the list
1307 if (net->prefixes().contains(uncheckedModes[0])) {
1308 validModes.append(net->prefixToMode(uncheckedModes[0]));
1310 // Remove this mode from the list of unchecked modes
1311 uncheckedModes = uncheckedModes.remove(0, 1);
1314 // Some IRC servers decide to not follow the spec, returning only -some- of the user
1315 // modes in WHO despite listing them all in NAMES. For now, assume it can only add
1316 // and not take away. *sigh*
1317 if (!validModes.isEmpty()) {
1318 if (targetChannel != "*") {
1319 // Channel-specific modes received, apply to given channel only
1320 IrcChannel* ircChan = net->ircChannel(targetChannel);
1322 // Do one mode at a time
1323 // TODO Better way of syncing this without breaking protocol?
1324 for (int i = 0; i < validModes.count(); ++i) {
1325 ircChan->addUserMode(ircUser, validModes.at(i));
1330 // Modes apply to the user everywhere
1331 ircUser->addUserModes(validModes);
1337 /* ERR_NOSUCHCHANNEL - "<channel name> :No such channel" */
1338 void CoreSessionEventProcessor::processIrcEvent403(IrcEventNumeric* e)
1340 // If this is the result of an AutoWho, hide it. It's confusing to show to the user.
1341 // Though the ":No such channel" remark should always be there, we should handle cases when it's
1342 // not included, too.
1343 if (!checkParamCount(e, 1))
1346 QString channelOrNick = e->params()[0];
1347 // Check if channel name has a who in progress.
1348 // If not, then check if user nick exists and has a who in progress.
1349 if (coreNetwork(e)->isAutoWhoInProgress(channelOrNick)) {
1350 qDebug() << "Channel/nick" << channelOrNick << "no longer exists during AutoWho, ignoring";
1351 e->setFlag(EventManager::Silent);
1355 /* ERR_ERRONEUSNICKNAME */
1356 void CoreSessionEventProcessor::processIrcEvent432(IrcEventNumeric* e)
1358 if (!checkParamCount(e, 1))
1362 if (e->params().count() < 2) {
1363 // handle unreal-ircd bug, where unreal ircd doesnt supply a TARGET in ERR_ERRONEUSNICKNAME during registration phase:
1365 // :irc.scortum.moep.net 432 @@@ :Erroneous Nickname: Illegal characters
1366 // correct server reply:
1367 // :irc.scortum.moep.net 432 * @@@ :Erroneous Nickname: Illegal characters
1368 e->params().prepend(e->target());
1371 errnick = e->params()[0];
1373 tryNextNick(e, errnick, true /* erroneus */);
1376 /* ERR_NICKNAMEINUSE */
1377 void CoreSessionEventProcessor::processIrcEvent433(IrcEventNumeric* e)
1379 if (!checkParamCount(e, 1))
1382 QString errnick = e->params().first();
1384 // if there is a problem while connecting to the server -> we handle it
1385 // but only if our connection has not been finished yet...
1386 if (!e->network()->currentServer().isEmpty())
1389 tryNextNick(e, errnick);
1392 /* ERR_UNAVAILRESOURCE */
1393 void CoreSessionEventProcessor::processIrcEvent437(IrcEventNumeric* e)
1395 if (!checkParamCount(e, 1))
1398 QString errnick = e->params().first();
1400 // if there is a problem while connecting to the server -> we handle it
1401 // but only if our connection has not been finished yet...
1402 if (!e->network()->currentServer().isEmpty())
1405 if (!e->network()->isChannelName(errnick))
1406 tryNextNick(e, errnick);
1410 void CoreSessionEventProcessor::processIrcEvent(IrcEvent *e) {
1411 if(!checkParamCount(e, 1))
1417 /* Handle signals from Netsplit objects */
1419 void CoreSessionEventProcessor::handleNetsplitJoin(
1420 Network* net, const QString& channel, const QStringList& users, const QStringList& modes, const QString& quitMessage)
1422 IrcChannel* ircChannel = net->ircChannel(channel);
1426 QList<IrcUser*> ircUsers;
1427 QStringList newModes = modes;
1428 QStringList newUsers = users;
1430 foreach (const QString& user, users) {
1431 IrcUser* iu = net->ircUser(nickFromMask(user));
1433 ircUsers.append(iu);
1434 else { // the user already quit
1435 int idx = users.indexOf(user);
1436 newUsers.removeAt(idx);
1437 newModes.removeAt(idx);
1441 ircChannel->joinIrcUsers(ircUsers, newModes);
1442 NetworkSplitEvent* event = new NetworkSplitEvent(EventManager::NetworkSplitJoin, net, channel, newUsers, quitMessage);
1443 emit newEvent(event);
1446 void CoreSessionEventProcessor::handleNetsplitQuit(Network* net, const QString& channel, const QStringList& users, const QString& quitMessage)
1448 NetworkSplitEvent* event = new NetworkSplitEvent(EventManager::NetworkSplitQuit, net, channel, users, quitMessage);
1449 emit newEvent(event);
1450 foreach (QString user, users) {
1451 IrcUser* iu = net->ircUser(nickFromMask(user));
1457 void CoreSessionEventProcessor::handleEarlyNetsplitJoin(Network* net, const QString& channel, const QStringList& users, const QStringList& modes)
1459 IrcChannel* ircChannel = net->ircChannel(channel);
1461 qDebug() << "handleEarlyNetsplitJoin(): channel " << channel << " invalid";
1464 QList<NetworkEvent*> events;
1465 QList<IrcUser*> ircUsers;
1466 QStringList newModes = modes;
1468 foreach (QString user, users) {
1469 IrcUser* iu = net->updateNickFromMask(user);
1471 ircUsers.append(iu);
1472 // fake event for scripts that consume join events
1473 events << new IrcEvent(EventManager::IrcEventJoin, net, iu->hostmask(), QStringList() << channel);
1476 newModes.removeAt(users.indexOf(user));
1479 ircChannel->joinIrcUsers(ircUsers, newModes);
1480 foreach (NetworkEvent* event, events) {
1481 event->setFlag(EventManager::Fake); // ignore this in here!
1482 emit newEvent(event);
1486 void CoreSessionEventProcessor::handleNetsplitFinished()
1488 auto* n = qobject_cast<Netsplit*>(sender());
1490 QHash<QString, Netsplit*> splithash = _netsplits.take(n->network());
1491 splithash.remove(splithash.key(n));
1492 if (splithash.count())
1493 _netsplits[n->network()] = splithash;
1497 void CoreSessionEventProcessor::destroyNetsplits(NetworkId netId)
1499 Network* net = coreSession()->network(netId);
1503 QHash<QString, Netsplit*> splits = _netsplits.take(net);
1507 /*******************************/
1508 /******** CTCP HANDLING ********/
1509 /*******************************/
1511 void CoreSessionEventProcessor::processCtcpEvent(CtcpEvent* e)
1513 if (e->testFlag(EventManager::Self))
1514 return; // ignore ctcp events generated by user input
1516 if (e->type() != EventManager::CtcpEvent || e->ctcpType() != CtcpEvent::Query)
1519 handle(e->ctcpCmd(), Q_ARG(CtcpEvent*, e));
1522 void CoreSessionEventProcessor::defaultHandler(const QString& ctcpCmd, CtcpEvent* e)
1524 // This handler is only there to avoid warnings for unknown CTCPs
1529 void CoreSessionEventProcessor::handleCtcpAction(CtcpEvent* e)
1531 // This handler is only there to feed CLIENTINFO
1535 void CoreSessionEventProcessor::handleCtcpClientinfo(CtcpEvent* e)
1537 QStringList supportedHandlers;
1538 foreach (QString handler, providesHandlers())
1539 supportedHandlers << handler.toUpper();
1540 qSort(supportedHandlers);
1541 e->setReply(supportedHandlers.join(" "));
1544 // http://www.irchelp.org/irchelp/rfc/ctcpspec.html
1545 // http://en.wikipedia.org/wiki/Direct_Client-to-Client
1546 void CoreSessionEventProcessor::handleCtcpDcc(CtcpEvent* e)
1548 // DCC support is unfinished, experimental and potentially dangerous, so make it opt-in
1549 if (!Quassel::isOptionSet("enable-experimental-dcc")) {
1550 qInfo() << "DCC disabled, start core with --enable-experimental-dcc if you really want to try it out";
1554 // normal: SEND <filename> <ip> <port> [<filesize>]
1555 // reverse: SEND <filename> <ip> 0 <filesize> <token>
1556 QStringList params = e->param().split(' ');
1557 if (params.count()) {
1558 QString cmd = params[0].toUpper();
1559 if (cmd == "SEND") {
1560 if (params.count() < 4) {
1561 qWarning() << "Invalid DCC SEND request:" << e; // TODO emit proper error to client
1564 QString filename = params[1];
1565 QHostAddress address;
1566 quint16 port = params[3].toUShort();
1568 QString numIp = params[2]; // this is either IPv4 as a 32 bit value, or IPv6 (which always contains a colon)
1569 if (numIp.contains(':')) { // IPv6
1570 if (!address.setAddress(numIp)) {
1571 qWarning() << "Invalid IPv6:" << numIp;
1576 address.setAddress(numIp.toUInt());
1579 if (port == 0) { // Reverse DCC is indicated by a 0 port
1580 emit newEvent(new MessageEvent(Message::Error,
1582 tr("Reverse DCC SEND not supported"),
1590 qWarning() << "Privileged port requested:" << port; // FIXME ask user if this is ok
1593 if (params.count() > 4) { // filesize is optional
1594 size = params[4].toULong();
1597 // TODO: check if target is the right thing to use for the partner
1598 CoreTransfer* transfer = new CoreTransfer(Transfer::Direction::Receive, e->target(), filename, address, port, size, this);
1599 coreSession()->signalProxy()->synchronize(transfer);
1600 coreSession()->transferManager()->addTransfer(transfer);
1603 emit newEvent(new MessageEvent(Message::Error,
1605 tr("DCC %1 not supported").arg(cmd),
1615 void CoreSessionEventProcessor::handleCtcpPing(CtcpEvent* e)
1617 e->setReply(e->param().isNull() ? "" : e->param());
1620 void CoreSessionEventProcessor::handleCtcpTime(CtcpEvent* e)
1622 // Use the ISO standard to avoid locale-specific translated names
1623 // Include timezone offset data to show which timezone a user's in, otherwise we're providing
1624 // NTP-over-IRC with terrible accuracy.
1625 e->setReply(formatDateTimeToOffsetISO(QDateTime::currentDateTime()));
1628 void CoreSessionEventProcessor::handleCtcpVersion(CtcpEvent* e)
1630 // Deliberately do not translate project name
1631 // Use the ISO standard to avoid locale-specific translated names
1632 // Use UTC time to provide a consistent string regardless of timezone
1633 // (Statistics tracking tools usually only group client versions by exact string matching)
1634 e->setReply(QString("Quassel IRC %1 (version date %2) -- https://www.quassel-irc.org")
1635 .arg(Quassel::buildInfo().plainVersionString)
1636 .arg(Quassel::buildInfo().commitDate.isEmpty()
1638 : tryFormatUnixEpoch(Quassel::buildInfo().commitDate, Qt::DateFormat::ISODate, true)));