]> git.netwichtig.de Git - user/henk/code/inspircd.git/blobdiff - src/inspircd.cpp
Added version flags
[user/henk/code/inspircd.git] / src / inspircd.cpp
index aecc2cc46b99f70959afa82a2ee6e0fa6ac8c574..f0d007cb949a7df723dcf5a2009c0d1c0ba10456 100644 (file)
@@ -53,6 +53,10 @@ using namespace std;
 #include "wildcard.h"
 #include "message.h"
 #include "mode.h"
+#include "commands.h"
+#include "xline.h"
+#include "inspstring.h"
+#include "dnsqueue.h"
 
 #ifdef GCC3
 #define nspace __gnu_cxx
@@ -74,47 +78,63 @@ char rules[MAXBUF];
 char list[MAXBUF];
 char PrefixQuit[MAXBUF];
 char DieValue[MAXBUF];
+char DNSServer[MAXBUF];
 int debugging =  0;
 int WHOWAS_STALE = 48; // default WHOWAS Entries last 2 days before they go 'stale'
 int WHOWAS_MAX = 100;  // default 100 people maximum in the WHOWAS list
 int DieDelay  =  5;
 time_t startup_time = time(NULL);
 int NetBufferSize = 10240; // NetBufferSize used as the buffer size for all read() ops
+extern int MaxWhoResults;
 time_t nb_start = 0;
+int dns_timeout = 5;
 
-extern vector<Module*> modules;
+bool AllowHalfop = true;
+bool AllowProtect = true;
+bool AllowFounder = true;
+
+extern std::vector<Module*> modules;
 std::vector<std::string> module_names;
-extern vector<ircd_module*> factory;
+extern std::vector<ircd_module*> factory;
 std::vector<int> fd_reap;
 
 extern int MODCOUNT;
-
+int openSockfd[MAXSOCKS];
 bool nofork = false;
 
+time_t TIME = time(NULL);
+
 namespace nspace
 {
-       template<> struct nspace::hash<in_addr>
-       {
-               size_t operator()(const struct in_addr &a) const
-               {
-                       size_t q;
-                       memcpy(&q,&a,sizeof(size_t));
-                       return q;
-               }
-       };
-
-       template<> struct nspace::hash<string>
-       {
-               size_t operator()(const string &s) const
-               {
-                       char a[MAXBUF];
-                       static struct hash<const char *> strhash;
-                       strcpy(a,s.c_str());
-                       strlower(a);
-                       return strhash(a);
-               }
-       };
-}      
+#ifdef GCC34
+        template<> struct hash<in_addr>
+#else
+        template<> struct nspace::hash<in_addr>
+#endif
+        {
+                size_t operator()(const struct in_addr &a) const
+                {
+                        size_t q;
+                        memcpy(&q,&a,sizeof(size_t));
+                        return q;
+                }
+        };
+#ifdef GCC34
+        template<> struct hash<string>
+#else
+        template<> struct nspace::hash<string>
+#endif
+        {
+                size_t operator()(const string &s) const
+                {
+                        char a[MAXBUF];
+                        static struct hash<const char *> strhash;
+                        strlcpy(a,s.c_str(),MAXBUF);
+                        strlower(a);
+                        return strhash(a);
+                }
+        };
+}
 
 
 struct StrHashComp
@@ -123,8 +143,8 @@ struct StrHashComp
        bool operator()(const string& s1, const string& s2) const
        {
                char a[MAXBUF],b[MAXBUF];
-               strcpy(a,s1.c_str());
-               strcpy(b,s2.c_str());
+               strlcpy(a,s1.c_str(),MAXBUF);
+               strlcpy(b,s2.c_str(),MAXBUF);
                return (strcasecmp(a,b) == 0);
        }
 
@@ -167,7 +187,7 @@ address_cache IP;
 ClassVector Classes;
 
 struct linger linger = { 0 };
-char bannerBuffer[MAXBUF];
+char MyExecutable[1024];
 int boundPortCount = 0;
 int portCount = 0, UDPportCount = 0, ports[MAXSOCKS];
 int defaultRoute = 0;
@@ -181,7 +201,6 @@ long MyKey = C.GenKey();
 int has_channel(userrec *u, chanrec *c);
 int usercount(chanrec *c);
 int usercount_i(chanrec *c);
-void update_stats_l(int fd,int data_out);
 char* Passwd(userrec *user);
 bool IsDenied(userrec *user);
 void AddWhoWas(userrec* u);
@@ -252,7 +271,7 @@ void log(int level,char *text, ...)
                va_start (argsPtr, text);
                vsnprintf(textbuffer, MAXBUF, text, argsPtr);
                va_end(argsPtr);
-               strcpy(b,asctime(timeinfo));
+               strlcpy(b,asctime(timeinfo),MAXBUF);
                b[strlen(b)-1] = ':';
                fprintf(log_file,"%s %s\n",b,textbuffer);
                if (nofork)
@@ -265,184 +284,239 @@ void log(int level,char *text, ...)
 
 void readfile(file_cache &F, const char* fname)
 {
-  FILE* file;
-  char linebuf[MAXBUF];
-
-  log(DEBUG,"readfile: loading %s",fname);
-  F.clear();
-  file =  fopen(fname,"r");
-  if (file)
-  {
-       while (!feof(file))
-       {
-               fgets(linebuf,sizeof(linebuf),file);
-               linebuf[strlen(linebuf)-1]='\0';
-               if (!strcmp(linebuf,""))
-               {
-                       strcpy(linebuf,"  ");
-               }
-               if (!feof(file))
-               {
-                       F.push_back(linebuf);
-               }
-       }
-       fclose(file);
-  }
-  else
-  {
-         log(DEBUG,"readfile: failed to load file: %s",fname);
-  }
-  log(DEBUG,"readfile: loaded %s, %d lines",fname,F.size());
+       FILE* file;
+       char linebuf[MAXBUF];
+       
+       log(DEBUG,"readfile: loading %s",fname);
+       F.clear();
+       file =  fopen(fname,"r");
+       if (file)
+       {
+               while (!feof(file))
+               {
+                       fgets(linebuf,sizeof(linebuf),file);
+                       linebuf[strlen(linebuf)-1]='\0';
+                       if (!strcmp(linebuf,""))
+                       {
+                               strcpy(linebuf,"  ");
+                       }
+                       if (!feof(file))
+                       {
+                               F.push_back(linebuf);
+                       }
+               }
+               fclose(file);
+       }
+       else
+       {
+               log(DEBUG,"readfile: failed to load file: %s",fname);
+       }
+       log(DEBUG,"readfile: loaded %s, %d lines",fname,F.size());
 }
 
-void ReadConfig(void)
+void ReadConfig(bool bail, userrec* user)
 {
-  char dbg[MAXBUF],pauseval[MAXBUF],Value[MAXBUF],timeout[MAXBUF],NB[MAXBUF],flood[MAXBUF];
-  ConnectClass c;
-
-  LoadConf(CONFIG_FILE,&config_f);
-  
-  ConfValue("server","name",0,ServerName,&config_f);
-  ConfValue("server","description",0,ServerDesc,&config_f);
-  ConfValue("server","network",0,Network,&config_f);
-  ConfValue("admin","name",0,AdminName,&config_f);
-  ConfValue("admin","email",0,AdminEmail,&config_f);
-  ConfValue("admin","nick",0,AdminNick,&config_f);
-  ConfValue("files","motd",0,motd,&config_f);
-  ConfValue("files","rules",0,rules,&config_f);
-  ConfValue("power","diepass",0,diepass,&config_f);
-  ConfValue("power","pause",0,pauseval,&config_f);
-  ConfValue("power","restartpass",0,restartpass,&config_f);
-  ConfValue("options","prefixquit",0,PrefixQuit,&config_f);
-  ConfValue("die","value",0,DieValue,&config_f);
-  ConfValue("options","loglevel",0,dbg,&config_f);
-  ConfValue("options","netbuffersize",0,NB,&config_f);
-  NetBufferSize = atoi(NB);
-  if ((!NetBufferSize) || (NetBufferSize > 65535) || (NetBufferSize < 1024))
-  {
-       log(DEFAULT,"No NetBufferSize specified or size out of range, setting to default of 10240.");
-       NetBufferSize = 10240;
-  }
-  if (!strcmp(dbg,"debug"))
-       LogLevel = DEBUG;
-  if (!strcmp(dbg,"verbose"))
-       LogLevel = VERBOSE;
-  if (!strcmp(dbg,"default"))
-       LogLevel = DEFAULT;
-  if (!strcmp(dbg,"sparse"))
-       LogLevel = SPARSE;
-  if (!strcmp(dbg,"none"))
-       LogLevel = NONE;
-  readfile(MOTD,motd);
-  log(DEBUG,"Reading message of the day");
-  readfile(RULES,rules);
-  log(DEBUG,"Reading connect classes");
-  Classes.clear();
-  for (int i = 0; i < ConfValueEnum("connect",&config_f); i++)
-  {
-       strcpy(Value,"");
-       ConfValue("connect","allow",i,Value,&config_f);
-       ConfValue("connect","timeout",i,timeout,&config_f);
-       ConfValue("connect","flood",i,flood,&config_f);
-       if (strcmp(Value,""))
-       {
-               strcpy(c.host,Value);
-               c.type = CC_ALLOW;
-               strcpy(Value,"");
-               ConfValue("connect","password",i,Value,&config_f);
-               strcpy(c.pass,Value);
-               c.registration_timeout = 90; // default is 2 minutes
-               c.flood = atoi(flood);
-               if (atoi(timeout)>0)
+       char dbg[MAXBUF],pauseval[MAXBUF],Value[MAXBUF],timeout[MAXBUF],NB[MAXBUF],flood[MAXBUF],MW[MAXBUF];
+       char AH[MAXBUF],AP[MAXBUF],AF[MAXBUF],DNT[MAXBUF];
+       ConnectClass c;
+       std::stringstream errstr;
+       
+       if (!LoadConf(CONFIG_FILE,&config_f,&errstr))
+       {
+               errstr.seekg(0);
+               if (bail)
+               {
+                       printf("There were errors in your configuration:\n%s",errstr.str().c_str());
+                       Exit(0);
+               }
+               else
                {
-                       c.registration_timeout = atoi(timeout);
+                       char dataline[1024];
+                       if (user)
+                       {
+                               WriteServ(user->fd,"NOTICE %s :There were errors in the configuration file:",user->nick);
+                               while (!errstr.eof())
+                               {
+                                       errstr.getline(dataline,1024);
+                                       WriteServ(user->fd,"NOTICE %s :%s",user->nick,dataline);
+                               }
+                       }
+                       else
+                       {
+                               WriteOpers("There were errors in the configuration file:",user->nick);
+                               while (!errstr.eof())
+                               {
+                                       errstr.getline(dataline,1024);
+                                       WriteOpers(dataline);
+                               }
+                       }
+                       return;
                }
-               Classes.push_back(c);
-               log(DEBUG,"Read connect class type ALLOW, host=%s password=%s timeout=%d flood=%d",c.host,c.pass,c.registration_timeout,c.flood);
        }
-       else
+         
+       ConfValue("server","name",0,ServerName,&config_f);
+       ConfValue("server","description",0,ServerDesc,&config_f);
+       ConfValue("server","network",0,Network,&config_f);
+       ConfValue("admin","name",0,AdminName,&config_f);
+       ConfValue("admin","email",0,AdminEmail,&config_f);
+       ConfValue("admin","nick",0,AdminNick,&config_f);
+       ConfValue("files","motd",0,motd,&config_f);
+       ConfValue("files","rules",0,rules,&config_f);
+       ConfValue("power","diepass",0,diepass,&config_f);
+       ConfValue("power","pause",0,pauseval,&config_f);
+       ConfValue("power","restartpass",0,restartpass,&config_f);
+       ConfValue("options","prefixquit",0,PrefixQuit,&config_f);
+       ConfValue("die","value",0,DieValue,&config_f);
+       ConfValue("options","loglevel",0,dbg,&config_f);
+       ConfValue("options","netbuffersize",0,NB,&config_f);
+       ConfValue("options","maxwho",0,MW,&config_f);
+       ConfValue("options","allowhalfop",0,AH,&config_f);
+       ConfValue("options","allowprotect",0,AP,&config_f);
+       ConfValue("options","allowfounder",0,AF,&config_f);
+       ConfValue("dns","server",0,DNSServer,&config_f);
+       ConfValue("dns","timeout",0,DNT,&config_f);
+       NetBufferSize = atoi(NB);
+       MaxWhoResults = atoi(MW);
+       dns_timeout = atoi(DNT);
+       if (!dns_timeout)
+               dns_timeout = 5;
+       if (!strcmp(DNSServer,""))
+               strlcpy(DNSServer,"127.0.0.1",MAXBUF);
+       AllowHalfop = ((!strcasecmp(AH,"true")) || (!strcasecmp(AH,"1")) || (!strcasecmp(AH,"yes")));
+       AllowProtect = ((!strcasecmp(AP,"true")) || (!strcasecmp(AP,"1")) || (!strcasecmp(AP,"yes")));
+       AllowFounder = ((!strcasecmp(AF,"true")) || (!strcasecmp(AF,"1")) || (!strcasecmp(AF,"yes")));
+       if ((!NetBufferSize) || (NetBufferSize > 65535) || (NetBufferSize < 1024))
+       {
+               log(DEFAULT,"No NetBufferSize specified or size out of range, setting to default of 10240.");
+               NetBufferSize = 10240;
+       }
+       if ((!MaxWhoResults) || (MaxWhoResults > 65535) || (MaxWhoResults < 1))
+       {
+               log(DEFAULT,"No MaxWhoResults specified or size out of range, setting to default of 128.");
+               MaxWhoResults = 128;
+       }
+       if (!strcmp(dbg,"debug"))
+               LogLevel = DEBUG;
+       if (!strcmp(dbg,"verbose"))
+               LogLevel = VERBOSE;
+       if (!strcmp(dbg,"default"))
+               LogLevel = DEFAULT;
+       if (!strcmp(dbg,"sparse"))
+               LogLevel = SPARSE;
+       if (!strcmp(dbg,"none"))
+               LogLevel = NONE;
+       readfile(MOTD,motd);
+       log(DEFAULT,"Reading message of the day...");
+       readfile(RULES,rules);
+       log(DEFAULT,"Reading connect classes...");
+       Classes.clear();
+       for (int i = 0; i < ConfValueEnum("connect",&config_f); i++)
        {
-               ConfValue("connect","deny",i,Value,&config_f);
-                strcpy(c.host,Value);
-                c.type = CC_DENY;
-               Classes.push_back(c);
-               log(DEBUG,"Read connect class type DENY, host=%s",c.host);
-       }
+               strcpy(Value,"");
+               ConfValue("connect","allow",i,Value,&config_f);
+               ConfValue("connect","timeout",i,timeout,&config_f);
+               ConfValue("connect","flood",i,flood,&config_f);
+               if (strcmp(Value,""))
+               {
+                       strlcpy(c.host,Value,MAXBUF);
+                       c.type = CC_ALLOW;
+                       strlcpy(Value,"",MAXBUF);
+                       ConfValue("connect","password",i,Value,&config_f);
+                       strlcpy(c.pass,Value,MAXBUF);
+                       c.registration_timeout = 90; // default is 2 minutes
+                       c.flood = atoi(flood);
+                       if (atoi(timeout)>0)
+                       {
+                               c.registration_timeout = atoi(timeout);
+                       }
+                       Classes.push_back(c);
+                       log(DEBUG,"Read connect class type ALLOW, host=%s password=%s timeout=%d flood=%d",c.host,c.pass,c.registration_timeout,c.flood);
+               }
+               else
+               {
+                       ConfValue("connect","deny",i,Value,&config_f);
+                       strlcpy(c.host,Value,MAXBUF);
+                       c.type = CC_DENY;
+                       Classes.push_back(c);
+                       log(DEBUG,"Read connect class type DENY, host=%s",c.host);
+               }
        
-  }
+       }
+       log(DEFAULT,"Reading K lines,Q lines and Z lines from config...");
+       read_xline_defaults();
+       log(DEFAULT,"Applying K lines, Q lines and Z lines...");
+       apply_lines();
+       log(DEFAULT,"Done reading configuration file, InspIRCd is now running.");
 }
 
 /* write formatted text to a socket, in same format as printf */
 
 void Write(int sock,char *text, ...)
 {
-  if (!text)
-  {
-       log(DEFAULT,"*** BUG *** Write was given an invalid parameter");
-       return;
-  }
-  char textbuffer[MAXBUF];
-  va_list argsPtr;
-  char tb[MAXBUF];
-
-  va_start (argsPtr, text);
-  vsnprintf(textbuffer, MAXBUF, text, argsPtr);
-  va_end(argsPtr);
-  sprintf(tb,"%s\r\n",textbuffer);
-  chop(tb);
-  if (sock != -1)
-  {
-       write(sock,tb,strlen(tb));
-       update_stats_l(sock,strlen(tb)); /* add one line-out to stats L for this fd */
-  }
+       if (!text)
+       {
+               log(DEFAULT,"*** BUG *** Write was given an invalid parameter");
+               return;
+       }
+       char textbuffer[MAXBUF];
+       va_list argsPtr;
+       char tb[MAXBUF];
+       
+       va_start (argsPtr, text);
+       vsnprintf(textbuffer, MAXBUF, text, argsPtr);
+       va_end(argsPtr);
+       snprintf(tb,MAXBUF,"%s\r\n",textbuffer);
+       chop(tb);
+       if (sock != -1)
+       {
+               write(sock,tb,strlen(tb));
+       }
 }
 
 /* write a server formatted numeric response to a single socket */
 
 void WriteServ(int sock, char* text, ...)
 {
-  if (!text)
-  {
-       log(DEFAULT,"*** BUG *** WriteServ was given an invalid parameter");
-       return;
-  }
-  char textbuffer[MAXBUF],tb[MAXBUF];
-  va_list argsPtr;
-  va_start (argsPtr, text);
-
-  vsnprintf(textbuffer, MAXBUF, text, argsPtr);
-  va_end(argsPtr);
-  sprintf(tb,":%s %s\r\n",ServerName,textbuffer);
-  chop(tb);
-  if (sock != -1)
-  {
-       write(sock,tb,strlen(tb));
-       update_stats_l(sock,strlen(tb)); /* add one line-out to stats L for this fd */
-  }
+       if (!text)
+       {
+               log(DEFAULT,"*** BUG *** WriteServ was given an invalid parameter");
+               return;
+       }
+       char textbuffer[MAXBUF],tb[MAXBUF];
+       va_list argsPtr;
+       va_start (argsPtr, text);
+       
+       vsnprintf(textbuffer, MAXBUF, text, argsPtr);
+       va_end(argsPtr);
+       snprintf(tb,MAXBUF,":%s %s\r\n",ServerName,textbuffer);
+       chop(tb);
+       if (sock != -1)
+       {
+               write(sock,tb,strlen(tb));
+       }
 }
 
 /* write text from an originating user to originating user */
 
 void WriteFrom(int sock, userrec *user,char* text, ...)
 {
-  if ((!text) || (!user))
-  {
-       log(DEFAULT,"*** BUG *** WriteFrom was given an invalid parameter");
-       return;
-  }
-  char textbuffer[MAXBUF],tb[MAXBUF];
-  va_list argsPtr;
-  va_start (argsPtr, text);
-
-  vsnprintf(textbuffer, MAXBUF, text, argsPtr);
-  va_end(argsPtr);
-  sprintf(tb,":%s!%s@%s %s\r\n",user->nick,user->ident,user->dhost,textbuffer);
-  chop(tb);
-  if (sock != -1)
-  {
-       write(sock,tb,strlen(tb));
-       update_stats_l(sock,strlen(tb)); /* add one line-out to stats L for this fd */
-  }
+       if ((!text) || (!user))
+       {
+               log(DEFAULT,"*** BUG *** WriteFrom was given an invalid parameter");
+               return;
+       }
+       char textbuffer[MAXBUF],tb[MAXBUF];
+       va_list argsPtr;
+       va_start (argsPtr, text);
+       
+       vsnprintf(textbuffer, MAXBUF, text, argsPtr);
+       va_end(argsPtr);
+       snprintf(tb,MAXBUF,":%s!%s@%s %s\r\n",user->nick,user->ident,user->dhost,textbuffer);
+       chop(tb);
+       if (sock != -1)
+       {
+               write(sock,tb,strlen(tb));
+       }
 }
 
 /* write text to an destination user from a source user (e.g. user privmsg) */
@@ -933,7 +1007,7 @@ void WriteWallOps(userrec *source, bool local_only, char* text, ...)
                {
                        if (strchr(i->second->modes,'w'))
                        {
-                               WriteTo(source,i->second,"WALLOPS %s",textbuffer);
+                               WriteTo(source,i->second,"WALLOPS :%s",textbuffer);
                        }
                 }
        }
@@ -978,7 +1052,7 @@ void strlower(char *n)
 
 /* Find a user record by nickname and return a pointer to it */
 
-userrec* Find(string nick)
+userrec* Find(std::string nick)
 {
        user_hash::iterator iter = clientlist.find(nick);
 
@@ -989,22 +1063,6 @@ userrec* Find(string nick)
        return iter->second;
 }
 
-void update_stats_l(int fd,int data_out) /* add one line-out to stats L for this fd */
-{
-       for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
-       {
-               if (i->second)
-               {
-                       if (i->second->fd == fd)
-                       {
-                               i->second->bytes_out+=data_out;
-                               i->second->cmds_out++;
-                       }
-               }
-       }
-}
-
-
 /* find a channel record by channel name and return a pointer to it */
 
 chanrec* FindChan(const char* chan)
@@ -1025,6 +1083,22 @@ chanrec* FindChan(const char* chan)
 }
 
 
