1 /***************************************************************************
2 * Copyright (C) 2005-2016 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"
32 #include "messageevent.h"
37 # include "keyevent.h"
43 CoreSessionEventProcessor::CoreSessionEventProcessor(CoreSession *session)
44 : BasicHandler("handleCtcp", session),
47 connect(coreSession(), SIGNAL(networkDisconnected(NetworkId)), this, SLOT(destroyNetsplits(NetworkId)));
48 connect(this, SIGNAL(newEvent(Event *)), coreSession()->eventManager(), SLOT(postEvent(Event *)));
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 << "params, got: " << e->params();
59 QString name = coreSession()->eventManager()->enumName(e->type());
60 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, e->network(),
81 tr("No free and valid nicks in nicklist found. use: /nick <othernick> to continue"),
82 QString(), QString(), Message::None, e->timestamp());
83 emit newEvent(msgEvent);
87 nextNick = errnick + "_";
90 // FIXME Use a proper output event for this
91 coreNetwork(e)->putRawLine("NICK " + coreNetwork(e)->encodeServerString(nextNick));
95 void CoreSessionEventProcessor::processIrcEventNumeric(IrcEventNumeric *e)
97 switch (e->number()) {
98 // SASL authentication replies
99 // See: http://ircv3.net/specs/extensions/sasl-3.1.html
101 //case 900: // RPL_LOGGEDIN
102 //case 901: // RPL_LOGGEDOUT
103 // Don't use 900 or 901 for updating the local hostmask. Unreal 3.2 gives it as the IP address
104 // even when cloaked.
105 // Every other reply should result in moving on
106 // TODO Handle errors to stop connection if appropriate
107 case 902: // ERR_NICKLOCKED
108 case 903: // RPL_SASLSUCCESS
109 case 904: // ERR_SASLFAIL
110 case 905: // ERR_SASLTOOLONG
111 case 906: // ERR_SASLABORTED
112 case 907: // ERR_SASLALREADY
113 // Move on to the next capability
114 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);
148 net->putRawLine("AUTHENTICATE +");
153 void CoreSessionEventProcessor::processIrcEventCap(IrcEvent *e)
155 // Handle capability negotiation
156 // See: http://ircv3.net/specs/core/capability-negotiation-3.2.html
157 // And: http://ircv3.net/specs/core/capability-negotiation-3.1.html
159 // All commands require at least 2 parameters
160 if (!checkParamCount(e, 2))
163 if (e->params().count() >= 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(' ');
179 capListFinished = true;
180 if (e->params().count() >= 3) {
181 // Some capabilities are specified, add them
182 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();
213 } else if (capCommand == "ACK") {
214 // CAP ACK requires at least 3 parameters (no empty response allowed)
215 if (!checkParamCount(e, 3))
218 // Server: CAP * ACK :multi-prefix sasl
219 // Got the capability we want, handle as needed.
220 // As only one capability is requested at a time, no need to split
221 QString acceptedCap = e->params().at(2).trimmed().toLower();
223 // Mark this cap as accepted
224 coreNet->acknowledgeCap(acceptedCap);
226 if (!coreNet->capsRequiringConfiguration.contains(acceptedCap)) {
227 // Some capabilities (e.g. SASL) require further messages to finish. If so, do NOT
228 // send the next capability; it will be handled elsewhere in CoreNetwork.
229 // Otherwise, move on to the next capability
230 coreNet->sendNextCap();
232 } else if (capCommand == "NAK" || capCommand == "DEL") {
233 // CAP NAK/DEL require at least 3 parameters (no empty response allowed)
234 if (!checkParamCount(e, 3))
237 // Either something went wrong with this capability, or it is no longer supported
239 // Server: CAP * NAK :multi-prefix sasl
241 // Server: :irc.example.com CAP modernclient DEL :multi-prefix sasl
242 // CAP NAK and CAP DEL replies are always single-line
244 QStringList removedCaps;
245 removedCaps = e->params().at(2).split(' ');
247 // Store what capability was denied or removed
249 for (int i = 0; i < removedCaps.count(); ++i) {
250 removedCap = removedCaps[i].trimmed().toLower();
251 // Mark this cap as removed
252 coreNet->removeCap(removedCap);
255 if (capCommand == "NAK") {
256 // Continue negotiation when capability listing complete only if this is the result
257 // of a denied cap, not a removed cap
258 coreNet->sendNextCap();
264 /* IRCv3 account-notify
265 * Log in: ":nick!user@host ACCOUNT accountname"
266 * Log out: ":nick!user@host ACCOUNT *" */
267 void CoreSessionEventProcessor::processIrcEventAccount(IrcEvent *e)
269 if (!checkParamCount(e, 1))
272 IrcUser *ircuser = e->network()->updateNickFromMask(e->prefix());
274 // WHOX uses '0' to indicate logged-out, account-notify and extended-join uses '*'.
275 // As '*' is used internally to represent logged-out, no need to handle that differently.
276 ircuser->setAccount(e->params().at(0));
278 qDebug() << "Received account-notify data for unknown user" << e->prefix();
282 /* IRCv3 away-notify - ":nick!user@host AWAY [:message]" */
283 void CoreSessionEventProcessor::processIrcEventAway(IrcEvent *e)
285 if (!checkParamCount(e, 1))
287 // Don't use checkParamCount(e, 2) since the message is optional. Some servers respond in a way
288 // that it counts as two parameters, but we shouldn't rely on that.
290 // Nick is sent as part of parameters in order to split user/server decoding
291 IrcUser *ircuser = e->network()->ircUser(e->params().at(0));
293 // If two parameters are sent -and- the second parameter isn't empty, then user is away.
294 // Otherwise, mark them as not away.
295 if (e->params().count() >= 2 && !e->params().at(1).isEmpty()) {
296 ircuser->setAway(true);
297 ircuser->setAwayMessage(e->params().at(1));
299 ircuser->setAway(false);
302 qDebug() << "Received away-notify data for unknown user" << e->params().at(0);
306 /* IRCv3 chghost - ":nick!user@host CHGHOST newuser new.host.goes.here" */
307 void CoreSessionEventProcessor::processIrcEventChghost(IrcEvent *e)
309 if (!checkParamCount(e, 2))
312 IrcUser *ircuser = e->network()->updateNickFromMask(e->prefix());
314 // Update with new user/hostname information. setUser/setHost handles checking what
316 ircuser->setUser(e->params().at(0));
317 ircuser->setHost(e->params().at(1));
319 qDebug() << "Received chghost data for unknown user" << e->prefix();
323 void CoreSessionEventProcessor::processIrcEventInvite(IrcEvent *e)
325 if (checkParamCount(e, 2)) {
326 e->network()->updateNickFromMask(e->prefix());
330 /* JOIN: ":<nick!user@host> JOIN <channel>" */
331 void CoreSessionEventProcessor::processIrcEventJoin(IrcEvent *e)
333 if (e->testFlag(EventManager::Fake)) // generated by handleEarlyNetsplitJoin
336 if (!checkParamCount(e, 1))
339 CoreNetwork *net = coreNetwork(e);
340 QString channel = e->params()[0];
341 IrcUser *ircuser = net->updateNickFromMask(e->prefix());
343 if (net->capEnabled(IrcCap::EXTENDED_JOIN)) {
344 if (e->params().count() < 3) {
345 // Some IRC servers don't send extended-join events in all situations. Rather than
346 // ignore the join entirely, treat it as a regular join with a debug-level log entry.
347 // See: https://github.com/inspircd/inspircd/issues/821
348 qDebug() << "extended-join requires 3 params, got:" << e->params() << ", handling as a "
351 // If logged in, :nick!user@host JOIN #channelname accountname :Real Name
352 // If logged out, :nick!user@host JOIN #channelname * :Real Name
353 // See: http://ircv3.net/specs/extensions/extended-join-3.1.html
354 // WHOX uses '0' to indicate logged-out, account-notify and extended-join uses '*'.
355 // As '*' is used internally to represent logged-out, no need to handle that differently.
356 ircuser->setAccount(e->params()[1]);
357 // Update the user's real name, too
358 ircuser->setRealName(e->params()[2]);
361 // Else :nick!user@host JOIN #channelname
363 bool handledByNetsplit = false;
364 foreach(Netsplit* n, _netsplits.value(e->network())) {
365 handledByNetsplit = n->userJoined(e->prefix(), channel);
366 if (handledByNetsplit)
370 // If using away-notify, check new users. Works around buggy IRC servers
371 // forgetting to send :away messages for users who join channels when away.
372 if (net->capEnabled(IrcCap::AWAY_NOTIFY)) {
373 net->queueAutoWhoOneshot(ircuser->nick());
376 if (!handledByNetsplit)
377 ircuser->joinChannel(channel);
379 e->setFlag(EventManager::Netsplit);
381 if (net->isMe(ircuser)) {
382 net->setChannelJoined(channel);
384 net->putRawLine(net->serverEncode("MODE " + channel)); // we want to know the modes of the channel we just joined, so we ask politely
389 void CoreSessionEventProcessor::lateProcessIrcEventKick(IrcEvent *e)
391 if (checkParamCount(e, 2)) {
392 e->network()->updateNickFromMask(e->prefix());
393 IrcUser *victim = e->network()->ircUser(e->params().at(1));
395 victim->partChannel(e->params().at(0));
396 //if(e->network()->isMe(victim)) e->network()->setKickedFromChannel(channel);
402 void CoreSessionEventProcessor::processIrcEventMode(IrcEvent *e)
404 if (!checkParamCount(e, 2))
407 if (e->network()->isChannelName(e->params().first())) {
410 IrcChannel *channel = e->network()->ircChannel(e->params()[0]);
412 // we received mode information for a channel we're not in. that means probably we've just been kicked out or something like that
413 // anyways: we don't have a place to store the data --> discard the info.
417 QString modes = e->params()[1];
420 for (int c = 0; c < modes.length(); c++) {
421 if (modes[c] == '+') {
425 if (modes[c] == '-') {
430 if (e->network()->prefixModes().contains(modes[c])) {
431 // user channel modes (op, voice, etc...)
432 if (paramOffset < e->params().count()) {
433 IrcUser *ircUser = e->network()->ircUser(e->params()[paramOffset]);
435 qWarning() << Q_FUNC_INFO << "Unknown IrcUser:" << e->params()[paramOffset];
439 bool handledByNetsplit = false;
440 QHash<QString, Netsplit *> splits = _netsplits.value(e->network());
441 foreach(Netsplit* n, _netsplits.value(e->network())) {
442 handledByNetsplit = n->userAlreadyJoined(ircUser->hostmask(), channel->name());
443 if (handledByNetsplit) {
444 n->addMode(ircUser->hostmask(), channel->name(), QString(modes[c]));
448 if (!handledByNetsplit)
449 channel->addUserMode(ircUser, QString(modes[c]));
452 channel->removeUserMode(ircUser, QString(modes[c]));
456 qWarning() << "Received MODE with too few parameters:" << e->params();
461 // regular channel modes
463 Network::ChannelModeType modeType = e->network()->channelModeType(modes[c]);
464 if (modeType == Network::A_CHANMODE || modeType == Network::B_CHANMODE || (modeType == Network::C_CHANMODE && add)) {
465 if (paramOffset < e->params().count()) {
466 value = e->params()[paramOffset];
469 qWarning() << "Received MODE with too few parameters:" << e->params();
475 channel->addChannelMode(modes[c], value);
477 channel->removeChannelMode(modes[c], value);
483 IrcUser *ircUser = e->network()->newIrcUser(e->params().first());
484 QString modeString(e->params()[1]);
488 for (int c = 0; c < modeString.count(); c++) {
489 if (modeString[c] == '+') {
493 if (modeString[c] == '-') {
498 addModes += modeString[c];
500 removeModes += modeString[c];
502 if (!addModes.isEmpty())
503 ircUser->addUserModes(addModes);
504 if (!removeModes.isEmpty())
505 ircUser->removeUserModes(removeModes);
507 if (e->network()->isMe(ircUser)) {
508 coreNetwork(e)->updatePersistentModes(addModes, removeModes);
514 void CoreSessionEventProcessor::lateProcessIrcEventNick(IrcEvent *e)
516 if (checkParamCount(e, 1)) {
517 IrcUser *ircuser = e->network()->updateNickFromMask(e->prefix());
519 qWarning() << Q_FUNC_INFO << "Unknown IrcUser!";
522 QString newnick = e->params().at(0);
523 QString oldnick = ircuser->nick();
525 // the order is cruicial
526 // otherwise the client would rename the buffer, see that the assigned ircuser doesn't match anymore
527 // and remove the ircuser from the querybuffer leading to a wrong on/offline state
528 ircuser->setNick(newnick);
529 coreSession()->renameBuffer(e->networkId(), newnick, oldnick);
534 void CoreSessionEventProcessor::lateProcessIrcEventPart(IrcEvent *e)
536 if (checkParamCount(e, 1)) {
537 IrcUser *ircuser = e->network()->updateNickFromMask(e->prefix());
539 qWarning() << Q_FUNC_INFO<< "Unknown IrcUser!";
542 QString channel = e->params().at(0);
543 ircuser->partChannel(channel);
544 if (e->network()->isMe(ircuser))
545 qobject_cast<CoreNetwork *>(e->network())->setChannelParted(channel);
550 void CoreSessionEventProcessor::processIrcEventPing(IrcEvent *e)
552 QString param = e->params().count() ? e->params().first() : QString();
554 // Take priority so this won't get stuck behind other queued messages.
555 coreNetwork(e)->putRawLine("PONG " + coreNetwork(e)->serverEncode(param), true);
559 void CoreSessionEventProcessor::processIrcEventPong(IrcEvent *e)
561 // the server is supposed to send back what we passed as param. and we send a timestamp
562 // but using quote and whatnought one can send arbitrary pings, so we have to do some sanity checks
563 if (checkParamCount(e, 2)) {
564 QString timestamp = e->params().at(1);
565 QTime sendTime = QTime::fromString(timestamp, "hh:mm:ss.zzz");
566 if (sendTime.isValid())
567 e->network()->setLatency(sendTime.msecsTo(QTime::currentTime()) / 2);
572 void CoreSessionEventProcessor::processIrcEventQuit(IrcEvent *e)
574 IrcUser *ircuser = e->network()->updateNickFromMask(e->prefix());
579 if (e->params().count() > 0)
580 msg = e->params()[0];
583 if (Netsplit::isNetsplit(msg)) {
585 if (!_netsplits[e->network()].contains(msg)) {
586 n = new Netsplit(e->network(), this);
587 connect(n, SIGNAL(finished()), this, SLOT(handleNetsplitFinished()));
588 connect(n, SIGNAL(netsplitJoin(Network*, QString, QStringList, QStringList, QString)),
589 this, SLOT(handleNetsplitJoin(Network*, QString, QStringList, QStringList, QString)));
590 connect(n, SIGNAL(netsplitQuit(Network*, QString, QStringList, QString)),
591 this, SLOT(handleNetsplitQuit(Network*, QString, QStringList, QString)));
592 connect(n, SIGNAL(earlyJoin(Network*, QString, QStringList, QStringList)),
593 this, SLOT(handleEarlyNetsplitJoin(Network*, QString, QStringList, QStringList)));
594 _netsplits[e->network()].insert(msg, n);
597 n = _netsplits[e->network()][msg];
599 // add this user to the netsplit
600 n->userQuit(e->prefix(), ircuser->channels(), msg);
601 e->setFlag(EventManager::Netsplit);
603 // normal quit is handled in lateProcessIrcEventQuit()
607 void CoreSessionEventProcessor::lateProcessIrcEventQuit(IrcEvent *e)
609 if (e->testFlag(EventManager::Netsplit))
612 IrcUser *ircuser = e->network()->updateNickFromMask(e->prefix());
620 void CoreSessionEventProcessor::processIrcEventTopic(IrcEvent *e)
622 if (checkParamCount(e, 2)) {
623 e->network()->updateNickFromMask(e->prefix());
624 IrcChannel *channel = e->network()->ircChannel(e->params().at(0));
626 channel->setTopic(e->params().at(1));
632 void CoreSessionEventProcessor::processKeyEvent(KeyEvent *e)
634 if (!Cipher::neededFeaturesAvailable()) {
635 emit newEvent(new MessageEvent(Message::Error, e->network(), tr("Unable to perform key exchange, missing qca-ossl plugin."), e->prefix(), e->target(), Message::None, e->timestamp()));
638 CoreNetwork *net = qobject_cast<CoreNetwork*>(e->network());
639 Cipher *c = net->cipher(e->target());
640 if (!c) // happens when there is no CoreIrcChannel for the target (i.e. never?)
643 if (e->exchangeType() == KeyEvent::Init) {
644 QByteArray pubKey = c->parseInitKeyX(e->key());
645 if (pubKey.isEmpty()) {
646 emit newEvent(new MessageEvent(Message::Error, e->network(), tr("Unable to parse the DH1080_INIT. Key exchange failed."), e->prefix(), e->target(), Message::None, e->timestamp()));
649 net->setCipherKey(e->target(), c->key());
650 emit newEvent(new MessageEvent(Message::Info, e->network(), tr("Your key is set and messages will be encrypted."), e->prefix(), e->target(), Message::None, e->timestamp()));
652 p << net->serverEncode(e->target()) << net->serverEncode("DH1080_FINISH ")+pubKey;
653 net->putCmd("NOTICE", p);
656 if (c->parseFinishKeyX(e->key())) {
657 net->setCipherKey(e->target(), c->key());
658 emit newEvent(new MessageEvent(Message::Info, e->network(), tr("Your key is set and messages will be encrypted."), e->prefix(), e->target(), Message::None, e->timestamp()));
660 emit newEvent(new MessageEvent(Message::Info, e->network(), tr("Failed to parse DH1080_FINISH. Key exchange failed."), e->prefix(), e->target(), Message::None, e->timestamp()));
668 void CoreSessionEventProcessor::processIrcEvent001(IrcEventNumeric *e)
670 e->network()->setCurrentServer(e->prefix());
671 e->network()->setMyNick(e->target());
676 // TODO Complete 005 handling, also use sensible defaults for non-sent stuff
677 void CoreSessionEventProcessor::processIrcEvent005(IrcEvent *e)
679 if (!checkParamCount(e, 1))
683 for (int i = 0; i < e->params().count() - 1; i++) {
684 QString key = e->params()[i].section("=", 0, 0);
685 QString value = e->params()[i].section("=", 1);
686 e->network()->addSupport(key, value);
689 /* determine our prefixes here to get an accurate result */
690 e->network()->determinePrefixes();
694 /* RPL_UMODEIS - "<user_modes> [<user_mode_params>]" */
695 void CoreSessionEventProcessor::processIrcEvent221(IrcEvent *)
697 // TODO: save information in network object
701 /* RPL_STATSCONN - "Highest connection cout: 8000 (7999 clients)" */
702 void CoreSessionEventProcessor::processIrcEvent250(IrcEvent *)
704 // TODO: save information in network object
708 /* RPL_LOCALUSERS - "Current local user: 5024 Max: 7999 */
709 void CoreSessionEventProcessor::processIrcEvent265(IrcEvent *)
711 // TODO: save information in network object
715 /* RPL_GLOBALUSERS - "Current global users: 46093 Max: 47650" */
716 void CoreSessionEventProcessor::processIrcEvent266(IrcEvent *)
718 // TODO: save information in network object
724 Replies 311 - 313, 317 - 319 are all replies generated in response to a WHOIS message.
726 "<nick> :<away message>"
728 Replies 352 and 315 paired are used to answer a WHO message.
731 Replies 314 and 369 are responses to a WHOWAS message.
735 /* RPL_AWAY - "<nick> :<away message>" */
736 void CoreSessionEventProcessor::processIrcEvent301(IrcEvent *e)
738 if (!checkParamCount(e, 2))
741 IrcUser *ircuser = e->network()->ircUser(e->params().at(0));
743 ircuser->setAway(true);
744 ircuser->setAwayMessage(e->params().at(1));
745 //ircuser->setLastAwayMessage(now);
750 /* RPL_UNAWAY - ":You are no longer marked as being away" */
751 void CoreSessionEventProcessor::processIrcEvent305(IrcEvent *e)
753 IrcUser *me = e->network()->me();
757 if (e->network()->autoAwayActive()) {
758 e->network()->setAutoAwayActive(false);
759 e->setFlag(EventManager::Silent);
764 /* RPL_NOWAWAY - ":You have been marked as being away" */
765 void CoreSessionEventProcessor::processIrcEvent306(IrcEvent *e)
767 IrcUser *me = e->network()->me();
773 /* RPL_WHOISSERVICE - "<user> is registered nick" */
774 void CoreSessionEventProcessor::processIrcEvent307(IrcEvent *e)
776 if (!checkParamCount(e, 1))
779 IrcUser *ircuser = e->network()->ircUser(e->params().at(0));
781 ircuser->setWhoisServiceReply(e->params().join(" "));
785 /* RPL_SUSERHOST - "<user> is available for help." */
786 void CoreSessionEventProcessor::processIrcEvent310(IrcEvent *e)
788 if (!checkParamCount(e, 1))
791 IrcUser *ircuser = e->network()->ircUser(e->params().at(0));
793 ircuser->setSuserHost(e->params().join(" "));
797 /* RPL_WHOISUSER - "<nick> <user> <host> * :<real name>" */
798 void CoreSessionEventProcessor::processIrcEvent311(IrcEvent *e)
800 if (!checkParamCount(e, 3))
803 IrcUser *ircuser = e->network()->ircUser(e->params().at(0));
805 ircuser->setUser(e->params().at(1));
806 ircuser->setHost(e->params().at(2));
807 ircuser->setRealName(e->params().last());
812 /* RPL_WHOISSERVER - "<nick> <server> :<server info>" */
813 void CoreSessionEventProcessor::processIrcEvent312(IrcEvent *e)
815 if (!checkParamCount(e, 2))
818 IrcUser *ircuser = e->network()->ircUser(e->params().at(0));
820 ircuser->setServer(e->params().at(1));
824 /* RPL_WHOISOPERATOR - "<nick> :is an IRC operator" */
825 void CoreSessionEventProcessor::processIrcEvent313(IrcEvent *e)
827 if (!checkParamCount(e, 1))
830 IrcUser *ircuser = e->network()->ircUser(e->params().at(0));
832 ircuser->setIrcOperator(e->params().last());
836 /* RPL_ENDOFWHO: "<name> :End of WHO list" */
837 void CoreSessionEventProcessor::processIrcEvent315(IrcEvent *e)
839 if (!checkParamCount(e, 1))
842 if (coreNetwork(e)->setAutoWhoDone(e->params()[0]))
843 e->setFlag(EventManager::Silent);
847 /* RPL_WHOISIDLE - "<nick> <integer> :seconds idle"
848 (real life: "<nick> <integer> <integer> :seconds idle, signon time) */
849 void CoreSessionEventProcessor::processIrcEvent317(IrcEvent *e)
851 if (!checkParamCount(e, 2))
856 int idleSecs = e->params()[1].toInt();
857 if (e->params().count() > 3) { // if we have more then 3 params we have the above mentioned "real life" situation
858 int logintime = e->params()[2].toInt();
859 loginTime = QDateTime::fromTime_t(logintime);
862 IrcUser *ircuser = e->network()->ircUser(e->params()[0]);
864 ircuser->setIdleTime(e->timestamp().addSecs(-idleSecs));
865 if (loginTime.isValid())
866 ircuser->setLoginTime(loginTime);
871 /* RPL_LIST - "<channel> <# visible> :<topic>" */
872 void CoreSessionEventProcessor::processIrcEvent322(IrcEvent *e)
874 if (!checkParamCount(e, 1))
878 quint32 userCount = 0;
881 switch (e->params().count()) {
883 topic = e->params()[2];
885 userCount = e->params()[1].toUInt();
887 channelName = e->params()[0];
891 if (coreSession()->ircListHelper()->addChannel(e->networkId(), channelName, userCount, topic))
892 e->stop(); // consumed by IrcListHelper, so don't further process/show this event
896 /* RPL_LISTEND ":End of LIST" */
897 void CoreSessionEventProcessor::processIrcEvent323(IrcEvent *e)
899 if (!checkParamCount(e, 1))
902 if (coreSession()->ircListHelper()->endOfChannelList(e->networkId()))
903 e->stop(); // consumed by IrcListHelper, so don't further process/show this event
907 /* RPL_CHANNELMODEIS - "<channel> <mode> <mode params>" */
908 void CoreSessionEventProcessor::processIrcEvent324(IrcEvent *e)
910 processIrcEventMode(e);
914 /* RPL_WHOISACCOUNT - "<nick> <account> :is authed as" */
915 void CoreSessionEventProcessor::processIrcEvent330(IrcEvent *e)
917 // Though the ":is authed as" remark should always be there, we should handle cases when it's
918 // not included, too.
919 if (!checkParamCount(e, 2))
922 IrcUser *ircuser = e->network()->ircUser(e->params().at(0));
924 ircuser->setAccount(e->params().at(1));
930 void CoreSessionEventProcessor::processIrcEvent331(IrcEvent *e)
932 if (!checkParamCount(e, 1))
935 IrcChannel *chan = e->network()->ircChannel(e->params()[0]);
937 chan->setTopic(QString());
942 void CoreSessionEventProcessor::processIrcEvent332(IrcEvent *e)
944 if (!checkParamCount(e, 2))
947 IrcChannel *chan = e->network()->ircChannel(e->params()[0]);
949 chan->setTopic(e->params()[1]);
953 /* RPL_WHOREPLY: "<channel> <user> <host> <server> <nick>
954 ( "H" / "G" > ["*"] [ ( "@" / "+" ) ] :<hopcount> <real name>" */
955 void CoreSessionEventProcessor::processIrcEvent352(IrcEvent *e)
957 if (!checkParamCount(e, 6))
960 QString channel = e->params()[0];
961 IrcUser *ircuser = e->network()->ircUser(e->params()[4]);
963 processWhoInformation(e->network(), channel, ircuser, e->params()[3], e->params()[1],
964 e->params()[2], e->params()[5], e->params().last().section(" ", 1));
967 // Check if channel name has a who in progress.
968 // If not, then check if user nick exists and has a who in progress.
969 if (coreNetwork(e)->isAutoWhoInProgress(channel) ||
970 (ircuser && coreNetwork(e)->isAutoWhoInProgress(ircuser->nick()))) {
971 e->setFlag(EventManager::Silent);
977 void CoreSessionEventProcessor::processIrcEvent353(IrcEvent *e)
979 if (!checkParamCount(e, 3))
982 // param[0] is either "=", "*" or "@" indicating a public, private or secret channel
983 // we don't use this information at the time beeing
984 QString channelname = e->params()[1];
986 IrcChannel *channel = e->network()->ircChannel(channelname);
988 qWarning() << Q_FUNC_INFO << "Received unknown target channel:" << channelname;
995 // Cache result of multi-prefix to avoid unneeded casts and lookups with each iteration.
996 bool _useCapMultiPrefix = coreNetwork(e)->capEnabled(IrcCap::MULTI_PREFIX);
998 foreach(QString nick, e->params()[2].split(' ', QString::SkipEmptyParts)) {
1001 if (_useCapMultiPrefix) {
1002 // If multi-prefix is enabled, all modes will be sent in NAMES replies.
1003 // :hades.arpa 353 guest = #tethys :~&@%+aji &@Attila @+alyx +KindOne Argure
1004 // See: http://ircv3.net/specs/extensions/multi-prefix-3.1.html
1005 while (e->network()->prefixes().contains(nick[0])) {
1006 // Mode found in 1 left-most character, add it to the list.
1007 // Note: sending multiple modes may cause a warning in older clients.
1008 // In testing, the clients still seemed to function fine.
1009 mode.append(e->network()->prefixToMode(nick[0]));
1010 // Remove this mode from the nick
1011 nick = nick.remove(0, 1);
1013 } else if (e->network()->prefixes().contains(nick[0])) {
1014 // Multi-prefix is disabled and a mode prefix was found.
1015 mode = e->network()->prefixToMode(nick[0]);
1019 // If userhost-in-names capability is enabled, the following will be
1020 // in the form "nick!user@host" rather than "nick". This works without
1021 // special handling as the following use nickFromHost() as needed.
1022 // See: http://ircv3.net/specs/extensions/userhost-in-names-3.2.html
1028 channel->joinIrcUsers(nicks, modes);
1032 /* RPL_WHOSPCRPL: "<yournick> 152 #<channel> ~<ident> <host> <servname> <nick>
1033 ("H"/ "G") <account> :<realname>"
1034 <channel> is * if not specific to any channel
1035 <account> is * if not logged in
1036 Follows HexChat's usage of 'whox'
1037 See https://github.com/hexchat/hexchat/blob/c874a9525c9b66f1d5ddcf6c4107d046eba7e2c5/src/common/proto-irc.c#L750
1038 And http://faerion.sourceforge.net/doc/irc/whox.var*/
1039 void CoreSessionEventProcessor::processIrcEvent354(IrcEvent *e)
1041 // First only check if at least one parameter exists. Otherwise, it'll stop the result from
1042 // being shown if the user chooses different parameters.
1043 if (!checkParamCount(e, 1))
1046 if (e->params()[0].toUInt() != IrcCap::ACCOUNT_NOTIFY_WHOX_NUM) {
1047 // Ignore WHOX replies without expected number for we have no idea what fields are specified
1051 // Now we're fairly certain this is supposed to be an automated WHOX. Bail out if it doesn't
1052 // match what we require - 9 parameters.
1053 if (!checkParamCount(e, 9))
1056 QString channel = e->params()[1];
1057 IrcUser *ircuser = e->network()->ircUser(e->params()[5]);
1059 processWhoInformation(e->network(), channel, ircuser, e->params()[4], e->params()[2],
1060 e->params()[3], e->params()[6], e->params().last());
1061 // Don't use .section(" ", 1) with WHOX replies, for there's no hopcount to trim out
1063 // As part of IRCv3 account-notify, check account name
1064 // WHOX uses '0' to indicate logged-out, account-notify and extended-join uses '*'.
1065 QString newAccount = e->params()[7];
1066 if (newAccount != "0") {
1067 // Account logged in, set account name
1068 ircuser->setAccount(newAccount);
1070 // Account logged out, set account name to logged-out
1071 ircuser->setAccount("*");
1075 // Check if channel name has a who in progress.
1076 // If not, then check if user nick exists and has a who in progress.
1077 if (coreNetwork(e)->isAutoWhoInProgress(channel) ||
1078 (ircuser && coreNetwork(e)->isAutoWhoInProgress(ircuser->nick()))) {
1079 e->setFlag(EventManager::Silent);
1084 void CoreSessionEventProcessor::processWhoInformation (Network *net, const QString &targetChannel, IrcUser *ircUser,
1085 const QString &server, const QString &user, const QString &host,
1086 const QString &awayStateAndModes, const QString &realname)
1088 ircUser->setUser(user);
1089 ircUser->setHost(host);
1090 ircUser->setServer(server);
1091 ircUser->setRealName(realname);
1093 bool away = awayStateAndModes.contains("G", Qt::CaseInsensitive);
1094 ircUser->setAway(away);
1096 if (net->capEnabled(IrcCap::MULTI_PREFIX)) {
1097 // If multi-prefix is enabled, all modes will be sent in WHO replies.
1098 // :kenny.chatspike.net 352 guest #test grawity broken.symlink *.chatspike.net grawity H@%+ :0 Mantas M.
1099 // See: http://ircv3.net/specs/extensions/multi-prefix-3.1.html
1100 QString uncheckedModes = awayStateAndModes;
1101 QString validModes = QString();
1102 while (!uncheckedModes.isEmpty()) {
1103 // Mode found in 1 left-most character, add it to the list
1104 if (net->prefixes().contains(uncheckedModes[0])) {
1105 validModes.append(net->prefixToMode(uncheckedModes[0]));
1107 // Remove this mode from the list of unchecked modes
1108 uncheckedModes = uncheckedModes.remove(0, 1);
1111 // Some IRC servers decide to not follow the spec, returning only -some- of the user
1112 // modes in WHO despite listing them all in NAMES. For now, assume it can only add
1113 // and not take away. *sigh*
1114 if (!validModes.isEmpty()) {
1115 if (targetChannel != "*") {
1116 // Channel-specific modes received, apply to given channel only
1117 IrcChannel *ircChan = net->ircChannel(targetChannel);
1119 // Do one mode at a time
1120 // TODO Better way of syncing this without breaking protocol?
1121 for (int i = 0; i < validModes.count(); ++i) {
1122 ircChan->addUserMode(ircUser, validModes.at(i));
1126 // Modes apply to the user everywhere
1127 ircUser->addUserModes(validModes);
1134 /* ERR_NOSUCHCHANNEL - "<channel name> :No such channel" */
1135 void CoreSessionEventProcessor::processIrcEvent403(IrcEventNumeric *e)
1137 // If this is the result of an AutoWho, hide it. It's confusing to show to the user.
1138 // Though the ":No such channel" remark should always be there, we should handle cases when it's
1139 // not included, too.
1140 if (!checkParamCount(e, 1))
1143 QString channelOrNick = e->params()[0];
1144 // Check if channel name has a who in progress.
1145 // If not, then check if user nick exists and has a who in progress.
1146 if (coreNetwork(e)->isAutoWhoInProgress(channelOrNick)) {
1147 qDebug() << "Channel/nick" << channelOrNick << "no longer exists during AutoWho, ignoring";
1148 e->setFlag(EventManager::Silent);
1152 /* ERR_ERRONEUSNICKNAME */
1153 void CoreSessionEventProcessor::processIrcEvent432(IrcEventNumeric *e)
1155 if (!checkParamCount(e, 1))
1159 if (e->params().count() < 2) {
1160 // handle unreal-ircd bug, where unreal ircd doesnt supply a TARGET in ERR_ERRONEUSNICKNAME during registration phase:
1162 // :irc.scortum.moep.net 432 @@@ :Erroneous Nickname: Illegal characters
1163 // correct server reply:
1164 // :irc.scortum.moep.net 432 * @@@ :Erroneous Nickname: Illegal characters
1165 e->params().prepend(e->target());
1168 errnick = e->params()[0];
1170 tryNextNick(e, errnick, true /* erroneus */);
1174 /* ERR_NICKNAMEINUSE */
1175 void CoreSessionEventProcessor::processIrcEvent433(IrcEventNumeric *e)
1177 if (!checkParamCount(e, 1))
1180 QString errnick = e->params().first();
1182 // if there is a problem while connecting to the server -> we handle it
1183 // but only if our connection has not been finished yet...
1184 if (!e->network()->currentServer().isEmpty())
1187 tryNextNick(e, errnick);
1191 /* ERR_UNAVAILRESOURCE */
1192 void CoreSessionEventProcessor::processIrcEvent437(IrcEventNumeric *e)
1194 if (!checkParamCount(e, 1))
1197 QString errnick = e->params().first();
1199 // if there is a problem while connecting to the server -> we handle it
1200 // but only if our connection has not been finished yet...
1201 if (!e->network()->currentServer().isEmpty())
1204 if (!e->network()->isChannelName(errnick))
1205 tryNextNick(e, errnick);
1210 void CoreSessionEventProcessor::processIrcEvent(IrcEvent *e) {
1211 if(!checkParamCount(e, 1))
1217 /* Handle signals from Netsplit objects */
1219 void CoreSessionEventProcessor::handleNetsplitJoin(Network *net,
1220 const QString &channel,
1221 const QStringList &users,
1222 const QStringList &modes,
1223 const QString &quitMessage)
1225 IrcChannel *ircChannel = net->ircChannel(channel);
1229 QList<IrcUser *> ircUsers;
1230 QStringList newModes = modes;
1231 QStringList newUsers = users;
1233 foreach(const QString &user, users) {
1234 IrcUser *iu = net->ircUser(nickFromMask(user));
1236 ircUsers.append(iu);
1237 else { // the user already quit
1238 int idx = users.indexOf(user);
1239 newUsers.removeAt(idx);
1240 newModes.removeAt(idx);
1244 ircChannel->joinIrcUsers(ircUsers, newModes);
1245 NetworkSplitEvent *event = new NetworkSplitEvent(EventManager::NetworkSplitJoin, net, channel, newUsers, quitMessage);
1246 emit newEvent(event);
1250 void CoreSessionEventProcessor::handleNetsplitQuit(Network *net, const QString &channel, const QStringList &users, const QString &quitMessage)
1252 NetworkSplitEvent *event = new NetworkSplitEvent(EventManager::NetworkSplitQuit, net, channel, users, quitMessage);
1253 emit newEvent(event);
1254 foreach(QString user, users) {
1255 IrcUser *iu = net->ircUser(nickFromMask(user));
1262 void CoreSessionEventProcessor::handleEarlyNetsplitJoin(Network *net, const QString &channel, const QStringList &users, const QStringList &modes)
1264 IrcChannel *ircChannel = net->ircChannel(channel);
1266 qDebug() << "handleEarlyNetsplitJoin(): channel " << channel << " invalid";
1269 QList<NetworkEvent *> events;
1270 QList<IrcUser *> ircUsers;
1271 QStringList newModes = modes;
1273 foreach(QString user, users) {
1274 IrcUser *iu = net->updateNickFromMask(user);
1276 ircUsers.append(iu);
1277 // fake event for scripts that consume join events
1278 events << new IrcEvent(EventManager::IrcEventJoin, net, iu->hostmask(), QStringList() << channel);
1281 newModes.removeAt(users.indexOf(user));
1284 ircChannel->joinIrcUsers(ircUsers, newModes);
1285 foreach(NetworkEvent *event, events) {
1286 event->setFlag(EventManager::Fake); // ignore this in here!
1287 emit newEvent(event);
1292 void CoreSessionEventProcessor::handleNetsplitFinished()
1294 Netsplit *n = qobject_cast<Netsplit *>(sender());
1296 QHash<QString, Netsplit *> splithash = _netsplits.take(n->network());
1297 splithash.remove(splithash.key(n));
1298 if (splithash.count())
1299 _netsplits[n->network()] = splithash;
1304 void CoreSessionEventProcessor::destroyNetsplits(NetworkId netId)
1306 Network *net = coreSession()->network(netId);
1310 QHash<QString, Netsplit *> splits = _netsplits.take(net);
1315 /*******************************/
1316 /******** CTCP HANDLING ********/
1317 /*******************************/
1319 void CoreSessionEventProcessor::processCtcpEvent(CtcpEvent *e)
1321 if (e->testFlag(EventManager::Self))
1322 return; // ignore ctcp events generated by user input
1324 if (e->type() != EventManager::CtcpEvent || e->ctcpType() != CtcpEvent::Query)
1327 handle(e->ctcpCmd(), Q_ARG(CtcpEvent *, e));
1331 void CoreSessionEventProcessor::defaultHandler(const QString &ctcpCmd, CtcpEvent *e)
1333 // This handler is only there to avoid warnings for unknown CTCPs
1339 void CoreSessionEventProcessor::handleCtcpAction(CtcpEvent *e)
1341 // This handler is only there to feed CLIENTINFO
1346 void CoreSessionEventProcessor::handleCtcpClientinfo(CtcpEvent *e)
1348 QStringList supportedHandlers;
1349 foreach(QString handler, providesHandlers())
1350 supportedHandlers << handler.toUpper();
1351 qSort(supportedHandlers);
1352 e->setReply(supportedHandlers.join(" "));
1356 // http://www.irchelp.org/irchelp/rfc/ctcpspec.html
1357 // http://en.wikipedia.org/wiki/Direct_Client-to-Client
1358 void CoreSessionEventProcessor::handleCtcpDcc(CtcpEvent *e)
1360 // DCC support is unfinished, experimental and potentially dangerous, so make it opt-in
1361 if (!Quassel::isOptionSet("enable-experimental-dcc")) {
1362 quInfo() << "DCC disabled, start core with --enable-experimental-dcc if you really want to try it out";
1366 // normal: SEND <filename> <ip> <port> [<filesize>]
1367 // reverse: SEND <filename> <ip> 0 <filesize> <token>
1368 QStringList params = e->param().split(' ');
1369 if (params.count()) {
1370 QString cmd = params[0].toUpper();
1371 if (cmd == "SEND") {
1372 if (params.count() < 4) {
1373 qWarning() << "Invalid DCC SEND request:" << e; // TODO emit proper error to client
1376 QString filename = params[1];
1377 QHostAddress address;
1378 quint16 port = params[3].toUShort();
1380 QString numIp = params[2]; // this is either IPv4 as a 32 bit value, or IPv6 (which always contains a colon)
1381 if (numIp.contains(':')) { // IPv6
1382 if (!address.setAddress(numIp)) {
1383 qWarning() << "Invalid IPv6:" << numIp;
1388 address.setAddress(numIp.toUInt());
1391 if (port == 0) { // Reverse DCC is indicated by a 0 port
1392 emit newEvent(new MessageEvent(Message::Error, e->network(), tr("Reverse DCC SEND not supported"), e->prefix(), e->target(), Message::None, e->timestamp()));
1396 qWarning() << "Privileged port requested:" << port; // FIXME ask user if this is ok
1400 if (params.count() > 4) { // filesize is optional
1401 size = params[4].toULong();
1404 // TODO: check if target is the right thing to use for the partner
1405 CoreTransfer *transfer = new CoreTransfer(Transfer::Direction::Receive, e->target(), filename, address, port, size, this);
1406 coreSession()->signalProxy()->synchronize(transfer);
1407 coreSession()->transferManager()->addTransfer(transfer);
1410 emit newEvent(new MessageEvent(Message::Error, e->network(), tr("DCC %1 not supported").arg(cmd), e->prefix(), e->target(), Message::None, e->timestamp()));
1417 void CoreSessionEventProcessor::handleCtcpPing(CtcpEvent *e)
1419 e->setReply(e->param().isNull() ? "" : e->param());
1423 void CoreSessionEventProcessor::handleCtcpTime(CtcpEvent *e)
1425 e->setReply(QDateTime::currentDateTime().toString());
1429 void CoreSessionEventProcessor::handleCtcpVersion(CtcpEvent *e)
1431 e->setReply(QString("Quassel IRC %1 (built on %2) -- http://www.quassel-irc.org")
1432 .arg(Quassel::buildInfo().plainVersionString).arg(Quassel::buildInfo().commitDate));