Finish 64-bit time conversion, modify protocol
[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 "logger.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     // If using away-notify, check new users.  Works around buggy IRC servers
406     // forgetting to send :away messages for users who join channels when away.
407     if (net->capEnabled(IrcCap::AWAY_NOTIFY)) {
408         net->queueAutoWhoOneshot(ircuser->nick());
409     }
410
411     if (!handledByNetsplit)
412         ircuser->joinChannel(channel);
413     else
414         e->setFlag(EventManager::Netsplit);
415
416     if (net->isMe(ircuser)) {
417         net->setChannelJoined(channel);
418         // Mark the message as Self
419         e->setFlag(EventManager::Self);
420         // FIXME use event
421         net->putRawLine(net->serverEncode("MODE " + channel)); // we want to know the modes of the channel we just joined, so we ask politely
422     }
423 }
424
425
426 void CoreSessionEventProcessor::lateProcessIrcEventKick(IrcEvent *e)
427 {
428     if (checkParamCount(e, 2)) {
429         e->network()->updateNickFromMask(e->prefix());
430         IrcUser *victim = e->network()->ircUser(e->params().at(1));
431         if (victim) {
432             victim->partChannel(e->params().at(0));
433             //if(e->network()->isMe(victim)) e->network()->setKickedFromChannel(channel);
434         }
435     }
436 }
437
438
439 void CoreSessionEventProcessor::processIrcEventMode(IrcEvent *e)
440 {
441     if (!checkParamCount(e, 2))
442         return;
443
444     if (e->network()->isChannelName(e->params().first())) {
445         // Channel Modes
446
447         IrcChannel *channel = e->network()->ircChannel(e->params()[0]);
448         if (!channel) {
449             // we received mode information for a channel we're not in. that means probably we've just been kicked out or something like that
450             // anyways: we don't have a place to store the data --> discard the info.
451             return;
452         }
453
454         QString modes = e->params()[1];
455         bool add = true;
456         int paramOffset = 2;
457         for (int c = 0; c < modes.length(); c++) {
458             if (modes[c] == '+') {
459                 add = true;
460                 continue;
461             }
462             if (modes[c] == '-') {
463                 add = false;
464                 continue;
465             }
466
467             if (e->network()->prefixModes().contains(modes[c])) {
468                 // user channel modes (op, voice, etc...)
469                 if (paramOffset < e->params().count()) {
470                     IrcUser *ircUser = e->network()->ircUser(e->params()[paramOffset]);
471                     if (!ircUser) {
472                         qWarning() << Q_FUNC_INFO << "Unknown IrcUser:" << e->params()[paramOffset];
473                     }
474                     else {
475                         if (add) {
476                             bool handledByNetsplit = false;
477                             QHash<QString, Netsplit *> splits = _netsplits.value(e->network());
478                             foreach(Netsplit* n, _netsplits.value(e->network())) {
479                                 handledByNetsplit = n->userAlreadyJoined(ircUser->hostmask(), channel->name());
480                                 if (handledByNetsplit) {
481                                     n->addMode(ircUser->hostmask(), channel->name(), QString(modes[c]));
482                                     break;
483                                 }
484                             }
485                             if (!handledByNetsplit)
486                                 channel->addUserMode(ircUser, QString(modes[c]));
487                         }
488                         else
489                             channel->removeUserMode(ircUser, QString(modes[c]));
490                     }
491                 }
492                 else {
493                     qWarning() << "Received MODE with too few parameters:" << e->params();
494                 }
495                 ++paramOffset;
496             }
497             else {
498                 // regular channel modes
499                 QString value;
500                 Network::ChannelModeType modeType = e->network()->channelModeType(modes[c]);
501                 if (modeType == Network::A_CHANMODE || modeType == Network::B_CHANMODE || (modeType == Network::C_CHANMODE && add)) {
502                     if (paramOffset < e->params().count()) {
503                         value = e->params()[paramOffset];
504                     }
505                     else {
506                         qWarning() << "Received MODE with too few parameters:" << e->params();
507                     }
508                     ++paramOffset;
509                 }
510
511                 if (add)
512                     channel->addChannelMode(modes[c], value);
513                 else
514                     channel->removeChannelMode(modes[c], value);
515             }
516         }
517     }
518     else {
519         // pure User Modes
520         IrcUser *ircUser = e->network()->newIrcUser(e->params().first());
521         QString modeString(e->params()[1]);
522         QString addModes;
523         QString removeModes;
524         bool add = false;
525         for (int c = 0; c < modeString.count(); c++) {
526             if (modeString[c] == '+') {
527                 add = true;
528                 continue;
529             }
530             if (modeString[c] == '-') {
531                 add = false;
532                 continue;
533             }
534             if (add)
535                 addModes += modeString[c];
536             else
537                 removeModes += modeString[c];
538         }
539         if (!addModes.isEmpty())
540             ircUser->addUserModes(addModes);
541         if (!removeModes.isEmpty())
542             ircUser->removeUserModes(removeModes);
543
544         if (e->network()->isMe(ircUser)) {
545             // Mark the message as Self
546             e->setFlag(EventManager::Self);
547             coreNetwork(e)->updatePersistentModes(addModes, removeModes);
548         }
549     }
550 }
551
552
553 void CoreSessionEventProcessor::processIrcEventNick(IrcEvent *e)
554 {
555     if (checkParamCount(e, 1)) {
556         IrcUser *ircuser = e->network()->updateNickFromMask(e->prefix());
557         if (!ircuser) {
558             qWarning() << Q_FUNC_INFO << "Unknown IrcUser!";
559             return;
560         }
561
562         if (e->network()->isMe(ircuser)) {
563             // Mark the message as Self
564             e->setFlag(EventManager::Self);
565         }
566
567         // Actual processing is handled in lateProcessIrcEventNick(), this just sets the event flag
568     }
569 }
570
571
572 void CoreSessionEventProcessor::lateProcessIrcEventNick(IrcEvent *e)
573 {
574     if (checkParamCount(e, 1)) {
575         IrcUser *ircuser = e->network()->updateNickFromMask(e->prefix());
576         if (!ircuser) {
577             qWarning() << Q_FUNC_INFO << "Unknown IrcUser!";
578             return;
579         }
580         QString newnick = e->params().at(0);
581         QString oldnick = ircuser->nick();
582
583         // the order is cruicial
584         // otherwise the client would rename the buffer, see that the assigned ircuser doesn't match anymore
585         // and remove the ircuser from the querybuffer leading to a wrong on/offline state
586         ircuser->setNick(newnick);
587         coreSession()->renameBuffer(e->networkId(), newnick, oldnick);
588     }
589 }
590
591
592 void CoreSessionEventProcessor::processIrcEventPart(IrcEvent *e)
593 {
594     if (checkParamCount(e, 1)) {
595         IrcUser *ircuser = e->network()->updateNickFromMask(e->prefix());
596         if (!ircuser) {
597             qWarning() << Q_FUNC_INFO<< "Unknown IrcUser!";
598             return;
599         }
600
601         if (e->network()->isMe(ircuser)) {
602             // Mark the message as Self
603             e->setFlag(EventManager::Self);
604         }
605
606         // Actual processing is handled in lateProcessIrcEventNick(), this just sets the event flag
607     }
608 }
609
610
611 void CoreSessionEventProcessor::lateProcessIrcEventPart(IrcEvent *e)
612 {
613     if (checkParamCount(e, 1)) {
614         IrcUser *ircuser = e->network()->updateNickFromMask(e->prefix());
615         if (!ircuser) {
616             qWarning() << Q_FUNC_INFO<< "Unknown IrcUser!";
617             return;
618         }
619         QString channel = e->params().at(0);
620         ircuser->partChannel(channel);
621         if (e->network()->isMe(ircuser)) {
622             qobject_cast<CoreNetwork *>(e->network())->setChannelParted(channel);
623         }
624     }
625 }
626
627
628 void CoreSessionEventProcessor::processIrcEventPing(IrcEvent *e)
629 {
630     QString param = e->params().count() ? e->params().first() : QString();
631     // FIXME use events
632     // Take priority so this won't get stuck behind other queued messages.
633     coreNetwork(e)->putRawLine("PONG " + coreNetwork(e)->serverEncode(param), true);
634 }
635
636
637 void CoreSessionEventProcessor::processIrcEventPong(IrcEvent *e)
638 {
639     // the server is supposed to send back what we passed as param. and we send a timestamp
640     // but using quote and whatnought one can send arbitrary pings, so we have to do some sanity checks
641     if (checkParamCount(e, 2)) {
642         QString timestamp = e->params().at(1);
643         QTime sendTime = QTime::fromString(timestamp, "hh:mm:ss.zzz");
644         if (sendTime.isValid())
645             e->network()->setLatency(sendTime.msecsTo(QTime::currentTime()) / 2);
646     }
647 }
648
649
650 void CoreSessionEventProcessor::processIrcEventQuit(IrcEvent *e)
651 {
652     IrcUser *ircuser = e->network()->updateNickFromMask(e->prefix());
653     if (!ircuser)
654         return;
655
656     if (e->network()->isMe(ircuser)) {
657         // Mark the message as Self
658         e->setFlag(EventManager::Self);
659     }
660
661     QString msg;
662     if (e->params().count() > 0)
663         msg = e->params()[0];
664
665     // check if netsplit
666     if (Netsplit::isNetsplit(msg)) {
667         Netsplit *n;
668         if (!_netsplits[e->network()].contains(msg)) {
669             n = new Netsplit(e->network(), this);
670             connect(n, SIGNAL(finished()), this, SLOT(handleNetsplitFinished()));
671             connect(n, SIGNAL(netsplitJoin(Network*, QString, QStringList, QStringList, QString)),
672                 this, SLOT(handleNetsplitJoin(Network*, QString, QStringList, QStringList, QString)));
673             connect(n, SIGNAL(netsplitQuit(Network*, QString, QStringList, QString)),
674                 this, SLOT(handleNetsplitQuit(Network*, QString, QStringList, QString)));
675             connect(n, SIGNAL(earlyJoin(Network*, QString, QStringList, QStringList)),
676                 this, SLOT(handleEarlyNetsplitJoin(Network*, QString, QStringList, QStringList)));
677             _netsplits[e->network()].insert(msg, n);
678         }
679         else {
680             n = _netsplits[e->network()][msg];
681         }
682         // add this user to the netsplit
683         n->userQuit(e->prefix(), ircuser->channels(), msg);
684         e->setFlag(EventManager::Netsplit);
685     }
686     // normal quit is handled in lateProcessIrcEventQuit()
687 }
688
689
690 void CoreSessionEventProcessor::lateProcessIrcEventQuit(IrcEvent *e)
691 {
692     if (e->testFlag(EventManager::Netsplit))
693         return;
694
695     IrcUser *ircuser = e->network()->updateNickFromMask(e->prefix());
696     if (!ircuser)
697         return;
698
699     ircuser->quit();
700 }
701
702
703 void CoreSessionEventProcessor::processIrcEventTopic(IrcEvent *e)
704 {
705     if (checkParamCount(e, 2)) {
706         IrcUser *ircuser = e->network()->updateNickFromMask(e->prefix());
707
708         if (e->network()->isMe(ircuser)) {
709             // Mark the message as Self
710             e->setFlag(EventManager::Self);
711         }
712
713         IrcChannel *channel = e->network()->ircChannel(e->params().at(0));
714         if (channel)
715             channel->setTopic(e->params().at(1));
716     }
717 }
718
719 /* ERROR - "ERROR :reason"
720 Example:  ERROR :Closing Link: nickname[xxx.xxx.xxx.xxx] (Large base64 image paste.)
721 See https://tools.ietf.org/html/rfc2812#section-3.7.4 */
722 void CoreSessionEventProcessor::processIrcEventError(IrcEvent *e)
723 {
724     if (!checkParamCount(e, 1))
725         return;
726
727     if (coreNetwork(e)->disconnectExpected()) {
728         // During QUIT, the server should send an error (often, but not always, "Closing Link"). As
729         // we're expecting it, don't show this to the user.
730         e->setFlag(EventManager::Silent);
731     }
732 }
733
734
735 #ifdef HAVE_QCA2
736 void CoreSessionEventProcessor::processKeyEvent(KeyEvent *e)
737 {
738     if (!Cipher::neededFeaturesAvailable()) {
739         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()));
740         return;
741     }
742     CoreNetwork *net = qobject_cast<CoreNetwork*>(e->network());
743     Cipher *c = net->cipher(e->target());
744     if (!c) // happens when there is no CoreIrcChannel for the target (i.e. never?)
745         return;
746
747     if (e->exchangeType() == KeyEvent::Init) {
748         QByteArray pubKey = c->parseInitKeyX(e->key());
749         if (pubKey.isEmpty()) {
750             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()));
751             return;
752         } else {
753             net->setCipherKey(e->target(), c->key());
754             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()));
755             QList<QByteArray> p;
756             p << net->serverEncode(e->target()) << net->serverEncode("DH1080_FINISH ")+pubKey;
757             net->putCmd("NOTICE", p);
758         }
759     } else {
760         if (c->parseFinishKeyX(e->key())) {
761             net->setCipherKey(e->target(), c->key());
762             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()));
763         } else {
764             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()));
765         }
766     }
767 }
768 #endif
769
770
771 /* RPL_WELCOME */
772 void CoreSessionEventProcessor::processIrcEvent001(IrcEventNumeric *e)
773 {
774     e->network()->setCurrentServer(e->prefix());
775     e->network()->setMyNick(e->target());
776 }
777
778
779 /* RPL_ISUPPORT */
780 // TODO Complete 005 handling, also use sensible defaults for non-sent stuff
781 void CoreSessionEventProcessor::processIrcEvent005(IrcEvent *e)
782 {
783     if (!checkParamCount(e, 1))
784         return;
785
786     QString key, value;
787     for (int i = 0; i < e->params().count() - 1; i++) {
788         QString key = e->params()[i].section("=", 0, 0);
789         QString value = e->params()[i].section("=", 1);
790         e->network()->addSupport(key, value);
791     }
792
793     /* determine our prefixes here to get an accurate result */
794     e->network()->determinePrefixes();
795 }
796
797
798 /* RPL_UMODEIS - "<user_modes> [<user_mode_params>]" */
799 void CoreSessionEventProcessor::processIrcEvent221(IrcEvent *)
800 {
801     // TODO: save information in network object
802 }
803
804
805 /* RPL_STATSCONN - "Highest connection cout: 8000 (7999 clients)" */
806 void CoreSessionEventProcessor::processIrcEvent250(IrcEvent *)
807 {
808     // TODO: save information in network object
809 }
810
811
812 /* RPL_LOCALUSERS - "Current local user: 5024  Max: 7999 */
813 void CoreSessionEventProcessor::processIrcEvent265(IrcEvent *)
814 {
815     // TODO: save information in network object
816 }
817
818
819 /* RPL_GLOBALUSERS - "Current global users: 46093  Max: 47650" */
820 void CoreSessionEventProcessor::processIrcEvent266(IrcEvent *)
821 {
822     // TODO: save information in network object
823 }
824
825
826 /*
827 WHOIS-Message:
828    Replies 311 - 313, 317 - 319 are all replies generated in response to a WHOIS message.
829   and 301 (RPL_AWAY)
830               "<nick> :<away message>"
831 WHO-Message:
832    Replies 352 and 315 paired are used to answer a WHO message.
833
834 WHOWAS-Message:
835    Replies 314 and 369 are responses to a WHOWAS message.
836
837 */
838
839 /* RPL_AWAY - "<nick> :<away message>" */
840 void CoreSessionEventProcessor::processIrcEvent301(IrcEvent *e)
841 {
842     if (!checkParamCount(e, 2))
843         return;
844
845     IrcUser *ircuser = e->network()->ircUser(e->params().at(0));
846     if (ircuser) {
847         ircuser->setAway(true);
848         ircuser->setAwayMessage(e->params().at(1));
849         //ircuser->setLastAwayMessage(now);
850     }
851 }
852
853
854 /* RPL_UNAWAY - ":You are no longer marked as being away" */
855 void CoreSessionEventProcessor::processIrcEvent305(IrcEvent *e)
856 {
857     IrcUser *me = e->network()->me();
858     if (me)
859         me->setAway(false);
860
861     if (e->network()->autoAwayActive()) {
862         e->network()->setAutoAwayActive(false);
863         e->setFlag(EventManager::Silent);
864     }
865 }
866
867
868 /* RPL_NOWAWAY - ":You have been marked as being away" */
869 void CoreSessionEventProcessor::processIrcEvent306(IrcEvent *e)
870 {
871     IrcUser *me = e->network()->me();
872     if (me)
873         me->setAway(true);
874 }
875
876
877 /* RPL_WHOISSERVICE - "<user> is registered nick" */
878 void CoreSessionEventProcessor::processIrcEvent307(IrcEvent *e)
879 {
880     if (!checkParamCount(e, 1))
881         return;
882
883     IrcUser *ircuser = e->network()->ircUser(e->params().at(0));
884     if (ircuser)
885         ircuser->setWhoisServiceReply(e->params().join(" "));
886 }
887
888
889 /* RPL_SUSERHOST - "<user> is available for help." */
890 void CoreSessionEventProcessor::processIrcEvent310(IrcEvent *e)
891 {
892     if (!checkParamCount(e, 1))
893         return;
894
895     IrcUser *ircuser = e->network()->ircUser(e->params().at(0));
896     if (ircuser)
897         ircuser->setSuserHost(e->params().join(" "));
898 }
899
900
901 /*  RPL_WHOISUSER - "<nick> <user> <host> * :<real name>" */
902 void CoreSessionEventProcessor::processIrcEvent311(IrcEvent *e)
903 {
904     if (!checkParamCount(e, 3))
905         return;
906
907     IrcUser *ircuser = e->network()->ircUser(e->params().at(0));
908     if (ircuser) {
909         ircuser->setUser(e->params().at(1));
910         ircuser->setHost(e->params().at(2));
911         ircuser->setRealName(e->params().last());
912     }
913 }
914
915
916 /*  RPL_WHOISSERVER -  "<nick> <server> :<server info>" */
917 void CoreSessionEventProcessor::processIrcEvent312(IrcEvent *e)
918 {
919     if (!checkParamCount(e, 2))
920         return;
921
922     IrcUser *ircuser = e->network()->ircUser(e->params().at(0));
923     if (ircuser)
924         ircuser->setServer(e->params().at(1));
925 }
926
927
928 /*  RPL_WHOISOPERATOR - "<nick> :is an IRC operator" */
929 void CoreSessionEventProcessor::processIrcEvent313(IrcEvent *e)
930 {
931     if (!checkParamCount(e, 1))
932         return;
933
934     IrcUser *ircuser = e->network()->ircUser(e->params().at(0));
935     if (ircuser)
936         ircuser->setIrcOperator(e->params().last());
937 }
938
939
940 /*  RPL_ENDOFWHO: "<name> :End of WHO list" */
941 void CoreSessionEventProcessor::processIrcEvent315(IrcEvent *e)
942 {
943     if (!checkParamCount(e, 1))
944         return;
945
946     if (coreNetwork(e)->setAutoWhoDone(e->params()[0]))
947         e->setFlag(EventManager::Silent);
948 }
949
950
951 /*  RPL_WHOISIDLE - "<nick> <integer> :seconds idle"
952    (real life: "<nick> <integer> <integer> :seconds idle, signon time) */
953 void CoreSessionEventProcessor::processIrcEvent317(IrcEvent *e)
954 {
955     if (!checkParamCount(e, 2))
956         return;
957
958     QDateTime loginTime;
959
960     int idleSecs = e->params()[1].toInt();
961     if (e->params().count() > 3) { // if we have more then 3 params we have the above mentioned "real life" situation
962         // Allow for 64-bit time
963         qint64 logintime = e->params()[2].toLongLong();
964         // Time in IRC protocol is defined as seconds.  Convert from seconds instead.
965         // See https://doc.qt.io/qt-5/qdatetime.html#fromSecsSinceEpoch
966 #if QT_VERSION >= 0x050800
967         loginTime = QDateTime::fromSecsSinceEpoch(logintime);
968 #else
969         // fromSecsSinceEpoch() was added in Qt 5.8.  Manually downconvert to seconds for
970         // now.
971         // See https://doc.qt.io/qt-5/qdatetime.html#fromMSecsSinceEpoch
972         loginTime = QDateTime::fromMSecsSinceEpoch((qint64)(logintime * 1000));
973 #endif
974     }
975
976     IrcUser *ircuser = e->network()->ircUser(e->params()[0]);
977     if (ircuser) {
978         ircuser->setIdleTime(e->timestamp().addSecs(-idleSecs));
979         if (loginTime.isValid())
980             ircuser->setLoginTime(loginTime);
981     }
982 }
983
984
985 /* RPL_LIST -  "<channel> <# visible> :<topic>" */
986 void CoreSessionEventProcessor::processIrcEvent322(IrcEvent *e)
987 {
988     if (!checkParamCount(e, 1))
989         return;
990
991     QString channelName;
992     quint32 userCount = 0;
993     QString topic;
994
995     switch (e->params().count()) {
996     case 3:
997         topic = e->params()[2];
998         [[clang::fallthrough]];
999     case 2:
1000         userCount = e->params()[1].toUInt();
1001         [[clang::fallthrough]];
1002     case 1:
1003         channelName = e->params()[0];
1004         [[clang::fallthrough]];
1005     default:
1006         break;
1007     }
1008     if (coreSession()->ircListHelper()->addChannel(e->networkId(), channelName, userCount, topic))
1009         e->stop();  // consumed by IrcListHelper, so don't further process/show this event
1010 }
1011
1012
1013 /* RPL_LISTEND ":End of LIST" */
1014 void CoreSessionEventProcessor::processIrcEvent323(IrcEvent *e)
1015 {
1016     if (!checkParamCount(e, 1))
1017         return;
1018
1019     if (coreSession()->ircListHelper()->endOfChannelList(e->networkId()))
1020         e->stop();  // consumed by IrcListHelper, so don't further process/show this event
1021 }
1022
1023
1024 /* RPL_CHANNELMODEIS - "<channel> <mode> <mode params>" */
1025 void CoreSessionEventProcessor::processIrcEvent324(IrcEvent *e)
1026 {
1027     processIrcEventMode(e);
1028 }
1029
1030
1031 /*  RPL_WHOISACCOUNT - "<nick> <account> :is authed as" */
1032 void CoreSessionEventProcessor::processIrcEvent330(IrcEvent *e)
1033 {
1034     // Though the ":is authed as" remark should always be there, we should handle cases when it's
1035     // not included, too.
1036     if (!checkParamCount(e, 2))
1037         return;
1038
1039     IrcUser *ircuser = e->network()->ircUser(e->params().at(0));
1040     if (ircuser) {
1041         ircuser->setAccount(e->params().at(1));
1042     }
1043 }
1044
1045
1046 /* RPL_NOTOPIC */
1047 void CoreSessionEventProcessor::processIrcEvent331(IrcEvent *e)
1048 {
1049     if (!checkParamCount(e, 1))
1050         return;
1051
1052     IrcChannel *chan = e->network()->ircChannel(e->params()[0]);
1053     if (chan)
1054         chan->setTopic(QString());
1055 }
1056
1057
1058 /* RPL_TOPIC */
1059 void CoreSessionEventProcessor::processIrcEvent332(IrcEvent *e)
1060 {
1061     if (!checkParamCount(e, 2))
1062         return;
1063
1064     IrcChannel *chan = e->network()->ircChannel(e->params()[0]);
1065     if (chan)
1066         chan->setTopic(e->params()[1]);
1067 }
1068
1069
1070 /*  RPL_WHOREPLY: "<channel> <user> <host> <server> <nick>
1071               ( "H" / "G" > ["*"] [ ( "@" / "+" ) ] :<hopcount> <real name>" */
1072 void CoreSessionEventProcessor::processIrcEvent352(IrcEvent *e)
1073 {
1074     if (!checkParamCount(e, 6))
1075         return;
1076
1077     QString channel = e->params()[0];
1078     // Store the nick separate from ircuser for AutoWho check below
1079     QString nick = e->params()[4];
1080     IrcUser *ircuser = e->network()->ircUser(nick);
1081     if (ircuser) {
1082         // Only process the WHO information if an IRC user exists.  Don't create an IRC user here;
1083         // there's no way to track when the user quits, which would leave a phantom IrcUser lying
1084         // around.
1085         // NOTE:  Whenever MONITOR support is introduced, the IrcUser will be created by an
1086         // RPL_MONONLINE numeric before any WHO commands are run.
1087         processWhoInformation(e->network(), channel, ircuser, e->params()[3], e->params()[1],
1088                 e->params()[2], e->params()[5], e->params().last().section(" ", 1));
1089     }
1090
1091     // Check if channel name has a who in progress.
1092     // If not, then check if user nickname has a who in progress.  Use nick directly; don't use
1093     // ircuser as that may be deleted (e.g. nick joins channel, leaves before WHO reply received).
1094     if (coreNetwork(e)->isAutoWhoInProgress(channel) ||
1095         (coreNetwork(e)->isAutoWhoInProgress(nick))) {
1096         e->setFlag(EventManager::Silent);
1097     }
1098 }
1099
1100
1101 /* RPL_NAMREPLY */
1102 void CoreSessionEventProcessor::processIrcEvent353(IrcEvent *e)
1103 {
1104     if (!checkParamCount(e, 3))
1105         return;
1106
1107     // param[0] is either "=", "*" or "@" indicating a public, private or secret channel
1108     // we don't use this information at the time beeing
1109     QString channelname = e->params()[1];
1110
1111     IrcChannel *channel = e->network()->ircChannel(channelname);
1112     if (!channel) {
1113         qWarning() << Q_FUNC_INFO << "Received unknown target channel:" << channelname;
1114         return;
1115     }
1116
1117     QStringList nicks;
1118     QStringList modes;
1119
1120     // Cache result of multi-prefix to avoid unneeded casts and lookups with each iteration.
1121     bool _useCapMultiPrefix = coreNetwork(e)->capEnabled(IrcCap::MULTI_PREFIX);
1122
1123     foreach(QString nick, e->params()[2].split(' ', QString::SkipEmptyParts)) {
1124         QString mode;
1125
1126         if (_useCapMultiPrefix) {
1127             // If multi-prefix is enabled, all modes will be sent in NAMES replies.
1128             // :hades.arpa 353 guest = #tethys :~&@%+aji &@Attila @+alyx +KindOne Argure
1129             // See: http://ircv3.net/specs/extensions/multi-prefix-3.1.html
1130             while (e->network()->prefixes().contains(nick[0])) {
1131                 // Mode found in 1 left-most character, add it to the list.
1132                 // Note: sending multiple modes may cause a warning in older clients.
1133                 // In testing, the clients still seemed to function fine.
1134                 mode.append(e->network()->prefixToMode(nick[0]));
1135                 // Remove this mode from the nick
1136                 nick = nick.remove(0, 1);
1137             }
1138         } else if (e->network()->prefixes().contains(nick[0])) {
1139             // Multi-prefix is disabled and a mode prefix was found.
1140             mode = e->network()->prefixToMode(nick[0]);
1141             nick = nick.mid(1);
1142         }
1143
1144         // If userhost-in-names capability is enabled, the following will be
1145         // in the form "nick!user@host" rather than "nick".  This works without
1146         // special handling as the following use nickFromHost() as needed.
1147         // See: http://ircv3.net/specs/extensions/userhost-in-names-3.2.html
1148
1149         nicks << nick;
1150         modes << mode;
1151     }
1152
1153     channel->joinIrcUsers(nicks, modes);
1154 }
1155
1156
1157 /*  RPL_WHOSPCRPL: "<yournick> 152 #<channel> ~<ident> <host> <servname> <nick>
1158                     ("H"/ "G") <account> :<realname>"
1159 <channel> is * if not specific to any channel
1160 <account> is * if not logged in
1161 Follows HexChat's usage of 'whox'
1162 See https://github.com/hexchat/hexchat/blob/c874a9525c9b66f1d5ddcf6c4107d046eba7e2c5/src/common/proto-irc.c#L750
1163 And http://faerion.sourceforge.net/doc/irc/whox.var*/
1164 void CoreSessionEventProcessor::processIrcEvent354(IrcEvent *e)
1165 {
1166     // First only check if at least one parameter exists.  Otherwise, it'll stop the result from
1167     // being shown if the user chooses different parameters.
1168     if (!checkParamCount(e, 1))
1169         return;
1170
1171     if (e->params()[0].toUInt() != IrcCap::ACCOUNT_NOTIFY_WHOX_NUM) {
1172         // Ignore WHOX replies without expected number for we have no idea what fields are specified
1173         return;
1174     }
1175
1176     // Now we're fairly certain this is supposed to be an automated WHOX.  Bail out if it doesn't
1177     // match what we require - 9 parameters.
1178     if (!checkParamCount(e, 9))
1179         return;
1180
1181     QString channel = e->params()[1];
1182     QString nick = e->params()[5];
1183     IrcUser *ircuser = e->network()->ircUser(nick);
1184     if (ircuser) {
1185         // Only process the WHO information if an IRC user exists.  Don't create an IRC user here;
1186         // there's no way to track when the user quits, which would leave a phantom IrcUser lying
1187         // around.
1188         // NOTE:  Whenever MONITOR support is introduced, the IrcUser will be created by an
1189         // RPL_MONONLINE numeric before any WHO commands are run.
1190         processWhoInformation(e->network(), channel, ircuser, e->params()[4], e->params()[2],
1191                 e->params()[3], e->params()[6], e->params().last());
1192         // Don't use .section(" ", 1) with WHOX replies, for there's no hopcount to trim out
1193
1194         // As part of IRCv3 account-notify, check account name
1195         // WHOX uses '0' to indicate logged-out, account-notify and extended-join uses '*'.
1196         QString newAccount = e->params()[7];
1197         if (newAccount != "0") {
1198             // Account logged in, set account name
1199             ircuser->setAccount(newAccount);
1200         } else {
1201             // Account logged out, set account name to logged-out
1202             ircuser->setAccount("*");
1203         }
1204     }
1205
1206     // Check if channel name has a who in progress.
1207     // If not, then check if user nickname has a who in progress.  Use nick directly; don't use
1208     // ircuser as that may be deleted (e.g. nick joins channel, leaves before WHO reply received).
1209     if (coreNetwork(e)->isAutoWhoInProgress(channel) ||
1210         (coreNetwork(e)->isAutoWhoInProgress(nick))) {
1211         e->setFlag(EventManager::Silent);
1212     }
1213 }
1214
1215
1216 void CoreSessionEventProcessor::processWhoInformation (Network *net, const QString &targetChannel, IrcUser *ircUser,
1217                             const QString &server, const QString &user, const QString &host,
1218                             const QString &awayStateAndModes, const QString &realname)
1219 {
1220     ircUser->setUser(user);
1221     ircUser->setHost(host);
1222     ircUser->setServer(server);
1223     ircUser->setRealName(realname);
1224
1225     bool away = awayStateAndModes.contains("G", Qt::CaseInsensitive);
1226     ircUser->setAway(away);
1227
1228     if (net->capEnabled(IrcCap::MULTI_PREFIX)) {
1229         // If multi-prefix is enabled, all modes will be sent in WHO replies.
1230         // :kenny.chatspike.net 352 guest #test grawity broken.symlink *.chatspike.net grawity H@%+ :0 Mantas M.
1231         // See: http://ircv3.net/specs/extensions/multi-prefix-3.1.html
1232         QString uncheckedModes = awayStateAndModes;
1233         QString validModes = QString();
1234         while (!uncheckedModes.isEmpty()) {
1235             // Mode found in 1 left-most character, add it to the list
1236             if (net->prefixes().contains(uncheckedModes[0])) {
1237                 validModes.append(net->prefixToMode(uncheckedModes[0]));
1238             }
1239             // Remove this mode from the list of unchecked modes
1240             uncheckedModes = uncheckedModes.remove(0, 1);
1241         }
1242
1243         // Some IRC servers decide to not follow the spec, returning only -some- of the user
1244         // modes in WHO despite listing them all in NAMES.  For now, assume it can only add
1245         // and not take away.  *sigh*
1246         if (!validModes.isEmpty()) {
1247             if (targetChannel != "*") {
1248                 // Channel-specific modes received, apply to given channel only
1249                 IrcChannel *ircChan = net->ircChannel(targetChannel);
1250                 if (ircChan) {
1251                     // Do one mode at a time
1252                     // TODO Better way of syncing this without breaking protocol?
1253                     for (int i = 0; i < validModes.count(); ++i) {
1254                         ircChan->addUserMode(ircUser, validModes.at(i));
1255                     }
1256                 }
1257             } else {
1258                 // Modes apply to the user everywhere
1259                 ircUser->addUserModes(validModes);
1260             }
1261         }
1262     }
1263 }
1264
1265
1266 /* ERR_NOSUCHCHANNEL - "<channel name> :No such channel" */
1267 void CoreSessionEventProcessor::processIrcEvent403(IrcEventNumeric *e)
1268 {
1269     // If this is the result of an AutoWho, hide it.  It's confusing to show to the user.
1270     // Though the ":No such channel" remark should always be there, we should handle cases when it's
1271     // not included, too.
1272     if (!checkParamCount(e, 1))
1273         return;
1274
1275     QString channelOrNick = e->params()[0];
1276     // Check if channel name has a who in progress.
1277     // If not, then check if user nick exists and has a who in progress.
1278     if (coreNetwork(e)->isAutoWhoInProgress(channelOrNick)) {
1279         qDebug() << "Channel/nick" << channelOrNick << "no longer exists during AutoWho, ignoring";
1280         e->setFlag(EventManager::Silent);
1281     }
1282 }
1283
1284 /* ERR_ERRONEUSNICKNAME */
1285 void CoreSessionEventProcessor::processIrcEvent432(IrcEventNumeric *e)
1286 {
1287     if (!checkParamCount(e, 1))
1288         return;
1289
1290     QString errnick;
1291     if (e->params().count() < 2) {
1292         // handle unreal-ircd bug, where unreal ircd doesnt supply a TARGET in ERR_ERRONEUSNICKNAME during registration phase:
1293         // nick @@@
1294         // :irc.scortum.moep.net 432  @@@ :Erroneous Nickname: Illegal characters
1295         // correct server reply:
1296         // :irc.scortum.moep.net 432 * @@@ :Erroneous Nickname: Illegal characters
1297         e->params().prepend(e->target());
1298         e->setTarget("*");
1299     }
1300     errnick = e->params()[0];
1301
1302     tryNextNick(e, errnick, true /* erroneus */);
1303 }
1304
1305
1306 /* ERR_NICKNAMEINUSE */
1307 void CoreSessionEventProcessor::processIrcEvent433(IrcEventNumeric *e)
1308 {
1309     if (!checkParamCount(e, 1))
1310         return;
1311
1312     QString errnick = e->params().first();
1313
1314     // if there is a problem while connecting to the server -> we handle it
1315     // but only if our connection has not been finished yet...
1316     if (!e->network()->currentServer().isEmpty())
1317         return;
1318
1319     tryNextNick(e, errnick);
1320 }
1321
1322
1323 /* ERR_UNAVAILRESOURCE */
1324 void CoreSessionEventProcessor::processIrcEvent437(IrcEventNumeric *e)
1325 {
1326     if (!checkParamCount(e, 1))
1327         return;
1328
1329     QString errnick = e->params().first();
1330
1331     // if there is a problem while connecting to the server -> we handle it
1332     // but only if our connection has not been finished yet...
1333     if (!e->network()->currentServer().isEmpty())
1334         return;
1335
1336     if (!e->network()->isChannelName(errnick))
1337         tryNextNick(e, errnick);
1338 }
1339
1340
1341 /* template
1342 void CoreSessionEventProcessor::processIrcEvent(IrcEvent *e) {
1343   if(!checkParamCount(e, 1))
1344     return;
1345
1346 }
1347 */
1348
1349 /* Handle signals from Netsplit objects  */
1350
1351 void CoreSessionEventProcessor::handleNetsplitJoin(Network *net,
1352     const QString &channel,
1353     const QStringList &users,
1354     const QStringList &modes,
1355     const QString &quitMessage)
1356 {
1357     IrcChannel *ircChannel = net->ircChannel(channel);
1358     if (!ircChannel) {
1359         return;
1360     }
1361     QList<IrcUser *> ircUsers;
1362     QStringList newModes = modes;
1363     QStringList newUsers = users;
1364
1365     foreach(const QString &user, users) {
1366         IrcUser *iu = net->ircUser(nickFromMask(user));
1367         if (iu)
1368             ircUsers.append(iu);
1369         else { // the user already quit
1370             int idx = users.indexOf(user);
1371             newUsers.removeAt(idx);
1372             newModes.removeAt(idx);
1373         }
1374     }
1375
1376     ircChannel->joinIrcUsers(ircUsers, newModes);
1377     NetworkSplitEvent *event = new NetworkSplitEvent(EventManager::NetworkSplitJoin, net, channel, newUsers, quitMessage);
1378     emit newEvent(event);
1379 }
1380
1381
1382 void CoreSessionEventProcessor::handleNetsplitQuit(Network *net, const QString &channel, const QStringList &users, const QString &quitMessage)
1383 {
1384     NetworkSplitEvent *event = new NetworkSplitEvent(EventManager::NetworkSplitQuit, net, channel, users, quitMessage);
1385     emit newEvent(event);
1386     foreach(QString user, users) {
1387         IrcUser *iu = net->ircUser(nickFromMask(user));
1388         if (iu)
1389             iu->quit();
1390     }
1391 }
1392
1393
1394 void CoreSessionEventProcessor::handleEarlyNetsplitJoin(Network *net, const QString &channel, const QStringList &users, const QStringList &modes)
1395 {
1396     IrcChannel *ircChannel = net->ircChannel(channel);
1397     if (!ircChannel) {
1398         qDebug() << "handleEarlyNetsplitJoin(): channel " << channel << " invalid";
1399         return;
1400     }
1401     QList<NetworkEvent *> events;
1402     QList<IrcUser *> ircUsers;
1403     QStringList newModes = modes;
1404
1405     foreach(QString user, users) {
1406         IrcUser *iu = net->updateNickFromMask(user);
1407         if (iu) {
1408             ircUsers.append(iu);
1409             // fake event for scripts that consume join events
1410             events << new IrcEvent(EventManager::IrcEventJoin, net, iu->hostmask(), QStringList() << channel);
1411         }
1412         else {
1413             newModes.removeAt(users.indexOf(user));
1414         }
1415     }
1416     ircChannel->joinIrcUsers(ircUsers, newModes);
1417     foreach(NetworkEvent *event, events) {
1418         event->setFlag(EventManager::Fake); // ignore this in here!
1419         emit newEvent(event);
1420     }
1421 }
1422
1423
1424 void CoreSessionEventProcessor::handleNetsplitFinished()
1425 {
1426     Netsplit *n = qobject_cast<Netsplit *>(sender());
1427     Q_ASSERT(n);
1428     QHash<QString, Netsplit *> splithash  = _netsplits.take(n->network());
1429     splithash.remove(splithash.key(n));
1430     if (splithash.count())
1431         _netsplits[n->network()] = splithash;
1432     n->deleteLater();
1433 }
1434
1435
1436 void CoreSessionEventProcessor::destroyNetsplits(NetworkId netId)
1437 {
1438     Network *net = coreSession()->network(netId);
1439     if (!net)
1440         return;
1441
1442     QHash<QString, Netsplit *> splits = _netsplits.take(net);
1443     qDeleteAll(splits);
1444 }
1445
1446
1447 /*******************************/
1448 /******** CTCP HANDLING ********/
1449 /*******************************/
1450
1451 void CoreSessionEventProcessor::processCtcpEvent(CtcpEvent *e)
1452 {
1453     if (e->testFlag(EventManager::Self))
1454         return;  // ignore ctcp events generated by user input
1455
1456     if (e->type() != EventManager::CtcpEvent || e->ctcpType() != CtcpEvent::Query)
1457         return;
1458
1459     handle(e->ctcpCmd(), Q_ARG(CtcpEvent *, e));
1460 }
1461
1462
1463 void CoreSessionEventProcessor::defaultHandler(const QString &ctcpCmd, CtcpEvent *e)
1464 {
1465     // This handler is only there to avoid warnings for unknown CTCPs
1466     Q_UNUSED(e);
1467     Q_UNUSED(ctcpCmd);
1468 }
1469
1470
1471 void CoreSessionEventProcessor::handleCtcpAction(CtcpEvent *e)
1472 {
1473     // This handler is only there to feed CLIENTINFO
1474     Q_UNUSED(e);
1475 }
1476
1477
1478 void CoreSessionEventProcessor::handleCtcpClientinfo(CtcpEvent *e)
1479 {
1480     QStringList supportedHandlers;
1481     foreach(QString handler, providesHandlers())
1482     supportedHandlers << handler.toUpper();
1483     qSort(supportedHandlers);
1484     e->setReply(supportedHandlers.join(" "));
1485 }
1486
1487
1488 // http://www.irchelp.org/irchelp/rfc/ctcpspec.html
1489 // http://en.wikipedia.org/wiki/Direct_Client-to-Client
1490 void CoreSessionEventProcessor::handleCtcpDcc(CtcpEvent *e)
1491 {
1492     // DCC support is unfinished, experimental and potentially dangerous, so make it opt-in
1493     if (!Quassel::isOptionSet("enable-experimental-dcc")) {
1494         quInfo() << "DCC disabled, start core with --enable-experimental-dcc if you really want to try it out";
1495         return;
1496     }
1497
1498     // normal:  SEND <filename> <ip> <port> [<filesize>]
1499     // reverse: SEND <filename> <ip> 0 <filesize> <token>
1500     QStringList params = e->param().split(' ');
1501     if (params.count()) {
1502         QString cmd = params[0].toUpper();
1503         if (cmd == "SEND") {
1504             if (params.count() < 4) {
1505                 qWarning() << "Invalid DCC SEND request:" << e;  // TODO emit proper error to client
1506                 return;
1507             }
1508             QString filename = params[1];
1509             QHostAddress address;
1510             quint16 port = params[3].toUShort();
1511             quint64 size = 0;
1512             QString numIp = params[2]; // this is either IPv4 as a 32 bit value, or IPv6 (which always contains a colon)
1513             if (numIp.contains(':')) { // IPv6
1514                 if (!address.setAddress(numIp)) {
1515                     qWarning() << "Invalid IPv6:" << numIp;
1516                     return;
1517                 }
1518             }
1519             else {
1520                 address.setAddress(numIp.toUInt());
1521             }
1522
1523             if (port == 0) { // Reverse DCC is indicated by a 0 port
1524                 emit newEvent(new MessageEvent(Message::Error, e->network(), tr("Reverse DCC SEND not supported"), e->prefix(), e->target(), Message::None, e->timestamp()));
1525                 return;
1526             }
1527             if (port < 1024) {
1528                 qWarning() << "Privileged port requested:" << port; // FIXME ask user if this is ok
1529             }
1530
1531
1532             if (params.count() > 4) { // filesize is optional
1533                 size = params[4].toULong();
1534             }
1535
1536             // TODO: check if target is the right thing to use for the partner
1537             CoreTransfer *transfer = new CoreTransfer(Transfer::Direction::Receive, e->target(), filename, address, port, size, this);
1538             coreSession()->signalProxy()->synchronize(transfer);
1539             coreSession()->transferManager()->addTransfer(transfer);
1540         }
1541         else {
1542             emit newEvent(new MessageEvent(Message::Error, e->network(), tr("DCC %1 not supported").arg(cmd), e->prefix(), e->target(), Message::None, e->timestamp()));
1543             return;
1544         }
1545     }
1546 }
1547
1548
1549 void CoreSessionEventProcessor::handleCtcpPing(CtcpEvent *e)
1550 {
1551     e->setReply(e->param().isNull() ? "" : e->param());
1552 }
1553
1554
1555 void CoreSessionEventProcessor::handleCtcpTime(CtcpEvent *e)
1556 {
1557     e->setReply(QDateTime::currentDateTime().toString());
1558 }
1559
1560
1561 void CoreSessionEventProcessor::handleCtcpVersion(CtcpEvent *e)
1562 {
1563     e->setReply(QString("Quassel IRC %1 (built on %2) -- https://www.quassel-irc.org")
1564         .arg(Quassel::buildInfo().plainVersionString).arg(Quassel::buildInfo().commitDate));
1565 }