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