Don't have CTCP ignore rules apply to ACTIONs
[quassel.git] / src / core / ircparser.cpp
1 /***************************************************************************
2  *   Copyright (C) 2005-2010 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
21 #include "ircparser.h"
22
23 #include "corenetwork.h"
24 #include "eventmanager.h"
25 #include "ircevent.h"
26 #include "messageevent.h"
27 #include "networkevent.h"
28
29 #ifdef HAVE_QCA2
30 #  include "cipher.h"
31 #endif
32
33 IrcParser::IrcParser(CoreSession *session) :
34   QObject(session),
35   _coreSession(session)
36 {
37
38 }
39
40 bool IrcParser::checkParamCount(const QString &cmd, const QList<QByteArray> &params, int minParams) {
41   if(params.count() < minParams) {
42     qWarning() << "Expected" << minParams << "params for IRC command" << cmd << ", got:" << params;
43     return false;
44   }
45   return true;
46 }
47
48 QByteArray IrcParser::decrypt(Network *network, const QString &bufferName, const QByteArray &message, bool isTopic) {
49 #ifdef HAVE_QCA2
50   if(message.isEmpty())
51     return message;
52
53   Cipher *cipher = qobject_cast<CoreNetwork *>(network)->cipher(bufferName);
54   if(!cipher)
55     return message;
56
57   return isTopic? cipher->decryptTopic(message) : cipher->decrypt(message);
58 #else
59   Q_UNUSED(network);
60   Q_UNUSED(bufferName);
61   Q_UNUSED(isTopic);
62   return message;
63 #endif
64 }
65
66 /* parse the raw server string and generate an appropriate event */
67 /* used to be handleServerMsg()                                  */
68 void IrcParser::processNetworkIncoming(NetworkDataEvent *e) {
69   CoreNetwork *net = qobject_cast<CoreNetwork *>(e->network());
70   if(!net) {
71     qWarning() << "Received network event without valid network pointer!";
72     return;
73   }
74
75   // note that the IRC server is still alive
76   net->resetPingTimeout();
77
78   QByteArray msg = e->data();
79   if(msg.isEmpty()) {
80     qWarning() << "Received empty string from server!";
81     return;
82   }
83
84   // Now we split the raw message into its various parts...
85   QString prefix;
86   QByteArray trailing;
87   QString cmd, target;
88
89   // First, check for a trailing parameter introduced by " :", since this might screw up splitting the msg
90   // NOTE: This assumes that this is true in raw encoding, but well, hopefully there are no servers running in japanese on protocol level...
91   int idx = msg.indexOf(" :");
92   if(idx >= 0) {
93     if(msg.length() > idx + 2)
94       trailing = msg.mid(idx + 2);
95     msg = msg.left(idx);
96   }
97   // OK, now it is safe to split...
98   QList<QByteArray> params = msg.split(' ');
99
100   // This could still contain empty elements due to (faulty?) ircds sending multiple spaces in a row
101   // Also, QByteArray is not nearly as convenient to work with as QString for such things :)
102   QList<QByteArray>::iterator iter = params.begin();
103   while(iter != params.end()) {
104     if(iter->isEmpty())
105       iter = params.erase(iter);
106     else
107       ++iter;
108   }
109
110   if(!trailing.isEmpty())
111     params << trailing;
112   if(params.count() < 1) {
113     qWarning() << "Received invalid string from server!";
114     return;
115   }
116
117   QString foo = net->serverDecode(params.takeFirst());
118
119   // a colon as the first chars indicates the existence of a prefix
120   if(foo[0] == ':') {
121     foo.remove(0, 1);
122     prefix = foo;
123     if(params.count() < 1) {
124       qWarning() << "Received invalid string from server!";
125       return;
126     }
127     foo = net->serverDecode(params.takeFirst());
128   }
129
130   // next string without a whitespace is the command
131   cmd = foo.trimmed();
132
133   QList<Event *> events;
134   EventManager::EventType type = EventManager::Invalid;
135
136   // numeric replies have the target as first param (RFC 2812 - 2.4). this is usually our own nick. Remove this!
137   uint num = cmd.toUInt();
138   if(num > 0) {
139     if(params.count() == 0) {
140       qWarning() << "Message received from server violates RFC and is ignored!" << msg;
141       return;
142     }
143     target = net->serverDecode(params.takeFirst());
144     type = EventManager::IrcEventNumeric;
145   } else {
146     QString typeName = QLatin1String("IrcEvent") + cmd.at(0).toUpper() + cmd.mid(1).toLower();
147     type = eventManager()->eventTypeByName(typeName);
148     if(type == EventManager::Invalid) {
149       type = eventManager()->eventTypeByName("IrcEventUnknown");
150       Q_ASSERT(type != EventManager::Invalid);
151     }
152     target = QString();
153   }
154
155   // Almost always, all params are server-encoded. There's a few exceptions, let's catch them here!
156   // Possibly not the best option, we might want something more generic? Maybe yet another layer of
157   // unencoded events with event handlers for the exceptions...
158   // Also, PRIVMSG and NOTICE need some special handling, we put this in here as well, so we get out
159   // nice pre-parsed events that the CTCP handler can consume.
160
161   QStringList decParams;
162   bool defaultHandling = true; // whether to automatically copy the remaining params and send the event
163
164   switch(type) {
165
166   case EventManager::IrcEventPrivmsg:
167     defaultHandling = false; // this might create a list of events
168
169     if(checkParamCount(cmd, params, 1)) {
170       QString senderNick = nickFromMask(prefix);
171       QByteArray msg = params.count() < 2 ? QByteArray() : params.at(1);
172
173       QStringList targets = net->serverDecode(params.at(0)).split(',', QString::SkipEmptyParts);
174       QStringList::const_iterator targetIter;
175       for(targetIter = targets.constBegin(); targetIter != targets.constEnd(); ++targetIter) {
176         QString target = net->isChannelName(*targetIter) ? *targetIter : senderNick;
177
178         msg = decrypt(net, target, msg);
179
180         events << new IrcEventRawMessage(EventManager::IrcEventRawPrivmsg, net, msg, prefix, target, e->timestamp());
181       }
182     }
183     break;
184
185   case EventManager::IrcEventNotice:
186     defaultHandling = false;
187
188     if(checkParamCount(cmd, params, 2)) {
189       QStringList targets = net->serverDecode(params.at(0)).split(',', QString::SkipEmptyParts);
190       QStringList::const_iterator targetIter;
191       for(targetIter = targets.constBegin(); targetIter != targets.constEnd(); ++targetIter) {
192         QString target = *targetIter;
193
194         // special treatment for welcome messages like:
195         // :ChanServ!ChanServ@services. NOTICE egst :[#apache] Welcome, this is #apache. Please read the in-channel topic message. This channel is being logged by IRSeekBot. If you have any question please see http://blog.freenode.net/?p=68
196         if(!net->isChannelName(target)) {
197           QString decMsg = net->serverDecode(params.at(1));
198           QRegExp welcomeRegExp("^\\[([^\\]]+)\\] ");
199           if(welcomeRegExp.indexIn(decMsg) != -1) {
200             QString channelname = welcomeRegExp.cap(1);
201             decMsg = decMsg.mid(welcomeRegExp.matchedLength());
202             CoreIrcChannel *chan = static_cast<CoreIrcChannel *>(net->ircChannel(channelname)); // we only have CoreIrcChannels in the core, so this cast is safe
203             if(chan && !chan->receivedWelcomeMsg()) {
204               chan->setReceivedWelcomeMsg();
205               events << new MessageEvent(Message::Notice, net, decMsg, prefix, channelname, Message::None, e->timestamp());
206               continue;
207             }
208           }
209         }
210
211         if(prefix.isEmpty() || target == "AUTH") {
212           target = QString();
213         } else {
214           if(!target.isEmpty() && net->prefixes().contains(target.at(0)))
215             target = target.mid(1);
216           if(!net->isChannelName(target))
217             target = nickFromMask(prefix);
218         }
219         events << new IrcEventRawMessage(EventManager::IrcEventRawNotice, net, params[1], prefix, target, e->timestamp());
220       }
221     }
222     break;
223
224     // the following events need only special casing for param decoding
225   case EventManager::IrcEventKick:
226     if(params.count() >= 3) { // we have a reason
227       decParams << net->serverDecode(params.at(0)) << net->serverDecode(params.at(1));
228       decParams << net->channelDecode(decParams.first(), params.at(2)); // kick reason
229     }
230     break;
231
232   case EventManager::IrcEventPart:
233     if(params.count() >= 2) {
234       QString channel = net->serverDecode(params.at(0));
235       decParams << channel;
236       decParams << net->userDecode(nickFromMask(prefix), params.at(1));
237     }
238     break;
239
240   case EventManager::IrcEventQuit:
241     if(params.count() >= 1) {
242       decParams << net->userDecode(nickFromMask(prefix), params.at(0));
243     }
244     break;
245
246   case EventManager::IrcEventTopic:
247     if(params.count() >= 1) {
248       QString channel = net->serverDecode(params.at(0));
249       decParams << channel;
250       decParams << (params.count() >= 2? net->channelDecode(channel, decrypt(net, channel, params.at(1), true)) : QString());
251     }
252     break;
253
254   case EventManager::IrcEventNumeric:
255     switch(num) {
256     case 301:  /* RPL_AWAY */
257       if(params.count() >= 2) {
258         QString nick = net->serverDecode(params.at(0));
259         decParams << nick;
260         decParams << net->userDecode(nick, params.at(1));
261       }
262       break;
263
264     case 332:  /* RPL_TOPIC */
265       if(params.count() >= 2) {
266         QString channel = net->serverDecode(params.at(0));
267         decParams << channel;
268         decParams << net->channelDecode(channel, decrypt(net, channel, params.at(1), true));
269       }
270       break;
271
272     case 333:  /* Topic set by... */
273       if(params.count() >= 2) {
274         QString channel = net->serverDecode(params.at(0));
275         decParams << channel << net->serverDecode(params.at(1));
276         decParams << net->channelDecode(channel, params.at(2));
277       }
278       break;
279     }
280
281   default:
282     break;
283   }
284
285   if(defaultHandling && type != EventManager::Invalid) {
286     for(int i = decParams.count(); i < params.count(); i++)
287       decParams << net->serverDecode(params.at(i));
288
289     IrcEvent *event;
290     if(type == EventManager::IrcEventNumeric)
291       event = new IrcEventNumeric(num, net, prefix, target);
292     else
293       event = new IrcEvent(type, net, prefix);
294     event->setParams(decParams);
295     event->setTimestamp(e->timestamp());
296     events << event;
297   }
298
299   foreach(Event *event, events) {
300     coreSession()->eventManager()->sendEvent(event);
301   }
302 }