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