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