dfb3009863cede934cbc7fc82837a9db8eda1277
[quassel.git] / src / core / ircserverhandler.cpp
1 /***************************************************************************
2  *   Copyright (C) 2005-10 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 #include "ircserverhandler.h"
21
22 #include "util.h"
23
24 #include "coresession.h"
25 #include "coreirclisthelper.h"
26 #include "coreidentity.h"
27 #include "ctcphandler.h"
28
29 #include "ircuser.h"
30 #include "coreircchannel.h"
31 #include "logger.h"
32
33 #include <QDebug>
34
35 #ifdef HAVE_QCA2
36 #  include "cipher.h"
37 #endif
38
39 IrcServerHandler::IrcServerHandler(CoreNetwork *parent)
40   : CoreBasicHandler(parent),
41     _whois(false)
42 {
43   connect(parent, SIGNAL(disconnected(NetworkId)), this, SLOT(destroyNetsplits()));
44 }
45
46 IrcServerHandler::~IrcServerHandler() {
47   destroyNetsplits();
48 }
49
50 /*! Handle a raw message string sent by the server. We try to find a suitable handler, otherwise we call a default handler. */
51 void IrcServerHandler::handleServerMsg(QByteArray msg) {
52   if(msg.isEmpty()) {
53     qWarning() << "Received empty string from server!";
54     return;
55   }
56
57   // Now we split the raw message into its various parts...
58   QString prefix = "";
59   QByteArray trailing;
60   QString cmd;
61
62   // First, check for a trailing parameter introduced by " :", since this might screw up splitting the msg
63   // NOTE: This assumes that this is true in raw encoding, but well, hopefully there are no servers running in japanese on protocol level...
64   int idx = msg.indexOf(" :");
65   if(idx >= 0) {
66     if(msg.length() > idx + 2)
67       trailing = msg.mid(idx + 2);
68     msg = msg.left(idx);
69   }
70   // OK, now it is safe to split...
71   QList<QByteArray> params = msg.split(' ');
72
73   // This could still contain empty elements due to (faulty?) ircds sending multiple spaces in a row
74   // Also, QByteArray is not nearly as convenient to work with as QString for such things :)
75   QList<QByteArray>::iterator iter = params.begin();
76   while(iter != params.end()) {
77     if(iter->isEmpty())
78       iter = params.erase(iter);
79     else
80       ++iter;
81   }
82
83   if(!trailing.isEmpty()) params << trailing;
84   if(params.count() < 1) {
85     qWarning() << "Received invalid string from server!";
86     return;
87   }
88
89   QString foo = serverDecode(params.takeFirst());
90
91   // with SASL, the command is 'AUTHENTICATE +' and we should check for this here.
92   /* obsolete because of events
93   if(foo == QString("AUTHENTICATE +")) {
94     handleAuthenticate();
95     return;
96   }
97   */
98   // a colon as the first chars indicates the existence of a prefix
99   if(foo[0] == ':') {
100     foo.remove(0, 1);
101     prefix = foo;
102     if(params.count() < 1) {
103       qWarning() << "Received invalid string from server!";
104       return;
105     }
106     foo = serverDecode(params.takeFirst());
107   }
108
109   // next string without a whitespace is the command
110   cmd = foo.trimmed().toUpper();
111
112   // numeric replies have the target as first param (RFC 2812 - 2.4). this is usually our own nick. Remove this!
113   uint num = cmd.toUInt();
114   if(num > 0) {
115     if(params.count() == 0) {
116       qWarning() << "Message received from server violates RFC and is ignored!" << msg;
117       return;
118     }
119     _target = serverDecode(params.takeFirst());
120   } else {
121     _target = QString();
122   }
123
124   // note that the IRC server is still alive
125   network()->resetPingTimeout();
126
127   // Now we try to find a handler for this message. BTW, I do love the Trolltech guys ;-)
128   handle(cmd, Q_ARG(QString, prefix), Q_ARG(QList<QByteArray>, params));
129 }
130
131
132 void IrcServerHandler::defaultHandler(QString cmd, const QString &prefix, const QList<QByteArray> &rawparams) {
133   // many commands are handled by the event system now
134   Q_UNUSED(cmd)
135   Q_UNUSED(prefix)
136   Q_UNUSED(rawparams)
137 }
138
139 //******************************/
140 // IRC SERVER HANDLER
141 //******************************/
142
143 void IrcServerHandler::handleJoin(const QString &prefix, const QList<QByteArray> &params) {
144   if(!checkParamCount("IrcServerHandler::handleJoin()", params, 1))
145     return;
146
147   QString channel = serverDecode(params[0]);
148   IrcUser *ircuser = network()->updateNickFromMask(prefix);
149
150   bool handledByNetsplit = false;
151   if(!_netsplits.empty()) {
152     foreach(Netsplit* n, _netsplits) {
153       handledByNetsplit = n->userJoined(prefix, channel);
154       if(handledByNetsplit)
155         break;
156     }
157   }
158
159   // normal join
160   if(!handledByNetsplit) {
161     emit displayMsg(Message::Join, BufferInfo::ChannelBuffer, channel, channel, prefix);
162     ircuser->joinChannel(channel);
163   }
164   //qDebug() << "IrcServerHandler::handleJoin()" << prefix << params;
165
166   if(network()->isMe(ircuser)) {
167     network()->setChannelJoined(channel);
168     putCmd("MODE", params[0]); // we want to know the modes of the channel we just joined, so we ask politely
169   }
170 }
171
172 void IrcServerHandler::handleMode(const QString &prefix, const QList<QByteArray> &params) {
173   if(!checkParamCount("IrcServerHandler::handleMode()", params, 2))
174     return;
175
176   if(network()->isChannelName(serverDecode(params[0]))) {
177     // Channel Modes
178     emit displayMsg(Message::Mode, BufferInfo::ChannelBuffer, serverDecode(params[0]), serverDecode(params).join(" "), prefix);
179
180     IrcChannel *channel = network()->ircChannel(params[0]);
181     if(!channel) {
182       // we received mode information for a channel we're not in. that means probably we've just been kicked out or something like that
183       // anyways: we don't have a place to store the data --> discard the info.
184       return;
185     }
186
187     QString modes = params[1];
188     bool add = true;
189     int paramOffset = 2;
190     for(int c = 0; c < modes.length(); c++) {
191       if(modes[c] == '+') {
192         add = true;
193         continue;
194       }
195       if(modes[c] == '-') {
196         add = false;
197         continue;
198       }
199
200       if(network()->prefixModes().contains(modes[c])) {
201         // user channel modes (op, voice, etc...)
202         if(paramOffset < params.count()) {
203           IrcUser *ircUser = network()->ircUser(params[paramOffset]);
204           if(!ircUser) {
205             qWarning() << Q_FUNC_INFO << "Unknown IrcUser:" << params[paramOffset];
206           } else {
207             if(add) {
208               bool handledByNetsplit = false;
209               if(!_netsplits.empty()) {
210                 foreach(Netsplit* n, _netsplits) {
211                   handledByNetsplit = n->userAlreadyJoined(ircUser->hostmask(), channel->name());
212                   if(handledByNetsplit) {
213                     n->addMode(ircUser->hostmask(), channel->name(), QString(modes[c]));
214                     break;
215                   }
216                 }
217               }
218               if(!handledByNetsplit)
219                 channel->addUserMode(ircUser, QString(modes[c]));
220             }
221             else
222               channel->removeUserMode(ircUser, QString(modes[c]));
223           }
224         } else {
225           qWarning() << "Received MODE with too few parameters:" << serverDecode(params);
226         }
227         paramOffset++;
228       } else {
229         // regular channel modes
230         QString value;
231         Network::ChannelModeType modeType = network()->channelModeType(modes[c]);
232         if(modeType == Network::A_CHANMODE || modeType == Network::B_CHANMODE || (modeType == Network::C_CHANMODE && add)) {
233           if(paramOffset < params.count()) {
234             value = params[paramOffset];
235           } else {
236             qWarning() << "Received MODE with too few parameters:" << serverDecode(params);
237           }
238           paramOffset++;
239         }
240
241         if(add)
242           channel->addChannelMode(modes[c], value);
243         else
244           channel->removeChannelMode(modes[c], value);
245       }
246     }
247
248   } else {
249     // pure User Modes
250     IrcUser *ircUser = network()->newIrcUser(params[0]);
251     QString modeString(serverDecode(params[1]));
252     QString addModes;
253     QString removeModes;
254     bool add = false;
255     for(int c = 0; c < modeString.count(); c++) {
256       if(modeString[c] == '+') {
257         add = true;
258         continue;
259       }
260       if(modeString[c] == '-') {
261         add = false;
262         continue;
263       }
264       if(add)
265         addModes += modeString[c];
266       else
267         removeModes += modeString[c];
268     }
269     if(!addModes.isEmpty())
270       ircUser->addUserModes(addModes);
271     if(!removeModes.isEmpty())
272       ircUser->removeUserModes(removeModes);
273
274     if(network()->isMe(ircUser)) {
275       network()->updatePersistentModes(addModes, removeModes);
276     }
277
278     // FIXME: redirect
279     emit displayMsg(Message::Mode, BufferInfo::StatusBuffer, "", serverDecode(params).join(" "), prefix);
280   }
281 }
282
283 void IrcServerHandler::handleNotice(const QString &prefix, const QList<QByteArray> &params) {
284   if(!checkParamCount("IrcServerHandler::handleNotice()", params, 2))
285     return;
286
287
288   QStringList targets = serverDecode(params[0]).split(',', QString::SkipEmptyParts);
289   QStringList::const_iterator targetIter;
290   for(targetIter = targets.constBegin(); targetIter != targets.constEnd(); targetIter++) {
291     QString target = *targetIter;
292
293     // special treatment for welcome messages like:
294     // :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
295     if(!network()->isChannelName(target)) {
296       QString msg = serverDecode(params[1]);
297       QRegExp welcomeRegExp("^\\[([^\\]]+)\\] ");
298       if(welcomeRegExp.indexIn(msg) != -1) {
299         QString channelname = welcomeRegExp.cap(1);
300         msg = msg.mid(welcomeRegExp.matchedLength());
301         CoreIrcChannel *chan = static_cast<CoreIrcChannel *>(network()->ircChannel(channelname)); // we only have CoreIrcChannels in the core, so this cast is safe
302         if(chan && !chan->receivedWelcomeMsg()) {
303           chan->setReceivedWelcomeMsg();
304           emit displayMsg(Message::Notice, BufferInfo::ChannelBuffer, channelname, msg, prefix);
305           continue;
306         }
307       }
308     }
309
310     if(prefix.isEmpty() || target == "AUTH") {
311       target = "";
312     } else {
313       if(!target.isEmpty() && network()->prefixes().contains(target[0]))
314         target = target.mid(1);
315       if(!network()->isChannelName(target))
316         target = nickFromMask(prefix);
317     }
318
319     network()->ctcpHandler()->parse(Message::Notice, prefix, target, params[1]);
320   }
321
322 }
323
324 void IrcServerHandler::handlePing(const QString &prefix, const QList<QByteArray> &params) {
325   Q_UNUSED(prefix);
326   putCmd("PONG", params);
327 }
328
329 void IrcServerHandler::handlePrivmsg(const QString &prefix, const QList<QByteArray> &params) {
330   if(!checkParamCount("IrcServerHandler::handlePrivmsg()", params, 1))
331     return;
332
333   IrcUser *ircuser = network()->updateNickFromMask(prefix);
334   if(!ircuser) {
335     qWarning() << "IrcServerHandler::handlePrivmsg(): Unknown IrcUser!";
336     return;
337   }
338
339   if(params.isEmpty()) {
340     qWarning() << "IrcServerHandler::handlePrivmsg(): received PRIVMSG without target or message from:" << prefix;
341     return;
342   }
343
344   QString senderNick = nickFromMask(prefix);
345
346   QByteArray msg = params.count() < 2
347     ? QByteArray("")
348     : params[1];
349
350   QStringList targets = serverDecode(params[0]).split(',', QString::SkipEmptyParts);
351   QStringList::const_iterator targetIter;
352   for(targetIter = targets.constBegin(); targetIter != targets.constEnd(); targetIter++) {
353     const QString &target = network()->isChannelName(*targetIter)
354       ? *targetIter
355       : senderNick;
356
357 #ifdef HAVE_QCA2
358     msg = decrypt(target, msg);
359 #endif
360     // it's possible to pack multiple privmsgs into one param using ctcp
361     // - > we let the ctcpHandler do the work
362     network()->ctcpHandler()->parse(Message::Plain, prefix, target, msg);
363   }
364 }
365
366 void IrcServerHandler::handleQuit(const QString &prefix, const QList<QByteArray> &params) {
367   IrcUser *ircuser = network()->updateNickFromMask(prefix);
368   if(!ircuser) return;
369
370   QString msg;
371   if(params.count() > 0)
372     msg = userDecode(ircuser->nick(), params[0]);
373
374   // check if netsplit
375   if(Netsplit::isNetsplit(msg)) {
376     Netsplit *n;
377     if(!_netsplits.contains(msg)) {
378       n = new Netsplit();
379       connect(n, SIGNAL(finished()), this, SLOT(handleNetsplitFinished()));
380       connect(n, SIGNAL(netsplitJoin(const QString&, const QStringList&, const QStringList&, const QString&)),
381               this, SLOT(handleNetsplitJoin(const QString&, const QStringList&, const QStringList&, const QString&)));
382       connect(n, SIGNAL(netsplitQuit(const QString&, const QStringList&, const QString&)),
383               this, SLOT(handleNetsplitQuit(const QString&, const QStringList&, const QString&)));
384       connect(n, SIGNAL(earlyJoin(const QString&, const QStringList&, const QStringList&)),
385               this, SLOT(handleEarlyNetsplitJoin(const QString&, const QStringList&, const QStringList&)));
386       _netsplits.insert(msg, n);
387     }
388     else {
389       n = _netsplits[msg];
390     }
391     // add this user to the netsplit
392     n->userQuit(prefix, ircuser->channels(),msg);
393   }
394   // normal quit
395   else {
396     foreach(QString channel, ircuser->channels())
397       emit displayMsg(Message::Quit, BufferInfo::ChannelBuffer, channel, msg, prefix);
398     ircuser->quit();
399   }
400 }
401
402 /* RPL_CHANNELMODEIS - "<channel> <mode> <mode params>" */
403 void IrcServerHandler::handle324(const QString &prefix, const QList<QByteArray> &params) {
404   Q_UNUSED(prefix);
405   handleMode(prefix, params);
406 }
407
408 /* ERR_ERRONEUSNICKNAME */
409 void IrcServerHandler::handle432(const QString &prefix, const QList<QByteArray> &params) {
410   Q_UNUSED(prefix);
411
412   QString errnick;
413   if(params.size() < 2) {
414     // handle unreal-ircd bug, where unreal ircd doesnt supply a TARGET in ERR_ERRONEUSNICKNAME during registration phase:
415     // nick @@@
416     // :irc.scortum.moep.net 432  @@@ :Erroneous Nickname: Illegal characters
417     // correct server reply:
418     // :irc.scortum.moep.net 432 * @@@ :Erroneous Nickname: Illegal characters
419     errnick = target();
420   } else {
421     errnick = params[0];
422   }
423   emit displayMsg(Message::Error, BufferInfo::StatusBuffer, "", tr("Nick %1 contains illegal characters").arg(errnick));
424   tryNextNick(errnick, true /* erroneus */);
425 }
426
427 /* ERR_NICKNAMEINUSE */
428 void IrcServerHandler::handle433(const QString &prefix, const QList<QByteArray> &params) {
429   Q_UNUSED(prefix);
430   if(!checkParamCount("IrcServerHandler::handle433()", params, 1))
431     return;
432
433   QString errnick = serverDecode(params[0]);
434   emit displayMsg(Message::Error, BufferInfo::StatusBuffer, "", tr("Nick already in use: %1").arg(errnick));
435
436   // if there is a problem while connecting to the server -> we handle it
437   // but only if our connection has not been finished yet...
438   if(!network()->currentServer().isEmpty())
439     return;
440
441   tryNextNick(errnick);
442 }
443
444 /* ERR_UNAVAILRESOURCE */
445 void IrcServerHandler::handle437(const QString &prefix, const QList<QByteArray> &params) {
446   Q_UNUSED(prefix);
447   if(!checkParamCount("IrcServerHandler::handle437()", params, 1))
448     return;
449
450   QString errnick = serverDecode(params[0]);
451   emit displayMsg(Message::Error, BufferInfo::StatusBuffer, "", tr("Nick/channel is temporarily unavailable: %1").arg(errnick));
452
453   // if there is a problem while connecting to the server -> we handle it
454   // but only if our connection has not been finished yet...
455   if(!network()->currentServer().isEmpty())
456     return;
457
458   if(!network()->isChannelName(errnick))
459     tryNextNick(errnick);
460 }
461
462 /* Handle signals from Netsplit objects  */
463
464 void IrcServerHandler::handleNetsplitJoin(const QString &channel, const QStringList &users, const QStringList &modes, const QString& quitMessage)
465 {
466   IrcChannel *ircChannel = network()->ircChannel(channel);
467   if(!ircChannel) {
468     return;
469   }
470   QList<IrcUser *> ircUsers;
471   QStringList newModes = modes;
472   QStringList newUsers = users;
473
474   foreach(QString user, users) {
475     IrcUser *iu = network()->ircUser(nickFromMask(user));
476     if(iu)
477       ircUsers.append(iu);
478     else { // the user already quit
479       int idx = users.indexOf(user);
480       newUsers.removeAt(idx);
481       newModes.removeAt(idx);
482     }
483   }
484
485   QString msg = newUsers.join("#:#").append("#:#").append(quitMessage);
486   emit displayMsg(Message::NetsplitJoin, BufferInfo::ChannelBuffer, channel, msg);
487   ircChannel->joinIrcUsers(ircUsers, newModes);
488 }
489
490 void IrcServerHandler::handleNetsplitQuit(const QString &channel, const QStringList &users, const QString& quitMessage)
491 {
492   QString msg = users.join("#:#").append("#:#").append(quitMessage);
493   emit displayMsg(Message::NetsplitQuit, BufferInfo::ChannelBuffer, channel, msg);
494   foreach(QString user, users) {
495     IrcUser *iu = network()->ircUser(nickFromMask(user));
496     if(iu)
497       iu->quit();
498   }
499 }
500
501 void IrcServerHandler::handleEarlyNetsplitJoin(const QString &channel, const QStringList &users, const QStringList &modes) {
502   IrcChannel *ircChannel = network()->ircChannel(channel);
503   if(!ircChannel) {
504     qDebug() << "handleEarlyNetsplitJoin(): channel " << channel << " invalid";
505     return;
506   }
507   QList<IrcUser *> ircUsers;
508   QStringList newModes = modes;
509
510   foreach(QString user, users) {
511     IrcUser *iu = network()->updateNickFromMask(user);
512     if(iu) {
513       ircUsers.append(iu);
514       emit displayMsg(Message::Join, BufferInfo::ChannelBuffer, channel, channel, user);
515     }
516     else {
517       newModes.removeAt(users.indexOf(user));
518     }
519   }
520   ircChannel->joinIrcUsers(ircUsers, newModes);
521 }
522 void IrcServerHandler::handleNetsplitFinished()
523 {
524   Netsplit* n = qobject_cast<Netsplit*>(sender());
525   _netsplits.remove(_netsplits.key(n));
526   n->deleteLater();
527 }
528
529 /* */
530
531 // FIXME networkConnection()->setChannelKey("") for all ERR replies indicating that a JOIN went wrong
532 //       mostly, these are codes in the 47x range
533
534 /* */
535
536 void IrcServerHandler::tryNextNick(const QString &errnick, bool erroneus) {
537   QStringList desiredNicks = coreSession()->identity(network()->identity())->nicks();
538   int nextNickIdx = desiredNicks.indexOf(errnick) + 1;
539   QString nextNick;
540   if(nextNickIdx > 0 && desiredNicks.size() > nextNickIdx) {
541     nextNick = desiredNicks[nextNickIdx];
542   } else {
543     if(erroneus) {
544       emit displayMsg(Message::Error, BufferInfo::StatusBuffer, "", tr("No free and valid nicks in nicklist found. use: /nick <othernick> to continue"));
545       return;
546     } else {
547       nextNick = errnick + "_";
548     }
549   }
550   putCmd("NICK", serverEncode(nextNick));
551 }
552
553 bool IrcServerHandler::checkParamCount(const QString &methodName, const QList<QByteArray> &params, int minParams) {
554   if(params.count() < minParams) {
555     qWarning() << qPrintable(methodName) << "requires" << minParams << "parameters but received only" << params.count() << serverDecode(params);
556     return false;
557   } else {
558     return true;
559   }
560 }
561
562 void IrcServerHandler::destroyNetsplits() {
563   qDeleteAll(_netsplits);
564   _netsplits.clear();
565 }
566
567 #ifdef HAVE_QCA2
568 QByteArray IrcServerHandler::decrypt(const QString &bufferName, const QByteArray &message_, bool isTopic) {
569   if(message_.isEmpty())
570     return message_;
571
572   Cipher *cipher = network()->cipher(bufferName);
573   if(!cipher)
574     return message_;
575
576   QByteArray message = message_;
577   message = isTopic? cipher->decryptTopic(message) : cipher->decrypt(message);
578   return message;
579 }
580 #endif