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