Make sure that clients can't access buffers belonging to other users
[quassel.git] / src / core / coreuserinputhandler.cpp
1 /***************************************************************************
2  *   Copyright (C) 2005-2013 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         uint now = QDateTime::currentDateTime().toTime_t();
173         message = QString::number(now);
174     }
175
176     // FIXME make this a proper event
177     coreNetwork()->coreSession()->ctcpParser()->query(coreNetwork(), nick, ctcpTag, message);
178     emit displayMsg(Message::Action, BufferInfo::StatusBuffer, "", verboseMessage, network()->myNick());
179 }
180
181
182 void CoreUserInputHandler::handleDelkey(const BufferInfo &bufferInfo, const QString &msg)
183 {
184     QString bufname = bufferInfo.bufferName().isNull() ? "" : bufferInfo.bufferName();
185 #ifdef HAVE_QCA2
186     if (!bufferInfo.isValid())
187         return;
188
189     if (!Cipher::neededFeaturesAvailable()) {
190         emit displayMsg(Message::Error, typeByTarget(bufname), bufname, tr("Error: QCA provider plugin not found. It is usually provided by the qca-ossl plugin."));
191         return;
192     }
193
194     QStringList parms = msg.split(' ', QString::SkipEmptyParts);
195
196     if (parms.isEmpty() && !bufferInfo.bufferName().isEmpty() && bufferInfo.acceptsRegularMessages())
197         parms.prepend(bufferInfo.bufferName());
198
199     if (parms.isEmpty()) {
200         emit displayMsg(Message::Info, typeByTarget(bufname), bufname,
201             tr("[usage] /delkey <nick|channel> deletes the encryption key for nick or channel or just /delkey when in a channel or query."));
202         return;
203     }
204
205     QString target = parms.at(0);
206
207     if (network()->cipherKey(target).isEmpty()) {
208         emit displayMsg(Message::Info, typeByTarget(bufname), bufname, tr("No key has been set for %1.").arg(target));
209         return;
210     }
211
212     network()->setCipherKey(target, QByteArray());
213     emit displayMsg(Message::Info, typeByTarget(bufname), bufname, tr("The key for %1 has been deleted.").arg(target));
214
215 #else
216     Q_UNUSED(msg)
217     emit displayMsg(Message::Error, typeByTarget(bufname), bufname, tr("Error: Setting an encryption key requires Quassel to have been built "
218                                                                     "with support for the Qt Cryptographic Architecture (QCA2) library. "
219                                                                     "Contact your distributor about a Quassel package with QCA2 "
220                                                                     "support, or rebuild Quassel with QCA2 present."));
221 #endif
222 }
223
224 void CoreUserInputHandler::doMode(const BufferInfo &bufferInfo, const QChar& addOrRemove, const QChar& mode, const QString &nicks)
225 {
226     QString m;
227     bool isNumber;
228     int maxModes = network()->support("MODES").toInt(&isNumber);
229     if (!isNumber || maxModes == 0) maxModes = 1;
230
231     QStringList nickList;
232     if (nicks == "*") { // All users in channel
233         const QList<IrcUser*> users = network()->ircChannel(bufferInfo.bufferName())->ircUsers();
234         foreach(IrcUser *user, users) {
235             if ((addOrRemove == '+' && !network()->ircChannel(bufferInfo.bufferName())->userModes(user).contains(mode))
236                 || (addOrRemove == '-' && network()->ircChannel(bufferInfo.bufferName())->userModes(user).contains(mode)))
237                 nickList.append(user->nick());
238         }
239     } else {
240         nickList = nicks.split(' ', QString::SkipEmptyParts);
241     }
242
243     if (nickList.count() == 0) return;
244
245     while (!nickList.isEmpty()) {
246         int amount = qMin(nickList.count(), maxModes);
247         QString m = addOrRemove; for(int i = 0; i < amount; i++) m += mode;
248         QStringList params;
249         params << bufferInfo.bufferName() << m;
250         for(int i = 0; i < amount; i++) params << nickList.takeFirst();
251         emit putCmd("MODE", serverEncode(params));
252     }
253 }
254
255
256 void CoreUserInputHandler::handleDeop(const BufferInfo &bufferInfo, const QString &nicks)
257 {
258     doMode(bufferInfo, '-', 'o', nicks);
259 }
260
261
262 void CoreUserInputHandler::handleDehalfop(const BufferInfo &bufferInfo, const QString &nicks)
263 {
264     doMode(bufferInfo, '-', 'h', nicks);
265 }
266
267
268 void CoreUserInputHandler::handleDevoice(const BufferInfo &bufferInfo, const QString &nicks)
269 {
270     doMode(bufferInfo, '-', 'v', nicks);
271 }
272
273 void CoreUserInputHandler::handleHalfop(const BufferInfo &bufferInfo, const QString &nicks)
274 {
275     doMode(bufferInfo, '+', 'h', nicks);
276 }
277
278 void CoreUserInputHandler::handleOp(const BufferInfo &bufferInfo, const QString &nicks) {
279   doMode(bufferInfo, '+', 'o', nicks);
280 }
281
282
283 void CoreUserInputHandler::handleInvite(const BufferInfo &bufferInfo, const QString &msg)
284 {
285     QStringList params;
286     params << msg << bufferInfo.bufferName();
287     emit putCmd("INVITE", serverEncode(params));
288 }
289
290
291 void CoreUserInputHandler::handleJoin(const BufferInfo &bufferInfo, const QString &msg)
292 {
293     Q_UNUSED(bufferInfo);
294
295     // trim spaces before chans or keys
296     QString sane_msg = msg;
297     sane_msg.replace(QRegExp(", +"), ",");
298     QStringList params = sane_msg.trimmed().split(" ");
299
300     QStringList chans = params[0].split(",", QString::SkipEmptyParts);
301     QStringList keys;
302     if (params.count() > 1)
303         keys = params[1].split(",");
304
305     int i;
306     for (i = 0; i < chans.count(); i++) {
307         if (!network()->isChannelName(chans[i]))
308             chans[i].prepend('#');
309
310         if (i < keys.count()) {
311             network()->addChannelKey(chans[i], keys[i]);
312         }
313         else {
314             network()->removeChannelKey(chans[i]);
315         }
316     }
317
318     static const char *cmd = "JOIN";
319     i = 0;
320     QStringList joinChans, joinKeys;
321     int slicesize = chans.count();
322     QList<QByteArray> encodedParams;
323
324     // go through all to-be-joined channels and (re)build the join list
325     while (i < chans.count()) {
326         joinChans.append(chans.at(i));
327         if (i < keys.count())
328             joinKeys.append(keys.at(i));
329
330         // if the channel list we built so far either contains all requested channels or exceeds
331         // the desired amount of channels in this slice, try to send what we have so far
332         if (++i == chans.count() || joinChans.count() >= slicesize) {
333             params.clear();
334             params.append(joinChans.join(","));
335             params.append(joinKeys.join(","));
336             encodedParams = serverEncode(params);
337             // check if it fits in one command
338             if (lastParamOverrun(cmd, encodedParams) == 0) {
339                 emit putCmd(cmd, encodedParams);
340             }
341             else if (slicesize > 1) {
342                 // back to start of slice, try again with half the amount of channels
343                 i -= slicesize;
344                 slicesize /= 2;
345             }
346             joinChans.clear();
347             joinKeys.clear();
348         }
349     }
350 }
351
352
353 void CoreUserInputHandler::handleKeyx(const BufferInfo &bufferInfo, const QString &msg)
354 {
355     QString bufname = bufferInfo.bufferName().isNull() ? "" : bufferInfo.bufferName();
356 #ifdef HAVE_QCA2
357     if (!bufferInfo.isValid())
358         return;
359
360     if (!Cipher::neededFeaturesAvailable()) {
361         emit displayMsg(Message::Error, typeByTarget(bufname), bufname, tr("Error: QCA provider plugin not found. It is usually provided by the qca-ossl plugin."));
362         return;
363     }
364
365     QStringList parms = msg.split(' ', QString::SkipEmptyParts);
366
367     if (parms.count() == 0 && !bufferInfo.bufferName().isEmpty() && bufferInfo.acceptsRegularMessages())
368         parms.prepend(bufferInfo.bufferName());
369     else if (parms.count() != 1) {
370         emit displayMsg(Message::Info, typeByTarget(bufname), bufname,
371             tr("[usage] /keyx [<nick>] Initiates a DH1080 key exchange with the target."));
372         return;
373     }
374
375     QString target = parms.at(0);
376
377     if (network()->isChannelName(target)) {
378         emit displayMsg(Message::Info, typeByTarget(bufname), bufname, tr("It is only possible to exchange keys in a query buffer."));
379         return;
380     }
381
382     Cipher *cipher = network()->cipher(target);
383     if (!cipher) // happens when there is no CoreIrcChannel for the target
384         return;
385
386     QByteArray pubKey = cipher->initKeyExchange();
387     if (pubKey.isEmpty())
388         emit displayMsg(Message::Error, typeByTarget(bufname), bufname, tr("Failed to initiate key exchange with %1.").arg(target));
389     else {
390         QList<QByteArray> params;
391         params << serverEncode(target) << serverEncode("DH1080_INIT ") + pubKey;
392         emit putCmd("NOTICE", params);
393         emit displayMsg(Message::Info, typeByTarget(bufname), bufname, tr("Initiated key exchange with %1.").arg(target));
394     }
395 #else
396     Q_UNUSED(msg)
397     emit displayMsg(Message::Error, typeByTarget(bufname), bufname, tr("Error: Setting an encryption key requires Quassel to have been built "
398                                                                 "with support for the Qt Cryptographic Architecture (QCA) library. "
399                                                                 "Contact your distributor about a Quassel package with QCA "
400                                                                 "support, or rebuild Quassel with QCA present."));
401 #endif
402 }
403
404
405 void CoreUserInputHandler::handleKick(const BufferInfo &bufferInfo, const QString &msg)
406 {
407     QString nick = msg.section(' ', 0, 0, QString::SectionSkipEmpty);
408     QString reason = msg.section(' ', 1, -1, QString::SectionSkipEmpty).trimmed();
409     if (reason.isEmpty())
410         reason = network()->identityPtr()->kickReason();
411
412     QList<QByteArray> params;
413     params << serverEncode(bufferInfo.bufferName()) << serverEncode(nick) << channelEncode(bufferInfo.bufferName(), reason);
414     emit putCmd("KICK", params);
415 }
416
417
418 void CoreUserInputHandler::handleKill(const BufferInfo &bufferInfo, const QString &msg)
419 {
420     Q_UNUSED(bufferInfo)
421     QString nick = msg.section(' ', 0, 0, QString::SectionSkipEmpty);
422     QString pass = msg.section(' ', 1, -1, QString::SectionSkipEmpty);
423     QList<QByteArray> params;
424     params << serverEncode(nick) << serverEncode(pass);
425     emit putCmd("KILL", params);
426 }
427
428
429 void CoreUserInputHandler::handleList(const BufferInfo &bufferInfo, const QString &msg)
430 {
431     Q_UNUSED(bufferInfo)
432     emit putCmd("LIST", serverEncode(msg.split(' ', QString::SkipEmptyParts)));
433 }
434
435
436 void CoreUserInputHandler::handleMe(const BufferInfo &bufferInfo, const QString &msg)
437 {
438     if (bufferInfo.bufferName().isEmpty() || !bufferInfo.acceptsRegularMessages())
439         return;  // server buffer
440     // FIXME make this a proper event
441     coreNetwork()->coreSession()->ctcpParser()->query(coreNetwork(), bufferInfo.bufferName(), "ACTION", msg);
442     emit displayMsg(Message::Action, bufferInfo.type(), bufferInfo.bufferName(), msg, network()->myNick(), Message::Self);
443 }
444
445
446 void CoreUserInputHandler::handleMode(const BufferInfo &bufferInfo, const QString &msg)
447 {
448     Q_UNUSED(bufferInfo)
449
450     QStringList params = msg.split(' ', QString::SkipEmptyParts);
451     // 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
452     if (!params.isEmpty()) {
453         if (!network()->isChannelName(params[0]) && !network()->isMyNick(params[0]))
454             params.prepend(bufferInfo.bufferName());
455         if (network()->isMyNick(params[0]) && params.count() == 2)
456             network()->updateIssuedModes(params[1]);
457         if (params[0] == "-reset" && params.count() == 1) {
458             // FIXME: give feedback to the user (I don't want to add new strings right now)
459             network()->resetPersistentModes();
460             return;
461         }
462     }
463
464     // TODO handle correct encoding for buffer modes (channelEncode())
465     emit putCmd("MODE", serverEncode(params));
466 }
467
468
469 // TODO: show privmsgs
470 void CoreUserInputHandler::handleMsg(const BufferInfo &bufferInfo, const QString &msg)
471 {
472     Q_UNUSED(bufferInfo);
473     if (!msg.contains(' '))
474         return;
475
476     QString target = msg.section(' ', 0, 0);
477     QByteArray encMsg = userEncode(target, msg.section(' ', 1));
478
479 #ifdef HAVE_QCA2
480     putPrivmsg(serverEncode(target), encMsg, network()->cipher(target));
481 #else
482     putPrivmsg(serverEncode(target), encMsg);
483 #endif
484 }
485
486
487 void CoreUserInputHandler::handleNick(const BufferInfo &bufferInfo, const QString &msg)
488 {
489     Q_UNUSED(bufferInfo)
490     QString nick = msg.section(' ', 0, 0);
491     emit putCmd("NICK", serverEncode(nick));
492 }
493
494
495 void CoreUserInputHandler::handleNotice(const BufferInfo &bufferInfo, const QString &msg)
496 {
497     QString bufferName = msg.section(' ', 0, 0);
498     QString payload = msg.section(' ', 1);
499     QList<QByteArray> params;
500     params << serverEncode(bufferName) << channelEncode(bufferInfo.bufferName(), payload);
501     emit putCmd("NOTICE", params);
502     emit displayMsg(Message::Notice, typeByTarget(bufferName), bufferName, payload, network()->myNick(), Message::Self);
503 }
504
505
506
507 void CoreUserInputHandler::handleOper(const BufferInfo &bufferInfo, const QString &msg)
508 {
509     Q_UNUSED(bufferInfo)
510     emit putRawLine(serverEncode(QString("OPER %1").arg(msg)));
511 }
512
513
514 void CoreUserInputHandler::handlePart(const BufferInfo &bufferInfo, const QString &msg)
515 {
516     QList<QByteArray> params;
517     QString partReason;
518
519     // msg might contain either a channel name and/or a reaon, so we have to check if the first word is a known channel
520     QString channelName = msg.section(' ', 0, 0);
521     if (channelName.isEmpty() || !network()->ircChannel(channelName)) {
522         channelName = bufferInfo.bufferName();
523         partReason = msg;
524     }
525     else {
526         partReason = msg.mid(channelName.length() + 1);
527     }
528
529     if (partReason.isEmpty())
530         partReason = network()->identityPtr()->partReason();
531
532     params << serverEncode(channelName) << channelEncode(bufferInfo.bufferName(), partReason);
533     emit putCmd("PART", params);
534 }
535
536
537 void CoreUserInputHandler::handlePing(const BufferInfo &bufferInfo, const QString &msg)
538 {
539     Q_UNUSED(bufferInfo)
540
541     QString param = msg;
542     if (param.isEmpty())
543         param = QTime::currentTime().toString("hh:mm:ss.zzz");
544
545     putCmd("PING", serverEncode(param));
546 }
547
548
549 // TODO: implement queries
550 void CoreUserInputHandler::handleQuery(const BufferInfo &bufferInfo, const QString &msg)
551 {
552     Q_UNUSED(bufferInfo)
553     QString target = msg.section(' ', 0, 0);
554     QString message = msg.section(' ', 1);
555     if (message.isEmpty())
556         emit displayMsg(Message::Server, BufferInfo::QueryBuffer, target, tr("Starting query with %1").arg(target), network()->myNick(), Message::Self);
557     else
558         emit displayMsg(Message::Plain, BufferInfo::QueryBuffer, target, message, network()->myNick(), Message::Self);
559     handleMsg(bufferInfo, msg);
560 }
561
562
563 void CoreUserInputHandler::handleQuit(const BufferInfo &bufferInfo, const QString &msg)
564 {
565     Q_UNUSED(bufferInfo)
566     network()->disconnectFromIrc(true, msg);
567 }
568
569
570 void CoreUserInputHandler::issueQuit(const QString &reason)
571 {
572     emit putCmd("QUIT", serverEncode(reason));
573 }
574
575
576 void CoreUserInputHandler::handleQuote(const BufferInfo &bufferInfo, const QString &msg)
577 {
578     Q_UNUSED(bufferInfo)
579     emit putRawLine(serverEncode(msg));
580 }
581
582
583 void CoreUserInputHandler::handleSay(const BufferInfo &bufferInfo, const QString &msg)
584 {
585     if (bufferInfo.bufferName().isEmpty() || !bufferInfo.acceptsRegularMessages())
586         return;  // server buffer
587
588     QByteArray encMsg = channelEncode(bufferInfo.bufferName(), msg);
589 #ifdef HAVE_QCA2
590     putPrivmsg(serverEncode(bufferInfo.bufferName()), encMsg, network()->cipher(bufferInfo.bufferName()));
591 #else
592     putPrivmsg(serverEncode(bufferInfo.bufferName()), encMsg);
593 #endif
594     emit displayMsg(Message::Plain, bufferInfo.type(), bufferInfo.bufferName(), msg, network()->myNick(), Message::Self);
595 }
596
597
598 void CoreUserInputHandler::handleSetkey(const BufferInfo &bufferInfo, const QString &msg)
599 {
600     QString bufname = bufferInfo.bufferName().isNull() ? "" : bufferInfo.bufferName();
601 #ifdef HAVE_QCA2
602     if (!bufferInfo.isValid())
603         return;
604
605     if (!Cipher::neededFeaturesAvailable()) {
606         emit displayMsg(Message::Error, typeByTarget(bufname), bufname, tr("Error: QCA provider plugin not found. It is usually provided by the qca-ossl plugin."));
607         return;
608     }
609
610     QStringList parms = msg.split(' ', QString::SkipEmptyParts);
611
612     if (parms.count() == 1 && !bufferInfo.bufferName().isEmpty() && bufferInfo.acceptsRegularMessages())
613         parms.prepend(bufferInfo.bufferName());
614     else if (parms.count() != 2) {
615         emit displayMsg(Message::Info, typeByTarget(bufname), bufname,
616             tr("[usage] /setkey <nick|channel> <key> sets the encryption key for nick or channel. "
617                "/setkey <key> when in a channel or query buffer sets the key for it."));
618         return;
619     }
620
621     QString target = parms.at(0);
622     QByteArray key = parms.at(1).toLocal8Bit();
623     network()->setCipherKey(target, key);
624
625     emit displayMsg(Message::Info, typeByTarget(bufname), bufname, tr("The key for %1 has been set.").arg(target));
626 #else
627     Q_UNUSED(msg)
628     emit displayMsg(Message::Error, typeByTarget(bufname), bufname, tr("Error: Setting an encryption key requires Quassel to have been built "
629                                                                 "with support for the Qt Cryptographic Architecture (QCA) library. "
630                                                                 "Contact your distributor about a Quassel package with QCA "
631                                                                 "support, or rebuild Quassel with QCA present."));
632 #endif
633 }
634
635
636 void CoreUserInputHandler::handleShowkey(const BufferInfo &bufferInfo, const QString &msg)
637 {
638     QString bufname = bufferInfo.bufferName().isNull() ? "" : bufferInfo.bufferName();
639 #ifdef HAVE_QCA2
640     if (!bufferInfo.isValid())
641         return;
642
643     if (!Cipher::neededFeaturesAvailable()) {
644         emit displayMsg(Message::Error, typeByTarget(bufname), bufname, tr("Error: QCA provider plugin not found. It is usually provided by the qca-ossl plugin."));
645         return;
646     }
647
648     QStringList parms = msg.split(' ', QString::SkipEmptyParts);
649
650     if (parms.isEmpty() && !bufferInfo.bufferName().isEmpty() && bufferInfo.acceptsRegularMessages())
651         parms.prepend(bufferInfo.bufferName());
652
653     if (parms.isEmpty()) {
654         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."));
655         return;
656     }
657
658     QString target = parms.at(0);
659     QByteArray key = network()->cipherKey(target);
660
661     if (key.isEmpty()) {
662         emit displayMsg(Message::Info, typeByTarget(bufname), bufname, tr("No key has been set for %1.").arg(target));
663         return;
664     }
665
666     emit displayMsg(Message::Info, typeByTarget(bufname), bufname, tr("The key for %1 is %2:%3").arg(target, network()->cipherUsesCBC(target) ? "CBC" : "ECB", QString(key)));
667
668 #else
669     Q_UNUSED(msg)
670     emit displayMsg(Message::Error, typeByTarget(bufname), bufname, tr("Error: Setting an encryption key requires Quassel to have been built "
671                                                                     "with support for the Qt Cryptographic Architecture (QCA2) library. "
672                                                                     "Contact your distributor about a Quassel package with QCA2 "
673                                                                     "support, or rebuild Quassel with QCA2 present."));
674 #endif
675 }
676
677
678 void CoreUserInputHandler::handleTopic(const BufferInfo &bufferInfo, const QString &msg)
679 {
680     if (bufferInfo.bufferName().isEmpty() || !bufferInfo.acceptsRegularMessages())
681         return;
682
683     QList<QByteArray> params;
684     params << serverEncode(bufferInfo.bufferName());
685
686     if (!msg.isEmpty()) {
687 #   ifdef HAVE_QCA2
688         params << encrypt(bufferInfo.bufferName(), channelEncode(bufferInfo.bufferName(), msg));
689 #   else
690         params << channelEncode(bufferInfo.bufferName(), msg);
691 #   endif
692     }
693
694     emit putCmd("TOPIC", params);
695 }
696
697
698 void CoreUserInputHandler::handleVoice(const BufferInfo &bufferInfo, const QString &msg)
699 {
700     QStringList nicks = msg.split(' ', QString::SkipEmptyParts);
701     QString m = "+"; for (int i = 0; i < nicks.count(); i++) m += 'v';
702     QStringList params;
703     params << bufferInfo.bufferName() << m << nicks;
704     emit putCmd("MODE", serverEncode(params));
705 }
706
707
708 void CoreUserInputHandler::handleWait(const BufferInfo &bufferInfo, const QString &msg)
709 {
710     int splitPos = msg.indexOf(';');
711     if (splitPos <= 0)
712         return;
713
714     bool ok;
715     int delay = msg.left(splitPos).trimmed().toInt(&ok);
716     if (!ok)
717         return;
718
719     delay *= 1000;
720
721     QString command = msg.mid(splitPos + 1).trimmed();
722     if (command.isEmpty())
723         return;
724
725     _delayedCommands[startTimer(delay)] = Command(bufferInfo, command);
726 }
727
728
729 void CoreUserInputHandler::handleWho(const BufferInfo &bufferInfo, const QString &msg)
730 {
731     Q_UNUSED(bufferInfo)
732     emit putCmd("WHO", serverEncode(msg.split(' ')));
733 }
734
735
736 void CoreUserInputHandler::handleWhois(const BufferInfo &bufferInfo, const QString &msg)
737 {
738     Q_UNUSED(bufferInfo)
739     emit putCmd("WHOIS", serverEncode(msg.split(' ')));
740 }
741
742
743 void CoreUserInputHandler::handleWhowas(const BufferInfo &bufferInfo, const QString &msg)
744 {
745     Q_UNUSED(bufferInfo)
746     emit putCmd("WHOWAS", serverEncode(msg.split(' ')));
747 }
748
749
750 void CoreUserInputHandler::defaultHandler(QString cmd, const BufferInfo &bufferInfo, const QString &msg)
751 {
752     Q_UNUSED(bufferInfo);
753     emit putCmd(serverEncode(cmd.toUpper()), serverEncode(msg.split(" ")));
754 }
755
756
757 void CoreUserInputHandler::putPrivmsg(const QByteArray &target, const QByteArray &message, Cipher *cipher)
758 {
759     // Encrypted messages need special care. There's no clear relation between cleartext and encrypted message length,
760     // so we can't just compute the maxSplitPos. Instead, we need to loop through the splitpoints until the crypted
761     // version is short enough...
762     // TODO: check out how the various possible encryption methods behave length-wise and make
763     //       this clean by predicting the length of the crypted msg.
764     //       For example, blowfish-ebc seems to create 8-char chunks.
765
766     static const char *cmd = "PRIVMSG";
767     static const char *splitter = " .,-";
768
769     int maxSplitPos = message.count();
770     int splitPos = maxSplitPos;
771     forever {
772         QByteArray crypted = message.left(splitPos);
773         bool isEncrypted = false;
774 #ifdef HAVE_QCA2
775         if (cipher && !cipher->key().isEmpty() && !message.isEmpty()) {
776             isEncrypted = cipher->encrypt(crypted);
777         }
778 #endif
779         int overrun = lastParamOverrun(cmd, QList<QByteArray>() << target << crypted);
780         if (overrun) {
781             // In case this is not an encrypted msg, we can just cut off at the end
782             if (!isEncrypted)
783                 maxSplitPos = message.count() - overrun;
784
785             splitPos = -1;
786             for (const char *splitChar = splitter; *splitChar != 0; splitChar++) {
787                 splitPos = qMax(splitPos, message.lastIndexOf(*splitChar, maxSplitPos) + 1); // keep split char on old line
788             }
789             if (splitPos <= 0 || splitPos > maxSplitPos)
790                 splitPos = maxSplitPos;
791
792             maxSplitPos = splitPos - 1;
793             if (maxSplitPos <= 0) { // this should never happen, but who knows...
794                 qWarning() << tr("[Error] Could not encrypt your message: %1").arg(message.data());
795                 return;
796             }
797             continue; // we never come back here for !encrypted!
798         }
799
800         // now we have found a valid splitpos (or didn't need to split to begin with)
801         putCmd(cmd, QList<QByteArray>() << target << crypted);
802         if (splitPos < message.count())
803             putPrivmsg(target, message.mid(splitPos), cipher);
804
805         return;
806     }
807 }
808
809
810 // returns 0 if the message will not be chopped by the irc server or number of chopped bytes if message is too long
811 int CoreUserInputHandler::lastParamOverrun(const QString &cmd, const QList<QByteArray> &params)
812 {
813     // the server will pass our message truncated to 512 bytes including CRLF with the following format:
814     // ":prefix COMMAND param0 param1 :lastparam"
815     // where prefix = "nickname!user@host"
816     // that means that the last message can be as long as:
817     // 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)
818     IrcUser *me = network()->me();
819     int maxLen = 480 - cmd.toAscii().count(); // educated guess in case we don't know us (yet?)
820
821     if (me)
822         maxLen = 512 - serverEncode(me->nick()).count() - serverEncode(me->user()).count() - serverEncode(me->host()).count() - cmd.toAscii().count() - 6;
823
824     if (!params.isEmpty()) {
825         for (int i = 0; i < params.count() - 1; i++) {
826             maxLen -= (params[i].count() + 1);
827         }
828         maxLen -= 2; // " :" last param separator;
829
830         if (params.last().count() > maxLen) {
831             return params.last().count() - maxLen;
832         }
833         else {
834             return 0;
835         }
836     }
837     else {
838         return 0;
839     }
840 }
841
842
843 #ifdef HAVE_QCA2
844 QByteArray CoreUserInputHandler::encrypt(const QString &target, const QByteArray &message_, bool *didEncrypt) const
845 {
846     if (didEncrypt)
847         *didEncrypt = false;
848
849     if (message_.isEmpty())
850         return message_;
851
852     if (!Cipher::neededFeaturesAvailable())
853         return message_;
854
855     Cipher *cipher = network()->cipher(target);
856     if (!cipher || cipher->key().isEmpty())
857         return message_;
858
859     QByteArray message = message_;
860     bool result = cipher->encrypt(message);
861     if (didEncrypt)
862         *didEncrypt = result;
863
864     return message;
865 }
866
867
868 #endif
869
870 void CoreUserInputHandler::timerEvent(QTimerEvent *event)
871 {
872     if (!_delayedCommands.contains(event->timerId())) {
873         QObject::timerEvent(event);
874         return;
875     }
876     BufferInfo bufferInfo = _delayedCommands[event->timerId()].bufferInfo;
877     QString rawCommand = _delayedCommands[event->timerId()].command;
878     _delayedCommands.remove(event->timerId());
879     event->accept();
880
881     // the stored command might be the result of an alias expansion, so we need to split it up again
882     QStringList commands = rawCommand.split(QRegExp("; ?"));
883     foreach(QString command, commands) {
884         handleUserInput(bufferInfo, command);
885     }
886 }