1 /***************************************************************************
2 * Copyright (C) 2005-2016 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 #if QT_VERSION < 0x050000
34 // QChar::LineFeed is Qt 5
35 static const QChar QCharLF = QChar('\n');
37 static const QChar QCharLF = QChar::LineFeed;
40 CoreUserInputHandler::CoreUserInputHandler(CoreNetwork *parent)
41 : CoreBasicHandler(parent)
46 void CoreUserInputHandler::handleUserInput(const BufferInfo &bufferInfo, const QString &msg)
51 AliasManager::CommandList list = coreSession()->aliasManager().processInput(bufferInfo, msg);
53 for (int i = 0; i < list.count(); i++) {
54 QString cmd = list.at(i).second.section(' ', 0, 0).remove(0, 1).toUpper();
55 QString payload = list.at(i).second.section(' ', 1);
56 handle(cmd, Q_ARG(BufferInfo, list.at(i).first), Q_ARG(QString, payload));
61 // ====================
63 // ====================
64 void CoreUserInputHandler::handleAway(const BufferInfo &bufferInfo, const QString &msg,
65 const bool skipFormatting)
68 if (msg.startsWith("-all")) {
69 if (msg.length() == 4) {
70 coreSession()->globalAway(QString(), skipFormatting);
73 Q_ASSERT(msg.length() > 4);
75 coreSession()->globalAway(msg.mid(5), skipFormatting);
79 issueAway(msg, true /* force away */, skipFormatting);
83 void CoreUserInputHandler::issueAway(const QString &msg, bool autoCheck, const bool skipFormatting)
85 QString awayMsg = msg;
86 IrcUser *me = network()->me();
88 // Only apply timestamp formatting when requested
89 // This avoids re-processing any existing away message when the core restarts, so chained escape
90 // percent signs won't get down-processed.
91 if (!skipFormatting) {
92 // Apply the timestamp formatting to the away message (if empty, nothing will happen)
93 awayMsg = formatCurrentDateTimeInString(awayMsg);
96 // if there is no message supplied we have to check if we are already away or not
97 if (autoCheck && msg.isEmpty()) {
98 if (me && !me->isAway()) {
99 Identity *identity = network()->identityPtr();
101 awayMsg = formatCurrentDateTimeInString(identity->awayReason());
103 if (awayMsg.isEmpty()) {
104 awayMsg = tr("away");
109 me->setAwayMessage(awayMsg);
111 putCmd("AWAY", serverEncode(awayMsg));
115 void CoreUserInputHandler::handleBan(const BufferInfo &bufferInfo, const QString &msg)
117 banOrUnban(bufferInfo, msg, true);
121 void CoreUserInputHandler::handleUnban(const BufferInfo &bufferInfo, const QString &msg)
123 banOrUnban(bufferInfo, msg, false);
127 void CoreUserInputHandler::banOrUnban(const BufferInfo &bufferInfo, const QString &msg, bool ban)
132 QStringList params = msg.split(" ");
134 if (!params.isEmpty() && isChannelName(params[0])) {
135 banChannel = params.takeFirst();
137 else if (bufferInfo.type() == BufferInfo::ChannelBuffer) {
138 banChannel = bufferInfo.bufferName();
141 emit displayMsg(Message::Error, BufferInfo::StatusBuffer, "", QString("Error: channel unknown in command: /BAN %1").arg(msg));
145 if (!params.isEmpty() && !params.contains("!") && network()->ircUser(params[0])) {
146 IrcUser *ircuser = network()->ircUser(params[0]);
147 // generalizedHost changes <nick> to *!ident@*.sld.tld.
148 QString generalizedHost = ircuser->host();
149 if (generalizedHost.isEmpty()) {
150 emit displayMsg(Message::Error, BufferInfo::StatusBuffer, "", QString("Error: host unknown in command: /BAN %1").arg(msg));
154 static QRegExp ipAddress("\\d+\\.\\d+\\.\\d+\\.\\d+");
155 if (ipAddress.exactMatch(generalizedHost)) {
156 int lastDotPos = generalizedHost.lastIndexOf('.') + 1;
157 generalizedHost.replace(lastDotPos, generalizedHost.length() - lastDotPos, '*');
159 else if (generalizedHost.lastIndexOf(".") != -1 && generalizedHost.lastIndexOf(".", generalizedHost.lastIndexOf(".")-1) != -1) {
160 int secondLastPeriodPosition = generalizedHost.lastIndexOf(".", generalizedHost.lastIndexOf(".")-1);
161 generalizedHost.replace(0, secondLastPeriodPosition, "*");
163 banUser = QString("*!%1@%2").arg(ircuser->user(), generalizedHost);
166 banUser = params.join(" ");
169 QString banMode = ban ? "+b" : "-b";
170 QString banMsg = QString("MODE %1 %2 %3").arg(banChannel, banMode, banUser);
171 emit putRawLine(serverEncode(banMsg));
175 void CoreUserInputHandler::handleCtcp(const BufferInfo &bufferInfo, const QString &msg)
179 QString nick = msg.section(' ', 0, 0);
180 QString ctcpTag = msg.section(' ', 1, 1).toUpper();
181 if (ctcpTag.isEmpty())
184 QString message = msg.section(' ', 2);
185 QString verboseMessage = tr("sending CTCP-%1 request to %2").arg(ctcpTag).arg(nick);
187 if (ctcpTag == "PING") {
188 message = QString::number(QDateTime::currentMSecsSinceEpoch());
191 // FIXME make this a proper event
192 coreNetwork()->coreSession()->ctcpParser()->query(coreNetwork(), nick, ctcpTag, message);
193 emit displayMsg(Message::Action, BufferInfo::StatusBuffer, "", verboseMessage,
194 network()->myNick(), Message::Flag::Self);
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(Message::Error, typeByTarget(bufname), bufname, tr("Error: QCA provider plugin not found. It is usually provided by the qca-ossl plugin."));
210 QStringList parms = msg.split(' ', QString::SkipEmptyParts);
212 if (parms.isEmpty() && !bufferInfo.bufferName().isEmpty() && bufferInfo.acceptsRegularMessages())
213 parms.prepend(bufferInfo.bufferName());
215 if (parms.isEmpty()) {
216 emit displayMsg(Message::Info, typeByTarget(bufname), bufname,
217 tr("[usage] /delkey <nick|channel> deletes the encryption key for nick or channel or just /delkey when in a channel or query."));
221 QString target = parms.at(0);
223 if (network()->cipherKey(target).isEmpty()) {
224 emit displayMsg(Message::Info, typeByTarget(bufname), bufname, tr("No key has been set for %1.").arg(target));
228 network()->setCipherKey(target, QByteArray());
229 emit displayMsg(Message::Info, typeByTarget(bufname), bufname, tr("The key for %1 has been deleted.").arg(target));
233 emit displayMsg(Message::Error, typeByTarget(bufname), bufname, tr("Error: Setting an encryption key requires Quassel to have been built "
234 "with support for the Qt Cryptographic Architecture (QCA2) library. "
235 "Contact your distributor about a Quassel package with QCA2 "
236 "support, or rebuild Quassel with QCA2 present."));
240 void CoreUserInputHandler::doMode(const BufferInfo &bufferInfo, const QChar& addOrRemove, const QChar& mode, const QString &nicks)
244 int maxModes = network()->support("MODES").toInt(&isNumber);
245 if (!isNumber || maxModes == 0) maxModes = 1;
247 QStringList nickList;
248 if (nicks == "*" && bufferInfo.type() == BufferInfo::ChannelBuffer) { // All users in channel
249 const QList<IrcUser*> users = network()->ircChannel(bufferInfo.bufferName())->ircUsers();
250 foreach(IrcUser *user, users) {
251 if ((addOrRemove == '+' && !network()->ircChannel(bufferInfo.bufferName())->userModes(user).contains(mode))
252 || (addOrRemove == '-' && network()->ircChannel(bufferInfo.bufferName())->userModes(user).contains(mode)))
253 nickList.append(user->nick());
256 nickList = nicks.split(' ', QString::SkipEmptyParts);
259 if (nickList.count() == 0) return;
261 while (!nickList.isEmpty()) {
262 int amount = qMin(nickList.count(), maxModes);
263 QString m = addOrRemove; for(int i = 0; i < amount; i++) m += mode;
265 params << bufferInfo.bufferName() << m;
266 for(int i = 0; i < amount; i++) params << nickList.takeFirst();
267 emit putCmd("MODE", serverEncode(params));
272 void CoreUserInputHandler::handleDeop(const BufferInfo &bufferInfo, const QString &nicks)
274 doMode(bufferInfo, '-', 'o', nicks);
278 void CoreUserInputHandler::handleDehalfop(const BufferInfo &bufferInfo, const QString &nicks)
280 doMode(bufferInfo, '-', 'h', nicks);
284 void CoreUserInputHandler::handleDevoice(const BufferInfo &bufferInfo, const QString &nicks)
286 doMode(bufferInfo, '-', 'v', nicks);
289 void CoreUserInputHandler::handleHalfop(const BufferInfo &bufferInfo, const QString &nicks)
291 doMode(bufferInfo, '+', 'h', nicks);
294 void CoreUserInputHandler::handleOp(const BufferInfo &bufferInfo, const QString &nicks) {
295 doMode(bufferInfo, '+', 'o', nicks);
299 void CoreUserInputHandler::handleInvite(const BufferInfo &bufferInfo, const QString &msg)
302 params << msg << bufferInfo.bufferName();
303 emit putCmd("INVITE", serverEncode(params));
307 void CoreUserInputHandler::handleJoin(const BufferInfo &bufferInfo, const QString &msg)
309 Q_UNUSED(bufferInfo);
311 // trim spaces before chans or keys
312 QString sane_msg = msg;
313 sane_msg.replace(QRegExp(", +"), ",");
314 QStringList params = sane_msg.trimmed().split(" ");
316 QStringList chans = params[0].split(",", QString::SkipEmptyParts);
318 if (params.count() > 1)
319 keys = params[1].split(",");
322 for (i = 0; i < chans.count(); i++) {
323 if (!network()->isChannelName(chans[i]))
324 chans[i].prepend('#');
326 if (i < keys.count()) {
327 network()->addChannelKey(chans[i], keys[i]);
330 network()->removeChannelKey(chans[i]);
334 static const char *cmd = "JOIN";
336 QStringList joinChans, joinKeys;
337 int slicesize = chans.count();
338 QList<QByteArray> encodedParams;
340 // go through all to-be-joined channels and (re)build the join list
341 while (i < chans.count()) {
342 joinChans.append(chans.at(i));
343 if (i < keys.count())
344 joinKeys.append(keys.at(i));
346 // if the channel list we built so far either contains all requested channels or exceeds
347 // the desired amount of channels in this slice, try to send what we have so far
348 if (++i == chans.count() || joinChans.count() >= slicesize) {
350 params.append(joinChans.join(","));
351 params.append(joinKeys.join(","));
352 encodedParams = serverEncode(params);
353 // check if it fits in one command
354 if (lastParamOverrun(cmd, encodedParams) == 0) {
355 emit putCmd(cmd, encodedParams);
357 else if (slicesize > 1) {
358 // back to start of slice, try again with half the amount of channels
369 void CoreUserInputHandler::handleKeyx(const BufferInfo &bufferInfo, const QString &msg)
371 QString bufname = bufferInfo.bufferName().isNull() ? "" : bufferInfo.bufferName();
373 if (!bufferInfo.isValid())
376 if (!Cipher::neededFeaturesAvailable()) {
377 emit displayMsg(Message::Error, typeByTarget(bufname), bufname, tr("Error: QCA provider plugin not found. It is usually provided by the qca-ossl plugin."));
381 QStringList parms = msg.split(' ', QString::SkipEmptyParts);
383 if (parms.count() == 0 && !bufferInfo.bufferName().isEmpty() && bufferInfo.acceptsRegularMessages())
384 parms.prepend(bufferInfo.bufferName());
385 else if (parms.count() != 1) {
386 emit displayMsg(Message::Info, typeByTarget(bufname), bufname,
387 tr("[usage] /keyx [<nick>] Initiates a DH1080 key exchange with the target."));
391 QString target = parms.at(0);
393 if (network()->isChannelName(target)) {
394 emit displayMsg(Message::Info, typeByTarget(bufname), bufname, tr("It is only possible to exchange keys in a query buffer."));
398 Cipher *cipher = network()->cipher(target);
399 if (!cipher) // happens when there is no CoreIrcChannel for the target
402 QByteArray pubKey = cipher->initKeyExchange();
403 if (pubKey.isEmpty())
404 emit displayMsg(Message::Error, typeByTarget(bufname), bufname, tr("Failed to initiate key exchange with %1.").arg(target));
406 QList<QByteArray> params;
407 params << serverEncode(target) << serverEncode("DH1080_INIT ") + pubKey;
408 emit putCmd("NOTICE", params);
409 emit displayMsg(Message::Info, typeByTarget(bufname), bufname, tr("Initiated key exchange with %1.").arg(target));
413 emit displayMsg(Message::Error, typeByTarget(bufname), bufname, tr("Error: Setting an encryption key requires Quassel to have been built "
414 "with support for the Qt Cryptographic Architecture (QCA) library. "
415 "Contact your distributor about a Quassel package with QCA "
416 "support, or rebuild Quassel with QCA present."));
421 void CoreUserInputHandler::handleKick(const BufferInfo &bufferInfo, const QString &msg)
423 QString nick = msg.section(' ', 0, 0, QString::SectionSkipEmpty);
424 QString reason = msg.section(' ', 1, -1, QString::SectionSkipEmpty).trimmed();
425 if (reason.isEmpty())
426 reason = network()->identityPtr()->kickReason();
428 QList<QByteArray> params;
429 params << serverEncode(bufferInfo.bufferName()) << serverEncode(nick) << channelEncode(bufferInfo.bufferName(), reason);
430 emit putCmd("KICK", params);
434 void CoreUserInputHandler::handleKill(const BufferInfo &bufferInfo, const QString &msg)
437 QString nick = msg.section(' ', 0, 0, QString::SectionSkipEmpty);
438 QString pass = msg.section(' ', 1, -1, QString::SectionSkipEmpty);
439 QList<QByteArray> params;
440 params << serverEncode(nick) << serverEncode(pass);
441 emit putCmd("KILL", params);
445 void CoreUserInputHandler::handleList(const BufferInfo &bufferInfo, const QString &msg)
448 emit putCmd("LIST", serverEncode(msg.split(' ', QString::SkipEmptyParts)));
452 void CoreUserInputHandler::handleMe(const BufferInfo &bufferInfo, const QString &msg)
454 if (bufferInfo.bufferName().isEmpty() || !bufferInfo.acceptsRegularMessages())
455 return; // server buffer
456 // FIXME make this a proper event
458 // Split apart messages at line feeds. The IRC protocol uses those to separate commands, so
459 // they need to be split into multiple messages.
460 QStringList messages = msg.split(QCharLF);
462 foreach (auto message, messages) {
463 // Handle each separated message independently, ignoring any carriage returns
464 message = message.trimmed();
465 coreNetwork()->coreSession()->ctcpParser()->query(coreNetwork(), bufferInfo.bufferName(),
467 emit displayMsg(Message::Action, bufferInfo.type(), bufferInfo.bufferName(), message,
468 network()->myNick(), Message::Self);
473 void CoreUserInputHandler::handleMode(const BufferInfo &bufferInfo, const QString &msg)
477 QStringList params = msg.split(' ', QString::SkipEmptyParts);
478 // if the first argument is neither a channel nor us (user modes are only to oneself) the current buffer is assumed to be the target
479 if (!params.isEmpty()) {
480 if (!network()->isChannelName(params[0]) && !network()->isMyNick(params[0]))
481 params.prepend(bufferInfo.bufferName());
482 if (network()->isMyNick(params[0]) && params.count() == 2)
483 network()->updateIssuedModes(params[1]);
484 if (params[0] == "-reset" && params.count() == 1) {
485 // FIXME: give feedback to the user (I don't want to add new strings right now)
486 network()->resetPersistentModes();
491 // TODO handle correct encoding for buffer modes (channelEncode())
492 emit putCmd("MODE", serverEncode(params));
496 // TODO: show privmsgs
497 void CoreUserInputHandler::handleMsg(const BufferInfo &bufferInfo, const QString &msg)
499 Q_UNUSED(bufferInfo);
500 if (!msg.contains(' '))
503 QString target = msg.section(' ', 0, 0);
504 QString msgSection = msg.section(' ', 1);
506 std::function<QByteArray(const QString &, const QString &)> encodeFunc = [this] (const QString &target, const QString &message) -> QByteArray {
507 return userEncode(target, message);
511 putPrivmsg(target, msgSection, encodeFunc, network()->cipher(target));
513 putPrivmsg(target, msgSection, encodeFunc);
518 void CoreUserInputHandler::handleNick(const BufferInfo &bufferInfo, const QString &msg)
521 QString nick = msg.section(' ', 0, 0);
522 emit putCmd("NICK", serverEncode(nick));
526 void CoreUserInputHandler::handleNotice(const BufferInfo &bufferInfo, const QString &msg)
528 QString bufferName = msg.section(' ', 0, 0);
529 QList<QByteArray> params;
530 // Split apart messages at line feeds. The IRC protocol uses those to separate commands, so
531 // they need to be split into multiple messages.
532 QStringList messages = msg.section(' ', 1).split(QCharLF);
534 foreach (auto message, messages) {
535 // Handle each separated message independently, ignoring any carriage returns
536 message = message.trimmed();
538 params << serverEncode(bufferName) << channelEncode(bufferInfo.bufferName(), message);
539 emit putCmd("NOTICE", params);
540 emit displayMsg(Message::Notice, typeByTarget(bufferName), bufferName, message,
541 network()->myNick(), Message::Self);
547 void CoreUserInputHandler::handleOper(const BufferInfo &bufferInfo, const QString &msg)
550 emit putRawLine(serverEncode(QString("OPER %1").arg(msg)));
554 void CoreUserInputHandler::handlePart(const BufferInfo &bufferInfo, const QString &msg)
556 QList<QByteArray> params;
559 // msg might contain either a channel name and/or a reaon, so we have to check if the first word is a known channel
560 QString channelName = msg.section(' ', 0, 0);
561 if (channelName.isEmpty() || !network()->ircChannel(channelName)) {
562 channelName = bufferInfo.bufferName();
566 partReason = msg.mid(channelName.length() + 1);
569 if (partReason.isEmpty())
570 partReason = network()->identityPtr()->partReason();
572 params << serverEncode(channelName) << channelEncode(bufferInfo.bufferName(), partReason);
573 emit putCmd("PART", params);
577 void CoreUserInputHandler::handlePing(const BufferInfo &bufferInfo, const QString &msg)
583 param = QTime::currentTime().toString("hh:mm:ss.zzz");
585 // Take priority so this won't get stuck behind other queued messages.
586 putCmd("PING", serverEncode(param), QByteArray(), true);
590 void CoreUserInputHandler::handlePrint(const BufferInfo &bufferInfo, const QString &msg)
592 if (bufferInfo.bufferName().isEmpty() || !bufferInfo.acceptsRegularMessages())
593 return; // server buffer
595 QByteArray encMsg = channelEncode(bufferInfo.bufferName(), msg);
596 emit displayMsg(Message::Info, bufferInfo.type(), bufferInfo.bufferName(), msg, network()->myNick(), Message::Self);
600 // TODO: implement queries
601 void CoreUserInputHandler::handleQuery(const BufferInfo &bufferInfo, const QString &msg)
604 QString target = msg.section(' ', 0, 0);
605 // Split apart messages at line feeds. The IRC protocol uses those to separate commands, so
606 // they need to be split into multiple messages.
607 QStringList messages = msg.section(' ', 1).split(QCharLF);
609 foreach (auto message, messages) {
610 // Handle each separated message independently, ignoring any carriage returns
611 message = message.trimmed();
612 if (message.isEmpty()) {
613 emit displayMsg(Message::Server, BufferInfo::QueryBuffer, target,
614 tr("Starting query with %1").arg(target), network()->myNick(),
616 // handleMsg is a no-op if message is empty
618 emit displayMsg(Message::Plain, BufferInfo::QueryBuffer, target, message,
619 network()->myNick(), Message::Self);
620 // handleMsg needs the target specified at the beginning of the message
621 handleMsg(bufferInfo, target + " " + message);
627 void CoreUserInputHandler::handleQuit(const BufferInfo &bufferInfo, const QString &msg)
630 network()->disconnectFromIrc(true, msg);
634 void CoreUserInputHandler::issueQuit(const QString &reason, bool forceImmediate)
636 // If needing an immediate QUIT (e.g. core shutdown), prepend this to the queue
637 emit putCmd("QUIT", serverEncode(reason), QByteArray(), forceImmediate);
641 void CoreUserInputHandler::handleQuote(const BufferInfo &bufferInfo, const QString &msg)
644 emit putRawLine(serverEncode(msg));
648 void CoreUserInputHandler::handleSay(const BufferInfo &bufferInfo, const QString &msg)
650 if (bufferInfo.bufferName().isEmpty() || !bufferInfo.acceptsRegularMessages())
651 return; // server buffer
653 std::function<QByteArray(const QString &, const QString &)> encodeFunc = [this] (const QString &target, const QString &message) -> QByteArray {
654 return channelEncode(target, message);
657 // Split apart messages at line feeds. The IRC protocol uses those to separate commands, so
658 // they need to be split into multiple messages.
659 QStringList messages = msg.split(QCharLF);
661 foreach (auto message, messages) {
662 // Handle each separated message independently, ignoring any carriage returns
663 message = message.trimmed();
665 putPrivmsg(bufferInfo.bufferName(), message, encodeFunc,
666 network()->cipher(bufferInfo.bufferName()));
668 putPrivmsg(bufferInfo.bufferName(), message, encodeFunc);
670 emit displayMsg(Message::Plain, bufferInfo.type(), bufferInfo.bufferName(), message,
671 network()->myNick(), Message::Self);
676 void CoreUserInputHandler::handleSetkey(const BufferInfo &bufferInfo, const QString &msg)
678 QString bufname = bufferInfo.bufferName().isNull() ? "" : bufferInfo.bufferName();
680 if (!bufferInfo.isValid())
683 if (!Cipher::neededFeaturesAvailable()) {
684 emit displayMsg(Message::Error, typeByTarget(bufname), bufname, tr("Error: QCA provider plugin not found. It is usually provided by the qca-ossl plugin."));
688 QStringList parms = msg.split(' ', QString::SkipEmptyParts);
690 if (parms.count() == 1 && !bufferInfo.bufferName().isEmpty() && bufferInfo.acceptsRegularMessages())
691 parms.prepend(bufferInfo.bufferName());
692 else if (parms.count() != 2) {
693 emit displayMsg(Message::Info, typeByTarget(bufname), bufname,
694 tr("[usage] /setkey <nick|channel> <key> sets the encryption key for nick or channel. "
695 "/setkey <key> when in a channel or query buffer sets the key for it."));
699 QString target = parms.at(0);
700 QByteArray key = parms.at(1).toLocal8Bit();
701 network()->setCipherKey(target, key);
703 emit displayMsg(Message::Info, typeByTarget(bufname), bufname, tr("The key for %1 has been set.").arg(target));
706 emit displayMsg(Message::Error, typeByTarget(bufname), bufname, tr("Error: Setting an encryption key requires Quassel to have been built "
707 "with support for the Qt Cryptographic Architecture (QCA) library. "
708 "Contact your distributor about a Quassel package with QCA "
709 "support, or rebuild Quassel with QCA present."));
714 void CoreUserInputHandler::handleShowkey(const BufferInfo &bufferInfo, const QString &msg)
716 QString bufname = bufferInfo.bufferName().isNull() ? "" : bufferInfo.bufferName();
718 if (!bufferInfo.isValid())
721 if (!Cipher::neededFeaturesAvailable()) {
722 emit displayMsg(Message::Error, typeByTarget(bufname), bufname, tr("Error: QCA provider plugin not found. It is usually provided by the qca-ossl plugin."));
726 QStringList parms = msg.split(' ', QString::SkipEmptyParts);
728 if (parms.isEmpty() && !bufferInfo.bufferName().isEmpty() && bufferInfo.acceptsRegularMessages())
729 parms.prepend(bufferInfo.bufferName());
731 if (parms.isEmpty()) {
732 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."));
736 QString target = parms.at(0);
737 QByteArray key = network()->cipherKey(target);
740 emit displayMsg(Message::Info, typeByTarget(bufname), bufname, tr("No key has been set for %1.").arg(target));
744 emit displayMsg(Message::Info, typeByTarget(bufname), bufname, tr("The key for %1 is %2:%3").arg(target, network()->cipherUsesCBC(target) ? "CBC" : "ECB", QString(key)));
748 emit displayMsg(Message::Error, typeByTarget(bufname), bufname, tr("Error: Setting an encryption key requires Quassel to have been built "
749 "with support for the Qt Cryptographic Architecture (QCA2) library. "
750 "Contact your distributor about a Quassel package with QCA2 "
751 "support, or rebuild Quassel with QCA2 present."));
756 void CoreUserInputHandler::handleTopic(const BufferInfo &bufferInfo, const QString &msg)
758 if (bufferInfo.bufferName().isEmpty() || !bufferInfo.acceptsRegularMessages())
761 QList<QByteArray> params;
762 params << serverEncode(bufferInfo.bufferName());
764 if (!msg.isEmpty()) {
766 params << encrypt(bufferInfo.bufferName(), channelEncode(bufferInfo.bufferName(), msg));
768 params << channelEncode(bufferInfo.bufferName(), msg);
772 emit putCmd("TOPIC", params);
776 void CoreUserInputHandler::handleVoice(const BufferInfo &bufferInfo, const QString &msg)
778 QStringList nicks = msg.split(' ', QString::SkipEmptyParts);
779 QString m = "+"; for (int i = 0; i < nicks.count(); i++) m += 'v';
781 params << bufferInfo.bufferName() << m << nicks;
782 emit putCmd("MODE", serverEncode(params));
786 void CoreUserInputHandler::handleWait(const BufferInfo &bufferInfo, const QString &msg)
788 int splitPos = msg.indexOf(';');
793 int delay = msg.left(splitPos).trimmed().toInt(&ok);
799 QString command = msg.mid(splitPos + 1).trimmed();
800 if (command.isEmpty())
803 _delayedCommands[startTimer(delay)] = Command(bufferInfo, command);
807 void CoreUserInputHandler::handleWho(const BufferInfo &bufferInfo, const QString &msg)
810 emit putCmd("WHO", serverEncode(msg.split(' ')));
814 void CoreUserInputHandler::handleWhois(const BufferInfo &bufferInfo, const QString &msg)
817 emit putCmd("WHOIS", serverEncode(msg.split(' ')));
821 void CoreUserInputHandler::handleWhowas(const BufferInfo &bufferInfo, const QString &msg)
824 emit putCmd("WHOWAS", serverEncode(msg.split(' ')));
828 void CoreUserInputHandler::defaultHandler(QString cmd, const BufferInfo &bufferInfo, const QString &msg)
830 Q_UNUSED(bufferInfo);
831 emit putCmd(serverEncode(cmd.toUpper()), serverEncode(msg.split(" ")));
835 void CoreUserInputHandler::putPrivmsg(const QString &target, const QString &message, std::function<QByteArray(const QString &, const QString &)> encodeFunc, Cipher *cipher)
838 QString cmd("PRIVMSG");
839 QByteArray targetEnc = serverEncode(target);
841 std::function<QList<QByteArray>(QString &)> cmdGenerator = [&] (QString &splitMsg) -> QList<QByteArray> {
842 QByteArray splitMsgEnc = encodeFunc(target, splitMsg);
845 if (cipher && !cipher->key().isEmpty() && !splitMsg.isEmpty()) {
846 cipher->encrypt(splitMsgEnc);
849 return QList<QByteArray>() << targetEnc << splitMsgEnc;
852 putCmd(cmd, network()->splitMessage(cmd, message, cmdGenerator));
856 // returns 0 if the message will not be chopped by the irc server or number of chopped bytes if message is too long
857 int CoreUserInputHandler::lastParamOverrun(const QString &cmd, const QList<QByteArray> ¶ms)
859 // the server will pass our message truncated to 512 bytes including CRLF with the following format:
860 // ":prefix COMMAND param0 param1 :lastparam"
861 // where prefix = "nickname!user@host"
862 // that means that the last message can be as long as:
863 // 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)
864 IrcUser *me = network()->me();
865 int maxLen = 480 - cmd.toLatin1().count(); // educated guess in case we don't know us (yet?)
868 maxLen = 512 - serverEncode(me->nick()).count() - serverEncode(me->user()).count() - serverEncode(me->host()).count() - cmd.toLatin1().count() - 6;
870 if (!params.isEmpty()) {
871 for (int i = 0; i < params.count() - 1; i++) {
872 maxLen -= (params[i].count() + 1);
874 maxLen -= 2; // " :" last param separator;
876 if (params.last().count() > maxLen) {
877 return params.last().count() - maxLen;
890 QByteArray CoreUserInputHandler::encrypt(const QString &target, const QByteArray &message_, bool *didEncrypt) const
895 if (message_.isEmpty())
898 if (!Cipher::neededFeaturesAvailable())
901 Cipher *cipher = network()->cipher(target);
902 if (!cipher || cipher->key().isEmpty())
905 QByteArray message = message_;
906 bool result = cipher->encrypt(message);
908 *didEncrypt = result;
916 void CoreUserInputHandler::timerEvent(QTimerEvent *event)
918 if (!_delayedCommands.contains(event->timerId())) {
919 QObject::timerEvent(event);
922 BufferInfo bufferInfo = _delayedCommands[event->timerId()].bufferInfo;
923 QString rawCommand = _delayedCommands[event->timerId()].command;
924 _delayedCommands.remove(event->timerId());
927 // the stored command might be the result of an alias expansion, so we need to split it up again
928 QStringList commands = rawCommand.split(QRegExp("; ?"));
929 foreach(QString command, commands) {
930 handleUserInput(bufferInfo, command);