]> git.netwichtig.de Git - user/henk/code/inspircd.git/blobdiff - src/inspircd.cpp
kick_channel -> chanrec::KickUser(), server_kick_channel -> chanrec::ServerKickUser()
[user/henk/code/inspircd.git] / src / inspircd.cpp
index fd164000a3eff82ddc601d4c4d07bf7e65fec033..27029a6e4b18344e90fd73af88ee1703f05d802e 100644 (file)
@@ -1,27 +1,40 @@
-/*       +------------------------------------+
- *       | Inspire Internet Relay Chat Daemon |
- *       +------------------------------------+
+/* ---------------------------------------------------------------------
+ * 
+ *              +------------------------------------+
+ *              | Inspire Internet Relay Chat Daemon |
+ *              +------------------------------------+
  *
- *  InspIRCd is copyright (C) 2002-2006 ChatSpike-Dev.
- *                       E-mail:
- *                <brain@chatspike.net>
- *               <Craig@chatspike.net>
+ *         InspIRCd is copyright (C) 2002-2006 ChatSpike-Dev.
+ *                             E-mail:
+ *                      <brain@chatspike.net>
+ *                      <Craig@chatspike.net>
  *     
- * Written by Craig Edwards, Craig McLure, and others.
- * This program is free but copyrighted software; see
- *            the file COPYING for details.
+ *  Written by Craig Edwards, Craig McLure, and others.
+ *  This program is free but copyrighted software; you can redistribute
+ *  it and/or modify it under the terms of the GNU General Public
+ *  License as published by the Free Software Foundation, version 2
+ *  (two) ONLY.
  *
- * ---------------------------------------------------
+ *  This program is distributed in the hope that it will be useful,
+ *  but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *  GNU General Public License for more details.
+ *
+ *  You should have received a copy of the GNU General Public License
+ *  along with this program; if not, write to the Free Software
+ *  Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
+ *
+ * ---------------------------------------------------------------------
  */
 
-/* Now with added unF! ;) */
-
+#include <algorithm>
 #include "inspircd_config.h"
 #include "inspircd.h"
 #include "configreader.h"
 #include <fcntl.h>
 #include <sys/errno.h>
 #include <sys/ioctl.h>
+#include <signal.h>
 #include <time.h>
 #include <string>
 #include <exception>
@@ -32,9 +45,6 @@
 #include <fstream>
 #include <vector>
 #include <deque>
-#ifdef THREADED_DNS
-#include <pthread.h>
-#endif
 #include "users.h"
 #include "ctables.h"
 #include "globals.h"
 #include "commands.h"
 #include "xline.h"
 #include "inspstring.h"
-#include "dnsqueue.h"
 #include "helperfuncs.h"
 #include "hashcomp.h"
 #include "socketengine.h"
+#include "inspircd_se_config.h"
 #include "userprocess.h"
 #include "socket.h"
 #include "typedefs.h"
 
 InspIRCd* ServerInstance;
 
-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
-
-extern std::vector<Module*> modules;
-extern std::vector<ircd_module*> factory;
+extern ModuleList modules;
+extern FactoryList factory;
 
 std::vector<InspSocket*> module_sockets;
 std::vector<userrec*> local_users;
 
 extern int MODCOUNT;
 extern char LOG_FILE[MAXBUF];
-int openSockfd[MAX_DESCRIPTORS];
-int yield_depth;
+
 int iterations = 0;
 
 insp_sockaddr client, server;
-
 socklen_t length;
 
 extern InspSocket* socket_ref[MAX_DESCRIPTORS];
-
 time_t TIME = time(NULL), OLDTIME = time(NULL);
 
 // This table references users by file descriptor.
 // its an array to make it VERY fast, as all lookups are referenced
 // by an integer, meaning there is no need for a scan/search operation.
 userrec* fd_ref_table[MAX_DESCRIPTORS];
-
 Server* MyServer = new Server;
 ServerConfig *Config = new ServerConfig;
-
 user_hash clientlist;
 chan_hash chanlist;
-
 servernamelist servernames;
 char lowermap[255];
 
-void AddServerName(std::string servername)
+void AddServerName(const std::string &servername)
 {
        log(DEBUG,"Adding server name: %s",servername.c_str());
-       for (servernamelist::iterator a = servernames.begin(); a < servernames.end(); a++)
-       {
-               if (*a == servername)
-                       return;
-       }
-       servernames.push_back(servername);
+       
+       if(find(servernames.begin(), servernames.end(), servername) == servernames.end())
+               servernames.push_back(servername); /* Wasn't already there. */
 }
 
