Port IrcServerHandler::defaultHandler() to the event backend
[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   if(foo == QString("AUTHENTICATE +")) {
93     handleAuthenticate();
94     return;
95   }
96
97   // a colon as the first chars indicates the existence of a prefix
98   if(foo[0] == ':') {
99     foo.remove(0, 1);
100     prefix = foo;
101     if(params.count() < 1) {
102       qWarning() << "Received invalid string from server!";
103       return;
104     }
105     foo = serverDecode(params.takeFirst());
106   }
107
108   // next string without a whitespace is the command
109   cmd = foo.trimmed().toUpper();
110
111   // numeric replies have the target as first param (RFC 2812 - 2.4). this is usually our own nick. Remove this!
112   uint num = cmd.toUInt();
113   if(num > 0) {
114     if(params.count() == 0) {
115       qWarning() << "Message received from server violates RFC and is ignored!" << msg;
116       return;
117     }
118     _target = serverDecode(params.takeFirst());
119   } else {
120     _target = QString();
121   }
122
123   // note that the IRC server is still alive
124   network()->resetPingTimeout();
125
126   // Now we try to find a handler for this message. BTW, I do love the Trolltech guys ;-)
127   handle(cmd, Q_ARG(QString, prefix), Q_ARG(QList<QByteArray>, params));
128 }
129
130
131 void IrcServerHandler::defaultHandler(QString cmd, const QString &prefix, const QList<QByteArray> &rawparams) {
132   // we assume that all this happens in server encoding
133   QStringList params = serverDecode(rawparams);
134   uint num = cmd.toUInt();
135   // numeric commands are handled by the event system now
136   if(!num) {
137     emit displayMsg(Message::Error, BufferInfo::StatusBuffer, "", QString("Unknown: ") + cmd + " " + params.join(" "), prefix);
138     //qDebug() << prefix <<":"<<cmd<<params;
139   }
140 }
141
142 //******************************/
143 // IRC SERVER HANDLER
144 //******************************/
145 void IrcServerHandler::handleInvite(const QString &prefix, const QList<QByteArray> &params) {
146   if(!checkParamCount("IrcServerHandler::handleInvite()", params, 2))
147     return;
148 //   qDebug() << "IrcServerHandler::handleInvite()" << prefix << params;
149
150   IrcUser *ircuser = network()->updateNickFromMask(prefix);
151   if(!ircuser) {
152     return;
153   }
154
155   QString channel = serverDecode(params[1]);
156
157   emit displayMsg(Message::Invite, BufferInfo::StatusBuffer, "", tr("%1 invited you to channel %2").arg(ircuser->nick()).arg(channel));
158 }
159
160 void IrcServerHandler::handleJoin(const QString &prefix, const QList<QByteArray> &params) {
161   if(!checkParamCount("IrcServerHandler::handleJoin()", params, 1))
162     return;
163
164   QString channel = serverDecode(params[0]);
165   IrcUser *ircuser = network()->updateNickFromMask(prefix);
166
167   bool handledByNetsplit = false;
168   if(!_netsplits.empty()) {
169     foreach(Netsplit* n, _netsplits) {
170       handledByNetsplit = n->userJoined(prefix, channel);
171       if(handledByNetsplit)
172         break;
173     }
174   }
175
176   // normal join
177   if(!handledByNetsplit) {
178     emit displayMsg(Message::Join, BufferInfo::ChannelBuffer, channel, channel, prefix);
179     ircuser->joinChannel(channel);
180   }
181   //qDebug() << "IrcServerHandler::handleJoin()" << prefix << params;
182
183   if(network()->isMe(ircuser)) {
184     network()->setChannelJoined(channel);
185     putCmd("MODE", params[0]); // we want to know the modes of the channel we just joined, so we ask politely
186   }
187 }
188
189 void IrcServerHandler::handleKick(const QString &prefix, const QList<QByteArray> &params) {
190   if(!checkParamCount("IrcServerHandler::handleKick()", params, 2))
191     return;
192
193   network()->updateNickFromMask(prefix);
194   IrcUser *victim = network()->ircUser(params[1]);
195   if(!victim)
196     return;
197
198   QString channel = serverDecode(params[0]);
199   victim->partChannel(channel);
200
201   QString msg;
202   if(params.count() > 2) // someone got a reason!
203     msg = QString("%1 %2").arg(victim->nick()).arg(channelDecode(channel, params[2]));
204   else
205     msg = victim->nick();
206
207   emit displayMsg(Message::Kick, BufferInfo::ChannelBuffer, channel, msg, prefix);
208   //if(network()->isMe(victim)) network()->setKickedFromChannel(channel);
209 }
210
211 void IrcServerHandler::handleMode(const QString &prefix, const QList<QByteArray> &params) {
212   if(!checkParamCount("IrcServerHandler::handleMode()", params, 2))
213     return;
214
215   if(network()->isChannelName(serverDecode(params[0]))) {
216     // Channel Modes
217     emit displayMsg(Message::Mode, BufferInfo::ChannelBuffer, serverDecode(params[0]), serverDecode(params).join(" "), prefix);
218
219     IrcChannel *channel = network()->ircChannel(params[0]);
220     if(!channel) {
221       // we received mode information for a channel we're not in. that means probably we've just been kicked out or something like that
222       // anyways: we don't have a place to store the data --> discard the info.
223       return;
224     }
225
226     QString modes = params[1];
227     bool add = true;
228     int paramOffset = 2;
229     for(int c = 0; c < modes.length(); c++) {
230       if(modes[c] == '+') {
231         add = true;
232         continue;
233       }
234       if(modes[c] == '-') {
235         add = false;
236         continue;
237       }
238
239       if(network()->prefixModes().contains(modes[c])) {
240         // user channel modes (op, voice, etc...)
241         if(paramOffset < params.count()) {
242           IrcUser *ircUser = network()->ircUser(params[paramOffset]);
243           if(!ircUser) {
244             qWarning() << Q_FUNC_INFO << "Unknown IrcUser:" << params[paramOffset];
245           } else {
246             if(add) {
247               bool handledByNetsplit = false;
248               if(!_netsplits.empty()) {
249                 foreach(Netsplit* n, _netsplits) {
250                   handledByNetsplit = n->userAlreadyJoined(ircUser->hostmask(), channel->name());
251                   if(handledByNetsplit) {
252                     n->addMode(ircUser->hostmask(), channel->name(), QString(modes[c]));
253                     break;
254                   }
255                 }
256               }
257               if(!handledByNetsplit)
258                 channel->addUserMode(ircUser, QString(modes[c]));
259             }
260             else
261               channel->removeUserMode(ircUser, QString(modes[c]));
262           }
263         } else {
264           qWarning() << "Received MODE with too few parameters:" << serverDecode(params);
265         }
266         paramOffset++;
267       } else {
268         // regular channel modes
269         QString value;
270         Network::ChannelModeType modeType = network()->channelModeType(modes[c]);
271         if(modeType == Network::A_CHANMODE || modeType == Network::B_CHANMODE || (modeType == Network::C_CHANMODE && add)) {
272           if(paramOffset < params.count()) {
273             value = params[paramOffset];
274           } else {
275             qWarning() << "Received MODE with too few parameters:" << serverDecode(params);
276           }
277           paramOffset++;
278         }
279
280         if(add)
281           channel->addChannelMode(modes[c], value);
282         else
283           channel->removeChannelMode(modes[c], value);
284       }
285     }
286
287   } else {
288     // pure User Modes
289     IrcUser *ircUser = network()->newIrcUser(params[0]);
290     QString modeString(serverDecode(params[1]));
291     QString addModes;
292     QString removeModes;
293     bool add = false;
294     for(int c = 0; c < modeString.count(); c++) {
295       if(modeString[c] == '+') {
296         add = true;
297         continue;
298       }
299       if(modeString[c] == '-') {
300         add = false;
301         continue;
302       }
303       if(add)
304         addModes += modeString[c];
305       else
306         removeModes += modeString[c];
307     }
308     if(!addModes.isEmpty())
309       ircUser->addUserModes(addModes);
310     if(!removeModes.isEmpty())
311       ircUser->removeUserModes(removeModes);
312
313     if(network()->isMe(ircUser)) {
314       network()->updatePersistentModes(addModes, removeModes);
315     }
316
317     // FIXME: redirect
318     emit displayMsg(Message::Mode, BufferInfo::StatusBuffer, "", serverDecode(params).join(" "), prefix);
319   }
320 }
321
322 void IrcServerHandler::handleNick(const QString &prefix, const QList<QByteArray> &params) {
323   if(!checkParamCount("IrcServerHandler::handleNick()", params, 1))
324     return;
325
326   IrcUser *ircuser = network()->updateNickFromMask(prefix);
327   if(!ircuser) {
328     qWarning() << "IrcServerHandler::handleNick(): Unknown IrcUser!";
329     return;
330   }
331   QString newnick = serverDecode(params[0]);
332   QString oldnick = ircuser->nick();
333
334   QString sender = network()->isMyNick(oldnick)
335     ? newnick
336     : prefix;
337
338
339   // the order is cruicial
340   // otherwise the client would rename the buffer, see that the assigned ircuser doesn't match anymore
341   // and remove the ircuser from the querybuffer leading to a wrong on/offline state
342   ircuser->setNick(newnick);
343   coreSession()->renameBuffer(network()->networkId(), newnick, oldnick);
344
345   foreach(QString channel, ircuser->channels())
346     emit displayMsg(Message::Nick, BufferInfo::ChannelBuffer, channel, newnick, sender);
347 }
348
349 void IrcServerHandler::handleNotice(const QString &prefix, const QList<QByteArray> &params) {
350   if(!checkParamCount("IrcServerHandler::handleNotice()", params, 2))
351     return;
352
353
354   QStringList targets = serverDecode(params[0]).split(',', QString::SkipEmptyParts);
355   QStringList::const_iterator targetIter;
356   for(targetIter = targets.constBegin(); targetIter != targets.constEnd(); targetIter++) {
357     QString target = *targetIter;
358
359     // special treatment for welcome messages like:
360     // :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
361     if(!network()->isChannelName(target)) {
362       QString msg = serverDecode(params[1]);
363       QRegExp welcomeRegExp("^\\[([^\\]]+)\\] ");
364       if(welcomeRegExp.indexIn(msg) != -1) {
365         QString channelname = welcomeRegExp.cap(1);
366         msg = msg.mid(welcomeRegExp.matchedLength());
367         CoreIrcChannel *chan = static_cast<CoreIrcChannel *>(network()->ircChannel(channelname)); // we only have CoreIrcChannels in the core, so this cast is safe
368         if(chan && !chan->receivedWelcomeMsg()) {
369           chan->setReceivedWelcomeMsg();
370           emit displayMsg(Message::Notice, BufferInfo::ChannelBuffer, channelname, msg, prefix);
371           continue;
372         }
373       }
374     }
375
376     if(prefix.isEmpty() || target == "AUTH") {
377       target = "";
378     } else {
379       if(!target.isEmpty() && network()->prefixes().contains(target[0]))
380         target = target.mid(1);
381       if(!network()->isChannelName(target))
382         target = nickFromMask(prefix);
383     }
384
385     network()->ctcpHandler()->parse(Message::Notice, prefix, target, params[1]);
386   }
387
388 }
389
390 void IrcServerHandler::handlePart(const QString &prefix, const QList<QByteArray> &params) {
391   if(!checkParamCount("IrcServerHandler::handlePart()", params, 1))
392     return;
393
394   IrcUser *ircuser = network()->updateNickFromMask(prefix);
395   QString channel = serverDecode(params[0]);
396   if(!ircuser) {
397     qWarning() << "IrcServerHandler::handlePart(): Unknown IrcUser!";
398     return;
399   }
400
401   ircuser->partChannel(channel);
402
403   QString msg;
404   if(params.count() > 1)
405     msg = userDecode(ircuser->nick(), params[1]);
406
407   emit displayMsg(Message::Part, BufferInfo::ChannelBuffer, channel, msg, prefix);
408   if(network()->isMe(ircuser)) network()->setChannelParted(channel);
409 }
410
411 void IrcServerHandler::handlePing(const QString &prefix, const QList<QByteArray> &params) {
412   Q_UNUSED(prefix);
413   putCmd("PONG", params);
414 }
415
416 void IrcServerHandler::handlePong(const QString &prefix, const QList<QByteArray> &params) {
417   Q_UNUSED(prefix);
418   // the server is supposed to send back what we passed as param. and we send a timestamp
419   // but using quote and whatnought one can send arbitrary pings, so we have to do some sanity checks
420   if(params.count() < 2)
421     return;
422
423   QString timestamp = serverDecode(params[1]);
424   QTime sendTime = QTime::fromString(timestamp, "hh:mm:ss.zzz");
425   if(!sendTime.isValid()) {
426     emit displayMsg(Message::Server, BufferInfo::StatusBuffer, "", "PONG " + serverDecode(params).join(" "), prefix);
427     return;
428   }
429
430   network()->setLatency(sendTime.msecsTo(QTime::currentTime()) / 2);
431 }
432
433 void IrcServerHandler::handlePrivmsg(const QString &prefix, const QList<QByteArray> &params) {
434   if(!checkParamCount("IrcServerHandler::handlePrivmsg()", params, 1))
435     return;
436
437   IrcUser *ircuser = network()->updateNickFromMask(prefix);
438   if(!ircuser) {
439     qWarning() << "IrcServerHandler::handlePrivmsg(): Unknown IrcUser!";
440     return;
441   }
442
443   if(params.isEmpty()) {
444     qWarning() << "IrcServerHandler::handlePrivmsg(): received PRIVMSG without target or message from:" << prefix;
445     return;
446   }
447
448   QString senderNick = nickFromMask(prefix);
449
450   QByteArray msg = params.count() < 2
451     ? QByteArray("")
452     : params[1];
453
454   QStringList targets = serverDecode(params[0]).split(',', QString::SkipEmptyParts);
455   QStringList::const_iterator targetIter;
456   for(targetIter = targets.constBegin(); targetIter != targets.constEnd(); targetIter++) {
457     const QString &target = network()->isChannelName(*targetIter)
458       ? *targetIter
459       : senderNick;
460
461 #ifdef HAVE_QCA2
462     msg = decrypt(target, msg);
463 #endif
464     // it's possible to pack multiple privmsgs into one param using ctcp
465     // - > we let the ctcpHandler do the work
466     network()->ctcpHandler()->parse(Message::Plain, prefix, target, msg);
467   }
468 }
469
470 void IrcServerHandler::handleQuit(const QString &prefix, const QList<QByteArray> &params) {
471   IrcUser *ircuser = network()->updateNickFromMask(prefix);
472   if(!ircuser) return;
473
474   QString msg;
475   if(params.count() > 0)
476     msg = userDecode(ircuser->nick(), params[0]);
477
478   // check if netsplit
479   if(Netsplit::isNetsplit(msg)) {
480     Netsplit *n;
481     if(!_netsplits.contains(msg)) {
482       n = new Netsplit();
483       connect(n, SIGNAL(finished()), this, SLOT(handleNetsplitFinished()));
484       connect(n, SIGNAL(netsplitJoin(const QString&, const QStringList&, const QStringList&, const QString&)),
485               this, SLOT(handleNetsplitJoin(const QString&, const QStringList&, const QStringList&, const QString&)));
486       connect(n, SIGNAL(netsplitQuit(const QString&, const QStringList&, const QString&)),
487               this, SLOT(handleNetsplitQuit(const QString&, const QStringList&, const QString&)));
488       connect(n, SIGNAL(earlyJoin(const QString&, const QStringList&, const QStringList&)),
489               this, SLOT(handleEarlyNetsplitJoin(const QString&, const QStringList&, const QStringList&)));
490       _netsplits.insert(msg, n);
491     }
492     else {
493       n = _netsplits[msg];
494     }
495     // add this user to the netsplit
496     n->userQuit(prefix, ircuser->channels(),msg);
497   }
498   // normal quit
499   else {
500     foreach(QString channel, ircuser->channels())
501       emit displayMsg(Message::Quit, BufferInfo::ChannelBuffer, channel, msg, prefix);
502     ircuser->quit();
503   }
504 }
505
506 void IrcServerHandler::handleTopic(const QString &prefix, const QList<QByteArray> &params) {
507   if(!checkParamCount("IrcServerHandler::handleTopic()", params, 1))
508     return;
509
510   IrcUser *ircuser = network()->updateNickFromMask(prefix);
511   if(!ircuser)
512     return;
513
514   IrcChannel *channel = network()->ircChannel(serverDecode(params[0]));
515   if(!channel)
516     return;
517
518   QString topic;
519   if(params.count() > 1) {
520     QByteArray rawTopic = params[1];
521 #ifdef HAVE_QCA2
522     rawTopic = decrypt(channel->name(), rawTopic, true);
523 #endif
524     topic = channelDecode(channel->name(), rawTopic);
525   }
526
527   channel->setTopic(topic);
528
529   emit displayMsg(Message::Topic, BufferInfo::ChannelBuffer, channel->name(), tr("%1 has changed topic for %2 to: \"%3\"").arg(ircuser->nick()).arg(channel->name()).arg(topic));
530 }
531
532 void IrcServerHandler::handleCap(const QString &prefix, const QList<QByteArray> &params) {
533     // for SASL, there will only be a single param of 'sasl', however you can check here for
534     // additional CAP messages (ls, multi-prefix, et cetera).
535
536     Q_UNUSED(prefix);
537
538     if(params.size() == 3) {
539         QString param = serverDecode(params[2]);
540         if(param == QString("sasl")) {  // SASL Ready
541             network()->putRawLine(serverEncode("AUTHENTICATE PLAIN"));  // Only working with PLAIN atm, blowfish later
542         }
543     }
544 }
545
546 void IrcServerHandler::handleAuthenticate() {
547     QString construct = network()->saslAccount();
548     construct.append(QChar(QChar::Null));
549     construct.append(network()->saslAccount());
550     construct.append(QChar(QChar::Null));
551     construct.append(network()->saslPassword());
552     QByteArray saslData = QByteArray(construct.toAscii().toBase64());
553     saslData.prepend(QString("AUTHENTICATE ").toAscii());
554     network()->putRawLine(saslData);
555 }
556
557 /* RPL_WELCOME */
558 void IrcServerHandler::handle001(const QString &prefix, const QList<QByteArray> &params) {
559   network()->setCurrentServer(prefix);
560
561   if(params.isEmpty()) {
562     emit displayMsg(Message::Error, BufferInfo::StatusBuffer, "", QString("%1 didn't supply a valid welcome message... expect some serious issues..."));
563   }
564   // there should be only one param: "Welcome to the Internet Relay Network <nick>!<user>@<host>"
565   QString param = serverDecode(params[0]);
566   QString myhostmask = param.section(' ', -1, -1);
567
568   network()->setMyNick(nickFromMask(myhostmask));
569
570   emit displayMsg(Message::Server, BufferInfo::StatusBuffer, "", param, prefix);
571 }
572
573 /* RPL_ISUPPORT */
574 // TODO Complete 005 handling, also use sensible defaults for non-sent stuff
575 void IrcServerHandler::handle005(const QString &prefix, const QList<QByteArray> &params) {
576   Q_UNUSED(prefix);
577   const int numParams = params.size();
578   if(numParams == 0) {
579     emit displayMsg(Message::Error, BufferInfo::StatusBuffer, "", tr("Received RPL_ISUPPORT (005) without parameters!"), prefix);
580     return;
581   }
582
583   emit displayMsg(Message::Server, BufferInfo::StatusBuffer, "", serverDecode(params).join(" "), prefix);
584
585   QString rpl_isupport_suffix = serverDecode(params.last());
586   if(!rpl_isupport_suffix.toLower().contains("are supported by this server")) {
587     emit displayMsg(Message::Error, BufferInfo::StatusBuffer, "", tr("Received non RFC compliant RPL_ISUPPORT: this can lead to unexpected behavior!"), prefix);
588   }
589
590   QString rawSupport;
591   QString key, value;
592   for(int i = 0; i < numParams - 1; i++) {
593     QString rawSupport = serverDecode(params[i]);
594     QString key = rawSupport.section("=", 0, 0);
595     QString value = rawSupport.section("=", 1);
596     network()->addSupport(key, value);
597   }
598
599   /* determine our prefixes here to get an accurate result */
600   network()->determinePrefixes();
601 }
602
603 /* RPL_UMODEIS - "<user_modes> [<user_mode_params>]" */
604 void IrcServerHandler::handle221(const QString &prefix, const QList<QByteArray> &params) {
605   Q_UNUSED(prefix)
606   //TODO: save information in network object
607   emit displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("%1").arg(serverDecode(params).join(" ")));
608 }
609
610 /* RPL_STATSCONN - "Highest connection cout: 8000 (7999 clients)" */
611 void IrcServerHandler::handle250(const QString &prefix, const QList<QByteArray> &params) {
612   Q_UNUSED(prefix)
613   //TODO: save information in network object
614   emit displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("%1").arg(serverDecode(params).join(" ")));
615 }
616
617 /* RPL_LOCALUSERS - "Current local user: 5024  Max: 7999 */
618 void IrcServerHandler::handle265(const QString &prefix, const QList<QByteArray> &params) {
619   Q_UNUSED(prefix)
620   //TODO: save information in network object
621   emit displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("%1").arg(serverDecode(params).join(" ")));
622 }
623
624 /* RPL_GLOBALUSERS - "Current global users: 46093  Max: 47650" */
625 void IrcServerHandler::handle266(const QString &prefix, const QList<QByteArray> &params) {
626   Q_UNUSED(prefix)
627   //TODO: save information in network object
628   emit displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("%1").arg(serverDecode(params).join(" ")));
629 }
630
631 /*
632 WHOIS-Message:
633    Replies 311 - 313, 317 - 319 are all replies generated in response to a WHOIS message.
634   and 301 (RPL_AWAY)
635               "<nick> :<away message>"
636 WHO-Message:
637    Replies 352 and 315 paired are used to answer a WHO message.
638
639 WHOWAS-Message:
640    Replies 314 and 369 are responses to a WHOWAS message.
641
642 */
643
644
645 /*   RPL_AWAY - "<nick> :<away message>" */
646 void IrcServerHandler::handle301(const QString &prefix, const QList<QByteArray> &params) {
647   Q_UNUSED(prefix);
648   if(!checkParamCount("IrcServerHandler::handle301()", params, 2))
649     return;
650
651
652   QString nickName = serverDecode(params[0]);
653   QString awayMessage = userDecode(nickName, params[1]);
654
655   IrcUser *ircuser = network()->ircUser(nickName);
656   if(ircuser) {
657     ircuser->setAwayMessage(awayMessage);
658     ircuser->setAway(true);
659   }
660
661   // FIXME: proper redirection needed
662   if(_whois) {
663     emit displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("[Whois] %1 is away: \"%2\"").arg(nickName).arg(awayMessage));
664   } else {
665     if(ircuser) {
666       int now = QDateTime::currentDateTime().toTime_t();
667       int silenceTime = 60;
668       if(ircuser->lastAwayMessage() + silenceTime < now) {
669         emit displayMsg(Message::Server, BufferInfo::QueryBuffer, params[0], tr("%1 is away: \"%2\"").arg(nickName).arg(awayMessage));
670       }
671       ircuser->setLastAwayMessage(now);
672     } else {
673       // probably should not happen
674       emit displayMsg(Message::Server, BufferInfo::QueryBuffer, params[0], tr("%1 is away: \"%2\"").arg(nickName).arg(awayMessage));
675     }
676   }
677 }
678
679 // 305  RPL_UNAWAY
680 //      ":You are no longer marked as being away"
681 void IrcServerHandler::handle305(const QString &prefix, const QList<QByteArray> &params) {
682   Q_UNUSED(prefix);
683   IrcUser *me = network()->me();
684   if(me)
685     me->setAway(false);
686
687   if(!network()->autoAwayActive()) {
688     if(!params.isEmpty())
689       emit displayMsg(Message::Server, BufferInfo::StatusBuffer, "", serverDecode(params[0]));
690   } else {
691     network()->setAutoAwayActive(false);
692   }
693 }
694
695 // 306  RPL_NOWAWAY
696 //      ":You have been marked as being away"
697 void IrcServerHandler::handle306(const QString &prefix, const QList<QByteArray> &params) {
698   Q_UNUSED(prefix);
699   IrcUser *me = network()->me();
700   if(me)
701     me->setAway(true);
702
703   if(!params.isEmpty() && !network()->autoAwayActive())
704     emit displayMsg(Message::Server, BufferInfo::StatusBuffer, "", serverDecode(params[0]));
705 }
706
707 /* RPL_WHOISSERVICE - "<user> is registered nick" */
708 void IrcServerHandler::handle307(const QString &prefix, const QList<QByteArray> &params) {
709   Q_UNUSED(prefix)
710   if(!checkParamCount("IrcServerHandler::handle307()", params, 1))
711     return;
712
713   QString whoisServiceReply = serverDecode(params).join(" ");
714   IrcUser *ircuser = network()->ircUser(serverDecode(params[0]));
715   if(ircuser) {
716     ircuser->setWhoisServiceReply(whoisServiceReply);
717   }
718   emit displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("[Whois] %1").arg(whoisServiceReply));
719 }
720
721 /* RPL_SUSERHOST - "<user> is available for help." */
722 void IrcServerHandler::handle310(const QString &prefix, const QList<QByteArray> &params) {
723   Q_UNUSED(prefix)
724   if(!checkParamCount("IrcServerHandler::handle310()", params, 1))
725     return;
726
727   QString suserHost = serverDecode(params).join(" ");
728   IrcUser *ircuser = network()->ircUser(serverDecode(params[0]));
729   if(ircuser) {
730     ircuser->setSuserHost(suserHost);
731   }
732   emit displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("[Whois] %1").arg(suserHost));
733 }
734
735 /*  RPL_WHOISUSER - "<nick> <user> <host> * :<real name>" */
736 void IrcServerHandler::handle311(const QString &prefix, const QList<QByteArray> &params) {
737   Q_UNUSED(prefix)
738   if(!checkParamCount("IrcServerHandler::handle311()", params, 3))
739     return;
740
741   _whois = true;
742   IrcUser *ircuser = network()->ircUser(serverDecode(params[0]));
743   if(ircuser) {
744     ircuser->setUser(serverDecode(params[1]));
745     ircuser->setHost(serverDecode(params[2]));
746     ircuser->setRealName(serverDecode(params.last()));
747     emit displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("[Whois] %1 is %2 (%3)") .arg(ircuser->nick()).arg(ircuser->hostmask()).arg(ircuser->realName()));
748   } else {
749     QString host = QString("%1!%2@%3").arg(serverDecode(params[0])).arg(serverDecode(params[1])).arg(serverDecode(params[2]));
750     emit displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("[Whois] %1 is %2 (%3)") .arg(serverDecode(params[0])).arg(host).arg(serverDecode(params.last())));
751   }
752 }
753
754 /*  RPL_WHOISSERVER -  "<nick> <server> :<server info>" */
755 void IrcServerHandler::handle312(const QString &prefix, const QList<QByteArray> &params) {
756   Q_UNUSED(prefix)
757   if(!checkParamCount("IrcServerHandler::handle312()", params, 2))
758     return;
759
760   IrcUser *ircuser = network()->ircUser(serverDecode(params[0]));
761   if(ircuser) {
762     ircuser->setServer(serverDecode(params[1]));
763   }
764
765   QString returnString = tr("%1 is online via %2 (%3)").arg(serverDecode(params[0])).arg(serverDecode(params[1])).arg(serverDecode(params.last()));
766   if(_whois) {
767     emit displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("[Whois] %1").arg(returnString));
768   } else {
769     emit displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("[Whowas] %1").arg(returnString));
770   }
771 }
772
773 /*  RPL_WHOISOPERATOR - "<nick> :is an IRC operator" */
774 void IrcServerHandler::handle313(const QString &prefix, const QList<QByteArray> &params) {
775   Q_UNUSED(prefix)
776   if(!checkParamCount("IrcServerHandler::handle313()", params, 1))
777     return;
778
779   IrcUser *ircuser = network()->ircUser(serverDecode(params[0]));
780   if(ircuser) {
781     ircuser->setIrcOperator(params.last());
782   }
783   emit displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("[Whois] %1").arg(serverDecode(params).join(" ")));
784 }
785
786 /*  RPL_WHOWASUSER - "<nick> <user> <host> * :<real name>" */
787 void IrcServerHandler::handle314(const QString &prefix, const QList<QByteArray> &params) {
788   Q_UNUSED(prefix)
789   if(!checkParamCount("IrcServerHandler::handle314()", params, 3))
790     return;
791
792   QString nick = serverDecode(params[0]);
793   QString hostmask = QString("%1@%2").arg(serverDecode(params[1])).arg(serverDecode(params[2]));
794   QString realName = serverDecode(params.last());
795   emit displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("[Whowas] %1 was %2 (%3)").arg(nick).arg(hostmask).arg(realName));
796 }
797
798 /*  RPL_ENDOFWHO: "<name> :End of WHO list" */
799 void IrcServerHandler::handle315(const QString &prefix, const QList<QByteArray> &params) {
800   Q_UNUSED(prefix);
801   if(!checkParamCount("IrcServerHandler::handle315()", params, 1))
802     return;
803
804   QStringList p = serverDecode(params);
805   if(network()->setAutoWhoDone(p[0])) {
806     return; // stay silent
807   }
808   p.takeLast(); // should be "End of WHO list"
809   emit displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("[Who] End of /WHO list for %1").arg(p.join(" ")));
810 }
811
812 /*  RPL_WHOISIDLE - "<nick> <integer> :seconds idle"
813    (real life: "<nick> <integer> <integer> :seconds idle, signon time) */
814 void IrcServerHandler::handle317(const QString &prefix, const QList<QByteArray> &params) {
815   Q_UNUSED(prefix);
816   if(!checkParamCount("IrcServerHandler::handle317()", params, 2))
817     return;
818
819   QString nick = serverDecode(params[0]);
820   IrcUser *ircuser = network()->ircUser(nick);
821
822   QDateTime now = QDateTime::currentDateTime();
823   int idleSecs = serverDecode(params[1]).toInt();
824   idleSecs *= -1;
825
826   if(ircuser) {
827     ircuser->setIdleTime(now.addSecs(idleSecs));
828     if(params.size() > 3) { // if we have more then 3 params we have the above mentioned "real life" situation
829       int loginTime = serverDecode(params[2]).toInt();
830       ircuser->setLoginTime(QDateTime::fromTime_t(loginTime));
831       emit displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("[Whois] %1 is logged in since %2").arg(ircuser->nick()).arg(ircuser->loginTime().toString()));
832     }
833     emit displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("[Whois] %1 is idling for %2 (%3)").arg(ircuser->nick()).arg(secondsToString(ircuser->idleTime().secsTo(now))).arg(ircuser->idleTime().toString()));
834   } else {
835     QDateTime idleSince = now.addSecs(idleSecs);
836     if (params.size() > 3) { // we have a signon time
837       int loginTime = serverDecode(params[2]).toInt();
838       QDateTime datetime = QDateTime::fromTime_t(loginTime);
839       emit displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("[Whois] %1 is logged in since %2").arg(nick).arg(datetime.toString()));
840     }
841     emit displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("[Whois] %1 is idling for %2 (%3)").arg(nick).arg(secondsToString(idleSince.secsTo(now))).arg(idleSince.toString()));
842   }
843 }
844
845 /*  RPL_ENDOFWHOIS - "<nick> :End of WHOIS list" */
846 void IrcServerHandler::handle318(const QString &prefix, const QList<QByteArray> &params) {
847   Q_UNUSED(prefix)
848   _whois = false;
849   QStringList parameter = serverDecode(params);
850   parameter.removeFirst();
851   emit displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("[Whois] %1").arg(parameter.join(" ")));
852 }
853
854 /*  RPL_WHOISCHANNELS - "<nick> :*( ( "@" / "+" ) <channel> " " )" */
855 void IrcServerHandler::handle319(const QString &prefix, const QList<QByteArray> &params) {
856   Q_UNUSED(prefix)
857   if(!checkParamCount("IrcServerHandler::handle319()", params, 2))
858     return;
859
860   QString nick = serverDecode(params.first());
861   QStringList op;
862   QStringList voice;
863   QStringList user;
864   foreach (QString channel, serverDecode(params.last()).split(" ")) {
865     if(channel.startsWith("@"))
866        op.append(channel.remove(0,1));
867     else if(channel.startsWith("+"))
868       voice.append(channel.remove(0,1));
869     else
870       user.append(channel);
871   }
872   if(!user.isEmpty())
873     emit displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("[Whois] %1 is a user on channels: %2").arg(nick).arg(user.join(" ")));
874   if(!voice.isEmpty())
875     emit displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("[Whois] %1 has voice on channels: %2").arg(nick).arg(voice.join(" ")));
876   if(!op.isEmpty())
877     emit displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("[Whois] %1 is an operator on channels: %2").arg(nick).arg(op.join(" ")));
878 }
879
880 /*  RPL_WHOISVIRT - "<nick> is identified to services" */
881 void IrcServerHandler::handle320(const QString &prefix, const QList<QByteArray> &params) {
882   Q_UNUSED(prefix);
883   emit displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("[Whois] %1").arg(serverDecode(params).join(" ")));
884 }
885
886 /* RPL_LIST -  "<channel> <# visible> :<topic>" */
887 void IrcServerHandler::handle322(const QString &prefix, const QList<QByteArray> &params) {
888   Q_UNUSED(prefix)
889   QString channelName;
890   quint32 userCount = 0;
891   QString topic;
892
893   int paramCount = params.count();
894   switch(paramCount) {
895   case 3:
896     topic = serverDecode(params[2]);
897   case 2:
898     userCount = serverDecode(params[1]).toUInt();
899   case 1:
900     channelName = serverDecode(params[0]);
901   default:
902     break;
903   }
904   if(!coreSession()->ircListHelper()->addChannel(network()->networkId(), channelName, userCount, topic))
905     emit displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Channel %1 has %2 users. Topic is: %3").arg(channelName).arg(userCount).arg(topic));
906 }
907
908 /* RPL_LISTEND ":End of LIST" */
909 void IrcServerHandler::handle323(const QString &prefix, const QList<QByteArray> &params) {
910   Q_UNUSED(prefix)
911   Q_UNUSED(params)
912
913   if(!coreSession()->ircListHelper()->endOfChannelList(network()->networkId()))
914     emit displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("End of channel list"));
915 }
916
917 /* RPL_CHANNELMODEIS - "<channel> <mode> <mode params>" */
918 void IrcServerHandler::handle324(const QString &prefix, const QList<QByteArray> &params) {
919   Q_UNUSED(prefix);
920   handleMode(prefix, params);
921 }
922
923 /* RPL_??? - "<channel> <homepage> */
924 void IrcServerHandler::handle328(const QString &prefix, const QList<QByteArray> &params) {
925   Q_UNUSED(prefix);
926   if(!checkParamCount("IrcServerHandler::handle328()", params, 2))
927     return;
928
929   QString channel = serverDecode(params[0]);
930   QString homepage = serverDecode(params[1]);
931
932   emit displayMsg(Message::Server, BufferInfo::ChannelBuffer, channel, tr("Homepage for %1 is %2").arg(channel, homepage));
933 }
934
935
936 /* RPL_??? - "<channel> <creation time (unix)>" */
937 void IrcServerHandler::handle329(const QString &prefix, const QList<QByteArray> &params) {
938   Q_UNUSED(prefix);
939   if(!checkParamCount("IrcServerHandler::handle329()", params, 2))
940     return;
941
942   QString channel = serverDecode(params[0]);
943   uint unixtime = params[1].toUInt();
944   if(!unixtime) {
945     qWarning() << Q_FUNC_INFO << "received invalid timestamp:" << params[1];
946     return;
947   }
948   QDateTime time = QDateTime::fromTime_t(unixtime);
949
950   emit displayMsg(Message::Server, BufferInfo::ChannelBuffer, channel, tr("Channel %1 created on %2").arg(channel, time.toString()));
951 }
952
953 /*  RPL_WHOISACCOUNT: "<nick> <account> :is authed as */
954 void IrcServerHandler::handle330(const QString &prefix, const QList<QByteArray> &params) {
955   Q_UNUSED(prefix);
956   if(!checkParamCount("IrcServerHandler::handle330()", params, 3))
957     return;
958
959   QString nick = serverDecode(params[0]);
960   QString account = serverDecode(params[1]);
961
962   emit displayMsg(Message::Server, BufferInfo::StatusBuffer, "",  tr("[Whois] %1 is authed as %2").arg(nick).arg(account));
963 }
964
965 /* RPL_NOTOPIC */
966 void IrcServerHandler::handle331(const QString &prefix, const QList<QByteArray> &params) {
967   Q_UNUSED(prefix);
968   if(!checkParamCount("IrcServerHandler::handle331()", params, 1))
969     return;
970
971   QString channel = serverDecode(params[0]);
972   IrcChannel *chan = network()->ircChannel(channel);
973   if(chan)
974     chan->setTopic(QString());
975
976   emit displayMsg(Message::Topic, BufferInfo::ChannelBuffer, channel, tr("No topic is set for %1.").arg(channel));
977 }
978
979 /* RPL_TOPIC */
980 void IrcServerHandler::handle332(const QString &prefix, const QList<QByteArray> &params) {
981   Q_UNUSED(prefix);
982   if(!checkParamCount("IrcServerHandler::handle332()", params, 2))
983     return;
984
985   QString channel = serverDecode(params[0]);
986   QByteArray rawTopic = params[1];
987 #ifdef HAVE_QCA2
988   rawTopic = decrypt(channel, rawTopic, true);
989 #endif
990   QString topic = channelDecode(channel, rawTopic);
991
992   IrcChannel *chan = network()->ircChannel(channel);
993   if(chan)
994     chan->setTopic(topic);
995
996   emit displayMsg(Message::Topic, BufferInfo::ChannelBuffer, channel, tr("Topic for %1 is \"%2\"").arg(channel, topic));
997 }
998
999 /* Topic set by... */
1000 void IrcServerHandler::handle333(const QString &prefix, const QList<QByteArray> &params) {
1001   Q_UNUSED(prefix);
1002   if(!checkParamCount("IrcServerHandler::handle333()", params, 3))
1003     return;
1004
1005   QString channel = serverDecode(params[0]);
1006   emit displayMsg(Message::Topic, BufferInfo::ChannelBuffer, channel,
1007                   tr("Topic set by %1 on %2") .arg(serverDecode(params[1]), QDateTime::fromTime_t(channelDecode(channel, params[2]).toUInt()).toString()));
1008 }
1009
1010 /* RPL_INVITING - "<nick> <channel>*/
1011 void IrcServerHandler::handle341(const QString &prefix, const QList<QByteArray> &params) {
1012   Q_UNUSED(prefix);
1013   if(!checkParamCount("IrcServerHandler::handle341()", params, 2))
1014     return;
1015
1016   QString nick = serverDecode(params[0]);
1017
1018   IrcChannel *channel = network()->ircChannel(serverDecode(params[1]));
1019   if(!channel) {
1020     qWarning() << "IrcServerHandler::handle341(): unknown channel:" << params[1];
1021     return;
1022   }
1023
1024   emit displayMsg(Message::Server, BufferInfo::ChannelBuffer, channel->name(), tr("%1 has been invited to %2").arg(nick).arg(channel->name()));
1025 }
1026
1027 /*  RPL_WHOREPLY: "<channel> <user> <host> <server> <nick>
1028               ( "H" / "G" > ["*"] [ ( "@" / "+" ) ] :<hopcount> <real name>" */
1029 void IrcServerHandler::handle352(const QString &prefix, const QList<QByteArray> &params) {
1030   Q_UNUSED(prefix)
1031   if(!checkParamCount("IrcServerHandler::handle352()", params, 6))
1032     return;
1033
1034   QString channel = serverDecode(params[0]);
1035   IrcUser *ircuser = network()->ircUser(serverDecode(params[4]));
1036   if(ircuser) {
1037     ircuser->setUser(serverDecode(params[1]));
1038     ircuser->setHost(serverDecode(params[2]));
1039
1040     bool away = serverDecode(params[5]).startsWith("G") ? true : false;
1041     ircuser->setAway(away);
1042     ircuser->setServer(serverDecode(params[3]));
1043     ircuser->setRealName(serverDecode(params.last()).section(" ", 1));
1044   }
1045
1046   if(!network()->isAutoWhoInProgress(channel)) {
1047     emit displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("[Who] %1").arg(serverDecode(params).join(" ")));
1048   }
1049 }
1050
1051 /* RPL_NAMREPLY */
1052 void IrcServerHandler::handle353(const QString &prefix, const QList<QByteArray> &params) {
1053   Q_UNUSED(prefix);
1054   if(!checkParamCount("IrcServerHandler::handle353()", params, 3))
1055     return;
1056
1057   // param[0] is either "=", "*" or "@" indicating a public, private or secret channel
1058   // we don't use this information at the time beeing
1059   QString channelname = serverDecode(params[1]);
1060
1061   IrcChannel *channel = network()->ircChannel(channelname);
1062   if(!channel) {
1063     qWarning() << "IrcServerHandler::handle353(): received unknown target channel:" << channelname;
1064     return;
1065   }
1066
1067   QStringList nicks;
1068   QStringList modes;
1069
1070   foreach(QString nick, serverDecode(params[2]).split(' ')) {
1071     QString mode = QString();
1072
1073     if(network()->prefixes().contains(nick[0])) {
1074       mode = network()->prefixToMode(nick[0]);
1075       nick = nick.mid(1);
1076     }
1077
1078     nicks << nick;
1079     modes << mode;
1080   }
1081
1082   channel->joinIrcUsers(nicks, modes);
1083 }
1084
1085 /*  RPL_ENDOFWHOWAS - "<nick> :End of WHOWAS" */
1086 void IrcServerHandler::handle369(const QString &prefix, const QList<QByteArray> &params) {
1087   Q_UNUSED(prefix)
1088   emit displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("[Whowas] %1").arg(serverDecode(params).join(" ")));
1089 }
1090
1091 /* ERR_ERRONEUSNICKNAME */
1092 void IrcServerHandler::handle432(const QString &prefix, const QList<QByteArray> &params) {
1093   Q_UNUSED(prefix);
1094
1095   QString errnick;
1096   if(params.size() < 2) {
1097     // handle unreal-ircd bug, where unreal ircd doesnt supply a TARGET in ERR_ERRONEUSNICKNAME during registration phase:
1098     // nick @@@
1099     // :irc.scortum.moep.net 432  @@@ :Erroneous Nickname: Illegal characters
1100     // correct server reply:
1101     // :irc.scortum.moep.net 432 * @@@ :Erroneous Nickname: Illegal characters
1102     errnick = target();
1103   } else {
1104     errnick = params[0];
1105   }
1106   emit displayMsg(Message::Error, BufferInfo::StatusBuffer, "", tr("Nick %1 contains illegal characters").arg(errnick));
1107   tryNextNick(errnick, true /* erroneus */);
1108 }
1109
1110 /* ERR_NICKNAMEINUSE */
1111 void IrcServerHandler::handle433(const QString &prefix, const QList<QByteArray> &params) {
1112   Q_UNUSED(prefix);
1113   if(!checkParamCount("IrcServerHandler::handle433()", params, 1))
1114     return;
1115
1116   QString errnick = serverDecode(params[0]);
1117   emit displayMsg(Message::Error, BufferInfo::StatusBuffer, "", tr("Nick already in use: %1").arg(errnick));
1118
1119   // if there is a problem while connecting to the server -> we handle it
1120   // but only if our connection has not been finished yet...
1121   if(!network()->currentServer().isEmpty())
1122     return;
1123
1124   tryNextNick(errnick);
1125 }
1126
1127 /* ERR_UNAVAILRESOURCE */
1128 void IrcServerHandler::handle437(const QString &prefix, const QList<QByteArray> &params) {
1129   Q_UNUSED(prefix);
1130   if(!checkParamCount("IrcServerHandler::handle437()", params, 1))
1131     return;
1132
1133   QString errnick = serverDecode(params[0]);
1134   emit displayMsg(Message::Error, BufferInfo::StatusBuffer, "", tr("Nick/channel is temporarily unavailable: %1").arg(errnick));
1135
1136   // if there is a problem while connecting to the server -> we handle it
1137   // but only if our connection has not been finished yet...
1138   if(!network()->currentServer().isEmpty())
1139     return;
1140
1141   if(!network()->isChannelName(errnick))
1142     tryNextNick(errnick);
1143 }
1144
1145 /* Handle signals from Netsplit objects  */
1146
1147 void IrcServerHandler::handleNetsplitJoin(const QString &channel, const QStringList &users, const QStringList &modes, const QString& quitMessage)
1148 {
1149   IrcChannel *ircChannel = network()->ircChannel(channel);
1150   if(!ircChannel) {
1151     return;
1152   }
1153   QList<IrcUser *> ircUsers;
1154   QStringList newModes = modes;
1155   QStringList newUsers = users;
1156
1157   foreach(QString user, users) {
1158     IrcUser *iu = network()->ircUser(nickFromMask(user));
1159     if(iu)
1160       ircUsers.append(iu);
1161     else { // the user already quit
1162       int idx = users.indexOf(user);
1163       newUsers.removeAt(idx);
1164       newModes.removeAt(idx);
1165     }
1166   }
1167
1168   QString msg = newUsers.join("#:#").append("#:#").append(quitMessage);
1169   emit displayMsg(Message::NetsplitJoin, BufferInfo::ChannelBuffer, channel, msg);
1170   ircChannel->joinIrcUsers(ircUsers, newModes);
1171 }
1172
1173 void IrcServerHandler::handleNetsplitQuit(const QString &channel, const QStringList &users, const QString& quitMessage)
1174 {
1175   QString msg = users.join("#:#").append("#:#").append(quitMessage);
1176   emit displayMsg(Message::NetsplitQuit, BufferInfo::ChannelBuffer, channel, msg);
1177   foreach(QString user, users) {
1178     IrcUser *iu = network()->ircUser(nickFromMask(user));
1179     if(iu)
1180       iu->quit();
1181   }
1182 }
1183
1184 void IrcServerHandler::handleEarlyNetsplitJoin(const QString &channel, const QStringList &users, const QStringList &modes) {
1185   IrcChannel *ircChannel = network()->ircChannel(channel);
1186   if(!ircChannel) {
1187     qDebug() << "handleEarlyNetsplitJoin(): channel " << channel << " invalid";
1188     return;
1189   }
1190   QList<IrcUser *> ircUsers;
1191   QStringList newModes = modes;
1192
1193   foreach(QString user, users) {
1194     IrcUser *iu = network()->updateNickFromMask(user);
1195     if(iu) {
1196       ircUsers.append(iu);
1197       emit displayMsg(Message::Join, BufferInfo::ChannelBuffer, channel, channel, user);
1198     }
1199     else {
1200       newModes.removeAt(users.indexOf(user));
1201     }
1202   }
1203   ircChannel->joinIrcUsers(ircUsers, newModes);
1204 }
1205 void IrcServerHandler::handleNetsplitFinished()
1206 {
1207   Netsplit* n = qobject_cast<Netsplit*>(sender());
1208   _netsplits.remove(_netsplits.key(n));
1209   n->deleteLater();
1210 }
1211
1212 /* */
1213
1214 // FIXME networkConnection()->setChannelKey("") for all ERR replies indicating that a JOIN went wrong
1215 //       mostly, these are codes in the 47x range
1216
1217 /* */
1218
1219 void IrcServerHandler::tryNextNick(const QString &errnick, bool erroneus) {
1220   QStringList desiredNicks = coreSession()->identity(network()->identity())->nicks();
1221   int nextNickIdx = desiredNicks.indexOf(errnick) + 1;
1222   QString nextNick;
1223   if(nextNickIdx > 0 && desiredNicks.size() > nextNickIdx) {
1224     nextNick = desiredNicks[nextNickIdx];
1225   } else {
1226     if(erroneus) {
1227       emit displayMsg(Message::Error, BufferInfo::StatusBuffer, "", tr("No free and valid nicks in nicklist found. use: /nick <othernick> to continue"));
1228       return;
1229     } else {
1230       nextNick = errnick + "_";
1231     }
1232   }
1233   putCmd("NICK", serverEncode(nextNick));
1234 }
1235
1236 bool IrcServerHandler::checkParamCount(const QString &methodName, const QList<QByteArray> &params, int minParams) {
1237   if(params.count() < minParams) {
1238     qWarning() << qPrintable(methodName) << "requires" << minParams << "parameters but received only" << params.count() << serverDecode(params);
1239     return false;
1240   } else {
1241     return true;
1242   }
1243 }
1244
1245 void IrcServerHandler::destroyNetsplits() {
1246   qDeleteAll(_netsplits);
1247   _netsplits.clear();
1248 }
1249
1250 #ifdef HAVE_QCA2
1251 QByteArray IrcServerHandler::decrypt(const QString &bufferName, const QByteArray &message_, bool isTopic) {
1252   if(message_.isEmpty())
1253     return message_;
1254
1255   Cipher *cipher = network()->cipher(bufferName);
1256   if(!cipher)
1257     return message_;
1258
1259   QByteArray message = message_;
1260   message = isTopic? cipher->decryptTopic(message) : cipher->decrypt(message);
1261   return message;
1262 }
1263 #endif