Implement sender prefix storage in the database
[quassel.git] / src / core / coreuserinputhandler.cpp
1 /***************************************************************************
2  *   Copyright (C) 2005-2016 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, ignoring any carriage returns
464         message = message.trimmed();
465         coreNetwork()->coreSession()->ctcpParser()->query(coreNetwork(), bufferInfo.bufferName(),
466                                                           "ACTION", message);
467         emit displayMsg(Message::Action, bufferInfo.type(), bufferInfo.bufferName(), message,
468                         network()->myNick(), Message::Self);
469     }
470 }
471
472
473 void CoreUserInputHandler::handleMode(const BufferInfo &bufferInfo, const QString &msg)
474 {
475     Q_UNUSED(bufferInfo)
476
477     QStringList params = msg.split(' ', QString::SkipEmptyParts);
478     // 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
479     if (!params.isEmpty()) {
480         if (!network()->isChannelName(params[0]) && !network()->isMyNick(params[0]))
481             params.prepend(bufferInfo.bufferName());
482         if (network()->isMyNick(params[0]) && params.count() == 2)
483             network()->updateIssuedModes(params[1]);
484         if (params[0] == "-reset" && params.count() == 1) {
485             // FIXME: give feedback to the user (I don't want to add new strings right now)
486             network()->resetPersistentModes();
487             return;
488         }
489     }
490
491     // TODO handle correct encoding for buffer modes (channelEncode())
492     emit putCmd("MODE", serverEncode(params));
493 }
494
495
496 // TODO: show privmsgs
497 void CoreUserInputHandler::handleMsg(const BufferInfo &bufferInfo, const QString &msg)
498 {
499     Q_UNUSED(bufferInfo);
500     if (!msg.contains(' '))
501         return;
502
503     QString target = msg.section(' ', 0, 0);
504     QString msgSection = msg.section(' ', 1);
505
506     std::function<QByteArray(const QString &, const QString &)> encodeFunc = [this] (const QString &target, const QString &message) -> QByteArray {
507         return userEncode(target, message);
508     };
509
510 #ifdef HAVE_QCA2
511     putPrivmsg(target, msgSection, encodeFunc, network()->cipher(target));
512 #else
513     putPrivmsg(target, msgSection, encodeFunc);
514 #endif
515 }
516
517
518 void CoreUserInputHandler::handleNick(const BufferInfo &bufferInfo, const QString &msg)
519 {
520     Q_UNUSED(bufferInfo)
521     QString nick = msg.section(' ', 0, 0);
522     emit putCmd("NICK", serverEncode(nick));
523 }
524
525
526 void CoreUserInputHandler::handleNotice(const BufferInfo &bufferInfo, const QString &msg)
527 {
528     QString bufferName = msg.section(' ', 0, 0);
529     QList<QByteArray> params;
530     // Split apart messages at line feeds.  The IRC protocol uses those to separate commands, so
531     // they need to be split into multiple messages.
532     QStringList messages = msg.section(' ', 1).split(QCharLF);
533
534     foreach (auto message, messages) {
535         // Handle each separated message independently, ignoring any carriage returns
536         message = message.trimmed();
537         params.clear();
538         params << serverEncode(bufferName) << channelEncode(bufferInfo.bufferName(), message);
539         emit putCmd("NOTICE", params);
540         emit displayMsg(Message::Notice, typeByTarget(bufferName), bufferName, message,
541                         network()->myNick(), Message::Self);
542     }
543 }
544
545
546
547 void CoreUserInputHandler::handleOper(const BufferInfo &bufferInfo, const QString &msg)
548 {
549     Q_UNUSED(bufferInfo)
550     emit putRawLine(serverEncode(QString("OPER %1").arg(msg)));
551 }
552
553
554 void CoreUserInputHandler::handlePart(const BufferInfo &bufferInfo, const QString &msg)
555 {
556     QList<QByteArray> params;
557     QString partReason;
558
559     // msg might contain either a channel name and/or a reaon, so we have to check if the first word is a known channel
560     QString channelName = msg.section(' ', 0, 0);
561     if (channelName.isEmpty() || !network()->ircChannel(channelName)) {
562         channelName = bufferInfo.bufferName();
563         partReason = msg;
564     }
565     else {
566         partReason = msg.mid(channelName.length() + 1);
567     }
568
569     if (partReason.isEmpty())
570         partReason = network()->identityPtr()->partReason();
571
572     params << serverEncode(channelName) << channelEncode(bufferInfo.bufferName(), partReason);
573     emit putCmd("PART", params);
574 }
575
576
577 void CoreUserInputHandler::handlePing(const BufferInfo &bufferInfo, const QString &msg)
578 {
579     Q_UNUSED(bufferInfo)
580
581     QString param = msg;
582     if (param.isEmpty())
583         param = QTime::currentTime().toString("hh:mm:ss.zzz");
584
585     // Take priority so this won't get stuck behind other queued messages.
586     putCmd("PING", serverEncode(param), QByteArray(), true);
587 }
588
589
590 void CoreUserInputHandler::handlePrint(const BufferInfo &bufferInfo, const QString &msg)
591 {
592     if (bufferInfo.bufferName().isEmpty() || !bufferInfo.acceptsRegularMessages())
593         return;  // server buffer
594
595     QByteArray encMsg = channelEncode(bufferInfo.bufferName(), msg);
596     emit displayMsg(Message::Info, bufferInfo.type(), bufferInfo.bufferName(), msg, network()->myNick(), Message::Self);
597 }
598
599
600 // TODO: implement queries
601 void CoreUserInputHandler::handleQuery(const BufferInfo &bufferInfo, const QString &msg)
602 {
603     Q_UNUSED(bufferInfo)
604     QString target = msg.section(' ', 0, 0);
605     // Split apart messages at line feeds.  The IRC protocol uses those to separate commands, so
606     // they need to be split into multiple messages.
607     QStringList messages = msg.section(' ', 1).split(QCharLF);
608
609     foreach (auto message, messages) {
610         // Handle each separated message independently, ignoring any carriage returns
611         message = message.trimmed();
612         if (message.isEmpty()) {
613             emit displayMsg(Message::Server, BufferInfo::QueryBuffer, target,
614                             tr("Starting query with %1").arg(target), network()->myNick(),
615                             Message::Self);
616             // handleMsg is a no-op if message is empty
617         } else {
618             emit displayMsg(Message::Plain, BufferInfo::QueryBuffer, target, message,
619                             network()->myNick(), Message::Self);
620             // handleMsg needs the target specified at the beginning of the message
621             handleMsg(bufferInfo, target + " " + message);
622         }
623     }
624 }
625
626
627 void CoreUserInputHandler::handleQuit(const BufferInfo &bufferInfo, const QString &msg)
628 {
629     Q_UNUSED(bufferInfo)
630     network()->disconnectFromIrc(true, msg);
631 }
632
633
634 void CoreUserInputHandler::issueQuit(const QString &reason, bool forceImmediate)
635 {
636     // If needing an immediate QUIT (e.g. core shutdown), prepend this to the queue
637     emit putCmd("QUIT", serverEncode(reason), QByteArray(), forceImmediate);
638 }
639
640
641 void CoreUserInputHandler::handleQuote(const BufferInfo &bufferInfo, const QString &msg)
642 {
643     Q_UNUSED(bufferInfo)
644     emit putRawLine(serverEncode(msg));
645 }
646
647
648 void CoreUserInputHandler::handleSay(const BufferInfo &bufferInfo, const QString &msg)
649 {
650     if (bufferInfo.bufferName().isEmpty() || !bufferInfo.acceptsRegularMessages())
651         return;  // server buffer
652
653     std::function<QByteArray(const QString &, const QString &)> encodeFunc = [this] (const QString &target, const QString &message) -> QByteArray {
654         return channelEncode(target, message);
655     };
656
657     // Split apart messages at line feeds.  The IRC protocol uses those to separate commands, so
658     // they need to be split into multiple messages.
659     QStringList messages = msg.split(QCharLF);
660
661     foreach (auto message, messages) {
662         // Handle each separated message independently, ignoring any carriage returns
663         message = message.trimmed();
664 #ifdef HAVE_QCA2
665         putPrivmsg(bufferInfo.bufferName(), message, encodeFunc,
666                    network()->cipher(bufferInfo.bufferName()));
667 #else
668         putPrivmsg(bufferInfo.bufferName(), message, encodeFunc);
669 #endif
670         emit displayMsg(Message::Plain, bufferInfo.type(), bufferInfo.bufferName(), message,
671                         network()->myNick(), Message::Self);
672     }
673 }
674
675
676 void CoreUserInputHandler::handleSetkey(const BufferInfo &bufferInfo, const QString &msg)
677 {
678     QString bufname = bufferInfo.bufferName().isNull() ? "" : bufferInfo.bufferName();
679 #ifdef HAVE_QCA2
680     if (!bufferInfo.isValid())
681         return;
682
683     if (!Cipher::neededFeaturesAvailable()) {
684         emit displayMsg(Message::Error, typeByTarget(bufname), bufname, tr("Error: QCA provider plugin not found. It is usually provided by the qca-ossl plugin."));
685         return;
686     }
687
688     QStringList parms = msg.split(' ', QString::SkipEmptyParts);
689
690     if (parms.count() == 1 && !bufferInfo.bufferName().isEmpty() && bufferInfo.acceptsRegularMessages())
691         parms.prepend(bufferInfo.bufferName());
692     else if (parms.count() != 2) {
693         emit displayMsg(Message::Info, typeByTarget(bufname), bufname,
694             tr("[usage] /setkey <nick|channel> <key> sets the encryption key for nick or channel. "
695                "/setkey <key> when in a channel or query buffer sets the key for it."));
696         return;
697     }
698
699     QString target = parms.at(0);
700     QByteArray key = parms.at(1).toLocal8Bit();
701     network()->setCipherKey(target, key);
702
703     emit displayMsg(Message::Info, typeByTarget(bufname), bufname, tr("The key for %1 has been set.").arg(target));
704 #else
705     Q_UNUSED(msg)
706     emit displayMsg(Message::Error, typeByTarget(bufname), bufname, tr("Error: Setting an encryption key requires Quassel to have been built "
707                                                                 "with support for the Qt Cryptographic Architecture (QCA) library. "
708                                                                 "Contact your distributor about a Quassel package with QCA "
709                                                                 "support, or rebuild Quassel with QCA present."));
710 #endif
711 }
712
713
714 void CoreUserInputHandler::handleShowkey(const BufferInfo &bufferInfo, const QString &msg)
715 {
716     QString bufname = bufferInfo.bufferName().isNull() ? "" : bufferInfo.bufferName();
717 #ifdef HAVE_QCA2
718     if (!bufferInfo.isValid())
719         return;
720
721     if (!Cipher::neededFeaturesAvailable()) {
722         emit displayMsg(Message::Error, typeByTarget(bufname), bufname, tr("Error: QCA provider plugin not found. It is usually provided by the qca-ossl plugin."));
723         return;
724     }
725
726     QStringList parms = msg.split(' ', QString::SkipEmptyParts);
727
728     if (parms.isEmpty() && !bufferInfo.bufferName().isEmpty() && bufferInfo.acceptsRegularMessages())
729         parms.prepend(bufferInfo.bufferName());
730
731     if (parms.isEmpty()) {
732         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."));
733         return;
734     }
735
736     QString target = parms.at(0);
737     QByteArray key = network()->cipherKey(target);
738
739     if (key.isEmpty()) {
740         emit displayMsg(Message::Info, typeByTarget(bufname), bufname, tr("No key has been set for %1.").arg(target));
741         return;
742     }
743
744     emit displayMsg(Message::Info, typeByTarget(bufname), bufname, tr("The key for %1 is %2:%3").arg(target, network()->cipherUsesCBC(target) ? "CBC" : "ECB", QString(key)));
745
746 #else
747     Q_UNUSED(msg)
748     emit displayMsg(Message::Error, typeByTarget(bufname), bufname, tr("Error: Setting an encryption key requires Quassel to have been built "
749                                                                     "with support for the Qt Cryptographic Architecture (QCA2) library. "
750                                                                     "Contact your distributor about a Quassel package with QCA2 "
751                                                                     "support, or rebuild Quassel with QCA2 present."));
752 #endif
753 }
754
755
756 void CoreUserInputHandler::handleTopic(const BufferInfo &bufferInfo, const QString &msg)
757 {
758     if (bufferInfo.bufferName().isEmpty() || !bufferInfo.acceptsRegularMessages())
759         return;
760
761     QList<QByteArray> params;
762     params << serverEncode(bufferInfo.bufferName());
763
764     if (!msg.isEmpty()) {
765 #   ifdef HAVE_QCA2
766         params << encrypt(bufferInfo.bufferName(), channelEncode(bufferInfo.bufferName(), msg));
767 #   else
768         params << channelEncode(bufferInfo.bufferName(), msg);
769 #   endif
770     }
771
772     emit putCmd("TOPIC", params);
773 }
774
775
776 void CoreUserInputHandler::handleVoice(const BufferInfo &bufferInfo, const QString &msg)
777 {
778     QStringList nicks = msg.split(' ', QString::SkipEmptyParts);
779     QString m = "+"; for (int i = 0; i < nicks.count(); i++) m += 'v';
780     QStringList params;
781     params << bufferInfo.bufferName() << m << nicks;
782     emit putCmd("MODE", serverEncode(params));
783 }
784
785
786 void CoreUserInputHandler::handleWait(const BufferInfo &bufferInfo, const QString &msg)
787 {
788     int splitPos = msg.indexOf(';');
789     if (splitPos <= 0)
790         return;
791
792     bool ok;
793     int delay = msg.left(splitPos).trimmed().toInt(&ok);
794     if (!ok)
795         return;
796
797     delay *= 1000;
798
799     QString command = msg.mid(splitPos + 1).trimmed();
800     if (command.isEmpty())
801         return;
802
803     _delayedCommands[startTimer(delay)] = Command(bufferInfo, command);
804 }
805
806
807 void CoreUserInputHandler::handleWho(const BufferInfo &bufferInfo, const QString &msg)
808 {
809     Q_UNUSED(bufferInfo)
810     emit putCmd("WHO", serverEncode(msg.split(' ')));
811 }
812
813
814 void CoreUserInputHandler::handleWhois(const BufferInfo &bufferInfo, const QString &msg)
815 {
816     Q_UNUSED(bufferInfo)
817     emit putCmd("WHOIS", serverEncode(msg.split(' ')));
818 }
819
820
821 void CoreUserInputHandler::handleWhowas(const BufferInfo &bufferInfo, const QString &msg)
822 {
823     Q_UNUSED(bufferInfo)
824     emit putCmd("WHOWAS", serverEncode(msg.split(' ')));
825 }
826
827
828 void CoreUserInputHandler::defaultHandler(QString cmd, const BufferInfo &bufferInfo, const QString &msg)
829 {
830     Q_UNUSED(bufferInfo);
831     emit putCmd(serverEncode(cmd.toUpper()), serverEncode(msg.split(" ")));
832 }
833
834
835 void CoreUserInputHandler::putPrivmsg(const QString &target, const QString &message, std::function<QByteArray(const QString &, const QString &)> encodeFunc, Cipher *cipher)
836 {
837     Q_UNUSED(cipher);
838     QString cmd("PRIVMSG");
839     QByteArray targetEnc = serverEncode(target);
840
841     std::function<QList<QByteArray>(QString &)> cmdGenerator = [&] (QString &splitMsg) -> QList<QByteArray> {
842         QByteArray splitMsgEnc = encodeFunc(target, splitMsg);
843
844 #ifdef HAVE_QCA2
845         if (cipher && !cipher->key().isEmpty() && !splitMsg.isEmpty()) {
846             cipher->encrypt(splitMsgEnc);
847         }
848 #endif
849         return QList<QByteArray>() << targetEnc << splitMsgEnc;
850     };
851
852     putCmd(cmd, network()->splitMessage(cmd, message, cmdGenerator));
853 }
854
855
856 // returns 0 if the message will not be chopped by the irc server or number of chopped bytes if message is too long
857 int CoreUserInputHandler::lastParamOverrun(const QString &cmd, const QList<QByteArray> &params)
858 {
859     // the server will pass our message truncated to 512 bytes including CRLF with the following format:
860     // ":prefix COMMAND param0 param1 :lastparam"
861     // where prefix = "nickname!user@host"
862     // that means that the last message can be as long as:
863     // 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)
864     IrcUser *me = network()->me();
865     int maxLen = 480 - cmd.toLatin1().count(); // educated guess in case we don't know us (yet?)
866
867     if (me)
868         maxLen = 512 - serverEncode(me->nick()).count() - serverEncode(me->user()).count() - serverEncode(me->host()).count() - cmd.toLatin1().count() - 6;
869
870     if (!params.isEmpty()) {
871         for (int i = 0; i < params.count() - 1; i++) {
872             maxLen -= (params[i].count() + 1);
873         }
874         maxLen -= 2; // " :" last param separator;
875
876         if (params.last().count() > maxLen) {
877             return params.last().count() - maxLen;
878         }
879         else {
880             return 0;
881         }
882     }
883     else {
884         return 0;
885     }
886 }
887
888
889 #ifdef HAVE_QCA2
890 QByteArray CoreUserInputHandler::encrypt(const QString &target, const QByteArray &message_, bool *didEncrypt) const
891 {
892     if (didEncrypt)
893         *didEncrypt = false;
894
895     if (message_.isEmpty())
896         return message_;
897
898     if (!Cipher::neededFeaturesAvailable())
899         return message_;
900
901     Cipher *cipher = network()->cipher(target);
902     if (!cipher || cipher->key().isEmpty())
903         return message_;
904
905     QByteArray message = message_;
906     bool result = cipher->encrypt(message);
907     if (didEncrypt)
908         *didEncrypt = result;
909
910     return message;
911 }
912
913
914 #endif
915
916 void CoreUserInputHandler::timerEvent(QTimerEvent *event)
917 {
918     if (!_delayedCommands.contains(event->timerId())) {
919         QObject::timerEvent(event);
920         return;
921     }
922     BufferInfo bufferInfo = _delayedCommands[event->timerId()].bufferInfo;
923     QString rawCommand = _delayedCommands[event->timerId()].command;
924     _delayedCommands.remove(event->timerId());
925     event->accept();
926
927     // the stored command might be the result of an alias expansion, so we need to split it up again
928     QStringList commands = rawCommand.split(QRegExp("; ?"));
929     foreach(QString command, commands) {
930         handleUserInput(bufferInfo, command);
931     }
932 }