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