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