Handle IRCv3 servers without any capabilities
[quassel.git] / src / core / coresessioneventprocessor.cpp
1 /***************************************************************************
2  *   Copyright (C) 2005-2016 by the Quassel Project                        *
3  *   devel@quassel-irc.org                                                 *
4  *                                                                         *
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.                                           *
9  *                                                                         *
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.                          *
14  *                                                                         *
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  ***************************************************************************/
20
21 #include "coresessioneventprocessor.h"
22
23 #include "coreirclisthelper.h"
24 #include "corenetwork.h"
25 #include "coresession.h"
26 #include "coretransfer.h"
27 #include "coretransfermanager.h"
28 #include "ctcpevent.h"
29 #include "ircevent.h"
30 #include "ircuser.h"
31 #include "logger.h"
32 #include "messageevent.h"
33 #include "netsplit.h"
34 #include "quassel.h"
35
36 #ifdef HAVE_QCA2
37 #  include "keyevent.h"
38 #endif
39
40 // IRCv3 capabilities
41 #include "irccap.h"
42
43 CoreSessionEventProcessor::CoreSessionEventProcessor(CoreSession *session)
44     : BasicHandler("handleCtcp", session),
45     _coreSession(session)
46 {
47     connect(coreSession(), SIGNAL(networkDisconnected(NetworkId)), this, SLOT(destroyNetsplits(NetworkId)));
48     connect(this, SIGNAL(newEvent(Event *)), coreSession()->eventManager(), SLOT(postEvent(Event *)));
49 }
50
51
52 bool CoreSessionEventProcessor::checkParamCount(IrcEvent *e, int minParams)
53 {
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();
57         }
58         else {
59             QString name = coreSession()->eventManager()->enumName(e->type());
60             qWarning() << qPrintable(name) << "requires" << minParams << "params, got:" << e->params();
61         }
62         e->stop();
63         return false;
64     }
65     return true;
66 }
67
68
69 void CoreSessionEventProcessor::tryNextNick(NetworkEvent *e, const QString &errnick, bool erroneus)
70 {
71     QStringList desiredNicks = coreSession()->identity(e->network()->identity())->nicks();
72     int nextNickIdx = desiredNicks.indexOf(errnick) + 1;
73     QString nextNick;
74     if (nextNickIdx > 0 && desiredNicks.size() > nextNickIdx) {
75         nextNick = desiredNicks[nextNickIdx];
76     }
77     else {
78         if (erroneus) {
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);
84             return;
85         }
86         else {
87             nextNick = errnick + "_";
88         }
89     }
90     // FIXME Use a proper output event for this
91     coreNetwork(e)->putRawLine("NICK " + coreNetwork(e)->encodeServerString(nextNick));
92 }
93
94
95 void CoreSessionEventProcessor::processIrcEventNumeric(IrcEventNumeric *e)
96 {
97     switch (e->number()) {
98     // SASL authentication replies
99     // See: http://ircv3.net/specs/extensions/sasl-3.1.html
100
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();
115         break;
116
117     default:
118         break;
119     }
120 }
121
122
123 void CoreSessionEventProcessor::processIrcEventAuthenticate(IrcEvent *e)
124 {
125     if (!checkParamCount(e, 1))
126         return;
127
128     if (e->params().at(0) != "+") {
129         qWarning() << "Invalid AUTHENTICATE" << e;
130         return;
131     }
132
133     CoreNetwork *net = coreNetwork(e);
134
135 #ifdef HAVE_SSL
136     if (net->identityPtr()->sslCert().isNull()) {
137 #endif
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);
146 #ifdef HAVE_SSL
147     } else {
148         net->putRawLine("AUTHENTICATE +");
149     }
150 #endif
151 }
152
153 void CoreSessionEventProcessor::processIrcEventCap(IrcEvent *e)
154 {
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
159     // All commands require at least 2 parameters
160     if (!checkParamCount(e, 2))
161         return;
162
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(' ');
177             } else {
178                 // Single line reply
179                 capListFinished = true;
180                 if (e->params().count() >= 3) {
181                     // Some capabilities are specified, add them
182                     availableCaps = e->params().at(2).split(' ');
183                 } else {
184                     // No capabilities available, add an empty list
185                     availableCaps = QStringList();
186                 }
187             }
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);
207                 }
208             }
209
210             // Begin capability requests when capability listing complete
211             if (capListFinished)
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))
216                 return;
217
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();
222
223             // Mark this cap as accepted
224             coreNet->acknowledgeCap(acceptedCap);
225
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();
231             }
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))
235                 return;
236
237             // Either something went wrong with this capability, or it is no longer supported
238             // > For CAP NAK
239             // Server: CAP * NAK :multi-prefix sasl
240             // > For CAP DEL
241             // Server: :irc.example.com CAP modernclient DEL :multi-prefix sasl
242             // CAP NAK and CAP DEL replies are always single-line
243
244             QStringList removedCaps;
245             removedCaps = e->params().at(2).split(' ');
246
247             // Store what capability was denied or removed
248             QString removedCap;
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);
253             }
254
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();
259             }
260         }
261     }
262 }
263
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)
268 {
269     if (!checkParamCount(e, 1))
270         return;
271
272     IrcUser *ircuser = e->network()->updateNickFromMask(e->prefix());
273     if (ircuser) {
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));
277     } else {
278         qDebug() << "Received account-notify data for unknown user" << e->prefix();
279     }
280 }
281
282 /* IRCv3 away-notify - ":nick!user@host AWAY [:message]" */
283 void CoreSessionEventProcessor::processIrcEventAway(IrcEvent *e)
284 {
285     if (!checkParamCount(e, 1))
286         return;
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.
289
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));
292     if (ircuser) {
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));
298         } else {
299             ircuser->setAway(false);
300         }
301     } else {
302         qDebug() << "Received away-notify data for unknown user" << e->params().at(0);
303     }
304 }
305
306 /* IRCv3 chghost - ":nick!user@host CHGHOST newuser new.host.goes.here" */
307 void CoreSessionEventProcessor::processIrcEventChghost(IrcEvent *e)
308 {
309     if (!checkParamCount(e, 2))
310         return;
311
312     IrcUser *ircuser = e->network()->updateNickFromMask(e->prefix());
313     if (ircuser) {
314         // Update with new user/hostname information.  setUser/setHost handles checking what
315         // actually changed.
316         ircuser->setUser(e->params().at(0));
317         ircuser->setHost(e->params().at(1));
318     } else {
319         qDebug() << "Received chghost data for unknown user" << e->prefix();
320     }
321 }
322
323 void CoreSessionEventProcessor::processIrcEventInvite(IrcEvent *e)
324 {
325     if (checkParamCount(e, 2)) {
326         e->network()->updateNickFromMask(e->prefix());
327     }
328 }
329
330 /*  JOIN: ":<nick!user@host> JOIN <channel>" */
331 void CoreSessionEventProcessor::processIrcEventJoin(IrcEvent *e)
332 {
333     if (e->testFlag(EventManager::Fake)) // generated by handleEarlyNetsplitJoin
334         return;
335
336     if (!checkParamCount(e, 1))
337         return;
338
339     CoreNetwork *net = coreNetwork(e);
340     QString channel = e->params()[0];
341     IrcUser *ircuser = net->updateNickFromMask(e->prefix());
342
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 "
349                         "regular join";
350         } else {
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]);
359         }
360     }
361     // Else :nick!user@host JOIN #channelname
362
363     bool handledByNetsplit = false;
364     foreach(Netsplit* n, _netsplits.value(e->network())) {
365         handledByNetsplit = n->userJoined(e->prefix(), channel);
366         if (handledByNetsplit)
367             break;
368     }
369
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());
374     }
375
376     if (!handledByNetsplit)
377         ircuser->joinChannel(channel);
378     else
379         e->setFlag(EventManager::Netsplit);
380
381     if (net->isMe(ircuser)) {
382         net->setChannelJoined(channel);
383         // FIXME use event
384         net->putRawLine(net->serverEncode("MODE " + channel)); // we want to know the modes of the channel we just joined, so we ask politely
385     }
386 }
387
388
389 void CoreSessionEventProcessor::lateProcessIrcEventKick(IrcEvent *e)
390 {
391     if (checkParamCount(e, 2)) {
392         e->network()->updateNickFromMask(e->prefix());
393         IrcUser *victim = e->network()->ircUser(e->params().at(1));
394         if (victim) {
395             victim->partChannel(e->params().at(0));
396             //if(e->network()->isMe(victim)) e->network()->setKickedFromChannel(channel);
397         }
398     }
399 }
400
401
402 void CoreSessionEventProcessor::processIrcEventMode(IrcEvent *e)
403 {
404     if (!checkParamCount(e, 2))
405         return;
406
407     if (e->network()->isChannelName(e->params().first())) {
408         // Channel Modes
409
410         IrcChannel *channel = e->network()->ircChannel(e->params()[0]);
411         if (!channel) {
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.
414             return;
415         }
416
417         QString modes = e->params()[1];
418         bool add = true;
419         int paramOffset = 2;
420         for (int c = 0; c < modes.length(); c++) {
421             if (modes[c] == '+') {
422                 add = true;
423                 continue;
424             }
425             if (modes[c] == '-') {
426                 add = false;
427                 continue;
428             }
429
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]);
434                     if (!ircUser) {
435                         qWarning() << Q_FUNC_INFO << "Unknown IrcUser:" << e->params()[paramOffset];
436                     }
437                     else {
438                         if (add) {
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]));
445                                     break;
446                                 }
447                             }
448                             if (!handledByNetsplit)
449                                 channel->addUserMode(ircUser, QString(modes[c]));
450                         }
451                         else
452                             channel->removeUserMode(ircUser, QString(modes[c]));
453                     }
454                 }
455                 else {
456                     qWarning() << "Received MODE with too few parameters:" << e->params();
457                 }
458                 ++paramOffset;
459             }
460             else {
461                 // regular channel modes
462                 QString value;
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];
467                     }
468                     else {
469                         qWarning() << "Received MODE with too few parameters:" << e->params();
470                     }
471                     ++paramOffset;
472                 }
473
474                 if (add)
475                     channel->addChannelMode(modes[c], value);
476                 else
477                     channel->removeChannelMode(modes[c], value);
478             }
479         }
480     }
481     else {
482         // pure User Modes
483         IrcUser *ircUser = e->network()->newIrcUser(e->params().first());
484         QString modeString(e->params()[1]);
485         QString addModes;
486         QString removeModes;
487         bool add = false;
488         for (int c = 0; c < modeString.count(); c++) {
489             if (modeString[c] == '+') {
490                 add = true;
491                 continue;
492             }
493             if (modeString[c] == '-') {
494                 add = false;
495                 continue;
496             }
497             if (add)
498                 addModes += modeString[c];
499             else
500                 removeModes += modeString[c];
501         }
502         if (!addModes.isEmpty())
503             ircUser->addUserModes(addModes);
504         if (!removeModes.isEmpty())
505             ircUser->removeUserModes(removeModes);
506
507         if (e->network()->isMe(ircUser)) {
508             coreNetwork(e)->updatePersistentModes(addModes, removeModes);
509         }
510     }
511 }
512
513
514 void CoreSessionEventProcessor::lateProcessIrcEventNick(IrcEvent *e)
515 {
516     if (checkParamCount(e, 1)) {
517         IrcUser *ircuser = e->network()->updateNickFromMask(e->prefix());
518         if (!ircuser) {
519             qWarning() << Q_FUNC_INFO << "Unknown IrcUser!";
520             return;
521         }
522         QString newnick = e->params().at(0);
523         QString oldnick = ircuser->nick();
524
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);
530     }
531 }
532
533
534 void CoreSessionEventProcessor::lateProcessIrcEventPart(IrcEvent *e)
535 {
536     if (checkParamCount(e, 1)) {
537         IrcUser *ircuser = e->network()->updateNickFromMask(e->prefix());
538         if (!ircuser) {
539             qWarning() << Q_FUNC_INFO<< "Unknown IrcUser!";
540             return;
541         }
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);
546     }
547 }
548
549
550 void CoreSessionEventProcessor::processIrcEventPing(IrcEvent *e)
551 {
552     QString param = e->params().count() ? e->params().first() : QString();
553     // FIXME use events
554     // Take priority so this won't get stuck behind other queued messages.
555     coreNetwork(e)->putRawLine("PONG " + coreNetwork(e)->serverEncode(param), true);
556 }
557
558
559 void CoreSessionEventProcessor::processIrcEventPong(IrcEvent *e)
560 {
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);
568     }
569 }
570
571
572 void CoreSessionEventProcessor::processIrcEventQuit(IrcEvent *e)
573 {
574     IrcUser *ircuser = e->network()->updateNickFromMask(e->prefix());
575     if (!ircuser)
576         return;
577
578     QString msg;
579     if (e->params().count() > 0)
580         msg = e->params()[0];
581
582     // check if netsplit
583     if (Netsplit::isNetsplit(msg)) {
584         Netsplit *n;
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);
595         }
596         else {
597             n = _netsplits[e->network()][msg];
598         }
599         // add this user to the netsplit
600         n->userQuit(e->prefix(), ircuser->channels(), msg);
601         e->setFlag(EventManager::Netsplit);
602     }
603     // normal quit is handled in lateProcessIrcEventQuit()
604 }
605
606
607 void CoreSessionEventProcessor::lateProcessIrcEventQuit(IrcEvent *e)
608 {
609     if (e->testFlag(EventManager::Netsplit))
610         return;
611
612     IrcUser *ircuser = e->network()->updateNickFromMask(e->prefix());
613     if (!ircuser)
614         return;
615
616     ircuser->quit();
617 }
618
619
620 void CoreSessionEventProcessor::processIrcEventTopic(IrcEvent *e)
621 {
622     if (checkParamCount(e, 2)) {
623         e->network()->updateNickFromMask(e->prefix());
624         IrcChannel *channel = e->network()->ircChannel(e->params().at(0));
625         if (channel)
626             channel->setTopic(e->params().at(1));
627     }
628 }
629
630
631 #ifdef HAVE_QCA2
632 void CoreSessionEventProcessor::processKeyEvent(KeyEvent *e)
633 {
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()));
636         return;
637     }
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?)
641         return;
642
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()));
647             return;
648         } else {
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()));
651             QList<QByteArray> p;
652             p << net->serverEncode(e->target()) << net->serverEncode("DH1080_FINISH ")+pubKey;
653             net->putCmd("NOTICE", p);
654         }
655     } else {
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()));
659         } else {
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()));
661         }
662     }
663 }
664 #endif
665
666
667 /* RPL_WELCOME */
668 void CoreSessionEventProcessor::processIrcEvent001(IrcEventNumeric *e)
669 {
670     e->network()->setCurrentServer(e->prefix());
671     e->network()->setMyNick(e->target());
672 }
673
674
675 /* RPL_ISUPPORT */
676 // TODO Complete 005 handling, also use sensible defaults for non-sent stuff
677 void CoreSessionEventProcessor::processIrcEvent005(IrcEvent *e)
678 {
679     if (!checkParamCount(e, 1))
680         return;
681
682     QString key, value;
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);
687     }
688
689     /* determine our prefixes here to get an accurate result */
690     e->network()->determinePrefixes();
691 }
692
693
694 /* RPL_UMODEIS - "<user_modes> [<user_mode_params>]" */
695 void CoreSessionEventProcessor::processIrcEvent221(IrcEvent *)
696 {
697     // TODO: save information in network object
698 }
699
700
701 /* RPL_STATSCONN - "Highest connection cout: 8000 (7999 clients)" */
702 void CoreSessionEventProcessor::processIrcEvent250(IrcEvent *)
703 {
704     // TODO: save information in network object
705 }
706
707
708 /* RPL_LOCALUSERS - "Current local user: 5024  Max: 7999 */
709 void CoreSessionEventProcessor::processIrcEvent265(IrcEvent *)
710 {
711     // TODO: save information in network object
712 }
713
714
715 /* RPL_GLOBALUSERS - "Current global users: 46093  Max: 47650" */
716 void CoreSessionEventProcessor::processIrcEvent266(IrcEvent *)
717 {
718     // TODO: save information in network object
719 }
720
721
722 /*
723 WHOIS-Message:
724    Replies 311 - 313, 317 - 319 are all replies generated in response to a WHOIS message.
725   and 301 (RPL_AWAY)
726               "<nick> :<away message>"
727 WHO-Message:
728    Replies 352 and 315 paired are used to answer a WHO message.
729
730 WHOWAS-Message:
731    Replies 314 and 369 are responses to a WHOWAS message.
732
733 */
734
735 /* RPL_AWAY - "<nick> :<away message>" */
736 void CoreSessionEventProcessor::processIrcEvent301(IrcEvent *e)
737 {
738     if (!checkParamCount(e, 2))
739         return;
740
741     IrcUser *ircuser = e->network()->ircUser(e->params().at(0));
742     if (ircuser) {
743         ircuser->setAway(true);
744         ircuser->setAwayMessage(e->params().at(1));
745         //ircuser->setLastAwayMessage(now);
746     }
747 }
748
749
750 /* RPL_UNAWAY - ":You are no longer marked as being away" */
751 void CoreSessionEventProcessor::processIrcEvent305(IrcEvent *e)
752 {
753     IrcUser *me = e->network()->me();
754     if (me)
755         me->setAway(false);
756
757     if (e->network()->autoAwayActive()) {
758         e->network()->setAutoAwayActive(false);
759         e->setFlag(EventManager::Silent);
760     }
761 }
762
763
764 /* RPL_NOWAWAY - ":You have been marked as being away" */
765 void CoreSessionEventProcessor::processIrcEvent306(IrcEvent *e)
766 {
767     IrcUser *me = e->network()->me();
768     if (me)
769         me->setAway(true);
770 }
771
772
773 /* RPL_WHOISSERVICE - "<user> is registered nick" */
774 void CoreSessionEventProcessor::processIrcEvent307(IrcEvent *e)
775 {
776     if (!checkParamCount(e, 1))
777         return;
778
779     IrcUser *ircuser = e->network()->ircUser(e->params().at(0));
780     if (ircuser)
781         ircuser->setWhoisServiceReply(e->params().join(" "));
782 }
783
784
785 /* RPL_SUSERHOST - "<user> is available for help." */
786 void CoreSessionEventProcessor::processIrcEvent310(IrcEvent *e)
787 {
788     if (!checkParamCount(e, 1))
789         return;
790
791     IrcUser *ircuser = e->network()->ircUser(e->params().at(0));
792     if (ircuser)
793         ircuser->setSuserHost(e->params().join(" "));
794 }
795
796
797 /*  RPL_WHOISUSER - "<nick> <user> <host> * :<real name>" */
798 void CoreSessionEventProcessor::processIrcEvent311(IrcEvent *e)
799 {
800     if (!checkParamCount(e, 3))
801         return;
802
803     IrcUser *ircuser = e->network()->ircUser(e->params().at(0));
804     if (ircuser) {
805         ircuser->setUser(e->params().at(1));
806         ircuser->setHost(e->params().at(2));
807         ircuser->setRealName(e->params().last());
808     }
809 }
810
811
812 /*  RPL_WHOISSERVER -  "<nick> <server> :<server info>" */
813 void CoreSessionEventProcessor::processIrcEvent312(IrcEvent *e)
814 {
815     if (!checkParamCount(e, 2))
816         return;
817
818     IrcUser *ircuser = e->network()->ircUser(e->params().at(0));
819     if (ircuser)
820         ircuser->setServer(e->params().at(1));
821 }
822
823
824 /*  RPL_WHOISOPERATOR - "<nick> :is an IRC operator" */
825 void CoreSessionEventProcessor::processIrcEvent313(IrcEvent *e)
826 {
827     if (!checkParamCount(e, 1))
828         return;
829
830     IrcUser *ircuser = e->network()->ircUser(e->params().at(0));
831     if (ircuser)
832         ircuser->setIrcOperator(e->params().last());
833 }
834
835
836 /*  RPL_ENDOFWHO: "<name> :End of WHO list" */
837 void CoreSessionEventProcessor::processIrcEvent315(IrcEvent *e)
838 {
839     if (!checkParamCount(e, 1))
840         return;
841
842     if (coreNetwork(e)->setAutoWhoDone(e->params()[0]))
843         e->setFlag(EventManager::Silent);
844 }
845
846
847 /*  RPL_WHOISIDLE - "<nick> <integer> :seconds idle"
848    (real life: "<nick> <integer> <integer> :seconds idle, signon time) */
849 void CoreSessionEventProcessor::processIrcEvent317(IrcEvent *e)
850 {
851     if (!checkParamCount(e, 2))
852         return;
853
854     QDateTime loginTime;
855
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);
860     }
861
862     IrcUser *ircuser = e->network()->ircUser(e->params()[0]);
863     if (ircuser) {
864         ircuser->setIdleTime(e->timestamp().addSecs(-idleSecs));
865         if (loginTime.isValid())
866             ircuser->setLoginTime(loginTime);
867     }
868 }
869
870
871 /* RPL_LIST -  "<channel> <# visible> :<topic>" */
872 void CoreSessionEventProcessor::processIrcEvent322(IrcEvent *e)
873 {
874     if (!checkParamCount(e, 1))
875         return;
876
877     QString channelName;
878     quint32 userCount = 0;
879     QString topic;
880
881     switch (e->params().count()) {
882     case 3:
883         topic = e->params()[2];
884     case 2:
885         userCount = e->params()[1].toUInt();
886     case 1:
887         channelName = e->params()[0];
888     default:
889         break;
890     }
891     if (coreSession()->ircListHelper()->addChannel(e->networkId(), channelName, userCount, topic))
892         e->stop();  // consumed by IrcListHelper, so don't further process/show this event
893 }
894
895
896 /* RPL_LISTEND ":End of LIST" */
897 void CoreSessionEventProcessor::processIrcEvent323(IrcEvent *e)
898 {
899     if (!checkParamCount(e, 1))
900         return;
901
902     if (coreSession()->ircListHelper()->endOfChannelList(e->networkId()))
903         e->stop();  // consumed by IrcListHelper, so don't further process/show this event
904 }
905
906
907 /* RPL_CHANNELMODEIS - "<channel> <mode> <mode params>" */
908 void CoreSessionEventProcessor::processIrcEvent324(IrcEvent *e)
909 {
910     processIrcEventMode(e);
911 }
912
913
914 /*  RPL_WHOISACCOUNT - "<nick> <account> :is authed as" */
915 void CoreSessionEventProcessor::processIrcEvent330(IrcEvent *e)
916 {
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))
920         return;
921
922     IrcUser *ircuser = e->network()->ircUser(e->params().at(0));
923     if (ircuser) {
924         ircuser->setAccount(e->params().at(1));
925     }
926 }
927
928
929 /* RPL_NOTOPIC */
930 void CoreSessionEventProcessor::processIrcEvent331(IrcEvent *e)
931 {
932     if (!checkParamCount(e, 1))
933         return;
934
935     IrcChannel *chan = e->network()->ircChannel(e->params()[0]);
936     if (chan)
937         chan->setTopic(QString());
938 }
939
940
941 /* RPL_TOPIC */
942 void CoreSessionEventProcessor::processIrcEvent332(IrcEvent *e)
943 {
944     if (!checkParamCount(e, 2))
945         return;
946
947     IrcChannel *chan = e->network()->ircChannel(e->params()[0]);
948     if (chan)
949         chan->setTopic(e->params()[1]);
950 }
951
952
953 /*  RPL_WHOREPLY: "<channel> <user> <host> <server> <nick>
954               ( "H" / "G" > ["*"] [ ( "@" / "+" ) ] :<hopcount> <real name>" */
955 void CoreSessionEventProcessor::processIrcEvent352(IrcEvent *e)
956 {
957     if (!checkParamCount(e, 6))
958         return;
959
960     QString channel = e->params()[0];
961     IrcUser *ircuser = e->network()->ircUser(e->params()[4]);
962     if (ircuser) {
963         processWhoInformation(e->network(), channel, ircuser, e->params()[3], e->params()[1],
964                 e->params()[2], e->params()[5], e->params().last().section(" ", 1));
965     }
966
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);
972     }
973 }
974
975
976 /* RPL_NAMREPLY */
977 void CoreSessionEventProcessor::processIrcEvent353(IrcEvent *e)
978 {
979     if (!checkParamCount(e, 3))
980         return;
981
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];
985
986     IrcChannel *channel = e->network()->ircChannel(channelname);
987     if (!channel) {
988         qWarning() << Q_FUNC_INFO << "Received unknown target channel:" << channelname;
989         return;
990     }
991
992     QStringList nicks;
993     QStringList modes;
994
995     // Cache result of multi-prefix to avoid unneeded casts and lookups with each iteration.
996     bool _useCapMultiPrefix = coreNetwork(e)->capEnabled(IrcCap::MULTI_PREFIX);
997
998     foreach(QString nick, e->params()[2].split(' ', QString::SkipEmptyParts)) {
999         QString mode;
1000
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);
1012             }
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]);
1016             nick = nick.mid(1);
1017         }
1018
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
1023
1024         nicks << nick;
1025         modes << mode;
1026     }
1027
1028     channel->joinIrcUsers(nicks, modes);
1029 }
1030
1031
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)
1040 {
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))
1044         return;
1045
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
1048         return;
1049     }
1050
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))
1054         return;
1055
1056     QString channel = e->params()[1];
1057     IrcUser *ircuser = e->network()->ircUser(e->params()[5]);
1058     if (ircuser) {
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
1062
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);
1069         } else {
1070             // Account logged out, set account name to logged-out
1071             ircuser->setAccount("*");
1072         }
1073     }
1074
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);
1080     }
1081 }
1082
1083
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)
1087 {
1088     ircUser->setUser(user);
1089     ircUser->setHost(host);
1090     ircUser->setServer(server);
1091     ircUser->setRealName(realname);
1092
1093     bool away = awayStateAndModes.contains("G", Qt::CaseInsensitive);
1094     ircUser->setAway(away);
1095
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]));
1106             }
1107             // Remove this mode from the list of unchecked modes
1108             uncheckedModes = uncheckedModes.remove(0, 1);
1109         }
1110
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);
1118                 if (ircChan) {
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));
1123                     }
1124                 }
1125             } else {
1126                 // Modes apply to the user everywhere
1127                 ircUser->addUserModes(validModes);
1128             }
1129         }
1130     }
1131 }
1132
1133
1134 /* ERR_NOSUCHCHANNEL - "<channel name> :No such channel" */
1135 void CoreSessionEventProcessor::processIrcEvent403(IrcEventNumeric *e)
1136 {
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))
1141         return;
1142
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);
1149     }
1150 }
1151
1152 /* ERR_ERRONEUSNICKNAME */
1153 void CoreSessionEventProcessor::processIrcEvent432(IrcEventNumeric *e)
1154 {
1155     if (!checkParamCount(e, 1))
1156         return;
1157
1158     QString errnick;
1159     if (e->params().count() < 2) {
1160         // handle unreal-ircd bug, where unreal ircd doesnt supply a TARGET in ERR_ERRONEUSNICKNAME during registration phase:
1161         // nick @@@
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());
1166         e->setTarget("*");
1167     }
1168     errnick = e->params()[0];
1169
1170     tryNextNick(e, errnick, true /* erroneus */);
1171 }
1172
1173
1174 /* ERR_NICKNAMEINUSE */
1175 void CoreSessionEventProcessor::processIrcEvent433(IrcEventNumeric *e)
1176 {
1177     if (!checkParamCount(e, 1))
1178         return;
1179
1180     QString errnick = e->params().first();
1181
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())
1185         return;
1186
1187     tryNextNick(e, errnick);
1188 }
1189
1190
1191 /* ERR_UNAVAILRESOURCE */
1192 void CoreSessionEventProcessor::processIrcEvent437(IrcEventNumeric *e)
1193 {
1194     if (!checkParamCount(e, 1))
1195         return;
1196
1197     QString errnick = e->params().first();
1198
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())
1202         return;
1203
1204     if (!e->network()->isChannelName(errnick))
1205         tryNextNick(e, errnick);
1206 }
1207
1208
1209 /* template
1210 void CoreSessionEventProcessor::processIrcEvent(IrcEvent *e) {
1211   if(!checkParamCount(e, 1))
1212     return;
1213
1214 }
1215 */
1216
1217 /* Handle signals from Netsplit objects  */
1218
1219 void CoreSessionEventProcessor::handleNetsplitJoin(Network *net,
1220     const QString &channel,
1221     const QStringList &users,
1222     const QStringList &modes,
1223     const QString &quitMessage)
1224 {
1225     IrcChannel *ircChannel = net->ircChannel(channel);
1226     if (!ircChannel) {
1227         return;
1228     }
1229     QList<IrcUser *> ircUsers;
1230     QStringList newModes = modes;
1231     QStringList newUsers = users;
1232
1233     foreach(const QString &user, users) {
1234         IrcUser *iu = net->ircUser(nickFromMask(user));
1235         if (iu)
1236             ircUsers.append(iu);
1237         else { // the user already quit
1238             int idx = users.indexOf(user);
1239             newUsers.removeAt(idx);
1240             newModes.removeAt(idx);
1241         }
1242     }
1243
1244     ircChannel->joinIrcUsers(ircUsers, newModes);
1245     NetworkSplitEvent *event = new NetworkSplitEvent(EventManager::NetworkSplitJoin, net, channel, newUsers, quitMessage);
1246     emit newEvent(event);
1247 }
1248
1249
1250 void CoreSessionEventProcessor::handleNetsplitQuit(Network *net, const QString &channel, const QStringList &users, const QString &quitMessage)
1251 {
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));
1256         if (iu)
1257             iu->quit();
1258     }
1259 }
1260
1261
1262 void CoreSessionEventProcessor::handleEarlyNetsplitJoin(Network *net, const QString &channel, const QStringList &users, const QStringList &modes)
1263 {
1264     IrcChannel *ircChannel = net->ircChannel(channel);
1265     if (!ircChannel) {
1266         qDebug() << "handleEarlyNetsplitJoin(): channel " << channel << " invalid";
1267         return;
1268     }
1269     QList<NetworkEvent *> events;
1270     QList<IrcUser *> ircUsers;
1271     QStringList newModes = modes;
1272
1273     foreach(QString user, users) {
1274         IrcUser *iu = net->updateNickFromMask(user);
1275         if (iu) {
1276             ircUsers.append(iu);
1277             // fake event for scripts that consume join events
1278             events << new IrcEvent(EventManager::IrcEventJoin, net, iu->hostmask(), QStringList() << channel);
1279         }
1280         else {
1281             newModes.removeAt(users.indexOf(user));
1282         }
1283     }
1284     ircChannel->joinIrcUsers(ircUsers, newModes);
1285     foreach(NetworkEvent *event, events) {
1286         event->setFlag(EventManager::Fake); // ignore this in here!
1287         emit newEvent(event);
1288     }
1289 }
1290
1291
1292 void CoreSessionEventProcessor::handleNetsplitFinished()
1293 {
1294     Netsplit *n = qobject_cast<Netsplit *>(sender());
1295     Q_ASSERT(n);
1296     QHash<QString, Netsplit *> splithash  = _netsplits.take(n->network());
1297     splithash.remove(splithash.key(n));
1298     if (splithash.count())
1299         _netsplits[n->network()] = splithash;
1300     n->deleteLater();
1301 }
1302
1303
1304 void CoreSessionEventProcessor::destroyNetsplits(NetworkId netId)
1305 {
1306     Network *net = coreSession()->network(netId);
1307     if (!net)
1308         return;
1309
1310     QHash<QString, Netsplit *> splits = _netsplits.take(net);
1311     qDeleteAll(splits);
1312 }
1313
1314
1315 /*******************************/
1316 /******** CTCP HANDLING ********/
1317 /*******************************/
1318
1319 void CoreSessionEventProcessor::processCtcpEvent(CtcpEvent *e)
1320 {
1321     if (e->testFlag(EventManager::Self))
1322         return;  // ignore ctcp events generated by user input
1323
1324     if (e->type() != EventManager::CtcpEvent || e->ctcpType() != CtcpEvent::Query)
1325         return;
1326
1327     handle(e->ctcpCmd(), Q_ARG(CtcpEvent *, e));
1328 }
1329
1330
1331 void CoreSessionEventProcessor::defaultHandler(const QString &ctcpCmd, CtcpEvent *e)
1332 {
1333     // This handler is only there to avoid warnings for unknown CTCPs
1334     Q_UNUSED(e);
1335     Q_UNUSED(ctcpCmd);
1336 }
1337
1338
1339 void CoreSessionEventProcessor::handleCtcpAction(CtcpEvent *e)
1340 {
1341     // This handler is only there to feed CLIENTINFO
1342     Q_UNUSED(e);
1343 }
1344
1345
1346 void CoreSessionEventProcessor::handleCtcpClientinfo(CtcpEvent *e)
1347 {
1348     QStringList supportedHandlers;
1349     foreach(QString handler, providesHandlers())
1350     supportedHandlers << handler.toUpper();
1351     qSort(supportedHandlers);
1352     e->setReply(supportedHandlers.join(" "));
1353 }
1354
1355
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)
1359 {
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";
1363         return;
1364     }
1365
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
1374                 return;
1375             }
1376             QString filename = params[1];
1377             QHostAddress address;
1378             quint16 port = params[3].toUShort();
1379             quint64 size = 0;
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;
1384                     return;
1385                 }
1386             }
1387             else {
1388                 address.setAddress(numIp.toUInt());
1389             }
1390
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()));
1393                 return;
1394             }
1395             if (port < 1024) {
1396                 qWarning() << "Privileged port requested:" << port; // FIXME ask user if this is ok
1397             }
1398
1399
1400             if (params.count() > 4) { // filesize is optional
1401                 size = params[4].toULong();
1402             }
1403
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);
1408         }
1409         else {
1410             emit newEvent(new MessageEvent(Message::Error, e->network(), tr("DCC %1 not supported").arg(cmd), e->prefix(), e->target(), Message::None, e->timestamp()));
1411             return;
1412         }
1413     }
1414 }
1415
1416
1417 void CoreSessionEventProcessor::handleCtcpPing(CtcpEvent *e)
1418 {
1419     e->setReply(e->param().isNull() ? "" : e->param());
1420 }
1421
1422
1423 void CoreSessionEventProcessor::handleCtcpTime(CtcpEvent *e)
1424 {
1425     e->setReply(QDateTime::currentDateTime().toString());
1426 }
1427
1428
1429 void CoreSessionEventProcessor::handleCtcpVersion(CtcpEvent *e)
1430 {
1431     e->setReply(QString("Quassel IRC %1 (built on %2) -- http://www.quassel-irc.org")
1432         .arg(Quassel::buildInfo().plainVersionString).arg(Quassel::buildInfo().commitDate));
1433 }