ec39c57bdfded0c10f43ad7618445b02b0efc451
[quassel.git] / src / core / ircserverhandler.cpp
1 /***************************************************************************
2  *   Copyright (C) 2005-07 by the Quassel IRC 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) 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 "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   //qDebug() << "IrcServerHandler::handleJoin()" << prefix << params;
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   Q_UNUSED(prefix)
179   Q_UNUSED(params)
180     
181 //   if(isChannelName(params[0])) {
182 //     // TODO only channel-user modes supported by now
183 //     QString prefixes = serverSupports["PrefixModes"].toString();
184 //     QString modes = params[1];
185 //     int p = 2;
186 //     int m = 0;
187 //     bool add = true;
188 //     while(m < modes.length()) {
189 //       if(modes[m] == '+') { add = true; m++; continue; }
190 //       if(modes[m] == '-') { add = false; m++; continue; }
191 //       if(prefixes.contains(modes[m])) {  // it's a user channel mode
192 //         Q_ASSERT(params.count() > m);
193 //         QString nick = params[p++];
194 //         if(nicks.contains(nick)) {  // sometimes, a server might try to set a MODE on a nick that is no longer there
195 //           QVariantMap n = nicks[nick]; QVariantMap clist = n["Channels"].toMap(); QVariantMap chan = clist[params[0]].toMap();
196 //           QString mstr = chan["Mode"].toString();
197 //           add ? mstr += modes[m] : mstr.remove(modes[m]);
198 //           chan["Mode"] = mstr; clist[params[0]] = chan; n["Channels"] = clist; nicks[nick] = n;
199 //           emit nickUpdated(network, nick, n);
200 //         }
201 //         m++;
202 //       } else {
203 //         // TODO add more modes
204 //         m++;
205 //       }
206 //     }
207 //     emit displayMsg(Message::Mode, params[0], params.join(" "), prefix);
208 //   } else {
209 //     //Q_ASSERT(nicks.contains(params[0]));
210 //     //QVariantMap n = nicks[params[0]].toMap();
211 //     //QString mode = n["Mode"].toString();
212 //     emit displayMsg(Message::Mode, "", params.join(" "));
213 //   }
214 }
215
216 void IrcServerHandler::handleNick(QString prefix, QStringList params) {
217   IrcUser *ircuser = networkInfo()->updateNickFromMask(prefix);
218   Q_ASSERT(ircuser);
219   QString newnick = params[0];
220   QString oldnick = ircuser->nick();
221
222   foreach(QString channel, ircuser->channels()) {
223     if(networkInfo()->isMyNick(oldnick)) {
224       emit displayMsg(Message::Nick, channel, newnick, newnick);
225     } else {
226       emit displayMsg(Message::Nick, channel, newnick, prefix);
227     }
228   }
229   ircuser->setNick(newnick);
230 }
231
232 void IrcServerHandler::handleNotice(QString prefix, QStringList params) {
233   if(networkInfo()->currentServer().isEmpty() || networkInfo()->currentServer() == prefix)
234     emit displayMsg(Message::Server, "", params[1], prefix);
235   else
236     emit displayMsg(Message::Notice, "", params[1], prefix);
237 }
238
239 void IrcServerHandler::handlePart(QString prefix, QStringList params) {
240   IrcUser *ircuser = networkInfo()->updateNickFromMask(prefix);
241   QString channel = params[0];
242   Q_ASSERT(ircuser);
243   
244   ircuser->partChannel(channel);
245   
246   QString msg;
247   if(params.count() > 1)
248     msg = params[1];
249   
250   emit displayMsg(Message::Part, params[0], msg, prefix);
251 }
252
253 void IrcServerHandler::handlePing(QString prefix, QStringList params) {
254   Q_UNUSED(prefix)
255   emit putCmd("PONG", params);
256 }
257
258 void IrcServerHandler::handlePrivmsg(QString prefix, QStringList params) {
259   networkInfo()->updateNickFromMask(prefix);
260   if(params.count()<2)
261     params << QString("");
262   
263   // it's possible to pack multiple privmsgs into one param using ctcp
264   QStringList messages = server->ctcpHandler()->parse(CtcpHandler::CtcpQuery, prefix, params[0], params[1]);
265   
266   // are we the target or is it a channel?
267   if(networkInfo()->isMyNick(params[0])) {
268     foreach(QString message, messages) {
269       if(!message.isEmpty()) {
270         emit displayMsg(Message::Plain, "", message, prefix, Message::PrivMsg);
271       }
272     }
273     
274   } else {
275     Q_ASSERT(isChannelName(params[0]));  // should be channel!
276     foreach(QString message, messages) {
277       if(!message.isEmpty()) {
278         emit displayMsg(Message::Plain, params[0], message, prefix);
279       }
280     }
281   }
282
283 }
284
285 void IrcServerHandler::handleQuit(QString prefix, QStringList params) {
286   IrcUser *ircuser = networkInfo()->updateNickFromMask(prefix);
287   Q_ASSERT(ircuser);
288   //qDebug() << "IrcServerHandler:handleQuit" << prefix << params;
289
290   QString msg;
291   if(params.count())
292     msg = params[0];
293   
294   foreach(QString channel, ircuser->channels())
295     emit displayMsg(Message::Quit, channel, msg, prefix);
296   
297   networkInfo()->removeIrcUser(nickFromMask(prefix));
298 }
299
300 void IrcServerHandler::handleTopic(QString prefix, QStringList params) {
301   IrcUser *ircuser = networkInfo()->updateNickFromMask(prefix);
302   QString channel = params[0];
303   QString topic = params[1];
304   Q_ASSERT(ircuser);
305
306   networkInfo()->ircChannel(channel)->setTopic(topic);
307
308   emit displayMsg(Message::Server, params[0], tr("%1 has changed topic for %2 to: \"%3\"").arg(ircuser->nick()).arg(channel).arg(topic));
309 }
310
311 /* RPL_WELCOME */
312 void IrcServerHandler::handle001(QString prefix, QStringList params) {
313   // there should be only one param: "Welcome to the Internet Relay Network <nick>!<user>@<host>"
314   QString myhostmask = params[0].section(' ', -1, -1);
315   networkInfo()->setCurrentServer(prefix);
316   networkInfo()->setMyNick(nickFromMask(myhostmask));
317
318   emit displayMsg(Message::Server, "", params[0], prefix);
319
320   // TODO: reimplement perform List!
321   //// send performlist
322   //QStringList performList = networkSettings["Perform"].toString().split( "\n" );
323   //int count = performList.count();
324   //for(int a = 0; a < count; a++) {
325   //  if(!performList[a].isEmpty() ) {
326   //    userInput(network, "", performList[a]);
327   //  }
328   //}
329 }
330
331 /* RPL_ISUPPORT */
332 // TODO Complete 005 handling, also use sensible defaults for non-sent stuff
333 void IrcServerHandler::handle005(QString prefix, QStringList params) {
334   Q_UNUSED(prefix)
335   QString rpl_isupport_suffix = params.takeLast();
336   if(rpl_isupport_suffix.toLower() != QString("are supported by this server")) {
337     qWarning() << "Received invalid RPL_ISUPPORT! Suffix is:" << rpl_isupport_suffix << "Excpected: are supported by this server";
338     return;
339   }
340   
341   foreach(QString param, params) {
342     QString key = param.section("=", 0, 0);
343     QString value = param.section("=", 1);
344     networkInfo()->addSupport(key, value);
345   }
346 }
347
348
349 /* RPL_NOTOPIC */
350 void IrcServerHandler::handle331(QString prefix, QStringList params) {
351   Q_UNUSED(prefix)
352   networkInfo()->ircChannel(params[0])->setTopic(QString());
353   emit displayMsg(Message::Server, params[0], tr("No topic is set for %1.").arg(params[0]));
354 }
355
356 /* RPL_TOPIC */
357 void IrcServerHandler::handle332(QString prefix, QStringList params) {
358   Q_UNUSED(prefix)
359   networkInfo()->ircChannel(params[0])->setTopic(params[1]);
360   emit displayMsg(Message::Server, params[0], tr("Topic for %1 is \"%2\"").arg(params[0]).arg(params[1]));
361 }
362
363 /* Topic set by... */
364 void IrcServerHandler::handle333(QString prefix, QStringList params) {
365   Q_UNUSED(prefix)
366   emit displayMsg(Message::Server, params[0], tr("Topic set by %1 on %2").arg(params[1]).arg(QDateTime::fromTime_t(params[2].toUInt()).toString()));
367 }
368
369 /* RPL_NAMREPLY */
370 void IrcServerHandler::handle353(QString prefix, QStringList params) {
371   Q_UNUSED(prefix)
372   params.removeFirst(); // either "=", "*" or "@" indicating a public, private or secret channel
373   QString channelname = params.takeFirst();
374
375   foreach(QString nick, params.takeFirst().split(' ')) {
376     QString mode = QString();
377
378     if(networkInfo()->prefixes().contains(nick[0])) {
379       mode = networkInfo()->prefixToMode(nick[0]);
380       nick = nick.mid(1);
381     }
382
383     IrcUser *ircuser = networkInfo()->newIrcUser(nick);
384     ircuser->joinChannel(channelname);
385
386     if(!mode.isNull())
387       networkInfo()->ircChannel(channelname)->addUserMode(ircuser, mode);
388   }
389 }
390
391 /* ERR_ERRONEUSNICKNAME */
392 void IrcServerHandler::handle432(QString prefix, QStringList params) {
393   Q_UNUSED(prefix)
394   Q_UNUSED(params)
395   emit displayMsg(Message::Error, "", tr("Your desired nickname contains illegal characters!"));
396   emit displayMsg(Message::Error, "", tr("Please use /nick <othernick> to continue your IRC-Session!"));
397   // FIXME!
398
399 //   if(params.size() < 2) {
400 //     // handle unreal-ircd bug, where unreal ircd doesnt supply a TARGET in ERR_ERRONEUSNICKNAME during registration phase:
401 //     // nick @@@
402 //     // :irc.scortum.moep.net 432  @@@ :Erroneous Nickname: Illegal characters
403 //     // correct server reply:
404 //     // :irc.scortum.moep.net 432 * @@@ :Erroneous Nickname: Illegal characters
405 //     emit displayMsg(Message::Error, "", tr("There is a nickname in your identity's nicklist which contains illegal characters"));
406 //     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"));
407 //     emit displayMsg(Message::Error, "", tr("Please use: /nick <othernick> to continue or clean up your nicklist"));
408 //   } else {
409 //     QString errnick = params[0];
410 //     emit displayMsg(Message::Error, "", tr("Nick %1 contains illegal characters").arg(errnick));
411 //     // if there is a problem while connecting to the server -> we handle it
412 //     // TODO rely on another source...
413 //     if(currentServer.isEmpty()) {
414 //       QStringList desiredNicks = identity["NickList"].toStringList();
415 //       int nextNick = desiredNicks.indexOf(errnick) + 1;
416 //       if (desiredNicks.size() > nextNick) {
417 //         putCmd("NICK", QStringList(desiredNicks[nextNick]));
418 //       } else {
419 //         emit displayMsg(Message::Error, "", tr("No free and valid nicks in nicklist found. use: /nick <othernick> to continue"));
420 //       }
421 //     }
422 //   }
423 }
424
425 /* ERR_NICKNAMEINUSE */
426 void IrcServerHandler::handle433(QString prefix, QStringList params) {
427   Q_UNUSED(prefix)
428   QString errnick = params[0];
429   emit displayMsg(Message::Error, "", tr("Nick %1 is already taken").arg(errnick));
430   emit displayMsg(Message::Error, "", tr("Please use /nick <othernick> to continue your IRC-Session!"));
431   // FIXME!
432   
433 //   // if there is a problem while connecting to the server -> we handle it
434 //   // TODO rely on another source...
435 //   if(currentServer.isEmpty()) {
436 //     QStringList desiredNicks = identity["NickList"].toStringList();
437 //     int nextNick = desiredNicks.indexOf(errnick) + 1;
438 //     if (desiredNicks.size() > nextNick) {
439 //       putCmd("NICK", QStringList(desiredNicks[nextNick]));
440 //     } else {
441 //       emit displayMsg(Message::Error, "", tr("No free and valid nicks in nicklist found. use: /nick <othernick> to continue"));
442 //     }
443 //   }
444 }
445
446 /***********************************************************************************/
447
448