Sync last message id per buffer
[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         ));
774         return;
775     }
776
777     QString target = parms.at(0);
778     QByteArray key = parms.at(1).toLocal8Bit();
779     network()->setCipherKey(target, key);
780
781     emit displayMsg(NetworkInternalMessage(
782         Message::Info,
783         typeByTarget(bufname),
784         bufname,
785         tr("The key for %1 has been set.").arg(target)
786     ));
787 #else
788     Q_UNUSED(msg)
789     emit displayMsg(NetworkInternalMessage(
790         Message::Error,
791         typeByTarget(bufname),
792         bufname,
793         tr("Error: Setting an encryption key requires Quassel to have been built "
794            "with support for the Qt Cryptographic Architecture (QCA) library. "
795            "Contact your distributor about a Quassel package with QCA "
796            "support, or rebuild Quassel with QCA present.")
797     ));
798 #endif
799 }
800
801 void CoreUserInputHandler::handleShowkey(const BufferInfo& bufferInfo, const QString& msg)
802 {
803     QString bufname = bufferInfo.bufferName().isNull() ? "" : bufferInfo.bufferName();
804 #ifdef HAVE_QCA2
805     if (!bufferInfo.isValid())
806         return;
807
808     if (!Cipher::neededFeaturesAvailable()) {
809         emit displayMsg(NetworkInternalMessage(
810             Message::Error,
811             typeByTarget(bufname),
812             bufname,
813             tr("Error: QCA provider plugin not found. It is usually provided by the qca-ossl plugin.")
814         ));
815         return;
816     }
817
818     QStringList parms = msg.split(' ', QString::SkipEmptyParts);
819
820     if (parms.isEmpty() && !bufferInfo.bufferName().isEmpty() && bufferInfo.acceptsRegularMessages())
821         parms.prepend(bufferInfo.bufferName());
822
823     if (parms.isEmpty()) {
824         emit displayMsg(NetworkInternalMessage(
825             Message::Info,
826             typeByTarget(bufname),
827             bufname,
828             tr("[usage] /showkey <nick|channel> shows the encryption key for nick or channel or just /showkey when in a "
829                "channel or query.")
830         ));
831         return;
832     }
833
834     QString target = parms.at(0);
835     QByteArray key = network()->cipherKey(target);
836
837     if (key.isEmpty()) {
838         emit displayMsg(NetworkInternalMessage(
839             Message::Info,
840             typeByTarget(bufname),
841             bufname,
842             tr("No key has been set for %1.").arg(target)
843         ));
844         return;
845     }
846
847     emit displayMsg(NetworkInternalMessage(
848         Message::Info,
849         typeByTarget(bufname),
850         bufname,
851         tr("The key for %1 is %2:%3").arg(target, network()->cipherUsesCBC(target) ? "CBC" : "ECB", QString(key))
852     ));
853
854 #else
855     Q_UNUSED(msg)
856     emit displayMsg(NetworkInternalMessage(
857         Message::Error,
858         typeByTarget(bufname),
859         bufname,
860         tr("Error: Setting an encryption key requires Quassel to have been built "
861            "with support for the Qt Cryptographic Architecture (QCA2) library. "
862            "Contact your distributor about a Quassel package with QCA2 "
863            "support, or rebuild Quassel with QCA2 present.")
864     ));
865 #endif
866 }
867
868 void CoreUserInputHandler::handleTopic(const BufferInfo& bufferInfo, const QString& msg)
869 {
870     if (bufferInfo.bufferName().isEmpty() || !bufferInfo.acceptsRegularMessages())
871         return;
872
873     QList<QByteArray> params;
874     params << serverEncode(bufferInfo.bufferName());
875
876     if (!msg.isEmpty()) {
877 #ifdef HAVE_QCA2
878         params << encrypt(bufferInfo.bufferName(), channelEncode(bufferInfo.bufferName(), msg));
879 #else
880         params << channelEncode(bufferInfo.bufferName(), msg);
881 #endif
882     }
883
884     emit putCmd("TOPIC", params);
885 }
886
887 void CoreUserInputHandler::handleVoice(const BufferInfo& bufferInfo, const QString& msg)
888 {
889     QStringList nicks = msg.split(' ', QString::SkipEmptyParts);
890     QString m = "+";
891     for (int i = 0; i < nicks.count(); i++)
892         m += 'v';
893     QStringList params;
894     params << bufferInfo.bufferName() << m << nicks;
895     emit putCmd("MODE", serverEncode(params));
896 }
897
898 void CoreUserInputHandler::handleWait(const BufferInfo& bufferInfo, const QString& msg)
899 {
900     int splitPos = msg.indexOf(';');
901     if (splitPos <= 0)
902         return;
903
904     bool ok;
905     int delay = msg.left(splitPos).trimmed().toInt(&ok);
906     if (!ok)
907         return;
908
909     delay *= 1000;
910
911     QString command = msg.mid(splitPos + 1).trimmed();
912     if (command.isEmpty())
913         return;
914
915     _delayedCommands[startTimer(delay)] = Command(bufferInfo, command);
916 }
917
918 void CoreUserInputHandler::handleWho(const BufferInfo& bufferInfo, const QString& msg)
919 {
920     Q_UNUSED(bufferInfo)
921     emit putCmd("WHO", serverEncode(msg.split(' ')));
922 }
923
924 void CoreUserInputHandler::handleWhois(const BufferInfo& bufferInfo, const QString& msg)
925 {
926     Q_UNUSED(bufferInfo)
927     emit putCmd("WHOIS", serverEncode(msg.split(' ')));
928 }
929
930 void CoreUserInputHandler::handleWhowas(const BufferInfo& bufferInfo, const QString& msg)
931 {
932     Q_UNUSED(bufferInfo)
933     emit putCmd("WHOWAS", serverEncode(msg.split(' ')));
934 }
935
936 void CoreUserInputHandler::defaultHandler(QString cmd, const BufferInfo& bufferInfo, const QString& msg)
937 {
938     Q_UNUSED(bufferInfo);
939     emit putCmd(serverEncode(cmd.toUpper()), serverEncode(msg.split(" ")));
940 }
941
942 void CoreUserInputHandler::putPrivmsg(const QString& target,
943                                       const QString& message,
944                                       std::function<QByteArray(const QString&, const QString&)> encodeFunc,
945                                       Cipher* cipher)
946 {
947     Q_UNUSED(cipher);
948     QString cmd("PRIVMSG");
949     QByteArray targetEnc = serverEncode(target);
950
951     std::function<QList<QByteArray>(QString&)> cmdGenerator = [&](QString& splitMsg) -> QList<QByteArray> {
952         QByteArray splitMsgEnc = encodeFunc(target, splitMsg);
953
954 #ifdef HAVE_QCA2
955         if (cipher && !cipher->key().isEmpty() && !splitMsg.isEmpty()) {
956             cipher->encrypt(splitMsgEnc);
957         }
958 #endif
959         return QList<QByteArray>() << targetEnc << splitMsgEnc;
960     };
961
962     putCmd(cmd, network()->splitMessage(cmd, message, cmdGenerator));
963 }
964
965 // returns 0 if the message will not be chopped by the irc server or number of chopped bytes if message is too long
966 int CoreUserInputHandler::lastParamOverrun(const QString& cmd, const QList<QByteArray>& params)
967 {
968     // the server will pass our message truncated to 512 bytes including CRLF with the following format:
969     // ":prefix COMMAND param0 param1 :lastparam"
970     // where prefix = "nickname!user@host"
971     // that means that the last message can be as long as:
972     // 512 - nicklen - userlen - hostlen - commandlen - sum(param[0]..param[n-1])) - 2 (for CRLF) - 4 (":!@" + 1space between prefix and
973     // command) - max(paramcount - 1, 0) (space for simple params) - 2 (space and colon for last param)
974     IrcUser* me = network()->me();
975     int maxLen = 480 - cmd.toLatin1().count();  // educated guess in case we don't know us (yet?)
976
977     if (me)
978         maxLen = 512 - serverEncode(me->nick()).count() - serverEncode(me->user()).count() - serverEncode(me->host()).count()
979                  - cmd.toLatin1().count() - 6;
980
981     if (!params.isEmpty()) {
982         for (int i = 0; i < params.count() - 1; i++) {
983             maxLen -= (params[i].count() + 1);
984         }
985         maxLen -= 2;  // " :" last param separator;
986
987         if (params.last().count() > maxLen) {
988             return params.last().count() - maxLen;
989         }
990         else {
991             return 0;
992         }
993     }
994     else {
995         return 0;
996     }
997 }
998
999 #ifdef HAVE_QCA2
1000 QByteArray CoreUserInputHandler::encrypt(const QString& target, const QByteArray& message_, bool* didEncrypt) const
1001 {
1002     if (didEncrypt)
1003         *didEncrypt = false;
1004
1005     if (message_.isEmpty())
1006         return message_;
1007
1008     if (!Cipher::neededFeaturesAvailable())
1009         return message_;
1010
1011     Cipher* cipher = network()->cipher(target);
1012     if (!cipher || cipher->key().isEmpty())
1013         return message_;
1014
1015     QByteArray message = message_;
1016     bool result = cipher->encrypt(message);
1017     if (didEncrypt)
1018         *didEncrypt = result;
1019
1020     return message;
1021 }
1022
1023 #endif
1024
1025 void CoreUserInputHandler::timerEvent(QTimerEvent* event)
1026 {
1027     if (!_delayedCommands.contains(event->timerId())) {
1028         QObject::timerEvent(event);
1029         return;
1030     }
1031     BufferInfo bufferInfo = _delayedCommands[event->timerId()].bufferInfo;
1032     QString rawCommand = _delayedCommands[event->timerId()].command;
1033     _delayedCommands.remove(event->timerId());
1034     event->accept();
1035
1036     // the stored command might be the result of an alias expansion, so we need to split it up again
1037     QStringList commands = rawCommand.split(QRegExp("; ?"));
1038     for (const QString& command : commands) {
1039         handleUserInput(bufferInfo, command);
1040     }
1041 }