Add support for DH1080 key exchange
[quassel.git] / src / core / coresessioneventprocessor.cpp
1 /***************************************************************************
2  *   Copyright (C) 2005-2012 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 "ctcpevent.h"
27 #include "ircevent.h"
28 #include "ircuser.h"
29 #include "messageevent.h"
30 #include "netsplit.h"
31 #include "quassel.h"
32
33 #ifdef HAVE_QCA2
34 #  include "keyevent.h"
35 #endif
36
37 CoreSessionEventProcessor::CoreSessionEventProcessor(CoreSession *session)
38     : BasicHandler("handleCtcp", session),
39     _coreSession(session)
40 {
41     connect(coreSession(), SIGNAL(networkDisconnected(NetworkId)), this, SLOT(destroyNetsplits(NetworkId)));
42     connect(this, SIGNAL(newEvent(Event *)), coreSession()->eventManager(), SLOT(postEvent(Event *)));
43 }
44
45
46 bool CoreSessionEventProcessor::checkParamCount(IrcEvent *e, int minParams)
47 {
48     if (e->params().count() < minParams) {
49         if (e->type() == EventManager::IrcEventNumeric) {
50             qWarning() << "Command " << static_cast<IrcEventNumeric *>(e)->number() << " requires " << minParams << "params, got: " << e->params();
51         }
52         else {
53             QString name = coreSession()->eventManager()->enumName(e->type());
54             qWarning() << qPrintable(name) << "requires" << minParams << "params, got:" << e->params();
55         }
56         e->stop();
57         return false;
58     }
59     return true;
60 }
61
62
63 void CoreSessionEventProcessor::tryNextNick(NetworkEvent *e, const QString &errnick, bool erroneus)
64 {
65     QStringList desiredNicks = coreSession()->identity(e->network()->identity())->nicks();
66     int nextNickIdx = desiredNicks.indexOf(errnick) + 1;
67     QString nextNick;
68     if (nextNickIdx > 0 && desiredNicks.size() > nextNickIdx) {
69         nextNick = desiredNicks[nextNickIdx];
70     }
71     else {
72         if (erroneus) {
73             // FIXME Make this an ErrorEvent or something like that, so it's translated in the client
74             MessageEvent *msgEvent = new MessageEvent(Message::Error, e->network(),
75                 tr("No free and valid nicks in nicklist found. use: /nick <othernick> to continue"),
76                 QString(), QString(), Message::None, e->timestamp());
77             emit newEvent(msgEvent);
78             return;
79         }
80         else {
81             nextNick = errnick + "_";
82         }
83     }
84     // FIXME Use a proper output event for this
85     coreNetwork(e)->putRawLine("NICK " + coreNetwork(e)->encodeServerString(nextNick));
86 }
87
88
89 void CoreSessionEventProcessor::processIrcEventNumeric(IrcEventNumeric *e)
90 {
91     switch (e->number()) {
92     // CAP stuff
93     case 903:
94     case 904:
95     case 905:
96     case 906:
97     case 907:
98         qobject_cast<CoreNetwork *>(e->network())->putRawLine("CAP END");
99         break;
100
101     default:
102         break;
103     }
104 }
105
106
107 void CoreSessionEventProcessor::processIrcEventAuthenticate(IrcEvent *e)
108 {
109     if (!checkParamCount(e, 1))
110         return;
111
112     if (e->params().at(0) != "+") {
113         qWarning() << "Invalid AUTHENTICATE" << e;
114         return;
115     }
116
117     CoreNetwork *net = coreNetwork(e);
118
119     QString construct = net->saslAccount();
120     construct.append(QChar(QChar::Null));
121     construct.append(net->saslAccount());
122     construct.append(QChar(QChar::Null));
123     construct.append(net->saslPassword());
124     QByteArray saslData = QByteArray(construct.toAscii().toBase64());
125     saslData.prepend("AUTHENTICATE ");
126     net->putRawLine(saslData);
127 }
128
129
130 void CoreSessionEventProcessor::processIrcEventCap(IrcEvent *e)
131 {
132     // for SASL, there will only be a single param of 'sasl', however you can check here for
133     // additional CAP messages (ls, multi-prefix, et cetera).
134
135     if (e->params().count() == 3) {
136         if (e->params().at(2) == "sasl") {
137             // FIXME use event
138             coreNetwork(e)->putRawLine(coreNetwork(e)->serverEncode("AUTHENTICATE PLAIN")); // Only working with PLAIN atm, blowfish later
139         }
140     }
141 }
142
143
144 void CoreSessionEventProcessor::processIrcEventInvite(IrcEvent *e)
145 {
146     if (checkParamCount(e, 2)) {
147         e->network()->updateNickFromMask(e->prefix());
148     }
149 }
150
151
152 void CoreSessionEventProcessor::processIrcEventJoin(IrcEvent *e)
153 {
154     if (e->testFlag(EventManager::Fake)) // generated by handleEarlyNetsplitJoin
155         return;
156
157     if (!checkParamCount(e, 1))
158         return;
159
160     CoreNetwork *net = coreNetwork(e);
161     QString channel = e->params()[0];
162     IrcUser *ircuser = net->updateNickFromMask(e->prefix());
163
164     bool handledByNetsplit = false;
165     foreach(Netsplit* n, _netsplits.value(e->network())) {
166         handledByNetsplit = n->userJoined(e->prefix(), channel);
167         if (handledByNetsplit)
168             break;
169     }
170
171     if (!handledByNetsplit)
172         ircuser->joinChannel(channel);
173     else
174         e->setFlag(EventManager::Netsplit);
175
176     if (net->isMe(ircuser)) {
177         net->setChannelJoined(channel);
178         // FIXME use event
179         net->putRawLine(net->serverEncode("MODE " + channel)); // we want to know the modes of the channel we just joined, so we ask politely
180     }
181 }
182
183
184 void CoreSessionEventProcessor::lateProcessIrcEventKick(IrcEvent *e)
185 {
186     if (checkParamCount(e, 2)) {
187         e->network()->updateNickFromMask(e->prefix());
188         IrcUser *victim = e->network()->ircUser(e->params().at(1));
189         if (victim) {
190             victim->partChannel(e->params().at(0));
191             //if(e->network()->isMe(victim)) e->network()->setKickedFromChannel(channel);
192         }
193     }
194 }
195
196
197 void CoreSessionEventProcessor::processIrcEventMode(IrcEvent *e)
198 {
199     if (!checkParamCount(e, 2))
200         return;
201
202     if (e->network()->isChannelName(e->params().first())) {
203         // Channel Modes
204
205         IrcChannel *channel = e->network()->ircChannel(e->params()[0]);
206         if (!channel) {
207             // we received mode information for a channel we're not in. that means probably we've just been kicked out or something like that
208             // anyways: we don't have a place to store the data --> discard the info.
209             return;
210         }
211
212         QString modes = e->params()[1];
213         bool add = true;
214         int paramOffset = 2;
215         for (int c = 0; c < modes.length(); c++) {
216             if (modes[c] == '+') {
217                 add = true;
218                 continue;
219             }
220             if (modes[c] == '-') {
221                 add = false;
222                 continue;
223             }
224
225             if (e->network()->prefixModes().contains(modes[c])) {
226                 // user channel modes (op, voice, etc...)
227                 if (paramOffset < e->params().count()) {
228                     IrcUser *ircUser = e->network()->ircUser(e->params()[paramOffset]);
229                     if (!ircUser) {
230                         qWarning() << Q_FUNC_INFO << "Unknown IrcUser:" << e->params()[paramOffset];
231                     }
232                     else {
233                         if (add) {
234                             bool handledByNetsplit = false;
235                             QHash<QString, Netsplit *> splits = _netsplits.value(e->network());
236                             foreach(Netsplit* n, _netsplits.value(e->network())) {
237                                 handledByNetsplit = n->userAlreadyJoined(ircUser->hostmask(), channel->name());
238                                 if (handledByNetsplit) {
239                                     n->addMode(ircUser->hostmask(), channel->name(), QString(modes[c]));
240                                     break;
241                                 }
242                             }
243                             if (!handledByNetsplit)
244                                 channel->addUserMode(ircUser, QString(modes[c]));
245                         }
246                         else
247                             channel->removeUserMode(ircUser, QString(modes[c]));
248                     }
249                 }
250                 else {
251                     qWarning() << "Received MODE with too few parameters:" << e->params();
252                 }
253                 ++paramOffset;
254             }
255             else {
256                 // regular channel modes
257                 QString value;
258                 Network::ChannelModeType modeType = e->network()->channelModeType(modes[c]);
259                 if (modeType == Network::A_CHANMODE || modeType == Network::B_CHANMODE || (modeType == Network::C_CHANMODE && add)) {
260                     if (paramOffset < e->params().count()) {
261                         value = e->params()[paramOffset];
262                     }
263                     else {
264                         qWarning() << "Received MODE with too few parameters:" << e->params();
265                     }
266                     ++paramOffset;
267                 }
268
269                 if (add)
270                     channel->addChannelMode(modes[c], value);
271                 else
272                     channel->removeChannelMode(modes[c], value);
273             }
274         }
275     }
276     else {
277         // pure User Modes
278         IrcUser *ircUser = e->network()->newIrcUser(e->params().first());
279         QString modeString(e->params()[1]);
280         QString addModes;
281         QString removeModes;
282         bool add = false;
283         for (int c = 0; c < modeString.count(); c++) {
284             if (modeString[c] == '+') {
285                 add = true;
286                 continue;
287             }
288             if (modeString[c] == '-') {
289                 add = false;
290                 continue;
291             }
292             if (add)
293                 addModes += modeString[c];
294             else
295                 removeModes += modeString[c];
296         }
297         if (!addModes.isEmpty())
298             ircUser->addUserModes(addModes);
299         if (!removeModes.isEmpty())
300             ircUser->removeUserModes(removeModes);
301
302         if (e->network()->isMe(ircUser)) {
303             coreNetwork(e)->updatePersistentModes(addModes, removeModes);
304         }
305     }
306 }
307
308
309 void CoreSessionEventProcessor::lateProcessIrcEventNick(IrcEvent *e)
310 {
311     if (checkParamCount(e, 1)) {
312         IrcUser *ircuser = e->network()->updateNickFromMask(e->prefix());
313         if (!ircuser) {
314             qWarning() << Q_FUNC_INFO << "Unknown IrcUser!";
315             return;
316         }
317         QString newnick = e->params().at(0);
318         QString oldnick = ircuser->nick();
319
320         // the order is cruicial
321         // otherwise the client would rename the buffer, see that the assigned ircuser doesn't match anymore
322         // and remove the ircuser from the querybuffer leading to a wrong on/offline state
323         ircuser->setNick(newnick);
324         coreSession()->renameBuffer(e->networkId(), newnick, oldnick);
325     }
326 }
327
328
329 void CoreSessionEventProcessor::lateProcessIrcEventPart(IrcEvent *e)
330 {
331     if (checkParamCount(e, 1)) {
332         IrcUser *ircuser = e->network()->updateNickFromMask(e->prefix());
333         if (!ircuser) {
334             qWarning() << Q_FUNC_INFO<< "Unknown IrcUser!";
335             return;
336         }
337         QString channel = e->params().at(0);
338         ircuser->partChannel(channel);
339         if (e->network()->isMe(ircuser))
340             qobject_cast<CoreNetwork *>(e->network())->setChannelParted(channel);
341     }
342 }
343
344
345 void CoreSessionEventProcessor::processIrcEventPing(IrcEvent *e)
346 {
347     QString param = e->params().count() ? e->params().first() : QString();
348     // FIXME use events
349     coreNetwork(e)->putRawLine("PONG " + coreNetwork(e)->serverEncode(param));
350 }
351
352
353 void CoreSessionEventProcessor::processIrcEventPong(IrcEvent *e)
354 {
355     // the server is supposed to send back what we passed as param. and we send a timestamp
356     // but using quote and whatnought one can send arbitrary pings, so we have to do some sanity checks
357     if (checkParamCount(e, 2)) {
358         QString timestamp = e->params().at(1);
359         QTime sendTime = QTime::fromString(timestamp, "hh:mm:ss.zzz");
360         if (sendTime.isValid())
361             e->network()->setLatency(sendTime.msecsTo(QTime::currentTime()) / 2);
362     }
363 }
364
365
366 void CoreSessionEventProcessor::processIrcEventQuit(IrcEvent *e)
367 {
368     IrcUser *ircuser = e->network()->updateNickFromMask(e->prefix());
369     if (!ircuser)
370         return;
371
372     QString msg;
373     if (e->params().count() > 0)
374         msg = e->params()[0];
375
376     // check if netsplit
377     if (Netsplit::isNetsplit(msg)) {
378         Netsplit *n;
379         if (!_netsplits[e->network()].contains(msg)) {
380             n = new Netsplit(e->network(), this);
381             connect(n, SIGNAL(finished()), this, SLOT(handleNetsplitFinished()));
382             connect(n, SIGNAL(netsplitJoin(Network*, QString, QStringList, QStringList, QString)),
383                 this, SLOT(handleNetsplitJoin(Network*, QString, QStringList, QStringList, QString)));
384             connect(n, SIGNAL(netsplitQuit(Network*, QString, QStringList, QString)),
385                 this, SLOT(handleNetsplitQuit(Network*, QString, QStringList, QString)));
386             connect(n, SIGNAL(earlyJoin(Network*, QString, QStringList, QStringList)),
387                 this, SLOT(handleEarlyNetsplitJoin(Network*, QString, QStringList, QStringList)));
388             _netsplits[e->network()].insert(msg, n);
389         }
390         else {
391             n = _netsplits[e->network()][msg];
392         }
393         // add this user to the netsplit
394         n->userQuit(e->prefix(), ircuser->channels(), msg);
395         e->setFlag(EventManager::Netsplit);
396     }
397     // normal quit is handled in lateProcessIrcEventQuit()
398 }
399
400
401 void CoreSessionEventProcessor::lateProcessIrcEventQuit(IrcEvent *e)
402 {
403     if (e->testFlag(EventManager::Netsplit))
404         return;
405
406     IrcUser *ircuser = e->network()->updateNickFromMask(e->prefix());
407     if (!ircuser)
408         return;
409
410     ircuser->quit();
411 }
412
413
414 void CoreSessionEventProcessor::processIrcEventTopic(IrcEvent *e)
415 {
416     if (checkParamCount(e, 2)) {
417         e->network()->updateNickFromMask(e->prefix());
418         IrcChannel *channel = e->network()->ircChannel(e->params().at(0));
419         if (channel)
420             channel->setTopic(e->params().at(1));
421     }
422 }
423
424
425 #ifdef HAVE_QCA2
426 void CoreSessionEventProcessor::processKeyEvent(KeyEvent *e)
427 {
428     if (!Cipher::neededFeaturesAvailable()) {
429         emit newEvent(new MessageEvent(Message::Error, e->network(), tr("Unable to perform key exchange."), e->prefix(), e->target(), Message::None, e->timestamp()));
430         return;
431     }
432     CoreNetwork *net = qobject_cast<CoreNetwork*>(e->network());
433     Cipher *c = net->cipher(e->target());
434     if (!c) // happens when there is no CoreIrcChannel for the target (i.e. never?)
435         return;
436
437     if (e->exchangeType() == KeyEvent::Init) {
438         QByteArray pubKey = c->parseInitKeyX(e->key());
439         if (pubKey.isEmpty()) {
440             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()));
441             return;
442         } else {
443             net->setCipherKey(e->target(), c->key());
444             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()));
445             QList<QByteArray> p;
446             p << net->serverEncode(e->target()) << net->serverEncode("DH1080_FINISH ")+pubKey;
447             net->putCmd("NOTICE", p);
448         }
449     } else {
450         if (c->parseFinishKeyX(e->key())) {
451             net->setCipherKey(e->target(), c->key());
452             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()));
453         } else {
454             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()));
455         }
456     }
457 }
458 #endif
459
460
461 /* RPL_WELCOME */
462 void CoreSessionEventProcessor::processIrcEvent001(IrcEvent *e)
463 {
464     if (!checkParamCount(e, 1))
465         return;
466
467     QString myhostmask = e->params().at(0).section(' ', -1, -1);
468     e->network()->setCurrentServer(e->prefix());
469     e->network()->setMyNick(nickFromMask(myhostmask));
470 }
471
472
473 /* RPL_ISUPPORT */
474 // TODO Complete 005 handling, also use sensible defaults for non-sent stuff
475 void CoreSessionEventProcessor::processIrcEvent005(IrcEvent *e)
476 {
477     if (!checkParamCount(e, 1))
478         return;
479
480     QString key, value;
481     for (int i = 0; i < e->params().count() - 1; i++) {
482         QString key = e->params()[i].section("=", 0, 0);
483         QString value = e->params()[i].section("=", 1);
484         e->network()->addSupport(key, value);
485     }
486
487     /* determine our prefixes here to get an accurate result */
488     e->network()->determinePrefixes();
489 }
490
491
492 /* RPL_UMODEIS - "<user_modes> [<user_mode_params>]" */
493 void CoreSessionEventProcessor::processIrcEvent221(IrcEvent *)
494 {
495     // TODO: save information in network object
496 }
497
498
499 /* RPL_STATSCONN - "Highest connection cout: 8000 (7999 clients)" */
500 void CoreSessionEventProcessor::processIrcEvent250(IrcEvent *)
501 {
502     // TODO: save information in network object
503 }
504
505
506 /* RPL_LOCALUSERS - "Current local user: 5024  Max: 7999 */
507 void CoreSessionEventProcessor::processIrcEvent265(IrcEvent *)
508 {
509     // TODO: save information in network object
510 }
511
512
513 /* RPL_GLOBALUSERS - "Current global users: 46093  Max: 47650" */
514 void CoreSessionEventProcessor::processIrcEvent266(IrcEvent *)
515 {
516     // TODO: save information in network object
517 }
518
519
520 /*
521 WHOIS-Message:
522    Replies 311 - 313, 317 - 319 are all replies generated in response to a WHOIS message.
523   and 301 (RPL_AWAY)
524               "<nick> :<away message>"
525 WHO-Message:
526    Replies 352 and 315 paired are used to answer a WHO message.
527
528 WHOWAS-Message:
529    Replies 314 and 369 are responses to a WHOWAS message.
530
531 */
532
533 /* RPL_AWAY - "<nick> :<away message>" */
534 void CoreSessionEventProcessor::processIrcEvent301(IrcEvent *e)
535 {
536     if (!checkParamCount(e, 2))
537         return;
538
539     IrcUser *ircuser = e->network()->ircUser(e->params().at(0));
540     if (ircuser) {
541         ircuser->setAway(true);
542         ircuser->setAwayMessage(e->params().at(1));
543         //ircuser->setLastAwayMessage(now);
544     }
545 }
546
547
548 /* RPL_UNAWAY - ":You are no longer marked as being away" */
549 void CoreSessionEventProcessor::processIrcEvent305(IrcEvent *e)
550 {
551     IrcUser *me = e->network()->me();
552     if (me)
553         me->setAway(false);
554
555     if (e->network()->autoAwayActive()) {
556         e->network()->setAutoAwayActive(false);
557         e->setFlag(EventManager::Silent);
558     }
559 }
560
561
562 /* RPL_NOWAWAY - ":You have been marked as being away" */
563 void CoreSessionEventProcessor::processIrcEvent306(IrcEvent *e)
564 {
565     IrcUser *me = e->network()->me();
566     if (me)
567         me->setAway(true);
568 }
569
570
571 /* RPL_WHOISSERVICE - "<user> is registered nick" */
572 void CoreSessionEventProcessor::processIrcEvent307(IrcEvent *e)
573 {
574     if (!checkParamCount(e, 1))
575         return;
576
577     IrcUser *ircuser = e->network()->ircUser(e->params().at(0));
578     if (ircuser)
579         ircuser->setWhoisServiceReply(e->params().join(" "));
580 }
581
582
583 /* RPL_SUSERHOST - "<user> is available for help." */
584 void CoreSessionEventProcessor::processIrcEvent310(IrcEvent *e)
585 {
586     if (!checkParamCount(e, 1))
587         return;
588
589     IrcUser *ircuser = e->network()->ircUser(e->params().at(0));
590     if (ircuser)
591         ircuser->setSuserHost(e->params().join(" "));
592 }
593
594
595 /*  RPL_WHOISUSER - "<nick> <user> <host> * :<real name>" */
596 void CoreSessionEventProcessor::processIrcEvent311(IrcEvent *e)
597 {
598     if (!checkParamCount(e, 3))
599         return;
600
601     IrcUser *ircuser = e->network()->ircUser(e->params().at(0));
602     if (ircuser) {
603         ircuser->setUser(e->params().at(1));
604         ircuser->setHost(e->params().at(2));
605         ircuser->setRealName(e->params().last());
606     }
607 }
608
609
610 /*  RPL_WHOISSERVER -  "<nick> <server> :<server info>" */
611 void CoreSessionEventProcessor::processIrcEvent312(IrcEvent *e)
612 {
613     if (!checkParamCount(e, 2))
614         return;
615
616     IrcUser *ircuser = e->network()->ircUser(e->params().at(0));
617     if (ircuser)
618         ircuser->setServer(e->params().at(1));
619 }
620
621
622 /*  RPL_WHOISOPERATOR - "<nick> :is an IRC operator" */
623 void CoreSessionEventProcessor::processIrcEvent313(IrcEvent *e)
624 {
625     if (!checkParamCount(e, 1))
626         return;
627
628     IrcUser *ircuser = e->network()->ircUser(e->params().at(0));
629     if (ircuser)
630         ircuser->setIrcOperator(e->params().last());
631 }
632
633
634 /*  RPL_ENDOFWHO: "<name> :End of WHO list" */
635 void CoreSessionEventProcessor::processIrcEvent315(IrcEvent *e)
636 {
637     if (!checkParamCount(e, 1))
638         return;
639
640     if (coreNetwork(e)->setAutoWhoDone(e->params()[0]))
641         e->setFlag(EventManager::Silent);
642 }
643
644
645 /*  RPL_WHOISIDLE - "<nick> <integer> :seconds idle"
646    (real life: "<nick> <integer> <integer> :seconds idle, signon time) */
647 void CoreSessionEventProcessor::processIrcEvent317(IrcEvent *e)
648 {
649     if (!checkParamCount(e, 2))
650         return;
651
652     QDateTime loginTime;
653
654     int idleSecs = e->params()[1].toInt();
655     if (e->params().count() > 3) { // if we have more then 3 params we have the above mentioned "real life" situation
656         int logintime = e->params()[2].toInt();
657         loginTime = QDateTime::fromTime_t(logintime);
658     }
659
660     IrcUser *ircuser = e->network()->ircUser(e->params()[0]);
661     if (ircuser) {
662         ircuser->setIdleTime(e->timestamp().addSecs(-idleSecs));
663         if (loginTime.isValid())
664             ircuser->setLoginTime(loginTime);
665     }
666 }
667
668
669 /* RPL_LIST -  "<channel> <# visible> :<topic>" */
670 void CoreSessionEventProcessor::processIrcEvent322(IrcEvent *e)
671 {
672     if (!checkParamCount(e, 1))
673         return;
674
675     QString channelName;
676     quint32 userCount = 0;
677     QString topic;
678
679     switch (e->params().count()) {
680     case 3:
681         topic = e->params()[2];
682     case 2:
683         userCount = e->params()[1].toUInt();
684     case 1:
685         channelName = e->params()[0];
686     default:
687         break;
688     }
689     if (coreSession()->ircListHelper()->addChannel(e->networkId(), channelName, userCount, topic))
690         e->stop();  // consumed by IrcListHelper, so don't further process/show this event
691 }
692
693
694 /* RPL_LISTEND ":End of LIST" */
695 void CoreSessionEventProcessor::processIrcEvent323(IrcEvent *e)
696 {
697     if (!checkParamCount(e, 1))
698         return;
699
700     if (coreSession()->ircListHelper()->endOfChannelList(e->networkId()))
701         e->stop();  // consumed by IrcListHelper, so don't further process/show this event
702 }
703
704
705 /* RPL_CHANNELMODEIS - "<channel> <mode> <mode params>" */
706 void CoreSessionEventProcessor::processIrcEvent324(IrcEvent *e)
707 {
708     processIrcEventMode(e);
709 }
710
711
712 /* RPL_NOTOPIC */
713 void CoreSessionEventProcessor::processIrcEvent331(IrcEvent *e)
714 {
715     if (!checkParamCount(e, 1))
716         return;
717
718     IrcChannel *chan = e->network()->ircChannel(e->params()[0]);
719     if (chan)
720         chan->setTopic(QString());
721 }
722
723
724 /* RPL_TOPIC */
725 void CoreSessionEventProcessor::processIrcEvent332(IrcEvent *e)
726 {
727     if (!checkParamCount(e, 2))
728         return;
729
730     IrcChannel *chan = e->network()->ircChannel(e->params()[0]);
731     if (chan)
732         chan->setTopic(e->params()[1]);
733 }
734
735
736 /*  RPL_WHOREPLY: "<channel> <user> <host> <server> <nick>
737               ( "H" / "G" > ["*"] [ ( "@" / "+" ) ] :<hopcount> <real name>" */
738 void CoreSessionEventProcessor::processIrcEvent352(IrcEvent *e)
739 {
740     if (!checkParamCount(e, 6))
741         return;
742
743     QString channel = e->params()[0];
744     IrcUser *ircuser = e->network()->ircUser(e->params()[4]);
745     if (ircuser) {
746         ircuser->setUser(e->params()[1]);
747         ircuser->setHost(e->params()[2]);
748
749         bool away = e->params()[5].startsWith("G");
750         ircuser->setAway(away);
751         ircuser->setServer(e->params()[3]);
752         ircuser->setRealName(e->params().last().section(" ", 1));
753     }
754
755     if (coreNetwork(e)->isAutoWhoInProgress(channel))
756         e->setFlag(EventManager::Silent);
757 }
758
759
760 /* RPL_NAMREPLY */
761 void CoreSessionEventProcessor::processIrcEvent353(IrcEvent *e)
762 {
763     if (!checkParamCount(e, 3))
764         return;
765
766     // param[0] is either "=", "*" or "@" indicating a public, private or secret channel
767     // we don't use this information at the time beeing
768     QString channelname = e->params()[1];
769
770     IrcChannel *channel = e->network()->ircChannel(channelname);
771     if (!channel) {
772         qWarning() << Q_FUNC_INFO << "Received unknown target channel:" << channelname;
773         return;
774     }
775
776     QStringList nicks;
777     QStringList modes;
778
779     foreach(QString nick, e->params()[2].split(' ')) {
780         QString mode;
781
782         if (e->network()->prefixes().contains(nick[0])) {
783             mode = e->network()->prefixToMode(nick[0]);
784             nick = nick.mid(1);
785         }
786
787         nicks << nick;
788         modes << mode;
789     }
790
791     channel->joinIrcUsers(nicks, modes);
792 }
793
794
795 /* ERR_ERRONEUSNICKNAME */
796 void CoreSessionEventProcessor::processIrcEvent432(IrcEventNumeric *e)
797 {
798     if (!checkParamCount(e, 1))
799         return;
800
801     QString errnick;
802     if (e->params().count() < 2) {
803         // handle unreal-ircd bug, where unreal ircd doesnt supply a TARGET in ERR_ERRONEUSNICKNAME during registration phase:
804         // nick @@@
805         // :irc.scortum.moep.net 432  @@@ :Erroneous Nickname: Illegal characters
806         // correct server reply:
807         // :irc.scortum.moep.net 432 * @@@ :Erroneous Nickname: Illegal characters
808         e->params().prepend(e->target());
809         e->setTarget("*");
810     }
811     errnick = e->params()[0];
812
813     tryNextNick(e, errnick, true /* erroneus */);
814 }
815
816
817 /* ERR_NICKNAMEINUSE */
818 void CoreSessionEventProcessor::processIrcEvent433(IrcEventNumeric *e)
819 {
820     if (!checkParamCount(e, 1))
821         return;
822
823     QString errnick = e->params().first();
824
825     // if there is a problem while connecting to the server -> we handle it
826     // but only if our connection has not been finished yet...
827     if (!e->network()->currentServer().isEmpty())
828         return;
829
830     tryNextNick(e, errnick);
831 }
832
833
834 /* ERR_UNAVAILRESOURCE */
835 void CoreSessionEventProcessor::processIrcEvent437(IrcEventNumeric *e)
836 {
837     if (!checkParamCount(e, 1))
838         return;
839
840     QString errnick = e->params().first();
841
842     // if there is a problem while connecting to the server -> we handle it
843     // but only if our connection has not been finished yet...
844     if (!e->network()->currentServer().isEmpty())
845         return;
846
847     if (!e->network()->isChannelName(errnick))
848         tryNextNick(e, errnick);
849 }
850
851
852 /* template
853 void CoreSessionEventProcessor::processIrcEvent(IrcEvent *e) {
854   if(!checkParamCount(e, 1))
855     return;
856
857 }
858 */
859
860 /* Handle signals from Netsplit objects  */
861
862 void CoreSessionEventProcessor::handleNetsplitJoin(Network *net,
863     const QString &channel,
864     const QStringList &users,
865     const QStringList &modes,
866     const QString &quitMessage)
867 {
868     IrcChannel *ircChannel = net->ircChannel(channel);
869     if (!ircChannel) {
870         return;
871     }
872     QList<IrcUser *> ircUsers;
873     QStringList newModes = modes;
874     QStringList newUsers = users;
875
876     foreach(const QString &user, users) {
877         IrcUser *iu = net->ircUser(nickFromMask(user));
878         if (iu)
879             ircUsers.append(iu);
880         else { // the user already quit
881             int idx = users.indexOf(user);
882             newUsers.removeAt(idx);
883             newModes.removeAt(idx);
884         }
885     }
886
887     ircChannel->joinIrcUsers(ircUsers, newModes);
888     NetworkSplitEvent *event = new NetworkSplitEvent(EventManager::NetworkSplitJoin, net, channel, newUsers, quitMessage);
889     emit newEvent(event);
890 }
891
892
893 void CoreSessionEventProcessor::handleNetsplitQuit(Network *net, const QString &channel, const QStringList &users, const QString &quitMessage)
894 {
895     NetworkSplitEvent *event = new NetworkSplitEvent(EventManager::NetworkSplitQuit, net, channel, users, quitMessage);
896     emit newEvent(event);
897     foreach(QString user, users) {
898         IrcUser *iu = net->ircUser(nickFromMask(user));
899         if (iu)
900             iu->quit();
901     }
902 }
903
904
905 void CoreSessionEventProcessor::handleEarlyNetsplitJoin(Network *net, const QString &channel, const QStringList &users, const QStringList &modes)
906 {
907     IrcChannel *ircChannel = net->ircChannel(channel);
908     if (!ircChannel) {
909         qDebug() << "handleEarlyNetsplitJoin(): channel " << channel << " invalid";
910         return;
911     }
912     QList<NetworkEvent *> events;
913     QList<IrcUser *> ircUsers;
914     QStringList newModes = modes;
915
916     foreach(QString user, users) {
917         IrcUser *iu = net->updateNickFromMask(user);
918         if (iu) {
919             ircUsers.append(iu);
920             // fake event for scripts that consume join events
921             events << new IrcEvent(EventManager::IrcEventJoin, net, iu->hostmask(), QStringList() << channel);
922         }
923         else {
924             newModes.removeAt(users.indexOf(user));
925         }
926     }
927     ircChannel->joinIrcUsers(ircUsers, newModes);
928     foreach(NetworkEvent *event, events) {
929         event->setFlag(EventManager::Fake); // ignore this in here!
930         emit newEvent(event);
931     }
932 }
933
934
935 void CoreSessionEventProcessor::handleNetsplitFinished()
936 {
937     Netsplit *n = qobject_cast<Netsplit *>(sender());
938     Q_ASSERT(n);
939     QHash<QString, Netsplit *> splithash  = _netsplits.take(n->network());
940     splithash.remove(splithash.key(n));
941     if (splithash.count())
942         _netsplits[n->network()] = splithash;
943     n->deleteLater();
944 }
945
946
947 void CoreSessionEventProcessor::destroyNetsplits(NetworkId netId)
948 {
949     Network *net = coreSession()->network(netId);
950     if (!net)
951         return;
952
953     QHash<QString, Netsplit *> splits = _netsplits.take(net);
954     qDeleteAll(splits);
955 }
956
957
958 /*******************************/
959 /******** CTCP HANDLING ********/
960 /*******************************/
961
962 void CoreSessionEventProcessor::processCtcpEvent(CtcpEvent *e)
963 {
964     if (e->testFlag(EventManager::Self))
965         return;  // ignore ctcp events generated by user input
966
967     if (e->type() != EventManager::CtcpEvent || e->ctcpType() != CtcpEvent::Query)
968         return;
969
970     handle(e->ctcpCmd(), Q_ARG(CtcpEvent *, e));
971 }
972
973
974 void CoreSessionEventProcessor::defaultHandler(const QString &ctcpCmd, CtcpEvent *e)
975 {
976     // This handler is only there to avoid warnings for unknown CTCPs
977     Q_UNUSED(e);
978     Q_UNUSED(ctcpCmd);
979 }
980
981
982 void CoreSessionEventProcessor::handleCtcpAction(CtcpEvent *e)
983 {
984     // This handler is only there to feed CLIENTINFO
985     Q_UNUSED(e);
986 }
987
988
989 void CoreSessionEventProcessor::handleCtcpClientinfo(CtcpEvent *e)
990 {
991     QStringList supportedHandlers;
992     foreach(QString handler, providesHandlers())
993     supportedHandlers << handler.toUpper();
994     qSort(supportedHandlers);
995     e->setReply(supportedHandlers.join(" "));
996 }
997
998
999 void CoreSessionEventProcessor::handleCtcpPing(CtcpEvent *e)
1000 {
1001     e->setReply(e->param());
1002 }
1003
1004
1005 void CoreSessionEventProcessor::handleCtcpTime(CtcpEvent *e)
1006 {
1007     e->setReply(QDateTime::currentDateTime().toString());
1008 }
1009
1010
1011 void CoreSessionEventProcessor::handleCtcpVersion(CtcpEvent *e)
1012 {
1013     e->setReply(QString("Quassel IRC %1 (built on %2) -- http://www.quassel-irc.org")
1014         .arg(Quassel::buildInfo().plainVersionString).arg(Quassel::buildInfo().buildDate));
1015 }