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