-const char* FindServerNamePtr(std::string servername)
+const char* FindServerNamePtr(const std::string &servername)
 {
-       for (servernamelist::iterator a = servernames.begin(); a < servernames.end(); a++)
-       {
-               if (*a == servername)
-                       return a->c_str();
+       servernamelist::iterator iter = find(servernames.begin(), servernames.end(), servername);
+       
+       if(iter == servernames.end())
+       {               
+               AddServerName(servername);
+               iter = --servernames.end();
        }
-       AddServerName(servername);
-       return FindServerNamePtr(servername);
+
+       return iter->c_str();
 }
 
-bool FindServerName(std::string servername)
+bool FindServerName(const std::string &servername)
 {
-       for (servernamelist::iterator a = servernames.begin(); a < servernames.end(); a++)
-       {
-               if (*a == servername)
-                       return true;
-       }
-       return false;
+       return (find(servernames.begin(), servernames.end(), servername) != servernames.end());
 }
 
 void Exit(int status)
@@ -134,11 +129,11 @@ void Exit(int status)
        exit (status);
 }
 
-void Start()
+void InspIRCd::Start()
 {
        printf("\033[1;32mInspire Internet Relay Chat Server, compiled %s at %s\n",__DATE__,__TIME__);
        printf("(C) ChatSpike Development team.\033[0m\n\n");
-       printf("Developers:\t\t\033[1;32mBrain, FrostyCoolSlug, w00t, Om\033[0m\n");
+       printf("Developers:\t\t\033[1;32mBrain, FrostyCoolSlug, w00t, Om, Special\033[0m\n");
        printf("Others:\t\t\t\033[1;32mSee /INFO Output\033[0m\n");
        printf("Name concept:\t\t\033[1;32mLord_Zathras\033[0m\n\n");
 }
@@ -160,16 +155,17 @@ void Rehash(int status)
        FOREACH_MOD(I_OnRehash,OnRehash(""));
 }
 
-void SetSignals()
+void InspIRCd::SetSignals(bool SEGVHandler)
 {
        signal (SIGALRM, SIG_IGN);
        signal (SIGHUP, Rehash);
        signal (SIGPIPE, SIG_IGN);
        signal (SIGTERM, Exit);
-       signal (SIGSEGV, Error);
+       if (SEGVHandler)
+               signal (SIGSEGV, Error);
 }
 
-bool DaemonSeed()
+bool InspIRCd::DaemonSeed()
 {
        int childpid;
        if ((childpid = fork ()) < 0)
@@ -200,7 +196,7 @@ bool DaemonSeed()
        return true;
 }
 
-void WritePID(const std::string &filename)
+void InspIRCd::WritePID(const std::string &filename)
 {
        std::ofstream outfile(filename.c_str());
        if (outfile.is_open())
@@ -237,7 +233,9 @@ void InspIRCd::MakeLowerMap()
 
 InspIRCd::InspIRCd(int argc, char** argv)
 {
-       Start();
+       bool SEGVHandler = false;
+
+       this->Start();
        module_sockets.clear();
        this->startup_time = time(NULL);
        srand(time(NULL));
@@ -273,6 +271,10 @@ InspIRCd::InspIRCd(int argc, char** argv)
                        {
                                printf("WARNING: The `-nolimit' option is deprecated, and now on by default. This behaviour may change in the future.\n");
                        }
+                       else if (!strcmp(argv[i],"-notraceback"))
+                       {
+                               SEGVHandler = false;
+                       }
                        else if (!strcmp(argv[i],"-logfile"))
                        {
                                if (argc > i+1)
@@ -285,6 +287,12 @@ InspIRCd::InspIRCd(int argc, char** argv)
                                        printf("ERROR: The -logfile parameter must be followed by a log file name and path.\n");
                                        Exit(ERROR);
                                }
+                               i++;
+                       }
+                       else
+                       {
+                               printf("Usage: %s [-nofork] [-nolog] [-debug] [-wait] [-nolimit] [-notraceback] [-logfile <filename>]\n",argv[0]);
+                               Exit(ERROR);
                        }
                }
        }
@@ -295,13 +303,14 @@ InspIRCd::InspIRCd(int argc, char** argv)
 
        OpenLog(argv, argc);
        this->stats = new serverstats();
