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