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