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