+long GetMaxBans(char* name)
+{
+       char CM[MAXBUF];
+       for (int count = 0; count < ConfValueEnum("banlist",&config_f); count++)
+       {
+               ConfValue("banlist","chan",count,CM,&config_f);
+               if (match(name,CM))
+               {
+                       ConfValue("banlist","limit",count,CM,&config_f);
+                       return atoi(CM);
+               }
+       }
+       return 64;
+}
+
+
 void purge_empty_chans(void)
 {
        int go_again = 1, purge = 0;
@@ -1041,7 +1115,7 @@ void purge_empty_chans(void)
                                        if (i != chanlist.end())
                                        {
                                                log(DEBUG,"del_channel: destroyed: %s",i->second->name);
-                                               delete i->second;
+                                               if (i->second) delete i->second;
                                                chanlist.erase(i);
                                                go_again = 1;
                                                purge++;
@@ -1075,61 +1149,62 @@ char* chanmodes(chanrec *chan)
        strcpy(sparam,"");
        if (chan->noexternal)
        {
-               strncat(scratch,"n",MAXMODES);
+               strlcat(scratch,"n",MAXMODES);
        }
        if (chan->topiclock)
        {
-               strncat(scratch,"t",MAXMODES);
+               strlcat(scratch,"t",MAXMODES);
        }
        if (strcmp(chan->key,""))
        {
-               strncat(scratch,"k",MAXMODES);
+               strlcat(scratch,"k",MAXMODES);
        }
        if (chan->limit)
        {
-               strncat(scratch,"l",MAXMODES);
+               strlcat(scratch,"l",MAXMODES);
        }
        if (chan->inviteonly)
        {
-               strncat(scratch,"i",MAXMODES);
+               strlcat(scratch,"i",MAXMODES);
        }
        if (chan->moderated)
        {
-               strncat(scratch,"m",MAXMODES);
+               strlcat(scratch,"m",MAXMODES);
        }
        if (chan->secret)
        {
-               strncat(scratch,"s",MAXMODES);
+               strlcat(scratch,"s",MAXMODES);
        }
        if (chan->c_private)
        {
-               strncat(scratch,"p",MAXMODES);
+               strlcat(scratch,"p",MAXMODES);
        }
        if (strcmp(chan->key,""))
        {
-               strncat(sparam,chan->key,MAXBUF);
+               strlcat(sparam," ",MAXBUF);
+               strlcat(sparam,chan->key,MAXBUF);
        }
        if (chan->limit)
        {
                char foo[24];
                sprintf(foo," %d",chan->limit);
-               strncat(sparam,foo,MAXBUF);
+               strlcat(sparam,foo,MAXBUF);
        }
        if (strlen(chan->custom_modes))
        {
-               strncat(scratch,chan->custom_modes,MAXMODES);
+               strlcat(scratch,chan->custom_modes,MAXMODES);
                for (int z = 0; z < strlen(chan->custom_modes); z++)
                {
                        std::string extparam = chan->GetModeParameter(chan->custom_modes[z]);
                        if (extparam != "")
                        {
-                               strncat(sparam," ",MAXBUF);
-                               strncat(sparam,extparam.c_str(),MAXBUF);
+                               strlcat(sparam," ",MAXBUF);
+                               strlcat(sparam,extparam.c_str(),MAXBUF);
                        }
                }
        }
        log(DEBUG,"chanmodes: %s %s%s",chan->name,scratch,sparam);
-       strncat(scratch,sparam,MAXMODES);
+       strlcat(scratch,sparam,MAXMODES);
        return scratch;
 }
 
@@ -1145,7 +1220,7 @@ void userlist(userrec *user,chanrec *c)
                return;
        }
 
-       sprintf(list,"353 %s = %s :", user->nick, c->name);
+       snprintf(list,MAXBUF,"353 %s = %s :", user->nick, c->name);
        for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
        {
                if (has_channel(i->second,c))
@@ -1158,23 +1233,22 @@ void userlist(userrec *user,chanrec *c)
                                         * nick in NAMES list */
                                        continue;
                                }
-                               strcat(list,cmode(i->second,c));
-                               strcat(list,i->second->nick);
-                               strcat(list," ");
+                               strlcat(list,cmode(i->second,c),MAXBUF);
+                               strlcat(list,i->second->nick,MAXBUF);
+                               strlcat(list," ",MAXBUF);
                                if (strlen(list)>(480-NICKMAX))
                                {
                                        /* list overflowed into
                                         * multiple numerics */
-                                       WriteServ(user->fd,list);
-                                       sprintf(list,"353 %s = %s :", user->nick, c->name);
+                                       WriteServ(user->fd,"%s",list);
+                                       snprintf(list,MAXBUF,"353 %s = %s :", user->nick, c->name);
                                }
                        }
                }
        }
-       /* if whats left in the list isnt empty, send it */
-       if (list[strlen(list)-1] != ':')
+       /* if whats left in the list isnt empty, send it */     if (list[strlen(list)-1] != ':')
        {
-               WriteServ(user->fd,list);
+               WriteServ(user->fd,"%s",list);
        }
 }
 
