Sort IRCv3 capabilities before negotiation
[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     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(' ');
172             } else {
173                 // Single line reply
174                 capListFinished = true;
175                 availableCaps = e->params().at(2).split(' ');
176             }
177             // Sort capabilities before requesting for consistency among networks.  This may avoid
178             // unexpected cases when some networks offer capabilities in a different order than
179             // others.  It also looks nicer in logs.  Not required.
180             availableCaps.sort();
181             // Store what capabilities are available
182             QString availableCapName, availableCapValue;
183             for (int i = 0; i < availableCaps.count(); ++i) {
184                 // Capability may include values, e.g. CAP * LS :multi-prefix sasl=EXTERNAL
185                 // Capability name comes before the first '='.  If no '=' exists, this gets the
186                 // whole string instead.
187                 availableCapName = availableCaps[i].section('=', 0, 0).trimmed();
188                 // Some capabilities include multiple key=value pairs in the listing,
189                 // e.g. "sts=duration=31536000,port=6697"
190                 // Include everything after the first equal sign as part of the value.  If no '='
191                 // exists, this gets an empty string.
192                 availableCapValue = availableCaps[i].section('=', 1).trimmed();
193                 // Only add the capability if it's non-empty
194                 if (!availableCapName.isEmpty()) {
195                     coreNet->addCap(availableCapName, availableCapValue);
196                 }
197             }
198
199             // Begin capability requests when capability listing complete
200             if (capListFinished)
201                 coreNet->beginCapNegotiation();
202         } else if (capCommand == "ACK") {
203             // Server: CAP * ACK :multi-prefix sasl
204             // Got the capability we want, handle as needed.
205             // As only one capability is requested at a time, no need to split
206             QString acceptedCap = e->params().at(2).trimmed().toLower();
207
208             // Mark this cap as accepted
209             coreNet->acknowledgeCap(acceptedCap);
210
211             if (!coreNet->capsRequiringConfiguration.contains(acceptedCap)) {
212                 // Some capabilities (e.g. SASL) require further messages to finish.  If so, do NOT
213                 // send the next capability; it will be handled elsewhere in CoreNetwork.
214                 // Otherwise, move on to the next capability
215                 coreNet->sendNextCap();
216             }
217         } else if (capCommand == "NAK" || capCommand == "DEL") {
218             // Either something went wrong with this capability, or it is no longer supported
219             // > For CAP NAK
220             // Server: CAP * NAK :multi-prefix sasl
221             // > For CAP DEL
222             // Server: :irc.example.com CAP modernclient DEL :multi-prefix sasl
223             // CAP NAK and CAP DEL replies are always single-line
224
225             QStringList removedCaps;
226             removedCaps = e->params().at(2).split(' ');
227
228             // Store what capability was denied or removed
229             QString removedCap;
230             for (int i = 0; i < removedCaps.count(); ++i) {
231                 removedCap = removedCaps[i].trimmed().toLower();
232                 // Mark this cap as removed
233                 coreNet->removeCap(removedCap);
234             }
235
236             if (capCommand == "NAK") {
237                 // Continue negotiation when capability listing complete only if this is the result
238                 // of a denied cap, not a removed cap
239                 coreNet->sendNextCap();
240             }
241         }
242     }
243 }
244
245 /* IRCv3 account-notify
246  * Log in:  ":nick!user@host ACCOUNT accountname"
247  * Log out: ":nick!user@host ACCOUNT *" */
248 void CoreSessionEventProcessor::processIrcEventAccount(IrcEvent *e)
249 {
250     if (!checkParamCount(e, 1))
251         return;
252
253     IrcUser *ircuser = e->network()->updateNickFromMask(e->prefix());
254     if (ircuser) {
255         // WHOX uses '0' to indicate logged-out, account-notify and extended-join uses '*'.
256         // As '*' is used internally to represent logged-out, no need to handle that differently.
257         ircuser->setAccount(e->params().at(0));
258     } else {
259         qDebug() << "Received account-notify data for unknown user" << e->prefix();
260     }
261 }
262
263 /* IRCv3 away-notify - ":nick!user@host AWAY [:message]" */
264 void CoreSessionEventProcessor::processIrcEventAway(IrcEvent *e)
265 {
266     if (!checkParamCount(e, 1))
267         return;
268     // Don't use checkParamCount(e, 2) since the message is optional.  Some servers respond in a way
269     // that it counts as two parameters, but we shouldn't rely on that.
270
271     // Nick is sent as part of parameters in order to split user/server decoding
272     IrcUser *ircuser = e->network()->ircUser(e->params().at(0));
273     if (ircuser) {
274         // If two parameters are sent -and- the second parameter isn't empty, then user is away.
275         // Otherwise, mark them as not away.
276         if (e->params().count() >= 2 && !e->params().at(1).isEmpty()) {
277             ircuser->setAway(true);
278             ircuser->setAwayMessage(e->params().at(1));
279         } else {
280             ircuser->setAway(false);
281         }
282     } else {
283         qDebug() << "Received away-notify data for unknown user" << e->params().at(0);
284     }
285 }
286
287 /* IRCv3 chghost - ":nick!user@host CHGHOST newuser new.host.goes.here" */
288 void CoreSessionEventProcessor::processIrcEventChghost(IrcEvent *e)
289 {
290     if (!checkParamCount(e, 2))
291         return;
292
293     IrcUser *ircuser = e->network()->updateNickFromMask(e->prefix());
294     if (ircuser) {
295         // Update with new user/hostname information.  setUser/setHost handles checking what
296         // actually changed.
297         ircuser->setUser(e->params().at(0));
298         ircuser->setHost(e->params().at(1));
299     } else {
300         qDebug() << "Received chghost data for unknown user" << e->prefix();
301     }
302 }
303
304 void CoreSessionEventProcessor::processIrcEventInvite(IrcEvent *e)
305 {
306     if (checkParamCount(e, 2)) {
307         e->network()->updateNickFromMask(e->prefix());
308     }
309 }
310
311 /*  JOIN: ":<nick!user@host> JOIN <channel>" */
312 void CoreSessionEventProcessor::processIrcEventJoin(IrcEvent *e)
313 {
314     if (e->testFlag(EventManager::Fake)) // generated by handleEarlyNetsplitJoin
315         return;
316
317     if (!checkParamCount(e, 1))
318         return;
319
320     CoreNetwork *net = coreNetwork(e);
321     QString channel = e->params()[0];
322     IrcUser *ircuser = net->updateNickFromMask(e->prefix());
323
324     if (net->capEnabled(IrcCap::EXTENDED_JOIN)) {
325         if (e->params().count() < 3) {
326             // Some IRC servers don't send extended-join events in all situations.  Rather than
327             // ignore the join entirely, treat it as a regular join with a debug-level log entry.
328             // See:  https://github.com/inspircd/inspircd/issues/821
329             qDebug() << "extended-join requires 3 params, got:" << e->params() << ", handling as a "
330                         "regular join";
331         } else {
332             // If logged in, :nick!user@host JOIN #channelname accountname :Real Name
333             // If logged out, :nick!user@host JOIN #channelname * :Real Name
334             // See:  http://ircv3.net/specs/extensions/extended-join-3.1.html
335             // WHOX uses '0' to indicate logged-out, account-notify and extended-join uses '*'.
336             // As '*' is used internally to represent logged-out, no need to handle that differently.
337             ircuser->setAccount(e->params()[1]);
338             // Update the user's real name, too
339             ircuser->setRealName(e->params()[2]);
340         }
341     }
342     // Else :nick!user@host JOIN #channelname
343
344     bool handledByNetsplit = false;
345     foreach(Netsplit* n, _netsplits.value(e->network())) {
346         handledByNetsplit = n->userJoined(e->prefix(), channel);
347         if (handledByNetsplit)
348             break;
349     }
350
351     // If using away-notify, check new users.  Works around buggy IRC servers
352     // forgetting to send :away messages for users who join channels when away.
353     if (net->capEnabled(IrcCap::AWAY_NOTIFY)) {
354         net->queueAutoWhoOneshot(ircuser->nick());
355     }
356
357     if (!handledByNetsplit)
358         ircuser->joinChannel(channel);
359     else
360         e->setFlag(EventManager::Netsplit);
361
362     if (net->isMe(ircuser)) {
363         net->setChannelJoined(channel);
364         // FIXME use event
365         net->putRawLine(net->serverEncode("MODE " + channel)); // we want to know the modes of the channel we just joined, so we ask politely
366     }
367 }
368
369
370 void CoreSessionEventProcessor::lateProcessIrcEventKick(IrcEvent *e)
371 {
372     if (checkParamCount(e, 2)) {
373         e->network()->updateNickFromMask(e->prefix());
374         IrcUser *victim = e->network()->ircUser(e->params().at(1));
375         if (victim) {
376             victim->partChannel(e->params().at(0));
377             //if(e->network()->isMe(victim)) e->network()->setKickedFromChannel(channel);
378         }
379     }
380 }
381
382
383 void CoreSessionEventProcessor::processIrcEventMode(IrcEvent *e)
384 {
385     if (!checkParamCount(e, 2))
386         return;
387
388     if (e->network()->isChannelName(e->params().first())) {
389         // Channel Modes
390
391         IrcChannel *channel = e->network()->ircChannel(e->params()[0]);
392         if (!channel) {
393             // we received mode information for a channel we're not in. that means probably we've just been kicked out or something like that
394             // anyways: we don't have a place to store the data --> discard the info.
395             return;
396         }
397
398         QString modes = e->params()[1];
399         bool add = true;
400         int paramOffset = 2;
401         for (int c = 0; c < modes.length(); c++) {
402             if (modes[c] == '+') {
403                 add = true;
404                 continue;
405             }
406             if (modes[c] == '-') {
407                 add = false;
408                 continue;
409             }
410
411             if (e->network()->prefixModes().contains(modes[c])) {
412                 // user channel modes (op, voice, etc...)
413                 if (paramOffset < e->params().count()) {
414                     IrcUser *ircUser = e->network()->ircUser(e->params()[paramOffset]);
415                     if (!ircUser) {
416                         qWarning() << Q_FUNC_INFO << "Unknown IrcUser:" << e->params()[paramOffset];
417                     }
418                     else {
419                         if (add) {
420                             bool handledByNetsplit = false;
421                             QHash<QString, Netsplit *> splits = _netsplits.value(e->network());
422                             foreach(Netsplit* n, _netsplits.value(e->network())) {
423                                 handledByNetsplit = n->userAlreadyJoined(ircUser->hostmask(), channel->name());
424                                 if (handledByNetsplit) {
425                                     n->addMode(ircUser->hostmask(), channel->name(), QString(modes[c]));
426                                     break;
427                                 }
428                             }
429                             if (!handledByNetsplit)
430                                 channel->addUserMode(ircUser, QString(modes[c]));
431                         }
432                         else
433                             channel->removeUserMode(ircUser, QString(modes[c]));
434                     }
435                 }
436                 else {
437                     qWarning() << "Received MODE with too few parameters:" << e->params();
438                 }
439                 ++paramOffset;
440             }
441             else {
442                 // regular channel modes
443                 QString value;
444                 Network::ChannelModeType modeType = e->network()->channelModeType(modes[c]);
445                 if (modeType == Network::A_CHANMODE || modeType == Network::B_CHANMODE || (modeType == Network::C_CHANMODE && add)) {
446                     if (paramOffset < e->params().count()) {
447                         value = e->params()[paramOffset];
448                     }
449                     else {
450                         qWarning() << "Received MODE with too few parameters:" << e->params();
451                     }
452                     ++paramOffset;
453                 }
454
455                 if (add)
456                     channel->addChannelMode(modes[c], value);
457                 else
458                     channel->removeChannelMode(modes[c], value);
459             }
460         }
461     }
462     else {
463         // pure User Modes
464         IrcUser *ircUser = e->network()->newIrcUser(e->params().first());
465         QString modeString(e->params()[1]);
466         QString addModes;
467         QString removeModes;
468         bool add = false;
469         for (int c = 0; c < modeString.count(); c++) {
470             if (modeString[c] == '+') {
471                 add = true;
472                 continue;
473             }
474             if (modeString[c] == '-') {
475                 add = false;
476                 continue;
477             }
478             if (add)
479                 addModes += modeString[c];
480             else
481                 removeModes += modeString[c];
482         }
483         if (!addModes.isEmpty())
484             ircUser->addUserModes(addModes);
485         if (!removeModes.isEmpty())
486             ircUser->removeUserModes(removeModes);
487
488         if (e->network()->isMe(ircUser)) {
489             coreNetwork(e)->updatePersistentModes(addModes, removeModes);
490         }
491     }
492 }
493
494
495 void CoreSessionEventProcessor::lateProcessIrcEventNick(IrcEvent *e)
496 {
497     if (checkParamCount(e, 1)) {
498         IrcUser *ircuser = e->network()->updateNickFromMask(e->prefix());
499         if (!ircuser) {
500             qWarning() << Q_FUNC_INFO << "Unknown IrcUser!";
501             return;
502         }
503         QString newnick = e->params().at(0);
504         QString oldnick = ircuser->nick();
505
506         // the order is cruicial
507         // otherwise the client would rename the buffer, see that the assigned ircuser doesn't match anymore
508         // and remove the ircuser from the querybuffer leading to a wrong on/offline state
509         ircuser->setNick(newnick);
510         coreSession()->renameBuffer(e->networkId(), newnick, oldnick);
511     }
512 }
513
514
515 void CoreSessionEventProcessor::lateProcessIrcEventPart(IrcEvent *e)
516 {
517     if (checkParamCount(e, 1)) {
518         IrcUser *ircuser = e->network()->updateNickFromMask(e->prefix());
519         if (!ircuser) {
520             qWarning() << Q_FUNC_INFO<< "Unknown IrcUser!";
521             return;
522         }
523         QString channel = e->params().at(0);
524         ircuser->partChannel(channel);
525         if (e->network()->isMe(ircuser))
526             qobject_cast<CoreNetwork *>(e->network())->setChannelParted(channel);
527     }
528 }
529
530
531 void CoreSessionEventProcessor::processIrcEventPing(IrcEvent *e)
532 {
533     QString param = e->params().count() ? e->params().first() : QString();
534     // FIXME use events
535     // Take priority so this won't get stuck behind other queued messages.
536     coreNetwork(e)->putRawLine("PONG " + coreNetwork(e)->serverEncode(param), true);
537 }
538
539
540 void CoreSessionEventProcessor::processIrcEventPong(IrcEvent *e)
541 {
542     // the server is supposed to send back what we passed as param. and we send a timestamp
543     // but using quote and whatnought one can send arbitrary pings, so we have to do some sanity checks
544     if (checkParamCount(e, 2)) {
545         QString timestamp = e->params().at(1);
546         QTime sendTime = QTime::fromString(timestamp, "hh:mm:ss.zzz");
547         if (sendTime.isValid())
548             e->network()->setLatency(sendTime.msecsTo(QTime::currentTime()) / 2);
549     }
550 }
551
552
553 void CoreSessionEventProcessor::processIrcEventQuit(IrcEvent *e)
554 {
555     IrcUser *ircuser = e->network()->updateNickFromMask(e->prefix());
556     if (!ircuser)
557         return;
558
559     QString msg;
560     if (e->params().count() > 0)
561         msg = e->params()[0];
562
563     // check if netsplit
564     if (Netsplit::isNetsplit(msg)) {
565         Netsplit *n;
566         if (!_netsplits[e->network()].contains(msg)) {
567             n = new Netsplit(e->network(), this);
568             connect(n, SIGNAL(finished()), this, SLOT(handleNetsplitFinished()));
569             connect(n, SIGNAL(netsplitJoin(Network*, QString, QStringList, QStringList, QString)),
570                 this, SLOT(handleNetsplitJoin(Network*, QString, QStringList, QStringList, QString)));
571             connect(n, SIGNAL(netsplitQuit(Network*, QString, QStringList, QString)),
572                 this, SLOT(handleNetsplitQuit(Network*, QString, QStringList, QString)));
573             connect(n, SIGNAL(earlyJoin(Network*, QString, QStringList, QStringList)),
574                 this, SLOT(handleEarlyNetsplitJoin(Network*, QString, QStringList, QStringList)));
575             _netsplits[e->network()].insert(msg, n);
576         }
577         else {
578             n = _netsplits[e->network()][msg];
579         }
580         // add this user to the netsplit
581         n->userQuit(e->prefix(), ircuser->channels(), msg);
582         e->setFlag(EventManager::Netsplit);
583     }
584     // normal quit is handled in lateProcessIrcEventQuit()
585 }
586
587
588 void CoreSessionEventProcessor::lateProcessIrcEventQuit(IrcEvent *e)
589 {
590     if (e->testFlag(EventManager::Netsplit))
591         return;
592
593     IrcUser *ircuser = e->network()->updateNickFromMask(e->prefix());
594     if (!ircuser)
595         return;
596
597     ircuser->quit();
598 }
599
600
601 void CoreSessionEventProcessor::processIrcEventTopic(IrcEvent *e)
602 {
603     if (checkParamCount(e, 2)) {
604         e->network()->updateNickFromMask(e->prefix());
605         IrcChannel *channel = e->network()->ircChannel(e->params().at(0));
606         if (channel)
607             channel->setTopic(e->params().at(1));
608     }
609 }
610
611
612 #ifdef HAVE_QCA2
613 void CoreSessionEventProcessor::processKeyEvent(KeyEvent *e)
614 {
615     if (!Cipher::neededFeaturesAvailable()) {
616         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()));
617         return;
618     }
619     CoreNetwork *net = qobject_cast<CoreNetwork*>(e->network());
620     Cipher *c = net->cipher(e->target());
621     if (!c) // happens when there is no CoreIrcChannel for the target (i.e. never?)
622         return;
623
624     if (e->exchangeType() == KeyEvent::Init) {
625         QByteArray pubKey = c->parseInitKeyX(e->key());
626         if (pubKey.isEmpty()) {
627             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()));
628             return;
629         } else {
630             net->setCipherKey(e->target(), c->key());
631             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()));
632             QList<QByteArray> p;
633             p << net->serverEncode(e->target()) << net->serverEncode("DH1080_FINISH ")+pubKey;
634             net->putCmd("NOTICE", p);
635         }
636     } else {
637         if (c->parseFinishKeyX(e->key())) {
638             net->setCipherKey(e->target(), c->key());
639             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()));
640         } else {
641             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()));
642         }
643     }
644 }
645 #endif
646
647
648 /* RPL_WELCOME */
649 void CoreSessionEventProcessor::processIrcEvent001(IrcEventNumeric *e)
650 {
651     e->network()->setCurrentServer(e->prefix());
652     e->network()->setMyNick(e->target());
653 }
654
655
656 /* RPL_ISUPPORT */
657 // TODO Complete 005 handling, also use sensible defaults for non-sent stuff
658 void CoreSessionEventProcessor::processIrcEvent005(IrcEvent *e)
659 {
660     if (!checkParamCount(e, 1))
661         return;
662
663     QString key, value;
664     for (int i = 0; i < e->params().count() - 1; i++) {
665         QString key = e->params()[i].section("=", 0, 0);
666         QString value = e->params()[i].section("=", 1);
667         e->network()->addSupport(key, value);
668     }
669
670     /* determine our prefixes here to get an accurate result */
671     e->network()->determinePrefixes();
672 }
673
674
675 /* RPL_UMODEIS - "<user_modes> [<user_mode_params>]" */
676 void CoreSessionEventProcessor::processIrcEvent221(IrcEvent *)
677 {
678     // TODO: save information in network object
679 }
680
681
682 /* RPL_STATSCONN - "Highest connection cout: 8000 (7999 clients)" */
683 void CoreSessionEventProcessor::processIrcEvent250(IrcEvent *)
684 {
685     // TODO: save information in network object
686 }
687
688
689 /* RPL_LOCALUSERS - "Current local user: 5024  Max: 7999 */
690 void CoreSessionEventProcessor::processIrcEvent265(IrcEvent *)
691 {
692     // TODO: save information in network object
693 }
694
695
696 /* RPL_GLOBALUSERS - "Current global users: 46093  Max: 47650" */
697 void CoreSessionEventProcessor::processIrcEvent266(IrcEvent *)
698 {
699     // TODO: save information in network object
700 }
701
702
703 /*
704 WHOIS-Message:
705    Replies 311 - 313, 317 - 319 are all replies generated in response to a WHOIS message.
706   and 301 (RPL_AWAY)
707               "<nick> :<away message>"
708 WHO-Message:
709    Replies 352 and 315 paired are used to answer a WHO message.
710
711 WHOWAS-Message:
712    Replies 314 and 369 are responses to a WHOWAS message.
713
714 */
715
716 /* RPL_AWAY - "<nick> :<away message>" */
717 void CoreSessionEventProcessor::processIrcEvent301(IrcEvent *e)
718 {
719     if (!checkParamCount(e, 2))
720         return;
721
722     IrcUser *ircuser = e->network()->ircUser(e->params().at(0));
723     if (ircuser) {
724         ircuser->setAway(true);
725         ircuser->setAwayMessage(e->params().at(1));
726         //ircuser->setLastAwayMessage(now);
727     }
728 }
729
730
731 /* RPL_UNAWAY - ":You are no longer marked as being away" */
732 void CoreSessionEventProcessor::processIrcEvent305(IrcEvent *e)
733 {
734     IrcUser *me = e->network()->me();
735     if (me)
736         me->setAway(false);
737
738     if (e->network()->autoAwayActive()) {
739         e->network()->setAutoAwayActive(false);
740         e->setFlag(EventManager::Silent);
741     }
742 }
743
744
745 /* RPL_NOWAWAY - ":You have been marked as being away" */
746 void CoreSessionEventProcessor::processIrcEvent306(IrcEvent *e)
747 {
748     IrcUser *me = e->network()->me();
749     if (me)
750         me->setAway(true);
751 }
752
753
754 /* RPL_WHOISSERVICE - "<user> is registered nick" */
755 void CoreSessionEventProcessor::processIrcEvent307(IrcEvent *e)
756 {
757     if (!checkParamCount(e, 1))
758         return;
759
760     IrcUser *ircuser = e->network()->ircUser(e->params().at(0));
761     if (ircuser)
762         ircuser->setWhoisServiceReply(e->params().join(" "));
763 }
764
765
766 /* RPL_SUSERHOST - "<user> is available for help." */
767 void CoreSessionEventProcessor::processIrcEvent310(IrcEvent *e)
768 {
769     if (!checkParamCount(e, 1))
770         return;
771
772     IrcUser *ircuser = e->network()->ircUser(e->params().at(0));
773     if (ircuser)
774         ircuser->setSuserHost(e->params().join(" "));
775 }
776
777
778 /*  RPL_WHOISUSER - "<nick> <user> <host> * :<real name>" */
779 void CoreSessionEventProcessor::processIrcEvent311(IrcEvent *e)
780 {
781     if (!checkParamCount(e, 3))
782         return;
783
784     IrcUser *ircuser = e->network()->ircUser(e->params().at(0));
785     if (ircuser) {
786         ircuser->setUser(e->params().at(1));
787         ircuser->setHost(e->params().at(2));
788         ircuser->setRealName(e->params().last());
789     }
790 }
791
792
793 /*  RPL_WHOISSERVER -  "<nick> <server> :<server info>" */
794 void CoreSessionEventProcessor::processIrcEvent312(IrcEvent *e)
795 {
796     if (!checkParamCount(e, 2))
797         return;
798
799     IrcUser *ircuser = e->network()->ircUser(e->params().at(0));
800     if (ircuser)
801         ircuser->setServer(e->params().at(1));
802 }
803
804
805 /*  RPL_WHOISOPERATOR - "<nick> :is an IRC operator" */
806 void CoreSessionEventProcessor::processIrcEvent313(IrcEvent *e)
807 {
808     if (!checkParamCount(e, 1))
809         return;
810
811     IrcUser *ircuser = e->network()->ircUser(e->params().at(0));
812     if (ircuser)
813         ircuser->setIrcOperator(e->params().last());
814 }
815
816
817 /*  RPL_ENDOFWHO: "<name> :End of WHO list" */
818 void CoreSessionEventProcessor::processIrcEvent315(IrcEvent *e)
819 {
820     if (!checkParamCount(e, 1))
821         return;
822
823     if (coreNetwork(e)->setAutoWhoDone(e->params()[0]))
824         e->setFlag(EventManager::Silent);
825 }
826
827
828 /*  RPL_WHOISIDLE - "<nick> <integer> :seconds idle"
829    (real life: "<nick> <integer> <integer> :seconds idle, signon time) */
830 void CoreSessionEventProcessor::processIrcEvent317(IrcEvent *e)
831 {
832     if (!checkParamCount(e, 2))
833         return;
834
835     QDateTime loginTime;
836
837     int idleSecs = e->params()[1].toInt();
838     if (e->params().count() > 3) { // if we have more then 3 params we have the above mentioned "real life" situation
839         int logintime = e->params()[2].toInt();
840         loginTime = QDateTime::fromTime_t(logintime);
841     }
842
843     IrcUser *ircuser = e->network()->ircUser(e->params()[0]);
844     if (ircuser) {
845         ircuser->setIdleTime(e->timestamp().addSecs(-idleSecs));
846         if (loginTime.isValid())
847             ircuser->setLoginTime(loginTime);
848     }
849 }
850
851
852 /* RPL_LIST -  "<channel> <# visible> :<topic>" */
853 void CoreSessionEventProcessor::processIrcEvent322(IrcEvent *e)
854 {
855     if (!checkParamCount(e, 1))
856         return;
857
858     QString channelName;
859     quint32 userCount = 0;
860     QString topic;
861
862     switch (e->params().count()) {
863     case 3:
864         topic = e->params()[2];
865     case 2:
866         userCount = e->params()[1].toUInt();
867     case 1:
868         channelName = e->params()[0];
869     default:
870         break;
871     }
872     if (coreSession()->ircListHelper()->addChannel(e->networkId(), channelName, userCount, topic))
873         e->stop();  // consumed by IrcListHelper, so don't further process/show this event
874 }
875
876
877 /* RPL_LISTEND ":End of LIST" */
878 void CoreSessionEventProcessor::processIrcEvent323(IrcEvent *e)
879 {
880     if (!checkParamCount(e, 1))
881         return;
882
883     if (coreSession()->ircListHelper()->endOfChannelList(e->networkId()))
884         e->stop();  // consumed by IrcListHelper, so don't further process/show this event
885 }
886
887
888 /* RPL_CHANNELMODEIS - "<channel> <mode> <mode params>" */
889 void CoreSessionEventProcessor::processIrcEvent324(IrcEvent *e)
890 {
891     processIrcEventMode(e);
892 }
893
894
895 /*  RPL_WHOISACCOUNT - "<nick> <account> :is authed as" */
896 void CoreSessionEventProcessor::processIrcEvent330(IrcEvent *e)
897 {
898     // Though the ":is authed as" remark should always be there, we should handle cases when it's
899     // not included, too.
900     if (!checkParamCount(e, 2))
901         return;
902
903     IrcUser *ircuser = e->network()->ircUser(e->params().at(0));
904     if (ircuser) {
905         ircuser->setAccount(e->params().at(1));
906     }
907 }
908
909
910 /* RPL_NOTOPIC */
911 void CoreSessionEventProcessor::processIrcEvent331(IrcEvent *e)
912 {
913     if (!checkParamCount(e, 1))
914         return;
915
916     IrcChannel *chan = e->network()->ircChannel(e->params()[0]);
917     if (chan)
918         chan->setTopic(QString());
919 }
920
921
922 /* RPL_TOPIC */
923 void CoreSessionEventProcessor::processIrcEvent332(IrcEvent *e)
924 {
925     if (!checkParamCount(e, 2))
926         return;
927
928     IrcChannel *chan = e->network()->ircChannel(e->params()[0]);
929     if (chan)
930         chan->setTopic(e->params()[1]);
931 }
932
933
934 /*  RPL_WHOREPLY: "<channel> <user> <host> <server> <nick>
935               ( "H" / "G" > ["*"] [ ( "@" / "+" ) ] :<hopcount> <real name>" */
936 void CoreSessionEventProcessor::processIrcEvent352(IrcEvent *e)
937 {
938     if (!checkParamCount(e, 6))
939         return;
940
941     QString channel = e->params()[0];
942     IrcUser *ircuser = e->network()->ircUser(e->params()[4]);
943     if (ircuser) {
944         processWhoInformation(e->network(), channel, ircuser, e->params()[3], e->params()[1],
945                 e->params()[2], e->params()[5], e->params().last().section(" ", 1));
946     }
947
948     // Check if channel name has a who in progress.
949     // If not, then check if user nick exists and has a who in progress.
950     if (coreNetwork(e)->isAutoWhoInProgress(channel) ||
951         (ircuser && coreNetwork(e)->isAutoWhoInProgress(ircuser->nick()))) {
952         e->setFlag(EventManager::Silent);
953     }
954 }
955
956
957 /* RPL_NAMREPLY */
958 void CoreSessionEventProcessor::processIrcEvent353(IrcEvent *e)
959 {
960     if (!checkParamCount(e, 3))
961         return;
962
963     // param[0] is either "=", "*" or "@" indicating a public, private or secret channel
964     // we don't use this information at the time beeing
965     QString channelname = e->params()[1];
966
967     IrcChannel *channel = e->network()->ircChannel(channelname);
968     if (!channel) {
969         qWarning() << Q_FUNC_INFO << "Received unknown target channel:" << channelname;
970         return;
971     }
972
973     QStringList nicks;
974     QStringList modes;
975
976     // Cache result of multi-prefix to avoid unneeded casts and lookups with each iteration.
977     bool _useCapMultiPrefix = coreNetwork(e)->capEnabled(IrcCap::MULTI_PREFIX);
978
979     foreach(QString nick, e->params()[2].split(' ', QString::SkipEmptyParts)) {
980         QString mode;
981
982         if (_useCapMultiPrefix) {
983             // If multi-prefix is enabled, all modes will be sent in NAMES replies.
984             // :hades.arpa 353 guest = #tethys :~&@%+aji &@Attila @+alyx +KindOne Argure
985             // See: http://ircv3.net/specs/extensions/multi-prefix-3.1.html
986             while (e->network()->prefixes().contains(nick[0])) {
987                 // Mode found in 1 left-most character, add it to the list.
988                 // Note: sending multiple modes may cause a warning in older clients.
989                 // In testing, the clients still seemed to function fine.
990                 mode.append(e->network()->prefixToMode(nick[0]));
991                 // Remove this mode from the nick
992                 nick = nick.remove(0, 1);
993             }
994         } else if (e->network()->prefixes().contains(nick[0])) {
995             // Multi-prefix is disabled and a mode prefix was found.
996             mode = e->network()->prefixToMode(nick[0]);
997             nick = nick.mid(1);
998         }
999
1000         // If userhost-in-names capability is enabled, the following will be
1001         // in the form "nick!user@host" rather than "nick".  This works without
1002         // special handling as the following use nickFromHost() as needed.
1003         // See: http://ircv3.net/specs/extensions/userhost-in-names-3.2.html
1004
1005         nicks << nick;
1006         modes << mode;
1007     }
1008
1009     channel->joinIrcUsers(nicks, modes);
1010 }
1011
1012
1013 /*  RPL_WHOSPCRPL: "<yournick> 152 #<channel> ~<ident> <host> <servname> <nick>
1014                     ("H"/ "G") <account> :<realname>"
1015 <channel> is * if not specific to any channel
1016 <account> is * if not logged in
1017 Follows HexChat's usage of 'whox'
1018 See https://github.com/hexchat/hexchat/blob/c874a9525c9b66f1d5ddcf6c4107d046eba7e2c5/src/common/proto-irc.c#L750
1019 And http://faerion.sourceforge.net/doc/irc/whox.var*/
1020 void CoreSessionEventProcessor::processIrcEvent354(IrcEvent *e)
1021 {
1022     // First only check if at least one parameter exists.  Otherwise, it'll stop the result from
1023     // being shown if the user chooses different parameters.
1024     if (!checkParamCount(e, 1))
1025         return;
1026
1027     if (e->params()[0].toUInt() != IrcCap::ACCOUNT_NOTIFY_WHOX_NUM) {
1028         // Ignore WHOX replies without expected number for we have no idea what fields are specified
1029         return;
1030     }
1031
1032     // Now we're fairly certain this is supposed to be an automated WHOX.  Bail out if it doesn't
1033     // match what we require - 9 parameters.
1034     if (!checkParamCount(e, 9))
1035         return;
1036
1037     QString channel = e->params()[1];
1038     IrcUser *ircuser = e->network()->ircUser(e->params()[5]);
1039     if (ircuser) {
1040         processWhoInformation(e->network(), channel, ircuser, e->params()[4], e->params()[2],
1041                 e->params()[3], e->params()[6], e->params().last());
1042         // Don't use .section(" ", 1) with WHOX replies, for there's no hopcount to trim out
1043
1044         // As part of IRCv3 account-notify, check account name
1045         // WHOX uses '0' to indicate logged-out, account-notify and extended-join uses '*'.
1046         QString newAccount = e->params()[7];
1047         if (newAccount != "0") {
1048             // Account logged in, set account name
1049             ircuser->setAccount(newAccount);
1050         } else {
1051             // Account logged out, set account name to logged-out
1052             ircuser->setAccount("*");
1053         }
1054     }
1055
1056     // Check if channel name has a who in progress.
1057     // If not, then check if user nick exists and has a who in progress.
1058     if (coreNetwork(e)->isAutoWhoInProgress(channel) ||
1059         (ircuser && coreNetwork(e)->isAutoWhoInProgress(ircuser->nick()))) {
1060         e->setFlag(EventManager::Silent);
1061     }
1062 }
1063
1064
1065 void CoreSessionEventProcessor::processWhoInformation (Network *net, const QString &targetChannel, IrcUser *ircUser,
1066                             const QString &server, const QString &user, const QString &host,
1067                             const QString &awayStateAndModes, const QString &realname)
1068 {
1069     ircUser->setUser(user);
1070     ircUser->setHost(host);
1071     ircUser->setServer(server);
1072     ircUser->setRealName(realname);
1073
1074     bool away = awayStateAndModes.contains("G", Qt::CaseInsensitive);
1075     ircUser->setAway(away);
1076
1077     if (net->capEnabled(IrcCap::MULTI_PREFIX)) {
1078         // If multi-prefix is enabled, all modes will be sent in WHO replies.
1079         // :kenny.chatspike.net 352 guest #test grawity broken.symlink *.chatspike.net grawity H@%+ :0 Mantas M.
1080         // See: http://ircv3.net/specs/extensions/multi-prefix-3.1.html
1081         QString uncheckedModes = awayStateAndModes;
1082         QString validModes = QString();
1083         while (!uncheckedModes.isEmpty()) {
1084             // Mode found in 1 left-most character, add it to the list
1085             if (net->prefixes().contains(uncheckedModes[0])) {
1086                 validModes.append(net->prefixToMode(uncheckedModes[0]));
1087             }
1088             // Remove this mode from the list of unchecked modes
1089             uncheckedModes = uncheckedModes.remove(0, 1);
1090         }
1091
1092         // Some IRC servers decide to not follow the spec, returning only -some- of the user
1093         // modes in WHO despite listing them all in NAMES.  For now, assume it can only add
1094         // and not take away.  *sigh*
1095         if (!validModes.isEmpty()) {
1096             if (targetChannel != "*") {
1097                 // Channel-specific modes received, apply to given channel only
1098                 IrcChannel *ircChan = net->ircChannel(targetChannel);
1099                 if (ircChan) {
1100                     // Do one mode at a time
1101                     // TODO Better way of syncing this without breaking protocol?
1102                     for (int i = 0; i < validModes.count(); ++i) {
1103                         ircChan->addUserMode(ircUser, validModes.at(i));
1104                     }
1105                 }
1106             } else {
1107                 // Modes apply to the user everywhere
1108                 ircUser->addUserModes(validModes);
1109             }
1110         }
1111     }
1112 }
1113
1114
1115 /* ERR_NOSUCHCHANNEL - "<channel name> :No such channel" */
1116 void CoreSessionEventProcessor::processIrcEvent403(IrcEventNumeric *e)
1117 {
1118     // If this is the result of an AutoWho, hide it.  It's confusing to show to the user.
1119     // Though the ":No such channel" remark should always be there, we should handle cases when it's
1120     // not included, too.
1121     if (!checkParamCount(e, 1))
1122         return;
1123
1124     QString channelOrNick = e->params()[0];
1125     // Check if channel name has a who in progress.
1126     // If not, then check if user nick exists and has a who in progress.
1127     if (coreNetwork(e)->isAutoWhoInProgress(channelOrNick)) {
1128         qDebug() << "Channel/nick" << channelOrNick << "no longer exists during AutoWho, ignoring";
1129         e->setFlag(EventManager::Silent);
1130     }
1131 }
1132
1133 /* ERR_ERRONEUSNICKNAME */
1134 void CoreSessionEventProcessor::processIrcEvent432(IrcEventNumeric *e)
1135 {
1136     if (!checkParamCount(e, 1))
1137         return;
1138
1139     QString errnick;
1140     if (e->params().count() < 2) {
1141         // handle unreal-ircd bug, where unreal ircd doesnt supply a TARGET in ERR_ERRONEUSNICKNAME during registration phase:
1142         // nick @@@
1143         // :irc.scortum.moep.net 432  @@@ :Erroneous Nickname: Illegal characters
1144         // correct server reply:
1145         // :irc.scortum.moep.net 432 * @@@ :Erroneous Nickname: Illegal characters
1146         e->params().prepend(e->target());
1147         e->setTarget("*");
1148     }
1149     errnick = e->params()[0];
1150
1151     tryNextNick(e, errnick, true /* erroneus */);
1152 }
1153
1154
1155 /* ERR_NICKNAMEINUSE */
1156 void CoreSessionEventProcessor::processIrcEvent433(IrcEventNumeric *e)
1157 {
1158     if (!checkParamCount(e, 1))
1159         return;
1160
1161     QString errnick = e->params().first();
1162
1163     // if there is a problem while connecting to the server -> we handle it
1164     // but only if our connection has not been finished yet...
1165     if (!e->network()->currentServer().isEmpty())
1166         return;
1167
1168     tryNextNick(e, errnick);
1169 }
1170
1171
1172 /* ERR_UNAVAILRESOURCE */
1173 void CoreSessionEventProcessor::processIrcEvent437(IrcEventNumeric *e)
1174 {
1175     if (!checkParamCount(e, 1))
1176         return;
1177
1178     QString errnick = e->params().first();
1179
1180     // if there is a problem while connecting to the server -> we handle it
1181     // but only if our connection has not been finished yet...
1182     if (!e->network()->currentServer().isEmpty())
1183         return;
1184
1185     if (!e->network()->isChannelName(errnick))
1186         tryNextNick(e, errnick);
1187 }
1188
1189
1190 /* template
1191 void CoreSessionEventProcessor::processIrcEvent(IrcEvent *e) {
1192   if(!checkParamCount(e, 1))
1193     return;
1194
1195 }
1196 */
1197
1198 /* Handle signals from Netsplit objects  */
1199
1200 void CoreSessionEventProcessor::handleNetsplitJoin(Network *net,
1201     const QString &channel,
1202     const QStringList &users,
1203     const QStringList &modes,
1204     const QString &quitMessage)
1205 {
1206     IrcChannel *ircChannel = net->ircChannel(channel);
1207     if (!ircChannel) {
1208         return;
1209     }
1210     QList<IrcUser *> ircUsers;
1211     QStringList newModes = modes;
1212     QStringList newUsers = users;
1213
1214     foreach(const QString &user, users) {
1215         IrcUser *iu = net->ircUser(nickFromMask(user));
1216         if (iu)
1217             ircUsers.append(iu);
1218         else { // the user already quit
1219             int idx = users.indexOf(user);
1220             newUsers.removeAt(idx);
1221             newModes.removeAt(idx);
1222         }
1223     }
1224
1225     ircChannel->joinIrcUsers(ircUsers, newModes);
1226     NetworkSplitEvent *event = new NetworkSplitEvent(EventManager::NetworkSplitJoin, net, channel, newUsers, quitMessage);
1227     emit newEvent(event);
1228 }
1229
1230
1231 void CoreSessionEventProcessor::handleNetsplitQuit(Network *net, const QString &channel, const QStringList &users, const QString &quitMessage)
1232 {
1233     NetworkSplitEvent *event = new NetworkSplitEvent(EventManager::NetworkSplitQuit, net, channel, users, quitMessage);
1234     emit newEvent(event);
1235     foreach(QString user, users) {
1236         IrcUser *iu = net->ircUser(nickFromMask(user));
1237         if (iu)
1238             iu->quit();
1239     }
1240 }
1241
1242
1243 void CoreSessionEventProcessor::handleEarlyNetsplitJoin(Network *net, const QString &channel, const QStringList &users, const QStringList &modes)
1244 {
1245     IrcChannel *ircChannel = net->ircChannel(channel);
1246     if (!ircChannel) {
1247         qDebug() << "handleEarlyNetsplitJoin(): channel " << channel << " invalid";
1248         return;
1249     }
1250     QList<NetworkEvent *> events;
1251     QList<IrcUser *> ircUsers;
1252     QStringList newModes = modes;
1253
1254     foreach(QString user, users) {
1255         IrcUser *iu = net->updateNickFromMask(user);
1256         if (iu) {
1257             ircUsers.append(iu);
1258             // fake event for scripts that consume join events
1259             events << new IrcEvent(EventManager::IrcEventJoin, net, iu->hostmask(), QStringList() << channel);
1260         }
1261         else {
1262             newModes.removeAt(users.indexOf(user));
1263         }
1264     }
1265     ircChannel->joinIrcUsers(ircUsers, newModes);
1266     foreach(NetworkEvent *event, events) {
1267         event->setFlag(EventManager::Fake); // ignore this in here!
1268         emit newEvent(event);
1269     }
1270 }
1271
1272
1273 void CoreSessionEventProcessor::handleNetsplitFinished()
1274 {
1275     Netsplit *n = qobject_cast<Netsplit *>(sender());
1276     Q_ASSERT(n);
1277     QHash<QString, Netsplit *> splithash  = _netsplits.take(n->network());
1278     splithash.remove(splithash.key(n));
1279     if (splithash.count())
1280         _netsplits[n->network()] = splithash;
1281     n->deleteLater();
1282 }
1283
1284
1285 void CoreSessionEventProcessor::destroyNetsplits(NetworkId netId)
1286 {
1287     Network *net = coreSession()->network(netId);
1288     if (!net)
1289         return;
1290
1291     QHash<QString, Netsplit *> splits = _netsplits.take(net);
1292     qDeleteAll(splits);
1293 }
1294
1295
1296 /*******************************/
1297 /******** CTCP HANDLING ********/
1298 /*******************************/
1299
1300 void CoreSessionEventProcessor::processCtcpEvent(CtcpEvent *e)
1301 {
1302     if (e->testFlag(EventManager::Self))
1303         return;  // ignore ctcp events generated by user input
1304
1305     if (e->type() != EventManager::CtcpEvent || e->ctcpType() != CtcpEvent::Query)
1306         return;
1307
1308     handle(e->ctcpCmd(), Q_ARG(CtcpEvent *, e));
1309 }
1310
1311
1312 void CoreSessionEventProcessor::defaultHandler(const QString &ctcpCmd, CtcpEvent *e)
1313 {
1314     // This handler is only there to avoid warnings for unknown CTCPs
1315     Q_UNUSED(e);
1316     Q_UNUSED(ctcpCmd);
1317 }
1318
1319
1320 void CoreSessionEventProcessor::handleCtcpAction(CtcpEvent *e)
1321 {
1322     // This handler is only there to feed CLIENTINFO
1323     Q_UNUSED(e);
1324 }
1325
1326
1327 void CoreSessionEventProcessor::handleCtcpClientinfo(CtcpEvent *e)
1328 {
1329     QStringList supportedHandlers;
1330     foreach(QString handler, providesHandlers())
1331     supportedHandlers << handler.toUpper();
1332     qSort(supportedHandlers);
1333     e->setReply(supportedHandlers.join(" "));
1334 }
1335
1336
1337 // http://www.irchelp.org/irchelp/rfc/ctcpspec.html
1338 // http://en.wikipedia.org/wiki/Direct_Client-to-Client
1339 void CoreSessionEventProcessor::handleCtcpDcc(CtcpEvent *e)
1340 {
1341     // DCC support is unfinished, experimental and potentially dangerous, so make it opt-in
1342     if (!Quassel::isOptionSet("enable-experimental-dcc")) {
1343         quInfo() << "DCC disabled, start core with --enable-experimental-dcc if you really want to try it out";
1344         return;
1345     }
1346
1347     // normal:  SEND <filename> <ip> <port> [<filesize>]
1348     // reverse: SEND <filename> <ip> 0 <filesize> <token>
1349     QStringList params = e->param().split(' ');
1350     if (params.count()) {
1351         QString cmd = params[0].toUpper();
1352         if (cmd == "SEND") {
1353             if (params.count() < 4) {
1354                 qWarning() << "Invalid DCC SEND request:" << e;  // TODO emit proper error to client
1355                 return;
1356             }
1357             QString filename = params[1];
1358             QHostAddress address;
1359             quint16 port = params[3].toUShort();
1360             quint64 size = 0;
1361             QString numIp = params[2]; // this is either IPv4 as a 32 bit value, or IPv6 (which always contains a colon)
1362             if (numIp.contains(':')) { // IPv6
1363                 if (!address.setAddress(numIp)) {
1364                     qWarning() << "Invalid IPv6:" << numIp;
1365                     return;
1366                 }
1367             }
1368             else {
1369                 address.setAddress(numIp.toUInt());
1370             }
1371
1372             if (port == 0) { // Reverse DCC is indicated by a 0 port
1373                 emit newEvent(new MessageEvent(Message::Error, e->network(), tr("Reverse DCC SEND not supported"), e->prefix(), e->target(), Message::None, e->timestamp()));
1374                 return;
1375             }
1376             if (port < 1024) {
1377                 qWarning() << "Privileged port requested:" << port; // FIXME ask user if this is ok
1378             }
1379
1380
1381             if (params.count() > 4) { // filesize is optional
1382                 size = params[4].toULong();
1383             }
1384
1385             // TODO: check if target is the right thing to use for the partner
1386             CoreTransfer *transfer = new CoreTransfer(Transfer::Direction::Receive, e->target(), filename, address, port, size, this);
1387             coreSession()->signalProxy()->synchronize(transfer);
1388             coreSession()->transferManager()->addTransfer(transfer);
1389         }
1390         else {
1391             emit newEvent(new MessageEvent(Message::Error, e->network(), tr("DCC %1 not supported").arg(cmd), e->prefix(), e->target(), Message::None, e->timestamp()));
1392             return;
1393         }
1394     }
1395 }
1396
1397
1398 void CoreSessionEventProcessor::handleCtcpPing(CtcpEvent *e)
1399 {
1400     e->setReply(e->param().isNull() ? "" : e->param());
1401 }
1402
1403
1404 void CoreSessionEventProcessor::handleCtcpTime(CtcpEvent *e)
1405 {
1406     e->setReply(QDateTime::currentDateTime().toString());
1407 }
1408
1409
1410 void CoreSessionEventProcessor::handleCtcpVersion(CtcpEvent *e)
1411 {
1412     e->setReply(QString("Quassel IRC %1 (built on %2) -- http://www.quassel-irc.org")
1413         .arg(Quassel::buildInfo().plainVersionString).arg(Quassel::buildInfo().commitDate));
1414 }