1 /***************************************************************************
2 * Copyright (C) 2005-2020 by the Quassel Project *
3 * devel@quassel-irc.org *
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. *
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. *
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 ***************************************************************************/
21 #include "coreuserinputhandler.h"
25 #include "ctcpparser.h"
32 CoreUserInputHandler::CoreUserInputHandler(CoreNetwork* parent)
33 : CoreBasicHandler(parent)
36 void CoreUserInputHandler::handleUserInput(const BufferInfo& bufferInfo, const QString& msg)
41 AliasManager::CommandList list = coreSession()->aliasManager().processInput(bufferInfo, msg);
43 for (int i = 0; i < list.count(); i++) {
44 QString cmd = list.at(i).second.section(' ', 0, 0).remove(0, 1).toUpper();
45 QString payload = list.at(i).second.section(' ', 1);
46 handle(cmd, Q_ARG(BufferInfo, list.at(i).first), Q_ARG(QString, payload));
50 // ====================
52 // ====================
53 void CoreUserInputHandler::handleAway(const BufferInfo& bufferInfo, const QString& msg, const bool skipFormatting)
56 if (msg.startsWith("-all")) {
57 if (msg.length() == 4) {
58 coreSession()->globalAway(QString(), skipFormatting);
61 Q_ASSERT(msg.length() > 4);
63 coreSession()->globalAway(msg.mid(5), skipFormatting);
67 issueAway(msg, true /* force away */, skipFormatting);
70 void CoreUserInputHandler::issueAway(const QString& msg, bool autoCheck, const bool skipFormatting)
72 QString awayMsg = msg;
73 IrcUser* me = network()->me();
75 // Only apply timestamp formatting when requested
76 // This avoids re-processing any existing away message when the core restarts, so chained escape
77 // percent signs won't get down-processed.
78 if (!skipFormatting) {
79 // Apply the timestamp formatting to the away message (if empty, nothing will happen)
80 awayMsg = formatCurrentDateTimeInString(awayMsg);
83 // if there is no message supplied we have to check if we are already away or not
84 if (autoCheck && msg.isEmpty()) {
85 if (me && !me->isAway()) {
86 Identity* identity = network()->identityPtr();
88 awayMsg = formatCurrentDateTimeInString(identity->awayReason());
90 if (awayMsg.isEmpty()) {
96 me->setAwayMessage(awayMsg);
98 putCmd("AWAY", serverEncode(awayMsg));
101 void CoreUserInputHandler::handleBan(const BufferInfo& bufferInfo, const QString& msg)
103 banOrUnban(bufferInfo, msg, true);
106 void CoreUserInputHandler::handleUnban(const BufferInfo& bufferInfo, const QString& msg)
108 banOrUnban(bufferInfo, msg, false);
111 void CoreUserInputHandler::banOrUnban(const BufferInfo& bufferInfo, const QString& msg, bool ban)
116 QStringList params = msg.split(" ");
118 if (!params.isEmpty() && isChannelName(params[0])) {
119 banChannel = params.takeFirst();
121 else if (bufferInfo.type() == BufferInfo::ChannelBuffer) {
122 banChannel = bufferInfo.bufferName();
125 emit displayMsg(NetworkInternalMessage(
127 BufferInfo::StatusBuffer,
129 QString("Error: channel unknown in command: /BAN %1").arg(msg)
134 if (!params.isEmpty() && !params.contains("!") && network()->ircUser(params[0])) {
135 IrcUser* ircuser = network()->ircUser(params[0]);
136 // generalizedHost changes <nick> to *!ident@*.sld.tld.
137 QString generalizedHost = ircuser->host();
138 if (generalizedHost.isEmpty()) {
139 emit displayMsg(NetworkInternalMessage(
141 BufferInfo::StatusBuffer,
143 QString("Error: host unknown in command: /BAN %1").arg(msg)
148 static QRegExp ipAddress(R"(\d+\.\d+\.\d+\.\d+)");
149 if (ipAddress.exactMatch(generalizedHost)) {
150 int lastDotPos = generalizedHost.lastIndexOf('.') + 1;
151 generalizedHost.replace(lastDotPos, generalizedHost.length() - lastDotPos, '*');
153 else if (generalizedHost.lastIndexOf(".") != -1 && generalizedHost.lastIndexOf(".", generalizedHost.lastIndexOf(".") - 1) != -1) {
154 int secondLastPeriodPosition = generalizedHost.lastIndexOf(".", generalizedHost.lastIndexOf(".") - 1);
155 generalizedHost.replace(0, secondLastPeriodPosition, "*");
157 banUser = QString("*!%1@%2").arg(ircuser->user(), generalizedHost);
160 banUser = params.join(" ");
163 QString banMode = ban ? "+b" : "-b";
164 QString banMsg = QString("MODE %1 %2 %3").arg(banChannel, banMode, banUser);
165 emit putRawLine(serverEncode(banMsg));
168 void CoreUserInputHandler::handleCtcp(const BufferInfo& bufferInfo, const QString& msg)
172 QString nick = msg.section(' ', 0, 0);
173 QString ctcpTag = msg.section(' ', 1, 1).toUpper();
174 if (ctcpTag.isEmpty())
177 QString message = msg.section(' ', 2);
178 QString verboseMessage = tr("sending CTCP-%1 request to %2").arg(ctcpTag).arg(nick);
180 if (ctcpTag == "PING") {
181 message = QString::number(QDateTime::currentMSecsSinceEpoch());
184 // FIXME make this a proper event
185 coreNetwork()->coreSession()->ctcpParser()->query(coreNetwork(), nick, ctcpTag, message);
186 if (!network()->capEnabled(IrcCap::ECHO_MESSAGE)) {
187 emit displayMsg(NetworkInternalMessage(
189 BufferInfo::StatusBuffer,
198 void CoreUserInputHandler::handleDelkey(const BufferInfo& bufferInfo, const QString& msg)
200 QString bufname = bufferInfo.bufferName().isNull() ? "" : bufferInfo.bufferName();
202 if (!bufferInfo.isValid())
205 if (!Cipher::neededFeaturesAvailable()) {
206 emit displayMsg(NetworkInternalMessage(
208 typeByTarget(bufname),
210 tr("Error: QCA provider plugin not found. It is usually provided by the qca-ossl plugin.")
215 QStringList parms = msg.split(' ', QString::SkipEmptyParts);
217 if (parms.isEmpty() && !bufferInfo.bufferName().isEmpty() && bufferInfo.acceptsRegularMessages())
218 parms.prepend(bufferInfo.bufferName());
220 if (parms.isEmpty()) {
221 emit displayMsg(NetworkInternalMessage(
223 typeByTarget(bufname),
225 tr("[usage] /delkey <nick|channel> deletes the encryption key for nick or channel or just /delkey when in a "
231 QString target = parms.at(0);
233 if (network()->cipherKey(target).isEmpty()) {
234 emit displayMsg(NetworkInternalMessage(
236 typeByTarget(bufname),
238 tr("No key has been set for %1.").arg(target)
243 network()->setCipherKey(target, QByteArray());
244 emit displayMsg(NetworkInternalMessage(
246 typeByTarget(bufname),
248 tr("The key for %1 has been deleted.").arg(target)
253 emit displayMsg(NetworkInternalMessage(
255 typeByTarget(bufname),
257 tr("Error: Setting an encryption key requires Quassel to have been built "
258 "with support for the Qt Cryptographic Architecture (QCA2) library. "
259 "Contact your distributor about a Quassel package with QCA2 "
260 "support, or rebuild Quassel with QCA2 present.")
265 void CoreUserInputHandler::doMode(const BufferInfo& bufferInfo, const QChar& addOrRemove, const QChar& mode, const QString& nicks)
268 int maxModes = network()->support("MODES").toInt(&isNumber);
269 if (!isNumber || maxModes == 0)
272 QStringList nickList;
273 if (nicks == "*" && bufferInfo.type() == BufferInfo::ChannelBuffer) { // All users in channel
274 const QList<IrcUser*> users = network()->ircChannel(bufferInfo.bufferName())->ircUsers();
275 for (IrcUser* user : users) {
276 if ((addOrRemove == '+' && !network()->ircChannel(bufferInfo.bufferName())->userModes(user).contains(mode))
277 || (addOrRemove == '-' && network()->ircChannel(bufferInfo.bufferName())->userModes(user).contains(mode)))
278 nickList.append(user->nick());
282 nickList = nicks.split(' ', QString::SkipEmptyParts);
285 if (nickList.count() == 0)
288 while (!nickList.isEmpty()) {
289 int amount = qMin(nickList.count(), maxModes);
290 QString m = addOrRemove;
291 for (int i = 0; i < amount; i++)
294 params << bufferInfo.bufferName() << m;
295 for (int i = 0; i < amount; i++)
296 params << nickList.takeFirst();
297 emit putCmd("MODE", serverEncode(params));
301 void CoreUserInputHandler::handleDeop(const BufferInfo& bufferInfo, const QString& nicks)
303 doMode(bufferInfo, '-', 'o', nicks);
306 void CoreUserInputHandler::handleDehalfop(const BufferInfo& bufferInfo, const QString& nicks)
308 doMode(bufferInfo, '-', 'h', nicks);
311 void CoreUserInputHandler::handleDevoice(const BufferInfo& bufferInfo, const QString& nicks)
313 doMode(bufferInfo, '-', 'v', nicks);
316 void CoreUserInputHandler::handleHalfop(const BufferInfo& bufferInfo, const QString& nicks)
318 doMode(bufferInfo, '+', 'h', nicks);
321 void CoreUserInputHandler::handleOp(const BufferInfo& bufferInfo, const QString& nicks)
323 doMode(bufferInfo, '+', 'o', nicks);
326 void CoreUserInputHandler::handleInvite(const BufferInfo& bufferInfo, const QString& msg)
329 params << msg << bufferInfo.bufferName();
330 emit putCmd("INVITE", serverEncode(params));
333 void CoreUserInputHandler::handleJoin(const BufferInfo& bufferInfo, const QString& msg)
335 Q_UNUSED(bufferInfo);
337 // trim spaces before chans or keys
338 QString sane_msg = msg;
339 sane_msg.replace(QRegExp(", +"), ",");
340 QStringList params = sane_msg.trimmed().split(" ");
342 QStringList chans = params[0].split(",", QString::SkipEmptyParts);
344 if (params.count() > 1)
345 keys = params[1].split(",");
348 for (i = 0; i < chans.count(); i++) {
349 if (!network()->isChannelName(chans[i]))
350 chans[i].prepend('#');
352 if (i < keys.count()) {
353 network()->addChannelKey(chans[i], keys[i]);
356 network()->removeChannelKey(chans[i]);
360 static const char* cmd = "JOIN";
362 QStringList joinChans, joinKeys;
363 int slicesize = chans.count();
364 QList<QByteArray> encodedParams;
366 // go through all to-be-joined channels and (re)build the join list
367 while (i < chans.count()) {
368 joinChans.append(chans.at(i));
369 if (i < keys.count())
370 joinKeys.append(keys.at(i));
372 // if the channel list we built so far either contains all requested channels or exceeds
373 // the desired amount of channels in this slice, try to send what we have so far
374 if (++i == chans.count() || joinChans.count() >= slicesize) {
376 params.append(joinChans.join(","));
377 params.append(joinKeys.join(","));
378 encodedParams = serverEncode(params);
379 // check if it fits in one command
380 if (lastParamOverrun(cmd, encodedParams) == 0) {
381 emit putCmd(cmd, encodedParams);
383 else if (slicesize > 1) {
384 // back to start of slice, try again with half the amount of channels
394 void CoreUserInputHandler::handleKeyx(const BufferInfo& bufferInfo, const QString& msg)
396 QString bufname = bufferInfo.bufferName().isNull() ? "" : bufferInfo.bufferName();
398 if (!bufferInfo.isValid())
401 if (!Cipher::neededFeaturesAvailable()) {
402 emit displayMsg(NetworkInternalMessage(
404 typeByTarget(bufname),
406 tr("Error: QCA provider plugin not found. It is usually provided by the qca-ossl plugin.")
411 QStringList parms = msg.split(' ', QString::SkipEmptyParts);
413 if (parms.count() == 0 && !bufferInfo.bufferName().isEmpty() && bufferInfo.acceptsRegularMessages())
414 parms.prepend(bufferInfo.bufferName());
415 else if (parms.count() != 1) {
416 emit displayMsg(NetworkInternalMessage(
418 typeByTarget(bufname),
420 tr("[usage] /keyx [<nick>] Initiates a DH1080 key exchange with the target.")
425 QString target = parms.at(0);
427 if (network()->isChannelName(target)) {
428 emit displayMsg(NetworkInternalMessage(
430 typeByTarget(bufname),
432 tr("It is only possible to exchange keys in a query buffer.")
437 Cipher* cipher = network()->cipher(target);
438 if (!cipher) // happens when there is no CoreIrcChannel for the target
441 QByteArray pubKey = cipher->initKeyExchange();
442 if (pubKey.isEmpty())
443 emit displayMsg(NetworkInternalMessage(
445 typeByTarget(bufname),
447 tr("Failed to initiate key exchange with %1.").arg(target)
450 QList<QByteArray> params;
451 params << serverEncode(target) << serverEncode("DH1080_INIT ") + pubKey;
452 emit putCmd("NOTICE", params);
453 emit displayMsg(NetworkInternalMessage(
455 typeByTarget(bufname),
457 tr("Initiated key exchange with %1.").arg(target)
462 emit displayMsg(NetworkInternalMessage(
464 typeByTarget(bufname),
466 tr("Error: Setting an encryption key requires Quassel to have been built "
467 "with support for the Qt Cryptographic Architecture (QCA) library. "
468 "Contact your distributor about a Quassel package with QCA "
469 "support, or rebuild Quassel with QCA present.")
474 void CoreUserInputHandler::handleKick(const BufferInfo& bufferInfo, const QString& msg)
476 QString nick = msg.section(' ', 0, 0, QString::SectionSkipEmpty);
477 QString reason = msg.section(' ', 1, -1, QString::SectionSkipEmpty).trimmed();
478 if (reason.isEmpty())
479 reason = network()->identityPtr()->kickReason();
481 QList<QByteArray> params;
482 params << serverEncode(bufferInfo.bufferName()) << serverEncode(nick) << channelEncode(bufferInfo.bufferName(), reason);
483 emit putCmd("KICK", params);
486 void CoreUserInputHandler::handleKill(const BufferInfo& bufferInfo, const QString& msg)
489 QString nick = msg.section(' ', 0, 0, QString::SectionSkipEmpty);
490 QString pass = msg.section(' ', 1, -1, QString::SectionSkipEmpty);
491 QList<QByteArray> params;
492 params << serverEncode(nick) << serverEncode(pass);
493 emit putCmd("KILL", params);
496 void CoreUserInputHandler::handleList(const BufferInfo& bufferInfo, const QString& msg)
499 emit putCmd("LIST", serverEncode(msg.split(' ', QString::SkipEmptyParts)));
502 void CoreUserInputHandler::handleMe(const BufferInfo& bufferInfo, const QString& msg)
504 if (bufferInfo.bufferName().isEmpty() || !bufferInfo.acceptsRegularMessages())
505 return; // server buffer
506 // FIXME make this a proper event
508 // Split apart messages at line feeds. The IRC protocol uses those to separate commands, so
509 // they need to be split into multiple messages.
510 QStringList messages = msg.split(QChar::LineFeed);
512 for (const auto& message : messages) {
513 // Handle each separated message independently
514 coreNetwork()->coreSession()->ctcpParser()->query(coreNetwork(), bufferInfo.bufferName(), "ACTION", message);
515 if (!network()->capEnabled(IrcCap::ECHO_MESSAGE)) {
516 emit displayMsg(NetworkInternalMessage(
519 bufferInfo.bufferName(),
528 void CoreUserInputHandler::handleMode(const BufferInfo& bufferInfo, const QString& msg)
532 QStringList params = msg.split(' ', QString::SkipEmptyParts);
533 if (!params.isEmpty()) {
534 if (params[0] == "-reset" && params.count() == 1) {
535 network()->resetPersistentModes();
536 emit displayMsg(NetworkInternalMessage(
538 BufferInfo::StatusBuffer,
540 tr("Your persistent modes have been reset.")
544 if (!network()->isChannelName(params[0]) && !network()->isMyNick(params[0]))
545 // If the first argument is neither a channel nor us (user modes are only to oneself)
546 // the current buffer is assumed to be the target.
547 // If the current buffer returns no name (e.g. status buffer), assume target is us.
548 params.prepend(!bufferInfo.bufferName().isEmpty() ? bufferInfo.bufferName() : network()->myNick());
549 if (network()->isMyNick(params[0]) && params.count() == 2)
550 network()->updateIssuedModes(params[1]);
553 // TODO handle correct encoding for buffer modes (channelEncode())
554 emit putCmd("MODE", serverEncode(params));
557 // TODO: show privmsgs
558 void CoreUserInputHandler::handleMsg(const BufferInfo& bufferInfo, const QString& msg)
560 Q_UNUSED(bufferInfo);
561 if (!msg.contains(' '))
564 QString target = msg.section(' ', 0, 0);
565 QString msgSection = msg.section(' ', 1);
567 std::function<QByteArray(const QString&, const QString&)> encodeFunc =
568 [this](const QString& target, const QString& message) -> QByteArray { return userEncode(target, message); };
571 putPrivmsg(target, msgSection, encodeFunc, network()->cipher(target));
573 putPrivmsg(target, msgSection, encodeFunc);
577 void CoreUserInputHandler::handleNick(const BufferInfo& bufferInfo, const QString& msg)
580 QString nick = msg.section(' ', 0, 0);
581 emit putCmd("NICK", serverEncode(nick));
584 void CoreUserInputHandler::handleNotice(const BufferInfo& bufferInfo, const QString& msg)
586 QString bufferName = msg.section(' ', 0, 0);
587 QList<QByteArray> params;
588 // Split apart messages at line feeds. The IRC protocol uses those to separate commands, so
589 // they need to be split into multiple messages.
590 QStringList messages = msg.section(' ', 1).split(QChar::LineFeed);
592 for (const auto& message : messages) {
593 // Handle each separated message independently
595 params << serverEncode(bufferName) << channelEncode(bufferInfo.bufferName(), message);
596 emit putCmd("NOTICE", params);
597 if (!network()->capEnabled(IrcCap::ECHO_MESSAGE)) {
598 emit displayMsg(NetworkInternalMessage(
600 typeByTarget(bufferName),
610 void CoreUserInputHandler::handleOper(const BufferInfo& bufferInfo, const QString& msg)
613 emit putRawLine(serverEncode(QString("OPER %1").arg(msg)));
616 void CoreUserInputHandler::handlePart(const BufferInfo& bufferInfo, const QString& msg)
618 QList<QByteArray> params;
621 // msg might contain either a channel name and/or a reaon, so we have to check if the first word is a known channel
622 QString channelName = msg.section(' ', 0, 0);
623 if (channelName.isEmpty() || !network()->ircChannel(channelName)) {
624 channelName = bufferInfo.bufferName();
628 partReason = msg.mid(channelName.length() + 1);
631 if (partReason.isEmpty())
632 partReason = network()->identityPtr()->partReason();
634 params << serverEncode(channelName) << channelEncode(bufferInfo.bufferName(), partReason);
635 emit putCmd("PART", params);
638 void CoreUserInputHandler::handlePing(const BufferInfo& bufferInfo, const QString& msg)
644 param = QTime::currentTime().toString("hh:mm:ss.zzz");
646 // Take priority so this won't get stuck behind other queued messages.
647 putCmd("PING", serverEncode(param), {}, {}, true);
650 void CoreUserInputHandler::handlePrint(const BufferInfo& bufferInfo, const QString& msg)
652 if (bufferInfo.bufferName().isEmpty() || !bufferInfo.acceptsRegularMessages())
653 return; // server buffer
655 QByteArray encMsg = channelEncode(bufferInfo.bufferName(), msg);
656 emit displayMsg(NetworkInternalMessage(
659 bufferInfo.bufferName(),
666 // TODO: implement queries
667 void CoreUserInputHandler::handleQuery(const BufferInfo& bufferInfo, const QString& msg)
670 QString target = msg.section(' ', 0, 0);
671 // Split apart messages at line feeds. The IRC protocol uses those to separate commands, so
672 // they need to be split into multiple messages.
673 QStringList messages = msg.section(' ', 1).split(QChar::LineFeed);
675 for (const auto& message : messages) {
676 // Handle each separated message independently
677 if (message.isEmpty()) {
678 emit displayMsg(NetworkInternalMessage(
680 BufferInfo::QueryBuffer,
682 tr("Starting query with %1").arg(target),
686 // handleMsg is a no-op if message is empty
689 if (!network()->capEnabled(IrcCap::ECHO_MESSAGE)) {
690 emit displayMsg(NetworkInternalMessage(
692 BufferInfo::QueryBuffer,
699 // handleMsg needs the target specified at the beginning of the message
700 handleMsg(bufferInfo, target + " " + message);
705 void CoreUserInputHandler::handleQuit(const BufferInfo& bufferInfo, const QString& msg)
708 network()->disconnectFromIrc(true, msg);
711 void CoreUserInputHandler::issueQuit(const QString& reason, bool forceImmediate)
713 // If needing an immediate QUIT (e.g. core shutdown), prepend this to the queue
714 emit putCmd("QUIT", serverEncode(reason), {}, {}, forceImmediate);
717 void CoreUserInputHandler::handleQuote(const BufferInfo& bufferInfo, const QString& msg)
720 emit putRawLine(serverEncode(msg));
723 void CoreUserInputHandler::handleSay(const BufferInfo& bufferInfo, const QString& msg)
725 if (bufferInfo.bufferName().isEmpty() || !bufferInfo.acceptsRegularMessages())
726 return; // server buffer
728 std::function<QByteArray(const QString&, const QString&)> encodeFunc =
729 [this](const QString& target, const QString& message) -> QByteArray { return channelEncode(target, message); };
731 // Split apart messages at line feeds. The IRC protocol uses those to separate commands, so
732 // they need to be split into multiple messages.
733 QStringList messages = msg.split(QChar::LineFeed, QString::SkipEmptyParts);
735 for (const auto& message : messages) {
736 // Handle each separated message independently
738 putPrivmsg(bufferInfo.bufferName(), message, encodeFunc, network()->cipher(bufferInfo.bufferName()));
740 putPrivmsg(bufferInfo.bufferName(), message, encodeFunc);
742 if (!network()->capEnabled(IrcCap::ECHO_MESSAGE)) {
743 emit displayMsg(NetworkInternalMessage(
746 bufferInfo.bufferName(),
755 void CoreUserInputHandler::handleSetkey(const BufferInfo& bufferInfo, const QString& msg)
757 QString bufname = bufferInfo.bufferName().isNull() ? "" : bufferInfo.bufferName();
759 if (!bufferInfo.isValid())
762 if (!Cipher::neededFeaturesAvailable()) {
763 emit displayMsg(NetworkInternalMessage(
765 typeByTarget(bufname),
767 tr("Error: QCA provider plugin not found. It is usually provided by the qca-ossl plugin.")
772 QStringList parms = msg.split(' ', QString::SkipEmptyParts);
774 if (parms.count() == 1 && !bufferInfo.bufferName().isEmpty() && bufferInfo.acceptsRegularMessages())
775 parms.prepend(bufferInfo.bufferName());
776 else if (parms.count() != 2) {
777 emit displayMsg(NetworkInternalMessage(
779 typeByTarget(bufname),
781 tr("[usage] /setkey <nick|channel> <key> sets the encryption key for nick or channel. "
782 "/setkey <key> when in a channel or query buffer sets the key for it. "
783 "Prefix <key> by cbc: or ebc: to explicitly set the encryption mode respectively. Default is CBC.")
788 QString target = parms.at(0);
789 QByteArray key = parms.at(1).toLocal8Bit();
790 network()->setCipherKey(target, key);
792 emit displayMsg(NetworkInternalMessage(
794 typeByTarget(bufname),
796 tr("The key for %1 has been set.").arg(target)
800 emit displayMsg(NetworkInternalMessage(
802 typeByTarget(bufname),
804 tr("Error: Setting an encryption key requires Quassel to have been built "
805 "with support for the Qt Cryptographic Architecture (QCA) library. "
806 "Contact your distributor about a Quassel package with QCA "
807 "support, or rebuild Quassel with QCA present.")
812 void CoreUserInputHandler::handleSetname(const BufferInfo& bufferInfo, const QString& msg)
815 emit putCmd("SETNAME", serverEncode(msg));
818 void CoreUserInputHandler::handleShowkey(const BufferInfo& bufferInfo, const QString& msg)
820 QString bufname = bufferInfo.bufferName().isNull() ? "" : bufferInfo.bufferName();
822 if (!bufferInfo.isValid())
825 if (!Cipher::neededFeaturesAvailable()) {
826 emit displayMsg(NetworkInternalMessage(
828 typeByTarget(bufname),
830 tr("Error: QCA provider plugin not found. It is usually provided by the qca-ossl plugin.")
835 QStringList parms = msg.split(' ', QString::SkipEmptyParts);
837 if (parms.isEmpty() && !bufferInfo.bufferName().isEmpty() && bufferInfo.acceptsRegularMessages())
838 parms.prepend(bufferInfo.bufferName());
840 if (parms.isEmpty()) {
841 emit displayMsg(NetworkInternalMessage(
843 typeByTarget(bufname),
845 tr("[usage] /showkey <nick|channel> shows the encryption key for nick or channel or just /showkey when in a "
851 QString target = parms.at(0);
852 QByteArray key = network()->cipherKey(target);
855 emit displayMsg(NetworkInternalMessage(
857 typeByTarget(bufname),
859 tr("No key has been set for %1.").arg(target)
864 emit displayMsg(NetworkInternalMessage(
866 typeByTarget(bufname),
868 tr("The key for %1 is %2:%3").arg(target, network()->cipherUsesCBC(target) ? "CBC" : "ECB", QString(key))
873 emit displayMsg(NetworkInternalMessage(
875 typeByTarget(bufname),
877 tr("Error: Setting an encryption key requires Quassel to have been built "
878 "with support for the Qt Cryptographic Architecture (QCA2) library. "
879 "Contact your distributor about a Quassel package with QCA2 "
880 "support, or rebuild Quassel with QCA2 present.")
885 void CoreUserInputHandler::handleTopic(const BufferInfo& bufferInfo, const QString& msg)
887 if (bufferInfo.bufferName().isEmpty() || !bufferInfo.acceptsRegularMessages())
890 QList<QByteArray> params;
891 params << serverEncode(bufferInfo.bufferName());
893 if (!msg.isEmpty()) {
895 params << encrypt(bufferInfo.bufferName(), channelEncode(bufferInfo.bufferName(), msg));
897 params << channelEncode(bufferInfo.bufferName(), msg);
901 emit putCmd("TOPIC", params);
904 void CoreUserInputHandler::handleVoice(const BufferInfo& bufferInfo, const QString& msg)
906 QStringList nicks = msg.split(' ', QString::SkipEmptyParts);
908 for (int i = 0; i < nicks.count(); i++)
911 params << bufferInfo.bufferName() << m << nicks;
912 emit putCmd("MODE", serverEncode(params));
915 void CoreUserInputHandler::handleWait(const BufferInfo& bufferInfo, const QString& msg)
917 int splitPos = msg.indexOf(';');
922 int delay = msg.left(splitPos).trimmed().toInt(&ok);
928 QString command = msg.mid(splitPos + 1).trimmed();
929 if (command.isEmpty())
932 _delayedCommands[startTimer(delay)] = Command(bufferInfo, command);
935 void CoreUserInputHandler::handleWho(const BufferInfo& bufferInfo, const QString& msg)
938 emit putCmd("WHO", serverEncode(msg.split(' ')));
941 void CoreUserInputHandler::handleWhois(const BufferInfo& bufferInfo, const QString& msg)
944 emit putCmd("WHOIS", serverEncode(msg.split(' ')));
947 void CoreUserInputHandler::handleWhowas(const BufferInfo& bufferInfo, const QString& msg)
950 emit putCmd("WHOWAS", serverEncode(msg.split(' ')));
953 void CoreUserInputHandler::defaultHandler(QString cmd, const BufferInfo& bufferInfo, const QString& msg)
955 Q_UNUSED(bufferInfo);
956 emit putCmd(serverEncode(cmd.toUpper()), serverEncode(msg.split(" ")));
959 void CoreUserInputHandler::putPrivmsg(const QString& target,
960 const QString& message,
961 std::function<QByteArray(const QString&, const QString&)> encodeFunc,
965 QString cmd("PRIVMSG");
966 QByteArray targetEnc = serverEncode(target);
968 std::function<QList<QByteArray>(QString&)> cmdGenerator = [&](QString& splitMsg) -> QList<QByteArray> {
969 QByteArray splitMsgEnc = encodeFunc(target, splitMsg);
972 if (cipher && !cipher->key().isEmpty() && !splitMsg.isEmpty()) {
973 cipher->encrypt(splitMsgEnc);
976 return QList<QByteArray>() << targetEnc << splitMsgEnc;
979 putCmd(cmd, network()->splitMessage(cmd, message, cmdGenerator));
982 // returns 0 if the message will not be chopped by the irc server or number of chopped bytes if message is too long
983 int CoreUserInputHandler::lastParamOverrun(const QString& cmd, const QList<QByteArray>& params)
985 // the server will pass our message truncated to 512 bytes including CRLF with the following format:
986 // ":prefix COMMAND param0 param1 :lastparam"
987 // where prefix = "nickname!user@host"
988 // that means that the last message can be as long as:
989 // 512 - nicklen - userlen - hostlen - commandlen - sum(param[0]..param[n-1])) - 2 (for CRLF) - 4 (":!@" + 1space between prefix and
990 // command) - max(paramcount - 1, 0) (space for simple params) - 2 (space and colon for last param)
991 IrcUser* me = network()->me();
992 int maxLen = 480 - cmd.toLatin1().count(); // educated guess in case we don't know us (yet?)
995 maxLen = 512 - serverEncode(me->nick()).count() - serverEncode(me->user()).count() - serverEncode(me->host()).count()
996 - cmd.toLatin1().count() - 6;
998 if (!params.isEmpty()) {
999 for (int i = 0; i < params.count() - 1; i++) {
1000 maxLen -= (params[i].count() + 1);
1002 maxLen -= 2; // " :" last param separator;
1004 if (params.last().count() > maxLen) {
1005 return params.last().count() - maxLen;
1017 QByteArray CoreUserInputHandler::encrypt(const QString& target, const QByteArray& message_, bool* didEncrypt) const
1020 *didEncrypt = false;
1022 if (message_.isEmpty())
1025 if (!Cipher::neededFeaturesAvailable())
1028 Cipher* cipher = network()->cipher(target);
1029 if (!cipher || cipher->key().isEmpty())
1032 QByteArray message = message_;
1033 bool result = cipher->encrypt(message);
1035 *didEncrypt = result;
1042 void CoreUserInputHandler::timerEvent(QTimerEvent* event)
1044 if (!_delayedCommands.contains(event->timerId())) {
1045 QObject::timerEvent(event);
1048 BufferInfo bufferInfo = _delayedCommands[event->timerId()].bufferInfo;
1049 QString rawCommand = _delayedCommands[event->timerId()].command;
1050 _delayedCommands.remove(event->timerId());
1053 // the stored command might be the result of an alias expansion, so we need to split it up again
1054 QStringList commands = rawCommand.split(QRegExp("; ?"));
1055 for (const QString& command : commands) {
1056 handleUserInput(bufferInfo, command);