+       this->Parser = new CommandParser();
        Config->ClearStack();
-       Config->Read(true,NULL);
+       Config->Read(true, NULL);
        CheckRoot();
        this->ModeGrok = new ModeParser();
-       this->Parser = new CommandParser();
        AddServerName(Config->ServerName);
        CheckDie();
+       InitializeDisabledCommands(Config->DisabledCommands, this);
        stats->BoundPortCount = BindPorts(true);
 
        for(int t = 0; t < 255; t++)
@@ -310,10 +319,10 @@ InspIRCd::InspIRCd(int argc, char** argv)
        memset(&Config->implement_lists,0,sizeof(Config->implement_lists));
 
        printf("\n");
-       SetSignals();
+       this->SetSignals(SEGVHandler);
        if (!Config->nofork)
        {
-               if (!DaemonSeed())
+               if (!this->DaemonSeed())
                {
                        printf("ERROR: could not go into daemon mode. Shutting down.\n");
                        Exit(ERROR);
@@ -323,7 +332,9 @@ InspIRCd::InspIRCd(int argc, char** argv)
        /* Because of limitations in kqueue on freebsd, we must fork BEFORE we
         * initialize the socket engine.
         */
-       SE = new SocketEngine();
+       SocketEngineFactory* SEF = new SocketEngineFactory();
+       SE = SEF->Create();
+       delete SEF;
 
        /* We must load the modules AFTER initializing the socket engine, now */
 
@@ -333,11 +344,7 @@ InspIRCd::InspIRCd(int argc, char** argv)
 std::string InspIRCd::GetVersionString()
 {
        char versiondata[MAXBUF];
-#ifdef THREADED_DNS
-       char dnsengine[] = "multithread";
-#else
-       char dnsengine[] = "singlethread";
-#endif
+       char dnsengine[] = "singlethread-object";
        if (*Config->CustomVersion)
        {
                snprintf(versiondata,MAXBUF,"%s %s :%s",VERSION,Config->ServerName,Config->CustomVersion);
@@ -354,7 +361,7 @@ char* InspIRCd::ModuleError()
        return MODERR;
 }
 
-void InspIRCd::erase_factory(int j)
+void InspIRCd::EraseFactory(int j)
 {
        int v = 0;
        for (std::vector<ircd_module*>::iterator t = factory.begin(); t != factory.end(); t++)
@@ -369,14 +376,14 @@ void InspIRCd::erase_factory(int j)
        }
 }
 
-void InspIRCd::erase_module(int j)
+void InspIRCd::EraseModule(int j)
 {
        int v1 = 0;
        for (std::vector<Module*>::iterator m = modules.begin(); m!= modules.end(); m++)
        {
                if (v1 == j)
                {
-                       delete *m;
+                       DELETE(*m);
                        modules.erase(m);
                        modules.push_back(NULL);
                        break;
@@ -529,12 +536,12 @@ bool InspIRCd::UnloadModule(const char* filename)
                        }
 
                        // found the module
-                       log(DEBUG,"Deleting module...");
-                       erase_module(j);
-                       log(DEBUG,"Erasing module entry...");
-                       erase_factory(j);
                        log(DEBUG,"Removing dependent commands...");
                        Parser->RemoveCommands(filename);
+                       log(DEBUG,"Deleting module...");
+                       this->EraseModule(j);
+                       log(DEBUG,"Erasing module entry...");
+                       this->EraseFactory(j);
                        log(DEFAULT,"Module %s unloaded",filename);
                        MODCOUNT--;
                        BuildISupport();
@@ -579,17 +586,17 @@ bool InspIRCd::LoadModule(const char* filename)
                                return false;
                        }
                }
-               ircd_module* a = new ircd_module(modfile);
-               factory[MODCOUNT+1] = a;
-               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());
-                       return false;
-               }
                try
                {
-                       if (factory[MODCOUNT+1]->factory)
+                       ircd_module* a = new ircd_module(modfile);
+                       factory[MODCOUNT+1] = a;
+                       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());
+                               return false;
+                       }
+                       if ((int)factory[MODCOUNT+1]->factory != -1)
                        {
                                Module* m = factory[MODCOUNT+1]->factory->CreateModule(MyServer);
                                modules[MODCOUNT+1] = m;
@@ -609,7 +616,7 @@ bool InspIRCd::LoadModule(const char* filename)
                        else
                        {
                                        log(DEFAULT,"Unable to load %s",modfile);
-                               snprintf(MODERR,MAXBUF,"Factory function failed!");
+                               snprintf(MODERR,MAXBUF,"Factory function failed: Probably missing init_module() entrypoint.");
                                return false;
                        }
                }
