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