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
158 if (e->params().count() >= 3) {
159 CoreNetwork *coreNet = coreNetwork(e);
160 QString capCommand = e->params().at(1).trimmed().toUpper();
161 if (capCommand == "LS" || capCommand == "NEW") {
162 // Either we've gotten a list of capabilities, or new capabilities we may want
163 // Server: CAP * LS * :multi-prefix extended-join account-notify batch invite-notify tls
164 // Server: CAP * LS * :cap-notify server-time example.org/dummy-cap=dummyvalue example.org/second-dummy-cap
165 // Server: CAP * LS :userhost-in-names sasl=EXTERNAL,DH-AES,DH-BLOWFISH,ECDSA-NIST256P-CHALLENGE,PLAIN
166 bool capListFinished;
167 QStringList availableCaps;
168 if (e->params().count() == 4) {
169 // Middle of multi-line reply, ignore the asterisk
170 capListFinished = false;
171 availableCaps = e->params().at(3).split(' ');
174 capListFinished = true;
175 availableCaps = e->params().at(2).split(' ');
177 // Store what capabilities are available
178 QString availableCapName, availableCapValue;
179 for (int i = 0; i < availableCaps.count(); ++i) {
180 // Capability may include values, e.g. CAP * LS :multi-prefix sasl=EXTERNAL
181 // Capability name comes before the first '='. If no '=' exists, this gets the
182 // whole string instead.
183 availableCapName = availableCaps[i].section('=', 0, 0).trimmed();
184 // Some capabilities include multiple key=value pairs in the listing,
185 // e.g. "sts=duration=31536000,port=6697"
186 // Include everything after the first equal sign as part of the value. If no '='
187 // exists, this gets an empty string.
188 availableCapValue = availableCaps[i].section('=', 1).trimmed();
189 // Only add the capability if it's non-empty
190 if (!availableCapName.isEmpty()) {
191 coreNet->addCap(availableCapName, availableCapValue);
195 // Begin capability requests when capability listing complete
197 coreNet->beginCapNegotiation();
198 } else if (capCommand == "ACK") {
199 // Server: CAP * ACK :multi-prefix sasl
200 // Got the capability we want, handle as needed.
201 // As only one capability is requested at a time, no need to split
202 QString acceptedCap = e->params().at(2).trimmed().toLower();
204 // Mark this cap as accepted
205 coreNet->acknowledgeCap(acceptedCap);
207 if (!coreNet->capsRequiringConfiguration.contains(acceptedCap)) {
208 // Some capabilities (e.g. SASL) require further messages to finish. If so, do NOT
209 // send the next capability; it will be handled elsewhere in CoreNetwork.
210 // Otherwise, move on to the next capability
211 coreNet->sendNextCap();
213 } else if (capCommand == "NAK" || capCommand == "DEL") {
214 // Either something went wrong with this capability, or it is no longer supported
216 // Server: CAP * NAK :multi-prefix sasl
218 // Server: :irc.example.com CAP modernclient DEL :multi-prefix sasl
219 // CAP NAK and CAP DEL replies are always single-line
221 QStringList removedCaps;
222 removedCaps = e->params().at(2).split(' ');
224 // Store what capability was denied or removed
226 for (int i = 0; i < removedCaps.count(); ++i) {
227 removedCap = removedCaps[i].trimmed().toLower();
228 // Mark this cap as removed
229 coreNet->removeCap(removedCap);
232 if (capCommand == "NAK") {
233 // Continue negotiation when capability listing complete only if this is the result
234 // of a denied cap, not a removed cap
235 coreNet->sendNextCap();
241 /* IRCv3 account-notify
242 * Log in: ":nick!user@host ACCOUNT accountname"
243 * Log out: ":nick!user@host ACCOUNT *" */
244 void CoreSessionEventProcessor::processIrcEventAccount(IrcEvent *e)
246 if (!checkParamCount(e, 1))
249 IrcUser *ircuser = e->network()->updateNickFromMask(e->prefix());
251 // WHOX uses '0' to indicate logged-out, account-notify and extended-join uses '*'.
252 // As '*' is used internally to represent logged-out, no need to handle that differently.
253 ircuser->setAccount(e->params().at(0));
255 qDebug() << "Received account-notify data for unknown user" << e->prefix();
259 /* IRCv3 away-notify - ":nick!user@host AWAY [:message]" */
260 void CoreSessionEventProcessor::processIrcEventAway(IrcEvent *e)
262 if (!checkParamCount(e, 1))
264 // Don't use checkParamCount(e, 2) since the message is optional. Some servers respond in a way
265 // that it counts as two parameters, but we shouldn't rely on that.
267 // Nick is sent as part of parameters in order to split user/server decoding
268 IrcUser *ircuser = e->network()->ircUser(e->params().at(0));
270 // If two parameters are sent -and- the second parameter isn't empty, then user is away.
271 // Otherwise, mark them as not away.
272 if (e->params().count() >= 2 && !e->params().at(1).isEmpty()) {
273 ircuser->setAway(true);
274 ircuser->setAwayMessage(e->params().at(1));
276 ircuser->setAway(false);
279 qDebug() << "Received away-notify data for unknown user" << e->params().at(0);
283 /* IRCv3 chghost - ":nick!user@host CHGHOST newuser new.host.goes.here" */
284 void CoreSessionEventProcessor::processIrcEventChghost(IrcEvent *e)
286 if (!checkParamCount(e, 2))
289 IrcUser *ircuser = e->network()->updateNickFromMask(e->prefix());
291 // Update with new user/hostname information. setUser/setHost handles checking what
293 ircuser->setUser(e->params().at(0));
294 ircuser->setHost(e->params().at(1));
296 qDebug() << "Received chghost data for unknown user" << e->prefix();
300 void CoreSessionEventProcessor::processIrcEventInvite(IrcEvent *e)
302 if (checkParamCount(e, 2)) {
303 e->network()->updateNickFromMask(e->prefix());
307 /* JOIN: ":<nick!user@host> JOIN <channel>" */
308 void CoreSessionEventProcessor::processIrcEventJoin(IrcEvent *e)
310 if (e->testFlag(EventManager::Fake)) // generated by handleEarlyNetsplitJoin
313 if (!checkParamCount(e, 1))
316 CoreNetwork *net = coreNetwork(e);
317 QString channel = e->params()[0];
318 IrcUser *ircuser = net->updateNickFromMask(e->prefix());
320 if (net->capEnabled(IrcCap::EXTENDED_JOIN)) {
321 if (e->params().count() < 3) {
322 // Some IRC servers don't send extended-join events in all situations. Rather than
323 // ignore the join entirely, treat it as a regular join with a debug-level log entry.
324 // See: https://github.com/inspircd/inspircd/issues/821
325 qDebug() << "extended-join requires 3 params, got:" << e->params() << ", handling as a "
328 // If logged in, :nick!user@host JOIN #channelname accountname :Real Name
329 // If logged out, :nick!user@host JOIN #channelname * :Real Name
330 // See: http://ircv3.net/specs/extensions/extended-join-3.1.html
331 // WHOX uses '0' to indicate logged-out, account-notify and extended-join uses '*'.
332 // As '*' is used internally to represent logged-out, no need to handle that differently.
333 ircuser->setAccount(e->params()[1]);
334 // Update the user's real name, too
335 ircuser->setRealName(e->params()[2]);
338 // Else :nick!user@host JOIN #channelname
340 bool handledByNetsplit = false;
341 foreach(Netsplit* n, _netsplits.value(e->network())) {
342 handledByNetsplit = n->userJoined(e->prefix(), channel);
343 if (handledByNetsplit)
347 // If using away-notify, check new users. Works around buggy IRC servers
348 // forgetting to send :away messages for users who join channels when away.
349 if (net->capEnabled(IrcCap::AWAY_NOTIFY)) {
350 net->queueAutoWhoOneshot(ircuser->nick());
353 if (!handledByNetsplit)
354 ircuser->joinChannel(channel);
356 e->setFlag(EventManager::Netsplit);
358 if (net->isMe(ircuser)) {
359 net->setChannelJoined(channel);
361 net->putRawLine(net->serverEncode("MODE " + channel)); // we want to know the modes of the channel we just joined, so we ask politely
366 void CoreSessionEventProcessor::lateProcessIrcEventKick(IrcEvent *e)
368 if (checkParamCount(e, 2)) {
369 e->network()->updateNickFromMask(e->prefix());
370 IrcUser *victim = e->network()->ircUser(e->params().at(1));
372 victim->partChannel(e->params().at(0));
373 //if(e->network()->isMe(victim)) e->network()->setKickedFromChannel(channel);
379 void CoreSessionEventProcessor::processIrcEventMode(IrcEvent *e)
381 if (!checkParamCount(e, 2))
384 if (e->network()->isChannelName(e->params().first())) {
387 IrcChannel *channel = e->network()->ircChannel(e->params()[0]);
389 // we received mode information for a channel we're not in. that means probably we've just been kicked out or something like that
390 // anyways: we don't have a place to store the data --> discard the info.
394 QString modes = e->params()[1];
397 for (int c = 0; c < modes.length(); c++) {
398 if (modes[c] == '+') {
402 if (modes[c] == '-') {
407 if (e->network()->prefixModes().contains(modes[c])) {
408 // user channel modes (op, voice, etc...)
409 if (paramOffset < e->params().count()) {
410 IrcUser *ircUser = e->network()->ircUser(e->params()[paramOffset]);
412 qWarning() << Q_FUNC_INFO << "Unknown IrcUser:" << e->params()[paramOffset];
416 bool handledByNetsplit = false;
417 QHash<QString, Netsplit *> splits = _netsplits.value(e->network());
418 foreach(Netsplit* n, _netsplits.value(e->network())) {
419 handledByNetsplit = n->userAlreadyJoined(ircUser->hostmask(), channel->name());
420 if (handledByNetsplit) {
421 n->addMode(ircUser->hostmask(), channel->name(), QString(modes[c]));
425 if (!handledByNetsplit)
426 channel->addUserMode(ircUser, QString(modes[c]));
429 channel->removeUserMode(ircUser, QString(modes[c]));
433 qWarning() << "Received MODE with too few parameters:" << e->params();
438 // regular channel modes
440 Network::ChannelModeType modeType = e->network()->channelModeType(modes[c]);
441 if (modeType == Network::A_CHANMODE || modeType == Network::B_CHANMODE || (modeType == Network::C_CHANMODE && add)) {
442 if (paramOffset < e->params().count()) {
443 value = e->params()[paramOffset];
446 qWarning() << "Received MODE with too few parameters:" << e->params();
452 channel->addChannelMode(modes[c], value);
454 channel->removeChannelMode(modes[c], value);
460 IrcUser *ircUser = e->network()->newIrcUser(e->params().first());
461 QString modeString(e->params()[1]);
465 for (int c = 0; c < modeString.count(); c++) {
466 if (modeString[c] == '+') {
470 if (modeString[c] == '-') {
475 addModes += modeString[c];
477 removeModes += modeString[c];
479 if (!addModes.isEmpty())
480 ircUser->addUserModes(addModes);
481 if (!removeModes.isEmpty())
482 ircUser->removeUserModes(removeModes);
484 if (e->network()->isMe(ircUser)) {
485 coreNetwork(e)->updatePersistentModes(addModes, removeModes);
491 void CoreSessionEventProcessor::lateProcessIrcEventNick(IrcEvent *e)
493 if (checkParamCount(e, 1)) {
494 IrcUser *ircuser = e->network()->updateNickFromMask(e->prefix());
496 qWarning() << Q_FUNC_INFO << "Unknown IrcUser!";
499 QString newnick = e->params().at(0);
500 QString oldnick = ircuser->nick();
502 // the order is cruicial
503 // otherwise the client would rename the buffer, see that the assigned ircuser doesn't match anymore
504 // and remove the ircuser from the querybuffer leading to a wrong on/offline state
505 ircuser->setNick(newnick);
506 coreSession()->renameBuffer(e->networkId(), newnick, oldnick);
511 void CoreSessionEventProcessor::lateProcessIrcEventPart(IrcEvent *e)
513 if (checkParamCount(e, 1)) {
514 IrcUser *ircuser = e->network()->updateNickFromMask(e->prefix());
516 qWarning() << Q_FUNC_INFO<< "Unknown IrcUser!";
519 QString channel = e->params().at(0);
520 ircuser->partChannel(channel);
521 if (e->network()->isMe(ircuser))
522 qobject_cast<CoreNetwork *>(e->network())->setChannelParted(channel);
527 void CoreSessionEventProcessor::processIrcEventPing(IrcEvent *e)
529 QString param = e->params().count() ? e->params().first() : QString();
531 // Take priority so this won't get stuck behind other queued messages.
532 coreNetwork(e)->putRawLine("PONG " + coreNetwork(e)->serverEncode(param), true);
536 void CoreSessionEventProcessor::processIrcEventPong(IrcEvent *e)
538 // the server is supposed to send back what we passed as param. and we send a timestamp
539 // but using quote and whatnought one can send arbitrary pings, so we have to do some sanity checks
540 if (checkParamCount(e, 2)) {
541 QString timestamp = e->params().at(1);
542 QTime sendTime = QTime::fromString(timestamp, "hh:mm:ss.zzz");
543 if (sendTime.isValid())
544 e->network()->setLatency(sendTime.msecsTo(QTime::currentTime()) / 2);
549 void CoreSessionEventProcessor::processIrcEventQuit(IrcEvent *e)
551 IrcUser *ircuser = e->network()->updateNickFromMask(e->prefix());
556 if (e->params().count() > 0)
557 msg = e->params()[0];
560 if (Netsplit::isNetsplit(msg)) {
562 if (!_netsplits[e->network()].contains(msg)) {
563 n = new Netsplit(e->network(), this);
564 connect(n, SIGNAL(finished()), this, SLOT(handleNetsplitFinished()));
565 connect(n, SIGNAL(netsplitJoin(Network*, QString, QStringList, QStringList, QString)),
566 this, SLOT(handleNetsplitJoin(Network*, QString, QStringList, QStringList, QString)));
567 connect(n, SIGNAL(netsplitQuit(Network*, QString, QStringList, QString)),
568 this, SLOT(handleNetsplitQuit(Network*, QString, QStringList, QString)));
569 connect(n, SIGNAL(earlyJoin(Network*, QString, QStringList, QStringList)),
570 this, SLOT(handleEarlyNetsplitJoin(Network*, QString, QStringList, QStringList)));
571 _netsplits[e->network()].insert(msg, n);
574 n = _netsplits[e->network()][msg];
576 // add this user to the netsplit
577 n->userQuit(e->prefix(), ircuser->channels(), msg);
578 e->setFlag(EventManager::Netsplit);
580 // normal quit is handled in lateProcessIrcEventQuit()
584 void CoreSessionEventProcessor::lateProcessIrcEventQuit(IrcEvent *e)
586 if (e->testFlag(EventManager::Netsplit))
589 IrcUser *ircuser = e->network()->updateNickFromMask(e->prefix());
597 void CoreSessionEventProcessor::processIrcEventTopic(IrcEvent *e)
599 if (checkParamCount(e, 2)) {
600 e->network()->updateNickFromMask(e->prefix());
601 IrcChannel *channel = e->network()->ircChannel(e->params().at(0));
603 channel->setTopic(e->params().at(1));
609 void CoreSessionEventProcessor::processKeyEvent(KeyEvent *e)
611 if (!Cipher::neededFeaturesAvailable()) {
612 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()));
615 CoreNetwork *net = qobject_cast<CoreNetwork*>(e->network());
616 Cipher *c = net->cipher(e->target());
617 if (!c) // happens when there is no CoreIrcChannel for the target (i.e. never?)
620 if (e->exchangeType() == KeyEvent::Init) {
621 QByteArray pubKey = c->parseInitKeyX(e->key());
622 if (pubKey.isEmpty()) {
623 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()));
626 net->setCipherKey(e->target(), c->key());
627 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()));
629 p << net->serverEncode(e->target()) << net->serverEncode("DH1080_FINISH ")+pubKey;
630 net->putCmd("NOTICE", p);
633 if (c->parseFinishKeyX(e->key())) {
634 net->setCipherKey(e->target(), c->key());
635 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()));
637 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()));
645 void CoreSessionEventProcessor::processIrcEvent001(IrcEventNumeric *e)
647 e->network()->setCurrentServer(e->prefix());
648 e->network()->setMyNick(e->target());
653 // TODO Complete 005 handling, also use sensible defaults for non-sent stuff
654 void CoreSessionEventProcessor::processIrcEvent005(IrcEvent *e)
656 if (!checkParamCount(e, 1))
660 for (int i = 0; i < e->params().count() - 1; i++) {
661 QString key = e->params()[i].section("=", 0, 0);
662 QString value = e->params()[i].section("=", 1);
663 e->network()->addSupport(key, value);
666 /* determine our prefixes here to get an accurate result */
667 e->network()->determinePrefixes();
671 /* RPL_UMODEIS - "<user_modes> [<user_mode_params>]" */
672 void CoreSessionEventProcessor::processIrcEvent221(IrcEvent *)
674 // TODO: save information in network object
678 /* RPL_STATSCONN - "Highest connection cout: 8000 (7999 clients)" */
679 void CoreSessionEventProcessor::processIrcEvent250(IrcEvent *)
681 // TODO: save information in network object
685 /* RPL_LOCALUSERS - "Current local user: 5024 Max: 7999 */
686 void CoreSessionEventProcessor::processIrcEvent265(IrcEvent *)
688 // TODO: save information in network object
692 /* RPL_GLOBALUSERS - "Current global users: 46093 Max: 47650" */
693 void CoreSessionEventProcessor::processIrcEvent266(IrcEvent *)
695 // TODO: save information in network object
701 Replies 311 - 313, 317 - 319 are all replies generated in response to a WHOIS message.
703 "<nick> :<away message>"
705 Replies 352 and 315 paired are used to answer a WHO message.
708 Replies 314 and 369 are responses to a WHOWAS message.
712 /* RPL_AWAY - "<nick> :<away message>" */
713 void CoreSessionEventProcessor::processIrcEvent301(IrcEvent *e)
715 if (!checkParamCount(e, 2))
718 IrcUser *ircuser = e->network()->ircUser(e->params().at(0));
720 ircuser->setAway(true);
721 ircuser->setAwayMessage(e->params().at(1));
722 //ircuser->setLastAwayMessage(now);
727 /* RPL_UNAWAY - ":You are no longer marked as being away" */
728 void CoreSessionEventProcessor::processIrcEvent305(IrcEvent *e)
730 IrcUser *me = e->network()->me();
734 if (e->network()->autoAwayActive()) {
735 e->network()->setAutoAwayActive(false);
736 e->setFlag(EventManager::Silent);
741 /* RPL_NOWAWAY - ":You have been marked as being away" */
742 void CoreSessionEventProcessor::processIrcEvent306(IrcEvent *e)
744 IrcUser *me = e->network()->me();
750 /* RPL_WHOISSERVICE - "<user> is registered nick" */
751 void CoreSessionEventProcessor::processIrcEvent307(IrcEvent *e)
753 if (!checkParamCount(e, 1))
756 IrcUser *ircuser = e->network()->ircUser(e->params().at(0));
758 ircuser->setWhoisServiceReply(e->params().join(" "));
762 /* RPL_SUSERHOST - "<user> is available for help." */
763 void CoreSessionEventProcessor::processIrcEvent310(IrcEvent *e)
765 if (!checkParamCount(e, 1))
768 IrcUser *ircuser = e->network()->ircUser(e->params().at(0));
770 ircuser->setSuserHost(e->params().join(" "));
774 /* RPL_WHOISUSER - "<nick> <user> <host> * :<real name>" */
775 void CoreSessionEventProcessor::processIrcEvent311(IrcEvent *e)
777 if (!checkParamCount(e, 3))
780 IrcUser *ircuser = e->network()->ircUser(e->params().at(0));
782 ircuser->setUser(e->params().at(1));
783 ircuser->setHost(e->params().at(2));
784 ircuser->setRealName(e->params().last());
789 /* RPL_WHOISSERVER - "<nick> <server> :<server info>" */
790 void CoreSessionEventProcessor::processIrcEvent312(IrcEvent *e)
792 if (!checkParamCount(e, 2))
795 IrcUser *ircuser = e->network()->ircUser(e->params().at(0));
797 ircuser->setServer(e->params().at(1));
801 /* RPL_WHOISOPERATOR - "<nick> :is an IRC operator" */
802 void CoreSessionEventProcessor::processIrcEvent313(IrcEvent *e)
804 if (!checkParamCount(e, 1))
807 IrcUser *ircuser = e->network()->ircUser(e->params().at(0));
809 ircuser->setIrcOperator(e->params().last());
813 /* RPL_ENDOFWHO: "<name> :End of WHO list" */
814 void CoreSessionEventProcessor::processIrcEvent315(IrcEvent *e)
816 if (!checkParamCount(e, 1))
819 if (coreNetwork(e)->setAutoWhoDone(e->params()[0]))
820 e->setFlag(EventManager::Silent);
824 /* RPL_WHOISIDLE - "<nick> <integer> :seconds idle"
825 (real life: "<nick> <integer> <integer> :seconds idle, signon time) */
826 void CoreSessionEventProcessor::processIrcEvent317(IrcEvent *e)
828 if (!checkParamCount(e, 2))
833 int idleSecs = e->params()[1].toInt();
834 if (e->params().count() > 3) { // if we have more then 3 params we have the above mentioned "real life" situation
835 int logintime = e->params()[2].toInt();
836 loginTime = QDateTime::fromTime_t(logintime);
839 IrcUser *ircuser = e->network()->ircUser(e->params()[0]);
841 ircuser->setIdleTime(e->timestamp().addSecs(-idleSecs));
842 if (loginTime.isValid())
843 ircuser->setLoginTime(loginTime);
848 /* RPL_LIST - "<channel> <# visible> :<topic>" */
849 void CoreSessionEventProcessor::processIrcEvent322(IrcEvent *e)
851 if (!checkParamCount(e, 1))
855 quint32 userCount = 0;
858 switch (e->params().count()) {
860 topic = e->params()[2];
862 userCount = e->params()[1].toUInt();
864 channelName = e->params()[0];
868 if (coreSession()->ircListHelper()->addChannel(e->networkId(), channelName, userCount, topic))
869 e->stop(); // consumed by IrcListHelper, so don't further process/show this event
873 /* RPL_LISTEND ":End of LIST" */
874 void CoreSessionEventProcessor::processIrcEvent323(IrcEvent *e)
876 if (!checkParamCount(e, 1))
879 if (coreSession()->ircListHelper()->endOfChannelList(e->networkId()))
880 e->stop(); // consumed by IrcListHelper, so don't further process/show this event
884 /* RPL_CHANNELMODEIS - "<channel> <mode> <mode params>" */
885 void CoreSessionEventProcessor::processIrcEvent324(IrcEvent *e)
887 processIrcEventMode(e);
891 /* RPL_WHOISACCOUNT - "<nick> <account> :is authed as" */
892 void CoreSessionEventProcessor::processIrcEvent330(IrcEvent *e)
894 // Though the ":is authed as" remark should always be there, we should handle cases when it's
895 // not included, too.
896 if (!checkParamCount(e, 2))
899 IrcUser *ircuser = e->network()->ircUser(e->params().at(0));
901 ircuser->setAccount(e->params().at(1));
907 void CoreSessionEventProcessor::processIrcEvent331(IrcEvent *e)
909 if (!checkParamCount(e, 1))
912 IrcChannel *chan = e->network()->ircChannel(e->params()[0]);
914 chan->setTopic(QString());
919 void CoreSessionEventProcessor::processIrcEvent332(IrcEvent *e)
921 if (!checkParamCount(e, 2))
924 IrcChannel *chan = e->network()->ircChannel(e->params()[0]);
926 chan->setTopic(e->params()[1]);
930 /* RPL_WHOREPLY: "<channel> <user> <host> <server> <nick>
931 ( "H" / "G" > ["*"] [ ( "@" / "+" ) ] :<hopcount> <real name>" */
932 void CoreSessionEventProcessor::processIrcEvent352(IrcEvent *e)
934 if (!checkParamCount(e, 6))
937 QString channel = e->params()[0];
938 IrcUser *ircuser = e->network()->ircUser(e->params()[4]);
940 processWhoInformation(e->network(), channel, ircuser, e->params()[3], e->params()[1],
941 e->params()[2], e->params()[5], e->params().last().section(" ", 1));
944 // Check if channel name has a who in progress.
945 // If not, then check if user nick exists and has a who in progress.
946 if (coreNetwork(e)->isAutoWhoInProgress(channel) ||
947 (ircuser && coreNetwork(e)->isAutoWhoInProgress(ircuser->nick()))) {
948 e->setFlag(EventManager::Silent);
954 void CoreSessionEventProcessor::processIrcEvent353(IrcEvent *e)
956 if (!checkParamCount(e, 3))
959 // param[0] is either "=", "*" or "@" indicating a public, private or secret channel
960 // we don't use this information at the time beeing
961 QString channelname = e->params()[1];
963 IrcChannel *channel = e->network()->ircChannel(channelname);
965 qWarning() << Q_FUNC_INFO << "Received unknown target channel:" << channelname;
972 // Cache result of multi-prefix to avoid unneeded casts and lookups with each iteration.
973 bool _useCapMultiPrefix = coreNetwork(e)->capEnabled(IrcCap::MULTI_PREFIX);
975 foreach(QString nick, e->params()[2].split(' ', QString::SkipEmptyParts)) {
978 if (_useCapMultiPrefix) {
979 // If multi-prefix is enabled, all modes will be sent in NAMES replies.
980 // :hades.arpa 353 guest = #tethys :~&@%+aji &@Attila @+alyx +KindOne Argure
981 // See: http://ircv3.net/specs/extensions/multi-prefix-3.1.html
982 while (e->network()->prefixes().contains(nick[0])) {
983 // Mode found in 1 left-most character, add it to the list.
984 // Note: sending multiple modes may cause a warning in older clients.
985 // In testing, the clients still seemed to function fine.
986 mode.append(e->network()->prefixToMode(nick[0]));
987 // Remove this mode from the nick
988 nick = nick.remove(0, 1);
990 } else if (e->network()->prefixes().contains(nick[0])) {
991 // Multi-prefix is disabled and a mode prefix was found.
992 mode = e->network()->prefixToMode(nick[0]);
996 // If userhost-in-names capability is enabled, the following will be
997 // in the form "nick!user@host" rather than "nick". This works without
998 // special handling as the following use nickFromHost() as needed.
999 // See: http://ircv3.net/specs/extensions/userhost-in-names-3.2.html
1005 channel->joinIrcUsers(nicks, modes);
1009 /* RPL_WHOSPCRPL: "<yournick> 152 #<channel> ~<ident> <host> <servname> <nick>
1010 ("H"/ "G") <account> :<realname>"
1011 <channel> is * if not specific to any channel
1012 <account> is * if not logged in
1013 Follows HexChat's usage of 'whox'
1014 See https://github.com/hexchat/hexchat/blob/c874a9525c9b66f1d5ddcf6c4107d046eba7e2c5/src/common/proto-irc.c#L750
1015 And http://faerion.sourceforge.net/doc/irc/whox.var*/
1016 void CoreSessionEventProcessor::processIrcEvent354(IrcEvent *e)
1018 // First only check if at least one parameter exists. Otherwise, it'll stop the result from
1019 // being shown if the user chooses different parameters.
1020 if (!checkParamCount(e, 1))
1023 if (e->params()[0].toUInt() != IrcCap::ACCOUNT_NOTIFY_WHOX_NUM) {
1024 // Ignore WHOX replies without expected number for we have no idea what fields are specified
1028 // Now we're fairly certain this is supposed to be an automated WHOX. Bail out if it doesn't
1029 // match what we require - 9 parameters.
1030 if (!checkParamCount(e, 9))
1033 QString channel = e->params()[1];
1034 IrcUser *ircuser = e->network()->ircUser(e->params()[5]);
1036 processWhoInformation(e->network(), channel, ircuser, e->params()[4], e->params()[2],
1037 e->params()[3], e->params()[6], e->params().last());
1038 // Don't use .section(" ", 1) with WHOX replies, for there's no hopcount to trim out
1040 // As part of IRCv3 account-notify, check account name
1041 // WHOX uses '0' to indicate logged-out, account-notify and extended-join uses '*'.
1042 QString newAccount = e->params()[7];
1043 if (newAccount != "0") {
1044 // Account logged in, set account name
1045 ircuser->setAccount(newAccount);
1047 // Account logged out, set account name to logged-out
1048 ircuser->setAccount("*");
1052 // Check if channel name has a who in progress.
1053 // If not, then check if user nick exists and has a who in progress.
1054 if (coreNetwork(e)->isAutoWhoInProgress(channel) ||
1055 (ircuser && coreNetwork(e)->isAutoWhoInProgress(ircuser->nick()))) {
1056 e->setFlag(EventManager::Silent);
1061 void CoreSessionEventProcessor::processWhoInformation (Network *net, const QString &targetChannel, IrcUser *ircUser,
1062 const QString &server, const QString &user, const QString &host,
1063 const QString &awayStateAndModes, const QString &realname)
1065 ircUser->setUser(user);
1066 ircUser->setHost(host);
1067 ircUser->setServer(server);
1068 ircUser->setRealName(realname);
1070 bool away = awayStateAndModes.contains("G", Qt::CaseInsensitive);
1071 ircUser->setAway(away);
1073 if (net->capEnabled(IrcCap::MULTI_PREFIX)) {
1074 // If multi-prefix is enabled, all modes will be sent in WHO replies.
1075 // :kenny.chatspike.net 352 guest #test grawity broken.symlink *.chatspike.net grawity H@%+ :0 Mantas M.
1076 // See: http://ircv3.net/specs/extensions/multi-prefix-3.1.html
1077 QString uncheckedModes = awayStateAndModes;
1078 QString validModes = QString();
1079 while (!uncheckedModes.isEmpty()) {
1080 // Mode found in 1 left-most character, add it to the list
1081 if (net->prefixes().contains(uncheckedModes[0])) {
1082 validModes.append(net->prefixToMode(uncheckedModes[0]));
1084 // Remove this mode from the list of unchecked modes
1085 uncheckedModes = uncheckedModes.remove(0, 1);
1088 // Some IRC servers decide to not follow the spec, returning only -some- of the user
1089 // modes in WHO despite listing them all in NAMES. For now, assume it can only add
1090 // and not take away. *sigh*
1091 if (!validModes.isEmpty()) {
1092 if (targetChannel != "*") {
1093 // Channel-specific modes received, apply to given channel only
1094 IrcChannel *ircChan = net->ircChannel(targetChannel);
1096 // Do one mode at a time
1097 // TODO Better way of syncing this without breaking protocol?
1098 for (int i = 0; i < validModes.count(); ++i) {
1099 ircChan->addUserMode(ircUser, validModes.at(i));
1103 // Modes apply to the user everywhere
1104 ircUser->addUserModes(validModes);
1111 /* ERR_NOSUCHCHANNEL - "<channel name> :No such channel" */
1112 void CoreSessionEventProcessor::processIrcEvent403(IrcEventNumeric *e)
1114 // If this is the result of an AutoWho, hide it. It's confusing to show to the user.
1115 // Though the ":No such channel" remark should always be there, we should handle cases when it's
1116 // not included, too.
1117 if (!checkParamCount(e, 1))
1120 QString channelOrNick = e->params()[0];
1121 // Check if channel name has a who in progress.
1122 // If not, then check if user nick exists and has a who in progress.
1123 if (coreNetwork(e)->isAutoWhoInProgress(channelOrNick)) {
1124 qDebug() << "Channel/nick" << channelOrNick << "no longer exists during AutoWho, ignoring";
1125 e->setFlag(EventManager::Silent);
1129 /* ERR_ERRONEUSNICKNAME */
1130 void CoreSessionEventProcessor::processIrcEvent432(IrcEventNumeric *e)
1132 if (!checkParamCount(e, 1))
1136 if (e->params().count() < 2) {
1137 // handle unreal-ircd bug, where unreal ircd doesnt supply a TARGET in ERR_ERRONEUSNICKNAME during registration phase:
1139 // :irc.scortum.moep.net 432 @@@ :Erroneous Nickname: Illegal characters
1140 // correct server reply:
1141 // :irc.scortum.moep.net 432 * @@@ :Erroneous Nickname: Illegal characters
1142 e->params().prepend(e->target());
1145 errnick = e->params()[0];
1147 tryNextNick(e, errnick, true /* erroneus */);
1151 /* ERR_NICKNAMEINUSE */
1152 void CoreSessionEventProcessor::processIrcEvent433(IrcEventNumeric *e)
1154 if (!checkParamCount(e, 1))
1157 QString errnick = e->params().first();
1159 // if there is a problem while connecting to the server -> we handle it
1160 // but only if our connection has not been finished yet...
1161 if (!e->network()->currentServer().isEmpty())
1164 tryNextNick(e, errnick);
1168 /* ERR_UNAVAILRESOURCE */
1169 void CoreSessionEventProcessor::processIrcEvent437(IrcEventNumeric *e)
1171 if (!checkParamCount(e, 1))
1174 QString errnick = e->params().first();
1176 // if there is a problem while connecting to the server -> we handle it
1177 // but only if our connection has not been finished yet...
1178 if (!e->network()->currentServer().isEmpty())
1181 if (!e->network()->isChannelName(errnick))
1182 tryNextNick(e, errnick);
1187 void CoreSessionEventProcessor::processIrcEvent(IrcEvent *e) {
1188 if(!checkParamCount(e, 1))
1194 /* Handle signals from Netsplit objects */
1196 void CoreSessionEventProcessor::handleNetsplitJoin(Network *net,
1197 const QString &channel,
1198 const QStringList &users,
1199 const QStringList &modes,
1200 const QString &quitMessage)
1202 IrcChannel *ircChannel = net->ircChannel(channel);
1206 QList<IrcUser *> ircUsers;
1207 QStringList newModes = modes;
1208 QStringList newUsers = users;
1210 foreach(const QString &user, users) {
1211 IrcUser *iu = net->ircUser(nickFromMask(user));
1213 ircUsers.append(iu);
1214 else { // the user already quit
1215 int idx = users.indexOf(user);
1216 newUsers.removeAt(idx);
1217 newModes.removeAt(idx);
1221 ircChannel->joinIrcUsers(ircUsers, newModes);
1222 NetworkSplitEvent *event = new NetworkSplitEvent(EventManager::NetworkSplitJoin, net, channel, newUsers, quitMessage);
1223 emit newEvent(event);
1227 void CoreSessionEventProcessor::handleNetsplitQuit(Network *net, const QString &channel, const QStringList &users, const QString &quitMessage)
1229 NetworkSplitEvent *event = new NetworkSplitEvent(EventManager::NetworkSplitQuit, net, channel, users, quitMessage);
1230 emit newEvent(event);
1231 foreach(QString user, users) {
1232 IrcUser *iu = net->ircUser(nickFromMask(user));
1239 void CoreSessionEventProcessor::handleEarlyNetsplitJoin(Network *net, const QString &channel, const QStringList &users, const QStringList &modes)
1241 IrcChannel *ircChannel = net->ircChannel(channel);
1243 qDebug() << "handleEarlyNetsplitJoin(): channel " << channel << " invalid";
1246 QList<NetworkEvent *> events;
1247 QList<IrcUser *> ircUsers;
1248 QStringList newModes = modes;
1250 foreach(QString user, users) {
1251 IrcUser *iu = net->updateNickFromMask(user);
1253 ircUsers.append(iu);
1254 // fake event for scripts that consume join events
1255 events << new IrcEvent(EventManager::IrcEventJoin, net, iu->hostmask(), QStringList() << channel);
1258 newModes.removeAt(users.indexOf(user));
1261 ircChannel->joinIrcUsers(ircUsers, newModes);
1262 foreach(NetworkEvent *event, events) {
1263 event->setFlag(EventManager::Fake); // ignore this in here!
1264 emit newEvent(event);
1269 void CoreSessionEventProcessor::handleNetsplitFinished()
1271 Netsplit *n = qobject_cast<Netsplit *>(sender());
1273 QHash<QString, Netsplit *> splithash = _netsplits.take(n->network());
1274 splithash.remove(splithash.key(n));
1275 if (splithash.count())
1276 _netsplits[n->network()] = splithash;
1281 void CoreSessionEventProcessor::destroyNetsplits(NetworkId netId)
1283 Network *net = coreSession()->network(netId);
1287 QHash<QString, Netsplit *> splits = _netsplits.take(net);
1292 /*******************************/
1293 /******** CTCP HANDLING ********/
1294 /*******************************/
1296 void CoreSessionEventProcessor::processCtcpEvent(CtcpEvent *e)
1298 if (e->testFlag(EventManager::Self))
1299 return; // ignore ctcp events generated by user input
1301 if (e->type() != EventManager::CtcpEvent || e->ctcpType() != CtcpEvent::Query)
1304 handle(e->ctcpCmd(), Q_ARG(CtcpEvent *, e));
1308 void CoreSessionEventProcessor::defaultHandler(const QString &ctcpCmd, CtcpEvent *e)
1310 // This handler is only there to avoid warnings for unknown CTCPs
1316 void CoreSessionEventProcessor::handleCtcpAction(CtcpEvent *e)
1318 // This handler is only there to feed CLIENTINFO
1323 void CoreSessionEventProcessor::handleCtcpClientinfo(CtcpEvent *e)
1325 QStringList supportedHandlers;
1326 foreach(QString handler, providesHandlers())
1327 supportedHandlers << handler.toUpper();
1328 qSort(supportedHandlers);
1329 e->setReply(supportedHandlers.join(" "));
1333 // http://www.irchelp.org/irchelp/rfc/ctcpspec.html
1334 // http://en.wikipedia.org/wiki/Direct_Client-to-Client
1335 void CoreSessionEventProcessor::handleCtcpDcc(CtcpEvent *e)
1337 // DCC support is unfinished, experimental and potentially dangerous, so make it opt-in
1338 if (!Quassel::isOptionSet("enable-experimental-dcc")) {
1339 quInfo() << "DCC disabled, start core with --enable-experimental-dcc if you really want to try it out";
1343 // normal: SEND <filename> <ip> <port> [<filesize>]
1344 // reverse: SEND <filename> <ip> 0 <filesize> <token>
1345 QStringList params = e->param().split(' ');
1346 if (params.count()) {
1347 QString cmd = params[0].toUpper();
1348 if (cmd == "SEND") {
1349 if (params.count() < 4) {
1350 qWarning() << "Invalid DCC SEND request:" << e; // TODO emit proper error to client
1353 QString filename = params[1];
1354 QHostAddress address;
1355 quint16 port = params[3].toUShort();
1357 QString numIp = params[2]; // this is either IPv4 as a 32 bit value, or IPv6 (which always contains a colon)
1358 if (numIp.contains(':')) { // IPv6
1359 if (!address.setAddress(numIp)) {
1360 qWarning() << "Invalid IPv6:" << numIp;
1365 address.setAddress(numIp.toUInt());
1368 if (port == 0) { // Reverse DCC is indicated by a 0 port
1369 emit newEvent(new MessageEvent(Message::Error, e->network(), tr("Reverse DCC SEND not supported"), e->prefix(), e->target(), Message::None, e->timestamp()));
1373 qWarning() << "Privileged port requested:" << port; // FIXME ask user if this is ok
1377 if (params.count() > 4) { // filesize is optional
1378 size = params[4].toULong();
1381 // TODO: check if target is the right thing to use for the partner
1382 CoreTransfer *transfer = new CoreTransfer(Transfer::Direction::Receive, e->target(), filename, address, port, size, this);
1383 coreSession()->signalProxy()->synchronize(transfer);
1384 coreSession()->transferManager()->addTransfer(transfer);
1387 emit newEvent(new MessageEvent(Message::Error, e->network(), tr("DCC %1 not supported").arg(cmd), e->prefix(), e->target(), Message::None, e->timestamp()));
1394 void CoreSessionEventProcessor::handleCtcpPing(CtcpEvent *e)
1396 e->setReply(e->param().isNull() ? "" : e->param());
1400 void CoreSessionEventProcessor::handleCtcpTime(CtcpEvent *e)
1402 e->setReply(QDateTime::currentDateTime().toString());
1406 void CoreSessionEventProcessor::handleCtcpVersion(CtcpEvent *e)
1408 e->setReply(QString("Quassel IRC %1 (built on %2) -- http://www.quassel-irc.org")
1409 .arg(Quassel::buildInfo().plainVersionString).arg(Quassel::buildInfo().commitDate));