1 /***************************************************************************
2 * Copyright (C) 2005-2018 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"
33 CoreUserInputHandler::CoreUserInputHandler(CoreNetwork *parent)
34 : CoreBasicHandler(parent)
39 void CoreUserInputHandler::handleUserInput(const BufferInfo &bufferInfo, const QString &msg)
44 AliasManager::CommandList list = coreSession()->aliasManager().processInput(bufferInfo, msg);
46 for (int i = 0; i < list.count(); i++) {
47 QString cmd = list.at(i).second.section(' ', 0, 0).remove(0, 1).toUpper();
48 QString payload = list.at(i).second.section(' ', 1);
49 handle(cmd, Q_ARG(BufferInfo, list.at(i).first), Q_ARG(QString, payload));
54 // ====================
56 // ====================
57 void CoreUserInputHandler::handleAway(const BufferInfo &bufferInfo, const QString &msg,
58 const bool skipFormatting)
61 if (msg.startsWith("-all")) {
62 if (msg.length() == 4) {
63 coreSession()->globalAway(QString(), skipFormatting);
66 Q_ASSERT(msg.length() > 4);
68 coreSession()->globalAway(msg.mid(5), skipFormatting);
72 issueAway(msg, true /* force away */, skipFormatting);
76 void CoreUserInputHandler::issueAway(const QString &msg, bool autoCheck, const bool skipFormatting)
78 QString awayMsg = msg;
79 IrcUser *me = network()->me();
81 // Only apply timestamp formatting when requested
82 // This avoids re-processing any existing away message when the core restarts, so chained escape
83 // percent signs won't get down-processed.
84 if (!skipFormatting) {
85 // Apply the timestamp formatting to the away message (if empty, nothing will happen)
86 awayMsg = formatCurrentDateTimeInString(awayMsg);
89 // if there is no message supplied we have to check if we are already away or not
90 if (autoCheck && msg.isEmpty()) {
91 if (me && !me->isAway()) {
92 Identity *identity = network()->identityPtr();
94 awayMsg = formatCurrentDateTimeInString(identity->awayReason());
96 if (awayMsg.isEmpty()) {
102 me->setAwayMessage(awayMsg);
104 putCmd("AWAY", serverEncode(awayMsg));
108 void CoreUserInputHandler::handleBan(const BufferInfo &bufferInfo, const QString &msg)
110 banOrUnban(bufferInfo, msg, true);
114 void CoreUserInputHandler::handleUnban(const BufferInfo &bufferInfo, const QString &msg)
116 banOrUnban(bufferInfo, msg, false);
120 void CoreUserInputHandler::banOrUnban(const BufferInfo &bufferInfo, const QString &msg, bool ban)
125 QStringList params = msg.split(" ");
127 if (!params.isEmpty() && isChannelName(params[0])) {
128 banChannel = params.takeFirst();
130 else if (bufferInfo.type() == BufferInfo::ChannelBuffer) {
131 banChannel = bufferInfo.bufferName();
134 emit displayMsg(Message::Error, BufferInfo::StatusBuffer, "", QString("Error: channel unknown in command: /BAN %1").arg(msg));
138 if (!params.isEmpty() && !params.contains("!") && network()->ircUser(params[0])) {
139 IrcUser *ircuser = network()->ircUser(params[0]);
140 // generalizedHost changes <nick> to *!ident@*.sld.tld.
141 QString generalizedHost = ircuser->host();
142 if (generalizedHost.isEmpty()) {
143 emit displayMsg(Message::Error, BufferInfo::StatusBuffer, "", QString("Error: host unknown in command: /BAN %1").arg(msg));
147 static QRegExp ipAddress("\\d+\\.\\d+\\.\\d+\\.\\d+");
148 if (ipAddress.exactMatch(generalizedHost)) {
149 int lastDotPos = generalizedHost.lastIndexOf('.') + 1;
150 generalizedHost.replace(lastDotPos, generalizedHost.length() - lastDotPos, '*');
152 else if (generalizedHost.lastIndexOf(".") != -1 && generalizedHost.lastIndexOf(".", generalizedHost.lastIndexOf(".")-1) != -1) {
153 int secondLastPeriodPosition = generalizedHost.lastIndexOf(".", generalizedHost.lastIndexOf(".")-1);
154 generalizedHost.replace(0, secondLastPeriodPosition, "*");
156 banUser = QString("*!%1@%2").arg(ircuser->user(), generalizedHost);
159 banUser = params.join(" ");
162 QString banMode = ban ? "+b" : "-b";
163 QString banMsg = QString("MODE %1 %2 %3").arg(banChannel, banMode, banUser);
164 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 emit displayMsg(Message::Action, BufferInfo::StatusBuffer, "", verboseMessage,
187 network()->myNick(), Message::Flag::Self);
191 void CoreUserInputHandler::handleDelkey(const BufferInfo &bufferInfo, const QString &msg)
193 QString bufname = bufferInfo.bufferName().isNull() ? "" : bufferInfo.bufferName();
195 if (!bufferInfo.isValid())
198 if (!Cipher::neededFeaturesAvailable()) {
199 emit displayMsg(Message::Error, typeByTarget(bufname), bufname, tr("Error: QCA provider plugin not found. It is usually provided by the qca-ossl plugin."));
203 QStringList parms = msg.split(' ', QString::SkipEmptyParts);
205 if (parms.isEmpty() && !bufferInfo.bufferName().isEmpty() && bufferInfo.acceptsRegularMessages())
206 parms.prepend(bufferInfo.bufferName());
208 if (parms.isEmpty()) {
209 emit displayMsg(Message::Info, typeByTarget(bufname), bufname,
210 tr("[usage] /delkey <nick|channel> deletes the encryption key for nick or channel or just /delkey when in a channel or query."));
214 QString target = parms.at(0);
216 if (network()->cipherKey(target).isEmpty()) {
217 emit displayMsg(Message::Info, typeByTarget(bufname), bufname, tr("No key has been set for %1.").arg(target));
221 network()->setCipherKey(target, QByteArray());
222 emit displayMsg(Message::Info, typeByTarget(bufname), bufname, tr("The key for %1 has been deleted.").arg(target));
226 emit displayMsg(Message::Error, typeByTarget(bufname), bufname, tr("Error: Setting an encryption key requires Quassel to have been built "
227 "with support for the Qt Cryptographic Architecture (QCA2) library. "
228 "Contact your distributor about a Quassel package with QCA2 "
229 "support, or rebuild Quassel with QCA2 present."));
233 void CoreUserInputHandler::doMode(const BufferInfo &bufferInfo, const QChar& addOrRemove, const QChar& mode, const QString &nicks)
237 int maxModes = network()->support("MODES").toInt(&isNumber);
238 if (!isNumber || maxModes == 0) maxModes = 1;
240 QStringList nickList;
241 if (nicks == "*" && bufferInfo.type() == BufferInfo::ChannelBuffer) { // All users in channel
242 const QList<IrcUser*> users = network()->ircChannel(bufferInfo.bufferName())->ircUsers();
243 foreach(IrcUser *user, users) {
244 if ((addOrRemove == '+' && !network()->ircChannel(bufferInfo.bufferName())->userModes(user).contains(mode))
245 || (addOrRemove == '-' && network()->ircChannel(bufferInfo.bufferName())->userModes(user).contains(mode)))
246 nickList.append(user->nick());
249 nickList = nicks.split(' ', QString::SkipEmptyParts);
252 if (nickList.count() == 0) return;
254 while (!nickList.isEmpty()) {
255 int amount = qMin(nickList.count(), maxModes);
256 QString m = addOrRemove; for(int i = 0; i < amount; i++) m += mode;
258 params << bufferInfo.bufferName() << m;
259 for(int i = 0; i < amount; i++) params << nickList.takeFirst();
260 emit putCmd("MODE", serverEncode(params));
265 void CoreUserInputHandler::handleDeop(const BufferInfo &bufferInfo, const QString &nicks)
267 doMode(bufferInfo, '-', 'o', nicks);
271 void CoreUserInputHandler::handleDehalfop(const BufferInfo &bufferInfo, const QString &nicks)
273 doMode(bufferInfo, '-', 'h', nicks);
277 void CoreUserInputHandler::handleDevoice(const BufferInfo &bufferInfo, const QString &nicks)
279 doMode(bufferInfo, '-', 'v', nicks);
282 void CoreUserInputHandler::handleHalfop(const BufferInfo &bufferInfo, const QString &nicks)
284 doMode(bufferInfo, '+', 'h', nicks);
287 void CoreUserInputHandler::handleOp(const BufferInfo &bufferInfo, const QString &nicks) {
288 doMode(bufferInfo, '+', 'o', nicks);
292 void CoreUserInputHandler::handleInvite(const BufferInfo &bufferInfo, const QString &msg)
295 params << msg << bufferInfo.bufferName();
296 emit putCmd("INVITE", serverEncode(params));
300 void CoreUserInputHandler::handleJoin(const BufferInfo &bufferInfo, const QString &msg)
302 Q_UNUSED(bufferInfo);
304 // trim spaces before chans or keys
305 QString sane_msg = msg;
306 sane_msg.replace(QRegExp(", +"), ",");
307 QStringList params = sane_msg.trimmed().split(" ");
309 QStringList chans = params[0].split(",", QString::SkipEmptyParts);
311 if (params.count() > 1)
312 keys = params[1].split(",");
315 for (i = 0; i < chans.count(); i++) {
316 if (!network()->isChannelName(chans[i]))
317 chans[i].prepend('#');
319 if (i < keys.count()) {
320 network()->addChannelKey(chans[i], keys[i]);
323 network()->removeChannelKey(chans[i]);
327 static const char *cmd = "JOIN";
329 QStringList joinChans, joinKeys;
330 int slicesize = chans.count();
331 QList<QByteArray> encodedParams;
333 // go through all to-be-joined channels and (re)build the join list
334 while (i < chans.count()) {
335 joinChans.append(chans.at(i));
336 if (i < keys.count())
337 joinKeys.append(keys.at(i));
339 // if the channel list we built so far either contains all requested channels or exceeds
340 // the desired amount of channels in this slice, try to send what we have so far
341 if (++i == chans.count() || joinChans.count() >= slicesize) {
343 params.append(joinChans.join(","));
344 params.append(joinKeys.join(","));
345 encodedParams = serverEncode(params);
346 // check if it fits in one command
347 if (lastParamOverrun(cmd, encodedParams) == 0) {
348 emit putCmd(cmd, encodedParams);
350 else if (slicesize > 1) {
351 // back to start of slice, try again with half the amount of channels
362 void CoreUserInputHandler::handleKeyx(const BufferInfo &bufferInfo, const QString &msg)
364 QString bufname = bufferInfo.bufferName().isNull() ? "" : bufferInfo.bufferName();
366 if (!bufferInfo.isValid())
369 if (!Cipher::neededFeaturesAvailable()) {
370 emit displayMsg(Message::Error, typeByTarget(bufname), bufname, tr("Error: QCA provider plugin not found. It is usually provided by the qca-ossl plugin."));
374 QStringList parms = msg.split(' ', QString::SkipEmptyParts);
376 if (parms.count() == 0 && !bufferInfo.bufferName().isEmpty() && bufferInfo.acceptsRegularMessages())
377 parms.prepend(bufferInfo.bufferName());
378 else if (parms.count() != 1) {
379 emit displayMsg(Message::Info, typeByTarget(bufname), bufname,
380 tr("[usage] /keyx [<nick>] Initiates a DH1080 key exchange with the target."));
384 QString target = parms.at(0);
386 if (network()->isChannelName(target)) {
387 emit displayMsg(Message::Info, typeByTarget(bufname), bufname, tr("It is only possible to exchange keys in a query buffer."));
391 Cipher *cipher = network()->cipher(target);
392 if (!cipher) // happens when there is no CoreIrcChannel for the target
395 QByteArray pubKey = cipher->initKeyExchange();
396 if (pubKey.isEmpty())
397 emit displayMsg(Message::Error, typeByTarget(bufname), bufname, tr("Failed to initiate key exchange with %1.").arg(target));
399 QList<QByteArray> params;
400 params << serverEncode(target) << serverEncode("DH1080_INIT ") + pubKey;
401 emit putCmd("NOTICE", params);
402 emit displayMsg(Message::Info, typeByTarget(bufname), bufname, tr("Initiated key exchange with %1.").arg(target));
406 emit displayMsg(Message::Error, typeByTarget(bufname), bufname, tr("Error: Setting an encryption key requires Quassel to have been built "
407 "with support for the Qt Cryptographic Architecture (QCA) library. "
408 "Contact your distributor about a Quassel package with QCA "
409 "support, or rebuild Quassel with QCA present."));
414 void CoreUserInputHandler::handleKick(const BufferInfo &bufferInfo, const QString &msg)
416 QString nick = msg.section(' ', 0, 0, QString::SectionSkipEmpty);
417 QString reason = msg.section(' ', 1, -1, QString::SectionSkipEmpty).trimmed();
418 if (reason.isEmpty())
419 reason = network()->identityPtr()->kickReason();
421 QList<QByteArray> params;
422 params << serverEncode(bufferInfo.bufferName()) << serverEncode(nick) << channelEncode(bufferInfo.bufferName(), reason);
423 emit putCmd("KICK", params);
427 void CoreUserInputHandler::handleKill(const BufferInfo &bufferInfo, const QString &msg)
430 QString nick = msg.section(' ', 0, 0, QString::SectionSkipEmpty);
431 QString pass = msg.section(' ', 1, -1, QString::SectionSkipEmpty);
432 QList<QByteArray> params;
433 params << serverEncode(nick) << serverEncode(pass);
434 emit putCmd("KILL", params);
438 void CoreUserInputHandler::handleList(const BufferInfo &bufferInfo, const QString &msg)
441 emit putCmd("LIST", serverEncode(msg.split(' ', QString::SkipEmptyParts)));
445 void CoreUserInputHandler::handleMe(const BufferInfo &bufferInfo, const QString &msg)
447 if (bufferInfo.bufferName().isEmpty() || !bufferInfo.acceptsRegularMessages())
448 return; // server buffer
449 // FIXME make this a proper event
451 // Split apart messages at line feeds. The IRC protocol uses those to separate commands, so
452 // they need to be split into multiple messages.
453 QStringList messages = msg.split(QChar::LineFeed);
455 foreach (auto message, messages) {
456 // Handle each separated message independently
457 coreNetwork()->coreSession()->ctcpParser()->query(coreNetwork(), bufferInfo.bufferName(),
459 emit displayMsg(Message::Action, bufferInfo.type(), bufferInfo.bufferName(), message,
460 network()->myNick(), Message::Self);
465 void CoreUserInputHandler::handleMode(const BufferInfo &bufferInfo, const QString &msg)
469 QStringList params = msg.split(' ', QString::SkipEmptyParts);
470 if (!params.isEmpty()) {
471 if (params[0] == "-reset" && params.count() == 1) {
472 network()->resetPersistentModes();
473 emit displayMsg(Message::Info, BufferInfo::StatusBuffer, "",
474 tr("Your persistent modes have been reset."));
477 if (!network()->isChannelName(params[0]) && !network()->isMyNick(params[0]))
478 // If the first argument is neither a channel nor us (user modes are only to oneself)
479 // the current buffer is assumed to be the target.
480 // If the current buffer returns no name (e.g. status buffer), assume target is us.
481 params.prepend(!bufferInfo.bufferName().isEmpty() ?
482 bufferInfo.bufferName() : network()->myNick());
483 if (network()->isMyNick(params[0]) && params.count() == 2)
484 network()->updateIssuedModes(params[1]);
487 // TODO handle correct encoding for buffer modes (channelEncode())
488 emit putCmd("MODE", serverEncode(params));
492 // TODO: show privmsgs
493 void CoreUserInputHandler::handleMsg(const BufferInfo &bufferInfo, const QString &msg)
495 Q_UNUSED(bufferInfo);
496 if (!msg.contains(' '))
499 QString target = msg.section(' ', 0, 0);
500 QString msgSection = msg.section(' ', 1);
502 std::function<QByteArray(const QString &, const QString &)> encodeFunc = [this] (const QString &target, const QString &message) -> QByteArray {
503 return userEncode(target, message);
507 putPrivmsg(target, msgSection, encodeFunc, network()->cipher(target));
509 putPrivmsg(target, msgSection, encodeFunc);
514 void CoreUserInputHandler::handleNick(const BufferInfo &bufferInfo, const QString &msg)
517 QString nick = msg.section(' ', 0, 0);
518 emit putCmd("NICK", serverEncode(nick));
522 void CoreUserInputHandler::handleNotice(const BufferInfo &bufferInfo, const QString &msg)
524 QString bufferName = msg.section(' ', 0, 0);
525 QList<QByteArray> params;
526 // Split apart messages at line feeds. The IRC protocol uses those to separate commands, so
527 // they need to be split into multiple messages.
528 QStringList messages = msg.section(' ', 1).split(QChar::LineFeed);
530 foreach (auto message, messages) {
531 // Handle each separated message independently
533 params << serverEncode(bufferName) << channelEncode(bufferInfo.bufferName(), message);
534 emit putCmd("NOTICE", params);
535 emit displayMsg(Message::Notice, typeByTarget(bufferName), bufferName, message,
536 network()->myNick(), Message::Self);
542 void CoreUserInputHandler::handleOper(const BufferInfo &bufferInfo, const QString &msg)
545 emit putRawLine(serverEncode(QString("OPER %1").arg(msg)));
549 void CoreUserInputHandler::handlePart(const BufferInfo &bufferInfo, const QString &msg)
551 QList<QByteArray> params;
554 // msg might contain either a channel name and/or a reaon, so we have to check if the first word is a known channel
555 QString channelName = msg.section(' ', 0, 0);
556 if (channelName.isEmpty() || !network()->ircChannel(channelName)) {
557 channelName = bufferInfo.bufferName();
561 partReason = msg.mid(channelName.length() + 1);
564 if (partReason.isEmpty())
565 partReason = network()->identityPtr()->partReason();
567 params << serverEncode(channelName) << channelEncode(bufferInfo.bufferName(), partReason);
568 emit putCmd("PART", params);
572 void CoreUserInputHandler::handlePing(const BufferInfo &bufferInfo, const QString &msg)
578 param = QTime::currentTime().toString("hh:mm:ss.zzz");
580 // Take priority so this won't get stuck behind other queued messages.
581 putCmd("PING", serverEncode(param), QByteArray(), true);
585 void CoreUserInputHandler::handlePrint(const BufferInfo &bufferInfo, const QString &msg)
587 if (bufferInfo.bufferName().isEmpty() || !bufferInfo.acceptsRegularMessages())
588 return; // server buffer
590 QByteArray encMsg = channelEncode(bufferInfo.bufferName(), msg);
591 emit displayMsg(Message::Info, bufferInfo.type(), bufferInfo.bufferName(), msg, network()->myNick(), Message::Self);
595 // TODO: implement queries
596 void CoreUserInputHandler::handleQuery(const BufferInfo &bufferInfo, const QString &msg)
599 QString target = msg.section(' ', 0, 0);
600 // Split apart messages at line feeds. The IRC protocol uses those to separate commands, so
601 // they need to be split into multiple messages.
602 QStringList messages = msg.section(' ', 1).split(QChar::LineFeed);
604 foreach (auto message, messages) {
605 // Handle each separated message independently
606 if (message.isEmpty()) {
607 emit displayMsg(Message::Server, BufferInfo::QueryBuffer, target,
608 tr("Starting query with %1").arg(target), network()->myNick(),
610 // handleMsg is a no-op if message is empty
612 emit displayMsg(Message::Plain, BufferInfo::QueryBuffer, target, message,
613 network()->myNick(), Message::Self);
614 // handleMsg needs the target specified at the beginning of the message
615 handleMsg(bufferInfo, target + " " + message);
621 void CoreUserInputHandler::handleQuit(const BufferInfo &bufferInfo, const QString &msg)
624 network()->disconnectFromIrc(true, msg);
628 void CoreUserInputHandler::issueQuit(const QString &reason, bool forceImmediate)
630 // If needing an immediate QUIT (e.g. core shutdown), prepend this to the queue
631 emit putCmd("QUIT", serverEncode(reason), QByteArray(), forceImmediate);
635 void CoreUserInputHandler::handleQuote(const BufferInfo &bufferInfo, const QString &msg)
638 emit putRawLine(serverEncode(msg));
642 void CoreUserInputHandler::handleSay(const BufferInfo &bufferInfo, const QString &msg)
644 if (bufferInfo.bufferName().isEmpty() || !bufferInfo.acceptsRegularMessages())
645 return; // server buffer
647 std::function<QByteArray(const QString &, const QString &)> encodeFunc = [this] (const QString &target, const QString &message) -> QByteArray {
648 return channelEncode(target, message);
651 // Split apart messages at line feeds. The IRC protocol uses those to separate commands, so
652 // they need to be split into multiple messages.
653 QStringList messages = msg.split(QChar::LineFeed, QString::SkipEmptyParts);
655 foreach (auto message, messages) {
656 // Handle each separated message independently
658 putPrivmsg(bufferInfo.bufferName(), message, encodeFunc,
659 network()->cipher(bufferInfo.bufferName()));
661 putPrivmsg(bufferInfo.bufferName(), message, encodeFunc);
663 emit displayMsg(Message::Plain, bufferInfo.type(), bufferInfo.bufferName(), message,
664 network()->myNick(), Message::Self);
669 void CoreUserInputHandler::handleSetkey(const BufferInfo &bufferInfo, const QString &msg)
671 QString bufname = bufferInfo.bufferName().isNull() ? "" : bufferInfo.bufferName();
673 if (!bufferInfo.isValid())
676 if (!Cipher::neededFeaturesAvailable()) {
677 emit displayMsg(Message::Error, typeByTarget(bufname), bufname, tr("Error: QCA provider plugin not found. It is usually provided by the qca-ossl plugin."));
681 QStringList parms = msg.split(' ', QString::SkipEmptyParts);
683 if (parms.count() == 1 && !bufferInfo.bufferName().isEmpty() && bufferInfo.acceptsRegularMessages())
684 parms.prepend(bufferInfo.bufferName());
685 else if (parms.count() != 2) {
686 emit displayMsg(Message::Info, typeByTarget(bufname), bufname,
687 tr("[usage] /setkey <nick|channel> <key> sets the encryption key for nick or channel. "
688 "/setkey <key> when in a channel or query buffer sets the key for it."));
692 QString target = parms.at(0);
693 QByteArray key = parms.at(1).toLocal8Bit();
694 network()->setCipherKey(target, key);
696 emit displayMsg(Message::Info, typeByTarget(bufname), bufname, tr("The key for %1 has been set.").arg(target));
699 emit displayMsg(Message::Error, typeByTarget(bufname), bufname, tr("Error: Setting an encryption key requires Quassel to have been built "
700 "with support for the Qt Cryptographic Architecture (QCA) library. "
701 "Contact your distributor about a Quassel package with QCA "
702 "support, or rebuild Quassel with QCA present."));
707 void CoreUserInputHandler::handleShowkey(const BufferInfo &bufferInfo, const QString &msg)
709 QString bufname = bufferInfo.bufferName().isNull() ? "" : bufferInfo.bufferName();
711 if (!bufferInfo.isValid())
714 if (!Cipher::neededFeaturesAvailable()) {
715 emit displayMsg(Message::Error, typeByTarget(bufname), bufname, tr("Error: QCA provider plugin not found. It is usually provided by the qca-ossl plugin."));
719 QStringList parms = msg.split(' ', QString::SkipEmptyParts);
721 if (parms.isEmpty() && !bufferInfo.bufferName().isEmpty() && bufferInfo.acceptsRegularMessages())
722 parms.prepend(bufferInfo.bufferName());
724 if (parms.isEmpty()) {
725 emit displayMsg(Message::Info, typeByTarget(bufname), bufname, tr("[usage] /showkey <nick|channel> shows the encryption key for nick or channel or just /showkey when in a channel or query."));
729 QString target = parms.at(0);
730 QByteArray key = network()->cipherKey(target);
733 emit displayMsg(Message::Info, typeByTarget(bufname), bufname, tr("No key has been set for %1.").arg(target));
737 emit displayMsg(Message::Info, typeByTarget(bufname), bufname, tr("The key for %1 is %2:%3").arg(target, network()->cipherUsesCBC(target) ? "CBC" : "ECB", QString(key)));
741 emit displayMsg(Message::Error, typeByTarget(bufname), bufname, tr("Error: Setting an encryption key requires Quassel to have been built "
742 "with support for the Qt Cryptographic Architecture (QCA2) library. "
743 "Contact your distributor about a Quassel package with QCA2 "
744 "support, or rebuild Quassel with QCA2 present."));
749 void CoreUserInputHandler::handleTopic(const BufferInfo &bufferInfo, const QString &msg)
751 if (bufferInfo.bufferName().isEmpty() || !bufferInfo.acceptsRegularMessages())
754 QList<QByteArray> params;
755 params << serverEncode(bufferInfo.bufferName());
757 if (!msg.isEmpty()) {
759 params << encrypt(bufferInfo.bufferName(), channelEncode(bufferInfo.bufferName(), msg));
761 params << channelEncode(bufferInfo.bufferName(), msg);
765 emit putCmd("TOPIC", params);
769 void CoreUserInputHandler::handleVoice(const BufferInfo &bufferInfo, const QString &msg)
771 QStringList nicks = msg.split(' ', QString::SkipEmptyParts);
772 QString m = "+"; for (int i = 0; i < nicks.count(); i++) m += 'v';
774 params << bufferInfo.bufferName() << m << nicks;
775 emit putCmd("MODE", serverEncode(params));
779 void CoreUserInputHandler::handleWait(const BufferInfo &bufferInfo, const QString &msg)
781 int splitPos = msg.indexOf(';');
786 int delay = msg.left(splitPos).trimmed().toInt(&ok);
792 QString command = msg.mid(splitPos + 1).trimmed();
793 if (command.isEmpty())
796 _delayedCommands[startTimer(delay)] = Command(bufferInfo, command);
800 void CoreUserInputHandler::handleWho(const BufferInfo &bufferInfo, const QString &msg)
803 emit putCmd("WHO", serverEncode(msg.split(' ')));
807 void CoreUserInputHandler::handleWhois(const BufferInfo &bufferInfo, const QString &msg)
810 emit putCmd("WHOIS", serverEncode(msg.split(' ')));
814 void CoreUserInputHandler::handleWhowas(const BufferInfo &bufferInfo, const QString &msg)
817 emit putCmd("WHOWAS", serverEncode(msg.split(' ')));
821 void CoreUserInputHandler::defaultHandler(QString cmd, const BufferInfo &bufferInfo, const QString &msg)
823 Q_UNUSED(bufferInfo);
824 emit putCmd(serverEncode(cmd.toUpper()), serverEncode(msg.split(" ")));
828 void CoreUserInputHandler::putPrivmsg(const QString &target, const QString &message, std::function<QByteArray(const QString &, const QString &)> encodeFunc, Cipher *cipher)
831 QString cmd("PRIVMSG");
832 QByteArray targetEnc = serverEncode(target);
834 std::function<QList<QByteArray>(QString &)> cmdGenerator = [&] (QString &splitMsg) -> QList<QByteArray> {
835 QByteArray splitMsgEnc = encodeFunc(target, splitMsg);
838 if (cipher && !cipher->key().isEmpty() && !splitMsg.isEmpty()) {
839 cipher->encrypt(splitMsgEnc);
842 return QList<QByteArray>() << targetEnc << splitMsgEnc;
845 putCmd(cmd, network()->splitMessage(cmd, message, cmdGenerator));
849 // returns 0 if the message will not be chopped by the irc server or number of chopped bytes if message is too long
850 int CoreUserInputHandler::lastParamOverrun(const QString &cmd, const QList<QByteArray> ¶ms)
852 // the server will pass our message truncated to 512 bytes including CRLF with the following format:
853 // ":prefix COMMAND param0 param1 :lastparam"
854 // where prefix = "nickname!user@host"
855 // that means that the last message can be as long as:
856 // 512 - nicklen - userlen - hostlen - commandlen - sum(param[0]..param[n-1])) - 2 (for CRLF) - 4 (":!@" + 1space between prefix and command) - max(paramcount - 1, 0) (space for simple params) - 2 (space and colon for last param)
857 IrcUser *me = network()->me();
858 int maxLen = 480 - cmd.toLatin1().count(); // educated guess in case we don't know us (yet?)
861 maxLen = 512 - serverEncode(me->nick()).count() - serverEncode(me->user()).count() - serverEncode(me->host()).count() - cmd.toLatin1().count() - 6;
863 if (!params.isEmpty()) {
864 for (int i = 0; i < params.count() - 1; i++) {
865 maxLen -= (params[i].count() + 1);
867 maxLen -= 2; // " :" last param separator;
869 if (params.last().count() > maxLen) {
870 return params.last().count() - maxLen;
883 QByteArray CoreUserInputHandler::encrypt(const QString &target, const QByteArray &message_, bool *didEncrypt) const
888 if (message_.isEmpty())
891 if (!Cipher::neededFeaturesAvailable())
894 Cipher *cipher = network()->cipher(target);
895 if (!cipher || cipher->key().isEmpty())
898 QByteArray message = message_;
899 bool result = cipher->encrypt(message);
901 *didEncrypt = result;
909 void CoreUserInputHandler::timerEvent(QTimerEvent *event)
911 if (!_delayedCommands.contains(event->timerId())) {
912 QObject::timerEvent(event);
915 BufferInfo bufferInfo = _delayedCommands[event->timerId()].bufferInfo;
916 QString rawCommand = _delayedCommands[event->timerId()].command;
917 _delayedCommands.remove(event->timerId());
920 // the stored command might be the result of an alias expansion, so we need to split it up again
921 QStringList commands = rawCommand.split(QRegExp("; ?"));
922 foreach(QString command, commands) {
923 handleUserInput(bufferInfo, command);