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