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