Ok this is the major rework of quassel we've all been waiting for. For the actual...
[quassel.git] / src / core / ircserverhandler.cpp
1 /***************************************************************************
2  *   Copyright (C) 2005-07 by The Quassel Team                             *
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) any later version.                                   *
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 "ircserverhandler.h"
21
22 #include "util.h"
23
24 #include "server.h"
25 #include "networkinfo.h"
26 #include "ctcphandler.h"
27
28 #include "ircuser.h"
29 #include "ircchannel.h"
30
31 #include <QDebug>
32
33 IrcServerHandler::IrcServerHandler(Server *parent)
34   : BasicHandler(parent) {
35 }
36
37 IrcServerHandler::~IrcServerHandler() {
38 }
39
40 /*! Handle a raw message string sent by the server. We try to find a suitable handler, otherwise we call a default handler. */
41 void IrcServerHandler::handleServerMsg(QByteArray rawmsg) {
42   try {
43     if(rawmsg.isEmpty()) {
44       qWarning() << "Received empty string from server!";
45       return;
46     }
47     // TODO Implement encoding conversion
48     /* At this point, we have a raw message as a byte array. This needs to be converted to a QString somewhere.
49      * Problem is, that at this point we don't know which encoding to use for the various parts of the message.
50      * This is something the command handler needs to take care of (e.g. PRIVMSG needs to first parse for CTCP,
51      * and then convert the raw strings into the correct encoding.
52      * We _can_ safely assume Server encoding for prefix and cmd, but not for the params. Therefore, we need to
53      * change from a QStringList to a QList<QByteArray> in all the handlers, and have the handlers call decodeString
54      * where needed...
55     */
56     QString msg = QString::fromLatin1(rawmsg);
57
58     // OK, first we split the raw message into its various parts...
59     QString prefix = "";
60     QString cmd;
61     QStringList params;
62
63     // a colon as the first chars indicates the existance of a prefix
64     if(msg[0] == ':') {
65       msg.remove(0,1);
66       prefix = msg.section(' ', 0, 0);
67       msg = msg.section(' ', 1);
68     }
69
70     // next string without a whitespace is the command
71     cmd = msg.section(' ', 0, 0).toUpper();
72     msg = msg.mid(cmd.length());
73
74     // get the parameters
75     QString trailing = "";
76     if(msg.contains(" :")) {
77       trailing = msg.section(" :", 1);
78       msg = msg.section(" :", 0, 0);
79     }
80     if(!msg.isEmpty()) {
81       params << msg.split(' ', QString::SkipEmptyParts);
82     }
83     if(!trailing.isEmpty()) {
84       params << trailing;
85     }
86
87     // numeric replies have the target as first param (RFC 2812 - 2.4). this is usually our own nick. Remove this!
88     uint num = cmd.toUInt();
89     if(num > 0) {
90       Q_ASSERT(params.count() > 0); // Violation to RFC
91       params.removeFirst();
92     }
93
94     // Now we try to find a handler for this message. BTW, I do love the Trolltech guys ;-)
95     handle(cmd, Q_ARG(QString, prefix), Q_ARG(QStringList, params));
96     //handle(cmd, Q_ARG(QString, prefix));
97   } catch(Exception e) {
98     emit displayMsg(Message::Error, "", e.msg());
99   }
100 }
101
102
103 void IrcServerHandler::defaultHandler(QString cmd, QString prefix, QStringList params) {
104   uint num = cmd.toUInt();
105   if(num) {
106     // A lot of server messages don't really need their own handler because they don't do much.
107     // Catch and handle these here.
108     switch(num) {
109       // Welcome, status, info messages. Just display these.
110       case 2: case 3: case 4: case 5: case 251: case 252: case 253: case 254: case 255: case 372: case 375:
111         emit displayMsg(Message::Server, "", params.join(" "), prefix);
112         break;
113       // Server error messages without param, just display them
114       case 409: case 411: case 412: case 422: case 424: case 445: case 446: case 451: case 462:
115       case 463: case 464: case 465: case 466: case 472: case 481: case 483: case 485: case 491: case 501: case 502:
116       case 431: // ERR_NONICKNAMEGIVEN 
117         emit displayMsg(Message::Error, "", params.join(" "), prefix);
118         break;
119       // Server error messages, display them in red. First param will be appended.
120       case 401: case 402: case 403: case 404: case 406: case 408: case 415: case 421: case 442:
121       { QString p = params.takeFirst();
122         emit displayMsg(Message::Error, "", params.join(" ") + " " + p, prefix);
123         break;
124       }
125       // Server error messages which will be displayed with a colon between the first param and the rest
126       case 413: case 414: case 423: case 441: case 444: case 461:
127       case 467: case 471: case 473: case 474: case 475: case 476: case 477: case 478: case 482:
128       case 436: // ERR_NICKCOLLISION
129       { QString p = params.takeFirst();
130         emit displayMsg(Message::Error, "", p + ": " + params.join(" "));
131         break;
132       }
133       // Ignore these commands.
134       case 366: case 376:
135         break;
136
137       // Everything else will be marked in red, so we can add them somewhere.
138       default:
139         emit displayMsg(Message::Error, "", cmd + " " + params.join(" "), prefix);
140     }
141     //qDebug() << prefix <<":"<<cmd<<params;
142   } else {
143     emit displayMsg(Message::Error, "", QString("Unknown: ") + cmd + " " + params.join(" "), prefix);
144     //qDebug() << prefix <<":"<<cmd<<params;
145   }
146 }
147
148 //******************************/
149 // IRC SERVER HANDLER
150 //******************************/
151 void IrcServerHandler::handleJoin(QString prefix, QStringList params) {
152   Q_ASSERT(params.count() == 1);
153   QString channel = params[0];
154   IrcUser *ircuser = networkInfo()->updateNickFromMask(prefix);
155   emit displayMsg(Message::Join, channel, channel, prefix);
156
157   ircuser->joinChannel(channel);
158 }
159
160 void IrcServerHandler::handleKick(QString prefix, QStringList params) {
161   networkInfo()->updateNickFromMask(prefix);
162   IrcUser *victim = networkInfo()->ircUser(params[1]);
163   QString channel = params[0];
164   Q_ASSERT(victim);
165
166   victim->partChannel(channel);
167
168   QString msg;
169   if(params.count() > 2) // someone got a reason!
170     msg = QString("%1 %2").arg(victim->nick()).arg(params[2]);
171   else
172     msg = victim->nick();
173   
174   emit displayMsg(Message::Kick, params[0], msg, prefix);
175 }
176
177 void IrcServerHandler::handleMode(QString prefix, QStringList params) {
178 //   if(isChannelName(params[0])) {
179 //     // TODO only channel-user modes supported by now
180 //     QString prefixes = serverSupports["PrefixModes"].toString();
181 //     QString modes = params[1];
182 //     int p = 2;
183 //     int m = 0;
184 //     bool add = true;
185 //     while(m < modes.length()) {
186 //       if(modes[m] == '+') { add = true; m++; continue; }
187 //       if(modes[m] == '-') { add = false; m++; continue; }
188 //       if(prefixes.contains(modes[m])) {  // it's a user channel mode
189 //         Q_ASSERT(params.count() > m);
190 //         QString nick = params[p++];
191 //         if(nicks.contains(nick)) {  // sometimes, a server might try to set a MODE on a nick that is no longer there
192 //           QVariantMap n = nicks[nick]; QVariantMap clist = n["Channels"].toMap(); QVariantMap chan = clist[params[0]].toMap();
193 //           QString mstr = chan["Mode"].toString();
194 //           add ? mstr += modes[m] : mstr.remove(modes[m]);
195 //           chan["Mode"] = mstr; clist[params[0]] = chan; n["Channels"] = clist; nicks[nick] = n;
196 //           emit nickUpdated(network, nick, n);
197 //         }
198 //         m++;
199 //       } else {
200 //         // TODO add more modes
201 //         m++;
202 //       }
203 //     }
204 //     emit displayMsg(Message::Mode, params[0], params.join(" "), prefix);
205 //   } else {
206 //     //Q_ASSERT(nicks.contains(params[0]));
207 //     //QVariantMap n = nicks[params[0]].toMap();
208 //     //QString mode = n["Mode"].toString();
209 //     emit displayMsg(Message::Mode, "", params.join(" "));
210 //   }
211 }
212
213 void IrcServerHandler::handleNick(QString prefix, QStringList params) {
214   IrcUser *ircuser = networkInfo()->updateNickFromMask(prefix);
215   Q_ASSERT(ircuser);
216   QString newnick = params[0];
217   QString oldnick = ircuser->nick();
218
219   foreach(QString channel, ircuser->channels()) {
220     if(networkInfo()->isMyNick(oldnick))
221       emit displayMsg(Message::Nick, channel, newnick, prefix);
222     else
223       emit displayMsg(Message::Nick, channel, newnick, newnick);
224   }
225   ircuser->setNick(newnick);
226 }
227
228 void IrcServerHandler::handleNotice(QString prefix, QStringList params) {
229   if(networkInfo()->currentServer().isEmpty() || networkInfo()->currentServer() == prefix)
230     emit displayMsg(Message::Server, "", params[1], prefix);
231   else
232     emit displayMsg(Message::Notice, "", params[1], prefix);
233 }
234
235 void IrcServerHandler::handlePart(QString prefix, QStringList params) {
236   IrcUser *ircuser = networkInfo()->updateNickFromMask(prefix);
237   QString channel = params[0];
238   Q_ASSERT(ircuser);
239   
240   ircuser->partChannel(channel);
241   
242   QString msg;
243   if(params.count() > 1)
244     msg = params[1];
245   
246   emit displayMsg(Message::Part, params[0], msg, prefix);
247 }
248
249 void IrcServerHandler::handlePing(QString prefix, QStringList params) {
250   emit putCmd("PONG", params);
251 }
252
253 void IrcServerHandler::handlePrivmsg(QString prefix, QStringList params) {
254   networkInfo()->updateNickFromMask(prefix);
255   Q_ASSERT(params.count() >= 2);
256   if(params.count()<2)
257     emit displayMsg(Message::Plain, params[0], "", prefix);
258   else {
259     // it's possible to pack multiple privmsgs into one param using ctcp
260     QStringList messages = server->ctcpHandler()->parse(CtcpHandler::CtcpQuery, prefix, params[0], params[1]);
261
262     // are we the target or is it a channel?
263     if(networkInfo()->isMyNick(params[0])) {
264       foreach(QString message, messages) {
265         if(!message.isEmpty()) {
266           emit displayMsg(Message::Plain, "", message, prefix, Message::PrivMsg);
267         }
268       }
269    
270     } else {
271       Q_ASSERT(isChannelName(params[0]));  // should be channel!
272       foreach(QString message, messages) {
273         if(!message.isEmpty()) {
274           emit displayMsg(Message::Plain, params[0], message, prefix);
275         }
276       }
277     }
278   }
279 }
280
281 void IrcServerHandler::handleQuit(QString prefix, QStringList params) {
282   IrcUser *ircuser = networkInfo()->updateNickFromMask(prefix);
283   Q_ASSERT(ircuser);
284
285   QString msg;
286   if(params.count())
287     msg = params[0];
288   
289   foreach(QString channel, ircuser->channels())
290     emit displayMsg(Message::Quit, channel, msg, prefix);
291
292   ircuser->deleteLater();
293 }
294
295 void IrcServerHandler::handleTopic(QString prefix, QStringList params) {
296   IrcUser *ircuser = networkInfo()->updateNickFromMask(prefix);
297   QString channel = params[0];
298   QString topic = params[1];
299   Q_ASSERT(ircuser);
300
301   networkInfo()->ircChannel(channel)->setTopic(topic);
302
303   emit displayMsg(Message::Server, params[0], tr("%1 has changed topic for %2 to: \"%3\"").arg(ircuser->nick()).arg(channel).arg(topic));
304 }
305
306 /* RPL_WELCOME */
307 void IrcServerHandler::handle001(QString prefix, QStringList params) {
308   // there should be only one param: "Welcome to the Internet Relay Network <nick>!<user>@<host>"
309   QString myhostmask = params[0].section(' ', -1, -1);
310   networkInfo()->setCurrentServer(prefix);
311   networkInfo()->setMyNick(nickFromMask(myhostmask));
312
313   emit displayMsg(Message::Server, "", params[0], prefix);
314
315   // TODO: reimplement perform List!
316   //// send performlist
317   //QStringList performList = networkSettings["Perform"].toString().split( "\n" );
318   //int count = performList.count();
319   //for(int a = 0; a < count; a++) {
320   //  if(!performList[a].isEmpty() ) {
321   //    userInput(network, "", performList[a]);
322   //  }
323   //}
324 }
325
326 /* RPL_ISUPPORT */
327 // TODO Complete 005 handling, also use sensible defaults for non-sent stuff
328 void IrcServerHandler::handle005(QString prefix, QStringList params) {
329   QString rpl_isupport_suffix = params.takeLast();
330   if(rpl_isupport_suffix.toLower() != QString("are supported by this server")) {
331     qWarning() << "Received invalid RPL_ISUPPORT! Suffix is:" << rpl_isupport_suffix << "Excpected: are supported by this server";
332     return;
333   }
334   
335   foreach(QString param, params) {
336     QString key = param.section("=", 0, 0);
337     QString value = param.section("=", 1);
338     networkInfo()->addSupport(key, value);
339   }
340 }
341
342
343 /* RPL_NOTOPIC */
344 void IrcServerHandler::handle331(QString prefix, QStringList params) {
345   networkInfo()->ircChannel(params[0])->setTopic(QString());
346   emit displayMsg(Message::Server, params[0], tr("No topic is set for %1.").arg(params[0]));
347 }
348
349 /* RPL_TOPIC */
350 void IrcServerHandler::handle332(QString prefix, QStringList params) {
351   networkInfo()->ircChannel(params[0])->setTopic(params[1]);
352   emit displayMsg(Message::Server, params[0], tr("Topic for %1 is \"%2\"").arg(params[0]).arg(params[1]));
353 }
354
355 /* Topic set by... */
356 void IrcServerHandler::handle333(QString prefix, QStringList params) {
357   emit displayMsg(Message::Server, params[0], tr("Topic set by %1 on %2").arg(params[1]).arg(QDateTime::fromTime_t(params[2].toUInt()).toString()));
358 }
359
360 /* RPL_NAMREPLY */
361 void IrcServerHandler::handle353(QString prefix, QStringList params) {
362   params.removeFirst(); // either "=", "*" or "@" indicating a public, private or secret channel
363   QString channelname = params.takeFirst();
364
365   foreach(QString nick, params.takeFirst().split(' ')) {
366     QString mode = QString();
367
368     if(networkInfo()->prefixes().contains(nick[0])) {
369       mode = networkInfo()->prefixToMode(nick[0]);
370       nick = nick.mid(1);
371     }
372     
373     IrcUser *ircuser = networkInfo()->newIrcUser(nick);
374     ircuser->joinChannel(channelname);
375
376     if(!mode.isNull())
377       networkInfo()->ircChannel(channelname)->addUserMode(ircuser, mode);
378   }
379 }
380
381 /* ERR_ERRONEUSNICKNAME */
382 void IrcServerHandler::handle432(QString prefix, QStringList params) {
383 //   if(params.size() < 2) {
384 //     // handle unreal-ircd bug, where unreal ircd doesnt supply a TARGET in ERR_ERRONEUSNICKNAME during registration phase:
385 //     // nick @@@
386 //     // :irc.scortum.moep.net 432  @@@ :Erroneous Nickname: Illegal characters
387 //     // correct server reply:
388 //     // :irc.scortum.moep.net 432 * @@@ :Erroneous Nickname: Illegal characters
389 //     emit displayMsg(Message::Error, "", tr("There is a nickname in your identity's nicklist which contains illegal characters"));
390 //     emit displayMsg(Message::Error, "", tr("Due to a bug in Unreal IRCd (and maybe other irc-servers too) we're unable to determine the erroneous nick"));
391 //     emit displayMsg(Message::Error, "", tr("Please use: /nick <othernick> to continue or clean up your nicklist"));
392 //   } else {
393 //     QString errnick = params[0];
394 //     emit displayMsg(Message::Error, "", tr("Nick %1 contains illegal characters").arg(errnick));
395 //     // if there is a problem while connecting to the server -> we handle it
396 //     // TODO rely on another source...
397 //     if(currentServer.isEmpty()) {
398 //       QStringList desiredNicks = identity["NickList"].toStringList();
399 //       int nextNick = desiredNicks.indexOf(errnick) + 1;
400 //       if (desiredNicks.size() > nextNick) {
401 //         putCmd("NICK", QStringList(desiredNicks[nextNick]));
402 //       } else {
403 //         emit displayMsg(Message::Error, "", tr("No free and valid nicks in nicklist found. use: /nick <othernick> to continue"));
404 //       }
405 //     }
406 //   }
407 }
408
409 /* ERR_NICKNAMEINUSE */
410 void IrcServerHandler::handle433(QString prefix, QStringList params) {
411 //   QString errnick = params[0];
412 //   emit displayMsg(Message::Error, "", tr("Nick %1 is already taken").arg(errnick));
413 //   // if there is a problem while connecting to the server -> we handle it
414 //   // TODO rely on another source...
415 //   if(currentServer.isEmpty()) {
416 //     QStringList desiredNicks = identity["NickList"].toStringList();
417 //     int nextNick = desiredNicks.indexOf(errnick) + 1;
418 //     if (desiredNicks.size() > nextNick) {
419 //       putCmd("NICK", QStringList(desiredNicks[nextNick]));
420 //     } else {
421 //       emit displayMsg(Message::Error, "", tr("No free and valid nicks in nicklist found. use: /nick <othernick> to continue"));
422 //     }
423 //   }
424 }
425
426 /***********************************************************************************/
427
428