2eb7f6d9e41fe860c2720dbab6484b824d3c882c
[quassel.git] / src / core / coresessioneventprocessor.cpp
1 /***************************************************************************
2  *   Copyright (C) 2005-2010 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
21 #include "coresessioneventprocessor.h"
22
23 #include "coreirclisthelper.h"
24 #include "corenetwork.h"
25 #include "coresession.h"
26 #include "ctcpevent.h"
27 #include "ircevent.h"
28 #include "ircuser.h"
29 #include "messageevent.h"
30 #include "netsplit.h"
31 #include "quassel.h"
32
33 CoreSessionEventProcessor::CoreSessionEventProcessor(CoreSession *session)
34   : BasicHandler("handleCtcp", session),
35   _coreSession(session)
36 {
37   connect(coreSession(), SIGNAL(networkDisconnected(NetworkId)), this, SLOT(destroyNetsplits(NetworkId)));
38   connect(this, SIGNAL(newEvent(Event *)), coreSession()->eventManager(), SLOT(postEvent(Event *)));
39 }
40
41 bool CoreSessionEventProcessor::checkParamCount(IrcEvent *e, int minParams) {
42   if(e->params().count() < minParams) {
43     if(e->type() == EventManager::IrcEventNumeric) {
44       qWarning() << "Command " << static_cast<IrcEventNumeric *>(e)->number() << " requires " << minParams << "params, got: " << e->params();
45     } else {
46       QString name = coreSession()->eventManager()->enumName(e->type());
47       qWarning() << qPrintable(name) << "requires" << minParams << "params, got:" << e->params();
48     }
49     e->stop();
50     return false;
51   }
52   return true;
53 }
54
55 void CoreSessionEventProcessor::tryNextNick(NetworkEvent *e, const QString &errnick, bool erroneus) {
56   QStringList desiredNicks = coreSession()->identity(e->network()->identity())->nicks();
57   int nextNickIdx = desiredNicks.indexOf(errnick) + 1;
58   QString nextNick;
59   if(nextNickIdx > 0 && desiredNicks.size() > nextNickIdx) {
60     nextNick = desiredNicks[nextNickIdx];
61   } else {
62     if(erroneus) {
63       // FIXME Make this an ErrorEvent or something like that, so it's translated in the client
64       MessageEvent *msgEvent = new MessageEvent(Message::Error, e->network(),
65                                                 tr("No free and valid nicks in nicklist found. use: /nick <othernick> to continue"),
66                                                 QString(), QString(), Message::None, e->timestamp());
67       emit newEvent(msgEvent);
68       return;
69     } else {
70       nextNick = errnick + "_";
71     }
72   }
73   // FIXME Use a proper output event for this
74   coreNetwork(e)->putRawLine("NICK " + coreNetwork(e)->encodeServerString(nextNick));
75 }
76
77 void CoreSessionEventProcessor::processIrcEventNumeric(IrcEventNumeric *e) {
78   switch(e->number()) {
79
80   // CAP stuff
81   case 903: case 904: case 905: case 906: case 907:
82     qobject_cast<CoreNetwork *>(e->network())->putRawLine("CAP END");
83     break;
84
85   default:
86     break;
87   }
88 }
89
90 void CoreSessionEventProcessor::processIrcEventAuthenticate(IrcEvent *e) {
91   if(!checkParamCount(e, 1))
92     return;
93
94   if(e->params().at(0) != "+") {
95     qWarning() << "Invalid AUTHENTICATE" << e;
96     return;
97   }
98
99   CoreNetwork *net = coreNetwork(e);
100
101   QString construct = net->saslAccount();
102   construct.append(QChar(QChar::Null));
103   construct.append(net->saslAccount());
104   construct.append(QChar(QChar::Null));
105   construct.append(net->saslPassword());
106   QByteArray saslData = QByteArray(construct.toAscii().toBase64());
107   saslData.prepend("AUTHENTICATE ");
108   net->putRawLine(saslData);
109 }
110
111 void CoreSessionEventProcessor::processIrcEventCap(IrcEvent *e) {
112   // for SASL, there will only be a single param of 'sasl', however you can check here for
113   // additional CAP messages (ls, multi-prefix, et cetera).
114
115   if(e->params().count() == 3) {
116     if(e->params().at(2) == "sasl") {
117       // FIXME use event
118       coreNetwork(e)->putRawLine(coreNetwork(e)->serverEncode("AUTHENTICATE PLAIN")); // Only working with PLAIN atm, blowfish later
119     }
120   }
121 }
122
123 void CoreSessionEventProcessor::processIrcEventInvite(IrcEvent *e) {
124   if(checkParamCount(e, 2)) {
125     e->network()->updateNickFromMask(e->prefix());
126   }
127 }
128
129 void CoreSessionEventProcessor::processIrcEventJoin(IrcEvent *e) {
130   if(e->testFlag(EventManager::Fake)) // generated by handleEarlyNetsplitJoin
131     return;
132
133   if(!checkParamCount(e, 1))
134     return;
135
136   CoreNetwork *net = coreNetwork(e);
137   QString channel = e->params()[0];
138   IrcUser *ircuser = net->updateNickFromMask(e->prefix());
139
140   bool handledByNetsplit = false;
141   foreach(Netsplit* n, _netsplits.value(e->network())) {
142     handledByNetsplit = n->userJoined(e->prefix(), channel);
143     if(handledByNetsplit)
144       break;
145   }
146
147   if(!handledByNetsplit)
148     ircuser->joinChannel(channel);
149   else
150     e->setFlag(EventManager::Netsplit);
151
152   if(net->isMe(ircuser)) {
153     net->setChannelJoined(channel);
154      // FIXME use event
155     net->putRawLine(net->serverEncode("MODE " + channel)); // we want to know the modes of the channel we just joined, so we ask politely
156   }
157 }
158
159 void CoreSessionEventProcessor::lateProcessIrcEventKick(IrcEvent *e) {
160   if(checkParamCount(e, 2)) {
161     e->network()->updateNickFromMask(e->prefix());
162     IrcUser *victim = e->network()->ircUser(e->params().at(1));
163     if(victim) {
164       victim->partChannel(e->params().at(0));
165       //if(e->network()->isMe(victim)) e->network()->setKickedFromChannel(channel);
166     }
167   }
168 }
169
170 void CoreSessionEventProcessor::processIrcEventMode(IrcEvent *e) {
171   if(!checkParamCount(e, 2))
172     return;
173
174   if(e->network()->isChannelName(e->params().first())) {
175     // Channel Modes
176
177     IrcChannel *channel = e->network()->ircChannel(e->params()[0]);
178     if(!channel) {
179       // we received mode information for a channel we're not in. that means probably we've just been kicked out or something like that
180       // anyways: we don't have a place to store the data --> discard the info.
181       return;
182     }
183
184     QString modes = e->params()[1];
185     bool add = true;
186     int paramOffset = 2;
187     for(int c = 0; c < modes.length(); c++) {
188       if(modes[c] == '+') {
189         add = true;
190         continue;
191       }
192       if(modes[c] == '-') {
193         add = false;
194         continue;
195       }
196
197       if(e->network()->prefixModes().contains(modes[c])) {
198         // user channel modes (op, voice, etc...)
199         if(paramOffset < e->params().count()) {
200           IrcUser *ircUser = e->network()->ircUser(e->params()[paramOffset]);
201           if(!ircUser) {
202             qWarning() << Q_FUNC_INFO << "Unknown IrcUser:" << e->params()[paramOffset];
203           } else {
204             if(add) {
205               bool handledByNetsplit = false;
206               QHash<QString, Netsplit *> splits = _netsplits.value(e->network());
207               foreach(Netsplit* n, _netsplits.value(e->network())) {
208                 handledByNetsplit = n->userAlreadyJoined(ircUser->hostmask(), channel->name());
209                 if(handledByNetsplit) {
210                   n->addMode(ircUser->hostmask(), channel->name(), QString(modes[c]));
211                   break;
212                 }
213               }
214               if(!handledByNetsplit)
215                 channel->addUserMode(ircUser, QString(modes[c]));
216             }
217             else
218               channel->removeUserMode(ircUser, QString(modes[c]));
219           }
220         } else {
221           qWarning() << "Received MODE with too few parameters:" << e->params();
222         }
223         ++paramOffset;
224       } else {
225         // regular channel modes
226         QString value;
227         Network::ChannelModeType modeType = e->network()->channelModeType(modes[c]);
228         if(modeType == Network::A_CHANMODE || modeType == Network::B_CHANMODE || (modeType == Network::C_CHANMODE && add)) {
229           if(paramOffset < e->params().count()) {
230             value = e->params()[paramOffset];
231           } else {
232             qWarning() << "Received MODE with too few parameters:" << e->params();
233           }
234           ++paramOffset;
235         }
236
237         if(add)
238           channel->addChannelMode(modes[c], value);
239         else
240           channel->removeChannelMode(modes[c], value);
241       }
242     }
243
244   } else {
245     // pure User Modes
246     IrcUser *ircUser = e->network()->newIrcUser(e->params().first());
247     QString modeString(e->params()[1]);
248     QString addModes;
249     QString removeModes;
250     bool add = false;
251     for(int c = 0; c < modeString.count(); c++) {
252       if(modeString[c] == '+') {
253         add = true;
254         continue;
255       }
256       if(modeString[c] == '-') {
257         add = false;
258         continue;
259       }
260       if(add)
261         addModes += modeString[c];
262       else
263         removeModes += modeString[c];
264     }
265     if(!addModes.isEmpty())
266       ircUser->addUserModes(addModes);
267     if(!removeModes.isEmpty())
268       ircUser->removeUserModes(removeModes);
269
270     if(e->network()->isMe(ircUser)) {
271       coreNetwork(e)->updatePersistentModes(addModes, removeModes);
272     }
273   }
274 }
275
276 void CoreSessionEventProcessor::lateProcessIrcEventNick(IrcEvent *e) {
277   if(checkParamCount(e, 1)) {
278     IrcUser *ircuser = e->network()->updateNickFromMask(e->prefix());
279     if(!ircuser) {
280       qWarning() << Q_FUNC_INFO << "Unknown IrcUser!";
281       return;
282     }
283     QString newnick = e->params().at(0);
284     QString oldnick = ircuser->nick();
285
286     // the order is cruicial
287     // otherwise the client would rename the buffer, see that the assigned ircuser doesn't match anymore
288     // and remove the ircuser from the querybuffer leading to a wrong on/offline state
289     ircuser->setNick(newnick);
290     coreSession()->renameBuffer(e->networkId(), newnick, oldnick);
291   }
292 }
293
294 void CoreSessionEventProcessor::lateProcessIrcEventPart(IrcEvent *e) {
295   if(checkParamCount(e, 1)) {
296     IrcUser *ircuser = e->network()->updateNickFromMask(e->prefix());
297     if(!ircuser) {
298       qWarning() << Q_FUNC_INFO<< "Unknown IrcUser!";
299       return;
300     }
301     QString channel = e->params().at(0);
302     ircuser->partChannel(channel);
303     if(e->network()->isMe(ircuser))
304       qobject_cast<CoreNetwork *>(e->network())->setChannelParted(channel);
305   }
306 }
307
308 void CoreSessionEventProcessor::processIrcEventPing(IrcEvent *e) {
309   QString param = e->params().count()? e->params().first() : QString();
310   // FIXME use events
311   coreNetwork(e)->putRawLine("PONG " + coreNetwork(e)->serverEncode(param));
312 }
313
314 void CoreSessionEventProcessor::processIrcEventPong(IrcEvent *e) {
315   // the server is supposed to send back what we passed as param. and we send a timestamp
316   // but using quote and whatnought one can send arbitrary pings, so we have to do some sanity checks
317   if(checkParamCount(e, 2)) {
318     QString timestamp = e->params().at(1);
319     QTime sendTime = QTime::fromString(timestamp, "hh:mm:ss.zzz");
320     if(sendTime.isValid())
321       e->network()->setLatency(sendTime.msecsTo(QTime::currentTime()) / 2);
322   }
323 }
324
325 void CoreSessionEventProcessor::processIrcEventQuit(IrcEvent *e) {
326   IrcUser *ircuser = e->network()->updateNickFromMask(e->prefix());
327   if(!ircuser)
328     return;
329
330   QString msg;
331   if(e->params().count() > 0)
332     msg = e->params()[0];
333
334   // check if netsplit
335   if(Netsplit::isNetsplit(msg)) {
336     Netsplit *n;
337     if(!_netsplits[e->network()].contains(msg)) {
338       n = new Netsplit(e->network(), this);
339       connect(n, SIGNAL(finished()), this, SLOT(handleNetsplitFinished()));
340       connect(n, SIGNAL(netsplitJoin(Network*,QString,QStringList,QStringList,QString)),
341               this, SLOT(handleNetsplitJoin(Network*,QString,QStringList,QStringList,QString)));
342       connect(n, SIGNAL(netsplitQuit(Network*,QString,QStringList,QString)),
343               this, SLOT(handleNetsplitQuit(Network*,QString,QStringList,QString)));
344       connect(n, SIGNAL(earlyJoin(Network*,QString,QStringList,QStringList)),
345               this, SLOT(handleEarlyNetsplitJoin(Network*,QString,QStringList,QStringList)));
346       _netsplits[e->network()].insert(msg, n);
347     }
348     else {
349       n = _netsplits[e->network()][msg];
350     }
351     // add this user to the netsplit
352     n->userQuit(e->prefix(), ircuser->channels(), msg);
353     e->setFlag(EventManager::Netsplit);
354   }
355   // normal quit is handled in lateProcessIrcEventQuit()
356 }
357
358 void CoreSessionEventProcessor::lateProcessIrcEventQuit(IrcEvent *e) {
359   if(e->testFlag(EventManager::Netsplit))
360     return;
361
362   IrcUser *ircuser = e->network()->updateNickFromMask(e->prefix());
363   if(!ircuser)
364     return;
365
366   ircuser->quit();
367 }
368
369 void CoreSessionEventProcessor::processIrcEventTopic(IrcEvent *e) {
370   if(checkParamCount(e, 2)) {
371     e->network()->updateNickFromMask(e->prefix());
372     IrcChannel *channel = e->network()->ircChannel(e->params().at(0));
373     if(channel)
374       channel->setTopic(e->params().at(1));
375   }
376 }
377
378 /* RPL_WELCOME */
379 void CoreSessionEventProcessor::processIrcEvent001(IrcEvent *e) {
380   if(!checkParamCount(e, 1))
381     return;
382
383   QString myhostmask = e->params().at(0).section(' ', -1, -1);
384   e->network()->setCurrentServer(e->prefix());
385   e->network()->setMyNick(nickFromMask(myhostmask));
386 }
387
388 /* RPL_ISUPPORT */
389 // TODO Complete 005 handling, also use sensible defaults for non-sent stuff
390 void CoreSessionEventProcessor::processIrcEvent005(IrcEvent *e) {
391   if(!checkParamCount(e, 1))
392     return;
393
394   QString key, value;
395   for(int i = 0; i < e->params().count() - 1; i++) {
396     QString key = e->params()[i].section("=", 0, 0);
397     QString value = e->params()[i].section("=", 1);
398     e->network()->addSupport(key, value);
399   }
400
401   /* determine our prefixes here to get an accurate result */
402   e->network()->determinePrefixes();
403 }
404
405 /* RPL_UMODEIS - "<user_modes> [<user_mode_params>]" */
406 void CoreSessionEventProcessor::processIrcEvent221(IrcEvent *) {
407   // TODO: save information in network object
408 }
409
410 /* RPL_STATSCONN - "Highest connection cout: 8000 (7999 clients)" */
411 void CoreSessionEventProcessor::processIrcEvent250(IrcEvent *) {
412   // TODO: save information in network object
413 }
414
415 /* RPL_LOCALUSERS - "Current local user: 5024  Max: 7999 */
416 void CoreSessionEventProcessor::processIrcEvent265(IrcEvent *) {
417   // TODO: save information in network object
418 }
419
420 /* RPL_GLOBALUSERS - "Current global users: 46093  Max: 47650" */
421 void CoreSessionEventProcessor::processIrcEvent266(IrcEvent *) {
422   // TODO: save information in network object
423 }
424
425 /*
426 WHOIS-Message:
427    Replies 311 - 313, 317 - 319 are all replies generated in response to a WHOIS message.
428   and 301 (RPL_AWAY)
429               "<nick> :<away message>"
430 WHO-Message:
431    Replies 352 and 315 paired are used to answer a WHO message.
432
433 WHOWAS-Message:
434    Replies 314 and 369 are responses to a WHOWAS message.
435
436 */
437
438 /* RPL_AWAY - "<nick> :<away message>" */
439 void CoreSessionEventProcessor::processIrcEvent301(IrcEvent *e) {
440   if(!checkParamCount(e, 2))
441     return;
442
443   IrcUser *ircuser = e->network()->ircUser(e->params().at(0));
444   if(ircuser) {
445     ircuser->setAway(true);
446     ircuser->setAwayMessage(e->params().at(1));
447     //ircuser->setLastAwayMessage(now);
448   }
449 }
450
451 /* RPL_UNAWAY - ":You are no longer marked as being away" */
452 void CoreSessionEventProcessor::processIrcEvent305(IrcEvent *e) {
453   IrcUser *me = e->network()->me();
454   if(me)
455     me->setAway(false);
456
457   if(e->network()->autoAwayActive()) {
458     e->network()->setAutoAwayActive(false);
459     e->setFlag(EventManager::Silent);
460   }
461 }
462
463 /* RPL_NOWAWAY - ":You have been marked as being away" */
464 void CoreSessionEventProcessor::processIrcEvent306(IrcEvent *e) {
465   IrcUser *me = e->network()->me();
466   if(me)
467     me->setAway(true);
468 }
469
470 /* RPL_WHOISSERVICE - "<user> is registered nick" */
471 void CoreSessionEventProcessor::processIrcEvent307(IrcEvent *e) {
472   if(!checkParamCount(e, 1))
473     return;
474
475   IrcUser *ircuser = e->network()->ircUser(e->params().at(0));
476   if(ircuser)
477     ircuser->setWhoisServiceReply(e->params().join(" "));
478 }
479
480 /* RPL_SUSERHOST - "<user> is available for help." */
481 void CoreSessionEventProcessor::processIrcEvent310(IrcEvent *e) {
482   if(!checkParamCount(e, 1))
483     return;
484
485   IrcUser *ircuser = e->network()->ircUser(e->params().at(0));
486   if(ircuser)
487     ircuser->setSuserHost(e->params().join(" "));
488 }
489
490 /*  RPL_WHOISUSER - "<nick> <user> <host> * :<real name>" */
491 void CoreSessionEventProcessor::processIrcEvent311(IrcEvent *e) {
492   if(!checkParamCount(e, 3))
493     return;
494
495   IrcUser *ircuser = e->network()->ircUser(e->params().at(0));
496   if(ircuser) {
497     ircuser->setUser(e->params().at(1));
498     ircuser->setHost(e->params().at(2));
499     ircuser->setRealName(e->params().last());
500   }
501 }
502
503 /*  RPL_WHOISSERVER -  "<nick> <server> :<server info>" */
504 void CoreSessionEventProcessor::processIrcEvent312(IrcEvent *e) {
505   if(!checkParamCount(e, 2))
506     return;
507
508   IrcUser *ircuser = e->network()->ircUser(e->params().at(0));
509   if(ircuser)
510     ircuser->setServer(e->params().at(1));
511 }
512
513 /*  RPL_WHOISOPERATOR - "<nick> :is an IRC operator" */
514 void CoreSessionEventProcessor::processIrcEvent313(IrcEvent *e) {
515   if(!checkParamCount(e, 1))
516     return;
517
518   IrcUser *ircuser = e->network()->ircUser(e->params().at(0));
519   if(ircuser)
520     ircuser->setIrcOperator(e->params().last());
521 }
522
523 /*  RPL_ENDOFWHO: "<name> :End of WHO list" */
524 void CoreSessionEventProcessor::processIrcEvent315(IrcEvent *e) {
525   if(!checkParamCount(e, 1))
526     return;
527
528   if(coreNetwork(e)->setAutoWhoDone(e->params()[0]))
529     e->setFlag(EventManager::Silent);
530 }
531
532 /*  RPL_WHOISIDLE - "<nick> <integer> :seconds idle"
533    (real life: "<nick> <integer> <integer> :seconds idle, signon time) */
534 void CoreSessionEventProcessor::processIrcEvent317(IrcEvent *e) {
535   if(!checkParamCount(e, 2))
536     return;
537
538   QDateTime loginTime;
539
540   int idleSecs = e->params()[1].toInt();
541   if(e->params().count() > 3) { // if we have more then 3 params we have the above mentioned "real life" situation
542     int logintime = e->params()[2].toInt();
543     loginTime = QDateTime::fromTime_t(logintime);
544   }
545
546   IrcUser *ircuser = e->network()->ircUser(e->params()[0]);
547   if(ircuser) {
548     ircuser->setIdleTime(e->timestamp().addSecs(-idleSecs));
549     if(loginTime.isValid())
550       ircuser->setLoginTime(loginTime);
551   }
552 }
553
554 /* RPL_LIST -  "<channel> <# visible> :<topic>" */
555 void CoreSessionEventProcessor::processIrcEvent322(IrcEvent *e) {
556   if(!checkParamCount(e, 1))
557     return;
558
559   QString channelName;
560   quint32 userCount = 0;
561   QString topic;
562
563   switch(e->params().count()) {
564   case 3:
565     topic = e->params()[2];
566   case 2:
567     userCount = e->params()[1].toUInt();
568   case 1:
569     channelName = e->params()[0];
570   default:
571     break;
572   }
573   if(coreSession()->ircListHelper()->addChannel(e->networkId(), channelName, userCount, topic))
574     e->stop(); // consumed by IrcListHelper, so don't further process/show this event
575 }
576
577 /* RPL_LISTEND ":End of LIST" */
578 void CoreSessionEventProcessor::processIrcEvent323(IrcEvent *e) {
579   if(!checkParamCount(e, 1))
580     return;
581
582   if(coreSession()->ircListHelper()->endOfChannelList(e->networkId()))
583     e->stop(); // consumed by IrcListHelper, so don't further process/show this event
584 }
585
586 /* RPL_CHANNELMODEIS - "<channel> <mode> <mode params>" */
587 void CoreSessionEventProcessor::processIrcEvent324(IrcEvent *e) {
588   processIrcEventMode(e);
589 }
590
591 /* RPL_NOTOPIC */
592 void CoreSessionEventProcessor::processIrcEvent331(IrcEvent *e) {
593   if(!checkParamCount(e, 1))
594     return;
595
596   IrcChannel *chan = e->network()->ircChannel(e->params()[0]);
597   if(chan)
598     chan->setTopic(QString());
599 }
600
601 /* RPL_TOPIC */
602 void CoreSessionEventProcessor::processIrcEvent332(IrcEvent *e) {
603   if(!checkParamCount(e, 2))
604     return;
605
606   IrcChannel *chan = e->network()->ircChannel(e->params()[0]);
607   if(chan)
608     chan->setTopic(e->params()[1]);
609 }
610
611 /*  RPL_WHOREPLY: "<channel> <user> <host> <server> <nick>
612               ( "H" / "G" > ["*"] [ ( "@" / "+" ) ] :<hopcount> <real name>" */
613 void CoreSessionEventProcessor::processIrcEvent352(IrcEvent *e) {
614   if(!checkParamCount(e, 6))
615     return;
616
617   QString channel = e->params()[0];
618   IrcUser *ircuser = e->network()->ircUser(e->params()[4]);
619   if(ircuser) {
620     ircuser->setUser(e->params()[1]);
621     ircuser->setHost(e->params()[2]);
622
623     bool away = e->params()[5].startsWith("G");
624     ircuser->setAway(away);
625     ircuser->setServer(e->params()[3]);
626     ircuser->setRealName(e->params().last().section(" ", 1));
627   }
628
629   if(coreNetwork(e)->isAutoWhoInProgress(channel))
630     e->setFlag(EventManager::Silent);
631 }
632
633 /* RPL_NAMREPLY */
634 void CoreSessionEventProcessor::processIrcEvent353(IrcEvent *e) {
635   if(!checkParamCount(e, 3))
636     return;
637
638   // param[0] is either "=", "*" or "@" indicating a public, private or secret channel
639   // we don't use this information at the time beeing
640   QString channelname = e->params()[1];
641
642   IrcChannel *channel = e->network()->ircChannel(channelname);
643   if(!channel) {
644     qWarning() << Q_FUNC_INFO << "Received unknown target channel:" << channelname;
645     return;
646   }
647
648   QStringList nicks;
649   QStringList modes;
650
651   foreach(QString nick, e->params()[2].split(' ')) {
652     QString mode;
653
654     if(e->network()->prefixes().contains(nick[0])) {
655       mode = e->network()->prefixToMode(nick[0]);
656       nick = nick.mid(1);
657     }
658
659     nicks << nick;
660     modes << mode;
661   }
662
663   channel->joinIrcUsers(nicks, modes);
664 }
665
666 /* ERR_ERRONEUSNICKNAME */
667 void CoreSessionEventProcessor::processIrcEvent432(IrcEventNumeric *e) {
668   QString errnick;
669   if(e->params().count() < 2) {
670     // handle unreal-ircd bug, where unreal ircd doesnt supply a TARGET in ERR_ERRONEUSNICKNAME during registration phase:
671     // nick @@@
672     // :irc.scortum.moep.net 432  @@@ :Erroneous Nickname: Illegal characters
673     // correct server reply:
674     // :irc.scortum.moep.net 432 * @@@ :Erroneous Nickname: Illegal characters
675     e->params().prepend(e->target());
676     e->setTarget("*");
677   }
678   errnick = e->params()[0];
679
680   tryNextNick(e, errnick, true /* erroneus */);
681 }
682
683 /* ERR_NICKNAMEINUSE */
684 void CoreSessionEventProcessor::processIrcEvent433(IrcEventNumeric *e) {
685   if(!checkParamCount(e, 1))
686     return;
687
688   QString errnick = e->params().first();
689
690   // if there is a problem while connecting to the server -> we handle it
691   // but only if our connection has not been finished yet...
692   if(!e->network()->currentServer().isEmpty())
693     return;
694
695   tryNextNick(e, errnick);
696 }
697
698 /* ERR_UNAVAILRESOURCE */
699 void CoreSessionEventProcessor::processIrcEvent437(IrcEventNumeric *e) {
700   if(!checkParamCount(e, 1))
701     return;
702
703   QString errnick = e->params().first();
704
705   // if there is a problem while connecting to the server -> we handle it
706   // but only if our connection has not been finished yet...
707   if(!e->network()->currentServer().isEmpty())
708     return;
709
710   if(!e->network()->isChannelName(errnick))
711     tryNextNick(e, errnick);
712 }
713
714 /* template
715 void CoreSessionEventProcessor::processIrcEvent(IrcEvent *e) {
716   if(!checkParamCount(e, 1))
717     return;
718
719 }
720 */
721
722 /* Handle signals from Netsplit objects  */
723
724 void CoreSessionEventProcessor::handleNetsplitJoin(Network *net,
725                                                    const QString &channel,
726                                                    const QStringList &users,
727                                                    const QStringList &modes,
728                                                    const QString& quitMessage)
729 {
730   IrcChannel *ircChannel = net->ircChannel(channel);
731   if(!ircChannel) {
732     return;
733   }
734   QList<IrcUser *> ircUsers;
735   QStringList newModes = modes;
736   QStringList newUsers = users;
737
738   foreach(const QString &user, users) {
739     IrcUser *iu = net->ircUser(nickFromMask(user));
740     if(iu)
741       ircUsers.append(iu);
742     else { // the user already quit
743       int idx = users.indexOf(user);
744       newUsers.removeAt(idx);
745       newModes.removeAt(idx);
746     }
747   }
748
749   ircChannel->joinIrcUsers(ircUsers, newModes);
750   NetworkSplitEvent *event = new NetworkSplitEvent(EventManager::NetworkSplitJoin, net, channel, newUsers, quitMessage);
751   emit newEvent(event);
752 }
753
754 void CoreSessionEventProcessor::handleNetsplitQuit(Network *net, const QString &channel, const QStringList &users, const QString& quitMessage) {
755   NetworkSplitEvent *event = new NetworkSplitEvent(EventManager::NetworkSplitQuit, net, channel, users, quitMessage);
756   emit newEvent(event);
757   foreach(QString user, users) {
758     IrcUser *iu = net->ircUser(nickFromMask(user));
759     if(iu)
760       iu->quit();
761   }
762 }
763
764 void CoreSessionEventProcessor::handleEarlyNetsplitJoin(Network *net, const QString &channel, const QStringList &users, const QStringList &modes) {
765   IrcChannel *ircChannel = net->ircChannel(channel);
766   if(!ircChannel) {
767     qDebug() << "handleEarlyNetsplitJoin(): channel " << channel << " invalid";
768     return;
769   }
770   QList<NetworkEvent *> events;
771   QList<IrcUser *> ircUsers;
772   QStringList newModes = modes;
773
774   foreach(QString user, users) {
775     IrcUser *iu = net->updateNickFromMask(user);
776     if(iu) {
777       ircUsers.append(iu);
778       // fake event for scripts that consume join events
779       events << new IrcEvent(EventManager::IrcEventJoin, net, iu->hostmask(), QStringList() << channel);
780     }
781     else {
782       newModes.removeAt(users.indexOf(user));
783     }
784   }
785   ircChannel->joinIrcUsers(ircUsers, newModes);
786   foreach(NetworkEvent *event, events) {
787     event->setFlag(EventManager::Fake); // ignore this in here!
788     emit newEvent(event);
789   }
790 }
791
792 void CoreSessionEventProcessor::handleNetsplitFinished() {
793   Netsplit* n = qobject_cast<Netsplit*>(sender());
794   Q_ASSERT(n);
795   QHash<QString, Netsplit *> splithash  = _netsplits.take(n->network());
796   splithash.remove(splithash.key(n));
797   if(splithash.count())
798     _netsplits[n->network()] = splithash;
799   n->deleteLater();
800 }
801
802 void CoreSessionEventProcessor::destroyNetsplits(NetworkId netId) {
803   Network *net = coreSession()->network(netId);
804   if(!net)
805     return;
806
807   QHash<QString, Netsplit *> splits = _netsplits.take(net);
808   qDeleteAll(splits);
809 }
810
811 /*******************************/
812 /******** CTCP HANDLING ********/
813 /*******************************/
814
815 void CoreSessionEventProcessor::processCtcpEvent(CtcpEvent *e) {
816   if(e->testFlag(EventManager::Self))
817     return; // ignore ctcp events generated by user input
818
819   if(e->type() != EventManager::CtcpEvent || e->ctcpType() != CtcpEvent::Query)
820     return;
821
822   handle(e->ctcpCmd(), Q_ARG(CtcpEvent *, e));
823 }
824
825 void CoreSessionEventProcessor::defaultHandler(const QString &ctcpCmd, CtcpEvent *e) {
826   // This handler is only there to avoid warnings for unknown CTCPs
827   Q_UNUSED(e);
828   Q_UNUSED(ctcpCmd);
829 }
830
831 void CoreSessionEventProcessor::handleCtcpAction(CtcpEvent *e) {
832   // This handler is only there to feed CLIENTINFO
833   Q_UNUSED(e);
834 }
835
836 void CoreSessionEventProcessor::handleCtcpClientinfo(CtcpEvent *e) {
837   QStringList supportedHandlers;
838   foreach(QString handler, providesHandlers())
839     supportedHandlers << handler.toUpper();
840   qSort(supportedHandlers);
841   e->setReply(supportedHandlers.join(" "));
842 }
843
844 void CoreSessionEventProcessor::handleCtcpPing(CtcpEvent *e) {
845   e->setReply(e->param());
846 }
847
848 void CoreSessionEventProcessor::handleCtcpTime(CtcpEvent *e) {
849   e->setReply(QDateTime::currentDateTime().toString());
850 }
851
852 void CoreSessionEventProcessor::handleCtcpVersion(CtcpEvent *e) {
853   e->setReply(QString("Quassel IRC %1 (built on %2) -- http://www.quassel-irc.org")
854               .arg(Quassel::buildInfo().plainVersionString).arg(Quassel::buildInfo().buildDate));
855 }