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