Fix joins for non-spec servers with extended-join
[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         QString newAccount = e->params().at(0);
246         // WHOX uses '0' to indicate logged-out, account-notify uses '*'
247         if (newAccount != "*") {
248             // Account logged in, set account name
249             ircuser->setAccount(newAccount);
250         } else {
251             // Account logged out, set account name to logged-out
252             ircuser->setAccount("*");
253         }
254     } else {
255         qDebug() << "Received account-notify data for unknown user" << e->prefix();
256     }
257 }
258
259 /* IRCv3 away-notify - ":nick!user@host AWAY [:message]" */
260 void CoreSessionEventProcessor::processIrcEventAway(IrcEvent *e)
261 {
262     if (!checkParamCount(e, 2))
263         return;
264
265     // Nick is sent as part of parameters in order to split user/server decoding
266     IrcUser *ircuser = e->network()->ircUser(e->params().at(0));
267     if (ircuser) {
268         if (!e->params().at(1).isEmpty()) {
269             ircuser->setAway(true);
270             ircuser->setAwayMessage(e->params().at(1));
271         } else {
272             ircuser->setAway(false);
273         }
274     } else {
275         qDebug() << "Received away-notify data for unknown user" << e->params().at(0);
276     }
277 }
278
279 /* IRCv3 chghost - ":nick!user@host CHGHOST newuser new.host.goes.here" */
280 void CoreSessionEventProcessor::processIrcEventChghost(IrcEvent *e)
281 {
282     if (!checkParamCount(e, 2))
283         return;
284
285     IrcUser *ircuser = e->network()->updateNickFromMask(e->prefix());
286     if (ircuser) {
287         // Update with new user/hostname information.  setUser/setHost handles checking what
288         // actually changed.
289         ircuser->setUser(e->params().at(0));
290         ircuser->setHost(e->params().at(1));
291     } else {
292         qDebug() << "Received chghost data for unknown user" << e->prefix();
293     }
294 }
295
296 void CoreSessionEventProcessor::processIrcEventInvite(IrcEvent *e)
297 {
298     if (checkParamCount(e, 2)) {
299         e->network()->updateNickFromMask(e->prefix());
300     }
301 }
302
303 /*  JOIN: ":<nick!user@host> JOIN <channel>" */
304 void CoreSessionEventProcessor::processIrcEventJoin(IrcEvent *e)
305 {
306     if (e->testFlag(EventManager::Fake)) // generated by handleEarlyNetsplitJoin
307         return;
308
309     if (!checkParamCount(e, 1))
310         return;
311
312     CoreNetwork *net = coreNetwork(e);
313     QString channel = e->params()[0];
314     IrcUser *ircuser = net->updateNickFromMask(e->prefix());
315
316     if (net->capEnabled(IrcCap::EXTENDED_JOIN)) {
317         if (e->params().count() < 3) {
318             // Some IRC servers don't send extended-join events in all situations.  Rather than
319             // ignore the join entirely, treat it as a regular join with a debug-level log entry.
320             // See:  https://github.com/inspircd/inspircd/issues/821
321             qDebug() << "extended-join requires 3 params, got:" << e->params() << ", handling as a "
322                         "regular join";
323         } else {
324             // If logged in, :nick!user@host JOIN #channelname accountname :Real Name
325             // If logged out, :nick!user@host JOIN #channelname * :Real Name
326             // See:  http://ircv3.net/specs/extensions/extended-join-3.1.html
327             // FIXME Keep track of authed user account, requires adding support to ircuser.h/cpp
328             // Update the user's real name, too
329             ircuser->setRealName(e->params()[2]);
330         }
331     }
332     // Else :nick!user@host JOIN #channelname
333
334     bool handledByNetsplit = false;
335     foreach(Netsplit* n, _netsplits.value(e->network())) {
336         handledByNetsplit = n->userJoined(e->prefix(), channel);
337         if (handledByNetsplit)
338             break;
339     }
340
341     // If using away-notify, check new users.  Works around buggy IRC servers
342     // forgetting to send :away messages for users who join channels when away.
343     if (net->capEnabled(IrcCap::AWAY_NOTIFY)) {
344         net->queueAutoWhoOneshot(ircuser->nick());
345     }
346
347     if (!handledByNetsplit)
348         ircuser->joinChannel(channel);
349     else
350         e->setFlag(EventManager::Netsplit);
351
352     if (net->isMe(ircuser)) {
353         net->setChannelJoined(channel);
354         // FIXME use event
355         net->putRawLine(net->serverEncode("MODE " + channel)); // we want to know the modes of the channel we just joined, so we ask politely
356     }
357 }
358
359
360 void CoreSessionEventProcessor::lateProcessIrcEventKick(IrcEvent *e)
361 {
362     if (checkParamCount(e, 2)) {
363         e->network()->updateNickFromMask(e->prefix());
364         IrcUser *victim = e->network()->ircUser(e->params().at(1));
365         if (victim) {
366             victim->partChannel(e->params().at(0));
367             //if(e->network()->isMe(victim)) e->network()->setKickedFromChannel(channel);
368         }
369     }
370 }
371
372
373 void CoreSessionEventProcessor::processIrcEventMode(IrcEvent *e)
374 {
375     if (!checkParamCount(e, 2))
376         return;
377
378     if (e->network()->isChannelName(e->params().first())) {
379         // Channel Modes
380
381         IrcChannel *channel = e->network()->ircChannel(e->params()[0]);
382         if (!channel) {
383             // we received mode information for a channel we're not in. that means probably we've just been kicked out or something like that
384             // anyways: we don't have a place to store the data --> discard the info.
385             return;
386         }
387
388         QString modes = e->params()[1];
389         bool add = true;
390         int paramOffset = 2;
391         for (int c = 0; c < modes.length(); c++) {
392             if (modes[c] == '+') {
393                 add = true;
394                 continue;
395             }
396             if (modes[c] == '-') {
397                 add = false;
398                 continue;
399             }
400
401             if (e->network()->prefixModes().contains(modes[c])) {
402                 // user channel modes (op, voice, etc...)
403                 if (paramOffset < e->params().count()) {
404                     IrcUser *ircUser = e->network()->ircUser(e->params()[paramOffset]);
405                     if (!ircUser) {
406                         qWarning() << Q_FUNC_INFO << "Unknown IrcUser:" << e->params()[paramOffset];
407                     }
408                     else {
409                         if (add) {
410                             bool handledByNetsplit = false;
411                             QHash<QString, Netsplit *> splits = _netsplits.value(e->network());
412                             foreach(Netsplit* n, _netsplits.value(e->network())) {
413                                 handledByNetsplit = n->userAlreadyJoined(ircUser->hostmask(), channel->name());
414                                 if (handledByNetsplit) {
415                                     n->addMode(ircUser->hostmask(), channel->name(), QString(modes[c]));
416                                     break;
417                                 }
418                             }
419                             if (!handledByNetsplit)
420                                 channel->addUserMode(ircUser, QString(modes[c]));
421                         }
422                         else
423                             channel->removeUserMode(ircUser, QString(modes[c]));
424                     }
425                 }
426                 else {
427                     qWarning() << "Received MODE with too few parameters:" << e->params();
428                 }
429                 ++paramOffset;
430             }
431             else {
432                 // regular channel modes
433                 QString value;
434                 Network::ChannelModeType modeType = e->network()->channelModeType(modes[c]);
435                 if (modeType == Network::A_CHANMODE || modeType == Network::B_CHANMODE || (modeType == Network::C_CHANMODE && add)) {
436                     if (paramOffset < e->params().count()) {
437                         value = e->params()[paramOffset];
438                     }
439                     else {
440                         qWarning() << "Received MODE with too few parameters:" << e->params();
441                     }
442                     ++paramOffset;
443                 }
444
445                 if (add)
446                     channel->addChannelMode(modes[c], value);
447                 else
448                     channel->removeChannelMode(modes[c], value);
449             }
450         }
451     }
452     else {
453         // pure User Modes
454         IrcUser *ircUser = e->network()->newIrcUser(e->params().first());
455         QString modeString(e->params()[1]);
456         QString addModes;
457         QString removeModes;
458         bool add = false;
459         for (int c = 0; c < modeString.count(); c++) {
460             if (modeString[c] == '+') {
461                 add = true;
462                 continue;
463             }
464             if (modeString[c] == '-') {
465                 add = false;
466                 continue;
467             }
468             if (add)
469                 addModes += modeString[c];
470             else
471                 removeModes += modeString[c];
472         }
473         if (!addModes.isEmpty())
474             ircUser->addUserModes(addModes);
475         if (!removeModes.isEmpty())
476             ircUser->removeUserModes(removeModes);
477
478         if (e->network()->isMe(ircUser)) {
479             coreNetwork(e)->updatePersistentModes(addModes, removeModes);
480         }
481     }
482 }
483
484
485 void CoreSessionEventProcessor::lateProcessIrcEventNick(IrcEvent *e)
486 {
487     if (checkParamCount(e, 1)) {
488         IrcUser *ircuser = e->network()->updateNickFromMask(e->prefix());
489         if (!ircuser) {
490             qWarning() << Q_FUNC_INFO << "Unknown IrcUser!";
491             return;
492         }
493         QString newnick = e->params().at(0);
494         QString oldnick = ircuser->nick();
495
496         // the order is cruicial
497         // otherwise the client would rename the buffer, see that the assigned ircuser doesn't match anymore
498         // and remove the ircuser from the querybuffer leading to a wrong on/offline state
499         ircuser->setNick(newnick);
500         coreSession()->renameBuffer(e->networkId(), newnick, oldnick);
501     }
502 }
503
504
505 void CoreSessionEventProcessor::lateProcessIrcEventPart(IrcEvent *e)
506 {
507     if (checkParamCount(e, 1)) {
508         IrcUser *ircuser = e->network()->updateNickFromMask(e->prefix());
509         if (!ircuser) {
510             qWarning() << Q_FUNC_INFO<< "Unknown IrcUser!";
511             return;
512         }
513         QString channel = e->params().at(0);
514         ircuser->partChannel(channel);
515         if (e->network()->isMe(ircuser))
516             qobject_cast<CoreNetwork *>(e->network())->setChannelParted(channel);
517     }
518 }
519
520
521 void CoreSessionEventProcessor::processIrcEventPing(IrcEvent *e)
522 {
523     QString param = e->params().count() ? e->params().first() : QString();
524     // FIXME use events
525     // Take priority so this won't get stuck behind other queued messages.
526     coreNetwork(e)->putRawLine("PONG " + coreNetwork(e)->serverEncode(param), true);
527 }
528
529
530 void CoreSessionEventProcessor::processIrcEventPong(IrcEvent *e)
531 {
532     // the server is supposed to send back what we passed as param. and we send a timestamp
533     // but using quote and whatnought one can send arbitrary pings, so we have to do some sanity checks
534     if (checkParamCount(e, 2)) {
535         QString timestamp = e->params().at(1);
536         QTime sendTime = QTime::fromString(timestamp, "hh:mm:ss.zzz");
537         if (sendTime.isValid())
538             e->network()->setLatency(sendTime.msecsTo(QTime::currentTime()) / 2);
539     }
540 }
541
542
543 void CoreSessionEventProcessor::processIrcEventQuit(IrcEvent *e)
544 {
545     IrcUser *ircuser = e->network()->updateNickFromMask(e->prefix());
546     if (!ircuser)
547         return;
548
549     QString msg;
550     if (e->params().count() > 0)
551         msg = e->params()[0];
552
553     // check if netsplit
554     if (Netsplit::isNetsplit(msg)) {
555         Netsplit *n;
556         if (!_netsplits[e->network()].contains(msg)) {
557             n = new Netsplit(e->network(), this);
558             connect(n, SIGNAL(finished()), this, SLOT(handleNetsplitFinished()));
559             connect(n, SIGNAL(netsplitJoin(Network*, QString, QStringList, QStringList, QString)),
560                 this, SLOT(handleNetsplitJoin(Network*, QString, QStringList, QStringList, QString)));
561             connect(n, SIGNAL(netsplitQuit(Network*, QString, QStringList, QString)),
562                 this, SLOT(handleNetsplitQuit(Network*, QString, QStringList, QString)));
563             connect(n, SIGNAL(earlyJoin(Network*, QString, QStringList, QStringList)),
564                 this, SLOT(handleEarlyNetsplitJoin(Network*, QString, QStringList, QStringList)));
565             _netsplits[e->network()].insert(msg, n);
566         }
567         else {
568             n = _netsplits[e->network()][msg];
569         }
570         // add this user to the netsplit
571         n->userQuit(e->prefix(), ircuser->channels(), msg);
572         e->setFlag(EventManager::Netsplit);
573     }
574     // normal quit is handled in lateProcessIrcEventQuit()
575 }
576
577
578 void CoreSessionEventProcessor::lateProcessIrcEventQuit(IrcEvent *e)
579 {
580     if (e->testFlag(EventManager::Netsplit))
581         return;
582
583     IrcUser *ircuser = e->network()->updateNickFromMask(e->prefix());
584     if (!ircuser)
585         return;
586
587     ircuser->quit();
588 }
589
590
591 void CoreSessionEventProcessor::processIrcEventTopic(IrcEvent *e)
592 {
593     if (checkParamCount(e, 2)) {
594         e->network()->updateNickFromMask(e->prefix());
595         IrcChannel *channel = e->network()->ircChannel(e->params().at(0));
596         if (channel)
597             channel->setTopic(e->params().at(1));
598     }
599 }
600
601
602 #ifdef HAVE_QCA2
603 void CoreSessionEventProcessor::processKeyEvent(KeyEvent *e)
604 {
605     if (!Cipher::neededFeaturesAvailable()) {
606         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()));
607         return;
608     }
609     CoreNetwork *net = qobject_cast<CoreNetwork*>(e->network());
610     Cipher *c = net->cipher(e->target());
611     if (!c) // happens when there is no CoreIrcChannel for the target (i.e. never?)
612         return;
613
614     if (e->exchangeType() == KeyEvent::Init) {
615         QByteArray pubKey = c->parseInitKeyX(e->key());
616         if (pubKey.isEmpty()) {
617             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()));
618             return;
619         } else {
620             net->setCipherKey(e->target(), c->key());
621             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()));
622             QList<QByteArray> p;
623             p << net->serverEncode(e->target()) << net->serverEncode("DH1080_FINISH ")+pubKey;
624             net->putCmd("NOTICE", p);
625         }
626     } else {
627         if (c->parseFinishKeyX(e->key())) {
628             net->setCipherKey(e->target(), c->key());
629             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()));
630         } else {
631             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()));
632         }
633     }
634 }
635 #endif
636
637
638 /* RPL_WELCOME */
639 void CoreSessionEventProcessor::processIrcEvent001(IrcEventNumeric *e)
640 {
641     e->network()->setCurrentServer(e->prefix());
642     e->network()->setMyNick(e->target());
643 }
644
645
646 /* RPL_ISUPPORT */
647 // TODO Complete 005 handling, also use sensible defaults for non-sent stuff
648 void CoreSessionEventProcessor::processIrcEvent005(IrcEvent *e)
649 {
650     if (!checkParamCount(e, 1))
651         return;
652
653     QString key, value;
654     for (int i = 0; i < e->params().count() - 1; i++) {
655         QString key = e->params()[i].section("=", 0, 0);
656         QString value = e->params()[i].section("=", 1);
657         e->network()->addSupport(key, value);
658     }
659
660     /* determine our prefixes here to get an accurate result */
661     e->network()->determinePrefixes();
662 }
663
664
665 /* RPL_UMODEIS - "<user_modes> [<user_mode_params>]" */
666 void CoreSessionEventProcessor::processIrcEvent221(IrcEvent *)
667 {
668     // TODO: save information in network object
669 }
670
671
672 /* RPL_STATSCONN - "Highest connection cout: 8000 (7999 clients)" */
673 void CoreSessionEventProcessor::processIrcEvent250(IrcEvent *)
674 {
675     // TODO: save information in network object
676 }
677
678
679 /* RPL_LOCALUSERS - "Current local user: 5024  Max: 7999 */
680 void CoreSessionEventProcessor::processIrcEvent265(IrcEvent *)
681 {
682     // TODO: save information in network object
683 }
684
685
686 /* RPL_GLOBALUSERS - "Current global users: 46093  Max: 47650" */
687 void CoreSessionEventProcessor::processIrcEvent266(IrcEvent *)
688 {
689     // TODO: save information in network object
690 }
691
692
693 /*
694 WHOIS-Message:
695    Replies 311 - 313, 317 - 319 are all replies generated in response to a WHOIS message.
696   and 301 (RPL_AWAY)
697               "<nick> :<away message>"
698 WHO-Message:
699    Replies 352 and 315 paired are used to answer a WHO message.
700
701 WHOWAS-Message:
702    Replies 314 and 369 are responses to a WHOWAS message.
703
704 */
705
706 /* RPL_AWAY - "<nick> :<away message>" */
707 void CoreSessionEventProcessor::processIrcEvent301(IrcEvent *e)
708 {
709     if (!checkParamCount(e, 2))
710         return;
711
712     IrcUser *ircuser = e->network()->ircUser(e->params().at(0));
713     if (ircuser) {
714         ircuser->setAway(true);
715         ircuser->setAwayMessage(e->params().at(1));
716         //ircuser->setLastAwayMessage(now);
717     }
718 }
719
720
721 /* RPL_UNAWAY - ":You are no longer marked as being away" */
722 void CoreSessionEventProcessor::processIrcEvent305(IrcEvent *e)
723 {
724     IrcUser *me = e->network()->me();
725     if (me)
726         me->setAway(false);
727
728     if (e->network()->autoAwayActive()) {
729         e->network()->setAutoAwayActive(false);
730         e->setFlag(EventManager::Silent);
731     }
732 }
733
734
735 /* RPL_NOWAWAY - ":You have been marked as being away" */
736 void CoreSessionEventProcessor::processIrcEvent306(IrcEvent *e)
737 {
738     IrcUser *me = e->network()->me();
739     if (me)
740         me->setAway(true);
741 }
742
743
744 /* RPL_WHOISSERVICE - "<user> is registered nick" */
745 void CoreSessionEventProcessor::processIrcEvent307(IrcEvent *e)
746 {
747     if (!checkParamCount(e, 1))
748         return;
749
750     IrcUser *ircuser = e->network()->ircUser(e->params().at(0));
751     if (ircuser)
752         ircuser->setWhoisServiceReply(e->params().join(" "));
753 }
754
755
756 /* RPL_SUSERHOST - "<user> is available for help." */
757 void CoreSessionEventProcessor::processIrcEvent310(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->setSuserHost(e->params().join(" "));
765 }
766
767
768 /*  RPL_WHOISUSER - "<nick> <user> <host> * :<real name>" */
769 void CoreSessionEventProcessor::processIrcEvent311(IrcEvent *e)
770 {
771     if (!checkParamCount(e, 3))
772         return;
773
774     IrcUser *ircuser = e->network()->ircUser(e->params().at(0));
775     if (ircuser) {
776         ircuser->setUser(e->params().at(1));
777         ircuser->setHost(e->params().at(2));
778         ircuser->setRealName(e->params().last());
779     }
780 }
781
782
783 /*  RPL_WHOISSERVER -  "<nick> <server> :<server info>" */
784 void CoreSessionEventProcessor::processIrcEvent312(IrcEvent *e)
785 {
786     if (!checkParamCount(e, 2))
787         return;
788
789     IrcUser *ircuser = e->network()->ircUser(e->params().at(0));
790     if (ircuser)
791         ircuser->setServer(e->params().at(1));
792 }
793
794
795 /*  RPL_WHOISOPERATOR - "<nick> :is an IRC operator" */
796 void CoreSessionEventProcessor::processIrcEvent313(IrcEvent *e)
797 {
798     if (!checkParamCount(e, 1))
799         return;
800
801     IrcUser *ircuser = e->network()->ircUser(e->params().at(0));
802     if (ircuser)
803         ircuser->setIrcOperator(e->params().last());
804 }
805
806
807 /*  RPL_ENDOFWHO: "<name> :End of WHO list" */
808 void CoreSessionEventProcessor::processIrcEvent315(IrcEvent *e)
809 {
810     if (!checkParamCount(e, 1))
811         return;
812
813     if (coreNetwork(e)->setAutoWhoDone(e->params()[0]))
814         e->setFlag(EventManager::Silent);
815 }
816
817
818 /*  RPL_WHOISIDLE - "<nick> <integer> :seconds idle"
819    (real life: "<nick> <integer> <integer> :seconds idle, signon time) */
820 void CoreSessionEventProcessor::processIrcEvent317(IrcEvent *e)
821 {
822     if (!checkParamCount(e, 2))
823         return;
824
825     QDateTime loginTime;
826
827     int idleSecs = e->params()[1].toInt();
828     if (e->params().count() > 3) { // if we have more then 3 params we have the above mentioned "real life" situation
829         int logintime = e->params()[2].toInt();
830         loginTime = QDateTime::fromTime_t(logintime);
831     }
832
833     IrcUser *ircuser = e->network()->ircUser(e->params()[0]);
834     if (ircuser) {
835         ircuser->setIdleTime(e->timestamp().addSecs(-idleSecs));
836         if (loginTime.isValid())
837             ircuser->setLoginTime(loginTime);
838     }
839 }
840
841
842 /* RPL_LIST -  "<channel> <# visible> :<topic>" */
843 void CoreSessionEventProcessor::processIrcEvent322(IrcEvent *e)
844 {
845     if (!checkParamCount(e, 1))
846         return;
847
848     QString channelName;
849     quint32 userCount = 0;
850     QString topic;
851
852     switch (e->params().count()) {
853     case 3:
854         topic = e->params()[2];
855     case 2:
856         userCount = e->params()[1].toUInt();
857     case 1:
858         channelName = e->params()[0];
859     default:
860         break;
861     }
862     if (coreSession()->ircListHelper()->addChannel(e->networkId(), channelName, userCount, topic))
863         e->stop();  // consumed by IrcListHelper, so don't further process/show this event
864 }
865
866
867 /* RPL_LISTEND ":End of LIST" */
868 void CoreSessionEventProcessor::processIrcEvent323(IrcEvent *e)
869 {
870     if (!checkParamCount(e, 1))
871         return;
872
873     if (coreSession()->ircListHelper()->endOfChannelList(e->networkId()))
874         e->stop();  // consumed by IrcListHelper, so don't further process/show this event
875 }
876
877
878 /* RPL_CHANNELMODEIS - "<channel> <mode> <mode params>" */
879 void CoreSessionEventProcessor::processIrcEvent324(IrcEvent *e)
880 {
881     processIrcEventMode(e);
882 }
883
884
885 /*  RPL_WHOISACCOUNT: "<nick> <account> :is authed as */
886 void CoreSessionEventProcessor::processIrcEvent330(IrcEvent *e)
887 {
888     if (!checkParamCount(e, 3))
889         return;
890
891     IrcUser *ircuser = e->network()->ircUser(e->params().at(0));
892     if (ircuser) {
893         ircuser->setAccount(e->params().at(1));
894     }
895 }
896
897
898 /* RPL_NOTOPIC */
899 void CoreSessionEventProcessor::processIrcEvent331(IrcEvent *e)
900 {
901     if (!checkParamCount(e, 1))
902         return;
903
904     IrcChannel *chan = e->network()->ircChannel(e->params()[0]);
905     if (chan)
906         chan->setTopic(QString());
907 }
908
909
910 /* RPL_TOPIC */
911 void CoreSessionEventProcessor::processIrcEvent332(IrcEvent *e)
912 {
913     if (!checkParamCount(e, 2))
914         return;
915
916     IrcChannel *chan = e->network()->ircChannel(e->params()[0]);
917     if (chan)
918         chan->setTopic(e->params()[1]);
919 }
920
921
922 /*  RPL_WHOREPLY: "<channel> <user> <host> <server> <nick>
923               ( "H" / "G" > ["*"] [ ( "@" / "+" ) ] :<hopcount> <real name>" */
924 void CoreSessionEventProcessor::processIrcEvent352(IrcEvent *e)
925 {
926     if (!checkParamCount(e, 6))
927         return;
928
929     QString channel = e->params()[0];
930     IrcUser *ircuser = e->network()->ircUser(e->params()[4]);
931     if (ircuser) {
932         processWhoInformation(e->network(), channel, ircuser, e->params()[3], e->params()[1],
933                 e->params()[2], e->params()[5], e->params().last().section(" ", 1));
934     }
935
936     // Check if channel name has a who in progress.
937     // If not, then check if user nick exists and has a who in progress.
938     if (coreNetwork(e)->isAutoWhoInProgress(channel) ||
939         (ircuser && coreNetwork(e)->isAutoWhoInProgress(ircuser->nick()))) {
940         e->setFlag(EventManager::Silent);
941     }
942 }
943
944
945 /* RPL_NAMREPLY */
946 void CoreSessionEventProcessor::processIrcEvent353(IrcEvent *e)
947 {
948     if (!checkParamCount(e, 3))
949         return;
950
951     // param[0] is either "=", "*" or "@" indicating a public, private or secret channel
952     // we don't use this information at the time beeing
953     QString channelname = e->params()[1];
954
955     IrcChannel *channel = e->network()->ircChannel(channelname);
956     if (!channel) {
957         qWarning() << Q_FUNC_INFO << "Received unknown target channel:" << channelname;
958         return;
959     }
960
961     QStringList nicks;
962     QStringList modes;
963
964     // Cache result of multi-prefix to avoid unneeded casts and lookups with each iteration.
965     bool _useCapMultiPrefix = coreNetwork(e)->capEnabled(IrcCap::MULTI_PREFIX);
966
967     foreach(QString nick, e->params()[2].split(' ', QString::SkipEmptyParts)) {
968         QString mode;
969
970         if (_useCapMultiPrefix) {
971             // If multi-prefix is enabled, all modes will be sent in NAMES replies.
972             // :hades.arpa 353 guest = #tethys :~&@%+aji &@Attila @+alyx +KindOne Argure
973             // See: http://ircv3.net/specs/extensions/multi-prefix-3.1.html
974             while (e->network()->prefixes().contains(nick[0])) {
975                 // Mode found in 1 left-most character, add it to the list.
976                 // Note: sending multiple modes may cause a warning in older clients.
977                 // In testing, the clients still seemed to function fine.
978                 mode.append(e->network()->prefixToMode(nick[0]));
979                 // Remove this mode from the nick
980                 nick = nick.remove(0, 1);
981             }
982         } else if (e->network()->prefixes().contains(nick[0])) {
983             // Multi-prefix is disabled and a mode prefix was found.
984             mode = e->network()->prefixToMode(nick[0]);
985             nick = nick.mid(1);
986         }
987
988         // If userhost-in-names capability is enabled, the following will be
989         // in the form "nick!user@host" rather than "nick".  This works without
990         // special handling as the following use nickFromHost() as needed.
991         // See: http://ircv3.net/specs/extensions/userhost-in-names-3.2.html
992
993         nicks << nick;
994         modes << mode;
995     }
996
997     channel->joinIrcUsers(nicks, modes);
998 }
999
1000
1001 /*  RPL_WHOSPCRPL: "<yournick> 152 #<channel> ~<ident> <host> <servname> <nick>
1002                     ("H"/ "G") <account> :<realname>"
1003 <channel> is * if not specific to any channel
1004 <account> is * if not logged in
1005 Follows HexChat's usage of 'whox'
1006 See https://github.com/hexchat/hexchat/blob/c874a9525c9b66f1d5ddcf6c4107d046eba7e2c5/src/common/proto-irc.c#L750
1007 And http://faerion.sourceforge.net/doc/irc/whox.var*/
1008 void CoreSessionEventProcessor::processIrcEvent354(IrcEvent *e)
1009 {
1010     // First only check if at least one parameter exists.  Otherwise, it'll stop the result from
1011     // being shown if the user chooses different parameters.
1012     if (!checkParamCount(e, 1))
1013         return;
1014
1015     if (e->params()[0].toUInt() != IrcCap::ACCOUNT_NOTIFY_WHOX_NUM) {
1016         // Ignore WHOX replies without expected number for we have no idea what fields are specified
1017         return;
1018     }
1019
1020     // Now we're fairly certain this is supposed to be an automated WHOX.  Bail out if it doesn't
1021     // match what we require - 9 parameters.
1022     if (!checkParamCount(e, 9))
1023         return;
1024
1025     QString channel = e->params()[1];
1026     IrcUser *ircuser = e->network()->ircUser(e->params()[5]);
1027     if (ircuser) {
1028         processWhoInformation(e->network(), channel, ircuser, e->params()[4], e->params()[2],
1029                 e->params()[3], e->params()[6], e->params().last());
1030         // Don't use .section(" ", 1) with WHOX replies, for there's no hopcount to trim out
1031
1032         // As part of IRCv3 account-notify, check account name
1033         // WHOX uses '0' to indicate logged-out, account-notify uses '*'
1034         QString newAccount = e->params()[7];
1035         if (newAccount != "0") {
1036             // Account logged in, set account name
1037             ircuser->setAccount(newAccount);
1038         } else {
1039             // Account logged out, set account name to logged-out
1040             ircuser->setAccount("*");
1041         }
1042     }
1043
1044     // Check if channel name has a who in progress.
1045     // If not, then check if user nick exists and has a who in progress.
1046     if (coreNetwork(e)->isAutoWhoInProgress(channel) ||
1047         (ircuser && coreNetwork(e)->isAutoWhoInProgress(ircuser->nick()))) {
1048         e->setFlag(EventManager::Silent);
1049     }
1050 }
1051
1052
1053 void CoreSessionEventProcessor::processWhoInformation (Network *net, const QString &targetChannel, IrcUser *ircUser,
1054                             const QString &server, const QString &user, const QString &host,
1055                             const QString &awayStateAndModes, const QString &realname)
1056 {
1057     ircUser->setUser(user);
1058     ircUser->setHost(host);
1059     ircUser->setServer(server);
1060     ircUser->setRealName(realname);
1061
1062     bool away = awayStateAndModes.contains("G", Qt::CaseInsensitive);
1063     ircUser->setAway(away);
1064
1065     if (net->capEnabled(IrcCap::MULTI_PREFIX)) {
1066         // If multi-prefix is enabled, all modes will be sent in WHO replies.
1067         // :kenny.chatspike.net 352 guest #test grawity broken.symlink *.chatspike.net grawity H@%+ :0 Mantas M.
1068         // See: http://ircv3.net/specs/extensions/multi-prefix-3.1.html
1069         QString uncheckedModes = awayStateAndModes;
1070         QString validModes = QString();
1071         while (!uncheckedModes.isEmpty()) {
1072             // Mode found in 1 left-most character, add it to the list
1073             if (net->prefixes().contains(uncheckedModes[0])) {
1074                 validModes.append(net->prefixToMode(uncheckedModes[0]));
1075             }
1076             // Remove this mode from the list of unchecked modes
1077             uncheckedModes = uncheckedModes.remove(0, 1);
1078         }
1079
1080         // Some IRC servers decide to not follow the spec, returning only -some- of the user
1081         // modes in WHO despite listing them all in NAMES.  For now, assume it can only add
1082         // and not take away.  *sigh*
1083         if (!validModes.isEmpty()) {
1084             if (targetChannel != "*") {
1085                 // Channel-specific modes received, apply to given channel only
1086                 IrcChannel *ircChan = net->ircChannel(targetChannel);
1087                 if (ircChan) {
1088                     // Do one mode at a time
1089                     // TODO Better way of syncing this without breaking protocol?
1090                     for (int i = 0; i < validModes.count(); ++i) {
1091                         ircChan->addUserMode(ircUser, validModes.at(i));
1092                     }
1093                 }
1094             } else {
1095                 // Modes apply to the user everywhere
1096                 ircUser->addUserModes(validModes);
1097             }
1098         }
1099     }
1100 }
1101
1102
1103 /* ERR_NOSUCHCHANNEL - "<channel name> :No such channel" */
1104 void CoreSessionEventProcessor::processIrcEvent403(IrcEventNumeric *e)
1105 {
1106     // If this is the result of an AutoWho, hide it.  It's confusing to show to the user.
1107     if (!checkParamCount(e, 2))
1108         return;
1109
1110     QString channelOrNick = e->params()[0];
1111     // Check if channel name has a who in progress.
1112     // If not, then check if user nick exists and has a who in progress.
1113     if (coreNetwork(e)->isAutoWhoInProgress(channelOrNick)) {
1114         qDebug() << "Channel/nick" << channelOrNick << "no longer exists during AutoWho, ignoring";
1115         e->setFlag(EventManager::Silent);
1116     }
1117 }
1118
1119 /* ERR_ERRONEUSNICKNAME */
1120 void CoreSessionEventProcessor::processIrcEvent432(IrcEventNumeric *e)
1121 {
1122     if (!checkParamCount(e, 1))
1123         return;
1124
1125     QString errnick;
1126     if (e->params().count() < 2) {
1127         // handle unreal-ircd bug, where unreal ircd doesnt supply a TARGET in ERR_ERRONEUSNICKNAME during registration phase:
1128         // nick @@@
1129         // :irc.scortum.moep.net 432  @@@ :Erroneous Nickname: Illegal characters
1130         // correct server reply:
1131         // :irc.scortum.moep.net 432 * @@@ :Erroneous Nickname: Illegal characters
1132         e->params().prepend(e->target());
1133         e->setTarget("*");
1134     }
1135     errnick = e->params()[0];
1136
1137     tryNextNick(e, errnick, true /* erroneus */);
1138 }
1139
1140
1141 /* ERR_NICKNAMEINUSE */
1142 void CoreSessionEventProcessor::processIrcEvent433(IrcEventNumeric *e)
1143 {
1144     if (!checkParamCount(e, 1))
1145         return;
1146
1147     QString errnick = e->params().first();
1148
1149     // if there is a problem while connecting to the server -> we handle it
1150     // but only if our connection has not been finished yet...
1151     if (!e->network()->currentServer().isEmpty())
1152         return;
1153
1154     tryNextNick(e, errnick);
1155 }
1156
1157
1158 /* ERR_UNAVAILRESOURCE */
1159 void CoreSessionEventProcessor::processIrcEvent437(IrcEventNumeric *e)
1160 {
1161     if (!checkParamCount(e, 1))
1162         return;
1163
1164     QString errnick = e->params().first();
1165
1166     // if there is a problem while connecting to the server -> we handle it
1167     // but only if our connection has not been finished yet...
1168     if (!e->network()->currentServer().isEmpty())
1169         return;
1170
1171     if (!e->network()->isChannelName(errnick))
1172         tryNextNick(e, errnick);
1173 }
1174
1175
1176 /* template
1177 void CoreSessionEventProcessor::processIrcEvent(IrcEvent *e) {
1178   if(!checkParamCount(e, 1))
1179     return;
1180
1181 }
1182 */
1183
1184 /* Handle signals from Netsplit objects  */
1185
1186 void CoreSessionEventProcessor::handleNetsplitJoin(Network *net,
1187     const QString &channel,
1188     const QStringList &users,
1189     const QStringList &modes,
1190     const QString &quitMessage)
1191 {
1192     IrcChannel *ircChannel = net->ircChannel(channel);
1193     if (!ircChannel) {
1194         return;
1195     }
1196     QList<IrcUser *> ircUsers;
1197     QStringList newModes = modes;
1198     QStringList newUsers = users;
1199
1200     foreach(const QString &user, users) {
1201         IrcUser *iu = net->ircUser(nickFromMask(user));
1202         if (iu)
1203             ircUsers.append(iu);
1204         else { // the user already quit
1205             int idx = users.indexOf(user);
1206             newUsers.removeAt(idx);
1207             newModes.removeAt(idx);
1208         }
1209     }
1210
1211     ircChannel->joinIrcUsers(ircUsers, newModes);
1212     NetworkSplitEvent *event = new NetworkSplitEvent(EventManager::NetworkSplitJoin, net, channel, newUsers, quitMessage);
1213     emit newEvent(event);
1214 }
1215
1216
1217 void CoreSessionEventProcessor::handleNetsplitQuit(Network *net, const QString &channel, const QStringList &users, const QString &quitMessage)
1218 {
1219     NetworkSplitEvent *event = new NetworkSplitEvent(EventManager::NetworkSplitQuit, net, channel, users, quitMessage);
1220     emit newEvent(event);
1221     foreach(QString user, users) {
1222         IrcUser *iu = net->ircUser(nickFromMask(user));
1223         if (iu)
1224             iu->quit();
1225     }
1226 }
1227
1228
1229 void CoreSessionEventProcessor::handleEarlyNetsplitJoin(Network *net, const QString &channel, const QStringList &users, const QStringList &modes)
1230 {
1231     IrcChannel *ircChannel = net->ircChannel(channel);
1232     if (!ircChannel) {
1233         qDebug() << "handleEarlyNetsplitJoin(): channel " << channel << " invalid";
1234         return;
1235     }
1236     QList<NetworkEvent *> events;
1237     QList<IrcUser *> ircUsers;
1238     QStringList newModes = modes;
1239
1240     foreach(QString user, users) {
1241         IrcUser *iu = net->updateNickFromMask(user);
1242         if (iu) {
1243             ircUsers.append(iu);
1244             // fake event for scripts that consume join events
1245             events << new IrcEvent(EventManager::IrcEventJoin, net, iu->hostmask(), QStringList() << channel);
1246         }
1247         else {
1248             newModes.removeAt(users.indexOf(user));
1249         }
1250     }
1251     ircChannel->joinIrcUsers(ircUsers, newModes);
1252     foreach(NetworkEvent *event, events) {
1253         event->setFlag(EventManager::Fake); // ignore this in here!
1254         emit newEvent(event);
1255     }
1256 }
1257
1258
1259 void CoreSessionEventProcessor::handleNetsplitFinished()
1260 {
1261     Netsplit *n = qobject_cast<Netsplit *>(sender());
1262     Q_ASSERT(n);
1263     QHash<QString, Netsplit *> splithash  = _netsplits.take(n->network());
1264     splithash.remove(splithash.key(n));
1265     if (splithash.count())
1266         _netsplits[n->network()] = splithash;
1267     n->deleteLater();
1268 }
1269
1270
1271 void CoreSessionEventProcessor::destroyNetsplits(NetworkId netId)
1272 {
1273     Network *net = coreSession()->network(netId);
1274     if (!net)
1275         return;
1276
1277     QHash<QString, Netsplit *> splits = _netsplits.take(net);
1278     qDeleteAll(splits);
1279 }
1280
1281
1282 /*******************************/
1283 /******** CTCP HANDLING ********/
1284 /*******************************/
1285
1286 void CoreSessionEventProcessor::processCtcpEvent(CtcpEvent *e)
1287 {
1288     if (e->testFlag(EventManager::Self))
1289         return;  // ignore ctcp events generated by user input
1290
1291     if (e->type() != EventManager::CtcpEvent || e->ctcpType() != CtcpEvent::Query)
1292         return;
1293
1294     handle(e->ctcpCmd(), Q_ARG(CtcpEvent *, e));
1295 }
1296
1297
1298 void CoreSessionEventProcessor::defaultHandler(const QString &ctcpCmd, CtcpEvent *e)
1299 {
1300     // This handler is only there to avoid warnings for unknown CTCPs
1301     Q_UNUSED(e);
1302     Q_UNUSED(ctcpCmd);
1303 }
1304
1305
1306 void CoreSessionEventProcessor::handleCtcpAction(CtcpEvent *e)
1307 {
1308     // This handler is only there to feed CLIENTINFO
1309     Q_UNUSED(e);
1310 }
1311
1312
1313 void CoreSessionEventProcessor::handleCtcpClientinfo(CtcpEvent *e)
1314 {
1315     QStringList supportedHandlers;
1316     foreach(QString handler, providesHandlers())
1317     supportedHandlers << handler.toUpper();
1318     qSort(supportedHandlers);
1319     e->setReply(supportedHandlers.join(" "));
1320 }
1321
1322
1323 // http://www.irchelp.org/irchelp/rfc/ctcpspec.html
1324 // http://en.wikipedia.org/wiki/Direct_Client-to-Client
1325 void CoreSessionEventProcessor::handleCtcpDcc(CtcpEvent *e)
1326 {
1327     // DCC support is unfinished, experimental and potentially dangerous, so make it opt-in
1328     if (!Quassel::isOptionSet("enable-experimental-dcc")) {
1329         quInfo() << "DCC disabled, start core with --enable-experimental-dcc if you really want to try it out";
1330         return;
1331     }
1332
1333     // normal:  SEND <filename> <ip> <port> [<filesize>]
1334     // reverse: SEND <filename> <ip> 0 <filesize> <token>
1335     QStringList params = e->param().split(' ');
1336     if (params.count()) {
1337         QString cmd = params[0].toUpper();
1338         if (cmd == "SEND") {
1339             if (params.count() < 4) {
1340                 qWarning() << "Invalid DCC SEND request:" << e;  // TODO emit proper error to client
1341                 return;
1342             }
1343             QString filename = params[1];
1344             QHostAddress address;
1345             quint16 port = params[3].toUShort();
1346             quint64 size = 0;
1347             QString numIp = params[2]; // this is either IPv4 as a 32 bit value, or IPv6 (which always contains a colon)
1348             if (numIp.contains(':')) { // IPv6
1349                 if (!address.setAddress(numIp)) {
1350                     qWarning() << "Invalid IPv6:" << numIp;
1351                     return;
1352                 }
1353             }
1354             else {
1355                 address.setAddress(numIp.toUInt());
1356             }
1357
1358             if (port == 0) { // Reverse DCC is indicated by a 0 port
1359                 emit newEvent(new MessageEvent(Message::Error, e->network(), tr("Reverse DCC SEND not supported"), e->prefix(), e->target(), Message::None, e->timestamp()));
1360                 return;
1361             }
1362             if (port < 1024) {
1363                 qWarning() << "Privileged port requested:" << port; // FIXME ask user if this is ok
1364             }
1365
1366
1367             if (params.count() > 4) { // filesize is optional
1368                 size = params[4].toULong();
1369             }
1370
1371             // TODO: check if target is the right thing to use for the partner
1372             CoreTransfer *transfer = new CoreTransfer(Transfer::Direction::Receive, e->target(), filename, address, port, size, this);
1373             coreSession()->signalProxy()->synchronize(transfer);
1374             coreSession()->transferManager()->addTransfer(transfer);
1375         }
1376         else {
1377             emit newEvent(new MessageEvent(Message::Error, e->network(), tr("DCC %1 not supported").arg(cmd), e->prefix(), e->target(), Message::None, e->timestamp()));
1378             return;
1379         }
1380     }
1381 }
1382
1383
1384 void CoreSessionEventProcessor::handleCtcpPing(CtcpEvent *e)
1385 {
1386     e->setReply(e->param().isNull() ? "" : e->param());
1387 }
1388
1389
1390 void CoreSessionEventProcessor::handleCtcpTime(CtcpEvent *e)
1391 {
1392     e->setReply(QDateTime::currentDateTime().toString());
1393 }
1394
1395
1396 void CoreSessionEventProcessor::handleCtcpVersion(CtcpEvent *e)
1397 {
1398     e->setReply(QString("Quassel IRC %1 (built on %2) -- http://www.quassel-irc.org")
1399         .arg(Quassel::buildInfo().plainVersionString).arg(Quassel::buildInfo().commitDate));
1400 }