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