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