Yay! After months, distributed client/core operation is working again!
[quassel.git] / src / core / server.cpp
1 /***************************************************************************
2  *   Copyright (C) 2005-07 by The Quassel Team                             *
3  *   devel@quassel-irc.org                                                 *
4  *                                                                         *
5  *   This program is free software; you can redistribute it and/or modify  *
6  *   it under the terms of the GNU General Public License as published by  *
7  *   the Free Software Foundation; either version 2 of the License, or     *
8  *   (at your option) any later version.                                   *
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 "server.h"
21
22 #include <QMetaObject>
23 #include <QMetaMethod>
24 #include <QDateTime>
25
26 #include "util.h"
27 #include "core.h"
28 #include "coresession.h"
29
30 Server::Server(UserId uid, QString net) : user(uid), network(net) {
31   QString MQUOTE = QString('\020');
32   ctcpMDequoteHash[MQUOTE + '0'] = QString('\000');
33   ctcpMDequoteHash[MQUOTE + 'n'] = QString('\n');
34   ctcpMDequoteHash[MQUOTE + 'r'] = QString('\r');
35   ctcpMDequoteHash[MQUOTE + MQUOTE] = MQUOTE;
36
37   XDELIM = QString('\001');
38   QString XQUOTE = QString('\134');
39   ctcpXDelimDequoteHash[XQUOTE + XQUOTE] = XQUOTE;
40   ctcpXDelimDequoteHash[XQUOTE + QString('a')] = XDELIM;
41   
42   serverinfo = new ServerInfo();
43 }
44
45 Server::~Server() {
46   delete serverinfo;
47 }
48
49 void Server::run() {
50   connect(&socket, SIGNAL(connected()), this, SLOT(socketConnected()));
51   connect(&socket, SIGNAL(disconnected()), this, SLOT(socketDisconnected()));
52   connect(&socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(socketError(QAbstractSocket::SocketError)));
53   connect(&socket, SIGNAL(stateChanged(QAbstractSocket::SocketState)), this, SLOT(socketStateChanged(QAbstractSocket::SocketState)));
54   connect(&socket, SIGNAL(readyRead()), this, SLOT(socketHasData()));
55
56   exec();
57 }
58
59 void Server::sendState() {
60   VarMap s;
61   VarMap n, t;
62   foreach(QString key, nicks.keys())  { n[key] = nicks[key]; }
63   foreach(QString key, topics.keys()) { t[key] = topics[key];}
64   s["Nicks"] = n;
65   s["Topics"] = t;
66   s["OwnNick"] = ownNick;
67   s["ServerSupports"] = serverSupports;
68   emit serverState(network, s);
69 }
70
71 void Server::connectToIrc(QString net) {
72   if(net != network) return; // not me!
73   CoreSession *sess = Core::session(user);
74   //networkSettings = Global::data(user, "Networks").toMap()[net].toMap();
75   networkSettings = sess->retrieveSessionData("Networks").toMap()[net].toMap();
76   //identity = Global::data(user, "Identities").toMap()[networkSettings["Identity"].toString()].toMap();
77   identity = sess->retrieveSessionData("Identities").toMap()[networkSettings["Identity"].toString()].toMap();
78   QList<QVariant> servers = networkSettings["Servers"].toList();
79   QString host = servers[0].toMap()["Address"].toString();
80   quint16 port = servers[0].toMap()["Port"].toUInt();
81   displayStatusMsg(QString("Connecting to %1:%2...").arg(host).arg(port));
82   socket.connectToHost(host, port);
83 }
84
85 void Server::disconnectFromIrc(QString net) {
86   if(net != network) return; // not me!
87   socket.disconnectFromHost();
88 }
89
90 void Server::socketHasData() {
91   while(socket.canReadLine()) {
92     QByteArray s = socket.readLine().trimmed();
93     //qDebug() << "Read" << s;
94     //emit recvRawServerMsg(s); // signal not needed, and we should make sure we consider encodings where we need them
95     //Message *msg = Message::createFromServerString(this, s);
96     handleServerMsg(s);
97   }
98 }
99
100 void Server::socketError( QAbstractSocket::SocketError err ) {
101   //qDebug() << "Socket Error!";
102   //emit error(err);
103 }
104
105 void Server::socketConnected( ) {
106   emit connected(network);
107   putRawLine(QString("NICK :%1").arg(identity["NickList"].toStringList()[0]));  // FIXME: try more nicks if error occurs
108   putRawLine(QString("USER %1 8 * :%2").arg(identity["Ident"].toString()).arg(identity["RealName"].toString()));
109 }
110
111 void Server::socketDisconnected( ) {
112   //qDebug() << "Socket disconnected!";
113   emit disconnected(network);
114   topics.clear();
115   nicks.clear();
116 }
117
118 void Server::socketStateChanged(QAbstractSocket::SocketState state) {
119   //qDebug() << "Socket state changed: " << state;
120 }
121
122 QString Server::updateNickFromMask(QString mask) {
123   QString user = userFromMask(mask);
124   QString host = hostFromMask(mask);
125   QString nick = nickFromMask(mask);
126   if(nicks.contains(nick) && !user.isEmpty() && !host.isEmpty()) {
127     VarMap n = nicks[nick];
128     if(n["User"].toString() != user || n["Host"].toString() != host) {
129       if(!n["User"].toString().isEmpty() || !n["Host"].toString().isEmpty())
130         qWarning(QString("Strange: Hostmask for nick %1 has changed!").arg(nick).toAscii());
131       n["User"] = user; n["Host"] = host;
132       nicks[nick] = n;
133       emit nickUpdated(network, nick, n);
134     }
135   }
136   return nick;
137 }
138
139 void Server::userInput(QString net, QString buf, QString msg) {
140   if(net != network) return; // not me!
141   //msg = msg.trimmed(); // remove whitespace from start and end
142   if(msg.isEmpty()) return;
143   if(!msg.startsWith('/')) {
144     msg = QString("/SAY ") + msg;
145   }
146   handleUserInput(buf, msg);
147 }
148
149 void Server::putRawLine(QString s) {
150 //  qDebug() << "SentRaw: " << s;
151   s += "\r\n";
152   socket.write(s.toAscii());
153 }
154
155 void Server::putCmd(QString cmd, QStringList params, QString prefix) {
156   QString m;
157   if(!prefix.isEmpty()) m += ":" + prefix + " ";
158   m += cmd.toUpper();
159   for(int i = 0; i < params.size() - 1; i++) {
160     m += " " + params[i];
161   }
162   if(!params.isEmpty()) m += " :" + params.last();
163 //  qDebug() << "Sent: " << m;
164   m += "\r\n";
165   socket.write(m.toAscii());
166 }
167
168 /*! Handle a raw message string sent by the server. We try to find a suitable handler, otherwise we call a default handler. */
169 void Server::handleServerMsg(QByteArray rawmsg) {
170   try {
171     if(rawmsg.isEmpty()) {
172       qWarning() << "Received empty string from server!";
173       return;
174     }
175     // TODO Implement encoding conversion
176     /* At this point, we have a raw message as a byte array. This needs to be converted to a QString somewhere.
177      * Problem is, that at this point we don't know which encoding to use for the various parts of the message.
178      * This is something the command handler needs to take care of (e.g. PRIVMSG needs to first parse for CTCP,
179      * and then convert the raw strings into the correct encoding.
180      * We _can_ safely assume Server encoding for prefix and cmd, but not for the params. Therefore, we need to
181      * change from a QStringList to a QList<QByteArray> in all the handlers, and have the handlers call decodeString
182      * where needed...
183     */
184     QString msg = QString::fromLatin1(rawmsg);
185
186     // OK, first we split the raw message into its various parts...
187     QString prefix = "";
188     QString cmd;
189     QStringList params;
190
191     // check for prefix by checking for a colon as the first char
192     if(msg[0] == ':') {
193       msg.remove(0,1);
194       prefix = msg.section(' ', 0, 0);
195       msg = msg.section(' ', 1);
196     }
197
198     // next string without a whitespace is the command
199     cmd = msg.section(' ', 0, 0).toUpper();
200     msg = msg.mid(cmd.length());
201
202     // get the parameters
203     QString trailing = "";
204     if(msg.contains(" :")) {
205       trailing = msg.section(" :", 1);
206       msg = msg.section(" :", 0, 0);
207     }
208     if(!msg.isEmpty()) {
209       params << msg.split(' ', QString::SkipEmptyParts);
210     }
211     if(!trailing.isEmpty()) {
212       params << trailing;
213     }
214
215     // numeric replies have the target as first param (RFC 2812 - 2.4). this is usually our own nick. Remove this!
216     uint num = cmd.toUInt();
217     if(num > 0) {
218       Q_ASSERT(params.count() > 0); // Violation to RFC
219       params.removeFirst();
220     }
221
222     // Now we try to find a handler for this message. BTW, I do love the Trolltech guys ;-)
223     QString hname = cmd.toLower();
224     hname[0] = hname[0].toUpper();
225     hname = "handleServer" + hname;
226     if(!QMetaObject::invokeMethod(this, hname.toAscii(), Q_ARG(QString, prefix), Q_ARG(QStringList, params))) {
227       // Ok. Default handler it is.
228       defaultServerHandler(cmd, prefix, params);
229     }
230   } catch(Exception e) {
231     emit displayMsg(Message::Error, "", e.msg());
232   }
233 }
234
235 void Server::defaultServerHandler(QString cmd, QString prefix, QStringList params) {
236   uint num = cmd.toUInt();
237   if(num) {
238     // A lot of server messages don't really need their own handler because they don't do much.
239     // Catch and handle these here.
240     switch(num) {
241       // Welcome, status, info messages. Just display these.
242       case 2: case 3: case 4: case 5: case 251: case 252: case 253: case 254: case 255: case 372: case 375:
243         emit displayMsg(Message::Server, "", params.join(" "), prefix);
244         break;
245       // Server error messages without param, just display them
246       case 409: case 411: case 412: case 422: case 424: case 445: case 446: case 451: case 462:
247       case 463: case 464: case 465: case 466: case 472: case 481: case 483: case 485: case 491: case 501: case 502:
248       case 431: // ERR_NONICKNAMEGIVEN 
249         emit displayMsg(Message::Error, "", params.join(" "), prefix);
250         break;
251       // Server error messages, display them in red. First param will be appended.
252       case 401: case 402: case 403: case 404: case 406: case 408: case 415: case 421: case 442:
253       { QString p = params.takeFirst();
254         emit displayMsg(Message::Error, "", params.join(" ") + " " + p, prefix);
255         break;
256       }
257       // Server error messages which will be displayed with a colon between the first param and the rest
258       case 413: case 414: case 423: case 441: case 444: case 461:
259       case 467: case 471: case 473: case 474: case 475: case 476: case 477: case 478: case 482:
260       case 436: // ERR_NICKCOLLISION
261       { QString p = params.takeFirst();
262         emit displayMsg(Message::Error, "", p + ": " + params.join(" "));
263         break;
264       }
265       // Ignore these commands.
266       case 366: case 376:
267         break;
268
269       // Everything else will be marked in red, so we can add them somewhere.
270       default:
271         emit displayMsg(Message::Error, "", cmd + " " + params.join(" "), prefix);
272     }
273     //qDebug() << prefix <<":"<<cmd<<params;
274   } else {
275     emit displayMsg(Message::Error, "", QString("Unknown: ") + cmd + " " + params.join(" "), prefix);
276     //qDebug() << prefix <<":"<<cmd<<params;
277   }
278 }
279
280 void Server::handleUserInput(QString bufname, QString usrMsg) {
281   try {
282     /* Looks like we don't need core-side buffers...
283     Buffer *buffer = 0;
284     if(!bufname.isEmpty()) {
285       Q_ASSERT(buffers.contains(bufname));
286       buffer = buffers[bufname];
287     }
288     */
289     QString cmd = usrMsg.section(' ', 0, 0).remove(0, 1).toUpper();
290     QString msg = usrMsg.section(' ', 1);
291     QString hname = cmd.toLower();
292     hname[0] = hname[0].toUpper();
293     hname = "handleUser" + hname;
294     if(!QMetaObject::invokeMethod(this, hname.toAscii(), Q_ARG(QString, bufname), Q_ARG(QString, msg))) {
295         // Ok. Default handler it is.
296       defaultUserHandler(bufname, cmd, msg);
297     }
298   } catch(Exception e) {
299     emit displayMsg(Message::Error, "", e.msg());
300   }
301 }
302
303 void Server::defaultUserHandler(QString bufname, QString cmd, QString msg) {
304   emit displayMsg(Message::Error, "", QString("Error: %1 %2").arg(cmd).arg(msg));
305
306 }
307
308 QStringList Server::providesUserHandlers() {
309   QStringList userHandlers;
310   for(int i=0; i < metaObject()->methodCount(); i++) {
311     QString methodSignature(metaObject()->method(i).signature());
312     if (methodSignature.startsWith("handleUser")) {
313       methodSignature = methodSignature.section('(',0,0);  // chop the attribute list
314       methodSignature = methodSignature.mid(10); // strip "handleUser"
315       userHandlers << methodSignature;
316     }
317   }
318   return userHandlers;
319 }
320
321 QString Server::ctcpDequote(QString message) {
322   QString dequotedMessage;
323   QString messagepart;
324   QHash<QString, QString>::iterator ctcpquote;
325   
326   // copy dequote Message
327   for(int i = 0; i < message.size(); i++) {
328     messagepart = message[i];
329     if(i+1 < message.size()) {
330       for(ctcpquote = ctcpMDequoteHash.begin(); ctcpquote != ctcpMDequoteHash.end(); ++ctcpquote) {
331         if(message.mid(i,2) == ctcpquote.key()) {
332           dequotedMessage += ctcpquote.value();
333           i++;
334           break;
335         }
336       }
337     }
338     dequotedMessage += messagepart;
339   }
340   return dequotedMessage;
341 }
342
343
344 QString Server::ctcpXdelimDequote(QString message) {
345   QString dequotedMessage;
346   QString messagepart;
347   QHash<QString, QString>::iterator xdelimquote;
348
349   for(int i = 0; i < message.size(); i++) {
350     messagepart = message[i];
351     if(i+1 < message.size()) {
352       for(xdelimquote = ctcpXDelimDequoteHash.begin(); xdelimquote != ctcpXDelimDequoteHash.end(); ++xdelimquote) {
353         if(message.mid(i,2) == xdelimquote.key()) {
354           messagepart = xdelimquote.value();
355           i++;
356           break;
357         }
358       }
359     }
360     dequotedMessage += messagepart;
361   }
362   return dequotedMessage;
363 }
364
365 QStringList Server::parseCtcp(CtcpType ctcptype, QString prefix, QString target, QString message) {
366   QStringList messages;
367   QString ctcp;
368   
369   //lowlevel message dequote
370   QString dequotedMessage = ctcpDequote(message);
371   
372   // extract tagged / extended data
373   while(dequotedMessage.contains(XDELIM)) {
374     messages << dequotedMessage.section(XDELIM,0,0);
375     ctcp = ctcpXdelimDequote(dequotedMessage.section(XDELIM,1,1));
376     dequotedMessage = dequotedMessage.section(XDELIM,2,2);
377     
378     //dispatch the ctcp command
379     QString ctcpcmd = ctcp.section(' ', 0, 0);
380     QString ctcpparam = ctcp.section(' ', 1);
381     
382     QString hname = ctcpcmd.toLower();
383     hname[0] = hname[0].toUpper();
384     hname = "handleCtcp" + hname;
385     if(!QMetaObject::invokeMethod(this, hname.toAscii(), Q_ARG(CtcpType, ctcptype), Q_ARG(QString, prefix), Q_ARG(QString, target), Q_ARG(QString, ctcpparam))) {
386       // Ok. Default handler it is.
387       defaultCtcpHandler(ctcptype, prefix, ctcpcmd, target, ctcpparam);
388     }
389   }
390   if(!dequotedMessage.isEmpty()) {
391     messages << dequotedMessage;
392   }
393   return messages;
394 }
395
396 QString Server::ctcpPack(QString ctcpTag, QString message) {
397   return XDELIM + ctcpTag + ' ' + message + XDELIM;
398 }
399
400 void Server::ctcpQuery(QString bufname, QString ctcpTag, QString message) {
401   QStringList params;
402   params << bufname << ctcpPack(ctcpTag, message);
403   putCmd("PRIVMSG", params); 
404 }
405
406 void Server::ctcpReply(QString bufname, QString ctcpTag, QString message) {
407   QStringList params;
408   params << bufname << ctcpPack(ctcpTag, message);
409   putCmd("NOTICE", params);
410 }
411
412 /**********************************************************************************/
413
414 /*
415 void Server::handleUser(QString bufname, QString msg) {
416
417
418 }
419 */
420
421 void Server::handleUserAway(QString bufname, QString msg) {
422   putCmd("AWAY", QStringList(msg));
423 }
424
425 void Server::handleUserDeop(QString bufname, QString msg) {
426   QStringList nicks = msg.split(' ', QString::SkipEmptyParts);
427   QString m = "-"; for(int i = 0; i < nicks.count(); i++) m += 'o';
428   QStringList params;
429   params << bufname << m << nicks;
430   putCmd("MODE", params);
431 }
432
433 void Server::handleUserDevoice(QString bufname, QString msg) {
434   QStringList nicks = msg.split(' ', QString::SkipEmptyParts);
435   QString m = "-"; for(int i = 0; i < nicks.count(); i++) m += 'v';
436   QStringList params;
437   params << bufname << m << nicks;
438   putCmd("MODE", params);
439 }
440
441 void Server::handleUserInvite(QString bufname, QString msg) {
442   QStringList params;
443   params << msg << bufname;
444   putCmd("INVITE", params);
445 }
446
447 void Server::handleUserJoin(QString bufname, QString msg) {
448   putCmd("JOIN", QStringList(msg));
449 }
450
451 void Server::handleUserKick(QString bufname, QString msg) {
452   QStringList params;
453   params << bufname << msg.split(' ', QString::SkipEmptyParts);
454   putCmd("KICK", params);
455 }
456
457 void Server::handleUserList(QString bufname, QString msg) {
458   putCmd("LIST", msg.split(' ', QString::SkipEmptyParts));
459 }
460
461 void Server::handleUserMode(QString bufname, QString msg) {
462   putCmd("MODE", msg.split(' ', QString::SkipEmptyParts));
463 }
464
465 // TODO: show privmsgs
466 void Server::handleUserMsg(QString bufname, QString msg) {
467   QString nick = msg.section(" ", 0, 0);
468   msg = msg.section(" ", 1);
469   if(nick.isEmpty() || msg.isEmpty()) return;
470   QStringList params;
471   params << nick << msg;
472   putCmd("PRIVMSG", params);
473 }
474
475 void Server::handleUserNick(QString bufname, QString msg) {
476   QString nick = msg.section(' ', 0, 0);
477   putCmd("NICK", QStringList(nick));
478 }
479
480 void Server::handleUserOp(QString bufname, QString msg) {
481   QStringList nicks = msg.split(' ', QString::SkipEmptyParts);
482   QString m = "+"; for(int i = 0; i < nicks.count(); i++) m += 'o';
483   QStringList params;
484   params << bufname << m << nicks;
485   putCmd("MODE", params);
486 }
487
488 void Server::handleUserPart(QString bufname, QString msg) {
489   QStringList params;
490   params << bufname << msg;
491   putCmd("PART", params);
492 }
493
494 // TODO: implement queries
495 void Server::handleUserQuery(QString bufname, QString msg) {
496   QString nick = msg.section(' ', 0, 0);
497   if(!nick.isEmpty()) emit queryRequested(network, nick);
498 }
499
500 void Server::handleUserQuit(QString bufname, QString msg) {
501   putCmd("QUIT", QStringList(msg));
502 }
503
504 void Server::handleUserQuote(QString bufname, QString msg) {
505   putRawLine(msg);
506 }
507
508 void Server::handleUserSay(QString bufname, QString msg) {
509   if(bufname.isEmpty()) return;  // server buffer
510   QStringList params;
511   params << bufname << msg;
512   putCmd("PRIVMSG", params);
513   if(isChannelName(bufname)) {
514     emit displayMsg(Message::Plain, params[0], msg, ownNick, Message::Self);
515   } else {
516     emit displayMsg(Message::Plain, params[0], msg, ownNick, Message::Self|Message::PrivMsg);
517   }
518 }
519
520 void Server::handleUserMe(QString bufname, QString msg) {
521   if(bufname.isEmpty()) return; // server buffer
522   ctcpQuery(bufname, "ACTION", msg);
523   emit displayMsg(Message::Action, bufname, msg, ownNick);
524 }
525
526 void Server::handleUserTopic(QString bufname, QString msg) {
527   if(bufname.isEmpty()) return;
528   QStringList params;
529   params << bufname << msg;
530   putCmd("TOPIC", params);
531 }
532
533 void Server::handleUserVoice(QString bufname, QString msg) {
534   QStringList nicks = msg.split(' ', QString::SkipEmptyParts);
535   QString m = "+"; for(int i = 0; i < nicks.count(); i++) m += 'v';
536   QStringList params;
537   params << bufname << m << nicks;
538   putCmd("MODE", params);
539 }
540
541 /**********************************************************************************/
542
543 void Server::handleServerJoin(QString prefix, QStringList params) {
544   Q_ASSERT(params.count() == 1);
545   QString nick = updateNickFromMask(prefix);
546   emit displayMsg(Message::Join, params[0], params[0], prefix);
547   if(nick == ownNick) {
548   //  Q_ASSERT(!buffers.contains(params[0]));  // cannot join a buffer twice!
549   //  Buffer *buf = new Buffer(params[0]);
550   //  buffers[params[0]] = buf;
551     topics[params[0]] = "";
552     emit topicSet(network, params[0], "");
553   } //else {
554     VarMap n;
555     if(nicks.contains(nick)) {
556       n = nicks[nick];
557       VarMap chans = n["Channels"].toMap();
558       // Q_ASSERT(!chans.keys().contains(params[0])); TODO uncomment
559       chans[params[0]] = VarMap();
560       n["Channels"] = chans;
561       nicks[nick] = n;
562       emit nickUpdated(network, nick, n);
563     } else {
564       VarMap chans;
565       chans[params[0]] = VarMap();
566       n["Channels"] = chans;
567       n["User"] = userFromMask(prefix);
568       n["Host"] = hostFromMask(prefix);
569       nicks[nick] = n;
570       emit nickAdded(network, nick, n);
571     }
572     //emit displayMsg(Message::Join, params[0], params[0], prefix);
573   //}
574 }
575
576 void Server::handleServerKick(QString prefix, QStringList params) {
577   QString kicker = updateNickFromMask(prefix);
578   QString nick = params[1];
579   Q_ASSERT(nicks.contains(nick));
580   VarMap n = nicks[nick];
581   VarMap chans = n["Channels"].toMap();
582   Q_ASSERT(chans.contains(params[0]));
583   chans.remove(params[0]);
584   QString msg = nick;
585   if(params.count() > 2) msg = QString("%1 %2").arg(msg).arg(params[2]);
586   emit displayMsg(Message::Kick, params[0], msg, prefix);
587   if(chans.count() > 0) {
588     n["Channels"] = chans;
589     nicks[nick] = n;
590     emit nickUpdated(network, nick, n);
591   } else {
592     nicks.remove(nick);
593     emit nickRemoved(network, nick);
594   }
595   if(nick == ownNick) {
596     topics.remove(params[0]);
597   }
598 }
599
600 void Server::handleServerMode(QString prefix, QStringList params) {
601   if(isChannelName(params[0])) {
602     // TODO only channel-user modes supported by now
603     QString prefixes = serverSupports["PrefixModes"].toString();
604     QString modes = params[1];
605     int p = 2;
606     int m = 0;
607     bool add = true;
608     while(m < modes.length()) {
609       if(modes[m] == '+') { add = true; m++; continue; }
610       if(modes[m] == '-') { add = false; m++; continue; }
611       if(prefixes.contains(modes[m])) {  // it's a user channel mode
612         Q_ASSERT(params.count() > m);
613         QString nick = params[p++];
614         if(nicks.contains(nick)) {  // sometimes, a server might try to set a MODE on a nick that is no longer there
615           VarMap n = nicks[nick]; VarMap clist = n["Channels"].toMap(); VarMap chan = clist[params[0]].toMap();
616           QString mstr = chan["Mode"].toString();
617           add ? mstr += modes[m] : mstr.remove(modes[m]);
618           chan["Mode"] = mstr; clist[params[0]] = chan; n["Channels"] = clist; nicks[nick] = n;
619           emit nickUpdated(network, nick, n);
620         }
621         m++;
622       } else {
623         // TODO add more modes
624         m++;
625       }
626     }
627     emit displayMsg(Message::Mode, params[0], params.join(" "), prefix);
628   } else {
629     //Q_ASSERT(nicks.contains(params[0]));
630     //VarMap n = nicks[params[0]].toMap();
631     //QString mode = n["Mode"].toString();
632     emit displayMsg(Message::Mode, "", params.join(" "));
633   }
634 }
635
636 void Server::handleServerNick(QString prefix, QStringList params) {
637   QString oldnick = updateNickFromMask(prefix);
638   QString newnick = params[0];
639   VarMap v = nicks.take(oldnick);
640   nicks[newnick] = v;
641   VarMap chans = v["Channels"].toMap();
642   foreach(QString c, chans.keys()) {
643     if(oldnick != ownNick) { emit displayMsg(Message::Nick, c, newnick, prefix); }
644     else { emit displayMsg(Message::Nick, c, newnick, newnick); }
645   }
646   emit nickRenamed(network, oldnick, newnick);
647   if(oldnick == ownNick) {
648     ownNick = newnick;
649     emit ownNickSet(network, newnick);
650   }
651 }
652
653 void Server::handleServerNotice(QString prefix, QStringList params) {
654   //Message msg(Message::Notice, params[1], prefix);
655   if(currentServer.isEmpty() || prefix == currentServer) emit displayMsg(Message::Server, "", params[1], prefix);
656   else emit displayMsg(Message::Notice, "", params[1], prefix);
657 }
658
659 void Server::handleServerPart(QString prefix, QStringList params) {
660   QString nick = updateNickFromMask(prefix);
661   Q_ASSERT(nicks.contains(nick));
662   VarMap n = nicks[nick];
663   VarMap chans = n["Channels"].toMap();
664   Q_ASSERT(chans.contains(params[0]));
665   chans.remove(params[0]);
666   QString msg;
667   if(params.count() > 1) msg = params[1];
668   emit displayMsg(Message::Part, params[0], msg, prefix);
669   if(chans.count() > 0) {
670     n["Channels"] = chans;
671     nicks[nick] = n;
672     emit nickUpdated(network, nick, n);
673   } else {
674     nicks.remove(nick);
675     emit nickRemoved(network, nick);
676   }
677   if(nick == ownNick) {
678     Q_ASSERT(topics.contains(params[0]));
679     topics.remove(params[0]);
680   }
681 }
682
683 void Server::handleServerPing(QString prefix, QStringList params) {
684   putCmd("PONG", params);
685 }
686
687 void Server::handleServerPrivmsg(QString prefix, QStringList params) {
688   updateNickFromMask(prefix);
689   Q_ASSERT(params.count() >= 2);
690   if(params.count()<2) emit displayMsg(Message::Plain, params[0], "", prefix);
691   else {
692     // it's possible to pack multiple privmsgs into one param using ctcp
693     QStringList messages = parseCtcp(Server::CtcpQuery, prefix, params[0], params[1]);
694     if(params[0].toLower() == ownNick.toLower()) {  // Freenode sends nickname in lower case!
695       foreach(QString message, messages) {
696         if(!message.isEmpty()) {
697           emit displayMsg(Message::Plain, "", message, prefix, Message::PrivMsg);
698         }
699       }
700       
701     } else {
702       //qDebug() << prefix << params;
703       Q_ASSERT(isChannelName(params[0]));  // should be channel!
704       foreach(QString message, messages) {
705         if(!message.isEmpty()) {
706           emit displayMsg(Message::Plain, params[0], message, prefix);
707         }
708       }
709     }
710   }
711 }
712
713 void Server::handleServerQuit(QString prefix, QStringList params) {
714   QString nick = updateNickFromMask(prefix);
715   Q_ASSERT(nicks.contains(nick));
716   VarMap chans = nicks[nick]["Channels"].toMap();
717   QString msg;
718   if(params.count()) msg = params[0];
719   foreach(QString c, chans.keys()) {
720     emit displayMsg(Message::Quit, c, msg, prefix);
721   }
722   nicks.remove(nick);
723   emit nickRemoved(network, nick);
724 }
725
726 void Server::handleServerTopic(QString prefix, QStringList params) {
727   QString nick = updateNickFromMask(prefix);
728   Q_ASSERT(nicks.contains(nick));
729   topics[params[0]] = params[1];
730   emit topicSet(network, params[0], params[1]);
731   emit displayMsg(Message::Server, params[0], tr("%1 has changed topic for %2 to: \"%3\"").arg(nick).arg(params[0]).arg(params[1]));
732 }
733
734 /* RPL_WELCOME */
735 void Server::handleServer001(QString prefix, QStringList params) {
736   // there should be only one param: "Welcome to the Internet Relay Network <nick>!<user>@<host>"
737   currentServer = prefix;
738   ownNick = params[0].section(' ', -1, -1).section('!', 0, 0);
739   VarMap n;
740   n["Channels"] = VarMap();
741   nicks[ownNick] = n;
742   emit ownNickSet(network, ownNick);
743   emit nickAdded(network, ownNick, VarMap());
744   emit displayMsg(Message::Server, "", params[0], prefix);
745   // send performlist
746   QStringList performList = networkSettings["Perform"].toString().split( "\n" );
747   int count = performList.count();
748   for(int a = 0; a < count; a++) {
749     if(!performList[a].isEmpty() ) {
750       userInput(network, "", performList[a]);
751     }
752   }
753 }
754
755 /* RPL_ISUPPORT */
756 // TODO Complete 005 handling, also use sensible defaults for non-sent stuff
757 void Server::handleServer005(QString prefix, QStringList params) {
758   //qDebug() << prefix << params;
759   params.removeLast();
760   foreach(QString p, params) {
761     QString key = p.section("=", 0, 0);
762     QString val = p.section("=", 1);
763     serverSupports[key] = val;
764     // handle some special cases
765     if(key == "PREFIX") {
766       VarMap foo; QString modes, prefixes;
767       Q_ASSERT(val.contains(')') && val.startsWith('('));
768       int m = 1, p;
769       for(p = 2; p < val.length(); p++) if(val[p] == ')') break;
770       p++;
771       for(; val[m] != ')'; m++, p++) {
772         Q_ASSERT(p < val.length());
773         foo[QString(val[m])] = QString(val[p]);
774         modes += val[m]; prefixes += val[p];
775       }
776       serverSupports["PrefixModes"] = modes; serverSupports["Prefixes"] = prefixes;
777       serverSupports["ModePrefixMap"] = foo;
778     }
779   }
780 }
781
782
783 /* RPL_NOTOPIC */
784 void Server::handleServer331(QString prefix, QStringList params) {
785   topics[params[0]] = "";
786   emit topicSet(network, params[0], "");
787   emit displayMsg(Message::Server, params[0], tr("No topic is set for %1.").arg(params[0]));
788 }
789
790 /* RPL_TOPIC */
791 void Server::handleServer332(QString prefix, QStringList params) {
792   topics[params[0]] = params[1];
793   emit topicSet(network, params[0], params[1]);
794   emit displayMsg(Message::Server, params[0], tr("Topic for %1 is \"%2\"").arg(params[0]).arg(params[1]));
795 }
796
797 /* Topic set by... */
798 void Server::handleServer333(QString prefix, QStringList params) {
799   emit displayMsg(Message::Server, params[0],
800                     tr("Topic set by %1 on %2").arg(params[1]).arg(QDateTime::fromTime_t(params[2].toUInt()).toString()));
801 }
802
803 /* RPL_NAMREPLY */
804 void Server::handleServer353(QString prefix, QStringList params) {
805   params.removeFirst(); // = or *
806   QString buf = params.takeFirst();
807   QString prefixes = serverSupports["Prefixes"].toString();
808   foreach(QString nick, params[0].split(' ')) {
809     QString mode = "", pfx = "";
810     if(prefixes.contains(nick[0])) {
811       pfx = nick[0];
812       for(int i = 0;; i++)
813         if(prefixes[i] == nick[0]) { mode = serverSupports["PrefixModes"].toString()[i]; break; }
814       nick.remove(0,1);
815     }
816     VarMap c; c["Mode"] = mode; c["Prefix"] = pfx;
817     if(nicks.contains(nick)) {
818       VarMap n = nicks[nick];
819       VarMap chans = n["Channels"].toMap();
820       chans[buf] = c;
821       n["Channels"] = chans;
822       nicks[nick] = n;
823       emit nickUpdated(network, nick, n);
824     } else {
825       VarMap n; VarMap c; VarMap chans;
826       c["Mode"] = mode;
827       chans[buf] = c;
828       n["Channels"] = chans;
829       nicks[nick] = n;
830       emit nickAdded(network, nick, n);
831     }
832   }
833 }
834
835 /* ERR_ERRONEUSNICKNAME */
836 void Server::handleServer432(QString prefix, QStringList params) {
837   if(params.size() < 2) {
838     // handle unreal-ircd bug, where unreal ircd doesnt supply a TARGET in ERR_ERRONEUSNICKNAME during registration phase:
839     // nick @@@
840     // :irc.scortum.moep.net 432  @@@ :Erroneous Nickname: Illegal characters
841     // correct server reply:
842     // :irc.scortum.moep.net 432 * @@@ :Erroneous Nickname: Illegal characters
843     emit displayMsg(Message::Error, "", tr("There is a nickname in your identity's nicklist which contains illegal characters"));
844     emit displayMsg(Message::Error, "", tr("Due to a bug in Unreal IRCd (and maybe other irc-servers too) we're unable to determine the erroneous nick"));
845     emit displayMsg(Message::Error, "", tr("Please use: /nick <othernick> to continue or clean up your nicklist"));
846   } else {
847     QString errnick = params[0];
848     emit displayMsg(Message::Error, "", tr("Nick %1 contains illegal characters").arg(errnick));
849     // if there is a problem while connecting to the server -> we handle it
850     // TODO rely on another source...
851     if(currentServer.isEmpty()) {
852       QStringList desiredNicks = identity["NickList"].toStringList();
853       int nextNick = desiredNicks.indexOf(errnick) + 1;
854       if (desiredNicks.size() > nextNick) {
855         putCmd("NICK", QStringList(desiredNicks[nextNick]));
856       } else {
857         emit displayMsg(Message::Error, "", tr("No free and valid nicks in nicklist found. use: /nick <othernick> to continue"));
858       }
859     }
860   }
861 }
862
863 /* ERR_NICKNAMEINUSE */
864 void Server::handleServer433(QString prefix, QStringList params) {
865   QString errnick = params[0];
866   emit displayMsg(Message::Error, "", tr("Nick %1 is already taken").arg(errnick));
867   // if there is a problem while connecting to the server -> we handle it
868   // TODO rely on another source...
869   if(currentServer.isEmpty()) {
870     QStringList desiredNicks = identity["NickList"].toStringList();
871     int nextNick = desiredNicks.indexOf(errnick) + 1;
872     if (desiredNicks.size() > nextNick) {
873       putCmd("NICK", QStringList(desiredNicks[nextNick]));
874     } else {
875       emit displayMsg(Message::Error, "", tr("No free and valid nicks in nicklist found. use: /nick <othernick> to continue"));
876     }
877   }
878 }
879
880 /***********************************************************************************/
881 // CTCP HANDLER
882
883 void Server::handleCtcpAction(CtcpType ctcptype, QString prefix, QString target, QString param) {
884   emit displayMsg(Message::Action, target, param, prefix);
885 }
886
887 void Server::handleCtcpPing(CtcpType ctcptype, QString prefix, QString target, QString param) {
888   if(ctcptype == CtcpQuery) {
889     ctcpReply(nickFromMask(prefix), "PING", param);
890     emit displayMsg(Message::Server, "", tr("Received CTCP PING request by %1").arg(prefix));
891   } else {
892     // display ping answer
893   }
894 }
895
896 void Server::handleCtcpVersion(CtcpType ctcptype, QString prefix, QString target, QString param) {
897   if(ctcptype == CtcpQuery) {
898     // FIXME use real Info about quassel :)
899     //ctcpReply(nickFromMask(prefix), "VERSION", QString("Quassel:pre Release:*nix"));
900     ctcpReply(nickFromMask(prefix), "VERSION", QString("Quassel IRC (Pre-Release) - http://www.quassel-irc.org"));
901     emit displayMsg(Message::Server, "", tr("Received CTCP VERSION request by %1").arg(prefix));
902   } else {
903     // TODO display Version answer
904   }
905 }
906
907 void Server::defaultCtcpHandler(CtcpType ctcptype, QString prefix, QString cmd, QString target, QString param) {
908   emit displayMsg(Message::Error, "", tr("Received unknown CTCP %1 by %2").arg(cmd).arg(prefix));
909 }
910
911
912 /***********************************************************************************/
913
914 /* Exception classes for message handling */
915 Server::ParseError::ParseError(QString cmd, QString prefix, QStringList params) {
916   _msg = QString("Command Parse Error: ") + cmd + params.join(" ");
917
918 }
919
920 Server::UnknownCmdError::UnknownCmdError(QString cmd, QString prefix, QStringList params) {
921   _msg = QString("Unknown Command: ") + cmd;
922
923 }