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