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