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