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