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