@@ -1283,8 +1357,9 @@ chanrec* add_channel(userrec *user, const char* cn, const char* key, bool overri
 
        if (!FindChan(cname))
        {
+               int MOD_RESULT = 0;
                FOREACH_RESULT(OnUserPreJoin(user,NULL,cname));
-               if (MOD_RESULT) {
+               if (MOD_RESULT == 1) {
                        return NULL;
                }
 
@@ -1293,10 +1368,10 @@ chanrec* add_channel(userrec *user, const char* cn, const char* key, bool overri
                {
                        chanlist[cname] = new chanrec();
 
-                       strcpy(chanlist[cname]->name, cname);
+                       strlcpy(chanlist[cname]->name, cname,CHANMAX);
                        chanlist[cname]->topiclock = 1;
                        chanlist[cname]->noexternal = 1;
-                       chanlist[cname]->created = time(NULL);
+                       chanlist[cname]->created = TIME;
                        strcpy(chanlist[cname]->topic, "");
                        strncpy(chanlist[cname]->setby, user->nick,NICKMAX);
                        chanlist[cname]->topicset = 0;
@@ -1318,79 +1393,87 @@ chanrec* add_channel(userrec *user, const char* cn, const char* key, bool overri
                        
                        // the override flag allows us to bypass channel modes
                        // and bans (used by servers)
-                       if (!override)
+                       if ((!override) || (!strcasecmp(user->server,ServerName)))
                        {
+                               log(DEBUG,"Not overriding...");
+                               int MOD_RESULT = 0;
                                FOREACH_RESULT(OnUserPreJoin(user,Ptr,cname));
-                               if (MOD_RESULT) {
+                               if (MOD_RESULT == 1) {
                                        return NULL;
                                }
+                               log(DEBUG,"MOD_RESULT=%d",MOD_RESULT);
                                
-                               if (strcmp(Ptr->key,""))
+                               if (!MOD_RESULT) 
                                {
-                                       log(DEBUG,"add_channel: %s has key %s",Ptr->name,Ptr->key);
-                                       if (!key)
-                                       {
-                                               log(DEBUG,"add_channel: no key given in JOIN");
-                                               WriteServ(user->fd,"475 %s %s :Cannot join channel (Requires key)",user->nick, Ptr->name);
-                                               return NULL;
-                                       }
-                                       else
+                                       log(DEBUG,"add_channel: checking key, invite, etc");
+                                       if (strcmp(Ptr->key,""))
                                        {
-                                               log(DEBUG,"key at %p is %s",key,key);
-                                               if (strcasecmp(key,Ptr->key))
+                                               log(DEBUG,"add_channel: %s has key %s",Ptr->name,Ptr->key);
+                                               if (!key)
                                                {
-                                                       log(DEBUG,"add_channel: bad key given in JOIN");
-                                                       WriteServ(user->fd,"475 %s %s :Cannot join channel (Incorrect key)",user->nick, Ptr->name);
+                                                       log(DEBUG,"add_channel: no key given in JOIN");
+                                                       WriteServ(user->fd,"475 %s %s :Cannot join channel (Requires key)",user->nick, Ptr->name);
                                                        return NULL;
                                                }
+                                               else
+                                               {
+                                                       log(DEBUG,"key at %p is %s",key,key);
+                                                       if (strcasecmp(key,Ptr->key))
+                                                       {
+                                                               log(DEBUG,"add_channel: bad key given in JOIN");
+                                                               WriteServ(user->fd,"475 %s %s :Cannot join channel (Incorrect key)",user->nick, Ptr->name);
+                                                               return NULL;
+                                                       }
+                                               }
                                        }
-                               }
-                               log(DEBUG,"add_channel: no key");
-       
-                               if (Ptr->inviteonly)
-                               {
-                                       log(DEBUG,"add_channel: channel is +i");
-                                       if (user->IsInvited(Ptr->name))
-                                       {
-                                               /* user was invited to channel */
-                                               /* there may be an optional channel NOTICE here */
-                                       }
-                                       else
+                                       log(DEBUG,"add_channel: no key");
+               
+                                       if (Ptr->inviteonly)
                                        {
-                                               WriteServ(user->fd,"473 %s %s :Cannot join channel (Invite only)",user->nick, Ptr->name);
-                                               return NULL;
+                                               log(DEBUG,"add_channel: channel is +i");
+                                               if (user->IsInvited(Ptr->name))
+                                               {
+                                                       /* user was invited to channel */
+                                                       /* there may be an optional channel NOTICE here */
+                                               }
+                                               else
+                                               {
+                                                       WriteServ(user->fd,"473 %s %s :Cannot join channel (Invite only)",user->nick, Ptr->name);
+                                                       return NULL;
+                                               }
                                        }
-                               }
-                               log(DEBUG,"add_channel: channel is not +i");
-       
-                               if (Ptr->limit)
-                               {
-                                       if (usercount(Ptr) == Ptr->limit)
+                                       log(DEBUG,"add_channel: channel is not +i");
+               
+                                       if (Ptr->limit)
                                        {
-                                               WriteServ(user->fd,"471 %s %s :Cannot join channel (Channel is full)",user->nick, Ptr->name);
-                                               return NULL;
+                                               if (usercount(Ptr) == Ptr->limit)
+                                               {
+                                                       WriteServ(user->fd,"471 %s %s :Cannot join channel (Channel is full)",user->nick, Ptr->name);
+                                                       return NULL;
+                                               }
                                        }
-                               }
-                               
-                               log(DEBUG,"add_channel: about to walk banlist");
-       
-                               /* check user against the channel banlist */
-                               if (Ptr)
-                               {
-                                       if (Ptr->bans.size())
+                                       
+                                       log(DEBUG,"add_channel: about to walk banlist");
+               
+                                       /* check user against the channel banlist */
+                                       if (Ptr)
                                        {
-                                               for (BanList::iterator i = Ptr->bans.begin(); i != Ptr->bans.end(); i++)
+                                               if (Ptr->bans.size())
                                                {
-                                                       if (match(user->GetFullHost(),i->data))
+                                                       for (BanList::iterator i = Ptr->bans.begin(); i != Ptr->bans.end(); i++)
                                                        {
-                                                               WriteServ(user->fd,"474 %s %s :Cannot join channel (You're banned)",user->nick, Ptr->name);
-                                                               return NULL;
+                                                               if (match(user->GetFullHost(),i->data))
+                                                               {
+                                                                       WriteServ(user->fd,"474 %s %s :Cannot join channel (You're banned)",user->nick, Ptr->name);
+                                                                       return NULL;
+                                                               }
                                                        }
                                                }
                                        }
-                               }
+                                       
+                                       log(DEBUG,"add_channel: bans checked");
                                
-                               log(DEBUG,"add_channel: bans checked");
+                               }
                                
 
                                if ((Ptr) && (user))
@@ -1436,7 +1519,14 @@ chanrec* add_channel(userrec *user, const char* cn, const char* key, bool overri
                        {
                                // use the stamdard J token with no privilages.
                                char buffer[MAXBUF];
-                               snprintf(buffer,MAXBUF,"J %s :%s",user->nick,Ptr->name);
+                               if (created == 2)
+                               {
+                                       snprintf(buffer,MAXBUF,"J %s @%s",user->nick,Ptr->name);
+                               }
+                               else
+                               {
+                                       snprintf(buffer,MAXBUF,"J %s %s",user->nick,Ptr->name);
+                               }
                                NetSendToAll(buffer);
                        }
 
@@ -1536,7 +1626,7 @@ chanrec* del_channel(userrec *user, const char* cname, const char* reason, bool
                if (iter != chanlist.end())
                {
                        log(DEBUG,"del_channel: destroyed: %s",Ptr->name);
-                       delete iter->second;
+                       if (iter->second) delete iter->second;
                        chanlist.erase(iter);
                }
        }
@@ -1566,18 +1656,28 @@ void kick_channel(userrec *src,userrec *user, chanrec *Ptr, char* reason)
                WriteServ(src->fd,"441 %s %s %s :They are not on that channel",src->nick, user->nick, Ptr->name);
                return;
        }
-       if ((cstatus(src,Ptr) < STATUS_HOP) || (cstatus(src,Ptr) < cstatus(user,Ptr)))
+
+       int MOD_RESULT = 0;
+       FOREACH_RESULT(OnAccessCheck(src,user,Ptr,AC_KICK));
+       
+       if (MOD_RESULT == ACR_DENY)
+               return;
+
+       if (MOD_RESULT == ACR_DEFAULT)
        {
-               if (cstatus(src,Ptr) == STATUS_HOP)
-               {
-                       WriteServ(src->fd,"482 %s %s :You must be a channel operator",src->nick, Ptr->name);
-               }
-               else
+               if (((cstatus(src,Ptr) < STATUS_HOP) || (cstatus(src,Ptr) < cstatus(user,Ptr))) && (!is_uline(src->server)))
                {
-                       WriteServ(src->fd,"482 %s %s :You must be at least a half-operator to change modes on this channel",src->nick, Ptr->name);
+                       if (cstatus(src,Ptr) == STATUS_HOP)
+                       {
+                               WriteServ(src->fd,"482 %s %s :You must be a channel operator",src->nick, Ptr->name);
+                       }
+                       else
+                       {
+                               WriteServ(src->fd,"482 %s %s :You must be at least a half-operator to change modes on this channel",src->nick, Ptr->name);
+                       }
+                       
+                       return;
                }
-               
-               return;
        }
        
        for (int i =0; i != MAXCHANS; i++)
@@ -1605,7 +1705,7 @@ void kick_channel(userrec *src,userrec *user, chanrec *Ptr, char* reason)
                if (iter != chanlist.end())
                {
                        log(DEBUG,"del_channel: destroyed: %s",Ptr->name);
-                       delete iter->second;
+                       if (iter->second) delete iter->second;
                        chanlist.erase(iter);
                }
        }
@@ -1616,7 +1716,7 @@ void kick_channel(userrec *src,userrec *user, chanrec *Ptr, char* reason)
 
 /* This function pokes and hacks at a parameter list like the following:
  *
- * PART #winbot, #darkgalaxy :m00!
+ * PART #winbot,#darkgalaxy :m00!
  *
  * to turn it into a series of individual calls like this:
  *
@@ -1661,7 +1761,7 @@ int loop_call(handlerfunc fn, char **parameters, int pcnt, userrec *u, int start
        {
                if (pcnt > 1) /* we have a key to copy */
                {
-                       strcpy(keystr,parameters[1]);
+                       strlcpy(keystr,parameters[1],MAXBUF);
                }
        }
 
@@ -1678,7 +1778,7 @@ int loop_call(handlerfunc fn, char **parameters, int pcnt, userrec *u, int start
        {
                if (parameters[i])
                {
-                       strcat(plist,parameters[i]);
+                       strlcat(plist,parameters[i],MAXBUF);
                }
        }
        
@@ -1691,7 +1791,7 @@ int loop_call(handlerfunc fn, char **parameters, int pcnt, userrec *u, int start
                if (plist[i] == ',')
                {
                        plist[i] = '\0';
-                       strcpy(blog[j++],param);
+                       strlcpy(blog[j++],param,MAXBUF);
                        param = plist+i+1;
                        if (j>20)
                        {
@@ -1700,7 +1800,7 @@ int loop_call(handlerfunc fn, char **parameters, int pcnt, userrec *u, int start
                        }
                }
        }
-       strcpy(blog[j++],param);
+       strlcpy(blog[j++],param,MAXBUF);
        total = j;
 
        if ((joins) && (keystr) && (total>0)) // more than one channel and is joining
@@ -1720,11 +1820,11 @@ int loop_call(handlerfunc fn, char **parameters, int pcnt, userrec *u, int start
                                if (keystr[i] == ',')
                                {
                                        keystr[i] = '\0';
-                                       strcpy(blog2[j++],param);
+                                       strlcpy(blog2[j++],param,MAXBUF);
                                        param = keystr+i+1;
                                }
                        }
-                       strcpy(blog2[j++],param);
+                       strlcpy(blog2[j++],param,MAXBUF);
                        total2 = j;
                }
        }
@@ -1777,112 +1877,6 @@ int loop_call(handlerfunc fn, char **parameters, int pcnt, userrec *u, int start
 }
 
 
-void handle_join(char **parameters, int pcnt, userrec *user)
-{
-       chanrec* Ptr;
-       int i = 0;
-       
-       if (loop_call(handle_join,parameters,pcnt,user,0,0,1))
-               return;
-       if (parameters[0][0] == '#')
-       {
-               Ptr = add_channel(user,parameters[0],parameters[1],false);
-       }
-}
-
-
-void handle_part(char **parameters, int pcnt, userrec *user)
-{
-       chanrec* Ptr;
-
-       if (pcnt > 1)
-       {
-               if (loop_call(handle_part,parameters,pcnt,user,0,pcnt-2,0))
-                       return;
-               del_channel(user,parameters[0],parameters[1],false);
-       }
-       else
-       {
-               if (loop_call(handle_part,parameters,pcnt,user,0,pcnt-1,0))
-                       return;
-               del_channel(user,parameters[0],NULL,false);
-       }
-}
-
-void handle_kick(char **parameters, int pcnt, userrec *user)
-{
-       chanrec* Ptr = FindChan(parameters[0]);
-       userrec* u   = Find(parameters[1]);
-
-       if ((!u) || (!Ptr))
-       {
-               WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
-               return;
-       }
-       
-       if (!has_channel(u,Ptr))
-       {
-               WriteServ(user->fd,"442 %s %s :You're not on that channel!",user->nick, parameters[0]);
-               return;
-       }
-
-       char reason[MAXBUF];
-       
-       if (pcnt > 2)
-       {
-               strncpy(reason,parameters[2],MAXBUF);
-               if (strlen(reason)>MAXKICK)
-               {
-                       reason[MAXKICK-1] = '\0';
-               }
-
-               kick_channel(user,u,Ptr,reason);
-       }
-       else
-       {
-               strcpy(reason,user->nick);
-               kick_channel(user,u,Ptr,reason);
-       }
-       
-       // this must be propogated so that channel membership is kept in step network-wide
-       
-       char buffer[MAXBUF];
-       snprintf(buffer,MAXBUF,"k %s %s %s :%s",user->nick,u->nick,Ptr->name,reason);
-       NetSendToAll(buffer);
-}
-
-
-void handle_die(char **parameters, int pcnt, userrec *user)
-{
-       log(DEBUG,"die: %s",user->nick);
-       if (!strcmp(parameters[0],diepass))
-       {
-               WriteOpers("*** DIE command from %s!%s@%s, terminating...",user->nick,user->ident,user->host);
-               sleep(DieDelay);
-               Exit(ERROR);
-       }
-       else
-       {
-               WriteOpers("*** Failed DIE Command from %s!%s@%s.",user->nick,user->ident,user->host);
-       }
-}
-
-void handle_restart(char **parameters, int pcnt, userrec *user)
-{
-       log(DEBUG,"restart: %s",user->nick);
-       if (!strcmp(parameters[0],restartpass))
-       {
-               WriteOpers("*** RESTART command from %s!%s@%s, Pretending to restart till this is finished :D",user->nick,user->ident,user->host);
-               sleep(DieDelay);
-               Exit(ERROR);
-               /* Will finish this later when i can be arsed :) */
-       }
-       else
-       {
-               WriteOpers("*** Failed RESTART Command from %s!%s@%s.",user->nick,user->ident,user->host);
-       }
-}
-
 
 void kill_link(userrec *user,const char* r)
 {
@@ -1929,7 +1923,7 @@ void kill_link(userrec *user,const char* r)
        {
                log(DEBUG,"deleting user hash value %d",iter->second);
                if ((iter->second) && (user->registered == 7)) {
-                       delete iter->second;
+                       if (iter->second) delete iter->second;
                }
                clientlist.erase(iter);
        }
@@ -1937,63 +1931,59 @@ void kill_link(userrec *user,const char* r)
        if (user->registered == 7) {
                purge_empty_chans();
        }
+       user = NULL;
 }
 
-
-void handle_kill(char **parameters, int pcnt, userrec *user)
+void kill_link_silent(userrec *user,const char* r)
 {
-       userrec *u = Find(parameters[0]);
-       char killreason[MAXBUF];
+       user_hash::iterator iter = clientlist.find(user->nick);
        
-        log(DEBUG,"kill: %s %s",parameters[0],parameters[1]);
-       if (u)
-       {
-               if (strcmp(ServerName,u->server))
-               {
-                       // remote kill
-                       WriteOpers("*** Remote kill by %s: %s!%s@%s (%s)",user->nick,u->nick,u->ident,u->host,parameters[1]);
-                       sprintf(killreason,"[%s] Killed (%s (%s))",ServerName,user->nick,parameters[1]);
-                       WriteCommonExcept(u,"QUIT :%s",killreason);
-                       // K token must go to ALL servers!!!
-                       char buffer[MAXBUF];
-                       snprintf(buffer,MAXBUF,"K %s %s :%s",user->nick,u->nick,killreason);
-                       NetSendToAll(buffer);
-                       
-                       user_hash::iterator iter = clientlist.find(u->nick);
-                       if (iter != clientlist.end())
-                       {
-                               log(DEBUG,"deleting user hash value %d",iter->second);
-                               if ((iter->second) && (user->registered == 7)) {
-                                       delete iter->second;
-                                       }
-                       clientlist.erase(iter);
-                       }
-                       purge_empty_chans();
-               }
-               else
-               {
-                       // local kill
-                       WriteTo(user, u, "KILL %s :%s!%s!%s (%s)", u->nick, ServerName,user->dhost,user->nick,parameters[1]);
-                       WriteOpers("*** Local Kill by %s: %s!%s@%s (%s)",user->nick,u->nick,u->ident,u->host,parameters[1]);
-                       sprintf(killreason,"Killed (%s (%s))",user->nick,parameters[1]);
-                       kill_link(u,killreason);
-               }
+       char reason[MAXBUF];
+       
+       strncpy(reason,r,MAXBUF);
+
+       if (strlen(reason)>MAXQUIT)
+       {
+               reason[MAXQUIT-1] = '\0';
        }
-       else
+
+       log(DEBUG,"kill_link: %s '%s'",user->nick,reason);
+       Write(user->fd,"ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,reason);
+       log(DEBUG,"closing fd %d",user->fd);
+
+       /* bugfix, cant close() a nonblocking socket (sux!) */
+       if (user->registered == 7) {
+               FOREACH_MOD OnUserQuit(user);
+               WriteCommonExcept(user,"QUIT :%s",reason);
+
+               // Q token must go to ALL servers!!!
+               char buffer[MAXBUF];
+               snprintf(buffer,MAXBUF,"Q %s :%s",user->nick,reason);
+               NetSendToAll(buffer);
+       }
+
+       /* push the socket on a stack of sockets due to be closed at the next opportunity
+        * 'Client exited' is an exception to this as it means the client side has already
+        * closed the socket, we don't need to do it.
+        */
+       fd_reap.push_back(user->fd);
+       
+       bool do_purge = false;
+       
+       if (iter != clientlist.end())
        {
-               WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
+               log(DEBUG,"deleting user hash value %d",iter->second);
+               if ((iter->second) && (user->registered == 7)) {
+                       if (iter->second) delete iter->second;
+               }
+               clientlist.erase(iter);
        }
-}
 
-void handle_summon(char **parameters, int pcnt, userrec *user)
-{
-       WriteServ(user->fd,"445 %s :SUMMON has been disabled (depreciated command)",user->nick);
+       if (user->registered == 7) {
+               purge_empty_chans();
+       }
 }
 
-void handle_users(char **parameters, int pcnt, userrec *user)
-{
-       WriteServ(user->fd,"445 %s :USERS has been disabled (depreciated command)",user->nick);
-}
 
 
 // looks up a users password for their connection class (<ALLOW>/<DENY> tags)
@@ -2024,135 +2014,6 @@ bool IsDenied(userrec *user)
 
 
 
-void handle_pass(char **parameters, int pcnt, userrec *user)
-{
-       // Check to make sure they havnt registered -- Fix by FCS
-       if (user->registered == 7)
-       {
-               WriteServ(user->fd,"462 %s :You may not reregister",user->nick);
-               return;
-       }
-       if (!strcasecmp(parameters[0],Passwd(user)))
-       {
-               user->haspassed = true;
-       }
-}
-
-void handle_invite(char **parameters, int pcnt, userrec *user)
-{
-       userrec* u = Find(parameters[0]);
-       chanrec* c = FindChan(parameters[1]);
-
-       if ((!c) || (!u))
-       {
-               if (!c)
-               {
-                       WriteServ(user->fd,"401 %s %s :No such nick/channel",user->nick, parameters[1]);
-               }
-               else
-               {
-                       if (c->inviteonly)
-                       {
-                               WriteServ(user->fd,"401 %s %s :No such nick/channel",user->nick, parameters[0]);
-                       }
-               }
-
-               return;
-       }
-
-       if (c->inviteonly)
-       {
-               if (cstatus(user,c) < STATUS_HOP)
-               {
-                       WriteServ(user->fd,"482 %s %s :You must be at least a half-operator to change modes on this channel",user->nick, c->name);
-                       return;
-               }
-       }
-       if (has_channel(u,c))
-       {
-               WriteServ(user->fd,"443 %s %s %s :Is already on channel %s",user->nick,u->nick,c->name,c->name);
-               return;
-       }
-       if (!has_channel(user,c))
-       {
-               WriteServ(user->fd,"442 %s %s :You're not on that channel!",user->nick, c->name);
-               return;
-       }
-       u->InviteTo(c->name);
-       WriteFrom(u->fd,user,"INVITE %s :%s",u->nick,c->name);
-       WriteServ(user->fd,"341 %s %s %s",user->nick,u->nick,c->name);
-       
-       // i token must go to ALL servers!!!
-       char buffer[MAXBUF];
-       snprintf(buffer,MAXBUF,"i %s %s %s",u->nick,user->nick,c->name);
-       NetSendToAll(buffer);
-}
-
-void handle_topic(char **parameters, int pcnt, userrec *user)
-{
-       chanrec* Ptr;
-
-       if (pcnt == 1)
-       {
-               if (strlen(parameters[0]) <= CHANMAX)
-               {
-                       Ptr = FindChan(parameters[0]);
-                       if (Ptr)
-                       {
-                               if (Ptr->topicset)
-                               {
-                                       WriteServ(user->fd,"332 %s %s :%s", user->nick, Ptr->name, Ptr->topic);
-                                       WriteServ(user->fd,"333 %s %s %s %d", user->nick, Ptr->name, Ptr->setby, Ptr->topicset);
-                               }
-                               else
-                               {
-                                       WriteServ(user->fd,"331 %s %s :No topic is set.", user->nick, Ptr->name);
-                               }
-                       }
-                       else
-                       {
-                               WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
-                       }
-               }
-               return;
-       }
-       else if (pcnt>1)
-       {
-               if (strlen(parameters[0]) <= CHANMAX)
-               {
-                       Ptr = FindChan(parameters[0]);
-                       if (Ptr)
-                       {
-                               if ((Ptr->topiclock) && (cstatus(user,Ptr)<STATUS_HOP))
-                               {
-                                       WriteServ(user->fd,"482 %s %s :You must be at least a half-operator to change modes on this channel", user->nick, Ptr->name);
-                                       return;
-                               }
-                               
-                               char topic[MAXBUF];
-                               strncpy(topic,parameters[1],MAXBUF);
-                               if (strlen(topic)>MAXTOPIC)
-                               {
-                                       topic[MAXTOPIC-1] = '\0';
-                               }
-                                       
-                               strcpy(Ptr->topic,topic);
-                               strcpy(Ptr->setby,user->nick);
-                               Ptr->topicset = time(NULL);
-                               WriteChannel(Ptr,user,"TOPIC %s :%s",Ptr->name, Ptr->topic);
-
-                               // t token must go to ALL servers!!!
-                               char buffer[MAXBUF];
-                               snprintf(buffer,MAXBUF,"t %s %s :%s",user->nick,Ptr->name,topic);
-                               NetSendToAll(buffer);
-                       }
-                       else
-                       {
-                               WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
-                       }
-               }
-       }
-}
 
 /* sends out an error notice to all connected clients (not to be used
  * lightly!) */
@@ -2183,13 +2044,13 @@ void Error(int status)
        signal (SIGSEGV, SIG_IGN);
        signal (SIGURG, SIG_IGN);
        signal (SIGKILL, SIG_IGN);
-       log(DEBUG,"*** fell down a pothole in the road to perfection ***");
+       log(DEFAULT,"*** fell down a pothole in the road to perfection ***");
        send_error("Error! Segmentation fault! save meeeeeeeeeeeeee *splat!*");
-       exit(status);
+       Exit(status);
 }
 
 
-int main(int argc, char *argv[])
+int main(int argc, char **argv)
 {
        Start();
        srand(time(NULL));
@@ -2197,18 +2058,26 @@ int main(int argc, char *argv[])
        if (!FileExists(CONFIG_FILE))
        {
                printf("ERROR: Cannot open config file: %s\nExiting...\n",CONFIG_FILE);
-               log(DEBUG,"main: no config");
+               log(DEFAULT,"main: no config");
                printf("ERROR: Your config file is missing, this IRCd will self destruct in 10 seconds!\n");
                Exit(ERROR);
        }
        if (argc > 1) {
-               if (!strcmp(argv[1],"-nofork")) {
-                       nofork = true;
+               for (int i = 1; i < argc; i++)
+               {
+                       if (!strcmp(argv[i],"-nofork")) {
+                               nofork = true;
+                       }
+                       if (!strcmp(argv[i],"-wait")) {
+                               sleep(6);
+                       }
                }
        }
+       strlcpy(MyExecutable,argv[0],MAXBUF);
+       
        if (InspIRCd() == ERROR)
        {
-               log(DEBUG,"main: daemon function bailed");
+               log(DEFAULT,"main: daemon function bailed");
                printf("ERROR: could not initialise. Shutting down.\n");
                Exit(ERROR);
        }
@@ -2245,7 +2114,6 @@ userrec* ReHashNick(char* Old, char* New)
 
        clientlist[New] = new userrec();
        clientlist[New] = oldnick->second;
-       /*delete oldnick->second; */
        clientlist.erase(oldnick);
 
        log(DEBUG,"ReHashNick: Nick rehashed as %s",New);
@@ -2258,12 +2126,12 @@ void AddWhoWas(userrec* u)
 {
        user_hash::iterator iter = whowas.find(u->nick);
        userrec *a = new userrec();
-       strcpy(a->nick,u->nick);
-       strcpy(a->ident,u->ident);
-       strcpy(a->dhost,u->dhost);
-       strcpy(a->host,u->host);
-       strcpy(a->fullname,u->fullname);
-       strcpy(a->server,u->server);
+       strlcpy(a->nick,u->nick,NICKMAX);
+       strlcpy(a->ident,u->ident,64);
+       strlcpy(a->dhost,u->dhost,256);
+       strlcpy(a->host,u->host,256);
+       strlcpy(a->fullname,u->fullname,128);
+       strlcpy(a->server,u->server,256);
        a->signon = u->signon;
 
        /* MAX_WHOWAS:   max number of /WHOWAS items
@@ -2278,9 +2146,9 @@ void AddWhoWas(userrec* u)
                        for (user_hash::iterator i = whowas.begin(); i != whowas.end(); i++)
                        {
                                // 3600 seconds in an hour ;)
-                               if ((i->second->signon)<(time(NULL)-(WHOWAS_STALE*3600)))
+                               if ((i->second->signon)<(TIME-(WHOWAS_STALE*3600)))
                                {
-                                       delete i->second;
+                                       if (i->second) delete i->second;
                                        i->second = a;
                                        log(DEBUG,"added WHOWAS entry, purged an old record");
                                        return;
@@ -2296,14 +2164,14 @@ void AddWhoWas(userrec* u)
        else
        {
                log(DEBUG,"updated WHOWAS entry");
-               delete iter->second;
+               if (iter->second) delete iter->second;
                iter->second = a;
        }
 }
 
 
 /* add a client connection to the sockets list */
-void AddClient(int socket, char* host, int port, bool iscached)
+void AddClient(int socket, char* host, int port, bool iscached, char* ip)
 {
        int i;
        int blocking = 1;
@@ -2329,7 +2197,7 @@ void AddClient(int socket, char* host, int port, bool iscached)
        clientlist[tempnick] = new userrec();
 
        NonBlocking(socket);
-       log(DEBUG,"AddClient: %d %s %d",socket,host,port);
+       log(DEBUG,"AddClient: %d %s %d %s",socket,host,port,ip);
 
        clientlist[tempnick]->fd = socket;
        strncpy(clientlist[tempnick]->nick, tn2,NICKMAX);
@@ -2338,42 +2206,27 @@ void AddClient(int socket, char* host, int port, bool iscached)
        strncpy(clientlist[tempnick]->server, ServerName,256);
        strncpy(clientlist[tempnick]->ident, "unknown",9);
        clientlist[tempnick]->registered = 0;
-       clientlist[tempnick]->signon = time(NULL);
-       clientlist[tempnick]->nping = time(NULL)+240;
+       clientlist[tempnick]->signon = TIME+dns_timeout;
+       clientlist[tempnick]->nping = TIME+240+dns_timeout;
        clientlist[tempnick]->lastping = 1;
        clientlist[tempnick]->port = port;
-
-       if (iscached)
-       {
-               WriteServ(socket,"NOTICE Auth :Found your hostname (cached)...");
-       }
-       else
-       {
-               WriteServ(socket,"NOTICE Auth :Looking up your hostname...");
-       }
+       strncpy(clientlist[tempnick]->ip,ip,32);
 
        // set the registration timeout for this user
        unsigned long class_regtimeout = 90;
-       for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
-       {
-               if (match(clientlist[tempnick]->host,i->host) && (i->type == CC_ALLOW))
-               {
-                       class_regtimeout = (unsigned long)i->registration_timeout;
-                       break;
-               }
-       }
-
        int class_flood = 0;
+
        for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
        {
                if (match(clientlist[tempnick]->host,i->host) && (i->type == CC_ALLOW))
                {
+                       class_regtimeout = (unsigned long)i->registration_timeout;
                        class_flood = i->flood;
                        break;
                }
        }
 
-       clientlist[tempnick]->timeout = time(NULL)+class_regtimeout;
+       clientlist[tempnick]->timeout = TIME+class_regtimeout;
        clientlist[tempnick]->flood = class_flood;
 
        for (int i = 0; i < MAXCHANS; i++)
@@ -2384,472 +2237,78 @@ void AddClient(int socket, char* host, int port, bool iscached)
 
        if (clientlist.size() == MAXCLIENTS)
                kill_link(clientlist[tempnick],"No more connections allowed in this class");
-}
-
-void handle_names(char **parameters, int pcnt, userrec *user)
-{
-       chanrec* c;
-
-       if (loop_call(handle_names,parameters,pcnt,user,0,pcnt-1,0))
-               return;
-       c = FindChan(parameters[0]);
-       if (c)
-       {
-               /*WriteServ(user->fd,"353 %s = %s :%s", user->nick, c->name,*/
-               userlist(user,c);
-               WriteServ(user->fd,"366 %s %s :End of /NAMES list.", user->nick, c->name);
-       }
-       else
-       {
-               WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
-       }
-}
-
-void handle_privmsg(char **parameters, int pcnt, userrec *user)
-{
-       userrec *dest;
-       chanrec *chan;
+               
 
-       user->idle_lastmsg = time(NULL);
-       
-       if (loop_call(handle_privmsg,parameters,pcnt,user,0,pcnt-2,0))
-               return;
-       if (parameters[0][0] == '#')
+        char* e = matches_exception(ip);
+       if (!e)
        {
-               chan = FindChan(parameters[0]);
-               if (chan)
-               {
-                       if ((chan->noexternal) && (!has_channel(user,chan)))
-                       {
-                               WriteServ(user->fd,"404 %s %s :Cannot send to channel (no external messages)", user->nick, chan->name);
-                               return;
-                       }
-                       if ((chan->moderated) && (cstatus(user,chan)<STATUS_VOICE))
-                       {
-                               WriteServ(user->fd,"404 %s %s :Cannot send to channel (+m)", user->nick, chan->name);
-                               return;
-                       }
-                       
-                       int MOD_RESULT = 0;
-
-                       FOREACH_RESULT(OnUserPreMessage(user,chan,TYPE_CHANNEL,std::string(parameters[1])));
-                       if (MOD_RESULT) {
-                               return;
-                       }
-                       
-                       ChanExceptSender(chan, user, "PRIVMSG %s :%s", chan->name, parameters[1]);
-                       
-                       // if any users of this channel are on remote servers, broadcast the packet
-                       char buffer[MAXBUF];
-                       snprintf(buffer,MAXBUF,"P %s %s :%s",user->nick,chan->name,parameters[1]);
-                       NetSendToCommon(user,buffer);
-               }
-               else
+               char* r = matches_zline(ip);
+               if (r)
                {
-                       /* no such nick/channel */
-                       WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
+                       char reason[MAXBUF];
+                       snprintf(reason,MAXBUF,"Z-Lined: %s",r);
+                       kill_link(clientlist[tempnick],reason);
                }
-               return;
        }
-       
-       dest = Find(parameters[0]);
-       if (dest)
-       {
-               if (strcmp(dest->awaymsg,""))
-               {
-                       /* auto respond with aweh msg */
-                       WriteServ(user->fd,"301 %s %s :%s",user->nick,dest->nick,dest->awaymsg);
-               }
+}
 
-               int MOD_RESULT = 0;
-               
-               FOREACH_RESULT(OnUserPreMessage(user,dest,TYPE_USER,std::string(parameters[1])));
-               if (MOD_RESULT) {
-                       return;
-               }
+// this function counts all users connected, wether they are registered or NOT.
+int usercnt(void)
+{
+       return clientlist.size();
+}
 
+// this counts only registered users, so that the percentages in /MAP don't mess up when users are sitting in an unregistered state
+int registered_usercount(void)
+{
+        int c = 0;
+        for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
+        {
+                if ((i->second->fd) && (isnick(i->second->nick))) c++;
+        }
+        return c;
+}
 
+int usercount_invisible(void)
+{
+       int c = 0;
 
-               if (!strcmp(dest->server,user->server))
-               {
-                       // direct write, same server
-                       WriteTo(user, dest, "PRIVMSG %s :%s", dest->nick, parameters[1]);
-               }
-               else
-               {
-                       char buffer[MAXBUF];
-                       snprintf(buffer,MAXBUF,"P %s %s :%s",user->nick,dest->nick,parameters[1]);
-                       NetSendToOne(dest->server,buffer);
-               }
-       }
-       else
+       for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
        {
-               /* no such nick/channel */
-               WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
+               if ((i->second->fd) && (isnick(i->second->nick)) && (strchr(i->second->modes,'i'))) c++;
        }
+       return c;
 }
 
-void handle_notice(char **parameters, int pcnt, userrec *user)
+int usercount_opers(void)
 {
-       userrec *dest;
-       chanrec *chan;
+       int c = 0;
 
-       user->idle_lastmsg = time(NULL);
-       
-       if (loop_call(handle_notice,parameters,pcnt,user,0,pcnt-2,0))
-               return;
-       if (parameters[0][0] == '#')
+       for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
        {
-               chan = FindChan(parameters[0]);
-               if (chan)
-               {
-                       if ((chan->noexternal) && (!has_channel(user,chan)))
-                       {
-                               WriteServ(user->fd,"404 %s %s :Cannot send to channel (no external messages)", user->nick, chan->name);
-                               return;
-                       }
-                       if ((chan->moderated) && (cstatus(user,chan)<STATUS_VOICE))
-                       {
-                               WriteServ(user->fd,"404 %s %s :Cannot send to channel (+m)", user->nick, chan->name);
-                               return;
-                       }
-
-                       int MOD_RESULT = 0;
-               
-                       FOREACH_RESULT(OnUserPreNotice(user,chan,TYPE_CHANNEL,std::string(parameters[1])));
-                       if (MOD_RESULT) {
-                               return;
-                       }
-
-                       ChanExceptSender(chan, user, "NOTICE %s :%s", chan->name, parameters[1]);
-
-                       // if any users of this channel are on remote servers, broadcast the packet
-                       char buffer[MAXBUF];
-                       snprintf(buffer,MAXBUF,"V %s %s :%s",user->nick,chan->name,parameters[1]);
-                       NetSendToCommon(user,buffer);
-               }
-               else
-               {
-                       /* no such nick/channel */
-                       WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
-               }
-               return;
+               if ((i->second->fd) && (isnick(i->second->nick)) && (strchr(i->second->modes,'o'))) c++;
        }
-       
-       dest = Find(parameters[0]);
-       if (dest)
-       {
-               int MOD_RESULT = 0;
-               
-               FOREACH_RESULT(OnUserPreNotice(user,dest,TYPE_USER,std::string(parameters[1])));
-               if (MOD_RESULT) {
-                       return;
-               }
+       return c;
+}
 
-               if (!strcmp(dest->server,user->server))
-               {
-                       // direct write, same server
-                       WriteTo(user, dest, "NOTICE %s :%s", dest->nick, parameters[1]);
-               }
-               else
-               {
-                       char buffer[MAXBUF];
-                       snprintf(buffer,MAXBUF,"V %s %s :%s",user->nick,dest->nick,parameters[1]);
-                       NetSendToOne(dest->server,buffer);
-               }
-       }
-       else
+int usercount_unknown(void)
+{
+       int c = 0;
+
+       for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
        {
-               /* no such nick/channel */
-               WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
+               if ((i->second->fd) && (i->second->registered != 7))
+                       c++;
        }
+       return c;
 }
 
-
-void handle_info(char **parameters, int pcnt, userrec *user)
+long chancount(void)
 {
-       WriteServ(user->fd,"371 %s :The Inspire IRCd Project Has been brought to you by the following people..",user->nick);
-       WriteServ(user->fd,"371 %s :Craig Edwards, Craig McLure, and Others..",user->nick);
-       WriteServ(user->fd,"371 %s :Will finish this later when i can be arsed :p",user->nick);
-       FOREACH_MOD OnInfo(user);
-       WriteServ(user->fd,"374 %s :End of /INFO list",user->nick);
+       return chanlist.size();
 }
 
-void handle_time(char **parameters, int pcnt, userrec *user)
-{
-       time_t rawtime;
-       struct tm * timeinfo;
-
-       time ( &rawtime );
-       timeinfo = localtime ( &rawtime );
-       WriteServ(user->fd,"391 %s %s :%s",user->nick,ServerName, asctime (timeinfo) );
-  
-}
-
-void handle_whois(char **parameters, int pcnt, userrec *user)
-{
-       userrec *dest;
-       char *t;
-
-       if (loop_call(handle_whois,parameters,pcnt,user,0,pcnt-1,0))
-               return;
-       dest = Find(parameters[0]);
-       if (dest)
-       {
-               // bug found by phidjit - were able to whois an incomplete connection if it had sent a NICK or USER
-               if (dest->registered == 7)
-               {
-                       WriteServ(user->fd,"311 %s %s %s %s * :%s",user->nick, dest->nick, dest->ident, dest->dhost, dest->fullname);
-                       if ((user == dest) || (strchr(user->modes,'o')))
-                       {
-                               WriteServ(user->fd,"378 %s %s :is connecting from *@%s",user->nick, dest->nick, dest->host);
-                       }
-                       if (strcmp(chlist(dest),""))
-                       {
-                               WriteServ(user->fd,"319 %s %s :%s",user->nick, dest->nick, chlist(dest));
-                       }
-                       WriteServ(user->fd,"312 %s %s %s :%s",user->nick, dest->nick, dest->server, GetServerDescription(dest->server).c_str());
-                       if (strcmp(dest->awaymsg,""))
-                       {
-                               WriteServ(user->fd,"301 %s %s :%s",user->nick, dest->nick, dest->awaymsg);
-                       }
-                       if (strchr(dest->modes,'o'))
-                       {
-                               WriteServ(user->fd,"313 %s %s :is an IRC operator",user->nick, dest->nick);
-                       }
-                       FOREACH_MOD OnWhois(user,dest);
-                       if (!strcasecmp(user->server,dest->server))
-                       {
-                               // idle time and signon line can only be sent if youre on the same server (according to RFC)
-                               WriteServ(user->fd,"317 %s %s %d %d :seconds idle, signon time",user->nick, dest->nick, abs((dest->idle_lastmsg)-time(NULL)), dest->signon);
-                       }
-                       
-                       WriteServ(user->fd,"318 %s %s :End of /WHOIS list.",user->nick, dest->nick);
-               }
-               else
-               {
-                       WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
-               }
-       }
-       else
-       {
-               /* no such nick/channel */
-               WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
-       }
-}
-
-void handle_quit(char **parameters, int pcnt, userrec *user)
-{
-       user_hash::iterator iter = clientlist.find(user->nick);
-       char* reason;
-
-       if (user->registered == 7)
-       {
-               /* theres more to do here, but for now just close the socket */
-               if (pcnt == 1)
-               {
-                       if (parameters[0][0] == ':')
-                       {
-                               *parameters[0]++;
-                       }
-                       reason = parameters[0];
-
-                       if (strlen(reason)>MAXQUIT)
-                       {
-                               reason[MAXQUIT-1] = '\0';
-                       }
-
-                       Write(user->fd,"ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,parameters[0]);
-                       WriteOpers("*** Client exiting: %s!%s@%s [%s]",user->nick,user->ident,user->host,parameters[0]);
-                       WriteCommonExcept(user,"QUIT :%s%s",PrefixQuit,parameters[0]);
-
-                       char buffer[MAXBUF];
-                       snprintf(buffer,MAXBUF,"Q %s :%s%s",user->nick,PrefixQuit,parameters[0]);
-                       NetSendToAll(buffer);
-               }
-               else
-               {
-                       Write(user->fd,"ERROR :Closing link (%s@%s) [QUIT]",user->ident,user->host);
-                       WriteOpers("*** Client exiting: %s!%s@%s [Client exited]",user->nick,user->ident,user->host);
-                       WriteCommonExcept(user,"QUIT :Client exited");
-
-                       char buffer[MAXBUF];
-                       snprintf(buffer,MAXBUF,"Q %s :Client exited",user->nick);
-                       NetSendToAll(buffer);
-               }
-               FOREACH_MOD OnUserQuit(user);
-               AddWhoWas(user);
-       }
-
-       /* push the socket on a stack of sockets due to be closed at the next opportunity */
-       fd_reap.push_back(user->fd);
-       
-       if (iter != clientlist.end())
-       {
-               clientlist.erase(iter);
-               log(DEBUG,"deleting user hash value %d",iter->second);
-               //if ((user) && (user->registered == 7)) {
-                       //delete user;
-               //}
-       }
-
-       if (user->registered == 7) {
-               purge_empty_chans();
-       }
-}
-
-void handle_who(char **parameters, int pcnt, userrec *user)
-{
-       chanrec* Ptr = NULL;
-       
-       /* theres more to do here, but for now just close the socket */
-       if (pcnt == 1)
-       {
-               if ((!strcmp(parameters[0],"0")) || (!strcmp(parameters[0],"*")))
-               {
-                       if (user->chans[0].channel)
-                       {
-                               Ptr = user->chans[0].channel;
-                               for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
-                               {
-                                       if ((common_channels(user,i->second)) && (isnick(i->second->nick)))
-                                       {
-                                               WriteServ(user->fd,"352 %s %s %s %s %s %s Hr@ :0 %s",user->nick, Ptr->name, i->second->ident, i->second->dhost, i->second->server, i->second->nick, i->second->fullname);
-                                       }
-                               }
-                       }
-                       if (Ptr)
-                       {
-                               WriteServ(user->fd,"315 %s %s :End of /WHO list.",user->nick, Ptr->name);
-                       }
-                       else
-                       {
-                               WriteServ(user->fd,"315 %s %s :End of /WHO list.",user->nick, user->nick);
-                       }
-                       return;
-               }
-               if (parameters[0][0] == '#')
-               {
-                       Ptr = FindChan(parameters[0]);
-                       if (Ptr)
-                       {
-                               for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
-                               {
-                                       if ((has_channel(i->second,Ptr)) && (isnick(i->second->nick)))
-                                       {
-                                               WriteServ(user->fd,"352 %s %s %s %s %s %s Hr@ :0 %s",user->nick, Ptr->name, i->second->ident, i->second->dhost, i->second->server, i->second->nick, i->second->fullname);
-                                       }
-                               }
-                               WriteServ(user->fd,"315 %s %s :End of /WHO list.",user->nick, Ptr->name);
-                       }
-                       else
-                       {
-                               WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
-                       }
-               }
-               else
-               {
-                       userrec* u = Find(parameters[0]);
-                       WriteServ(user->fd,"352 %s %s %s %s %s %s Hr@ :0 %s",user->nick, u->nick, u->ident, u->dhost, u->server, u->nick, u->fullname);
-               }
-       }
-       if (pcnt == 2)
-       {
-                if ((!strcmp(parameters[0],"0")) || (!strcmp(parameters[0],"*")) && (!strcmp(parameters[1],"o")))
-                {
-                        Ptr = user->chans[0].channel;
-                       for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
-                        {
-                                if ((common_channels(user,i->second)) && (isnick(i->second->nick)))
-                                {
-                                        if (strchr(i->second->modes,'o'))
-                                        {
-                                                WriteServ(user->fd,"352 %s %s %s %s %s %s Hr@ :0 %s",user->nick, Ptr->name, i->second->ident, i->second->dhost, i->second->server, i->second->nick, i->second->fullname);
-                                        }
-                                }
-                        }
-                        WriteServ(user->fd,"315 %s %s :End of /WHO list.",user->nick, Ptr->name);
-                        return;
-                }
-       }
-}
-
-void handle_wallops(char **parameters, int pcnt, userrec *user)
-{
-       WriteWallOps(user,false,"%s",parameters[0]);
-}
-
-void handle_list(char **parameters, int pcnt, userrec *user)
-{
-       chanrec* Ptr;
-       
-       WriteServ(user->fd,"321 %s Channel :Users Name",user->nick);
-       for (chan_hash::const_iterator i = chanlist.begin(); i != chanlist.end(); i++)
-       {
-               if ((!i->second->c_private) && (!i->second->secret))
-               {
-                       WriteServ(user->fd,"322 %s %s %d :[+%s] %s",user->nick,i->second->name,usercount_i(i->second),chanmodes(i->second),i->second->topic);
-               }
-       }
-       WriteServ(user->fd,"323 %s :End of channel list.",user->nick);
-}
-
-
-void handle_rehash(char **parameters, int pcnt, userrec *user)
-{
-       WriteServ(user->fd,"382 %s %s :Rehashing",user->nick,CleanFilename(CONFIG_FILE));
-       ReadConfig();
-       FOREACH_MOD OnRehash();
-       WriteOpers("%s is rehashing config file %s",user->nick,CleanFilename(CONFIG_FILE));
-}
-
-
-int usercnt(void)
-{
-       return clientlist.size();
-}
-
-
-int usercount_invisible(void)
-{
-       int c = 0;
-
-       for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
-       {
-               if ((i->second->fd) && (isnick(i->second->nick)) && (strchr(i->second->modes,'i'))) c++;
-       }
-       return c;
-}
-
-int usercount_opers(void)
-{
-       int c = 0;
-
-       for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
-       {
-               if ((i->second->fd) && (isnick(i->second->nick)) && (strchr(i->second->modes,'o'))) c++;
-       }
-       return c;
-}
-
-int usercount_unknown(void)
-{
-       int c = 0;
-
-       for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
-       {
-               if ((i->second->fd) && (i->second->registered != 7))
-                       c++;
-       }
-       return c;
-}
-
-long chancount(void)
-{
-       return chanlist.size();
-}
-
-long count_servs(void)
+long count_servs(void)
 {
        int c = 0;
        //for (int j = 0; j < 255; j++)
@@ -2876,36 +2335,23 @@ long local_count()
 }
 
 
-void handle_lusers(char **parameters, int pcnt, userrec *user)
-{
-       WriteServ(user->fd,"251 %s :There are %d users and %d invisible on %d servers",user->nick,usercnt()-usercount_invisible(),usercount_invisible(),servercount());
-       WriteServ(user->fd,"252 %s %d :operator(s) online",user->nick,usercount_opers());
-       WriteServ(user->fd,"253 %s %d :unknown connections",user->nick,usercount_unknown());
-       WriteServ(user->fd,"254 %s %d :channels formed",user->nick,chancount());
-       WriteServ(user->fd,"254 %s :I have %d clients and %d servers",user->nick,local_count(),count_servs());
-}
-
-void handle_admin(char **parameters, int pcnt, userrec *user)
-{
-       WriteServ(user->fd,"256 %s :Administrative info for %s",user->nick,ServerName);
-       WriteServ(user->fd,"257 %s :Name     - %s",user->nick,AdminName);
-       WriteServ(user->fd,"258 %s :Nickname - %s",user->nick,AdminNick);
-       WriteServ(user->fd,"258 %s :E-Mail   - %s",user->nick,AdminEmail);
-}
-
 void ShowMOTD(userrec *user)
 {
-       if (!MOTD.size())
-       {
-               WriteServ(user->fd,"422 %s :Message of the day file is missing.",user->nick);
-               return;
-       }
-       WriteServ(user->fd,"375 %s :- %s message of the day",user->nick,ServerName);
-       for (int i = 0; i != MOTD.size(); i++)
-       {
-                               WriteServ(user->fd,"372 %s :- %s",user->nick,MOTD[i].c_str());
-       }
-       WriteServ(user->fd,"376 %s :End of %s message of the day.",user->nick,ServerName);
+        std::string WholeMOTD = "";
+        if (!MOTD.size())
+        {
+                WriteServ(user->fd,"422 %s :Message of the day file is missing.",user->nick);
+                return;
+        }
+        WholeMOTD = std::string(":") + std::string(ServerName) + std::string(" 375 ") + std::string(user->nick) + std::string(" :- ") + std::string(ServerName) + " message of the day\r\n";
+        for (int i = 0; i != MOTD.size(); i++)
+        {
+                WholeMOTD = WholeMOTD + std::string(":") + std::string(ServerName) + std::string(" 372 ") + std::string(user->nick) + std::string(" :- ") + MOTD[i] + std::string("\r\n");
+        }
+        WholeMOTD = WholeMOTD + std::string(":") + std::string(ServerName) + std::string(" 376 ") + std::string(user->nick) + std::string(" :End of message of the day.\r\n");
+        // only one write operation
+        send(user->fd,WholeMOTD.c_str(),WholeMOTD.length(),0);
+
 }
 
 void ShowRULES(userrec *user)
@@ -2924,37 +2370,94 @@ void ShowRULES(userrec *user)
 }
 
 /* shows the message of the day, and any other on-logon stuff */
-void ConnectUser(userrec *user)
+void FullConnectUser(userrec* user)
 {
-       user->registered = 7;
-       user->idle_lastmsg = time(NULL);
+        user->registered = 7;
+        user->idle_lastmsg = TIME;
         log(DEBUG,"ConnectUser: %s",user->nick);
 
-       if (strcmp(Passwd(user),"") && (!user->haspassed))
+        if (strcmp(Passwd(user),"") && (!user->haspassed))
+        {
+                kill_link(user,"Invalid password");
+                return;
+        }
+        if (IsDenied(user))
+        {
+                kill_link(user,"Unauthorised connection");
+                return;
+        }
+
+        char match_against[MAXBUF];
+        snprintf(match_against,MAXBUF,"%s@%s",user->ident,user->host);
+       char* e = matches_exception(match_against);
+       if (!e)
        {
-               kill_link(user,"Invalid password");
-               return;
-       }
-       if (IsDenied(user))
+               char* r = matches_gline(match_against);
+               if (r)
+               {
+                       char reason[MAXBUF];
+                       snprintf(reason,MAXBUF,"G-Lined: %s",r);
+                       kill_link_silent(user,reason);
+                       return;
+               }
+               r = matches_kline(user->host);
+               if (r)
+               {
+                       char reason[MAXBUF];
+                       snprintf(reason,MAXBUF,"K-Lined: %s",r);
+                       kill_link_silent(user,reason);
+                       return;
+               }
+       }
+
+        WriteServ(user->fd,"NOTICE Auth :Welcome to \002%s\002!",Network);
+        WriteServ(user->fd,"001 %s :Welcome to the %s IRC Network %s!%s@%s",user->nick,Network,user->nick,user->ident,user->host);
+        WriteServ(user->fd,"002 %s :Your host is %s, running version %s",user->nick,ServerName,VERSION);
+        WriteServ(user->fd,"003 %s :This server was created %s %s",user->nick,__TIME__,__DATE__);
+        WriteServ(user->fd,"004 %s %s %s iowghraAsORVSxNCWqBzvdHtGI lvhopsmntikrRcaqOALQbSeKVfHGCuzN",user->nick,ServerName,VERSION);
+        // the neatest way to construct the initial 005 numeric, considering the number of configure constants to go in it...
+        std::stringstream v;
+        v << "MESHED WALLCHOPS MODES=13 CHANTYPES=# PREFIX=(ohv)@%+ MAP SAFELIST MAXCHANNELS=" << MAXCHANS;
+        v << " MAXBANS=60 NICKLEN=" << NICKMAX;
+        v << " TOPICLEN=307 KICKLEN=307 MAXTARGETS=20 AWAYLEN=307 CHANMODES=ohvb,k,l,psmnti NETWORK=";
+        v << std::string(Network);
+        std::string data005 = v.str();
+        FOREACH_MOD On005Numeric(data005);
+        // anfl @ #ratbox, efnet reminded me that according to the RFC this cant contain more than 13 tokens per line...
+        // so i'd better split it :)
+        std::stringstream out(data005);
+        std::string token = "";
+        std::string line5 = "";
+        int token_counter = 0;
+        while (!out.eof())
+        {
+                out >> token;
+                line5 = line5 + token + " ";
+                token_counter++;
+                if ((token_counter >= 13) || (out.eof() == true))
+                {
+                        WriteServ(user->fd,"005 %s %s:are supported by this server",user->nick,line5.c_str());
+                        line5 = "";
+                        token_counter = 0;
+                }
+        }
+        ShowMOTD(user);
+        FOREACH_MOD OnUserConnect(user);
+        WriteOpers("*** Client connecting on port %d: %s!%s@%s [%s]",user->port,user->nick,user->ident,user->host,user->ip);
+
+        char buffer[MAXBUF];
+       snprintf(buffer,MAXBUF,"N %d %s %s %s %s +%s %s %s :%s",user->age,user->nick,user->host,user->dhost,user->ident,user->modes,user->ip,ServerName,user->fullname);
+        NetSendToAll(buffer);
+}
+
+/* shows the message of the day, and any other on-logon stuff */
+void ConnectUser(userrec *user)
+{
+       // dns is already done, things are fast. no need to wait for dns to complete just pass them straight on
+       if ((user->dns_done) && (user->registered >= 3))
        {
-               kill_link(user,"Unauthorised connection");
-               return;
+               FullConnectUser(user);
        }
-
-       WriteServ(user->fd,"NOTICE Auth :Welcome to \002%s\002!",Network);
-       WriteServ(user->fd,"001 %s :Welcome to the %s IRC Network %s!%s@%s",user->nick,Network,user->nick,user->ident,user->host);
-       WriteServ(user->fd,"002 %s :Your host is %s, running version %s",user->nick,ServerName,VERSION);
-       WriteServ(user->fd,"003 %s :This server was created %s %s",user->nick,__TIME__,__DATE__);
-       WriteServ(user->fd,"004 %s :%s %s iowghraAsORVSxNCWqBzvdHtGI lvhopsmntikrRcaqOALQbSeKVfHGCuzN",user->nick,ServerName,VERSION);
-       WriteServ(user->fd,"005 %s :MAP KNOCK SAFELIST HCN MAXCHANNELS=20 MAXBANS=60 NICKLEN=30 TOPICLEN=307 KICKLEN=307 MAXTARGETS=20 AWAYLEN=307 :are supported by this server",user->nick);
-       WriteServ(user->fd,"005 %s :WALLCHOPS WATCH=128 SILENCE=5 MODES=13 CHANTYPES=# PREFIX=(ohv)@%c+ CHANMODES=ohvbeqa,kfL,l,psmntirRcOAQKVHGCuzN NETWORK=%s :are supported by this server",user->nick,'%',Network);
-       ShowMOTD(user);
-       FOREACH_MOD OnUserConnect(user);
-       WriteOpers("*** Client connecting on port %d: %s!%s@%s",user->port,user->nick,user->ident,user->host);
-       
-       char buffer[MAXBUF];
-       snprintf(buffer,MAXBUF,"N %d %s %s %s %s +%s %s :%s",user->age,user->nick,user->host,user->dhost,user->ident,user->modes,ServerName,user->fullname);
-       NetSendToAll(buffer);
 }
 
 void handle_version(char **parameters, int pcnt, userrec *user)
@@ -2971,174 +2474,6 @@ void handle_version(char **parameters, int pcnt, userrec *user)
        WriteServ(user->fd,"351 %s :%s Rev. %s %s :%s (O=%d)",user->nick,VERSION,v2,ServerName,SYSTEM,OPTIMISATION);
 }
 
-void handle_ping(char **parameters, int pcnt, userrec *user)
-{
-       WriteServ(user->fd,"PONG %s :%s",ServerName,parameters[0]);
-}
-
-void handle_pong(char **parameters, int pcnt, userrec *user)
-{
-       // set the user as alive so they survive to next ping
-       user->lastping = 1;
-}
-
-void handle_motd(char **parameters, int pcnt, userrec *user)
-{
-       ShowMOTD(user);
-}
-
-void handle_rules(char **parameters, int pcnt, userrec *user)
-{
-       ShowRULES(user);
-}
-
-void handle_user(char **parameters, int pcnt, userrec *user)
-{
-       if (user->registered < 3)
-       {
-               if (isident(parameters[0]) == 0) {
-                       // This kinda Sucks, According to the RFC thou, its either this,
-                       // or "You have already registered" :p -- Craig
-                       WriteServ(user->fd,"461 %s USER :Not enough parameters",user->nick);
-               }
-               else {
-                       WriteServ(user->fd,"NOTICE Auth :No ident response, ident prefixed with ~");
-                       strcpy(user->ident,"~"); /* we arent checking ident... but these days why bother anyway? */
-                       strncat(user->ident,parameters[0],IDENTMAX);
-                       strncpy(user->fullname,parameters[3],128);
-                       user->registered = (user->registered | 1);
-               }
-       }
-       else
-       {
-               WriteServ(user->fd,"462 %s :You may not reregister",user->nick);
-               return;
-       }
-       /* parameters 2 and 3 are local and remote hosts, ignored when sent by client connection */
-       if (user->registered == 3)
-       {
-               /* user is registered now, bit 0 = USER command, bit 1 = sent a NICK command */
-               ConnectUser(user);
-       }
-}
-
-void handle_userhost(char **parameters, int pcnt, userrec *user)
-{
-       char Return[MAXBUF],junk[MAXBUF];
-       sprintf(Return,"302 %s :",user->nick);
-       for (int i = 0; i < pcnt; i++)
-       {
-               userrec *u = Find(parameters[i]);
-               if (u)
-               {
-                       if (strchr(u->modes,'o'))
-                       {
-                               sprintf(junk,"%s*=+%s@%s ",u->nick,u->ident,u->host);
-                               strcat(Return,junk);
-                       }
-                       else
-                       {
-                               sprintf(junk,"%s=+%s@%s ",u->nick,u->ident,u->host);
-                               strcat(Return,junk);
-                       }
-               }
-       }
-       WriteServ(user->fd,Return);
-}
-
-
-void handle_ison(char **parameters, int pcnt, userrec *user)
-{
-       char Return[MAXBUF];
-       sprintf(Return,"303 %s :",user->nick);
-       for (int i = 0; i < pcnt; i++)
-       {
-               userrec *u = Find(parameters[i]);
-               if (u)
-               {
-                       strcat(Return,u->nick);
-                       strcat(Return," ");
-               }
-       }
-       WriteServ(user->fd,Return);
-}
-
-
-void handle_away(char **parameters, int pcnt, userrec *user)
-{
-       if (pcnt)
-       {
-               strcpy(user->awaymsg,parameters[0]);
-               WriteServ(user->fd,"306 %s :You have been marked as being away",user->nick);
-       }
-       else
-       {
-               strcpy(user->awaymsg,"");
-               WriteServ(user->fd,"305 %s :You are no longer marked as being away",user->nick);
-       }
-}
-
-void handle_whowas(char **parameters, int pcnt, userrec* user)
-{
-       user_hash::iterator i = whowas.find(parameters[0]);
-
-       if (i == whowas.end())
-       {
-               WriteServ(user->fd,"406 %s %s :There was no such nickname",user->nick,parameters[0]);
-               WriteServ(user->fd,"369 %s %s :End of WHOWAS",user->nick,parameters[0]);
-       }
-       else
-       {
-               time_t rawtime = i->second->signon;
-               tm *timeinfo;
-               char b[MAXBUF];
-               
-               timeinfo = localtime(&rawtime);
-               strcpy(b,asctime(timeinfo));
-               b[strlen(b)-1] = '\0';
-               
-               WriteServ(user->fd,"314 %s %s %s %s * :%s",user->nick,i->second->nick,i->second->ident,i->second->dhost,i->second->fullname);
-               WriteServ(user->fd,"312 %s %s %s :%s",user->nick,i->second->nick,i->second->server,b);
-               WriteServ(user->fd,"369 %s %s :End of WHOWAS",user->nick,parameters[0]);
-       }
-
-}
-
-void handle_trace(char **parameters, int pcnt, userrec *user)
-{
-       for (user_hash::iterator i = clientlist.begin(); i != clientlist.end(); i++)
-       {
-               if (i->second)
-               {
-                       if (isnick(i->second->nick))
-                       {
-                               if (strchr(i->second->modes,'o'))
-                               {
-                                       WriteServ(user->fd,"205 %s :Oper 0 %s",user->nick,i->second->nick);
-                               }
-                               else
-                               {
-                                       WriteServ(user->fd,"204 %s :User 0 %s",user->nick,i->second->nick);
-                               }
-                       }
-                       else
-                       {
-                               WriteServ(user->fd,"203 %s :???? 0 [%s]",user->nick,i->second->host);
-                       }
-               }
-       }
-}
-
-void handle_modules(char **parameters, int pcnt, userrec *user)
-{
-       for (int i = 0; i < module_names.size(); i++)
-       {
-                       Version V = modules[i]->GetVersion();
-                       char modulename[MAXBUF];
-                       strncpy(modulename,module_names[i].c_str(),256);
-                       WriteServ(user->fd,"900 %s :0x%08lx %d.%d.%d.%d %s",user->nick,modules[i],V.Major,V.Minor,V.Revision,V.Build,CleanFilename(modulename));
-       }
-}
 
 // calls a handler function for a command
 
@@ -3162,152 +2497,6 @@ void call_handler(const char* commandname,char **parameters, int pcnt, userrec *
                }
 }
 
-void handle_stats(char **parameters, int pcnt, userrec *user)
-{
-       if (pcnt != 1)
-       {
-               return;
-       }
-       if (strlen(parameters[0])>1)
-       {
-               /* make the stats query 1 character long */
-               parameters[0][1] = '\0';
-       }
-
-       /* stats m (list number of times each command has been used, plus bytecount) */
-       if (!strcasecmp(parameters[0],"m"))
-       {
-               for (int i = 0; i < cmdlist.size(); i++)
-               {
-                       if (cmdlist[i].handler_function)
-                       {
-                               if (cmdlist[i].use_count)
-                               {
-                                       /* RPL_STATSCOMMANDS */
-                                       WriteServ(user->fd,"212 %s %s %d %d",user->nick,cmdlist[i].command,cmdlist[i].use_count,cmdlist[i].total_bytes);
-                               }
-                       }
-               }
-                       
-       }
-
-       /* stats z (debug and memory info) */
-       if (!strcasecmp(parameters[0],"z"))
-       {
-               WriteServ(user->fd,"249 %s :Users(HASH_MAP) %d (%d bytes, %d buckets)",user->nick,clientlist.size(),clientlist.size()*sizeof(userrec),clientlist.bucket_count());
-               WriteServ(user->fd,"249 %s :Channels(HASH_MAP) %d (%d bytes, %d buckets)",user->nick,chanlist.size(),chanlist.size()*sizeof(chanrec),chanlist.bucket_count());
-               WriteServ(user->fd,"249 %s :Commands(VECTOR) %d (%d bytes)",user->nick,cmdlist.size(),cmdlist.size()*sizeof(command_t));
-               WriteServ(user->fd,"249 %s :MOTD(VECTOR) %d, RULES(VECTOR) %d",user->nick,MOTD.size(),RULES.size());
-               WriteServ(user->fd,"249 %s :address_cache(HASH_MAP) %d (%d buckets)",user->nick,IP.size(),IP.bucket_count());
-               WriteServ(user->fd,"249 %s :Modules(VECTOR) %d (%d)",user->nick,modules.size(),modules.size()*sizeof(Module));
-               WriteServ(user->fd,"249 %s :ClassFactories(VECTOR) %d (%d)",user->nick,factory.size(),factory.size()*sizeof(ircd_module));
-               WriteServ(user->fd,"249 %s :Ports(STATIC_ARRAY) %d",user->nick,boundPortCount);
-       }
-       
-       /* stats o */
-       if (!strcasecmp(parameters[0],"o"))
-       {
-               for (int i = 0; i < ConfValueEnum("oper",&config_f); i++)
-               {
-                       char LoginName[MAXBUF];
-                       char HostName[MAXBUF];
-                       char OperType[MAXBUF];
-                       ConfValue("oper","name",i,LoginName,&config_f);
-                       ConfValue("oper","host",i,HostName,&config_f);
-                       ConfValue("oper","type",i,OperType,&config_f);
-                       WriteServ(user->fd,"243 %s O %s * %s %s 0",user->nick,HostName,LoginName,OperType);
-               }
-       }
-       
-       /* stats l (show user I/O stats) */
-       if (!strcasecmp(parameters[0],"l"))
-       {
-               WriteServ(user->fd,"211 %s :server:port nick bytes_in cmds_in bytes_out cmds_out",user->nick);
-               for (user_hash::iterator i = clientlist.begin(); i != clientlist.end(); i++)
-               {
-                       if (isnick(i->second->nick))
-                       {
-                               WriteServ(user->fd,"211 %s :%s:%d %s %d %d %d %d",user->nick,ServerName,i->second->port,i->second->nick,i->second->bytes_in,i->second->cmds_in,i->second->bytes_out,i->second->cmds_out);
-                       }
-                       else
-                       {
-                               WriteServ(user->fd,"211 %s :%s:%d (unknown@%d) %d %d %d %d",user->nick,ServerName,i->second->port,i->second->fd,i->second->bytes_in,i->second->cmds_in,i->second->bytes_out,i->second->cmds_out);
-                       }
-                       
-               }
-       }
-       
-       /* stats u (show server uptime) */
-       if (!strcasecmp(parameters[0],"u"))
-       {
-               time_t current_time = 0;
-               current_time = time(NULL);
-               time_t server_uptime = current_time - startup_time;
-               struct tm* stime;
-               stime = gmtime(&server_uptime);
-               /* i dont know who the hell would have an ircd running for over a year nonstop, but
-                * Craig suggested this, and it seemed a good idea so in it went */
-               if (stime->tm_year > 70)
-               {
-                       WriteServ(user->fd,"242 %s :Server up %d years, %d days, %.2d:%.2d:%.2d",user->nick,(stime->tm_year-70),stime->tm_yday,stime->tm_hour,stime->tm_min,stime->tm_sec);
-               }
-               else
-               {
-                       WriteServ(user->fd,"242 %s :Server up %d days, %.2d:%.2d:%.2d",user->nick,stime->tm_yday,stime->tm_hour,stime->tm_min,stime->tm_sec);
-               }
-       }
-
-       WriteServ(user->fd,"219 %s %s :End of /STATS report",user->nick,parameters[0]);
-       WriteOpers("*** Notice: Stats '%s' requested by %s (%s@%s)",parameters[0],user->nick,user->ident,user->host);
-       
-}
-
-void handle_connect(char **parameters, int pcnt, userrec *user)
-{
-       char Link_ServerName[1024];
-       char Link_IPAddr[1024];
-       char Link_Port[1024];
-       char Link_Pass[1024];
-       int LinkPort;
-       bool found = false;
-       
-       for (int i = 0; i < ConfValueEnum("link",&config_f); i++)
-       {
-               if (!found)
-               {
-                       ConfValue("link","name",i,Link_ServerName,&config_f);
-                       ConfValue("link","ipaddr",i,Link_IPAddr,&config_f);
-                       ConfValue("link","port",i,Link_Port,&config_f);
-                       ConfValue("link","sendpass",i,Link_Pass,&config_f);
-                       log(DEBUG,"(%d) Comparing against name='%s', ipaddr='%s', port='%s', recvpass='%s'",i,Link_ServerName,Link_IPAddr,Link_Port,Link_Pass);
-                       LinkPort = atoi(Link_Port);
-                       if (match(Link_ServerName,parameters[0])) {
-                               found = true;
-                               break;
-                       }
-               }
-       }
-       
-       if (!found) {
-               WriteServ(user->fd,"NOTICE %s :*** Failed to connect to %s: No servers matching this pattern are configured for linking.",user->nick,parameters[0]);
-               return;
-       }
-       
-       // TODO: Perform a check here to stop a server being linked twice!
-
-       WriteServ(user->fd,"NOTICE %s :*** Connecting to %s (%s) port %s...",user->nick,Link_ServerName,Link_IPAddr,Link_Port);
-
-       if (me[defaultRoute])
-       {
-               me[defaultRoute]->BeginLink(Link_IPAddr,LinkPort,Link_Pass,Link_ServerName,me[defaultRoute]->port);
-               return;
-       }
-       else
-       {
-               WriteServ(user->fd,"NOTICE %s :No default route is defined for server connections on this server. You must define a server connection to be default route so that sockets can be bound to it.",user->nick);
-       }
-}
-
 void DoSplitEveryone()
 {
        bool go_again = true;
@@ -3356,227 +2545,57 @@ void DoSplitEveryone()
 
 
 
-void handle_squit(char **parameters, int pcnt, userrec *user)
-{
-       // send out an squit across the mesh and then clear the server list (for local squit)
-       if (!pcnt)
-       {
-               WriteOpers("SQUIT command issued by %s",user->nick);
-               char buffer[MAXBUF];
-               snprintf(buffer,MAXBUF,"& %s",ServerName);
-               NetSendToAll(buffer);
-               DoSplitEveryone();
-       }
-       else
-       {
-               WriteServ(user->fd,"NOTICE :*** Remote SQUIT not supported yet.");
-       }
-}
-
 char islast(const char* s)
 {
        char c = '`';
        for (int j = 0; j < 32; j++)
-       {
-               if (me[j] != NULL)
-               {
-                       for (int k = 0; k < me[j]->connectors.size(); k++)
-                       {
-                               if (strcasecmp(me[j]->connectors[k].GetServerName().c_str(),s))
-                               {
-                                       c = '|';
-                               }
-                               if (!strcasecmp(me[j]->connectors[k].GetServerName().c_str(),s))
-                               {
-                                       c = '`';
-                               }
-                       }
-               }
-       }
-       return c;
-}
-
-long map_count(const char* s)
-{
-       int c = 0;
-       for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
-       {
-               if ((i->second->fd) && (isnick(i->second->nick)) && (!strcasecmp(i->second->server,s))) c++;
-       }
-       return c;
-}
-
-void handle_links(char **parameters, int pcnt, userrec *user)
-{
-       WriteServ(user->fd,"364 %s %s %s :0 %s",user->nick,ServerName,ServerName,ServerDesc);
-       for (int j = 0; j < 32; j++)
-       {
-               if (me[j] != NULL)
-               {
-                       for (int k = 0; k < me[j]->connectors.size(); k++)
-                       {
-                               WriteServ(user->fd,"364 %s %s %s :1 %s",user->nick,me[j]->connectors[k].GetServerName().c_str(),ServerName,me[j]->connectors[k].GetDescription().c_str());
-                       }
-               }
-       }
-       WriteServ(user->fd,"365 %s * :End of /LINKS list.",user->nick);
-}
-
-void handle_map(char **parameters, int pcnt, userrec *user)
-{
-       char line[MAXBUF];
-       snprintf(line,MAXBUF,"006 %s :%s",user->nick,ServerName);
-       while (strlen(line) < 50)
-               strcat(line," ");
-       WriteServ(user->fd,"%s%d (%.2f%%)",line,local_count(),(float)(((float)local_count()/(float)usercnt())*100));
-       for (int j = 0; j < 32; j++)
-       {
-               if (me[j] != NULL)
-               {
-                       for (int k = 0; k < me[j]->connectors.size(); k++)
-                       {
-                               snprintf(line,MAXBUF,"006 %s :%c-%s",user->nick,islast(me[j]->connectors[k].GetServerName().c_str()),me[j]->connectors[k].GetServerName().c_str());
-                               while (strlen(line) < 50)
-                                       strcat(line," ");
-                               WriteServ(user->fd,"%s%d (%.2f%%)",line,map_count(me[j]->connectors[k].GetServerName().c_str()),(float)(((float)map_count(me[j]->connectors[k].GetServerName().c_str())/(float)usercnt())*100));
-                       }
-               }
-       }
-       WriteServ(user->fd,"007 %s :End of /MAP",user->nick);
-}
-
-
-void handle_oper(char **parameters, int pcnt, userrec *user)
-{
-       char LoginName[MAXBUF];
-       char Password[MAXBUF];
-       char OperType[MAXBUF];
-       char TypeName[MAXBUF];
-       char Hostname[MAXBUF];
-       int i,j;
-
-       for (int i = 0; i < ConfValueEnum("oper",&config_f); i++)
-       {
-               ConfValue("oper","name",i,LoginName,&config_f);
-               ConfValue("oper","password",i,Password,&config_f);
-               if ((!strcmp(LoginName,parameters[0])) && (!strcmp(Password,parameters[1])))
-               {
-                       /* correct oper credentials */
-                       ConfValue("oper","type",i,OperType,&config_f);
-                       WriteOpers("*** %s (%s@%s) is now an IRC operator of type %s",user->nick,user->ident,user->host,OperType);
-                       WriteServ(user->fd,"381 %s :You are now an IRC operator of type %s",user->nick,OperType);
-                       WriteServ(user->fd,"MODE %s :+o",user->nick);
-                       for (j =0; j < ConfValueEnum("type",&config_f); j++)
-                       {
-                               ConfValue("type","name",j,TypeName,&config_f);
-                               if (!strcmp(TypeName,OperType))
-                               {
-                                       /* found this oper's opertype */
-                                       ConfValue("type","host",j,Hostname,&config_f);
-                                       ChangeDisplayedHost(user,Hostname);
-                               }
-                       }
-                       if (!strchr(user->modes,'o'))
-                       {
-                               strcat(user->modes,"o");
-                       }
-                       FOREACH_MOD OnOper(user);
-                       return;
-               }
-       }
-       /* no such oper */
-       WriteServ(user->fd,"491 %s :Invalid oper credentials",user->nick);
-       WriteOpers("*** WARNING! Failed oper attempt by %s!%s@%s!",user->nick,user->ident,user->host);
-}
-
-void handle_nick(char **parameters, int pcnt, userrec *user)
-{
-       if (pcnt < 1) 
-       {
-               log(DEBUG,"not enough params for handle_nick");
-               return;
-       }
-       if (!parameters[0])
-       {
-               log(DEBUG,"invalid parameter passed to handle_nick");
-               return;
-       }
-       if (!strlen(parameters[0]))
-       {
-               log(DEBUG,"zero length new nick passed to handle_nick");
-               return;
-       }
-       if (!user)
-       {
-               log(DEBUG,"invalid user passed to handle_nick");
-               return;
-       }
-       if (!user->nick)
-       {
-               log(DEBUG,"invalid old nick passed to handle_nick");
-               return;
-       }
-       if (!strcasecmp(user->nick,parameters[0]))
-       {
-               log(DEBUG,"old nick is new nick, skipping");
-               return;
-       }
-       else
-       {
-               if (strlen(parameters[0]) > 1)
-               {
-                       if (parameters[0][0] == ':')
+       {
+               if (me[j] != NULL)
+               {
+                       for (int k = 0; k < me[j]->connectors.size(); k++)
                        {
-                               *parameters[0]++;
+                               if (strcasecmp(me[j]->connectors[k].GetServerName().c_str(),s))
+                               {
+                                       c = '|';
+                               }
+                               if (!strcasecmp(me[j]->connectors[k].GetServerName().c_str(),s))
+                               {
+                                       c = '`';
+                               }
                        }
                }
-               if ((Find(parameters[0])) && (Find(parameters[0]) != user))
-               {
-                       WriteServ(user->fd,"433 %s %s :Nickname is already in use.",user->nick,parameters[0]);
-                       return;
-               }
-       }
-       if (isnick(parameters[0]) == 0)
-       {
-               WriteServ(user->fd,"432 %s %s :Erroneous Nickname",user->nick,parameters[0]);
-               return;
-       }
-
-       if (user->registered == 7)
-       {
-               WriteCommon(user,"NICK %s",parameters[0]);
-               
-               // Q token must go to ALL servers!!!
-               char buffer[MAXBUF];
-               snprintf(buffer,MAXBUF,"n %s %s",user->nick,parameters[0]);
-               NetSendToAll(buffer);
-               
        }
-       
-       /* change the nick of the user in the users_hash */
-       user = ReHashNick(user->nick, parameters[0]);
-       /* actually change the nick within the record */
-       if (!user) return;
-       if (!user->nick) return;
-
-       strncpy(user->nick, parameters[0],NICKMAX);
+       return c;
+}
 
-       log(DEBUG,"new nick set: %s",user->nick);
-       
-       if (user->registered < 3)
-               user->registered = (user->registered | 2);
-       if (user->registered == 3)
+long map_count(const char* s)
+{
+       int c = 0;
+       for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
        {
-               /* user is registered now, bit 0 = USER command, bit 1 = sent a NICK command */
-               ConnectUser(user);
+               if ((i->second->fd) && (isnick(i->second->nick)) && (!strcasecmp(i->second->server,s))) c++;
        }
-       log(DEBUG,"exit nickchange: %s",user->nick);
+       return c;
 }
 
+
 void force_nickchange(userrec* user,const char* newnick)
 {
        char nick[MAXBUF];
+       int MOD_RESULT = 0;
+       
        strcpy(nick,"");
+
+       FOREACH_RESULT(OnUserPreNick(user,newnick));
+       if (MOD_RESULT) {
+               kill_link(user,"Nickname collision");
+               return;
+       }
+       if (matches_qline(newnick))
+       {
+               kill_link(user,"Nickname collision");
+               return;
+       }
        
        if (user)
        {
@@ -3687,17 +2706,18 @@ void process_command(userrec *user, char* cmd)
        // another phidjit bug...
        if (total_params > 126)
        {
-               kill_link(user,"Protocol violation (1)");
+               //kill_link(user,"Protocol violation (1)");
+               WriteServ(user->fd,"421 %s * :Unknown command",user->nick);
                return;
        }
        
-       strcpy(temp,cmd);
+       strlcpy(temp,cmd,MAXBUF);
 
        std::string tmp = cmd;
        for (int i = 0; i <= MODCOUNT; i++)
        {
                std::string oldtmp = tmp;
-               modules[i]->OnServerRaw(tmp,true);
+               modules[i]->OnServerRaw(tmp,true,user);
                if (oldtmp != tmp)
                {
                        log(DEBUG,"A Module changed the input string!");
@@ -3706,8 +2726,8 @@ void process_command(userrec *user, char* cmd)
                        break;
                }
        }
-       strncpy(cmd,tmp.c_str(),MAXBUF);
-       strcpy(temp,cmd);
+       strlcpy(cmd,tmp.c_str(),MAXBUF);
+       strlcpy(temp,cmd,MAXBUF);
 
        if (!strchr(cmd,' '))
        {
@@ -3770,7 +2790,8 @@ void process_command(userrec *user, char* cmd)
        
        if (strlen(command)>MAXCOMMAND)
        {
-               kill_link(user,"Protocol violation (2)");
+               //kill_link(user,"Protocol violation (2)");
+               WriteServ(user->fd,"421 %s * :Unknown command",user->nick);
                return;
        }
        
@@ -3780,9 +2801,10 @@ void process_command(userrec *user, char* cmd)
                {
                        if (((command[x] < '0') || (command[x]> '9')) && (command[x] != '-'))
                        {
-                               if (!strchr("@!\"$%^&*(){}[]_-=+;:'#~,.<>/?\\|`",command[x]))
+                               if (strchr("@!\"$%^&*(){}[]_=+;:'#~,<>/?\\|`",command[x]))
                                {
-                                       kill_link(user,"Protocol violation (3)");
+                                       //kill_link(user,"Protocol violation (3)");
+                                       WriteServ(user->fd,"421 %s * :Unknown command",user->nick);
                                        return;
                                }
                        }
@@ -3820,7 +2842,7 @@ void process_command(userrec *user, char* cmd)
                                        log(DEBUG,"Processing command");
                                        
                                        /* activity resets the ping pending timer */
-                                       user->nping = time(NULL) + 120;
+                                       user->nping = TIME + 120;
                                        if ((items) < cmdlist[i].min_params)
                                        {
                                                log(DEBUG,"process_command: not enough parameters: %s %s",user->nick,command);
@@ -3834,6 +2856,13 @@ void process_command(userrec *user, char* cmd)
                                                cmd_found = 1;
                                                return;
                                        }
+                                       if ((cmdlist[i].flags_needed) && (!user->HasPermission(command)))
+                                       {
+                                               log(DEBUG,"process_command: permission denied: %s %s",user->nick,command);
+                                               WriteServ(user->fd,"481 %s :Permission Denied- Oper type %s does not have access to command %s",user->nick,user->oper,command);
+                                               cmd_found = 1;
+                                               return;
+                                       }
                                        /* if the command isnt USER, PASS, or NICK, and nick is empty,
                                         * deny command! */
                                        if ((strncmp(command,"USER",4)) && (strncmp(command,"NICK",4)) && (strncmp(command,"PASS",4)))
@@ -3857,6 +2886,8 @@ void process_command(userrec *user, char* cmd)
                                                                {
                                                                        user->bytes_in += strlen(temp);
                                                                        user->cmds_in++;
+                                                                       user->bytes_out+=strlen(temp);
+                                                                       user->cmds_out++;
                                                                }
                                                                cmdlist[i].use_count++;
                                                                cmdlist[i].total_bytes+=strlen(temp);
@@ -3889,11 +2920,12 @@ void process_command(userrec *user, char* cmd)
 }
 
 
-void createcommand(char* cmd, handlerfunc f, char flags, int minparams)
+void createcommand(char* cmd, handlerfunc f, char flags, int minparams,char* source)
 {
        command_t comm;
        /* create the command and push it onto the table */     
-       strcpy(comm.command,cmd);
+       strlcpy(comm.command,cmd,MAXBUF);
+       strlcpy(comm.source,source,MAXBUF);
        comm.handler_function = f;
        comm.flags_needed = flags;
        comm.min_params = minparams;
@@ -3903,52 +2935,80 @@ void createcommand(char* cmd, handlerfunc f, char flags, int minparams)
        log(DEBUG,"Added command %s (%d parameters)",cmd,minparams);
 }
 
+bool removecommands(const char* source)
+{
+       bool go_again = true;
+       while (go_again)
+       {
+               go_again = false;
+               for (std::deque<command_t>::iterator i = cmdlist.begin(); i != cmdlist.end(); i++)
+               {
+                       if (!strcmp(i->source,source))
+                       {
+                               log(DEBUG,"removecommands(%s) Removing dependent command: %s",i->source,i->command);
+                               cmdlist.erase(i);
+                               go_again = true;
+                               break;
+                       }
+               }
+       }
+       return true;
+}
+
 void SetupCommandTable(void)
 {
-       createcommand("USER",handle_user,0,4);
-       createcommand("NICK",handle_nick,0,1);
-       createcommand("QUIT",handle_quit,0,0);
-       createcommand("VERSION",handle_version,0,0);
-       createcommand("PING",handle_ping,0,1);
-       createcommand("PONG",handle_pong,0,1);
-       createcommand("ADMIN",handle_admin,0,0);
-       createcommand("PRIVMSG",handle_privmsg,0,2);
-       createcommand("INFO",handle_info,0,0);
-       createcommand("TIME",handle_time,0,0);
-       createcommand("WHOIS",handle_whois,0,1);
-       createcommand("WALLOPS",handle_wallops,'o',1);
-       createcommand("NOTICE",handle_notice,0,2);
-       createcommand("JOIN",handle_join,0,1);
-       createcommand("NAMES",handle_names,0,1);
-       createcommand("PART",handle_part,0,1);
-       createcommand("KICK",handle_kick,0,2);
-       createcommand("MODE",handle_mode,0,1);
-       createcommand("TOPIC",handle_topic,0,1);
-       createcommand("WHO",handle_who,0,1);
-       createcommand("MOTD",handle_motd,0,0);
-       createcommand("RULES",handle_rules,0,0);
-       createcommand("OPER",handle_oper,0,2);
-       createcommand("LIST",handle_list,0,0);
-       createcommand("DIE",handle_die,'o',1);
-       createcommand("RESTART",handle_restart,'o',1);
-       createcommand("KILL",handle_kill,'o',2);
-       createcommand("REHASH",handle_rehash,'o',0);
-       createcommand("LUSERS",handle_lusers,0,0);
-       createcommand("STATS",handle_stats,0,1);
-       createcommand("USERHOST",handle_userhost,0,1);
-       createcommand("AWAY",handle_away,0,0);
-       createcommand("ISON",handle_ison,0,0);
-       createcommand("SUMMON",handle_summon,0,0);
-       createcommand("USERS",handle_users,0,0);
-       createcommand("INVITE",handle_invite,0,2);
-       createcommand("PASS",handle_pass,0,1);
-       createcommand("TRACE",handle_trace,'o',0);
-       createcommand("WHOWAS",handle_whowas,0,1);
-       createcommand("CONNECT",handle_connect,'o',1);
-       createcommand("SQUIT",handle_squit,'o',0);
-       createcommand("MODULES",handle_modules,'o',0);
-       createcommand("LINKS",handle_links,0,0);
-       createcommand("MAP",handle_map,0,0);
+       createcommand("USER",handle_user,0,4,"<core>");
+       createcommand("NICK",handle_nick,0,1,"<core>");
+       createcommand("QUIT",handle_quit,0,0,"<core>");
+       createcommand("VERSION",handle_version,0,0,"<core>");
+       createcommand("PING",handle_ping,0,1,"<core>");
+       createcommand("PONG",handle_pong,0,1,"<core>");
+       createcommand("ADMIN",handle_admin,0,0,"<core>");
+       createcommand("PRIVMSG",handle_privmsg,0,2,"<core>");
+       createcommand("INFO",handle_info,0,0,"<core>");
+       createcommand("TIME",handle_time,0,0,"<core>");
+       createcommand("WHOIS",handle_whois,0,1,"<core>");
+       createcommand("WALLOPS",handle_wallops,'o',1,"<core>");
+       createcommand("NOTICE",handle_notice,0,2,"<core>");
+       createcommand("JOIN",handle_join,0,1,"<core>");
+       createcommand("NAMES",handle_names,0,1,"<core>");
+       createcommand("PART",handle_part,0,1,"<core>");
+       createcommand("KICK",handle_kick,0,2,"<core>");
+       createcommand("MODE",handle_mode,0,1,"<core>");
+       createcommand("TOPIC",handle_topic,0,1,"<core>");
+       createcommand("WHO",handle_who,0,1,"<core>");
+       createcommand("MOTD",handle_motd,0,0,"<core>");
+       createcommand("RULES",handle_rules,0,0,"<core>");
+       createcommand("OPER",handle_oper,0,2,"<core>");
+       createcommand("LIST",handle_list,0,0,"<core>");
+       createcommand("DIE",handle_die,'o',1,"<core>");
+       createcommand("RESTART",handle_restart,'o',1,"<core>");
+       createcommand("KILL",handle_kill,'o',2,"<core>");
+       createcommand("REHASH",handle_rehash,'o',0,"<core>");
+       createcommand("LUSERS",handle_lusers,0,0,"<core>");
+       createcommand("STATS",handle_stats,0,1,"<core>");
+       createcommand("USERHOST",handle_userhost,0,1,"<core>");
+       createcommand("AWAY",handle_away,0,0,"<core>");
+       createcommand("ISON",handle_ison,0,0,"<core>");
+       createcommand("SUMMON",handle_summon,0,0,"<core>");
+       createcommand("USERS",handle_users,0,0,"<core>");
+       createcommand("INVITE",handle_invite,0,2,"<core>");
+       createcommand("PASS",handle_pass,0,1,"<core>");
+       createcommand("TRACE",handle_trace,'o',0,"<core>");
+       createcommand("WHOWAS",handle_whowas,0,1,"<core>");
+       createcommand("CONNECT",handle_connect,'o',1,"<core>");
+       createcommand("SQUIT",handle_squit,'o',0,"<core>");
+       createcommand("MODULES",handle_modules,'o',0,"<core>");
+       createcommand("LINKS",handle_links,0,0,"<core>");
+       createcommand("MAP",handle_map,0,0,"<core>");
+       createcommand("KLINE",handle_kline,'o',1,"<core>");
+       createcommand("GLINE",handle_gline,'o',1,"<core>");
+       createcommand("ZLINE",handle_zline,'o',1,"<core>");
+       createcommand("QLINE",handle_qline,'o',1,"<core>");
+       createcommand("ELINE",handle_eline,'o',1,"<core>");
+       createcommand("LOADMODULE",handle_loadmodule,'o',1,"<core>");
+       createcommand("UNLOADMODULE",handle_unloadmodule,'o',1,"<core>");
+       createcommand("SERVER",handle_server,0,0,"<core>");
 }
 
 void process_buffer(const char* cmdbuf,userrec *user)
@@ -3969,7 +3029,9 @@ void process_buffer(const char* cmdbuf,userrec *user)
        {
                return;
        }
-       strncpy(cmd,cmdbuf,MAXBUF);
+       while ((cmdbuf[0] == ' ') && (strlen(cmdbuf)>0)) cmdbuf++; // strip leading spaces
+
+       strlcpy(cmd,cmdbuf,MAXBUF);
        if (!strcmp(cmd,""))
        {
                return;
@@ -3982,6 +3044,12 @@ void process_buffer(const char* cmdbuf,userrec *user)
        {
                cmd[strlen(cmd)-1] = '\0';
        }
+
+       while ((cmd[strlen(cmd)-1] == ' ') && (strlen(cmd)>0)) // strip trailing spaces
+       {
+               cmd[strlen(cmd)-1] = '\0';
+       }
+
        if (!strcmp(cmd,""))
        {
                return;
@@ -3994,510 +3062,93 @@ void process_buffer(const char* cmdbuf,userrec *user)
        }
 }
 
-void DoSync(serverrec* serv, char* udp_host)
-{
-       char data[MAXBUF];
-       // send start of sync marker: Y <timestamp>
-       // at this point the ircd receiving it starts broadcasting this netburst to all ircds
-       // except the ones its receiving it from.
-       snprintf(data,MAXBUF,"Y %d",time(NULL));
-       serv->SendPacket(data,udp_host);
-       // send users and channels
-       for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
-       {
-               snprintf(data,MAXBUF,"N %d %s %s %s %s +%s %s :%s",u->second->age,u->second->nick,u->second->host,u->second->dhost,u->second->ident,u->second->modes,u->second->server,u->second->fullname);
-               serv->SendPacket(data,udp_host);
-               if (strcmp(chlist(u->second),""))
-               {
-                       snprintf(data,MAXBUF,"J %s %s",u->second->nick,chlist(u->second));
-                       serv->SendPacket(data,udp_host);
-               }
-       }
-       // send channel modes, topics etc...
-       for (chan_hash::iterator c = chanlist.begin(); c != chanlist.end(); c++)
-       {
-               snprintf(data,MAXBUF,"M %s +%s",c->second->name,chanmodes(c->second));
-               serv->SendPacket(data,udp_host);
-               if (strcmp(c->second->topic,""))
-               {
-                       snprintf(data,MAXBUF,"T %d %s %s :%s",c->second->topicset,c->second->setby,c->second->name,c->second->topic);
-                       serv->SendPacket(data,udp_host);
-               }
-               // send current banlist
-               
-               for (BanList::iterator b = c->second->bans.begin(); b != c->second->bans.end(); b++)
-               {
-                       snprintf(data,MAXBUF,"M %s +b %s",b->set_time,c->second->name,b->data);
-                       serv->SendPacket(data,udp_host);
-               }
-       }
-       // send end of sync marker: E <timestamp>
-       snprintf(data,MAXBUF,"F %d",time(NULL));
-       serv->SendPacket(data,udp_host);
-       // ircd sends its serverlist after the end of sync here
-}
-
-
-void handle_V(char token,char* params,serverrec* source,serverrec* reply, char* udp_host)
-{
-       char* src = strtok(params," ");
-       char* dest = strtok(NULL," :");
-       char* text = strtok(NULL,"\r\n");
-       text++;
-       
-       userrec* user = Find(src);
-       if (user)
-       {
-               userrec* dst = Find(dest);
-               
-               if (dst)
-               {
-                       WriteTo(user, dst, "NOTICE %s :%s", dst->nick, text);
-               }
-               else
-               {
-                       chanrec* d = FindChan(dest);
-                       if (d)
-                       {
-                               ChanExceptSender(d, user, "NOTICE %s :%s", d->name, text);
-                       }
-               }
-       }
-       
-}
-
-
-void handle_P(char token,char* params,serverrec* source,serverrec* reply, char* udp_host)
-{
-       char* src = strtok(params," ");
-       char* dest = strtok(NULL," :");
-       char* text = strtok(NULL,"\r\n");
-       text++;
-       
-       userrec* user = Find(src);
-       if (user)
-       {
-               userrec* dst = Find(dest);
-               
-               if (dst)
-               {
-                       WriteTo(user, dst, "PRIVMSG %s :%s", dst->nick, text);
-               }
-               else
-               {
-                       chanrec* d = FindChan(dest);
-                       if (d)
-                       {
-                               ChanExceptSender(d, user, "PRIVMSG %s :%s", d->name, text);
-                       }
-               }
-       }
-       
-}
-
-void handle_i(char token,char* params,serverrec* source,serverrec* reply, char* udp_host)
-{
-       char* nick = strtok(params," ");
-       char* from = strtok(NULL," ");
-       char* channel = strtok(NULL," ");
-       userrec* u = Find(nick);
-       userrec* user = Find(from);
-       chanrec* c = FindChan(channel);
-       if ((c) && (u) && (user))
-       {
-               u->InviteTo(c->name);
-               WriteFrom(u->fd,user,"INVITE %s :%s",u->nick,c->name);
-       }
-}
-
-void handle_t(char token,char* params,serverrec* source,serverrec* reply, char* udp_host)
-{
-       char* setby = strtok(params," ");
-       char* channel = strtok(NULL," :");
-       char* topic = strtok(NULL,"\r\n");
-       topic++;
-       userrec* u = Find(setby);
-       chanrec* c = FindChan(channel);
-       if ((c) && (u))
-       {
-               WriteChannelLocal(c,u,"TOPIC %s :%s",c->name,topic);
-               strncpy(c->topic,topic,MAXTOPIC);
-               strncpy(c->setby,u->nick,NICKMAX);
-       }       
-}
-       
-
-void handle_T(char token,char* params,serverrec* source,serverrec* reply, char* udp_host)
-{
-       char* tm = strtok(params," ");
-       char* setby = strtok(NULL," ");
-       char* channel = strtok(NULL," :");
-       char* topic = strtok(NULL,"\r\n");
-       topic++;
-       time_t TS = atoi(tm);
-       chanrec* c = FindChan(channel);
-       if (c)
-       {
-               // in the case of topics and TS, the *NEWER* 
-               if (TS <= c->topicset)
-               {
-                       WriteChannelLocal(c,NULL,"TOPIC %s :%s",c->name,topic);
-                       strncpy(c->topic,topic,MAXTOPIC);
-                       strncpy(c->setby,setby,NICKMAX);
-               }
-       }       
-}
-       
-void handle_M(char token,char* params,serverrec* source,serverrec* reply, char* udp_host)
-{
-       char* pars[128];
-       char original[MAXBUF],target[MAXBUF];
-       strncpy(original,params,MAXBUF);
-       int index = 0;
-       char* parameter = strtok(params," ");
-       strncpy(target,parameter,MAXBUF);
-       while (parameter)
-       {
-               pars[index++] = parameter;
-               parameter = strtok(NULL," ");
-       }
-       merge_mode(pars,index);
-       if (FindChan(target))
-       {
-               WriteChannelLocal(FindChan(target), NULL, "MODE %s",original);
-       }
-       if (Find(target))
-       {
-               WriteTo(NULL,Find(target),"MODE %s",original);
-       }
-}
-
-// m is modes set by users only (not servers) valid targets are channels or users.
-
-void handle_m(char token,char* params,serverrec* source,serverrec* reply, char* udp_host)
-{
-       // m blah #chatspike +b *!test@*4
-       char* pars[128];
-       char original[MAXBUF];
-       strncpy(original,params,MAXBUF);
-       
-       if (!strchr(params,' '))
-       {
-               WriteOpers("WARNING! 'm' token in data stream without any parameters! Something fishy is going on!");
-               return;
-       }
-       
-       int index = 0;
-       
-       char* src = strtok(params," ");
-       userrec* user = Find(src);
-       
-       if (user)
-       {
-               log(DEBUG,"Found user: %s",user->nick);
-               char* parameter = strtok(NULL," ");
-               while (parameter)
-               {
-                       pars[index++] = parameter;
-                       parameter = strtok(NULL," ");
-               }
-               
-               log(DEBUG,"Calling merge_mode2");
-               merge_mode2(pars,index,user);
-       }
-}
-
-
-void handle_L(char token,char* params,serverrec* source,serverrec* reply, char* udp_host)
-{
-       char* nick = strtok(params," ");
-       char* channel = strtok(NULL," :");
-       char* reason = strtok(NULL,"\r\n");
-       userrec* user = Find(nick);
-       reason++;
-       if (user)
-       {
-               if (strcmp(reason,""))
-               {
-                       del_channel(user,channel,reason,true);
-               }
-               else
-               {
-                       del_channel(user,channel,NULL,true);
-               }
-       }
-}
-
-void handle_K(char token,char* params,serverrec* source,serverrec* reply, char* udp_host)
-{
-       char* src = strtok(params," ");
-       char* nick = strtok(NULL," :");
-       char* reason = strtok(NULL,"\r\n");
-       char kreason[MAXBUF];
-       reason++;
-
-       userrec* u = Find(nick);
-       userrec* user = Find(src);
-       
-       if ((user) && (u))
-       {
-               WriteTo(user, u, "KILL %s :%s!%s!%s!%s (%s)", u->nick, source->name, ServerName, user->dhost,user->nick,reason);
-               WriteOpers("*** Remote kill from %s by %s: %s!%s@%s (%s)",source->name,user->nick,u->nick,u->ident,u->host,reason);
-               snprintf(kreason,MAXBUF,"[%s] Killed (%s (%s))",source->name,user->nick,reason);
-               kill_link(u,kreason);
-       }
-}
-
-void handle_Q(char token,char* params,serverrec* source,serverrec* reply, char* udp_host)
-{
-       char* nick = strtok(params," :");
-       char* reason = strtok(NULL,"\r\n");
-       reason++;
-
-       userrec* user = Find(nick);
-       
-       if (user)
-       {
-               if (strlen(reason)>MAXQUIT)
-               {
-                       reason[MAXQUIT-1] = '\0';
-               }
-
-
-               WriteCommonExcept(user,"QUIT :%s",reason);
-
-               user_hash::iterator iter = clientlist.find(user->nick);
-       
-               if (iter != clientlist.end())
-               {
-                       log(DEBUG,"deleting user hash value %d",iter->second);
-                       if ((iter->second) && (user->registered == 7)) {
-                               delete iter->second;
-                       }
-                       clientlist.erase(iter);
-               }
-
-               purge_empty_chans();
-       }
-}
-
-void handle_n(char token,char* params,serverrec* source,serverrec* reply, char* udp_host)
-{
-       char* oldnick = strtok(params," ");
-       char* newnick = strtok(NULL," ");
-       
-       userrec* user = Find(oldnick);
-       
-       if (user)
-       {
-               WriteCommon(user,"NICK %s",newnick);
-               user = ReHashNick(user->nick, newnick);
-               if (!user) return;
-               if (!user->nick) return;
-               strncpy(user->nick, newnick,NICKMAX);
-               log(DEBUG,"new nick set: %s",user->nick);
-       }
-}
-
-// k <SOURCE> <DEST> <CHANNEL> :<REASON>
-void handle_k(char token,char* params,serverrec* source,serverrec* reply, char* udp_host)
-{
-       char* src = strtok(params," ");
-       char* dest = strtok(NULL," ");
-       char* channel = strtok(NULL," :");
-       char* reason = strtok(NULL,"\r\n");
-       reason++;
-       userrec* s = Find(src);
-       userrec* d = Find(dest);
-       chanrec* c = FindChan(channel);
-       if ((s) && (d) && (c))
-       {
-               kick_channel(s,d,c,reason);
-       }
-}
-
-void handle_AT(char token,char* params,serverrec* source,serverrec* reply, char* udp_host)
-{
-       char* who = strtok(params," :");
-       char* text = strtok(NULL,"\r\n");
-       text++;
-       userrec* s = Find(who);
-       if (s)
-       {
-               WriteWallOps(s,true,text);
-       }
-}
-
-
-void handle_N(char token,char* params,serverrec* source,serverrec* reply, char* udp_host)
-{
-       char* tm = strtok(params," ");
-       char* nick = strtok(NULL," ");
-       char* host = strtok(NULL," ");
-       char* dhost = strtok(NULL," ");
-       char* ident = strtok(NULL," ");
-       char* modes = strtok(NULL," ");
-       char* server = strtok(NULL," :");
-       char* gecos = strtok(NULL,"\r\n");
-       gecos++;
-       modes++;
-       time_t TS = atoi(tm);
-       user_hash::iterator iter = clientlist.find(nick);
-       if (iter != clientlist.end())
-       {
-               // nick collision
-               WriteOpers("Nickname collision: %s@%s != %s@%s",nick,server,iter->second->nick,iter->second->server);
-               char str[MAXBUF];
-               snprintf(str,MAXBUF,"Killed (Nick Collision (%s@%s < %s@%s))",nick,server,iter->second->nick,iter->second->server);
-               WriteServ(iter->second->fd, "KILL %s :%s",iter->second->nick,str);
-               kill_link(iter->second,str);
-       }
-       clientlist[nick] = new userrec();
-       // remote users have an fd of -1. This is so that our Write abstraction
-       // routines know to route any messages to this record away to whatever server
-       // theyre on.
-       clientlist[nick]->fd = -1;
-       strncpy(clientlist[nick]->nick, nick,NICKMAX);
-       strncpy(clientlist[nick]->host, host,160);
-       strncpy(clientlist[nick]->dhost, dhost,160);
-       strncpy(clientlist[nick]->server, server,256);
-       strncpy(clientlist[nick]->ident, ident,10); // +1 char to compensate for tilde
-       strncpy(clientlist[nick]->fullname, gecos,128);
-       clientlist[nick]->signon = TS;
-       clientlist[nick]->nping = 0; // this is ignored for a remote user anyway.
-       clientlist[nick]->lastping = 1;
-       clientlist[nick]->port = 0; // so is this...
-       clientlist[nick]->registered = 7; // this however we need to set for them to receive messages and appear online
-       clientlist[nick]->idle_lastmsg = time(NULL); // this is unrealiable and wont actually be used locally
-       for (int i = 0; i < MAXCHANS; i++)
-       {
-               clientlist[nick]->chans[i].channel = NULL;
-               clientlist[nick]->chans[i].uc_modes = 0;
-       }
-}
-
-void handle_F(char token,char* params,serverrec* source,serverrec* reply, char* udp_host)
-{
-       long tdiff = time(NULL) - atoi(params);
-       if (tdiff)
-               WriteOpers("TS split for %s -> %s: %d",source->name,reply->name,tdiff);
-}
-
-void handle_a(char token,char* params,serverrec* source,serverrec* reply, char* udp_host)
-{
-       char* nick = strtok(params," :");
-       char* gecos = strtok(NULL,"\r\n");
-       
-       userrec* user = Find(nick);
-
-       if (user)
-               strncpy(user->fullname,gecos,MAXBUF);
-}
-
-void handle_b(char token,char* params,serverrec* source,serverrec* reply, char* udp_host)
-{
-       char* nick = strtok(params," ");
-       char* host = strtok(NULL," ");
-       
-       userrec* user = Find(nick);
-
-       if (user)
-               strncpy(user->dhost,host,160);
-}
-
-void handle_plus(char token,char* params,serverrec* source,serverrec* reply, char* udp_host)
+void DoSync(serverrec* serv, char* tcp_host)
 {
-       // %s %s %d %d
-       // + test3.chatspike.net 7010 -2016508415
-       char* servername = strtok(params," ");
-       char* ipaddr = strtok(NULL," ");
-       char* ipport = strtok(NULL," ");
-       char* cookie = strtok(NULL," ");
-       log(DEBUG,"*** Connecting back to %s:%d",ipaddr,atoi(ipport));
-
-
-       bool conn_already = false;
-       for (int i = 0; i < 32; i++)
+       char data[MAXBUF];
+       log(DEBUG,"Sending sync");
+       // send start of sync marker: Y <timestamp>
+       // at this point the ircd receiving it starts broadcasting this netburst to all ircds
+       // except the ones its receiving it from.
+       snprintf(data,MAXBUF,"Y %d",TIME);
+       serv->SendPacket(data,tcp_host);
+       // send users and channels
+       for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
        {
-               if (me[i] != NULL)
+               snprintf(data,MAXBUF,"N %d %s %s %s %s +%s %s %s :%s",u->second->age,u->second->nick,u->second->host,u->second->dhost,u->second->ident,u->second->modes,u->second->ip,u->second->server,u->second->fullname);
+               serv->SendPacket(data,tcp_host);
+               if (strchr(u->second->modes,'o'))
                {
-                       for (int j = 0; j < me[i]->connectors.size(); j++)
+                       snprintf(data,MAXBUF,"| %s %s",u->second->nick,u->second->oper);
+                       serv->SendPacket(data,tcp_host);
+               }
+               for (int i = 0; i <= MODCOUNT; i++)
+               {
+                       string_list l = modules[i]->OnUserSync(u->second);
+                       for (int j = 0; j < l.size(); j++)
                        {
-                               if (!strcasecmp(me[i]->connectors[j].GetServerName().c_str(),servername))
-                               {
-                                       if (me[i]->connectors[j].GetServerPort() == atoi(ipport))
-                                       {
-                                               log(DEBUG,"Already got a connection to %s:%d, ignoring +",ipaddr,atoi(ipport));
-                                               conn_already = true;
-                                       }
-                               }
-                       }
+                               strlcpy(data,l[j].c_str(),MAXBUF);
+                               serv->SendPacket(data,tcp_host);
+                       }
+               }
+               if (strcmp(chlist(u->second),""))
+               {
+                       snprintf(data,MAXBUF,"J %s %s",u->second->nick,chlist(u->second));
+                       serv->SendPacket(data,tcp_host);
                }
        }
-       if (!conn_already)
-               me[defaultRoute]->MeshCookie(ipaddr,atoi(ipport),atoi(cookie),servername);
-}
-
-void handle_R(char token,char* params,serverrec* source,serverrec* reply, char* udp_host)
-{
-       char* server = strtok(params," ");
-       char* data = strtok(NULL,"\r\n");
-       log(DEBUG,"Forwarded packet '%s' to '%s'",data,server);
-       NetSendToOne(server,data);
-}
-
-void handle_J(char token,char* params,serverrec* source,serverrec* reply, char* udp_host)
-{
-       // IMPORTANT NOTE
-       // The J token currently has no timestamp - this needs looking at
-       // because it will allow splitriding.
-       char* nick = strtok(params," ");
-       char* channel = strtok(NULL," ");
-       userrec* user = Find(nick);
-       while (channel)
-       {
-               if ((user != NULL) && (strcmp(channel,"")))
+       // send channel modes, topics etc...
+       for (chan_hash::iterator c = chanlist.begin(); c != chanlist.end(); c++)
+       {
+               snprintf(data,MAXBUF,"M %s +%s",c->second->name,chanmodes(c->second));
+               serv->SendPacket(data,tcp_host);
+               for (int i = 0; i <= MODCOUNT; i++)
                {
-                       char privilage = '\0';
-                       if (channel[0] != '#')
+                       string_list l = modules[i]->OnChannelSync(c->second);
+                       for (int j = 0; j < l.size(); j++)
                        {
-                               privilage = channel[0];
-                               channel++;
-                       }
-                       add_channel(user,channel,"",true);
+                               strlcpy(data,l[j].c_str(),MAXBUF);
+                               serv->SendPacket(data,tcp_host);
+                       }
+               }
+               if (strcmp(c->second->topic,""))
+               {
+                       snprintf(data,MAXBUF,"T %d %s %s :%s",c->second->topicset,c->second->setby,c->second->name,c->second->topic);
+                       serv->SendPacket(data,tcp_host);
+               }
+               // send current banlist
+               
+               for (BanList::iterator b = c->second->bans.begin(); b != c->second->bans.end(); b++)
+               {
+                       snprintf(data,MAXBUF,"M %s +b %s",b->set_time,c->second->name,b->data);
+                       serv->SendPacket(data,tcp_host);
+               }
+       }
+       // sync global zlines, glines, etc
+       sync_xlines(serv,tcp_host);
 
-                       // now work out the privilages they should have on each channel
-                       // and send the appropriate servermodes.
-                       for (int i = 0; i != MAXCHANS; i++)
+       for (int j = 0; j < 32; j++)
+       {
+               if (me[j] != NULL)
+               {
+                       for (int k = 0; k < me[j]->connectors.size(); k++)
                        {
-                               if (user->chans[i].channel)
+                               if (is_uline(me[j]->connectors[k].GetServerName().c_str()))
                                {
-                                       if (!strcasecmp(user->chans[i].channel->name,channel))
-                                       {
-                                               if (privilage == '@')
-                                               {
-                                                       user->chans[i].uc_modes = user->chans[i].uc_modes | UCMODE_OP;
-                                                       WriteChannelLocal(user->chans[i].channel, NULL, "MODE %s +o %s",channel,user->nick);
-                                               }
-                                               if (privilage == '%')
-                                               {
-                                                       user->chans[i].uc_modes = user->chans[i].uc_modes | UCMODE_HOP;
-                                                       WriteChannelLocal(user->chans[i].channel, NULL, "MODE %s +h %s",channel,user->nick);
-                                               }
-                                               if (privilage == '+')
-                                               {
-                                                       user->chans[i].uc_modes = user->chans[i].uc_modes | UCMODE_VOICE;
-                                                       WriteChannelLocal(user->chans[i].channel, NULL, "MODE %s +v %s",channel,user->nick);
-                                               }
-                                       }
+                                       snprintf(data,MAXBUF,"H %s",me[j]->connectors[k].GetServerName().c_str());
+                                       serv->SendPacket(data,tcp_host);
+                                       NetSendMyRoutingTable();
                                }
                        }
-
                }
-               channel = strtok(NULL," ");
        }
+
+       snprintf(data,MAXBUF,"F %d",TIME);
+       serv->SendPacket(data,tcp_host);
+       log(DEBUG,"Sent sync");
+       // ircd sends its serverlist after the end of sync here
 }
 
+
 void NetSendMyRoutingTable()
 {
        // send out a line saying what is reachable to us.
@@ -4507,7 +3158,7 @@ void NetSendMyRoutingTable()
        // $ A B D
        // if it has no links, dont even send out the line at all.
        char buffer[MAXBUF];
-       sprintf(buffer,"$ %s",ServerName);
+       snprintf(buffer,MAXBUF,"$ %s",ServerName);
        bool sendit = false;
        for (int i = 0; i < 32; i++)
        {
@@ -4515,10 +3166,10 @@ void NetSendMyRoutingTable()
                {
                        for (int j = 0; j < me[i]->connectors.size(); j++)
                        {
-                               if (me[i]->connectors[j].GetState() != STATE_DISCONNECTED)
+                               if ((me[i]->connectors[j].GetState() != STATE_DISCONNECTED) || (is_uline(me[i]->connectors[j].GetServerName().c_str())))
                                {
-                                       strncat(buffer," ",MAXBUF);
-                                       strncat(buffer,me[i]->connectors[j].GetServerName().c_str(),MAXBUF);
+                                       strlcat(buffer," ",MAXBUF);
+                                       strlcat(buffer,me[i]->connectors[j].GetServerName().c_str(),MAXBUF);
                                        sendit = true;
                                }
                        }
@@ -4528,36 +3179,6 @@ void NetSendMyRoutingTable()
                NetSendToAll(buffer);
 }
 
-void handle_dollar(char token,char* params,serverrec* source,serverrec* reply, char* udp_host)
-{
-       log(DEBUG,"Storing routing table...");
-       char* sourceserver = strtok(params," ");
-       char* server = strtok(NULL," ");
-       for (int i = 0; i < 32; i++)
-       {
-               if (me[i] != NULL)
-               {
-                       for (int j = 0; j < me[i]->connectors.size(); j++)
-                       {
-                               if (!strcasecmp(me[i]->connectors[j].GetServerName().c_str(),sourceserver))
-                               {
-                                       me[i]->connectors[j].routes.clear();
-                                       log(DEBUG,"Found entry for source server.");
-                                       while (server)
-                                       {
-                                               // store each route
-                                               me[i]->connectors[j].routes.push_back(server);
-                                               log(DEBUG,"*** Stored route: %s -> %s -> %s",ServerName,sourceserver,server);
-                                               server = strtok(NULL," ");
-                                       }
-                                       return;
-                               }
-                       }
-               }
-       }
-       log(DEBUG,"Warning! routing table received from nonexistent server!");
-}
-
 
 void DoSplit(const char* params)
 {
@@ -4633,487 +3254,120 @@ void RemoveServer(const char* name)
        }
 }
 
-void handle_amp(char token,char* params,serverrec* source,serverrec* reply, char* udp_host)
-{
-       log(DEBUG,"Netsplit! %s split from mesh, removing!",params);
-       bool go_again = true;
-       while (go_again)
-       {
-               go_again = false;
-               for (int i = 0; i < 32; i++)
-               {
-                       if (me[i] != NULL)
-                       {
-                               for (vector<ircd_connector>::iterator j = me[i]->connectors.begin(); j != me[i]->connectors.end(); j++)
-                               {
-                                       if (!strcasecmp(j->GetServerName().c_str(),params))
-                                       {
-                                               j->routes.clear();
-                                               j->CloseConnection();
-                                               me[i]->connectors.erase(j);
-                                               go_again = true;
-                                               break;
-                                       }
-                               }
-                       }
-               }
-       }
-       log(DEBUG,"Removed server. Will remove clients...");
-       // iterate through the userlist and remove all users on this server.
-       // because we're dealing with a mesh, we dont have to deal with anything
-       // "down-route" from this server (nice huh)
-       go_again = true;
-       char reason[MAXBUF];
-       snprintf(reason,MAXBUF,"%s %s",ServerName,params);
-       while (go_again)
-       {
-               go_again = false;
-               for (user_hash::const_iterator u = clientlist.begin(); u != clientlist.end(); u++)
-               {
-                       if (!strcasecmp(u->second->server,params))
-                       {
-                               kill_link(u->second,reason);
-                               go_again = true;
-                               break;
-                       }
-               }
-       }
-}
-
-long authcookie;
 
+int reap_counter = 0;
+char MODERR[MAXBUF];
 
-void process_restricted_commands(char token,char* params,serverrec* source,serverrec* reply, char* udp_host,char* ipaddr,int port)
+char* ModuleError()
 {
-       char buffer[MAXBUF];
-
-       switch(token)
-       {
-               // Y <TS>
-               // start netburst
-               case 'Y':
-                       nb_start = time(NULL);
-                       WriteOpers("Server %s is starting netburst.",udp_host);
-                       // now broadcast this new servers address out to all servers that are linked to us,
-                       // except the newcomer. They'll all attempt to connect back to it.
-                       authcookie = rand()*rand();
-                       snprintf(buffer,MAXBUF,"~ %d",authcookie);
-                       NetSendToAll(buffer);
-               break;
-               // ~
-               // Store authcookie
-               // once stored, this authcookie permits other servers to log in
-               // without user or password, using it.
-               case '~':
-                       auth_cookies.push_back(atoi(params));
-                       log(DEBUG,"*** Stored auth cookie, will permit servers with auth-cookie %d",atoi(params));
-               break;
-               // connect back to a server using an authcookie
-               case '+':
-                       handle_plus(token,params,source,reply,udp_host);
-               break;
-               // routing table
-               case '$':
-                       handle_dollar(token,params,source,reply,udp_host);
-               break;
-               // node unreachable - we cant route to a server, sooooo we slit it off.
-               // servers can generate these for themselves for an squit.
-               case '&':
-                       handle_amp(token,params,source,reply,udp_host);
-               break;
-               // R <server> <data>
-               // redirect token, send all of <data> along to the given 
-               // server as this server has been found to still have a route to it
-               case 'R':
-                       handle_R(token,params,source,reply,udp_host);
-               break;
-               // ?
-               // ping
-               case '?':
-                       reply->SendPacket("!",udp_host);
-               break;
-               // ?
-               // pong
-               case '!':
-               break;
-               // *
-               // no operation
-               case '*':
-               break;
-               // N <TS> <NICK> <HOST> <DHOST> <IDENT> <MODES> <SERVER> :<GECOS>
-               // introduce remote client
-               case 'N':
-                       handle_N(token,params,source,reply,udp_host);
-               break;
-               // a <NICK> :<GECOS>
-               // change GECOS (SETNAME)
-               case 'a':
-                       handle_a(token,params,source,reply,udp_host);
-               break;
-               // b <NICK> :<HOST>
-               // change displayed host (SETHOST)
-               case 'b':
-                       handle_b(token,params,source,reply,udp_host);
-               break;
-               // t <NICK> <CHANNEL> :<TOPIC>
-               // change a channel topic
-               case 't':
-                       handle_t(token,params,source,reply,udp_host);
-               break;
-               // i <NICK> <CHANNEL>
-               // invite a user to a channel
-               case 'i':
-                       handle_i(token,params,source,reply,udp_host);
-               break;
-               // k <SOURCE> <DEST> <CHANNEL> :<REASON>
-               // kick a user from a channel
-               case 'k':
-                       handle_k(token,params,source,reply,udp_host);
-               break;
-               // n <NICK> <NEWNICK>
-               // change nickname of client -- a server should only be able to
-               // change the nicknames of clients that reside on it unless
-               // they are ulined.
-               case 'n':
-                       handle_n(token,params,source,reply,udp_host);
-               break;
-               // J <NICK> <CHANLIST>
-               // Join user to channel list, merge channel permissions
-               case 'J':
-                       handle_J(token,params,source,reply,udp_host);
-               break;
-               // T <TS> <CHANNEL> <TOPICSETTER> :<TOPIC>
-               // change channel topic (netburst only)
-               case 'T':
-                       handle_T(token,params,source,reply,udp_host);
-               break;
-               // M <TARGET> <MODES> [MODE-PARAMETERS]
-               // Server setting modes on an object
-               case 'M':
-                       handle_M(token,params,source,reply,udp_host);
-               break;
-               // m <SOURCE> <TARGET> <MODES> [MODE-PARAMETERS]
-               // User setting modes on an object
-               case 'm':
-                       handle_m(token,params,source,reply,udp_host);
-               break;
-               // P <SOURCE> <TARGET> :<TEXT>
-               // Send a private/channel message
-               case 'P':
-                       handle_P(token,params,source,reply,udp_host);
-               break;
-               // V <SOURCE> <TARGET> :<TEXT>
-               // Send a private/channel notice
-               case 'V':
-                       handle_V(token,params,source,reply,udp_host);
-               break;
-               // L <SOURCE> <CHANNEL> :<REASON>
-               // User parting a channel
-               case 'L':
-                       handle_L(token,params,source,reply,udp_host);
-               break;
-               // Q <SOURCE> :<REASON>
-               // user quitting
-               case 'Q':
-                       handle_Q(token,params,source,reply,udp_host);
-               break;
-               // K <SOURCE> <DEST> :<REASON>
-               // remote kill
-               case 'K':
-                       handle_K(token,params,source,reply,udp_host);
-               break;
-               // @ <SOURCE> :<TEXT>
-               // wallops
-               case '@':
-                       handle_AT(token,params,source,reply,udp_host);
-               break;
-               // F <TS>
-               // end netburst
-               case 'F':
-                       WriteOpers("Server %s has completed netburst. (%d secs)",udp_host,time(NULL)-nb_start);
-                       handle_F(token,params,source,reply,udp_host);
-                       nb_start = 0;
-                       // tell all the other servers to use this authcookie to connect back again
-                       // got '+ test3.chatspike.net 7010 -2016508415' from test.chatspike.net
-                       snprintf(buffer,MAXBUF,"+ %s %s %d %d",udp_host,ipaddr,port,authcookie);
-                       NetSendToAllExcept(udp_host,buffer);
-               break;
-               // X <reserved>
-               // Send netburst now
-               case 'X':
-                       WriteOpers("Sending my netburst to %s",udp_host);
-                       DoSync(source,udp_host);
-                       WriteOpers("Send of netburst to %s completed",udp_host);
-                       NetSendMyRoutingTable();
-               break;
-               // anything else
-               default:
-                       WriteOpers("WARNING! Unknown datagram type '%c'",token);
-               break;
-       }
+       return MODERR;
 }
 
-
-void handle_link_packet(char* udp_msg, char* udp_host, serverrec *serv)
+bool UnloadModule(const char* filename)
 {
-       char response[10240];
-       char token = udp_msg[0];
-       char* params = udp_msg + 2;
-       char finalparam[1024];
-       strcpy(finalparam," :xxxx");
-       if (strstr(udp_msg," :")) {
-               strncpy(finalparam,strstr(udp_msg," :"),1024);
-       }
-       if (token == '-') {
-               char* cookie = strtok(params," ");
-               char* servername = strtok(NULL," ");
-               char* serverdesc = finalparam+2;
-
-               WriteOpers("AuthCookie CONNECT from %s (%s)",servername,udp_host);
-
-               for (int u = 0; u < auth_cookies.size(); u++)
-               {
-                       if (auth_cookies[u] == atoi(cookie))
-                       {
-                               WriteOpers("Allowed cookie from %s, is now part of the mesh",servername);
-
-
-                               for (int j = 0; j < 32; j++)
-                               {
-                                       if (me[j] != NULL)
-                                       {
-                                               for (int k = 0; k < me[j]->connectors.size(); k++)
-                                               {
-                                                       if (!strcasecmp(me[j]->connectors[k].GetServerName().c_str(),udp_host))
-                                                       {
-                                                               me[j]->connectors[k].SetServerName(servername);
-                                                               me[j]->connectors[k].SetDescription(serverdesc);
-                                                               me[j]->connectors[k].SetState(STATE_CONNECTED);
-                                                               NetSendMyRoutingTable();
-                                                               return;
-                                                       }
-                                               }
-                                       }
-                                       WriteOpers("\2WARNING!\2 %s sent us an authentication packet but we are not authenticating with this server right now! Possible intrusion attempt!",udp_host);
-                                       return;
-                               }
-
-
-                               return;
-                       }
-               }
-               // bad cookie, bad bad! go sit in the corner!
-               WriteOpers("Bad cookie from %s!",servername);
-               return;
-       }
-       else
-       if (token == 'S') {
-               // S test.chatspike.net password portn :ChatSpike InspIRCd test server
-               char* servername = strtok(params," ");
-               char* password = strtok(NULL," ");
-               char* myport = strtok(NULL," ");
-               char* revision = strtok(NULL," ");
-               char* serverdesc = finalparam+2;
-
-               WriteOpers("CONNECT from %s (%s) (their port: %d)",servername,udp_host,atoi(myport));
-               
-               ircd_connector* cn = serv->FindHost(servername);
-               
-               if (cn)
-               {
-                       WriteOpers("CONNECT aborted: Server %s already exists from %s",servername,ServerName);
-                       char buffer[MAXBUF];
-                       sprintf(buffer,"E :Server %s already exists!",servername);
-                       serv->SendPacket(buffer,udp_host);
-                       RemoveServer(udp_host);
-                       return;
-               }
-
-               if (atoi(revision) != GetRevision())
-               {
-                       WriteOpers("CONNECT aborted: Could not link to %s, is an incompatible version %s, our version is %d",servername,revision,GetRevision());
-                       char buffer[MAXBUF];
-                       sprintf(buffer,"E :Version number mismatch");
-                       serv->SendPacket(buffer,udp_host);
-                       RemoveServer(udp_host);
-                       RemoveServer(servername);
-                       return;
-               }
-
-               for (int j = 0; j < serv->connectors.size(); j++)
+       for (int j = 0; j != module_names.size(); j++)
+       {
+               if (module_names[j] == std::string(filename))
                {
-                       if (!strcasecmp(serv->connectors[j].GetServerName().c_str(),udp_host))
+                       // found the module
+                       log(DEBUG,"Deleting module...");
+                       delete factory[j]->factory;
+                       log(DEBUG,"Deleting module factory...");
+                       delete factory[j];
+                       log(DEBUG,"Erasing module entry...");
+                       factory[j] = NULL;
+                       // here we should locate ALL resources claimed by this module... and release them
+                       // for example commands
+                       log(DEBUG,"Erasing module vector...");
+                       for (std::vector<ircd_module*>::iterator t = factory.begin(); t != factory.end(); t++)
                        {
-                               serv->connectors[j].SetServerName(servername);
-                               serv->connectors[j].SetDescription(serverdesc);
-                               serv->connectors[j].SetServerPort(atoi(myport));
-                       }
-               }
-               
-               
-               char Link_ServerName[1024];
-               char Link_IPAddr[1024];
-               char Link_Port[1024];
-               char Link_Pass[1024];
-               char Link_SendPass[1024];
-               int LinkPort = 0;
-               
-               // search for a corresponding <link> block in the config files
-               for (int i = 0; i < ConfValueEnum("link",&config_f); i++)
-               {
-                       ConfValue("link","name",i,Link_ServerName,&config_f);
-                       ConfValue("link","ipaddr",i,Link_IPAddr,&config_f);
-                       ConfValue("link","port",i,Link_Port,&config_f);
-                       ConfValue("link","recvpass",i,Link_Pass,&config_f);
-                       ConfValue("link","sendpass",i,Link_SendPass,&config_f);
-                       log(DEBUG,"(%d) Comparing against name='%s', ipaddr='%s', port='%s', recvpass='%s'",i,Link_ServerName,Link_IPAddr,Link_Port,Link_Pass);
-                       LinkPort = atoi(Link_Port);
-                       if (!strcasecmp(Link_ServerName,servername))
-                       {
-                               // we have a matching link line -
-                               // send a 'diminutive' server message back...
-                               snprintf(response,10240,"s %s %s :%s",ServerName,Link_SendPass,ServerDesc);
-                               serv->SendPacket(response,servername);
-
-                               for (int t = 0; t < serv->connectors.size(); t++)
-                               {
-                                       if (!strcasecmp(serv->connectors[t].GetServerName().c_str(),servername))
-                                       {
-                                               serv->connectors[t].SetState(STATE_CONNECTED);
-                                       }
-                               }
-               
-                               return;
-                       }
-               }
-               char buffer[MAXBUF];
-               sprintf(buffer,"E :Access is denied (no matching link block)");
-               serv->SendPacket(buffer,udp_host);
-               WriteOpers("CONNECT from %s denied, no matching link block",servername);
-               RemoveServer(udp_host);
-               RemoveServer(servername);
-               return;
-       }
-       else
-       if (token == 's') {
-               // S test.chatspike.net password :ChatSpike InspIRCd test server
-               char* servername = strtok(params," ");
-               char* password = strtok(NULL," ");
-               char* serverdesc = finalparam+2;
-               
-               // TODO: we should do a check here to ensure that this server is one we recently initiated a
-               // link with, and didnt hear an 's' or 'E' back from yet (these are the only two valid responses
-               // to an 'S' command. If we didn't recently send an 'S' to this server, theyre trying to spoof
-               // a connect, so put out an oper alert!
-               
-               // for now, just accept all, we'll fix that later.
-               WriteOpers("%s accepted our link credentials ",servername);
-               
-               char Link_ServerName[1024];
-               char Link_IPAddr[1024];
-               char Link_Port[1024];
-               char Link_Pass[1024];
-               char Link_SendPass[1024];
-               int LinkPort = 0;
-               
-               // search for a corresponding <link> block in the config files
-               for (int i = 0; i < ConfValueEnum("link",&config_f); i++)
-               {
-                       ConfValue("link","name",i,Link_ServerName,&config_f);
-                       ConfValue("link","ipaddr",i,Link_IPAddr,&config_f);
-                       ConfValue("link","port",i,Link_Port,&config_f);
-                       ConfValue("link","recvpass",i,Link_Pass,&config_f);
-                       ConfValue("link","sendpass",i,Link_SendPass,&config_f);
-                       log(DEBUG,"(%d) Comparing against name='%s', ipaddr='%s', port='%s', recvpass='%s'",i,Link_ServerName,Link_IPAddr,Link_Port,Link_Pass);
-                       LinkPort = atoi(Link_Port);
-                       if (!strcasecmp(Link_ServerName,servername))
-                       {
-                               // matching link at this end too, we're all done!
-                               // at this point we must begin key exchange and insert this
-                               // server into our 'active' table.
-                               for (int j = 0; j < 32; j++)
+                               if (*t == NULL)
                                {
-                                       if (me[j] != NULL)
-                                       {
-                                               for (int k = 0; k < me[j]->connectors.size(); k++)
-                                               {
-                                                       if (!strcasecmp(me[j]->connectors[k].GetServerName().c_str(),udp_host))
-                                                       {
-                                                               char buffer[MAXBUF];
-                                                               me[j]->connectors[k].SetDescription(serverdesc);
-                                                               me[j]->connectors[k].SetState(STATE_CONNECTED);
-                                                               sprintf(buffer,"X 0");
-                                                               serv->SendPacket(buffer,udp_host);
-                                                               DoSync(me[j],udp_host);
-                                                               NetSendMyRoutingTable();
-                                                               return;
-                                                       }
-                                               }
-                                       }
-                                       WriteOpers("\2WARNING!\2 %s sent us an authentication packet but we are not authenticating with this server right noe! Possible intrusion attempt!",udp_host);
-                                       return;
+                                       factory.erase(t);
+                                       break;
                                }
                        }
-                       else {
-                               log(DEBUG,"Server names '%s' and '%s' don't match",Link_ServerName,servername);
-                       }
+                       log(DEBUG,"Erasing module name vector...");
+                       for (std::vector<std::string>::iterator v = module_names.begin(); v != module_names.end(); v++)
+                        {
+                                if (*v == std::string(filename))
+                                {
+                                        module_names.erase(v);
+                                        break;
+                                }
+                        }
+                        log(DEBUG,"Removing dependent commands...");
+                        removecommands(filename);
+                       log(DEFAULT,"Module %s unloaded",filename);
+                       MODCOUNT--;
+                       return true;
                }
-               char buffer[MAXBUF];
-               sprintf(buffer,"E :Access is denied (no matching link block)");
-               serv->SendPacket(buffer,udp_host);
-               WriteOpers("CONNECT from %s denied, no matching link block",servername);
-               RemoveServer(udp_host);
-               RemoveServer(servername);
-               return;
        }
-       else
-       if (token == 'E') {
-               char* error_message = finalparam+2;
-               WriteOpers("ERROR from %s: %s",udp_host,error_message);
-               return;
-       }
-       else {
-
-               serverrec* source_server = NULL;
+       log(DEFAULT,"Module %s is not loaded, cannot unload it!",filename);
+       snprintf(MODERR,MAXBUF,"Module not loaded");
+       return false;
+}
 
-               for (int j = 0; j < 32; j++)
-               {
-                       if (me[j] != NULL)
-                       {
-                               for (int x = 0; x < me[j]->connectors.size(); x++)
-                               {
-                                       log(DEBUG,"Servers are: '%s' '%s'",udp_host,me[j]->connectors[x].GetServerName().c_str());
-                                       if (!strcasecmp(me[j]->connectors[x].GetServerName().c_str(),udp_host))
-                                       {
-                                               if (me[j]->connectors[x].GetState() == STATE_CONNECTED)
-                                               {
-                                                       // found a valid ircd_connector.
-                                                       process_restricted_commands(token,params,me[j],serv,udp_host,me[j]->connectors[x].GetServerIP(),me[j]->connectors[x].GetServerPort());
-                                                       return;
-                                               }
-                                       }
-                               }
+bool LoadModule(const char* filename)
+{
+       char modfile[MAXBUF];
+       snprintf(modfile,MAXBUF,"%s/%s",MOD_PATH,filename,&config_f);
+       log(DEBUG,"Loading module: %s",modfile);
+        if (FileExists(modfile))
+        {
+               for (int j = 0; j < module_names.size(); j++)
+               {
+                       if (module_names[j] == std::string(filename))
+                       {
+                               log(DEFAULT,"Module %s is already loaded, cannot load a module twice!",modfile);
+                               snprintf(MODERR,MAXBUF,"Module already loaded");
+                               return false;
                        }
                }
-
-               log(DEBUG,"Unrecognised token or unauthenticated host in datagram from %s: %c",udp_host,token);
-       }
+                factory[MODCOUNT+1] = new ircd_module(modfile);
+                if (factory[MODCOUNT+1]->LastError())
+                {
+                        log(DEFAULT,"Unable to load %s: %s",modfile,factory[MODCOUNT+1]->LastError());
+                       snprintf(MODERR,MAXBUF,"Loader/Linker error: %s",factory[MODCOUNT+1]->LastError());
+                       MODCOUNT--;
+                       return false;
+                }
+                if (factory[MODCOUNT+1]->factory)
+                {
+                        modules[MODCOUNT+1] = factory[MODCOUNT+1]->factory->CreateModule();
+                        /* save the module and the module's classfactory, if
+                         * this isnt done, random crashes can occur :/ */
+                        module_names.push_back(filename);
+                }
+               else
+                {
+                        log(DEFAULT,"Unable to load %s",modfile);
+                       snprintf(MODERR,MAXBUF,"Factory function failed!");
+                       return false;
+                }
+        }
+        else
+        {
+                log(DEFAULT,"InspIRCd: startup: Module Not Found %s",modfile);
+               snprintf(MODERR,MAXBUF,"Module file could not be found");
+               return false;
+        }
+       MODCOUNT++;
+       return true;
 }
 
-int reap_counter = 0;
-
 int InspIRCd(void)
 {
-       struct sockaddr_in client, server;
+       struct sockaddr_in client,server;
        char addrs[MAXBUF][255];
-       int openSockfd[MAXSOCKS], incomingSockfd, result = TRUE;
+       int incomingSockfd, result = TRUE;
        socklen_t length;
-       int count = 0, scanDetectTrigger = TRUE, showBanner = FALSE;
+       int count = 0;
        int selectResult = 0, selectResult2 = 0;
        char *temp, configToken[MAXBUF], stuff[MAXBUF], Addr[MAXBUF], Type[MAXBUF];
        char resolvedHost[MAXBUF];
        fd_set selectFds;
-       struct timeval tv;
+       timeval tv;
 
        log_file = fopen("ircd.log","a+");
        if (!log_file)
@@ -5128,15 +3382,16 @@ int InspIRCd(void)
        {
                printf("WARNING!!! You are running an irc server as ROOT!!! DO NOT DO THIS!!!\n\n");
                Exit(ERROR);
-               log(DEBUG,"InspIRCd: startup: not starting with UID 0!");
+               log(DEFAULT,"InspIRCd: startup: not starting with UID 0!");
        }
        SetupCommandTable();
        log(DEBUG,"InspIRCd: startup: default command table set up");
        
-       ReadConfig();
+       ReadConfig(true,NULL);
        if (strcmp(DieValue,"")) 
        { 
                printf("WARNING: %s\n\n",DieValue);
+               log(DEFAULT,"Ut-Oh, somebody didn't read their config file: '%s'",DieValue);
                exit(0); 
        }  
        log(DEBUG,"InspIRCd: startup: read config");
@@ -5159,13 +3414,19 @@ int InspIRCd(void)
                                log(DEBUG,"InspIRCd: startup: binding '%s:%s' is default server route",Addr,configToken);
                        }
                        me[count3] = new serverrec(ServerName,100L,false);
-                       me[count3]->CreateListener(Addr,atoi(configToken));
-                       count3++;
+                       if (!me[count3]->CreateListener(Addr,atoi(configToken)))
+                       {
+                               log(DEFAULT,"Error! Failed to bind port %d",atoi(configToken));
+                       }
+                       else
+                       {
+                               count3++;
+                       }
                }
                else
                {
                        ports[count2] = atoi(configToken);
-                       strcpy(addrs[count2],Addr);
+                       strlcpy(addrs[count2],Addr,256);
                        count2++;
                }
                log(DEBUG,"InspIRCd: startup: read binding %s:%s [%s] from config",Addr,configToken, Type);
@@ -5180,49 +3441,18 @@ int InspIRCd(void)
        printf("\n");
        
        /* BugFix By Craig! :p */
-       count = 0;
+       MODCOUNT = -1;
        for (count2 = 0; count2 < ConfValueEnum("module",&config_f); count2++)
        {
-               char modfile[MAXBUF];
                ConfValue("module","name",count2,configToken,&config_f);
-               sprintf(modfile,"%s/%s",MOD_PATH,configToken,&config_f);
-               printf("Loading module... \033[1;37m%s\033[0;37m\n",modfile);
-               log(DEBUG,"InspIRCd: startup: Loading module: %s",modfile);
-               /* If The File Doesnt exist, Trying to load it
-                * Will Segfault the IRCd.. So, check to see if
-                * it Exists, Before Proceeding. */
-               if (FileExists(modfile))
-               {
-                       factory[count] = new ircd_module(modfile);
-                       if (factory[count]->LastError())
-                       {
-                               log(DEBUG,"Unable to load %s: %s",modfile,factory[count]->LastError());
-                               sprintf("Unable to load %s: %s\nExiting...\n",modfile,factory[count]->LastError());
-                               Exit(ERROR);
-                       }
-                       if (factory[count]->factory)
-                       {
-                               modules[count] = factory[count]->factory->CreateModule();
-                               /* save the module and the module's classfactory, if
-                                * this isnt done, random crashes can occur :/ */
-                               module_names.push_back(modfile);        
-                       }
-                       else
-                       {
-                               log(DEBUG,"Unable to load %s",modfile);
-                               sprintf("Unable to load %s\nExiting...\n",modfile);
-                               Exit(ERROR);
-                       }
-                       /* Increase the Count */
-                       count++;
-               }
-               else
+               printf("Loading module... \033[1;37m%s\033[0;37m\n",configToken);
+               if (!LoadModule(configToken))
                {
-                       log(DEBUG,"InspIRCd: startup: Module Not Found %s",modfile);
-                       printf("Module Not Found: \033[1;37m%s\033[0;37m, Skipping\n",modfile);
+                       log(DEBUG,"Exiting due to a module loader error.");
+                       printf("There was an error loading a module: %s\n",ModuleError());
+                       Exit(0);
                }
        }
-       MODCOUNT = count - 1;
        log(DEBUG,"Total loaded modules: %d",MODCOUNT+1);
        
        printf("\nInspIRCd is now running!\n");
@@ -5237,11 +3467,15 @@ int InspIRCd(void)
        {
                if (DaemonSeed() == ERROR)
                {
-                       log(DEBUG,"InspIRCd: startup: can't daemonise");
+                       log(DEFAULT,"InspIRCd: startup: can't daemonise");
                        printf("ERROR: could not go into daemon mode. Shutting down.\n");
                        Exit(ERROR);
                }
        }
+
+       char PID[MAXBUF];
+       ConfValue("pid","file",0,PID,&config_f);
+       WritePID(PID);
          
          
        /* setup select call */
@@ -5258,7 +3492,7 @@ int InspIRCd(void)
                }
                if (BindSocket(openSockfd[boundPortCount],client,server,ports[count],addrs[count]) == ERROR)
                {
-                       log(DEBUG,"InspIRCd: startup: failed to bind port %d",ports[count]);
+                       log(DEFAULT,"InspIRCd: startup: failed to bind port %d",ports[count]);
                }
                else    /* well we at least bound to one socket so we'll continue */
                {
@@ -5271,13 +3505,28 @@ int InspIRCd(void)
        /* if we didn't bind to anything then abort */
        if (boundPortCount == 0)
        {
-               log(DEBUG,"InspIRCd: startup: no ports bound, bailing!");
+               log(DEFAULT,"InspIRCd: startup: no ports bound, bailing!");
                return (ERROR);
        }
        
 
        length = sizeof (client);
-       char udp_msg[MAXBUF], udp_host[MAXBUF];
+       char udp_msg[MAXBUF], tcp_host[MAXBUF];
+
+        fd_set serverfds;
+        timeval tvs;
+        tvs.tv_usec = 7000L;
+        tvs.tv_sec = 0;
+       tv.tv_sec = 0;
+       tv.tv_usec = 7000L;
+        char data[10240];
+       timeval tval;
+       fd_set sfd;
+        tval.tv_usec = 7000L;
+        tval.tv_sec = 0;
+        int total_in_this_set = 0;
+       int v = 0;
+       bool expire_run = false;
          
        /* main loop, this never returns */
        for (;;)
@@ -5285,24 +3534,34 @@ int InspIRCd(void)
 #ifdef _POSIX_PRIORITY_SCHEDULING
                sched_yield();
 #endif
-
-               fd_set sfd;
-               timeval tval;
+                // poll dns queue
+                dns_poll();
                FD_ZERO(&sfd);
 
+               // we only read time() once per iteration rather than tons of times!
+               TIME = time(NULL);
+
                user_hash::iterator count2 = clientlist.begin();
 
                // *FIX* Instead of closing sockets in kill_link when they receive the ERROR :blah line, we should queue
                // them in a list, then reap the list every second or so.
+               if (((TIME % 5) == 0) && (!expire_run))
+               {
+                       expire_lines();
+                       expire_run = true;
+               }
+               if ((TIME % 5) == 1)
+                       expire_run = false;
                if (reap_counter>300)
                {
                        if (fd_reap.size() > 0)
                        {
                                for( int n = 0; n < fd_reap.size(); n++)
                                {
-                                       Blocking(fd_reap[n]);
+                                       //Blocking(fd_reap[n]);
                                        close(fd_reap[n]);
-                                       NonBlocking(fd_reap[n]);
+                                       shutdown (fd_reap[n],2);
+                                       //NonBlocking(fd_reap[n]);
                                }
                        }
                        fd_reap.clear();
@@ -5310,36 +3569,38 @@ int InspIRCd(void)
                }
                reap_counter++;
 
-               fd_set serverfds;
                FD_ZERO(&serverfds);
-               timeval tvs;
                
                for (int x = 0; x != UDPportCount; x++)
                {
-                       FD_SET(me[x]->fd, &serverfds);
+                       if (me[x])
+                               FD_SET(me[x]->fd, &serverfds);
                }
                
-               tvs.tv_usec = 0;                
-               tvs.tv_sec = 0;
+               // serverFds timevals went here
                
+               tvs.tv_usec = 7000L;
                int servresult = select(32767, &serverfds, NULL, NULL, &tvs);
                if (servresult > 0)
                {
                        for (int x = 0; x != UDPportCount; x++)
                        {
-                               if (FD_ISSET (me[x]->fd, &serverfds))
+                               if ((me[x]) && (FD_ISSET (me[x]->fd, &serverfds)))
                                {
                                        char remotehost[MAXBUF],resolved[MAXBUF];
                                        length = sizeof (client);
                                        incomingSockfd = accept (me[x]->fd, (sockaddr *) &client, &length);
-                                       strncpy(remotehost,(char *)inet_ntoa(client.sin_addr),MAXBUF);
-                                       if(CleanAndResolve(resolved, remotehost) != TRUE)
+                                       if (incomingSockfd != -1)
                                        {
-                                               strncpy(resolved,remotehost,MAXBUF);
+                                               strlcpy(remotehost,(char *)inet_ntoa(client.sin_addr),MAXBUF);
+                                               if(CleanAndResolve(resolved, remotehost) != TRUE)
+                                               {
+                                                       strlcpy(resolved,remotehost,MAXBUF);
+                                               }
+                                               // add to this connections ircd_connector vector
+                                               // *FIX* - we need the LOCAL port not the remote port in &client!
+                                               me[x]->AddIncoming(incomingSockfd,resolved,me[x]->port);
                                        }
-                                       // add to this connections ircd_connector vector
-                                       // *FIX* - we need the LOCAL port not the remote port in &client!
-                                       me[x]->AddIncoming(incomingSockfd,resolved,me[x]->port);
                                }
                        }
                }
@@ -5348,24 +3609,32 @@ int InspIRCd(void)
                {
                        std::deque<std::string> msgs;
                        msgs.clear();
-                       if (me[x]->RecvPacket(msgs, udp_host))
+                       if ((me[x]) && (me[x]->RecvPacket(msgs, tcp_host)))
                        {
                                for (int ctr = 0; ctr < msgs.size(); ctr++)
                                {
                                        char udp_msg[MAXBUF];
-                                       strncpy(udp_msg,msgs[ctr].c_str(),MAXBUF);
+                                       strlcpy(udp_msg,msgs[ctr].c_str(),MAXBUF);
                                        if (strlen(udp_msg)<1)
                                        {
-                                               log(DEBUG,"Invalid string from %s [route%d]",udp_host,x);
+                                               log(DEBUG,"Invalid string from %s [route%d]",tcp_host,x);
                                                break;
                                        }
                                        // during a netburst, send all data to all other linked servers
-                                       if ((nb_start>0) && (udp_msg[0] != 'Y') && (udp_msg[0] != 'X') && (udp_msg[0] != 'F'))
+                                       if ((((nb_start>0) && (udp_msg[0] != 'Y') && (udp_msg[0] != 'X') && (udp_msg[0] != 'F'))) || (is_uline(tcp_host)))
                                        {
-                                               NetSendToAllExcept(udp_host,udp_msg);
+                                               if (is_uline(tcp_host))
+                                               {
+                                                       if ((udp_msg[0] != 'Y') && (udp_msg[0] != 'X') && (udp_msg[0] != 'F'))
+                                                       {
+                                                               NetSendToAllExcept(tcp_host,udp_msg);
+                                                       }
+                                               }
+                                               else
+                                                       NetSendToAllExcept(tcp_host,udp_msg);
                                        }
                                        FOREACH_MOD OnPacketReceive(udp_msg);
-                                       handle_link_packet(udp_msg, udp_host, me[x]);
+                                       handle_link_packet(udp_msg, tcp_host, me[x]);
                                }
                                goto label;
                        }
@@ -5374,15 +3643,13 @@ int InspIRCd(void)
 
        while (count2 != clientlist.end())
        {
-               char data[10240];
-               tval.tv_usec = tval.tv_sec = 0;
                FD_ZERO(&sfd);
-               int total_in_this_set = 0;
+               total_in_this_set = 0;
 
                user_hash::iterator xcount = count2;
                user_hash::iterator endingiter = count2;
 
-               if (!count2->second) break;
+               if (count2 == clientlist.end()) break;
                
                if (count2->second)
                if (count2->second->fd != 0)
@@ -5403,13 +3670,24 @@ int InspIRCd(void)
 
                                                // registration timeout -- didnt send USER/NICK/HOST in the time specified in
                                                // their connection class.
-                                               if ((time(NULL) > count2->second->timeout) && (count2->second->registered != 7)) 
+                                               if ((TIME > count2->second->timeout) && (count2->second->registered != 7)) 
                                                {
                                                        log(DEBUG,"InspIRCd: registration timeout: %s",count2->second->nick);
                                                        kill_link(count2->second,"Registration timeout");
                                                        goto label;
                                                }
-                                               if (((time(NULL)) > count2->second->nping) && (isnick(count2->second->nick)) && (count2->second->registered == 7))
+                                               if ((TIME > count2->second->signon) && (count2->second->registered == 3))
+                                               {
+                                                               count2->second->dns_done = true;
+                                                               FullConnectUser(count2->second);
+                                                               goto label;
+                                               }
+                                               if ((count2->second->dns_done) && (count2->second->registered == 3)) // both NICK and USER... and DNS
+                                               {
+                                                       FullConnectUser(count2->second);
+                                                       goto label;
+                                               }
+                                               if ((TIME > count2->second->nping) && (isnick(count2->second->nick)) && (count2->second->registered == 7))
                                                {
                                                        if ((!count2->second->lastping) && (count2->second->registered == 7))
                                                        {
@@ -5420,7 +3698,7 @@ int InspIRCd(void)
                                                        Write(count2->second->fd,"PING :%s",ServerName);
                                                        log(DEBUG,"InspIRCd: pinging: %s",count2->second->nick);
                                                        count2->second->lastping = 0;
-                                                       count2->second->nping = time(NULL)+120;
+                                                       count2->second->nping = TIME+120;
                                                }
                                        }
                                        count2++;
@@ -5432,10 +3710,11 @@ int InspIRCd(void)
                        endingiter = count2;
                                count2 = xcount; // roll back to where we were
         
-                       int v = 0;
+                       v = 0;
 
-                       tval.tv_usec = 0;
-                       tval.tv_sec = 0;
+                       // tvals defined here
+
+                       tval.tv_usec = 7000L;
                        selectResult2 = select(65535, &sfd, NULL, NULL, &tval);
                        
                        // now loop through all of the items in this pool if any are waiting
@@ -5450,14 +3729,11 @@ int InspIRCd(void)
                                result = EAGAIN;
                                if ((count2a->second->fd != -1) && (FD_ISSET (count2a->second->fd, &sfd)))
                                {
-                                       log(DEBUG,"Reading fd %d",count2a->second->fd);
                                        memset(data, 0, 10240);
                                        result = read(count2a->second->fd, data, 10240);
                                        
                                        if (result)
                                        {
-                                               if (result > 0)
-                                                       log(DEBUG,"Read %d characters from socket",result);
                                                userrec* current = count2a->second;
                                                int currfd = current->fd;
                                                char* l = strtok(data,"\n");
@@ -5556,7 +3832,7 @@ int InspIRCd(void)
                FD_SET (openSockfd[count], &selectFds);
        }
 
-       tv.tv_usec = 1;
+       tv.tv_usec = 7000L;
        selectResult = select(MAXSOCKS, &selectFds, NULL, NULL, &tv);
 
        /* select is reporting a waiting socket. Poll them all to find out which */
@@ -5570,26 +3846,8 @@ int InspIRCd(void)
                                length = sizeof (client);
                                incomingSockfd = accept (openSockfd[count], (struct sockaddr *) &client, &length);
                              
-                               address_cache::iterator iter = IP.find(client.sin_addr);
-                               bool iscached = false;
-                               if (iter == IP.end())
-                               {
-                                       /* ip isn't in cache, add it */
-                                       strncpy (target, (char *) inet_ntoa (client.sin_addr), MAXBUF);
-                                       if(CleanAndResolve(resolved, target) != TRUE)
-                                       {
-                                               strncpy(resolved,target,MAXBUF);
-                                       }
-                                       /* hostname now in 'target' */
-                                       IP[client.sin_addr] = new string(resolved);
-                                       /* hostname in cache */
-                               }
-                               else
-                               {
-                                       /* found ip (cached) */
-                                       strncpy(resolved, iter->second->c_str(), MAXBUF);
-                                       iscached = true;
-                               }
+                               strlcpy (target, (char *) inet_ntoa (client.sin_addr), MAXBUF);
+                               strlcpy (resolved, target, MAXBUF);
                        
                                if (incomingSockfd < 0)
                                {
@@ -5598,7 +3856,7 @@ int InspIRCd(void)
                                }
                                else
                                {
-                                       AddClient(incomingSockfd, resolved, ports[count], iscached);
+                                       AddClient(incomingSockfd, resolved, ports[count], false, inet_ntoa (client.sin_addr));
                                        log(DEBUG,"InspIRCd: adding client on port %d fd=%d",ports[count],incomingSockfd);
                                }
                                goto label;