Add support for userhost-in-names capability
[quassel.git] / src / core / coresessioneventprocessor.cpp
1 /***************************************************************************
2  *   Copyright (C) 2005-2015 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 CoreSessionEventProcessor::CoreSessionEventProcessor(CoreSession *session)
41     : BasicHandler("handleCtcp", session),
42     _coreSession(session)
43 {
44     connect(coreSession(), SIGNAL(networkDisconnected(NetworkId)), this, SLOT(destroyNetsplits(NetworkId)));
45     connect(this, SIGNAL(newEvent(Event *)), coreSession()->eventManager(), SLOT(postEvent(Event *)));
46 }
47
48
49 bool CoreSessionEventProcessor::checkParamCount(IrcEvent *e, int minParams)
50 {
51     if (e->params().count() < minParams) {
52         if (e->type() == EventManager::IrcEventNumeric) {
53             qWarning() << "Command " << static_cast<IrcEventNumeric *>(e)->number() << " requires " << minParams << "params, got: " << e->params();
54         }
55         else {
56             QString name = coreSession()->eventManager()->enumName(e->type());
57             qWarning() << qPrintable(name) << "requires" << minParams << "params, got:" << e->params();
58         }
59         e->stop();
60         return false;
61     }
62     return true;
63 }
64
65
66 void CoreSessionEventProcessor::tryNextNick(NetworkEvent *e, const QString &errnick, bool erroneus)
67 {
68     QStringList desiredNicks = coreSession()->identity(e->network()->identity())->nicks();
69     int nextNickIdx = desiredNicks.indexOf(errnick) + 1;
70     QString nextNick;
71     if (nextNickIdx > 0 && desiredNicks.size() > nextNickIdx) {
72         nextNick = desiredNicks[nextNickIdx];
73     }
74     else {
75         if (erroneus) {
76             // FIXME Make this an ErrorEvent or something like that, so it's translated in the client
77             MessageEvent *msgEvent = new MessageEvent(Message::Error, e->network(),
78                 tr("No free and valid nicks in nicklist found. use: /nick <othernick> to continue"),
79                 QString(), QString(), Message::None, e->timestamp());
80             emit newEvent(msgEvent);
81             return;
82         }
83         else {
84             nextNick = errnick + "_";
85         }
86     }
87     // FIXME Use a proper output event for this
88     coreNetwork(e)->putRawLine("NICK " + coreNetwork(e)->encodeServerString(nextNick));
89 }
90
91
92 void CoreSessionEventProcessor::processIrcEventNumeric(IrcEventNumeric *e)
93 {
94     switch (e->number()) {
95     // SASL authentication replies
96     // See: http://ircv3.net/specs/extensions/sasl-3.1.html
97     // TODO Handle errors to stop connection if appropriate
98     case 903:  // RPL_SASLSUCCESS
99     case 904:  // ERR_SASLFAIL
100     case 905:  // ERR_SASLTOOLONG
101     case 906:  // ERR_SASLABORTED
102     case 907:  // ERR_SASLALREADY
103         // Move on to the next capability
104         sendNextCap(e->network());
105         break;
106
107     default:
108         break;
109     }
110 }
111
112
113 void CoreSessionEventProcessor::processIrcEventAuthenticate(IrcEvent *e)
114 {
115     if (!checkParamCount(e, 1))
116         return;
117
118     if (e->params().at(0) != "+") {
119         qWarning() << "Invalid AUTHENTICATE" << e;
120         return;
121     }
122
123     CoreNetwork *net = coreNetwork(e);
124
125 #ifdef HAVE_SSL
126     if (net->identityPtr()->sslCert().isNull()) {
127 #endif
128         QString construct = net->saslAccount();
129         construct.append(QChar(QChar::Null));
130         construct.append(net->saslAccount());
131         construct.append(QChar(QChar::Null));
132         construct.append(net->saslPassword());
133         QByteArray saslData = QByteArray(construct.toLatin1().toBase64());
134         saslData.prepend("AUTHENTICATE ");
135         net->putRawLine(saslData);
136 #ifdef HAVE_SSL
137     } else {
138         net->putRawLine("AUTHENTICATE +");
139     }
140 #endif
141 }
142
143 void CoreSessionEventProcessor::sendNextCap(Network *net)
144 {
145     CoreNetwork *coreNet = qobject_cast<CoreNetwork *>(net);
146     if (coreNet->capNegotiationInProgress()) {
147         // Request the next capability and remove it from the list
148         // Handle one at a time so one capability failing won't NAK all of 'em
149         coreNet->putRawLine(coreNet->serverEncode(QString("CAP REQ :%1").arg(coreNet->takeQueuedCap())));
150     } else {
151         // If SASL requested but not available, print a warning
152         if (coreNet->networkInfo().useSasl && !coreNet->useCapSASL())
153             emit newEvent(new MessageEvent(Message::Error, net, tr("SASL authentication not supported by server, continuing without"), QString(), QString(), Message::None, QDateTime::currentDateTimeUtc()));
154
155         // No pending desired capabilities, end negotiation
156         coreNet->putRawLine(coreNet->serverEncode(QString("CAP END")));
157         emit newEvent(new MessageEvent(Message::Server, net, tr("Capability negotiation finished"), QString(), QString(), Message::None, QDateTime::currentDateTimeUtc()));
158     }
159 }
160
161 void CoreSessionEventProcessor::processIrcEventCap(IrcEvent *e)
162 {
163     // Handle capability negotiation
164     // See: http://ircv3.net/specs/core/capability-negotiation-3.2.html
165     // And: http://ircv3.net/specs/core/capability-negotiation-3.1.html
166     if (e->params().count() >= 3) {
167         CoreNetwork *coreNet = coreNetwork(e);
168         if (e->params().at(1).compare("LS", Qt::CaseInsensitive) == 0) {
169             // Server: CAP * LS * :multi-prefix extended-join account-notify batch invite-notify tls
170             // Server: CAP * LS * :cap-notify server-time example.org/dummy-cap=dummyvalue example.org/second-dummy-cap
171             // Server: CAP * LS :userhost-in-names sasl=EXTERNAL,DH-AES,DH-BLOWFISH,ECDSA-NIST256P-CHALLENGE,PLAIN
172             bool capListFinished;
173             QStringList availableCaps;
174             if (e->params().count() == 4) {
175                 // Middle of multi-line reply, ignore the asterisk
176                 capListFinished = false;
177                 availableCaps = e->params().at(3).split(' ');
178             } else {
179                 // Single line reply
180                 capListFinished = true;
181                 availableCaps = e->params().at(2).split(' ');
182             }
183             // We know what capabilities are available, request what we want.
184             QStringList availableCapPair;
185             bool queueCurrentCap;
186             for (int i = 0; i < availableCaps.count(); ++i) {
187                 // Capability may include values, e.g. CAP * LS :multi-prefix sasl=EXTERNAL
188                 availableCapPair = availableCaps[i].trimmed().split('=');
189                 queueCurrentCap = false;
190                 if (availableCapPair.at(0).startsWith("sasl")) {
191                     // Only request SASL if it's enabled
192                     if (coreNet->networkInfo().useSasl)
193                         queueCurrentCap = true;
194                 } else if (availableCapPair.at(0).startsWith("away-notify") ||
195                            availableCapPair.at(0).startsWith("account-notify") ||
196                            availableCapPair.at(0).startsWith("extended-join") ||
197                            availableCapPair.at(0).startsWith("userhost-in-names")) {
198                     // Always request these capabilities if available
199                     queueCurrentCap = true;
200                 }
201                 if (queueCurrentCap) {
202                     if(availableCapPair.count() >= 2)
203                         coreNet->queuePendingCap(availableCapPair.at(0).trimmed(), availableCapPair.at(1).trimmed());
204                     else
205                         coreNet->queuePendingCap(availableCapPair.at(0).trimmed());
206                 }
207             }
208             // Begin capability requests when capability listing complete
209             if (capListFinished) {
210                 emit newEvent(new MessageEvent(Message::Server, e->network(), tr("Negotiating capabilities..."), QString(), QString(), Message::None, e->timestamp()));
211                 sendNextCap(coreNet);
212             }
213         } else if (e->params().at(1).compare("ACK", Qt::CaseInsensitive) == 0) {
214             // Server: CAP * ACK :multi-prefix sasl
215             // Got the capability we want, enable, handle as needed.
216             // As only one capability is requested at a time, no need to split
217             // Lower-case the list to make later comparisons easier
218             // Capability may include values, e.g. CAP * LS :multi-prefix sasl=EXTERNAL
219             QStringList acceptedCap = e->params().at(2).trimmed().split('=');
220
221             // Mark this cap as accepted
222             if(acceptedCap.count() >= 2)
223                 coreNet->addCap(acceptedCap.at(0), acceptedCap.at(1));
224             else
225                 coreNet->addCap(acceptedCap.at(0));
226
227             // Handle special cases
228             if (acceptedCap.at(0).startsWith("sasl")) {
229                 // Freenode (at least) sends "sasl " with a trailing space for some reason!
230                 // if the current identity has a cert set, use SASL EXTERNAL
231                 // FIXME use event
232                 // TODO If value of sasl capability is not empty, limit to accepted
233 #ifdef HAVE_SSL
234                 if (!coreNet->identityPtr()->sslCert().isNull()) {
235                     coreNet->putRawLine(coreNet->serverEncode("AUTHENTICATE EXTERNAL"));
236                 } else {
237 #endif
238                     // Only working with PLAIN atm, blowfish later
239                     coreNet->putRawLine(coreNet->serverEncode("AUTHENTICATE PLAIN"));
240 #ifdef HAVE_SSL
241                 }
242 #endif
243             } else {
244                 // Special handling not needed, move on to next cap
245                 sendNextCap(coreNet);
246             }
247         } else if (e->params().at(1).compare("NAK", Qt::CaseInsensitive) == 0) {
248             // Something went wrong with this capability, disable, go to next cap
249             // As only one capability is requested at a time, no need to split
250             // Lower-case the list to make later comparisons easier
251             QString deniedCap = e->params().at(2).trimmed();
252             coreNet->removeCap(deniedCap);
253             sendNextCap(coreNet);
254         }
255     }
256 }
257
258 /* IRCv3 account-notify
259  * Log in:  ":nick!user@host ACCOUNT accountname"
260  * Log out: ":nick!user@host ACCOUNT *" */
261 void CoreSessionEventProcessor::processIrcEventAccount(IrcEvent *e)
262 {
263     if (!checkParamCount(e, 1))
264         return;
265
266     IrcUser *ircuser = e->network()->updateNickFromMask(e->prefix());
267     if (ircuser) {
268         // FIXME Keep track of authed user account, requires adding support to ircuser.h/cpp
269         /*
270         if (e->params().at(0) != "*") {
271             // Account logged in
272             qDebug() << "account-notify:" << ircuser->nick() << "logged in to" << e->params().at(0);
273         } else {
274             // Account logged out
275             qDebug() << "account-notify:" << ircuser->nick() << "logged out";
276         }
277         */
278     } else {
279         qDebug() << "Received account-notify data for unknown user" << e->prefix();
280     }
281 }
282
283 /* IRCv3 away-notify - ":nick!user@host AWAY [:message]" */
284 void CoreSessionEventProcessor::processIrcEventAway(IrcEvent *e)
285 {
286     if (!checkParamCount(e, 2))
287         return;
288
289     // Nick is sent as part of parameters in order to split user/server decoding
290     IrcUser *ircuser = e->network()->ircUser(e->params().at(0));
291     if (ircuser) {
292         if (!e->params().at(1).isEmpty()) {
293             ircuser->setAway(true);
294             ircuser->setAwayMessage(e->params().at(1));
295         } else {
296             ircuser->setAway(false);
297         }
298     } else {
299         qDebug() << "Received away-notify data for unknown user" << e->params().at(0);
300     }
301 }
302
303 void CoreSessionEventProcessor::processIrcEventInvite(IrcEvent *e)
304 {
305     if (checkParamCount(e, 2)) {
306         e->network()->updateNickFromMask(e->prefix());
307     }
308 }
309
310
311 void CoreSessionEventProcessor::processIrcEventJoin(IrcEvent *e)
312 {
313     if (e->testFlag(EventManager::Fake)) // generated by handleEarlyNetsplitJoin
314         return;
315
316     if (!checkParamCount(e, 1))
317         return;
318
319     CoreNetwork *net = coreNetwork(e);
320     QString channel = e->params()[0];
321     IrcUser *ircuser = net->updateNickFromMask(e->prefix());
322
323     if (net->useCapExtendedJoin()) {
324         if (!checkParamCount(e, 3))
325             return;
326         // If logged in, :nick!user@host JOIN #channelname accountname :Real Name
327         // If logged out, :nick!user@host JOIN #channelname * :Real Name
328         // See:  http://ircv3.net/specs/extensions/extended-join-3.1.html
329         // FIXME Keep track of authed user account, requires adding support to ircuser.h/cpp
330         ircuser->setRealName(e->params()[2]);
331     }
332     // Else :nick!user@host JOIN #channelname
333
334     bool handledByNetsplit = false;
335     foreach(Netsplit* n, _netsplits.value(e->network())) {
336         handledByNetsplit = n->userJoined(e->prefix(), channel);
337         if (handledByNetsplit)
338             break;
339     }
340
341     // If using away-notify, check new users.  Works around buggy IRC servers
342     // forgetting to send :away messages for users who join channels when away.
343     if (coreNetwork(e)->useCapAwayNotify()) {
344         coreNetwork(e)->queueAutoWhoOneshot(ircuser->nick());
345     }
346
347     if (!handledByNetsplit)
348         ircuser->joinChannel(channel);
349     else
350         e->setFlag(EventManager::Netsplit);
351
352     if (net->isMe(ircuser)) {
353         net->setChannelJoined(channel);
354         // FIXME use event
355         net->putRawLine(net->serverEncode("MODE " + channel)); // we want to know the modes of the channel we just joined, so we ask politely
356     }
357 }
358
359
360 void CoreSessionEventProcessor::lateProcessIrcEventKick(IrcEvent *e)
361 {
362     if (checkParamCount(e, 2)) {
363         e->network()->updateNickFromMask(e->prefix());
364         IrcUser *victim = e->network()->ircUser(e->params().at(1));
365         if (victim) {
366             victim->partChannel(e->params().at(0));
367             //if(e->network()->isMe(victim)) e->network()->setKickedFromChannel(channel);
368         }
369     }
370 }
371
372
373 void CoreSessionEventProcessor::processIrcEventMode(IrcEvent *e)
374 {
375     if (!checkParamCount(e, 2))
376         return;
377
378     if (e->network()->isChannelName(e->params().first())) {
379         // Channel Modes
380
381         IrcChannel *channel = e->network()->ircChannel(e->params()[0]);
382         if (!channel) {
383             // we received mode information for a channel we're not in. that means probably we've just been kicked out or something like that
384             // anyways: we don't have a place to store the data --> discard the info.
385             return;
386         }
387
388         QString modes = e->params()[1];
389         bool add = true;
390         int paramOffset = 2;
391         for (int c = 0; c < modes.length(); c++) {
392             if (modes[c] == '+') {
393                 add = true;
394                 continue;
395             }
396             if (modes[c] == '-') {
397                 add = false;
398                 continue;
399             }
400
401             if (e->network()->prefixModes().contains(modes[c])) {
402                 // user channel modes (op, voice, etc...)
403                 if (paramOffset < e->params().count()) {
404                     IrcUser *ircUser = e->network()->ircUser(e->params()[paramOffset]);
405                     if (!ircUser) {
406                         qWarning() << Q_FUNC_INFO << "Unknown IrcUser:" << e->params()[paramOffset];
407                     }
408                     else {
409                         if (add) {
410                             bool handledByNetsplit = false;
411                             QHash<QString, Netsplit *> splits = _netsplits.value(e->network());
412                             foreach(Netsplit* n, _netsplits.value(e->network())) {
413                                 handledByNetsplit = n->userAlreadyJoined(ircUser->hostmask(), channel->name());
414                                 if (handledByNetsplit) {
415                                     n->addMode(ircUser->hostmask(), channel->name(), QString(modes[c]));
416                                     break;
417                                 }
418                             }
419                             if (!handledByNetsplit)
420                                 channel->addUserMode(ircUser, QString(modes[c]));
421                         }
422                         else
423                             channel->removeUserMode(ircUser, QString(modes[c]));
424                     }
425                 }
426                 else {
427                     qWarning() << "Received MODE with too few parameters:" << e->params();
428                 }
429                 ++paramOffset;
430             }
431             else {
432                 // regular channel modes
433                 QString value;
434                 Network::ChannelModeType modeType = e->network()->channelModeType(modes[c]);
435                 if (modeType == Network::A_CHANMODE || modeType == Network::B_CHANMODE || (modeType == Network::C_CHANMODE && add)) {
436                     if (paramOffset < e->params().count()) {
437                         value = e->params()[paramOffset];
438                     }
439                     else {
440                         qWarning() << "Received MODE with too few parameters:" << e->params();
441                     }
442                     ++paramOffset;
443                 }
444
445                 if (add)
446                     channel->addChannelMode(modes[c], value);
447                 else
448                     channel->removeChannelMode(modes[c], value);
449             }
450         }
451     }
452     else {
453         // pure User Modes
454         IrcUser *ircUser = e->network()->newIrcUser(e->params().first());
455         QString modeString(e->params()[1]);
456         QString addModes;
457         QString removeModes;
458         bool add = false;
459         for (int c = 0; c < modeString.count(); c++) {
460             if (modeString[c] == '+') {
461                 add = true;
462                 continue;
463             }
464             if (modeString[c] == '-') {
465                 add = false;
466                 continue;
467             }
468             if (add)
469                 addModes += modeString[c];
470             else
471                 removeModes += modeString[c];
472         }
473         if (!addModes.isEmpty())
474             ircUser->addUserModes(addModes);
475         if (!removeModes.isEmpty())
476             ircUser->removeUserModes(removeModes);
477
478         if (e->network()->isMe(ircUser)) {
479             coreNetwork(e)->updatePersistentModes(addModes, removeModes);
480         }
481     }
482 }
483
484
485 void CoreSessionEventProcessor::lateProcessIrcEventNick(IrcEvent *e)
486 {
487     if (checkParamCount(e, 1)) {
488         IrcUser *ircuser = e->network()->updateNickFromMask(e->prefix());
489         if (!ircuser) {
490             qWarning() << Q_FUNC_INFO << "Unknown IrcUser!";
491             return;
492         }
493         QString newnick = e->params().at(0);
494         QString oldnick = ircuser->nick();
495
496         // the order is cruicial
497         // otherwise the client would rename the buffer, see that the assigned ircuser doesn't match anymore
498         // and remove the ircuser from the querybuffer leading to a wrong on/offline state
499         ircuser->setNick(newnick);
500         coreSession()->renameBuffer(e->networkId(), newnick, oldnick);
501     }
502 }
503
504
505 void CoreSessionEventProcessor::lateProcessIrcEventPart(IrcEvent *e)
506 {
507     if (checkParamCount(e, 1)) {
508         IrcUser *ircuser = e->network()->updateNickFromMask(e->prefix());
509         if (!ircuser) {
510             qWarning() << Q_FUNC_INFO<< "Unknown IrcUser!";
511             return;
512         }
513         QString channel = e->params().at(0);
514         ircuser->partChannel(channel);
515         if (e->network()->isMe(ircuser))
516             qobject_cast<CoreNetwork *>(e->network())->setChannelParted(channel);
517     }
518 }
519
520
521 void CoreSessionEventProcessor::processIrcEventPing(IrcEvent *e)
522 {
523     QString param = e->params().count() ? e->params().first() : QString();
524     // FIXME use events
525     coreNetwork(e)->putRawLine("PONG " + coreNetwork(e)->serverEncode(param));
526 }
527
528
529 void CoreSessionEventProcessor::processIrcEventPong(IrcEvent *e)
530 {
531     // the server is supposed to send back what we passed as param. and we send a timestamp
532     // but using quote and whatnought one can send arbitrary pings, so we have to do some sanity checks
533     if (checkParamCount(e, 2)) {
534         QString timestamp = e->params().at(1);
535         QTime sendTime = QTime::fromString(timestamp, "hh:mm:ss.zzz");
536         if (sendTime.isValid())
537             e->network()->setLatency(sendTime.msecsTo(QTime::currentTime()) / 2);
538     }
539 }
540
541
542 void CoreSessionEventProcessor::processIrcEventQuit(IrcEvent *e)
543 {
544     IrcUser *ircuser = e->network()->updateNickFromMask(e->prefix());
545     if (!ircuser)
546         return;
547
548     QString msg;
549     if (e->params().count() > 0)
550         msg = e->params()[0];
551
552     // check if netsplit
553     if (Netsplit::isNetsplit(msg)) {
554         Netsplit *n;
555         if (!_netsplits[e->network()].contains(msg)) {
556             n = new Netsplit(e->network(), this);
557             connect(n, SIGNAL(finished()), this, SLOT(handleNetsplitFinished()));
558             connect(n, SIGNAL(netsplitJoin(Network*, QString, QStringList, QStringList, QString)),
559                 this, SLOT(handleNetsplitJoin(Network*, QString, QStringList, QStringList, QString)));
560             connect(n, SIGNAL(netsplitQuit(Network*, QString, QStringList, QString)),
561                 this, SLOT(handleNetsplitQuit(Network*, QString, QStringList, QString)));
562             connect(n, SIGNAL(earlyJoin(Network*, QString, QStringList, QStringList)),
563                 this, SLOT(handleEarlyNetsplitJoin(Network*, QString, QStringList, QStringList)));
564             _netsplits[e->network()].insert(msg, n);
565         }
566         else {
567             n = _netsplits[e->network()][msg];
568         }
569         // add this user to the netsplit
570         n->userQuit(e->prefix(), ircuser->channels(), msg);
571         e->setFlag(EventManager::Netsplit);
572     }
573     // normal quit is handled in lateProcessIrcEventQuit()
574 }
575
576
577 void CoreSessionEventProcessor::lateProcessIrcEventQuit(IrcEvent *e)
578 {
579     if (e->testFlag(EventManager::Netsplit))
580         return;
581
582     IrcUser *ircuser = e->network()->updateNickFromMask(e->prefix());
583     if (!ircuser)
584         return;
585
586     ircuser->quit();
587 }
588
589
590 void CoreSessionEventProcessor::processIrcEventTopic(IrcEvent *e)
591 {
592     if (checkParamCount(e, 2)) {
593         e->network()->updateNickFromMask(e->prefix());
594         IrcChannel *channel = e->network()->ircChannel(e->params().at(0));
595         if (channel)
596             channel->setTopic(e->params().at(1));
597     }
598 }
599
600
601 #ifdef HAVE_QCA2
602 void CoreSessionEventProcessor::processKeyEvent(KeyEvent *e)
603 {
604     if (!Cipher::neededFeaturesAvailable()) {
605         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()));
606         return;
607     }
608     CoreNetwork *net = qobject_cast<CoreNetwork*>(e->network());
609     Cipher *c = net->cipher(e->target());
610     if (!c) // happens when there is no CoreIrcChannel for the target (i.e. never?)
611         return;
612
613     if (e->exchangeType() == KeyEvent::Init) {
614         QByteArray pubKey = c->parseInitKeyX(e->key());
615         if (pubKey.isEmpty()) {
616             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()));
617             return;
618         } else {
619             net->setCipherKey(e->target(), c->key());
620             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()));
621             QList<QByteArray> p;
622             p << net->serverEncode(e->target()) << net->serverEncode("DH1080_FINISH ")+pubKey;
623             net->putCmd("NOTICE", p);
624         }
625     } else {
626         if (c->parseFinishKeyX(e->key())) {
627             net->setCipherKey(e->target(), c->key());
628             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()));
629         } else {
630             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()));
631         }
632     }
633 }
634 #endif
635
636
637 /* RPL_WELCOME */
638 void CoreSessionEventProcessor::processIrcEvent001(IrcEventNumeric *e)
639 {
640     e->network()->setCurrentServer(e->prefix());
641     e->network()->setMyNick(e->target());
642 }
643
644
645 /* RPL_ISUPPORT */
646 // TODO Complete 005 handling, also use sensible defaults for non-sent stuff
647 void CoreSessionEventProcessor::processIrcEvent005(IrcEvent *e)
648 {
649     if (!checkParamCount(e, 1))
650         return;
651
652     QString key, value;
653     for (int i = 0; i < e->params().count() - 1; i++) {
654         QString key = e->params()[i].section("=", 0, 0);
655         QString value = e->params()[i].section("=", 1);
656         e->network()->addSupport(key, value);
657     }
658
659     /* determine our prefixes here to get an accurate result */
660     e->network()->determinePrefixes();
661 }
662
663
664 /* RPL_UMODEIS - "<user_modes> [<user_mode_params>]" */
665 void CoreSessionEventProcessor::processIrcEvent221(IrcEvent *)
666 {
667     // TODO: save information in network object
668 }
669
670
671 /* RPL_STATSCONN - "Highest connection cout: 8000 (7999 clients)" */
672 void CoreSessionEventProcessor::processIrcEvent250(IrcEvent *)
673 {
674     // TODO: save information in network object
675 }
676
677
678 /* RPL_LOCALUSERS - "Current local user: 5024  Max: 7999 */
679 void CoreSessionEventProcessor::processIrcEvent265(IrcEvent *)
680 {
681     // TODO: save information in network object
682 }
683
684
685 /* RPL_GLOBALUSERS - "Current global users: 46093  Max: 47650" */
686 void CoreSessionEventProcessor::processIrcEvent266(IrcEvent *)
687 {
688     // TODO: save information in network object
689 }
690
691
692 /*
693 WHOIS-Message:
694    Replies 311 - 313, 317 - 319 are all replies generated in response to a WHOIS message.
695   and 301 (RPL_AWAY)
696               "<nick> :<away message>"
697 WHO-Message:
698    Replies 352 and 315 paired are used to answer a WHO message.
699
700 WHOWAS-Message:
701    Replies 314 and 369 are responses to a WHOWAS message.
702
703 */
704
705 /* RPL_AWAY - "<nick> :<away message>" */
706 void CoreSessionEventProcessor::processIrcEvent301(IrcEvent *e)
707 {
708     if (!checkParamCount(e, 2))
709         return;
710
711     IrcUser *ircuser = e->network()->ircUser(e->params().at(0));
712     if (ircuser) {
713         ircuser->setAway(true);
714         ircuser->setAwayMessage(e->params().at(1));
715         //ircuser->setLastAwayMessage(now);
716     }
717 }
718
719
720 /* RPL_UNAWAY - ":You are no longer marked as being away" */
721 void CoreSessionEventProcessor::processIrcEvent305(IrcEvent *e)
722 {
723     IrcUser *me = e->network()->me();
724     if (me)
725         me->setAway(false);
726
727     if (e->network()->autoAwayActive()) {
728         e->network()->setAutoAwayActive(false);
729         e->setFlag(EventManager::Silent);
730     }
731 }
732
733
734 /* RPL_NOWAWAY - ":You have been marked as being away" */
735 void CoreSessionEventProcessor::processIrcEvent306(IrcEvent *e)
736 {
737     IrcUser *me = e->network()->me();
738     if (me)
739         me->setAway(true);
740 }
741
742
743 /* RPL_WHOISSERVICE - "<user> is registered nick" */
744 void CoreSessionEventProcessor::processIrcEvent307(IrcEvent *e)
745 {
746     if (!checkParamCount(e, 1))
747         return;
748
749     IrcUser *ircuser = e->network()->ircUser(e->params().at(0));
750     if (ircuser)
751         ircuser->setWhoisServiceReply(e->params().join(" "));
752 }
753
754
755 /* RPL_SUSERHOST - "<user> is available for help." */
756 void CoreSessionEventProcessor::processIrcEvent310(IrcEvent *e)
757 {
758     if (!checkParamCount(e, 1))
759         return;
760
761     IrcUser *ircuser = e->network()->ircUser(e->params().at(0));
762     if (ircuser)
763         ircuser->setSuserHost(e->params().join(" "));
764 }
765
766
767 /*  RPL_WHOISUSER - "<nick> <user> <host> * :<real name>" */
768 void CoreSessionEventProcessor::processIrcEvent311(IrcEvent *e)
769 {
770     if (!checkParamCount(e, 3))
771         return;
772
773     IrcUser *ircuser = e->network()->ircUser(e->params().at(0));
774     if (ircuser) {
775         ircuser->setUser(e->params().at(1));
776         ircuser->setHost(e->params().at(2));
777         ircuser->setRealName(e->params().last());
778     }
779 }
780
781
782 /*  RPL_WHOISSERVER -  "<nick> <server> :<server info>" */
783 void CoreSessionEventProcessor::processIrcEvent312(IrcEvent *e)
784 {
785     if (!checkParamCount(e, 2))
786         return;
787
788     IrcUser *ircuser = e->network()->ircUser(e->params().at(0));
789     if (ircuser)
790         ircuser->setServer(e->params().at(1));
791 }
792
793
794 /*  RPL_WHOISOPERATOR - "<nick> :is an IRC operator" */
795 void CoreSessionEventProcessor::processIrcEvent313(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->setIrcOperator(e->params().last());
803 }
804
805
806 /*  RPL_ENDOFWHO: "<name> :End of WHO list" */
807 void CoreSessionEventProcessor::processIrcEvent315(IrcEvent *e)
808 {
809     if (!checkParamCount(e, 1))
810         return;
811
812     if (coreNetwork(e)->setAutoWhoDone(e->params()[0]))
813         e->setFlag(EventManager::Silent);
814 }
815
816
817 /*  RPL_WHOISIDLE - "<nick> <integer> :seconds idle"
818    (real life: "<nick> <integer> <integer> :seconds idle, signon time) */
819 void CoreSessionEventProcessor::processIrcEvent317(IrcEvent *e)
820 {
821     if (!checkParamCount(e, 2))
822         return;
823
824     QDateTime loginTime;
825
826     int idleSecs = e->params()[1].toInt();
827     if (e->params().count() > 3) { // if we have more then 3 params we have the above mentioned "real life" situation
828         int logintime = e->params()[2].toInt();
829         loginTime = QDateTime::fromTime_t(logintime);
830     }
831
832     IrcUser *ircuser = e->network()->ircUser(e->params()[0]);
833     if (ircuser) {
834         ircuser->setIdleTime(e->timestamp().addSecs(-idleSecs));
835         if (loginTime.isValid())
836             ircuser->setLoginTime(loginTime);
837     }
838 }
839
840
841 /* RPL_LIST -  "<channel> <# visible> :<topic>" */
842 void CoreSessionEventProcessor::processIrcEvent322(IrcEvent *e)
843 {
844     if (!checkParamCount(e, 1))
845         return;
846
847     QString channelName;
848     quint32 userCount = 0;
849     QString topic;
850
851     switch (e->params().count()) {
852     case 3:
853         topic = e->params()[2];
854     case 2:
855         userCount = e->params()[1].toUInt();
856     case 1:
857         channelName = e->params()[0];
858     default:
859         break;
860     }
861     if (coreSession()->ircListHelper()->addChannel(e->networkId(), channelName, userCount, topic))
862         e->stop();  // consumed by IrcListHelper, so don't further process/show this event
863 }
864
865
866 /* RPL_LISTEND ":End of LIST" */
867 void CoreSessionEventProcessor::processIrcEvent323(IrcEvent *e)
868 {
869     if (!checkParamCount(e, 1))
870         return;
871
872     if (coreSession()->ircListHelper()->endOfChannelList(e->networkId()))
873         e->stop();  // consumed by IrcListHelper, so don't further process/show this event
874 }
875
876
877 /* RPL_CHANNELMODEIS - "<channel> <mode> <mode params>" */
878 void CoreSessionEventProcessor::processIrcEvent324(IrcEvent *e)
879 {
880     processIrcEventMode(e);
881 }
882
883
884 /* RPL_NOTOPIC */
885 void CoreSessionEventProcessor::processIrcEvent331(IrcEvent *e)
886 {
887     if (!checkParamCount(e, 1))
888         return;
889
890     IrcChannel *chan = e->network()->ircChannel(e->params()[0]);
891     if (chan)
892         chan->setTopic(QString());
893 }
894
895
896 /* RPL_TOPIC */
897 void CoreSessionEventProcessor::processIrcEvent332(IrcEvent *e)
898 {
899     if (!checkParamCount(e, 2))
900         return;
901
902     IrcChannel *chan = e->network()->ircChannel(e->params()[0]);
903     if (chan)
904         chan->setTopic(e->params()[1]);
905 }
906
907
908 /*  RPL_WHOREPLY: "<channel> <user> <host> <server> <nick>
909               ( "H" / "G" > ["*"] [ ( "@" / "+" ) ] :<hopcount> <real name>" */
910 void CoreSessionEventProcessor::processIrcEvent352(IrcEvent *e)
911 {
912     if (!checkParamCount(e, 6))
913         return;
914
915     QString channel = e->params()[0];
916     IrcUser *ircuser = e->network()->ircUser(e->params()[4]);
917     if (ircuser) {
918         ircuser->setUser(e->params()[1]);
919         ircuser->setHost(e->params()[2]);
920
921         bool away = e->params()[5].startsWith("G");
922         ircuser->setAway(away);
923         ircuser->setServer(e->params()[3]);
924         ircuser->setRealName(e->params().last().section(" ", 1));
925     }
926
927     // Check if channel name has a who in progress.
928     // If not, then check if user nick exists and has a who in progress.
929     if (coreNetwork(e)->isAutoWhoInProgress(channel) ||
930         (ircuser && coreNetwork(e)->isAutoWhoInProgress(ircuser->nick()))) {
931         e->setFlag(EventManager::Silent);
932     }
933 }
934
935
936 /* RPL_NAMREPLY */
937 void CoreSessionEventProcessor::processIrcEvent353(IrcEvent *e)
938 {
939     if (!checkParamCount(e, 3))
940         return;
941
942     // param[0] is either "=", "*" or "@" indicating a public, private or secret channel
943     // we don't use this information at the time beeing
944     QString channelname = e->params()[1];
945
946     IrcChannel *channel = e->network()->ircChannel(channelname);
947     if (!channel) {
948         qWarning() << Q_FUNC_INFO << "Received unknown target channel:" << channelname;
949         return;
950     }
951
952     QStringList nicks;
953     QStringList modes;
954
955     foreach(QString nick, e->params()[2].split(' ', QString::SkipEmptyParts)) {
956         QString mode;
957
958         if (e->network()->prefixes().contains(nick[0])) {
959             mode = e->network()->prefixToMode(nick[0]);
960             nick = nick.mid(1);
961         }
962
963         // If userhost-in-names capability is enabled, the following will be
964         // in the form "nick!user@host" rather than "nick".  This works without
965         // special handling as the following use nickFromHost() as needed.
966         // See: http://ircv3.net/specs/extensions/userhost-in-names-3.2.html
967
968         nicks << nick;
969         modes << mode;
970     }
971
972     channel->joinIrcUsers(nicks, modes);
973 }
974
975
976 /* ERR_ERRONEUSNICKNAME */
977 void CoreSessionEventProcessor::processIrcEvent432(IrcEventNumeric *e)
978 {
979     if (!checkParamCount(e, 1))
980         return;
981
982     QString errnick;
983     if (e->params().count() < 2) {
984         // handle unreal-ircd bug, where unreal ircd doesnt supply a TARGET in ERR_ERRONEUSNICKNAME during registration phase:
985         // nick @@@
986         // :irc.scortum.moep.net 432  @@@ :Erroneous Nickname: Illegal characters
987         // correct server reply:
988         // :irc.scortum.moep.net 432 * @@@ :Erroneous Nickname: Illegal characters
989         e->params().prepend(e->target());
990         e->setTarget("*");
991     }
992     errnick = e->params()[0];
993
994     tryNextNick(e, errnick, true /* erroneus */);
995 }
996
997
998 /* ERR_NICKNAMEINUSE */
999 void CoreSessionEventProcessor::processIrcEvent433(IrcEventNumeric *e)
1000 {
1001     if (!checkParamCount(e, 1))
1002         return;
1003
1004     QString errnick = e->params().first();
1005
1006     // if there is a problem while connecting to the server -> we handle it
1007     // but only if our connection has not been finished yet...
1008     if (!e->network()->currentServer().isEmpty())
1009         return;
1010
1011     tryNextNick(e, errnick);
1012 }
1013
1014
1015 /* ERR_UNAVAILRESOURCE */
1016 void CoreSessionEventProcessor::processIrcEvent437(IrcEventNumeric *e)
1017 {
1018     if (!checkParamCount(e, 1))
1019         return;
1020
1021     QString errnick = e->params().first();
1022
1023     // if there is a problem while connecting to the server -> we handle it
1024     // but only if our connection has not been finished yet...
1025     if (!e->network()->currentServer().isEmpty())
1026         return;
1027
1028     if (!e->network()->isChannelName(errnick))
1029         tryNextNick(e, errnick);
1030 }
1031
1032
1033 /* template
1034 void CoreSessionEventProcessor::processIrcEvent(IrcEvent *e) {
1035   if(!checkParamCount(e, 1))
1036     return;
1037
1038 }
1039 */
1040
1041 /* Handle signals from Netsplit objects  */
1042
1043 void CoreSessionEventProcessor::handleNetsplitJoin(Network *net,
1044     const QString &channel,
1045     const QStringList &users,
1046     const QStringList &modes,
1047     const QString &quitMessage)
1048 {
1049     IrcChannel *ircChannel = net->ircChannel(channel);
1050     if (!ircChannel) {
1051         return;
1052     }
1053     QList<IrcUser *> ircUsers;
1054     QStringList newModes = modes;
1055     QStringList newUsers = users;
1056
1057     foreach(const QString &user, users) {
1058         IrcUser *iu = net->ircUser(nickFromMask(user));
1059         if (iu)
1060             ircUsers.append(iu);
1061         else { // the user already quit
1062             int idx = users.indexOf(user);
1063             newUsers.removeAt(idx);
1064             newModes.removeAt(idx);
1065         }
1066     }
1067
1068     ircChannel->joinIrcUsers(ircUsers, newModes);
1069     NetworkSplitEvent *event = new NetworkSplitEvent(EventManager::NetworkSplitJoin, net, channel, newUsers, quitMessage);
1070     emit newEvent(event);
1071 }
1072
1073
1074 void CoreSessionEventProcessor::handleNetsplitQuit(Network *net, const QString &channel, const QStringList &users, const QString &quitMessage)
1075 {
1076     NetworkSplitEvent *event = new NetworkSplitEvent(EventManager::NetworkSplitQuit, net, channel, users, quitMessage);
1077     emit newEvent(event);
1078     foreach(QString user, users) {
1079         IrcUser *iu = net->ircUser(nickFromMask(user));
1080         if (iu)
1081             iu->quit();
1082     }
1083 }
1084
1085
1086 void CoreSessionEventProcessor::handleEarlyNetsplitJoin(Network *net, const QString &channel, const QStringList &users, const QStringList &modes)
1087 {
1088     IrcChannel *ircChannel = net->ircChannel(channel);
1089     if (!ircChannel) {
1090         qDebug() << "handleEarlyNetsplitJoin(): channel " << channel << " invalid";
1091         return;
1092     }
1093     QList<NetworkEvent *> events;
1094     QList<IrcUser *> ircUsers;
1095     QStringList newModes = modes;
1096
1097     foreach(QString user, users) {
1098         IrcUser *iu = net->updateNickFromMask(user);
1099         if (iu) {
1100             ircUsers.append(iu);
1101             // fake event for scripts that consume join events
1102             events << new IrcEvent(EventManager::IrcEventJoin, net, iu->hostmask(), QStringList() << channel);
1103         }
1104         else {
1105             newModes.removeAt(users.indexOf(user));
1106         }
1107     }
1108     ircChannel->joinIrcUsers(ircUsers, newModes);
1109     foreach(NetworkEvent *event, events) {
1110         event->setFlag(EventManager::Fake); // ignore this in here!
1111         emit newEvent(event);
1112     }
1113 }
1114
1115
1116 void CoreSessionEventProcessor::handleNetsplitFinished()
1117 {
1118     Netsplit *n = qobject_cast<Netsplit *>(sender());
1119     Q_ASSERT(n);
1120     QHash<QString, Netsplit *> splithash  = _netsplits.take(n->network());
1121     splithash.remove(splithash.key(n));
1122     if (splithash.count())
1123         _netsplits[n->network()] = splithash;
1124     n->deleteLater();
1125 }
1126
1127
1128 void CoreSessionEventProcessor::destroyNetsplits(NetworkId netId)
1129 {
1130     Network *net = coreSession()->network(netId);
1131     if (!net)
1132         return;
1133
1134     QHash<QString, Netsplit *> splits = _netsplits.take(net);
1135     qDeleteAll(splits);
1136 }
1137
1138
1139 /*******************************/
1140 /******** CTCP HANDLING ********/
1141 /*******************************/
1142
1143 void CoreSessionEventProcessor::processCtcpEvent(CtcpEvent *e)
1144 {
1145     if (e->testFlag(EventManager::Self))
1146         return;  // ignore ctcp events generated by user input
1147
1148     if (e->type() != EventManager::CtcpEvent || e->ctcpType() != CtcpEvent::Query)
1149         return;
1150
1151     handle(e->ctcpCmd(), Q_ARG(CtcpEvent *, e));
1152 }
1153
1154
1155 void CoreSessionEventProcessor::defaultHandler(const QString &ctcpCmd, CtcpEvent *e)
1156 {
1157     // This handler is only there to avoid warnings for unknown CTCPs
1158     Q_UNUSED(e);
1159     Q_UNUSED(ctcpCmd);
1160 }
1161
1162
1163 void CoreSessionEventProcessor::handleCtcpAction(CtcpEvent *e)
1164 {
1165     // This handler is only there to feed CLIENTINFO
1166     Q_UNUSED(e);
1167 }
1168
1169
1170 void CoreSessionEventProcessor::handleCtcpClientinfo(CtcpEvent *e)
1171 {
1172     QStringList supportedHandlers;
1173     foreach(QString handler, providesHandlers())
1174     supportedHandlers << handler.toUpper();
1175     qSort(supportedHandlers);
1176     e->setReply(supportedHandlers.join(" "));
1177 }
1178
1179
1180 // http://www.irchelp.org/irchelp/rfc/ctcpspec.html
1181 // http://en.wikipedia.org/wiki/Direct_Client-to-Client
1182 void CoreSessionEventProcessor::handleCtcpDcc(CtcpEvent *e)
1183 {
1184     // DCC support is unfinished, experimental and potentially dangerous, so make it opt-in
1185     if (!Quassel::isOptionSet("enable-experimental-dcc")) {
1186         quInfo() << "DCC disabled, start core with --enable-experimental-dcc if you really want to try it out";
1187         return;
1188     }
1189
1190     // normal:  SEND <filename> <ip> <port> [<filesize>]
1191     // reverse: SEND <filename> <ip> 0 <filesize> <token>
1192     QStringList params = e->param().split(' ');
1193     if (params.count()) {
1194         QString cmd = params[0].toUpper();
1195         if (cmd == "SEND") {
1196             if (params.count() < 4) {
1197                 qWarning() << "Invalid DCC SEND request:" << e;  // TODO emit proper error to client
1198                 return;
1199             }
1200             QString filename = params[1];
1201             QHostAddress address;
1202             quint16 port = params[3].toUShort();
1203             quint64 size = 0;
1204             QString numIp = params[2]; // this is either IPv4 as a 32 bit value, or IPv6 (which always contains a colon)
1205             if (numIp.contains(':')) { // IPv6
1206                 if (!address.setAddress(numIp)) {
1207                     qWarning() << "Invalid IPv6:" << numIp;
1208                     return;
1209                 }
1210             }
1211             else {
1212                 address.setAddress(numIp.toUInt());
1213             }
1214
1215             if (port == 0) { // Reverse DCC is indicated by a 0 port
1216                 emit newEvent(new MessageEvent(Message::Error, e->network(), tr("Reverse DCC SEND not supported"), e->prefix(), e->target(), Message::None, e->timestamp()));
1217                 return;
1218             }
1219             if (port < 1024) {
1220                 qWarning() << "Privileged port requested:" << port; // FIXME ask user if this is ok
1221             }
1222
1223
1224             if (params.count() > 4) { // filesize is optional
1225                 size = params[4].toULong();
1226             }
1227
1228             // TODO: check if target is the right thing to use for the partner
1229             CoreTransfer *transfer = new CoreTransfer(Transfer::Receive, e->target(), filename, address, port, size, this);
1230             coreSession()->signalProxy()->synchronize(transfer);
1231             coreSession()->transferManager()->addTransfer(transfer);
1232         }
1233         else {
1234             emit newEvent(new MessageEvent(Message::Error, e->network(), tr("DCC %1 not supported").arg(cmd), e->prefix(), e->target(), Message::None, e->timestamp()));
1235             return;
1236         }
1237     }
1238 }
1239
1240
1241 void CoreSessionEventProcessor::handleCtcpPing(CtcpEvent *e)
1242 {
1243     e->setReply(e->param().isNull() ? "" : e->param());
1244 }
1245
1246
1247 void CoreSessionEventProcessor::handleCtcpTime(CtcpEvent *e)
1248 {
1249     e->setReply(QDateTime::currentDateTime().toString());
1250 }
1251
1252
1253 void CoreSessionEventProcessor::handleCtcpVersion(CtcpEvent *e)
1254 {
1255     e->setReply(QString("Quassel IRC %1 (built on %2) -- http://www.quassel-irc.org")
1256         .arg(Quassel::buildInfo().plainVersionString).arg(Quassel::buildInfo().buildDate));
1257 }