@@ -687,11 +694,6 @@ void InspIRCd::DoOneIteration(bool process_module_sockets)
        insp_sockaddr sock_us;     // our port number
        socklen_t uslen;         // length of our port number
 
-       if (yield_depth > 100)
-               return;
-
-       yield_depth++;
-
        /* time() seems to be a pretty expensive syscall, so avoid calling it too much.
         * Once per loop iteration is pleanty.
         */
@@ -724,7 +726,6 @@ void InspIRCd::DoOneIteration(bool process_module_sockets)
                }
                TickMissedTimers(TIME);
                expire_run = true;
-               yield_depth--;
                return;
        }   
        else if ((TIME % 5) == 1)
@@ -765,10 +766,7 @@ void InspIRCd::DoOneIteration(bool process_module_sockets)
         * servers... so its nice and easy, just one call.
         */
        if (!(numberactive = SE->Wait(activefds)))
-       {
-               yield_depth--;
                return;
-       }
 
        /**
         * Now process each of the fd's. For users, we have a fast
@@ -808,12 +806,12 @@ void InspIRCd::DoOneIteration(bool process_module_sockets)
              
                                if ((s) && (!s->Poll()))
                                {
-                                       log(DEBUG,"inspircd.cpp: Socket poll returned false, close and bail");
+                                       log(DEBUG,"Socket poll returned false, close and bail");
                                        SE->DelFd(s->GetFd());
                                        socket_ref[activefds[activefd]] = NULL;
                                        for (std::vector<InspSocket*>::iterator a = module_sockets.begin(); a < module_sockets.end(); a++)
                                        {
-                                               s_del = (InspSocket*)*a;
+                                               s_del = *a;
                                                if ((s_del) && (s_del->GetFd() == activefds[activefd]))
                                                {
                                                        module_sockets.erase(a);
@@ -821,7 +819,7 @@ void InspIRCd::DoOneIteration(bool process_module_sockets)
                                                }
                                        }
                                        s->Close();
-                                       delete s;
+                                       DELETE(s);
                                }
                                else if (!s)
                                {
@@ -831,22 +829,16 @@ void InspIRCd::DoOneIteration(bool process_module_sockets)
                        break;
 
                        case X_ESTAB_DNS:
-                               /* When we are using single-threaded dns,
-                                * the sockets for dns end up in our mainloop.
-                                * When we are using multi-threaded dns,
-                                * each thread has its own basic poll() loop
-                                * within it, making them 'fire and forget'
-                                * and independent of the mainloop.
+                               /* Handles instances of the Resolver class,
+                                * a simple class extended by modules and the core for
+                                * nonblocking resolving of addresses.
                                 */
-#ifndef THREADED_DNS
-                               log(DEBUG,"Type: X_ESTAB_DNS: fd=%d",activefds[activefd]);
-                               dns_poll(activefds[activefd]);
-#endif
+                               this->Res->MarshallReads(activefds[activefd]);
                        break;
 
                        case X_LISTEN:
 
-                               log(DEBUG,"Type: X_LISTEN_MODULE: fd=%d",activefds[activefd]);
+                               log(DEBUG,"Type: X_LISTEN: fd=%d",activefds[activefd]);
 
                                /* It's a listener */
                                uslen = sizeof(sock_us);
