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