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