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