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