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