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