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