Allow sending unknown commands to server with >1 params
[quassel.git] / src / core / coreuserinputhandler.cpp
1 /***************************************************************************
2  *   Copyright (C) 2005-10 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  *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
19  ***************************************************************************/
20 #include "coreuserinputhandler.h"
21
22 #include "util.h"
23
24 #include "ctcphandler.h"
25 #include "coreidentity.h"
26 #include "ircuser.h"
27
28 #include <QDebug>
29 #include <QRegExp>
30
31 CoreUserInputHandler::CoreUserInputHandler(CoreNetwork *parent)
32   : CoreBasicHandler(parent)
33 {
34 }
35
36 void CoreUserInputHandler::handleUserInput(const BufferInfo &bufferInfo, const QString &msg) {
37   if(msg.isEmpty())
38     return;
39
40   AliasManager::CommandList list = coreSession()->aliasManager().processInput(bufferInfo, msg);
41
42   for(int i = 0; i < list.count(); i++) {
43     QString cmd = list.at(i).second.section(' ', 0, 0).remove(0, 1).toUpper();
44     QString payload = list.at(i).second.section(' ', 1);
45     handle(cmd, Q_ARG(BufferInfo, list.at(i).first), Q_ARG(QString, payload));
46   }
47 }
48
49 // ====================
50 //  Public Slots
51 // ====================
52 void CoreUserInputHandler::handleAway(const BufferInfo &bufferInfo, const QString &msg) {
53   Q_UNUSED(bufferInfo)
54
55   QString awayMsg = msg;
56   IrcUser *me = network()->me();
57
58   // if there is no message supplied we have to check if we are already away or not
59   if(msg.isEmpty()) {
60     if(me && !me->isAway()) {
61       awayMsg = network()->identityPtr()->awayReason();
62       if(awayMsg.isEmpty()) {
63         awayMsg = tr("away");
64       }
65     }
66   }
67   if(me)
68     me->setAwayMessage(awayMsg);
69
70   putCmd("AWAY", serverEncode(awayMsg));
71 }
72
73 void CoreUserInputHandler::handleBan(const BufferInfo &bufferInfo, const QString &msg) {
74   banOrUnban(bufferInfo, msg, true);
75 }
76
77 void CoreUserInputHandler::handleUnban(const BufferInfo &bufferInfo, const QString &msg) {
78   banOrUnban(bufferInfo, msg, false);
79 }
80
81 void CoreUserInputHandler::banOrUnban(const BufferInfo &bufferInfo, const QString &msg, bool ban) {
82   QString banChannel;
83   QString banUser;
84
85   QStringList params = msg.split(" ");
86
87   if(!params.isEmpty() && isChannelName(params[0])) {
88     banChannel = params.takeFirst();
89   } else if(bufferInfo.type() == BufferInfo::ChannelBuffer) {
90     banChannel = bufferInfo.bufferName();
91   } else {
92     emit displayMsg(Message::Error, BufferInfo::StatusBuffer, "", QString("Error: channel unknown in command: /BAN %1").arg(msg));
93     return;
94   }
95
96   if(!params.isEmpty() && !params.contains("!") && network()->ircUser(params[0])) {
97     IrcUser *ircuser = network()->ircUser(params[0]);
98     // generalizedHost changes <nick> to  *!ident@*.sld.tld.
99     QString generalizedHost = ircuser->host();
100     if(generalizedHost.isEmpty()) {
101       emit displayMsg(Message::Error, BufferInfo::StatusBuffer, "", QString("Error: host unknown in command: /BAN %1").arg(msg));
102       return;
103     }
104
105     static QRegExp ipAddress("\\d+\\.\\d+\\.\\d+\\.\\d+");
106     if(ipAddress.exactMatch(generalizedHost))    {
107         int lastDotPos = generalizedHost.lastIndexOf('.') + 1;
108         generalizedHost.replace(lastDotPos, generalizedHost.length() - lastDotPos, '*');
109     } else if(generalizedHost.lastIndexOf(".") != -1 && generalizedHost.lastIndexOf(".", generalizedHost.lastIndexOf(".")-1) != -1) {
110       int secondLastPeriodPosition = generalizedHost.lastIndexOf(".", generalizedHost.lastIndexOf(".")-1);
111       generalizedHost.replace(0, secondLastPeriodPosition, "*");
112     }
113     banUser = QString("*!%1@%2").arg(ircuser->user(), generalizedHost);
114   } else {
115     banUser = params.join(" ");
116   }
117
118   QString banMode = ban ? "+b" : "-b";
119   QString banMsg = QString("MODE %1 %2 %3").arg(banChannel, banMode, banUser);
120   emit putRawLine(serverEncode(banMsg));
121 }
122
123 void CoreUserInputHandler::handleCtcp(const BufferInfo &bufferInfo, const QString &msg) {
124   Q_UNUSED(bufferInfo)
125
126   QString nick = msg.section(' ', 0, 0);
127   QString ctcpTag = msg.section(' ', 1, 1).toUpper();
128   if(ctcpTag.isEmpty())
129     return;
130
131   QString message = msg.section(' ', 2);
132   QString verboseMessage = tr("sending CTCP-%1 request to %2").arg(ctcpTag).arg(nick);
133
134   if(ctcpTag == "PING") {
135     uint now = QDateTime::currentDateTime().toTime_t();
136     message = QString::number(now);
137   }
138
139   network()->ctcpHandler()->query(nick, ctcpTag, message);
140   emit displayMsg(Message::Action, BufferInfo::StatusBuffer, "", verboseMessage, network()->myNick());
141 }
142
143 void CoreUserInputHandler::handleDeop(const BufferInfo &bufferInfo, const QString &msg) {
144   QStringList nicks = msg.split(' ', QString::SkipEmptyParts);
145   QString m = "-"; for(int i = 0; i < nicks.count(); i++) m += 'o';
146   QStringList params;
147   params << bufferInfo.bufferName() << m << nicks;
148   emit putCmd("MODE", serverEncode(params));
149 }
150
151 void CoreUserInputHandler::handleDevoice(const BufferInfo &bufferInfo, const QString &msg) {
152   QStringList nicks = msg.split(' ', QString::SkipEmptyParts);
153   QString m = "-"; for(int i = 0; i < nicks.count(); i++) m += 'v';
154   QStringList params;
155   params << bufferInfo.bufferName() << m << nicks;
156   emit putCmd("MODE", serverEncode(params));
157 }
158
159 void CoreUserInputHandler::handleInvite(const BufferInfo &bufferInfo, const QString &msg) {
160   QStringList params;
161   params << msg << bufferInfo.bufferName();
162   emit putCmd("INVITE", serverEncode(params));
163 }
164
165 void CoreUserInputHandler::handleJoin(const BufferInfo &bufferInfo, const QString &msg) {
166   Q_UNUSED(bufferInfo);
167
168   // trim spaces before chans or keys
169   QString sane_msg = msg;
170   sane_msg.replace(QRegExp(", +"), ",");
171   QStringList params = sane_msg.trimmed().split(" ");
172
173   QStringList chans = params[0].split(",", QString::SkipEmptyParts);
174   QStringList keys;
175   if(params.count() > 1)
176     keys = params[1].split(",");
177
178   int i;
179   for(i = 0; i < chans.count(); i++) {
180     if(!network()->isChannelName(chans[i]))
181       chans[i].prepend('#');
182
183     if(i < keys.count()) {
184       network()->addChannelKey(chans[i], keys[i]);
185     } else {
186       network()->removeChannelKey(chans[i]);
187     }
188   }
189
190   static const char *cmd = "JOIN";
191   i = 0;
192   QStringList joinChans, joinKeys;
193   int slicesize = chans.count();
194   QList<QByteArray> encodedParams;
195
196   // go through all to-be-joined channels and (re)build the join list
197   while(i < chans.count()) {
198     joinChans.append(chans.at(i));
199     if(i < keys.count())
200       joinKeys.append(keys.at(i));
201
202     // if the channel list we built so far either contains all requested channels or exceeds
203     // the desired amount of channels in this slice, try to send what we have so far
204     if(++i == chans.count() || joinChans.count() >= slicesize) {
205       params.clear();
206       params.append(joinChans.join(","));
207       params.append(joinKeys.join(","));
208       encodedParams = serverEncode(params);
209       // check if it fits in one command
210       if(lastParamOverrun(cmd, encodedParams) == 0) {
211         emit putCmd(cmd, encodedParams);
212       } else if(slicesize > 1) {
213         // back to start of slice, try again with half the amount of channels
214         i -= slicesize;
215         slicesize /= 2;
216       }
217       joinChans.clear();
218       joinKeys.clear();
219     }
220   }
221 }
222
223 void CoreUserInputHandler::handleKick(const BufferInfo &bufferInfo, const QString &msg) {
224   QString nick = msg.section(' ', 0, 0, QString::SectionSkipEmpty);
225   QString reason = msg.section(' ', 1, -1, QString::SectionSkipEmpty).trimmed();
226   if(reason.isEmpty())
227     reason = network()->identityPtr()->kickReason();
228
229   QList<QByteArray> params;
230   params << serverEncode(bufferInfo.bufferName()) << serverEncode(nick) << channelEncode(bufferInfo.bufferName(), reason);
231   emit putCmd("KICK", params);
232 }
233
234 void CoreUserInputHandler::handleKill(const BufferInfo &bufferInfo, const QString &msg) {
235   Q_UNUSED(bufferInfo)
236   QString nick = msg.section(' ', 0, 0, QString::SectionSkipEmpty);
237   QString pass = msg.section(' ', 1, -1, QString::SectionSkipEmpty);
238   QList<QByteArray> params;
239   params << serverEncode(nick) << serverEncode(pass);
240   emit putCmd("KILL", params);
241 }
242
243
244 void CoreUserInputHandler::handleList(const BufferInfo &bufferInfo, const QString &msg) {
245   Q_UNUSED(bufferInfo)
246   emit putCmd("LIST", serverEncode(msg.split(' ', QString::SkipEmptyParts)));
247 }
248
249 void CoreUserInputHandler::handleMe(const BufferInfo &bufferInfo, const QString &msg) {
250   if(bufferInfo.bufferName().isEmpty()) return; // server buffer
251   network()->ctcpHandler()->query(bufferInfo.bufferName(), "ACTION", msg);
252   emit displayMsg(Message::Action, bufferInfo.type(), bufferInfo.bufferName(), msg, network()->myNick(), Message::Self);
253 }
254
255 void CoreUserInputHandler::handleMode(const BufferInfo &bufferInfo, const QString &msg) {
256   Q_UNUSED(bufferInfo)
257
258   QStringList params = msg.split(' ', QString::SkipEmptyParts);
259   // 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
260   if(!params.isEmpty() && !network()->isChannelName(params[0]) && !network()->isMyNick(params[0]))
261     params.prepend(bufferInfo.bufferName());
262
263   // TODO handle correct encoding for buffer modes (channelEncode())
264   emit putCmd("MODE", serverEncode(params));
265 }
266
267 // TODO: show privmsgs
268 void CoreUserInputHandler::handleMsg(const BufferInfo &bufferInfo, const QString &msg) {
269   Q_UNUSED(bufferInfo);
270   if(!msg.contains(' '))
271     return;
272
273   QByteArray target = serverEncode(msg.section(' ', 0, 0));
274   putPrivmsg(target, userEncode(target, msg.section(' ', 1)));
275 }
276
277 void CoreUserInputHandler::handleNick(const BufferInfo &bufferInfo, const QString &msg) {
278   Q_UNUSED(bufferInfo)
279   QString nick = msg.section(' ', 0, 0);
280   emit putCmd("NICK", serverEncode(nick));
281 }
282
283 void CoreUserInputHandler::handleNotice(const BufferInfo &bufferInfo, const QString &msg) {
284   QString bufferName = msg.section(' ', 0, 0);
285   QString payload = msg.section(' ', 1);
286   QList<QByteArray> params;
287   params << serverEncode(bufferName) << channelEncode(bufferInfo.bufferName(), payload);
288   emit putCmd("NOTICE", params);
289   emit displayMsg(Message::Notice, bufferName, payload, network()->myNick(), Message::Self);
290 }
291
292 void CoreUserInputHandler::handleOp(const BufferInfo &bufferInfo, const QString &msg) {
293   QStringList nicks = msg.split(' ', QString::SkipEmptyParts);
294   QString m = "+"; for(int i = 0; i < nicks.count(); i++) m += 'o';
295   QStringList params;
296   params << bufferInfo.bufferName() << m << nicks;
297   emit putCmd("MODE", serverEncode(params));
298 }
299
300 void CoreUserInputHandler::handleOper(const BufferInfo &bufferInfo, const QString &msg) {
301   Q_UNUSED(bufferInfo)
302   emit putRawLine(serverEncode(QString("OPER %1").arg(msg)));
303 }
304
305 void CoreUserInputHandler::handlePart(const BufferInfo &bufferInfo, const QString &msg) {
306   QList<QByteArray> params;
307   QString partReason;
308
309   // msg might contain either a channel name and/or a reaon, so we have to check if the first word is a known channel
310   QString channelName = msg.section(' ', 0, 0);
311   if(channelName.isEmpty() || !network()->ircChannel(channelName)) {
312     channelName = bufferInfo.bufferName();
313     partReason = msg;
314   } else {
315     partReason = msg.mid(channelName.length() + 1);
316   }
317
318   if(partReason.isEmpty())
319     partReason = network()->identityPtr()->partReason();
320
321   params << serverEncode(channelName) << channelEncode(bufferInfo.bufferName(), partReason);
322   emit putCmd("PART", params);
323 }
324
325 void CoreUserInputHandler::handlePing(const BufferInfo &bufferInfo, const QString &msg) {
326   Q_UNUSED(bufferInfo)
327
328   QString param = msg;
329   if(param.isEmpty())
330     param = QTime::currentTime().toString("hh:mm:ss.zzz");
331
332   putCmd("PING", serverEncode(param));
333 }
334
335 // TODO: implement queries
336 void CoreUserInputHandler::handleQuery(const BufferInfo &bufferInfo, const QString &msg) {
337   Q_UNUSED(bufferInfo)
338   QString target = msg.section(' ', 0, 0);
339   QString message = msg.section(' ', 1);
340   if(message.isEmpty())
341     emit displayMsg(Message::Server, BufferInfo::QueryBuffer, target, "Starting query with " + target, network()->myNick(), Message::Self);
342   else
343     emit displayMsg(Message::Plain, BufferInfo::QueryBuffer, target, message, network()->myNick(), Message::Self);
344   handleMsg(bufferInfo, msg);
345 }
346
347 void CoreUserInputHandler::handleQuit(const BufferInfo &bufferInfo, const QString &msg) {
348   Q_UNUSED(bufferInfo)
349   network()->disconnectFromIrc(true, msg);
350 }
351
352 void CoreUserInputHandler::issueQuit(const QString &reason) {
353   emit putCmd("QUIT", serverEncode(reason));
354 }
355
356 void CoreUserInputHandler::handleQuote(const BufferInfo &bufferInfo, const QString &msg) {
357   Q_UNUSED(bufferInfo)
358   emit putRawLine(serverEncode(msg));
359 }
360
361 void CoreUserInputHandler::handleSay(const BufferInfo &bufferInfo, const QString &msg) {
362   if(bufferInfo.bufferName().isEmpty())
363     return;  // server buffer
364   putPrivmsg(serverEncode(bufferInfo.bufferName()), channelEncode(bufferInfo.bufferName(), msg));
365   emit displayMsg(Message::Plain, bufferInfo.type(), bufferInfo.bufferName(), msg, network()->myNick(), Message::Self);
366 }
367
368 void CoreUserInputHandler::handleTopic(const BufferInfo &bufferInfo, const QString &msg) {
369   if(bufferInfo.bufferName().isEmpty()) return;
370   QList<QByteArray> params;
371   params << serverEncode(bufferInfo.bufferName());
372   if(!msg.isEmpty())
373     params << channelEncode(bufferInfo.bufferName(), msg);
374   emit putCmd("TOPIC", params);
375 }
376
377 void CoreUserInputHandler::handleVoice(const BufferInfo &bufferInfo, const QString &msg) {
378   QStringList nicks = msg.split(' ', QString::SkipEmptyParts);
379   QString m = "+"; for(int i = 0; i < nicks.count(); i++) m += 'v';
380   QStringList params;
381   params << bufferInfo.bufferName() << m << nicks;
382   emit putCmd("MODE", serverEncode(params));
383 }
384
385 void CoreUserInputHandler::handleWait(const BufferInfo &bufferInfo, const QString &msg) {
386   int splitPos = msg.indexOf(';');
387   if(splitPos <= 0)
388     return;
389
390   bool ok;
391   int delay = msg.left(splitPos).trimmed().toInt(&ok);
392   if(!ok)
393     return;
394
395   delay *= 1000;
396
397   QString command = msg.mid(splitPos + 1).trimmed();
398   if(command.isEmpty())
399     return;
400
401   _delayedCommands[startTimer(delay)] = Command(bufferInfo, command);
402 }
403
404 void CoreUserInputHandler::handleWho(const BufferInfo &bufferInfo, const QString &msg) {
405   Q_UNUSED(bufferInfo)
406   emit putCmd("WHO", serverEncode(msg.split(' ')));
407 }
408
409 void CoreUserInputHandler::handleWhois(const BufferInfo &bufferInfo, const QString &msg) {
410   Q_UNUSED(bufferInfo)
411   emit putCmd("WHOIS", serverEncode(msg.split(' ')));
412 }
413
414 void CoreUserInputHandler::handleWhowas(const BufferInfo &bufferInfo, const QString &msg) {
415   Q_UNUSED(bufferInfo)
416   emit putCmd("WHOWAS", serverEncode(msg.split(' ')));
417 }
418
419 void CoreUserInputHandler::defaultHandler(QString cmd, const BufferInfo &bufferInfo, const QString &msg) {
420   Q_UNUSED(bufferInfo);
421   emit putCmd(serverEncode(cmd.toUpper()), serverEncode(msg.split(" ")));
422 }
423
424 void CoreUserInputHandler::putPrivmsg(const QByteArray &target, const QByteArray &message) {
425   static const char *cmd = "PRIVMSG";
426   int overrun = lastParamOverrun(cmd, QList<QByteArray>() << target << message);
427   if(overrun) {
428     static const char *splitter = " .,-";
429     int maxSplitPos = message.count() - overrun;
430     int splitPos = -1;
431     for(const char *splitChar = splitter; *splitChar != 0; splitChar++) {
432       splitPos = qMax(splitPos, message.lastIndexOf(*splitChar, maxSplitPos));
433     }
434     if(splitPos <= 0) {
435       splitPos = maxSplitPos;
436     }
437     putCmd(cmd, QList<QByteArray>() << target << message.left(splitPos));
438     putPrivmsg(target, message.mid(splitPos));
439     return;
440   } else {
441     putCmd(cmd, QList<QByteArray>() << target << message);
442   }
443 }
444
445 // returns 0 if the message will not be chopped by the irc server or number of chopped bytes if message is too long
446 int CoreUserInputHandler::lastParamOverrun(const QString &cmd, const QList<QByteArray> &params) {
447   // the server will pass our message truncated to 512 bytes including CRLF with the following format:
448   // ":prefix COMMAND param0 param1 :lastparam"
449   // where prefix = "nickname!user@host"
450   // that means that the last message can be as long as:
451   // 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)
452   IrcUser *me = network()->me();
453   int maxLen = 480 - cmd.toAscii().count(); // educated guess in case we don't know us (yet?)
454
455   if(me)
456     maxLen = 512 - serverEncode(me->nick()).count() - serverEncode(me->user()).count() - serverEncode(me->host()).count() - cmd.toAscii().count() - 6;
457
458   if(!params.isEmpty()) {
459     for(int i = 0; i < params.count() - 1; i++) {
460       maxLen -= (params[i].count() + 1);
461     }
462     maxLen -= 2; // " :" last param separator;
463
464     if(params.last().count() > maxLen) {
465       return params.last().count() - maxLen;
466     } else {
467       return 0;
468     }
469   } else {
470     return 0;
471   }
472 }
473
474 void CoreUserInputHandler::timerEvent(QTimerEvent *event) {
475   if(!_delayedCommands.contains(event->timerId())) {
476     QObject::timerEvent(event);
477     return;
478   }
479   BufferInfo bufferInfo = _delayedCommands[event->timerId()].bufferInfo;
480   QString rawCommand = _delayedCommands[event->timerId()].command;
481   _delayedCommands.remove(event->timerId());
482   event->accept();
483
484   // the stored command might be the result of an alias expansion, so we need to split it up again
485   QStringList commands = rawCommand.split(QRegExp("; ?"));
486   foreach(QString command, commands) {
487     handleUserInput(bufferInfo, command);
488   }
489 }