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