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