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