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