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