@@ -855,7 +847,11 @@ void InspIRCd::DoOneIteration(bool process_module_sockets)
        
                                if ((incomingSockfd > -1) && (!getsockname(incomingSockfd,(sockaddr*)&sock_us,&uslen)))
                                {
+#ifdef IPV6
+                                       in_port = ntohs(sock_us.sin6_port);
+#else
                                        in_port = ntohs(sock_us.sin_port);
+#endif
                                        log(DEBUG,"Accepted socket %d",incomingSockfd);
                                        /* Years and years ago, we used to resolve here
                                         * using gethostbyaddr(). That is sucky and we
@@ -866,7 +862,11 @@ void InspIRCd::DoOneIteration(bool process_module_sockets)
                                        {
                                                try
                                                {
-                                                       Config->GetIOHook(in_port)->OnRawSocketAccept(incomingSockfd, (char*)inet_ntoa(client.sin_addr), in_port);
+#ifdef IPV6
+                                                       Config->GetIOHook(in_port)->OnRawSocketAccept(incomingSockfd, insp_ntoa(client.sin6_addr), in_port);
+#else
+                                                       Config->GetIOHook(in_port)->OnRawSocketAccept(incomingSockfd, insp_ntoa(client.sin_addr), in_port);
+#endif
                                                }
                                                catch (ModuleException& modexcept)
                                                {
@@ -874,12 +874,18 @@ void InspIRCd::DoOneIteration(bool process_module_sockets)
                                                }
                                        }
                                        stats->statsAccept++;
+#ifdef IPV6
+                                       log(DEBUG,"Add ipv6 client");
+                                       AddClient(incomingSockfd, in_port, false, client.sin6_addr);
+#else
+                                       log(DEBUG,"Add ipv4 client");
                                        AddClient(incomingSockfd, in_port, false, client.sin_addr);
-                                       log(DEBUG,"Adding client on port %lu fd=%lu",(unsigned long)in_port,(unsigned long)incomingSockfd);
+#endif
+                                       log(DEBUG,"Adding client on port %d fd=%d",in_port,incomingSockfd);
                                }
                                else
                                {
-                                       log(DEBUG,"Accept failed on fd %lu: %s",(unsigned long)incomingSockfd,strerror(errno));
+                                       log(DEBUG,"Accept failed on fd %d: %s",incomingSockfd,strerror(errno));
                                        shutdown(incomingSockfd,2);
                                        close(incomingSockfd);
                                        stats->statsRefused++;
@@ -897,20 +903,39 @@ void InspIRCd::DoOneIteration(bool process_module_sockets)
                        break;
                }
        }
-       yield_depth--;
 }
 
 int InspIRCd::Run()
 {
        /* Until THIS point, ServerInstance == NULL */
-       
+
+       this->Res = new DNS();
+
        LoadAllModules(this);
 
        /* Just in case no modules were loaded - fix for bug #101 */
        this->BuildISupport();
 
-       printf("\nInspIRCd is now running!\n");
-       
+       if (!stats->BoundPortCount)
+       {
+               printf("\nI couldn't bind any ports! Are you sure you didn't start InspIRCd twice?\n");
+               Exit(ERROR);
+       }
+
+       /* Add the listening sockets used for client inbound connections
+        * to the socket engine
+        */
+       log(DEBUG,"%d listeners",stats->BoundPortCount);
+       for (unsigned long count = 0; count < stats->BoundPortCount; count++)
+       {
+               log(DEBUG,"Add listener: %d",Config->openSockfd[count]);
+               if (!SE->AddFd(Config->openSockfd[count],true,X_LISTEN))
+               {
+                       printf("\nEH? Could not add listener to socketengine. You screwed up, aborting.\n");
+                       Exit(ERROR);
+               }
+       }
+
        if (!Config->nofork)
        {
                fclose(stdout);
@@ -918,17 +943,12 @@ int InspIRCd::Run()
                fclose(stdin);
        }
 
-       /* Add the listening sockets used for client inbound connections
-        * to the socket engine
-        */
-       for (int count = 0; count < stats->BoundPortCount; count++)
-               SE->AddFd(openSockfd[count],true,X_LISTEN);
+       printf("\nInspIRCd is now running!\n");
 
-       WritePID(Config->PID);
+       this->WritePID(Config->PID);
 
        /* main loop, this never returns */
        expire_run = false;
-       yield_depth = 0;
        iterations = 0;
 
        while (true)
@@ -947,11 +967,19 @@ int InspIRCd::Run()
 
 int main(int argc, char** argv)
 {
+       /* This is a MatchCIDR() test suite -
+       printf("Should be 0: %d\n",MatchCIDR("127.0.0.1","1.2.3.4/8"));
+       printf("Should be 1: %d\n",MatchCIDR("127.0.0.1","127.0.0.0/8"));
+       printf("Should be 1: %d\n",MatchCIDR("127.0.0.1","127.0.0.0/18"));
+       printf("Should be 0: %d\n",MatchCIDR("3ffe::0","2fc9::0/16"));
+       printf("Should be 1: %d\n",MatchCIDR("3ffe:1:3::0", "3ffe:1::0/32"));
+       exit(0); */
+
        try
        {
                ServerInstance = new InspIRCd(argc, argv);
                ServerInstance->Run();
-               delete ServerInstance;
+               DELETE(ServerInstance);
        }
        catch (std::bad_alloc)
        {