Use correct nick on 001 RPL_WELCOME
[quassel.git] / src / core / coresessioneventprocessor.cpp
1 /***************************************************************************
2  *   Copyright (C) 2005-2014 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(IrcEventNumeric *e)
481 {
482     e->network()->setCurrentServer(e->prefix());
483     e->network()->setMyNick(e->target());
484 }
485
486
487 /* RPL_ISUPPORT */
488 // TODO Complete 005 handling, also use sensible defaults for non-sent stuff
489 void CoreSessionEventProcessor::processIrcEvent005(IrcEvent *e)
490 {
491     if (!checkParamCount(e, 1))
492         return;
493
494     QString key, value;
495     for (int i = 0; i < e->params().count() - 1; i++) {
496         QString key = e->params()[i].section("=", 0, 0);
497         QString value = e->params()[i].section("=", 1);
498         e->network()->addSupport(key, value);
499     }
500
501     /* determine our prefixes here to get an accurate result */
502     e->network()->determinePrefixes();
503 }
504
505
506 /* RPL_UMODEIS - "<user_modes> [<user_mode_params>]" */
507 void CoreSessionEventProcessor::processIrcEvent221(IrcEvent *)
508 {
509     // TODO: save information in network object
510 }
511
512
513 /* RPL_STATSCONN - "Highest connection cout: 8000 (7999 clients)" */
514 void CoreSessionEventProcessor::processIrcEvent250(IrcEvent *)
515 {
516     // TODO: save information in network object
517 }
518
519
520 /* RPL_LOCALUSERS - "Current local user: 5024  Max: 7999 */
521 void CoreSessionEventProcessor::processIrcEvent265(IrcEvent *)
522 {
523     // TODO: save information in network object
524 }
525
526
527 /* RPL_GLOBALUSERS - "Current global users: 46093  Max: 47650" */
528 void CoreSessionEventProcessor::processIrcEvent266(IrcEvent *)
529 {
530     // TODO: save information in network object
531 }
532
533
534 /*
535 WHOIS-Message:
536    Replies 311 - 313, 317 - 319 are all replies generated in response to a WHOIS message.
537   and 301 (RPL_AWAY)
538               "<nick> :<away message>"
539 WHO-Message:
540    Replies 352 and 315 paired are used to answer a WHO message.
541
542 WHOWAS-Message:
543    Replies 314 and 369 are responses to a WHOWAS message.
544
545 */
546
547 /* RPL_AWAY - "<nick> :<away message>" */
548 void CoreSessionEventProcessor::processIrcEvent301(IrcEvent *e)
549 {
550     if (!checkParamCount(e, 2))
551         return;
552
553     IrcUser *ircuser = e->network()->ircUser(e->params().at(0));
554     if (ircuser) {
555         ircuser->setAway(true);
556         ircuser->setAwayMessage(e->params().at(1));
557         //ircuser->setLastAwayMessage(now);
558     }
559 }
560
561
562 /* RPL_UNAWAY - ":You are no longer marked as being away" */
563 void CoreSessionEventProcessor::processIrcEvent305(IrcEvent *e)
564 {
565     IrcUser *me = e->network()->me();
566     if (me)
567         me->setAway(false);
568
569     if (e->network()->autoAwayActive()) {
570         e->network()->setAutoAwayActive(false);
571         e->setFlag(EventManager::Silent);
572     }
573 }
574
575
576 /* RPL_NOWAWAY - ":You have been marked as being away" */
577 void CoreSessionEventProcessor::processIrcEvent306(IrcEvent *e)
578 {
579     IrcUser *me = e->network()->me();
580     if (me)
581         me->setAway(true);
582 }
583
584
585 /* RPL_WHOISSERVICE - "<user> is registered nick" */
586 void CoreSessionEventProcessor::processIrcEvent307(IrcEvent *e)
587 {
588     if (!checkParamCount(e, 1))
589         return;
590
591     IrcUser *ircuser = e->network()->ircUser(e->params().at(0));
592     if (ircuser)
593         ircuser->setWhoisServiceReply(e->params().join(" "));
594 }
595
596
597 /* RPL_SUSERHOST - "<user> is available for help." */
598 void CoreSessionEventProcessor::processIrcEvent310(IrcEvent *e)
599 {
600     if (!checkParamCount(e, 1))
601         return;
602
603     IrcUser *ircuser = e->network()->ircUser(e->params().at(0));
604     if (ircuser)
605         ircuser->setSuserHost(e->params().join(" "));
606 }
607
608
609 /*  RPL_WHOISUSER - "<nick> <user> <host> * :<real name>" */
610 void CoreSessionEventProcessor::processIrcEvent311(IrcEvent *e)
611 {
612     if (!checkParamCount(e, 3))
613         return;
614
615     IrcUser *ircuser = e->network()->ircUser(e->params().at(0));
616     if (ircuser) {
617         ircuser->setUser(e->params().at(1));
618         ircuser->setHost(e->params().at(2));
619         ircuser->setRealName(e->params().last());
620     }
621 }
622
623
624 /*  RPL_WHOISSERVER -  "<nick> <server> :<server info>" */
625 void CoreSessionEventProcessor::processIrcEvent312(IrcEvent *e)
626 {
627     if (!checkParamCount(e, 2))
628         return;
629
630     IrcUser *ircuser = e->network()->ircUser(e->params().at(0));
631     if (ircuser)
632         ircuser->setServer(e->params().at(1));
633 }
634
635
636 /*  RPL_WHOISOPERATOR - "<nick> :is an IRC operator" */
637 void CoreSessionEventProcessor::processIrcEvent313(IrcEvent *e)
638 {
639     if (!checkParamCount(e, 1))
640         return;
641
642     IrcUser *ircuser = e->network()->ircUser(e->params().at(0));
643     if (ircuser)
644         ircuser->setIrcOperator(e->params().last());
645 }
646
647
648 /*  RPL_ENDOFWHO: "<name> :End of WHO list" */
649 void CoreSessionEventProcessor::processIrcEvent315(IrcEvent *e)
650 {
651     if (!checkParamCount(e, 1))
652         return;
653
654     if (coreNetwork(e)->setAutoWhoDone(e->params()[0]))
655         e->setFlag(EventManager::Silent);
656 }
657
658
659 /*  RPL_WHOISIDLE - "<nick> <integer> :seconds idle"
660    (real life: "<nick> <integer> <integer> :seconds idle, signon time) */
661 void CoreSessionEventProcessor::processIrcEvent317(IrcEvent *e)
662 {
663     if (!checkParamCount(e, 2))
664         return;
665
666     QDateTime loginTime;
667
668     int idleSecs = e->params()[1].toInt();
669     if (e->params().count() > 3) { // if we have more then 3 params we have the above mentioned "real life" situation
670         int logintime = e->params()[2].toInt();
671         loginTime = QDateTime::fromTime_t(logintime);
672     }
673
674     IrcUser *ircuser = e->network()->ircUser(e->params()[0]);
675     if (ircuser) {
676         ircuser->setIdleTime(e->timestamp().addSecs(-idleSecs));
677         if (loginTime.isValid())
678             ircuser->setLoginTime(loginTime);
679     }
680 }
681
682
683 /* RPL_LIST -  "<channel> <# visible> :<topic>" */
684 void CoreSessionEventProcessor::processIrcEvent322(IrcEvent *e)
685 {
686     if (!checkParamCount(e, 1))
687         return;
688
689     QString channelName;
690     quint32 userCount = 0;
691     QString topic;
692
693     switch (e->params().count()) {
694     case 3:
695         topic = e->params()[2];
696     case 2:
697         userCount = e->params()[1].toUInt();
698     case 1:
699         channelName = e->params()[0];
700     default:
701         break;
702     }
703     if (coreSession()->ircListHelper()->addChannel(e->networkId(), channelName, userCount, topic))
704         e->stop();  // consumed by IrcListHelper, so don't further process/show this event
705 }
706
707
708 /* RPL_LISTEND ":End of LIST" */
709 void CoreSessionEventProcessor::processIrcEvent323(IrcEvent *e)
710 {
711     if (!checkParamCount(e, 1))
712         return;
713
714     if (coreSession()->ircListHelper()->endOfChannelList(e->networkId()))
715         e->stop();  // consumed by IrcListHelper, so don't further process/show this event
716 }
717
718
719 /* RPL_CHANNELMODEIS - "<channel> <mode> <mode params>" */
720 void CoreSessionEventProcessor::processIrcEvent324(IrcEvent *e)
721 {
722     processIrcEventMode(e);
723 }
724
725
726 /* RPL_NOTOPIC */
727 void CoreSessionEventProcessor::processIrcEvent331(IrcEvent *e)
728 {
729     if (!checkParamCount(e, 1))
730         return;
731
732     IrcChannel *chan = e->network()->ircChannel(e->params()[0]);
733     if (chan)
734         chan->setTopic(QString());
735 }
736
737
738 /* RPL_TOPIC */
739 void CoreSessionEventProcessor::processIrcEvent332(IrcEvent *e)
740 {
741     if (!checkParamCount(e, 2))
742         return;
743
744     IrcChannel *chan = e->network()->ircChannel(e->params()[0]);
745     if (chan)
746         chan->setTopic(e->params()[1]);
747 }
748
749
750 /*  RPL_WHOREPLY: "<channel> <user> <host> <server> <nick>
751               ( "H" / "G" > ["*"] [ ( "@" / "+" ) ] :<hopcount> <real name>" */
752 void CoreSessionEventProcessor::processIrcEvent352(IrcEvent *e)
753 {
754     if (!checkParamCount(e, 6))
755         return;
756
757     QString channel = e->params()[0];
758     IrcUser *ircuser = e->network()->ircUser(e->params()[4]);
759     if (ircuser) {
760         ircuser->setUser(e->params()[1]);
761         ircuser->setHost(e->params()[2]);
762
763         bool away = e->params()[5].startsWith("G");
764         ircuser->setAway(away);
765         ircuser->setServer(e->params()[3]);
766         ircuser->setRealName(e->params().last().section(" ", 1));
767     }
768
769     if (coreNetwork(e)->isAutoWhoInProgress(channel))
770         e->setFlag(EventManager::Silent);
771 }
772
773
774 /* RPL_NAMREPLY */
775 void CoreSessionEventProcessor::processIrcEvent353(IrcEvent *e)
776 {
777     if (!checkParamCount(e, 3))
778         return;
779
780     // param[0] is either "=", "*" or "@" indicating a public, private or secret channel
781     // we don't use this information at the time beeing
782     QString channelname = e->params()[1];
783
784     IrcChannel *channel = e->network()->ircChannel(channelname);
785     if (!channel) {
786         qWarning() << Q_FUNC_INFO << "Received unknown target channel:" << channelname;
787         return;
788     }
789
790     QStringList nicks;
791     QStringList modes;
792
793     foreach(QString nick, e->params()[2].split(' ', QString::SkipEmptyParts)) {
794         QString mode;
795
796         if (e->network()->prefixes().contains(nick[0])) {
797             mode = e->network()->prefixToMode(nick[0]);
798             nick = nick.mid(1);
799         }
800
801         nicks << nick;
802         modes << mode;
803     }
804
805     channel->joinIrcUsers(nicks, modes);
806 }
807
808
809 /* ERR_ERRONEUSNICKNAME */
810 void CoreSessionEventProcessor::processIrcEvent432(IrcEventNumeric *e)
811 {
812     if (!checkParamCount(e, 1))
813         return;
814
815     QString errnick;
816     if (e->params().count() < 2) {
817         // handle unreal-ircd bug, where unreal ircd doesnt supply a TARGET in ERR_ERRONEUSNICKNAME during registration phase:
818         // nick @@@
819         // :irc.scortum.moep.net 432  @@@ :Erroneous Nickname: Illegal characters
820         // correct server reply:
821         // :irc.scortum.moep.net 432 * @@@ :Erroneous Nickname: Illegal characters
822         e->params().prepend(e->target());
823         e->setTarget("*");
824     }
825     errnick = e->params()[0];
826
827     tryNextNick(e, errnick, true /* erroneus */);
828 }
829
830
831 /* ERR_NICKNAMEINUSE */
832 void CoreSessionEventProcessor::processIrcEvent433(IrcEventNumeric *e)
833 {
834     if (!checkParamCount(e, 1))
835         return;
836
837     QString errnick = e->params().first();
838
839     // if there is a problem while connecting to the server -> we handle it
840     // but only if our connection has not been finished yet...
841     if (!e->network()->currentServer().isEmpty())
842         return;
843
844     tryNextNick(e, errnick);
845 }
846
847
848 /* ERR_UNAVAILRESOURCE */
849 void CoreSessionEventProcessor::processIrcEvent437(IrcEventNumeric *e)
850 {
851     if (!checkParamCount(e, 1))
852         return;
853
854     QString errnick = e->params().first();
855
856     // if there is a problem while connecting to the server -> we handle it
857     // but only if our connection has not been finished yet...
858     if (!e->network()->currentServer().isEmpty())
859         return;
860
861     if (!e->network()->isChannelName(errnick))
862         tryNextNick(e, errnick);
863 }
864
865
866 /* template
867 void CoreSessionEventProcessor::processIrcEvent(IrcEvent *e) {
868   if(!checkParamCount(e, 1))
869     return;
870
871 }
872 */
873
874 /* Handle signals from Netsplit objects  */
875
876 void CoreSessionEventProcessor::handleNetsplitJoin(Network *net,
877     const QString &channel,
878     const QStringList &users,
879     const QStringList &modes,
880     const QString &quitMessage)
881 {
882     IrcChannel *ircChannel = net->ircChannel(channel);
883     if (!ircChannel) {
884         return;
885     }
886     QList<IrcUser *> ircUsers;
887     QStringList newModes = modes;
888     QStringList newUsers = users;
889
890     foreach(const QString &user, users) {
891         IrcUser *iu = net->ircUser(nickFromMask(user));
892         if (iu)
893             ircUsers.append(iu);
894         else { // the user already quit
895             int idx = users.indexOf(user);
896             newUsers.removeAt(idx);
897             newModes.removeAt(idx);
898         }
899     }
900
901     ircChannel->joinIrcUsers(ircUsers, newModes);
902     NetworkSplitEvent *event = new NetworkSplitEvent(EventManager::NetworkSplitJoin, net, channel, newUsers, quitMessage);
903     emit newEvent(event);
904 }
905
906
907 void CoreSessionEventProcessor::handleNetsplitQuit(Network *net, const QString &channel, const QStringList &users, const QString &quitMessage)
908 {
909     NetworkSplitEvent *event = new NetworkSplitEvent(EventManager::NetworkSplitQuit, net, channel, users, quitMessage);
910     emit newEvent(event);
911     foreach(QString user, users) {
912         IrcUser *iu = net->ircUser(nickFromMask(user));
913         if (iu)
914             iu->quit();
915     }
916 }
917
918
919 void CoreSessionEventProcessor::handleEarlyNetsplitJoin(Network *net, const QString &channel, const QStringList &users, const QStringList &modes)
920 {
921     IrcChannel *ircChannel = net->ircChannel(channel);
922     if (!ircChannel) {
923         qDebug() << "handleEarlyNetsplitJoin(): channel " << channel << " invalid";
924         return;
925     }
926     QList<NetworkEvent *> events;
927     QList<IrcUser *> ircUsers;
928     QStringList newModes = modes;
929
930     foreach(QString user, users) {
931         IrcUser *iu = net->updateNickFromMask(user);
932         if (iu) {
933             ircUsers.append(iu);
934             // fake event for scripts that consume join events
935             events << new IrcEvent(EventManager::IrcEventJoin, net, iu->hostmask(), QStringList() << channel);
936         }
937         else {
938             newModes.removeAt(users.indexOf(user));
939         }
940     }
941     ircChannel->joinIrcUsers(ircUsers, newModes);
942     foreach(NetworkEvent *event, events) {
943         event->setFlag(EventManager::Fake); // ignore this in here!
944         emit newEvent(event);
945     }
946 }
947
948
949 void CoreSessionEventProcessor::handleNetsplitFinished()
950 {
951     Netsplit *n = qobject_cast<Netsplit *>(sender());
952     Q_ASSERT(n);
953     QHash<QString, Netsplit *> splithash  = _netsplits.take(n->network());
954     splithash.remove(splithash.key(n));
955     if (splithash.count())
956         _netsplits[n->network()] = splithash;
957     n->deleteLater();
958 }
959
960
961 void CoreSessionEventProcessor::destroyNetsplits(NetworkId netId)
962 {
963     Network *net = coreSession()->network(netId);
964     if (!net)
965         return;
966
967     QHash<QString, Netsplit *> splits = _netsplits.take(net);
968     qDeleteAll(splits);
969 }
970
971
972 /*******************************/
973 /******** CTCP HANDLING ********/
974 /*******************************/
975
976 void CoreSessionEventProcessor::processCtcpEvent(CtcpEvent *e)
977 {
978     if (e->testFlag(EventManager::Self))
979         return;  // ignore ctcp events generated by user input
980
981     if (e->type() != EventManager::CtcpEvent || e->ctcpType() != CtcpEvent::Query)
982         return;
983
984     handle(e->ctcpCmd(), Q_ARG(CtcpEvent *, e));
985 }
986
987
988 void CoreSessionEventProcessor::defaultHandler(const QString &ctcpCmd, CtcpEvent *e)
989 {
990     // This handler is only there to avoid warnings for unknown CTCPs
991     Q_UNUSED(e);
992     Q_UNUSED(ctcpCmd);
993 }
994
995
996 void CoreSessionEventProcessor::handleCtcpAction(CtcpEvent *e)
997 {
998     // This handler is only there to feed CLIENTINFO
999     Q_UNUSED(e);
1000 }
1001
1002
1003 void CoreSessionEventProcessor::handleCtcpClientinfo(CtcpEvent *e)
1004 {
1005     QStringList supportedHandlers;
1006     foreach(QString handler, providesHandlers())
1007     supportedHandlers << handler.toUpper();
1008     qSort(supportedHandlers);
1009     e->setReply(supportedHandlers.join(" "));
1010 }
1011
1012
1013 void CoreSessionEventProcessor::handleCtcpPing(CtcpEvent *e)
1014 {
1015     e->setReply(e->param().isNull() ? "" : e->param());
1016 }
1017
1018
1019 void CoreSessionEventProcessor::handleCtcpTime(CtcpEvent *e)
1020 {
1021     e->setReply(QDateTime::currentDateTime().toString());
1022 }
1023
1024
1025 void CoreSessionEventProcessor::handleCtcpVersion(CtcpEvent *e)
1026 {
1027     e->setReply(QString("Quassel IRC %1 (built on %2) -- http://www.quassel-irc.org")
1028         .arg(Quassel::buildInfo().plainVersionString).arg(Quassel::buildInfo().buildDate));
1029 }