cmake: avoid de-duplication of user's CXXFLAGS
[quassel.git] / src / core / coreuserinputhandler.cpp
1 /***************************************************************************
2  *   Copyright (C) 2005-2020 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 "coreuserinputhandler.h"
22
23 #include <QRegExp>
24
25 #include "ctcpparser.h"
26 #include "util.h"
27
28 #ifdef HAVE_QCA2
29 #    include "cipher.h"
30 #endif
31
32 CoreUserInputHandler::CoreUserInputHandler(CoreNetwork* parent)
33     : CoreBasicHandler(parent)
34 {}
35
36 void CoreUserInputHandler::handleUserInput(const BufferInfo& bufferInfo, const QString& msg)
37 {
38     if (msg.isEmpty())
39         return;
40
41     AliasManager::CommandList list = coreSession()->aliasManager().processInput(bufferInfo, msg);
42
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));
47     }
48 }
49
50 // ====================
51 //  Public Slots
52 // ====================
53 void CoreUserInputHandler::handleAway(const BufferInfo& bufferInfo, const QString& msg, const bool skipFormatting)
54 {
55     Q_UNUSED(bufferInfo)
56     if (msg.startsWith("-all")) {
57         if (msg.length() == 4) {
58             coreSession()->globalAway(QString(), skipFormatting);
59             return;
60         }
61         Q_ASSERT(msg.length() > 4);
62         if (msg[4] == ' ') {
63             coreSession()->globalAway(msg.mid(5), skipFormatting);
64             return;
65         }
66     }
67     issueAway(msg, true /* force away */, skipFormatting);
68 }
69
70 void CoreUserInputHandler::issueAway(const QString& msg, bool autoCheck, const bool skipFormatting)
71 {
72     QString awayMsg = msg;
73     IrcUser* me = network()->me();
74
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);
81     }
82
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();
87             if (identity) {
88                 awayMsg = formatCurrentDateTimeInString(identity->awayReason());
89             }
90             if (awayMsg.isEmpty()) {
91                 awayMsg = tr("away");
92             }
93         }
94     }
95     if (me)
96         me->setAwayMessage(awayMsg);
97
98     putCmd("AWAY", serverEncode(awayMsg));
99 }
100
101 void CoreUserInputHandler::handleBan(const BufferInfo& bufferInfo, const QString& msg)
102 {
103     banOrUnban(bufferInfo, msg, true);
104 }
105
106 void CoreUserInputHandler::handleUnban(const BufferInfo& bufferInfo, const QString& msg)
107 {
108     banOrUnban(bufferInfo, msg, false);
109 }
110
111 void CoreUserInputHandler::banOrUnban(const BufferInfo& bufferInfo, const QString& msg, bool ban)
112 {
113     QString banChannel;
114     QString banUser;
115
116     QStringList params = msg.split(" ");
117
118     if (!params.isEmpty() && isChannelName(params[0])) {
119         banChannel = params.takeFirst();
120     }
121     else if (bufferInfo.type() == BufferInfo::ChannelBuffer) {
122         banChannel = bufferInfo.bufferName();
123     }
124     else {
125         emit displayMsg(NetworkInternalMessage(
126             Message::Error,
127             BufferInfo::StatusBuffer,
128             "",
129             QString("Error: channel unknown in command: /BAN %1").arg(msg)
130         ));
131         return;
132     }
133
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(
140                 Message::Error,
141                 BufferInfo::StatusBuffer,
142                 "",
143                 QString("Error: host unknown in command: /BAN %1").arg(msg)
144             ));
145             return;
146         }
147
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, '*');
152         }
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, "*");
156         }
157         banUser = QString("*!%1@%2").arg(ircuser->user(), generalizedHost);
158     }
159     else {
160         banUser = params.join(" ");
161     }
162
163     QString banMode = ban ? "+b" : "-b";
164     QString banMsg = QString("MODE %1 %2 %3").arg(banChannel, banMode, banUser);
165     emit putRawLine(serverEncode(banMsg));
166 }
167
168 void CoreUserInputHandler::handleCtcp(const BufferInfo& bufferInfo, const QString& msg)
169 {
170     Q_UNUSED(bufferInfo)
171
172     QString nick = msg.section(' ', 0, 0);
173     QString ctcpTag = msg.section(' ', 1, 1).toUpper();
174     if (ctcpTag.isEmpty())
175         return;
176
177     QString message = msg.section(' ', 2);
178     QString verboseMessage = tr("sending CTCP-%1 request to %2").arg(ctcpTag).arg(nick);
179
180     if (ctcpTag == "PING") {
181         message = QString::number(QDateTime::currentMSecsSinceEpoch());
182     }
183
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(
188             Message::Action,
189             BufferInfo::StatusBuffer,
190             "",
191             verboseMessage,
192             network()->myNick(),
193             Message::Flag::Self
194         ));
195     }
196 }
197
198 void CoreUserInputHandler::handleDelkey(const BufferInfo& bufferInfo, const QString& msg)
199 {
200     QString bufname = bufferInfo.bufferName().isNull() ? "" : bufferInfo.bufferName();
201 #ifdef HAVE_QCA2
202     if (!bufferInfo.isValid())
203         return;
204
205     if (!Cipher::neededFeaturesAvailable()) {
206         emit displayMsg(NetworkInternalMessage(
207             Message::Error,
208             typeByTarget(bufname),
209             bufname,
210             tr("Error: QCA provider plugin not found. It is usually provided by the qca-ossl plugin.")
211         ));
212         return;
213     }
214
215     QStringList parms = msg.split(' ', QString::SkipEmptyParts);
216
217     if (parms.isEmpty() && !bufferInfo.bufferName().isEmpty() && bufferInfo.acceptsRegularMessages())
218         parms.prepend(bufferInfo.bufferName());
219
220     if (parms.isEmpty()) {
221         emit displayMsg(NetworkInternalMessage(
222             Message::Info,
223             typeByTarget(bufname),
224             bufname,
225             tr("[usage] /delkey <nick|channel> deletes the encryption key for nick or channel or just /delkey when in a "
226                "channel or query.")
227         ));
228         return;
229     }
230
231     QString target = parms.at(0);
232
233     if (network()->cipherKey(target).isEmpty()) {
234         emit displayMsg(NetworkInternalMessage(
235             Message::Info,
236             typeByTarget(bufname),
237             bufname,
238             tr("No key has been set for %1.").arg(target)
239         ));
240         return;
241     }
242
243     network()->setCipherKey(target, QByteArray());
244     emit displayMsg(NetworkInternalMessage(
245         Message::Info,
246         typeByTarget(bufname),
247         bufname,
248         tr("The key for %1 has been deleted.").arg(target)
249     ));
250
251 #else
252     Q_UNUSED(msg)
253     emit displayMsg(NetworkInternalMessage(
254         Message::Error,
255         typeByTarget(bufname),
256         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.")
261     ));
262 #endif
263 }
264
265 void CoreUserInputHandler::doMode(const BufferInfo& bufferInfo, const QChar& addOrRemove, const QChar& mode, const QString& nicks)
266 {
267     bool isNumber;
268     int maxModes = network()->support("MODES").toInt(&isNumber);
269     if (!isNumber || maxModes == 0)
270         maxModes = 1;
271
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());
279         }
280     }
281     else {
282         nickList = nicks.split(' ', QString::SkipEmptyParts);
283     }
284
285     if (nickList.count() == 0)
286         return;
287
288     while (!nickList.isEmpty()) {
289         int amount = qMin(nickList.count(), maxModes);
290         QString m = addOrRemove;
291         for (int i = 0; i < amount; i++)
292             m += mode;
293         QStringList params;
294         params << bufferInfo.bufferName() << m;
295         for (int i = 0; i < amount; i++)
296             params << nickList.takeFirst();
297         emit putCmd("MODE", serverEncode(params));
298     }
299 }
300
301 void CoreUserInputHandler::handleDeop(const BufferInfo& bufferInfo, const QString& nicks)
302 {
303     doMode(bufferInfo, '-', 'o', nicks);
304 }
305
306 void CoreUserInputHandler::handleDehalfop(const BufferInfo& bufferInfo, const QString& nicks)
307 {
308     doMode(bufferInfo, '-', 'h', nicks);
309 }
310
311 void CoreUserInputHandler::handleDevoice(const BufferInfo& bufferInfo, const QString& nicks)
312 {
313     doMode(bufferInfo, '-', 'v', nicks);
314 }
315
316 void CoreUserInputHandler::handleHalfop(const BufferInfo& bufferInfo, const QString& nicks)
317 {
318     doMode(bufferInfo, '+', 'h', nicks);
319 }
320
321 void CoreUserInputHandler::handleOp(const BufferInfo& bufferInfo, const QString& nicks)
322 {
323     doMode(bufferInfo, '+', 'o', nicks);
324 }
325
326 void CoreUserInputHandler::handleInvite(const BufferInfo& bufferInfo, const QString& msg)
327 {
328     QStringList params;
329     params << msg << bufferInfo.bufferName();
330     emit putCmd("INVITE", serverEncode(params));
331 }
332
333 void CoreUserInputHandler::handleJoin(const BufferInfo& bufferInfo, const QString& msg)
334 {
335     Q_UNUSED(bufferInfo);
336
337     // trim spaces before chans or keys
338     QString sane_msg = msg;
339     sane_msg.replace(QRegExp(", +"), ",");
340     QStringList params = sane_msg.trimmed().split(" ");
341
342     QStringList chans = params[0].split(",", QString::SkipEmptyParts);
343     QStringList keys;
344     if (params.count() > 1)
345         keys = params[1].split(",");
346
347     int i;
348     for (i = 0; i < chans.count(); i++) {
349         if (!network()->isChannelName(chans[i]))
350             chans[i].prepend('#');
351
352         if (i < keys.count()) {
353             network()->addChannelKey(chans[i], keys[i]);
354         }
355         else {
356             network()->removeChannelKey(chans[i]);
357         }
358     }
359
360     static const char* cmd = "JOIN";
361     i = 0;
362     QStringList joinChans, joinKeys;
363     int slicesize = chans.count();
364     QList<QByteArray> encodedParams;
365
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));
371
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) {
375             params.clear();
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);
382             }
383             else if (slicesize > 1) {
384                 // back to start of slice, try again with half the amount of channels
385                 i -= slicesize;
386                 slicesize /= 2;
387             }
388             joinChans.clear();
389             joinKeys.clear();
390         }
391     }
392 }
393
394 void CoreUserInputHandler::handleKeyx(const BufferInfo& bufferInfo, const QString& msg)
395 {
396     QString bufname = bufferInfo.bufferName().isNull() ? "" : bufferInfo.bufferName();
397 #ifdef HAVE_QCA2
398     if (!bufferInfo.isValid())
399         return;
400
401     if (!Cipher::neededFeaturesAvailable()) {
402         emit displayMsg(NetworkInternalMessage(
403             Message::Error,
404             typeByTarget(bufname),
405             bufname,
406             tr("Error: QCA provider plugin not found. It is usually provided by the qca-ossl plugin.")
407         ));
408         return;
409     }
410
411     QStringList parms = msg.split(' ', QString::SkipEmptyParts);
412
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(
417             Message::Info,
418             typeByTarget(bufname),
419             bufname,
420             tr("[usage] /keyx [<nick>] Initiates a DH1080 key exchange with the target.")
421         ));
422         return;
423     }
424
425     QString target = parms.at(0);
426
427     if (network()->isChannelName(target)) {
428         emit displayMsg(NetworkInternalMessage(
429             Message::Info,
430             typeByTarget(bufname),
431             bufname,
432             tr("It is only possible to exchange keys in a query buffer.")
433         ));
434         return;
435     }
436
437     Cipher* cipher = network()->cipher(target);
438     if (!cipher)  // happens when there is no CoreIrcChannel for the target
439         return;
440
441     QByteArray pubKey = cipher->initKeyExchange();
442     if (pubKey.isEmpty())
443         emit displayMsg(NetworkInternalMessage(
444             Message::Error,
445             typeByTarget(bufname),
446             bufname,
447             tr("Failed to initiate key exchange with %1.").arg(target)
448         ));
449     else {
450         QList<QByteArray> params;
451         params << serverEncode(target) << serverEncode("DH1080_INIT ") + pubKey;
452         emit putCmd("NOTICE", params);
453         emit displayMsg(NetworkInternalMessage(
454             Message::Info,
455             typeByTarget(bufname),
456             bufname,
457             tr("Initiated key exchange with %1.").arg(target)
458         ));
459     }
460 #else
461     Q_UNUSED(msg)
462     emit displayMsg(NetworkInternalMessage(
463         Message::Error,
464         typeByTarget(bufname),
465         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.")
470     ));
471 #endif
472 }
473
474 void CoreUserInputHandler::handleKick(const BufferInfo& bufferInfo, const QString& msg)
475 {
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();
480
481     QList<QByteArray> params;
482     params << serverEncode(bufferInfo.bufferName()) << serverEncode(nick) << channelEncode(bufferInfo.bufferName(), reason);
483     emit putCmd("KICK", params);
484 }
485
486 void CoreUserInputHandler::handleKill(const BufferInfo& bufferInfo, const QString& msg)
487 {
488     Q_UNUSED(bufferInfo)
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);
494 }
495
496 void CoreUserInputHandler::handleList(const BufferInfo& bufferInfo, const QString& msg)
497 {
498     Q_UNUSED(bufferInfo)
499     emit putCmd("LIST", serverEncode(msg.split(' ', QString::SkipEmptyParts)));
500 }
501
502 void CoreUserInputHandler::handleMe(const BufferInfo& bufferInfo, const QString& msg)
503 {
504     if (bufferInfo.bufferName().isEmpty() || !bufferInfo.acceptsRegularMessages())
505         return;  // server buffer
506     // FIXME make this a proper event
507
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);
511
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(
517                 Message::Action,
518                 bufferInfo.type(),
519                 bufferInfo.bufferName(),
520                 message,
521                 network()->myNick(),
522                 Message::Self
523             ));
524         }
525     }
526 }
527
528 void CoreUserInputHandler::handleMode(const BufferInfo& bufferInfo, const QString& msg)
529 {
530     Q_UNUSED(bufferInfo)
531
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(
537                 Message::Info,
538                 BufferInfo::StatusBuffer,
539                 "",
540                 tr("Your persistent modes have been reset.")
541             ));
542             return;
543         }
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]);
551     }
552
553     // TODO handle correct encoding for buffer modes (channelEncode())
554     emit putCmd("MODE", serverEncode(params));
555 }
556
557 // TODO: show privmsgs
558 void CoreUserInputHandler::handleMsg(const BufferInfo& bufferInfo, const QString& msg)
559 {
560     Q_UNUSED(bufferInfo);
561     if (!msg.contains(' '))
562         return;
563
564     QString target = msg.section(' ', 0, 0);
565     QString msgSection = msg.section(' ', 1);
566
567     std::function<QByteArray(const QString&, const QString&)> encodeFunc =
568         [this](const QString& target, const QString& message) -> QByteArray { return userEncode(target, message); };
569
570 #ifdef HAVE_QCA2
571     putPrivmsg(target, msgSection, encodeFunc, network()->cipher(target));
572 #else
573     putPrivmsg(target, msgSection, encodeFunc);
574 #endif
575 }
576
577 void CoreUserInputHandler::handleNick(const BufferInfo& bufferInfo, const QString& msg)
578 {
579     Q_UNUSED(bufferInfo)
580     QString nick = msg.section(' ', 0, 0);
581     emit putCmd("NICK", serverEncode(nick));
582 }
583
584 void CoreUserInputHandler::handleNotice(const BufferInfo& bufferInfo, const QString& msg)
585 {
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);
591
592     for (const auto& message : messages) {
593         // Handle each separated message independently
594         params.clear();
595         params << serverEncode(bufferName) << channelEncode(bufferInfo.bufferName(), message);
596         emit putCmd("NOTICE", params);
597         if (!network()->capEnabled(IrcCap::ECHO_MESSAGE)) {
598             emit displayMsg(NetworkInternalMessage(
599                 Message::Notice,
600                 typeByTarget(bufferName),
601                 bufferName,
602                 message,
603                 network()->myNick(),
604                 Message::Self
605             ));
606         }
607     }
608 }
609
610 void CoreUserInputHandler::handleOper(const BufferInfo& bufferInfo, const QString& msg)
611 {
612     Q_UNUSED(bufferInfo)
613     emit putRawLine(serverEncode(QString("OPER %1").arg(msg)));
614 }
615
616 void CoreUserInputHandler::handlePart(const BufferInfo& bufferInfo, const QString& msg)
617 {
618     QList<QByteArray> params;
619     QString partReason;
620
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();
625         partReason = msg;
626     }
627     else {
628         partReason = msg.mid(channelName.length() + 1);
629     }
630
631     if (partReason.isEmpty())
632         partReason = network()->identityPtr()->partReason();
633
634     params << serverEncode(channelName) << channelEncode(bufferInfo.bufferName(), partReason);
635     emit putCmd("PART", params);
636 }
637
638 void CoreUserInputHandler::handlePing(const BufferInfo& bufferInfo, const QString& msg)
639 {
640     Q_UNUSED(bufferInfo)
641
642     QString param = msg;
643     if (param.isEmpty())
644         param = QTime::currentTime().toString("hh:mm:ss.zzz");
645
646     // Take priority so this won't get stuck behind other queued messages.
647     putCmd("PING", serverEncode(param), {}, {}, true);
648 }
649
650 void CoreUserInputHandler::handlePrint(const BufferInfo& bufferInfo, const QString& msg)
651 {
652     if (bufferInfo.bufferName().isEmpty() || !bufferInfo.acceptsRegularMessages())
653         return;  // server buffer
654
655     QByteArray encMsg = channelEncode(bufferInfo.bufferName(), msg);
656     emit displayMsg(NetworkInternalMessage(
657         Message::Info,
658         bufferInfo.type(),
659         bufferInfo.bufferName(),
660         msg,
661         network()->myNick(),
662         Message::Self
663     ));
664 }
665
666 // TODO: implement queries
667 void CoreUserInputHandler::handleQuery(const BufferInfo& bufferInfo, const QString& msg)
668 {
669     Q_UNUSED(bufferInfo)
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);
674
675     for (const auto& message : messages) {
676         // Handle each separated message independently
677         if (message.isEmpty()) {
678             emit displayMsg(NetworkInternalMessage(
679                 Message::Server,
680                 BufferInfo::QueryBuffer,
681                 target,
682                 tr("Starting query with %1").arg(target),
683                 network()->myNick(),
684                 Message::Self
685             ));
686             // handleMsg is a no-op if message is empty
687         }
688         else {
689             if (!network()->capEnabled(IrcCap::ECHO_MESSAGE)) {
690                 emit displayMsg(NetworkInternalMessage(
691                     Message::Plain,
692                     BufferInfo::QueryBuffer,
693                     target,
694                     message,
695                     network()->myNick(),
696                     Message::Self
697                 ));
698             }
699             // handleMsg needs the target specified at the beginning of the message
700             handleMsg(bufferInfo, target + " " + message);
701         }
702     }
703 }
704
705 void CoreUserInputHandler::handleQuit(const BufferInfo& bufferInfo, const QString& msg)
706 {
707     Q_UNUSED(bufferInfo)
708     network()->disconnectFromIrc(true, msg);
709 }
710
711 void CoreUserInputHandler::issueQuit(const QString& reason, bool forceImmediate)
712 {
713     // If needing an immediate QUIT (e.g. core shutdown), prepend this to the queue
714     emit putCmd("QUIT", serverEncode(reason), {}, {}, forceImmediate);
715 }
716
717 void CoreUserInputHandler::handleQuote(const BufferInfo& bufferInfo, const QString& msg)
718 {
719     Q_UNUSED(bufferInfo)
720     emit putRawLine(serverEncode(msg));
721 }
722
723 void CoreUserInputHandler::handleSay(const BufferInfo& bufferInfo, const QString& msg)
724 {
725     if (bufferInfo.bufferName().isEmpty() || !bufferInfo.acceptsRegularMessages())
726         return;  // server buffer
727
728     std::function<QByteArray(const QString&, const QString&)> encodeFunc =
729         [this](const QString& target, const QString& message) -> QByteArray { return channelEncode(target, message); };
730
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);
734
735     for (const auto& message : messages) {
736         // Handle each separated message independently
737 #ifdef HAVE_QCA2
738         putPrivmsg(bufferInfo.bufferName(), message, encodeFunc, network()->cipher(bufferInfo.bufferName()));
739 #else
740         putPrivmsg(bufferInfo.bufferName(), message, encodeFunc);
741 #endif
742         if (!network()->capEnabled(IrcCap::ECHO_MESSAGE)) {
743             emit displayMsg(NetworkInternalMessage(
744                 Message::Plain,
745                 bufferInfo.type(),
746                 bufferInfo.bufferName(),
747                 message,
748                 network()->myNick(),
749                 Message::Self
750             ));
751         }
752     }
753 }
754
755 void CoreUserInputHandler::handleSetkey(const BufferInfo& bufferInfo, const QString& msg)
756 {
757     QString bufname = bufferInfo.bufferName().isNull() ? "" : bufferInfo.bufferName();
758 #ifdef HAVE_QCA2
759     if (!bufferInfo.isValid())
760         return;
761
762     if (!Cipher::neededFeaturesAvailable()) {
763         emit displayMsg(NetworkInternalMessage(
764             Message::Error,
765             typeByTarget(bufname),
766             bufname,
767             tr("Error: QCA provider plugin not found. It is usually provided by the qca-ossl plugin.")
768         ));
769         return;
770     }
771
772     QStringList parms = msg.split(' ', QString::SkipEmptyParts);
773
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(
778             Message::Info,
779             typeByTarget(bufname),
780             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.")
784         ));
785         return;
786     }
787
788     QString target = parms.at(0);
789     QByteArray key = parms.at(1).toLocal8Bit();
790     network()->setCipherKey(target, key);
791
792     emit displayMsg(NetworkInternalMessage(
793         Message::Info,
794         typeByTarget(bufname),
795         bufname,
796         tr("The key for %1 has been set.").arg(target)
797     ));
798 #else
799     Q_UNUSED(msg)
800     emit displayMsg(NetworkInternalMessage(
801         Message::Error,
802         typeByTarget(bufname),
803         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.")
808     ));
809 #endif
810 }
811
812 void CoreUserInputHandler::handleSetname(const BufferInfo& bufferInfo, const QString& msg)
813 {
814     Q_UNUSED(bufferInfo)
815     emit putCmd("SETNAME", serverEncode(msg));
816 }
817
818 void CoreUserInputHandler::handleShowkey(const BufferInfo& bufferInfo, const QString& msg)
819 {
820     QString bufname = bufferInfo.bufferName().isNull() ? "" : bufferInfo.bufferName();
821 #ifdef HAVE_QCA2
822     if (!bufferInfo.isValid())
823         return;
824
825     if (!Cipher::neededFeaturesAvailable()) {
826         emit displayMsg(NetworkInternalMessage(
827             Message::Error,
828             typeByTarget(bufname),
829             bufname,
830             tr("Error: QCA provider plugin not found. It is usually provided by the qca-ossl plugin.")
831         ));
832         return;
833     }
834
835     QStringList parms = msg.split(' ', QString::SkipEmptyParts);
836
837     if (parms.isEmpty() && !bufferInfo.bufferName().isEmpty() && bufferInfo.acceptsRegularMessages())
838         parms.prepend(bufferInfo.bufferName());
839
840     if (parms.isEmpty()) {
841         emit displayMsg(NetworkInternalMessage(
842             Message::Info,
843             typeByTarget(bufname),
844             bufname,
845             tr("[usage] /showkey <nick|channel> shows the encryption key for nick or channel or just /showkey when in a "
846                "channel or query.")
847         ));
848         return;
849     }
850
851     QString target = parms.at(0);
852     QByteArray key = network()->cipherKey(target);
853
854     if (key.isEmpty()) {
855         emit displayMsg(NetworkInternalMessage(
856             Message::Info,
857             typeByTarget(bufname),
858             bufname,
859             tr("No key has been set for %1.").arg(target)
860         ));
861         return;
862     }
863
864     emit displayMsg(NetworkInternalMessage(
865         Message::Info,
866         typeByTarget(bufname),
867         bufname,
868         tr("The key for %1 is %2:%3").arg(target, network()->cipherUsesCBC(target) ? "CBC" : "ECB", QString(key))
869     ));
870
871 #else
872     Q_UNUSED(msg)
873     emit displayMsg(NetworkInternalMessage(
874         Message::Error,
875         typeByTarget(bufname),
876         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.")
881     ));
882 #endif
883 }
884
885 void CoreUserInputHandler::handleTopic(const BufferInfo& bufferInfo, const QString& msg)
886 {
887     if (bufferInfo.bufferName().isEmpty() || !bufferInfo.acceptsRegularMessages())
888         return;
889
890     QList<QByteArray> params;
891     params << serverEncode(bufferInfo.bufferName());
892
893     if (!msg.isEmpty()) {
894 #ifdef HAVE_QCA2
895         params << encrypt(bufferInfo.bufferName(), channelEncode(bufferInfo.bufferName(), msg));
896 #else
897         params << channelEncode(bufferInfo.bufferName(), msg);
898 #endif
899     }
900
901     emit putCmd("TOPIC", params);
902 }
903
904 void CoreUserInputHandler::handleVoice(const BufferInfo& bufferInfo, const QString& msg)
905 {
906     QStringList nicks = msg.split(' ', QString::SkipEmptyParts);
907     QString m = "+";
908     for (int i = 0; i < nicks.count(); i++)
909         m += 'v';
910     QStringList params;
911     params << bufferInfo.bufferName() << m << nicks;
912     emit putCmd("MODE", serverEncode(params));
913 }
914
915 void CoreUserInputHandler::handleWait(const BufferInfo& bufferInfo, const QString& msg)
916 {
917     int splitPos = msg.indexOf(';');
918     if (splitPos <= 0)
919         return;
920
921     bool ok;
922     int delay = msg.left(splitPos).trimmed().toInt(&ok);
923     if (!ok)
924         return;
925
926     delay *= 1000;
927
928     QString command = msg.mid(splitPos + 1).trimmed();
929     if (command.isEmpty())
930         return;
931
932     _delayedCommands[startTimer(delay)] = Command(bufferInfo, command);
933 }
934
935 void CoreUserInputHandler::handleWho(const BufferInfo& bufferInfo, const QString& msg)
936 {
937     Q_UNUSED(bufferInfo)
938     emit putCmd("WHO", serverEncode(msg.split(' ')));
939 }
940
941 void CoreUserInputHandler::handleWhois(const BufferInfo& bufferInfo, const QString& msg)
942 {
943     Q_UNUSED(bufferInfo)
944     emit putCmd("WHOIS", serverEncode(msg.split(' ')));
945 }
946
947 void CoreUserInputHandler::handleWhowas(const BufferInfo& bufferInfo, const QString& msg)
948 {
949     Q_UNUSED(bufferInfo)
950     emit putCmd("WHOWAS", serverEncode(msg.split(' ')));
951 }
952
953 void CoreUserInputHandler::defaultHandler(QString cmd, const BufferInfo& bufferInfo, const QString& msg)
954 {
955     Q_UNUSED(bufferInfo);
956     emit putCmd(serverEncode(cmd.toUpper()), serverEncode(msg.split(" ")));
957 }
958
959 void CoreUserInputHandler::putPrivmsg(const QString& target,
960                                       const QString& message,
961                                       std::function<QByteArray(const QString&, const QString&)> encodeFunc,
962                                       Cipher* cipher)
963 {
964     Q_UNUSED(cipher);
965     QString cmd("PRIVMSG");
966     QByteArray targetEnc = serverEncode(target);
967
968     std::function<QList<QByteArray>(QString&)> cmdGenerator = [&](QString& splitMsg) -> QList<QByteArray> {
969         QByteArray splitMsgEnc = encodeFunc(target, splitMsg);
970
971 #ifdef HAVE_QCA2
972         if (cipher && !cipher->key().isEmpty() && !splitMsg.isEmpty()) {
973             cipher->encrypt(splitMsgEnc);
974         }
975 #endif
976         return QList<QByteArray>() << targetEnc << splitMsgEnc;
977     };
978
979     putCmd(cmd, network()->splitMessage(cmd, message, cmdGenerator));
980 }
981
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)
984 {
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?)
993
994     if (me)
995         maxLen = 512 - serverEncode(me->nick()).count() - serverEncode(me->user()).count() - serverEncode(me->host()).count()
996                  - cmd.toLatin1().count() - 6;
997
998     if (!params.isEmpty()) {
999         for (int i = 0; i < params.count() - 1; i++) {
1000             maxLen -= (params[i].count() + 1);
1001         }
1002         maxLen -= 2;  // " :" last param separator;
1003
1004         if (params.last().count() > maxLen) {
1005             return params.last().count() - maxLen;
1006         }
1007         else {
1008             return 0;
1009         }
1010     }
1011     else {
1012         return 0;
1013     }
1014 }
1015
1016 #ifdef HAVE_QCA2
1017 QByteArray CoreUserInputHandler::encrypt(const QString& target, const QByteArray& message_, bool* didEncrypt) const
1018 {
1019     if (didEncrypt)
1020         *didEncrypt = false;
1021
1022     if (message_.isEmpty())
1023         return message_;
1024
1025     if (!Cipher::neededFeaturesAvailable())
1026         return message_;
1027
1028     Cipher* cipher = network()->cipher(target);
1029     if (!cipher || cipher->key().isEmpty())
1030         return message_;
1031
1032     QByteArray message = message_;
1033     bool result = cipher->encrypt(message);
1034     if (didEncrypt)
1035         *didEncrypt = result;
1036
1037     return message;
1038 }
1039
1040 #endif
1041
1042 void CoreUserInputHandler::timerEvent(QTimerEvent* event)
1043 {
1044     if (!_delayedCommands.contains(event->timerId())) {
1045         QObject::timerEvent(event);
1046         return;
1047     }
1048     BufferInfo bufferInfo = _delayedCommands[event->timerId()].bufferInfo;
1049     QString rawCommand = _delayedCommands[event->timerId()].command;
1050     _delayedCommands.remove(event->timerId());
1051     event->accept();
1052
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);
1057     }
1058 }