core: Implement invite-notify
[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     emit displayMsg(NetworkInternalMessage(
187         Message::Action,
188         BufferInfo::StatusBuffer,
189         "",
190         verboseMessage,
191         network()->myNick(),
192         Message::Flag::Self
193     ));
194 }
195
196 void CoreUserInputHandler::handleDelkey(const BufferInfo& bufferInfo, const QString& msg)
197 {
198     QString bufname = bufferInfo.bufferName().isNull() ? "" : bufferInfo.bufferName();
199 #ifdef HAVE_QCA2
200     if (!bufferInfo.isValid())
201         return;
202
203     if (!Cipher::neededFeaturesAvailable()) {
204         emit displayMsg(NetworkInternalMessage(
205             Message::Error,
206             typeByTarget(bufname),
207             bufname,
208             tr("Error: QCA provider plugin not found. It is usually provided by the qca-ossl plugin.")
209         ));
210         return;
211     }
212
213     QStringList parms = msg.split(' ', QString::SkipEmptyParts);
214
215     if (parms.isEmpty() && !bufferInfo.bufferName().isEmpty() && bufferInfo.acceptsRegularMessages())
216         parms.prepend(bufferInfo.bufferName());
217
218     if (parms.isEmpty()) {
219         emit displayMsg(NetworkInternalMessage(
220             Message::Info,
221             typeByTarget(bufname),
222             bufname,
223             tr("[usage] /delkey <nick|channel> deletes the encryption key for nick or channel or just /delkey when in a "
224                "channel or query.")
225         ));
226         return;
227     }
228
229     QString target = parms.at(0);
230
231     if (network()->cipherKey(target).isEmpty()) {
232         emit displayMsg(NetworkInternalMessage(
233             Message::Info,
234             typeByTarget(bufname),
235             bufname,
236             tr("No key has been set for %1.").arg(target)
237         ));
238         return;
239     }
240
241     network()->setCipherKey(target, QByteArray());
242     emit displayMsg(NetworkInternalMessage(
243         Message::Info,
244         typeByTarget(bufname),
245         bufname,
246         tr("The key for %1 has been deleted.").arg(target)
247     ));
248
249 #else
250     Q_UNUSED(msg)
251     emit displayMsg(NetworkInternalMessage(
252         Message::Error,
253         typeByTarget(bufname),
254         bufname,
255         tr("Error: Setting an encryption key requires Quassel to have been built "
256            "with support for the Qt Cryptographic Architecture (QCA2) library. "
257            "Contact your distributor about a Quassel package with QCA2 "
258            "support, or rebuild Quassel with QCA2 present.")
259     ));
260 #endif
261 }
262
263 void CoreUserInputHandler::doMode(const BufferInfo& bufferInfo, const QChar& addOrRemove, const QChar& mode, const QString& nicks)
264 {
265     bool isNumber;
266     int maxModes = network()->support("MODES").toInt(&isNumber);
267     if (!isNumber || maxModes == 0)
268         maxModes = 1;
269
270     QStringList nickList;
271     if (nicks == "*" && bufferInfo.type() == BufferInfo::ChannelBuffer) {  // All users in channel
272         const QList<IrcUser*> users = network()->ircChannel(bufferInfo.bufferName())->ircUsers();
273         for (IrcUser* user : users) {
274             if ((addOrRemove == '+' && !network()->ircChannel(bufferInfo.bufferName())->userModes(user).contains(mode))
275                 || (addOrRemove == '-' && network()->ircChannel(bufferInfo.bufferName())->userModes(user).contains(mode)))
276                 nickList.append(user->nick());
277         }
278     }
279     else {
280         nickList = nicks.split(' ', QString::SkipEmptyParts);
281     }
282
283     if (nickList.count() == 0)
284         return;
285
286     while (!nickList.isEmpty()) {
287         int amount = qMin(nickList.count(), maxModes);
288         QString m = addOrRemove;
289         for (int i = 0; i < amount; i++)
290             m += mode;
291         QStringList params;
292         params << bufferInfo.bufferName() << m;
293         for (int i = 0; i < amount; i++)
294             params << nickList.takeFirst();
295         emit putCmd("MODE", serverEncode(params));
296     }
297 }
298
299 void CoreUserInputHandler::handleDeop(const BufferInfo& bufferInfo, const QString& nicks)
300 {
301     doMode(bufferInfo, '-', 'o', nicks);
302 }
303
304 void CoreUserInputHandler::handleDehalfop(const BufferInfo& bufferInfo, const QString& nicks)
305 {
306     doMode(bufferInfo, '-', 'h', nicks);
307 }
308
309 void CoreUserInputHandler::handleDevoice(const BufferInfo& bufferInfo, const QString& nicks)
310 {
311     doMode(bufferInfo, '-', 'v', nicks);
312 }
313
314 void CoreUserInputHandler::handleHalfop(const BufferInfo& bufferInfo, const QString& nicks)
315 {
316     doMode(bufferInfo, '+', 'h', nicks);
317 }
318
319 void CoreUserInputHandler::handleOp(const BufferInfo& bufferInfo, const QString& nicks)
320 {
321     doMode(bufferInfo, '+', 'o', nicks);
322 }
323
324 void CoreUserInputHandler::handleInvite(const BufferInfo& bufferInfo, const QString& msg)
325 {
326     QStringList params;
327     params << msg << bufferInfo.bufferName();
328     emit putCmd("INVITE", serverEncode(params));
329 }
330
331 void CoreUserInputHandler::handleJoin(const BufferInfo& bufferInfo, const QString& msg)
332 {
333     Q_UNUSED(bufferInfo);
334
335     // trim spaces before chans or keys
336     QString sane_msg = msg;
337     sane_msg.replace(QRegExp(", +"), ",");
338     QStringList params = sane_msg.trimmed().split(" ");
339
340     QStringList chans = params[0].split(",", QString::SkipEmptyParts);
341     QStringList keys;
342     if (params.count() > 1)
343         keys = params[1].split(",");
344
345     int i;
346     for (i = 0; i < chans.count(); i++) {
347         if (!network()->isChannelName(chans[i]))
348             chans[i].prepend('#');
349
350         if (i < keys.count()) {
351             network()->addChannelKey(chans[i], keys[i]);
352         }
353         else {
354             network()->removeChannelKey(chans[i]);
355         }
356     }
357
358     static const char* cmd = "JOIN";
359     i = 0;
360     QStringList joinChans, joinKeys;
361     int slicesize = chans.count();
362     QList<QByteArray> encodedParams;
363
364     // go through all to-be-joined channels and (re)build the join list
365     while (i < chans.count()) {
366         joinChans.append(chans.at(i));
367         if (i < keys.count())
368             joinKeys.append(keys.at(i));
369
370         // if the channel list we built so far either contains all requested channels or exceeds
371         // the desired amount of channels in this slice, try to send what we have so far
372         if (++i == chans.count() || joinChans.count() >= slicesize) {
373             params.clear();
374             params.append(joinChans.join(","));
375             params.append(joinKeys.join(","));
376             encodedParams = serverEncode(params);
377             // check if it fits in one command
378             if (lastParamOverrun(cmd, encodedParams) == 0) {
379                 emit putCmd(cmd, encodedParams);
380             }
381             else if (slicesize > 1) {
382                 // back to start of slice, try again with half the amount of channels
383                 i -= slicesize;
384                 slicesize /= 2;
385             }
386             joinChans.clear();
387             joinKeys.clear();
388         }
389     }
390 }
391
392 void CoreUserInputHandler::handleKeyx(const BufferInfo& bufferInfo, const QString& msg)
393 {
394     QString bufname = bufferInfo.bufferName().isNull() ? "" : bufferInfo.bufferName();
395 #ifdef HAVE_QCA2
396     if (!bufferInfo.isValid())
397         return;
398
399     if (!Cipher::neededFeaturesAvailable()) {
400         emit displayMsg(NetworkInternalMessage(
401             Message::Error,
402             typeByTarget(bufname),
403             bufname,
404             tr("Error: QCA provider plugin not found. It is usually provided by the qca-ossl plugin.")
405         ));
406         return;
407     }
408
409     QStringList parms = msg.split(' ', QString::SkipEmptyParts);
410
411     if (parms.count() == 0 && !bufferInfo.bufferName().isEmpty() && bufferInfo.acceptsRegularMessages())
412         parms.prepend(bufferInfo.bufferName());
413     else if (parms.count() != 1) {
414         emit displayMsg(NetworkInternalMessage(
415             Message::Info,
416             typeByTarget(bufname),
417             bufname,
418             tr("[usage] /keyx [<nick>] Initiates a DH1080 key exchange with the target.")
419         ));
420         return;
421     }
422
423     QString target = parms.at(0);
424
425     if (network()->isChannelName(target)) {
426         emit displayMsg(NetworkInternalMessage(
427             Message::Info,
428             typeByTarget(bufname),
429             bufname,
430             tr("It is only possible to exchange keys in a query buffer.")
431         ));
432         return;
433     }
434
435     Cipher* cipher = network()->cipher(target);
436     if (!cipher)  // happens when there is no CoreIrcChannel for the target
437         return;
438
439     QByteArray pubKey = cipher->initKeyExchange();
440     if (pubKey.isEmpty())
441         emit displayMsg(NetworkInternalMessage(
442             Message::Error,
443             typeByTarget(bufname),
444             bufname,
445             tr("Failed to initiate key exchange with %1.").arg(target)
446         ));
447     else {
448         QList<QByteArray> params;
449         params << serverEncode(target) << serverEncode("DH1080_INIT ") + pubKey;
450         emit putCmd("NOTICE", params);
451         emit displayMsg(NetworkInternalMessage(
452             Message::Info,
453             typeByTarget(bufname),
454             bufname,
455             tr("Initiated key exchange with %1.").arg(target)
456         ));
457     }
458 #else
459     Q_UNUSED(msg)
460     emit displayMsg(NetworkInternalMessage(
461         Message::Error,
462         typeByTarget(bufname),
463         bufname,
464         tr("Error: Setting an encryption key requires Quassel to have been built "
465            "with support for the Qt Cryptographic Architecture (QCA) library. "
466            "Contact your distributor about a Quassel package with QCA "
467            "support, or rebuild Quassel with QCA present.")
468     ));
469 #endif
470 }
471
472 void CoreUserInputHandler::handleKick(const BufferInfo& bufferInfo, const QString& msg)
473 {
474     QString nick = msg.section(' ', 0, 0, QString::SectionSkipEmpty);
475     QString reason = msg.section(' ', 1, -1, QString::SectionSkipEmpty).trimmed();
476     if (reason.isEmpty())
477         reason = network()->identityPtr()->kickReason();
478
479     QList<QByteArray> params;
480     params << serverEncode(bufferInfo.bufferName()) << serverEncode(nick) << channelEncode(bufferInfo.bufferName(), reason);
481     emit putCmd("KICK", params);
482 }
483
484 void CoreUserInputHandler::handleKill(const BufferInfo& bufferInfo, const QString& msg)
485 {
486     Q_UNUSED(bufferInfo)
487     QString nick = msg.section(' ', 0, 0, QString::SectionSkipEmpty);
488     QString pass = msg.section(' ', 1, -1, QString::SectionSkipEmpty);
489     QList<QByteArray> params;
490     params << serverEncode(nick) << serverEncode(pass);
491     emit putCmd("KILL", params);
492 }
493
494 void CoreUserInputHandler::handleList(const BufferInfo& bufferInfo, const QString& msg)
495 {
496     Q_UNUSED(bufferInfo)
497     emit putCmd("LIST", serverEncode(msg.split(' ', QString::SkipEmptyParts)));
498 }
499
500 void CoreUserInputHandler::handleMe(const BufferInfo& bufferInfo, const QString& msg)
501 {
502     if (bufferInfo.bufferName().isEmpty() || !bufferInfo.acceptsRegularMessages())
503         return;  // server buffer
504     // FIXME make this a proper event
505
506     // Split apart messages at line feeds.  The IRC protocol uses those to separate commands, so
507     // they need to be split into multiple messages.
508     QStringList messages = msg.split(QChar::LineFeed);
509
510     for (const auto& message : messages) {
511         // Handle each separated message independently
512         coreNetwork()->coreSession()->ctcpParser()->query(coreNetwork(), bufferInfo.bufferName(), "ACTION", message);
513         emit displayMsg(NetworkInternalMessage(
514             Message::Action,
515             bufferInfo.type(),
516             bufferInfo.bufferName(),
517             message,
518             network()->myNick(),
519             Message::Self
520         ));
521     }
522 }
523
524 void CoreUserInputHandler::handleMode(const BufferInfo& bufferInfo, const QString& msg)
525 {
526     Q_UNUSED(bufferInfo)
527
528     QStringList params = msg.split(' ', QString::SkipEmptyParts);
529     if (!params.isEmpty()) {
530         if (params[0] == "-reset" && params.count() == 1) {
531             network()->resetPersistentModes();
532             emit displayMsg(NetworkInternalMessage(
533                 Message::Info,
534                 BufferInfo::StatusBuffer,
535                 "",
536                 tr("Your persistent modes have been reset.")
537             ));
538             return;
539         }
540         if (!network()->isChannelName(params[0]) && !network()->isMyNick(params[0]))
541             // If the first argument is neither a channel nor us (user modes are only to oneself)
542             // the current buffer is assumed to be the target.
543             // If the current buffer returns no name (e.g. status buffer), assume target is us.
544             params.prepend(!bufferInfo.bufferName().isEmpty() ? bufferInfo.bufferName() : network()->myNick());
545         if (network()->isMyNick(params[0]) && params.count() == 2)
546             network()->updateIssuedModes(params[1]);
547     }
548
549     // TODO handle correct encoding for buffer modes (channelEncode())
550     emit putCmd("MODE", serverEncode(params));
551 }
552
553 // TODO: show privmsgs
554 void CoreUserInputHandler::handleMsg(const BufferInfo& bufferInfo, const QString& msg)
555 {
556     Q_UNUSED(bufferInfo);
557     if (!msg.contains(' '))
558         return;
559
560     QString target = msg.section(' ', 0, 0);
561     QString msgSection = msg.section(' ', 1);
562
563     std::function<QByteArray(const QString&, const QString&)> encodeFunc =
564         [this](const QString& target, const QString& message) -> QByteArray { return userEncode(target, message); };
565
566 #ifdef HAVE_QCA2
567     putPrivmsg(target, msgSection, encodeFunc, network()->cipher(target));
568 #else
569     putPrivmsg(target, msgSection, encodeFunc);
570 #endif
571 }
572
573 void CoreUserInputHandler::handleNick(const BufferInfo& bufferInfo, const QString& msg)
574 {
575     Q_UNUSED(bufferInfo)
576     QString nick = msg.section(' ', 0, 0);
577     emit putCmd("NICK", serverEncode(nick));
578 }
579
580 void CoreUserInputHandler::handleNotice(const BufferInfo& bufferInfo, const QString& msg)
581 {
582     QString bufferName = msg.section(' ', 0, 0);
583     QList<QByteArray> params;
584     // Split apart messages at line feeds.  The IRC protocol uses those to separate commands, so
585     // they need to be split into multiple messages.
586     QStringList messages = msg.section(' ', 1).split(QChar::LineFeed);
587
588     for (const auto& message : messages) {
589         // Handle each separated message independently
590         params.clear();
591         params << serverEncode(bufferName) << channelEncode(bufferInfo.bufferName(), message);
592         emit putCmd("NOTICE", params);
593         emit displayMsg(NetworkInternalMessage(
594             Message::Notice,
595             typeByTarget(bufferName),
596             bufferName,
597             message,
598             network()->myNick(),
599             Message::Self
600         ));
601     }
602 }
603
604 void CoreUserInputHandler::handleOper(const BufferInfo& bufferInfo, const QString& msg)
605 {
606     Q_UNUSED(bufferInfo)
607     emit putRawLine(serverEncode(QString("OPER %1").arg(msg)));
608 }
609
610 void CoreUserInputHandler::handlePart(const BufferInfo& bufferInfo, const QString& msg)
611 {
612     QList<QByteArray> params;
613     QString partReason;
614
615     // msg might contain either a channel name and/or a reaon, so we have to check if the first word is a known channel
616     QString channelName = msg.section(' ', 0, 0);
617     if (channelName.isEmpty() || !network()->ircChannel(channelName)) {
618         channelName = bufferInfo.bufferName();
619         partReason = msg;
620     }
621     else {
622         partReason = msg.mid(channelName.length() + 1);
623     }
624
625     if (partReason.isEmpty())
626         partReason = network()->identityPtr()->partReason();
627
628     params << serverEncode(channelName) << channelEncode(bufferInfo.bufferName(), partReason);
629     emit putCmd("PART", params);
630 }
631
632 void CoreUserInputHandler::handlePing(const BufferInfo& bufferInfo, const QString& msg)
633 {
634     Q_UNUSED(bufferInfo)
635
636     QString param = msg;
637     if (param.isEmpty())
638         param = QTime::currentTime().toString("hh:mm:ss.zzz");
639
640     // Take priority so this won't get stuck behind other queued messages.
641     putCmd("PING", serverEncode(param), {}, {}, true);
642 }
643
644 void CoreUserInputHandler::handlePrint(const BufferInfo& bufferInfo, const QString& msg)
645 {
646     if (bufferInfo.bufferName().isEmpty() || !bufferInfo.acceptsRegularMessages())
647         return;  // server buffer
648
649     QByteArray encMsg = channelEncode(bufferInfo.bufferName(), msg);
650     emit displayMsg(NetworkInternalMessage(
651         Message::Info,
652         bufferInfo.type(),
653         bufferInfo.bufferName(),
654         msg,
655         network()->myNick(),
656         Message::Self
657     ));
658 }
659
660 // TODO: implement queries
661 void CoreUserInputHandler::handleQuery(const BufferInfo& bufferInfo, const QString& msg)
662 {
663     Q_UNUSED(bufferInfo)
664     QString target = msg.section(' ', 0, 0);
665     // Split apart messages at line feeds.  The IRC protocol uses those to separate commands, so
666     // they need to be split into multiple messages.
667     QStringList messages = msg.section(' ', 1).split(QChar::LineFeed);
668
669     for (const auto& message : messages) {
670         // Handle each separated message independently
671         if (message.isEmpty()) {
672             emit displayMsg(NetworkInternalMessage(
673                 Message::Server,
674                 BufferInfo::QueryBuffer,
675                 target,
676                 tr("Starting query with %1").arg(target),
677                 network()->myNick(),
678                 Message::Self
679             ));
680             // handleMsg is a no-op if message is empty
681         }
682         else {
683             emit displayMsg(NetworkInternalMessage(
684                 Message::Plain,
685                 BufferInfo::QueryBuffer,
686                 target,
687                 message,
688                 network()->myNick(),
689                 Message::Self
690             ));
691             // handleMsg needs the target specified at the beginning of the message
692             handleMsg(bufferInfo, target + " " + message);
693         }
694     }
695 }
696
697 void CoreUserInputHandler::handleQuit(const BufferInfo& bufferInfo, const QString& msg)
698 {
699     Q_UNUSED(bufferInfo)
700     network()->disconnectFromIrc(true, msg);
701 }
702
703 void CoreUserInputHandler::issueQuit(const QString& reason, bool forceImmediate)
704 {
705     // If needing an immediate QUIT (e.g. core shutdown), prepend this to the queue
706     emit putCmd("QUIT", serverEncode(reason), {}, {}, forceImmediate);
707 }
708
709 void CoreUserInputHandler::handleQuote(const BufferInfo& bufferInfo, const QString& msg)
710 {
711     Q_UNUSED(bufferInfo)
712     emit putRawLine(serverEncode(msg));
713 }
714
715 void CoreUserInputHandler::handleSay(const BufferInfo& bufferInfo, const QString& msg)
716 {
717     if (bufferInfo.bufferName().isEmpty() || !bufferInfo.acceptsRegularMessages())
718         return;  // server buffer
719
720     std::function<QByteArray(const QString&, const QString&)> encodeFunc =
721         [this](const QString& target, const QString& message) -> QByteArray { return channelEncode(target, message); };
722
723     // Split apart messages at line feeds.  The IRC protocol uses those to separate commands, so
724     // they need to be split into multiple messages.
725     QStringList messages = msg.split(QChar::LineFeed, QString::SkipEmptyParts);
726
727     for (const auto& message : messages) {
728         // Handle each separated message independently
729 #ifdef HAVE_QCA2
730         putPrivmsg(bufferInfo.bufferName(), message, encodeFunc, network()->cipher(bufferInfo.bufferName()));
731 #else
732         putPrivmsg(bufferInfo.bufferName(), message, encodeFunc);
733 #endif
734         emit displayMsg(NetworkInternalMessage(
735             Message::Plain,
736             bufferInfo.type(),
737             bufferInfo.bufferName(),
738             message,
739             network()->myNick(),
740             Message::Self
741         ));
742     }
743 }
744
745 void CoreUserInputHandler::handleSetkey(const BufferInfo& bufferInfo, const QString& msg)
746 {
747     QString bufname = bufferInfo.bufferName().isNull() ? "" : bufferInfo.bufferName();
748 #ifdef HAVE_QCA2
749     if (!bufferInfo.isValid())
750         return;
751
752     if (!Cipher::neededFeaturesAvailable()) {
753         emit displayMsg(NetworkInternalMessage(
754             Message::Error,
755             typeByTarget(bufname),
756             bufname,
757             tr("Error: QCA provider plugin not found. It is usually provided by the qca-ossl plugin.")
758         ));
759         return;
760     }
761
762     QStringList parms = msg.split(' ', QString::SkipEmptyParts);
763
764     if (parms.count() == 1 && !bufferInfo.bufferName().isEmpty() && bufferInfo.acceptsRegularMessages())
765         parms.prepend(bufferInfo.bufferName());
766     else if (parms.count() != 2) {
767         emit displayMsg(NetworkInternalMessage(
768             Message::Info,
769             typeByTarget(bufname),
770             bufname,
771             tr("[usage] /setkey <nick|channel> <key> sets the encryption key for nick or channel. "
772                "/setkey <key> when in a channel or query buffer sets the key for it. "
773                "Prefix <key> by cbc: or ebc: to explicitly set the encryption mode respectively. Default is CBC.")
774         ));
775         return;
776     }
777
778     QString target = parms.at(0);
779     QByteArray key = parms.at(1).toLocal8Bit();
780     network()->setCipherKey(target, key);
781
782     emit displayMsg(NetworkInternalMessage(
783         Message::Info,
784         typeByTarget(bufname),
785         bufname,
786         tr("The key for %1 has been set.").arg(target)
787     ));
788 #else
789     Q_UNUSED(msg)
790     emit displayMsg(NetworkInternalMessage(
791         Message::Error,
792         typeByTarget(bufname),
793         bufname,
794         tr("Error: Setting an encryption key requires Quassel to have been built "
795            "with support for the Qt Cryptographic Architecture (QCA) library. "
796            "Contact your distributor about a Quassel package with QCA "
797            "support, or rebuild Quassel with QCA present.")
798     ));
799 #endif
800 }
801
802 void CoreUserInputHandler::handleSetname(const BufferInfo& bufferInfo, const QString& msg)
803 {
804     Q_UNUSED(bufferInfo)
805     emit putCmd("SETNAME", serverEncode(msg));
806 }
807
808 void CoreUserInputHandler::handleShowkey(const BufferInfo& bufferInfo, const QString& msg)
809 {
810     QString bufname = bufferInfo.bufferName().isNull() ? "" : bufferInfo.bufferName();
811 #ifdef HAVE_QCA2
812     if (!bufferInfo.isValid())
813         return;
814
815     if (!Cipher::neededFeaturesAvailable()) {
816         emit displayMsg(NetworkInternalMessage(
817             Message::Error,
818             typeByTarget(bufname),
819             bufname,
820             tr("Error: QCA provider plugin not found. It is usually provided by the qca-ossl plugin.")
821         ));
822         return;
823     }
824
825     QStringList parms = msg.split(' ', QString::SkipEmptyParts);
826
827     if (parms.isEmpty() && !bufferInfo.bufferName().isEmpty() && bufferInfo.acceptsRegularMessages())
828         parms.prepend(bufferInfo.bufferName());
829
830     if (parms.isEmpty()) {
831         emit displayMsg(NetworkInternalMessage(
832             Message::Info,
833             typeByTarget(bufname),
834             bufname,
835             tr("[usage] /showkey <nick|channel> shows the encryption key for nick or channel or just /showkey when in a "
836                "channel or query.")
837         ));
838         return;
839     }
840
841     QString target = parms.at(0);
842     QByteArray key = network()->cipherKey(target);
843
844     if (key.isEmpty()) {
845         emit displayMsg(NetworkInternalMessage(
846             Message::Info,
847             typeByTarget(bufname),
848             bufname,
849             tr("No key has been set for %1.").arg(target)
850         ));
851         return;
852     }
853
854     emit displayMsg(NetworkInternalMessage(
855         Message::Info,
856         typeByTarget(bufname),
857         bufname,
858         tr("The key for %1 is %2:%3").arg(target, network()->cipherUsesCBC(target) ? "CBC" : "ECB", QString(key))
859     ));
860
861 #else
862     Q_UNUSED(msg)
863     emit displayMsg(NetworkInternalMessage(
864         Message::Error,
865         typeByTarget(bufname),
866         bufname,
867         tr("Error: Setting an encryption key requires Quassel to have been built "
868            "with support for the Qt Cryptographic Architecture (QCA2) library. "
869            "Contact your distributor about a Quassel package with QCA2 "
870            "support, or rebuild Quassel with QCA2 present.")
871     ));
872 #endif
873 }
874
875 void CoreUserInputHandler::handleTopic(const BufferInfo& bufferInfo, const QString& msg)
876 {
877     if (bufferInfo.bufferName().isEmpty() || !bufferInfo.acceptsRegularMessages())
878         return;
879
880     QList<QByteArray> params;
881     params << serverEncode(bufferInfo.bufferName());
882
883     if (!msg.isEmpty()) {
884 #ifdef HAVE_QCA2
885         params << encrypt(bufferInfo.bufferName(), channelEncode(bufferInfo.bufferName(), msg));
886 #else
887         params << channelEncode(bufferInfo.bufferName(), msg);
888 #endif
889     }
890
891     emit putCmd("TOPIC", params);
892 }
893
894 void CoreUserInputHandler::handleVoice(const BufferInfo& bufferInfo, const QString& msg)
895 {
896     QStringList nicks = msg.split(' ', QString::SkipEmptyParts);
897     QString m = "+";
898     for (int i = 0; i < nicks.count(); i++)
899         m += 'v';
900     QStringList params;
901     params << bufferInfo.bufferName() << m << nicks;
902     emit putCmd("MODE", serverEncode(params));
903 }
904
905 void CoreUserInputHandler::handleWait(const BufferInfo& bufferInfo, const QString& msg)
906 {
907     int splitPos = msg.indexOf(';');
908     if (splitPos <= 0)
909         return;
910
911     bool ok;
912     int delay = msg.left(splitPos).trimmed().toInt(&ok);
913     if (!ok)
914         return;
915
916     delay *= 1000;
917
918     QString command = msg.mid(splitPos + 1).trimmed();
919     if (command.isEmpty())
920         return;
921
922     _delayedCommands[startTimer(delay)] = Command(bufferInfo, command);
923 }
924
925 void CoreUserInputHandler::handleWho(const BufferInfo& bufferInfo, const QString& msg)
926 {
927     Q_UNUSED(bufferInfo)
928     emit putCmd("WHO", serverEncode(msg.split(' ')));
929 }
930
931 void CoreUserInputHandler::handleWhois(const BufferInfo& bufferInfo, const QString& msg)
932 {
933     Q_UNUSED(bufferInfo)
934     emit putCmd("WHOIS", serverEncode(msg.split(' ')));
935 }
936
937 void CoreUserInputHandler::handleWhowas(const BufferInfo& bufferInfo, const QString& msg)
938 {
939     Q_UNUSED(bufferInfo)
940     emit putCmd("WHOWAS", serverEncode(msg.split(' ')));
941 }
942
943 void CoreUserInputHandler::defaultHandler(QString cmd, const BufferInfo& bufferInfo, const QString& msg)
944 {
945     Q_UNUSED(bufferInfo);
946     emit putCmd(serverEncode(cmd.toUpper()), serverEncode(msg.split(" ")));
947 }
948
949 void CoreUserInputHandler::putPrivmsg(const QString& target,
950                                       const QString& message,
951                                       std::function<QByteArray(const QString&, const QString&)> encodeFunc,
952                                       Cipher* cipher)
953 {
954     Q_UNUSED(cipher);
955     QString cmd("PRIVMSG");
956     QByteArray targetEnc = serverEncode(target);
957
958     std::function<QList<QByteArray>(QString&)> cmdGenerator = [&](QString& splitMsg) -> QList<QByteArray> {
959         QByteArray splitMsgEnc = encodeFunc(target, splitMsg);
960
961 #ifdef HAVE_QCA2
962         if (cipher && !cipher->key().isEmpty() && !splitMsg.isEmpty()) {
963             cipher->encrypt(splitMsgEnc);
964         }
965 #endif
966         return QList<QByteArray>() << targetEnc << splitMsgEnc;
967     };
968
969     putCmd(cmd, network()->splitMessage(cmd, message, cmdGenerator));
970 }
971
972 // returns 0 if the message will not be chopped by the irc server or number of chopped bytes if message is too long
973 int CoreUserInputHandler::lastParamOverrun(const QString& cmd, const QList<QByteArray>& params)
974 {
975     // the server will pass our message truncated to 512 bytes including CRLF with the following format:
976     // ":prefix COMMAND param0 param1 :lastparam"
977     // where prefix = "nickname!user@host"
978     // that means that the last message can be as long as:
979     // 512 - nicklen - userlen - hostlen - commandlen - sum(param[0]..param[n-1])) - 2 (for CRLF) - 4 (":!@" + 1space between prefix and
980     // command) - max(paramcount - 1, 0) (space for simple params) - 2 (space and colon for last param)
981     IrcUser* me = network()->me();
982     int maxLen = 480 - cmd.toLatin1().count();  // educated guess in case we don't know us (yet?)
983
984     if (me)
985         maxLen = 512 - serverEncode(me->nick()).count() - serverEncode(me->user()).count() - serverEncode(me->host()).count()
986                  - cmd.toLatin1().count() - 6;
987
988     if (!params.isEmpty()) {
989         for (int i = 0; i < params.count() - 1; i++) {
990             maxLen -= (params[i].count() + 1);
991         }
992         maxLen -= 2;  // " :" last param separator;
993
994         if (params.last().count() > maxLen) {
995             return params.last().count() - maxLen;
996         }
997         else {
998             return 0;
999         }
1000     }
1001     else {
1002         return 0;
1003     }
1004 }
1005
1006 #ifdef HAVE_QCA2
1007 QByteArray CoreUserInputHandler::encrypt(const QString& target, const QByteArray& message_, bool* didEncrypt) const
1008 {
1009     if (didEncrypt)
1010         *didEncrypt = false;
1011
1012     if (message_.isEmpty())
1013         return message_;
1014
1015     if (!Cipher::neededFeaturesAvailable())
1016         return message_;
1017
1018     Cipher* cipher = network()->cipher(target);
1019     if (!cipher || cipher->key().isEmpty())
1020         return message_;
1021
1022     QByteArray message = message_;
1023     bool result = cipher->encrypt(message);
1024     if (didEncrypt)
1025         *didEncrypt = result;
1026
1027     return message;
1028 }
1029
1030 #endif
1031
1032 void CoreUserInputHandler::timerEvent(QTimerEvent* event)
1033 {
1034     if (!_delayedCommands.contains(event->timerId())) {
1035         QObject::timerEvent(event);
1036         return;
1037     }
1038     BufferInfo bufferInfo = _delayedCommands[event->timerId()].bufferInfo;
1039     QString rawCommand = _delayedCommands[event->timerId()].command;
1040     _delayedCommands.remove(event->timerId());
1041     event->accept();
1042
1043     // the stored command might be the result of an alias expansion, so we need to split it up again
1044     QStringList commands = rawCommand.split(QRegExp("; ?"));
1045     for (const QString& command : commands) {
1046         handleUserInput(bufferInfo, command);
1047     }
1048 }