The InspIRCd Project
Home | Developers | Wiki | Forums | Bug Tracker | SVN | Download
Main Page | Namespace List | Class Hierarchy | Alphabetical List | Class List | Directories | File List | Namespace Members | Class Members | File Members

inspircd.cpp

Go to the documentation of this file.
00001 /*       +------------------------------------+
00002  *       | Inspire Internet Relay Chat Daemon |
00003  *       +------------------------------------+
00004  *
00005  *  InspIRCd: (C) 2002-2008 InspIRCd Development Team
00006  * See: http://www.inspircd.org/wiki/index.php/Credits
00007  *
00008  * This program is free but copyrighted software; see
00009  *          the file COPYING for details.
00010  *
00011  * ---------------------------------------------------
00012  */
00013 
00014 /* w00t was here. ;p */
00015 
00016 /* $Install: src/inspircd $(BINPATH) */
00017 #include "inspircd.h"
00018 #include <signal.h>
00019 
00020 #ifndef WIN32
00021         #include <dirent.h>
00022         #include <unistd.h>
00023         #include <sys/resource.h>
00024         #include <dlfcn.h>
00025         #include <getopt.h>
00026 
00027         /* Some systems don't define RUSAGE_SELF. This should fix them. */
00028         #ifndef RUSAGE_SELF
00029                 #define RUSAGE_SELF 0
00030         #endif
00031 
00032         /* CRT memory debugging */
00033         #ifdef DEBUG
00034         #define _CRTDBG_MAP_ALLOC
00035         #include <stdlib.h>
00036         #include <crtdbg.h>
00037         #endif
00038 #endif
00039 
00040 #include <fstream>
00041 #include "xline.h"
00042 #include "bancache.h"
00043 #include "socketengine.h"
00044 #include "inspircd_se_config.h"
00045 #include "socket.h"
00046 #include "command_parse.h"
00047 #include "exitcodes.h"
00048 #include "caller.h"
00049 #include "testsuite.h"
00050 
00051 InspIRCd* SI = NULL;
00052 int* mysig = NULL;
00053 
00054 
00055 /* Moved from exitcodes.h -- due to duplicate symbols -- Burlex
00056  * XXX this is a bit ugly. -- w00t
00057  */
00058 const char* ExitCodes[] =
00059 {
00060                 "No error", /* 0 */
00061                 "DIE command", /* 1 */
00062                 "execv() failed", /* 2 */
00063                 "Internal error", /* 3 */
00064                 "Config file error", /* 4 */
00065                 "Logfile error", /* 5 */
00066                 "POSIX fork failed", /* 6 */
00067                 "Bad commandline parameters", /* 7 */
00068                 "No ports could be bound", /* 8 */
00069                 "Can't write PID file", /* 9 */
00070                 "SocketEngine could not initialize", /* 10 */
00071                 "Refusing to start up as root", /* 11 */
00072                 "Found a <die> tag!", /* 12 */
00073                 "Couldn't load module on startup", /* 13 */
00074                 "Could not create windows forked process", /* 14 */
00075                 "Received SIGTERM", /* 15 */
00076                 "Bad command handler loaded", /* 16 */
00077                 "RegisterServiceCtrlHandler failed", /* 17 */
00078                 "UpdateSCMStatus failed", /* 18 */
00079                 "CreateEvent failed" /* 19 */
00080 };
00081 
00082 void InspIRCd::Cleanup()
00083 {
00084         if (Config)
00085         {
00086                 for (unsigned int i = 0; i < Config->ports.size(); i++)
00087                 {
00088                         /* This calls the constructor and closes the listening socket */
00089                         delete Config->ports[i];
00090                 }
00091 
00092                 Config->ports.clear();
00093         }
00094 
00095         /* Close all client sockets, or the new process inherits them */
00096         for (std::vector<User*>::const_iterator i = this->Users->local_users.begin(); i != this->Users->local_users.end(); i++)
00097         {
00098                 this->Users->QuitUser((*i), "Server shutdown");
00099                 (*i)->CloseSocket();
00100         }
00101 
00102         /* We do this more than once, so that any service providers get a
00103          * chance to be unhooked by the modules using them, but then get
00104          * a chance to be removed themsleves.
00105          *
00106          * XXX there may be a better way to do this with 1.2
00107          */
00108         for (int tries = 0; tries < 3; tries++)
00109         {
00110                 std::vector<std::string> module_names = Modules->GetAllModuleNames(0);
00111                 for (std::vector<std::string>::iterator k = module_names.begin(); k != module_names.end(); ++k)
00112                 {
00113                         /* Unload all modules, so they get a chance to clean up their listeners */
00114                         this->Modules->Unload(k->c_str());
00115                 }
00116         }
00117         /* Remove core commands */
00118         Parser->RemoveCommands("<core>");
00119 
00120         /* Cleanup Server Names */
00121         for(servernamelist::iterator itr = servernames.begin(); itr != servernames.end(); ++itr)
00122                 delete (*itr);
00123 
00124         /* Delete objects dynamically allocated in constructor
00125          * (destructor would be more appropriate, but we're likely exiting)
00126          */
00127 
00128         // Must be deleted before modes as it decrements modelines
00129         if (this->Users)
00130         {
00131                 delete this->Users;
00132                 this->Users = 0;
00133         }
00134         
00135         if (this->Modes)
00136         {
00137                 delete this->Modes;
00138                 this->Modes = 0;
00139         }
00140 
00141         if (this->XLines)
00142         {
00143                 delete this->XLines;
00144                 this->XLines = 0;
00145         }
00146 
00147         if (this->Parser)
00148         {
00149                 delete this->Parser;
00150                 this->Parser = 0;
00151 
00152         if (this->stats)
00153         {
00154                 delete this->stats;
00155                 this->stats = 0;
00156         }
00157 
00158         if (this->Modules)
00159         {
00160                 delete this->Modules;
00161                 this->Modules = 0;
00162         }
00163 
00164         if (this->BanCache)
00165                 delete this->BanCache;
00166                 this->BanCache = 0;
00167         }
00168 
00169         if (this->SNO)
00170         {
00171                 delete this->SNO;
00172                 this->SNO = 0;
00173         }
00174 
00175         if (this->Config)
00176         {
00177                 delete this->Config;
00178                 this->Config = 0;
00179         }
00180 
00181         if (this->Res)
00182         {
00183                 delete this->Res;
00184                 this->Res = 0;
00185         }
00186 
00187         if (this->chanlist)
00188         {
00189                 delete chanlist;
00190                 chanlist = 0;
00191         }
00192 
00193         if (this->PI)
00194         {
00195                 delete this->PI;
00196                 this->PI = 0;
00197         }
00198         
00199         if (this->Threads)
00200         {
00201                 delete this->Threads;
00202                 this->Threads = 0;
00203         }
00204 
00205         /* Needs to be deleted after Res, DNS has a timer */
00206         if (this->Timers)
00207         {
00208                 delete this->Timers;
00209                 this->Timers = 0;
00210         }
00211 
00212         /* Close logging */
00213         this->Logs->CloseLogs();
00214 
00215         if (this->Logs)
00216         {
00217                 delete this->Logs;
00218                 this->Logs = 0;
00219         }
00220 }
00221 
00222 void InspIRCd::Restart(const std::string &reason)
00223 {
00224         /* SendError flushes each client's queue,
00225          * regardless of writeability state
00226          */
00227         this->SendError(reason);
00228 
00229         /* Figure out our filename (if theyve renamed it, we're boned) */
00230         std::string me;
00231 
00232 #ifdef WINDOWS
00233         char module[MAX_PATH];
00234         if (GetModuleFileName(NULL, module, MAX_PATH))
00235                 me = module;
00236 #else
00237         me = Config->MyDir + "/inspircd";
00238 #endif
00239 
00240         char** argv = Config->argv;
00241 
00242         this->Cleanup();
00243 
00244         if (execv(me.c_str(), argv) == -1)
00245         {
00246                 /* Will raise a SIGABRT if not trapped */
00247                 throw CoreException(std::string("Failed to execv()! error: ") + strerror(errno));
00248         }
00249 }
00250 
00251 void InspIRCd::ResetMaxBans()
00252 {
00253         for (chan_hash::const_iterator i = chanlist->begin(); i != chanlist->end(); i++)
00254                 i->second->ResetMaxBans();
00255 }
00256 
00264 void InspIRCd::RehashUsersAndChans()
00265 {
00266         user_hash* old_users = this->Users->clientlist;
00267         user_hash* old_uuid  = this->Users->uuidlist;
00268         chan_hash* old_chans = this->chanlist;
00269 
00270         this->Users->clientlist = new user_hash();
00271         this->Users->uuidlist = new user_hash();
00272         this->chanlist = new chan_hash();
00273 
00274         for (user_hash::const_iterator n = old_users->begin(); n != old_users->end(); n++)
00275                 this->Users->clientlist->insert(*n);
00276 
00277         delete old_users;
00278 
00279         for (user_hash::const_iterator n = old_uuid->begin(); n != old_uuid->end(); n++)
00280                 this->Users->uuidlist->insert(*n);
00281 
00282         delete old_uuid;
00283 
00284         for (chan_hash::const_iterator n = old_chans->begin(); n != old_chans->end(); n++)
00285                 this->chanlist->insert(*n);
00286 
00287         delete old_chans;
00288 }
00289 
00290 void InspIRCd::SetSignals()
00291 {
00292 #ifndef WIN32
00293         signal(SIGALRM, SIG_IGN);
00294         signal(SIGHUP, InspIRCd::SetSignal);
00295         signal(SIGPIPE, SIG_IGN);
00296         signal(SIGCHLD, SIG_IGN);
00297 #endif
00298         signal(SIGTERM, InspIRCd::SetSignal);
00299 }
00300 
00301 void InspIRCd::QuickExit(int status)
00302 {
00303         exit(0);
00304 }
00305 
00306 bool InspIRCd::DaemonSeed()
00307 {
00308 #ifdef WINDOWS
00309         printf_c("InspIRCd Process ID: \033[1;32m%lu\033[0m\n", GetCurrentProcessId());
00310         return true;
00311 #else
00312         signal(SIGTERM, InspIRCd::QuickExit);
00313 
00314         int childpid;
00315         if ((childpid = fork ()) < 0)
00316                 return false;
00317         else if (childpid > 0)
00318         {
00319                 /* We wait here for the child process to kill us,
00320                  * so that the shell prompt doesnt come back over
00321                  * the output.
00322                  * Sending a kill with a signal of 0 just checks
00323                  * if the child pid is still around. If theyre not,
00324                  * they threw an error and we should give up.
00325                  */
00326                 while (kill(childpid, 0) != -1)
00327                         sleep(1);
00328                 exit(0);
00329         }
00330         setsid ();
00331         umask (007);
00332         printf("InspIRCd Process ID: \033[1;32m%lu\033[0m\n",(unsigned long)getpid());
00333 
00334         signal(SIGTERM, InspIRCd::SetSignal);
00335 
00336         rlimit rl;
00337         if (getrlimit(RLIMIT_CORE, &rl) == -1)
00338         {
00339                 this->Logs->Log("STARTUP",DEFAULT,"Failed to getrlimit()!");
00340                 return false;
00341         }
00342         else
00343         {
00344                 rl.rlim_cur = rl.rlim_max;
00345                 if (setrlimit(RLIMIT_CORE, &rl) == -1)
00346                         this->Logs->Log("STARTUP",DEFAULT,"setrlimit() failed, cannot increase coredump size.");
00347         }
00348 
00349         return true;
00350 #endif
00351 }
00352 
00353 void InspIRCd::WritePID(const std::string &filename)
00354 {
00355         std::string fname = (filename.empty() ? "inspircd.pid" : filename);
00356         std::replace(fname.begin(), fname.end(), '\\', '/');
00357         if ((fname[0] != '/') && (!Config->StartsWithWindowsDriveLetter(filename)))
00358         {
00359                 std::string::size_type pos;
00360                 std::string confpath = this->ConfigFileName;
00361                 if ((pos = confpath.rfind("/")) != std::string::npos)
00362                 {
00363                         /* Leaves us with just the path */
00364                         fname = confpath.substr(0, pos) + std::string("/") + fname;
00365                 }
00366         }
00367         std::ofstream outfile(fname.c_str());
00368         if (outfile.is_open())
00369         {
00370                 outfile << getpid();
00371                 outfile.close();
00372         }
00373         else
00374         {
00375                 printf("Failed to write PID-file '%s', exiting.\n",fname.c_str());
00376                 this->Logs->Log("STARTUP",DEFAULT,"Failed to write PID-file '%s', exiting.",fname.c_str());
00377                 Exit(EXIT_STATUS_PID);
00378         }
00379 }
00380 
00381 InspIRCd::InspIRCd(int argc, char** argv)
00382         : GlobalCulls(this),
00383 
00384          /* Functor initialisation. Note that the ordering here is very important. 
00385           *
00386           * THIS MUST MATCH ORDER OF DECLARATION OF THE HandleWhateverFunc classes
00387           * within class InspIRCd.
00388           */
00389          HandleProcessUser(this),
00390          HandleIsNick(this),
00391          HandleIsIdent(this),
00392          HandleFindDescriptor(this),
00393          HandleFloodQuitUser(this),
00394          HandleIsChannel(this),
00395          HandleIsSID(this),
00396          HandleRehash(this),
00397 
00398          /* Functor pointer initialisation. Must match the order of the list above
00399           *
00400           * THIS MUST MATCH THE ORDER OF DECLARATION OF THE FUNCTORS, e.g. the methods
00401           * themselves within the class.
00402           */
00403          ProcessUser(&HandleProcessUser),
00404          IsChannel(&HandleIsChannel),
00405          IsSID(&HandleIsSID),
00406          Rehash(&HandleRehash),
00407          IsNick(&HandleIsNick),
00408          IsIdent(&HandleIsIdent),
00409          FindDescriptor(&HandleFindDescriptor),
00410          FloodQuitUser(&HandleFloodQuitUser)
00411 
00412 {
00413 #ifdef WIN32
00414         // Strict, frequent checking of memory on debug builds
00415         _CrtSetDbgFlag ( _CRTDBG_CHECK_ALWAYS_DF | _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF );
00416         
00417         // Avoid erroneous frees on early exit
00418         WindowsIPC = 0;
00419 #endif
00420         int found_ports = 0;
00421         FailedPortList pl;
00422         int do_version = 0, do_nofork = 0, do_debug = 0,
00423             do_nolog = 0, do_root = 0, do_testsuite = 0;    /* flag variables */
00424         char c = 0;
00425 
00426         // Initialize so that if we exit before proper initialization they're not deleted
00427         this->Logs = 0;
00428         this->Threads = 0;
00429         this->PI = 0;
00430         this->Users = 0;
00431         this->chanlist = 0;
00432         this->Config = 0;
00433         this->SNO = 0;
00434         this->BanCache = 0;
00435         this->Modules = 0;
00436         this->stats = 0;
00437         this->Timers = 0;
00438         this->Parser = 0;
00439         this->XLines = 0;
00440         this->Modes = 0;
00441         this->Res = 0;
00442 
00443 
00444         memset(&server, 0, sizeof(server));
00445         memset(&client, 0, sizeof(client));
00446 
00447         // This must be created first, so other parts of Insp can use it while starting up
00448         this->Logs = new LogManager(this);
00449 
00450         SocketEngineFactory* SEF = new SocketEngineFactory();
00451         SE = SEF->Create(this);
00452         delete SEF;
00453 
00454         ThreadEngineFactory* tef = new ThreadEngineFactory();
00455         this->Threads = tef->Create(this);
00456         delete tef;
00457         this->Mutexes = new MutexFactory(this);
00458 
00459         /* Default implementation does nothing */
00460         this->PI = new ProtocolInterface(this);
00461 
00462         this->s_signal = 0;
00463         
00464         // Create base manager classes early, so nothing breaks
00465         this->Users = new UserManager(this);
00466         
00467         this->Users->unregistered_count = 0;
00468 
00469         this->Users->clientlist = new user_hash();
00470         this->Users->uuidlist = new user_hash();
00471         this->chanlist = new chan_hash();
00472 
00473         this->Config = new ServerConfig(this);
00474         this->SNO = new SnomaskManager(this);
00475         this->BanCache = new BanCacheManager(this);
00476         this->Modules = new ModuleManager(this);
00477         this->stats = new serverstats();
00478         this->Timers = new TimerManager(this);
00479         this->Parser = new CommandParser(this);
00480         this->XLines = new XLineManager(this);
00481 
00482         this->Config->argv = argv;
00483         this->Config->argc = argc;
00484 
00485         if (chdir(Config->GetFullProgDir().c_str()))
00486         {
00487                 printf("Unable to change to my directory: %s\nAborted.", strerror(errno));
00488                 exit(0);
00489         }
00490 
00491         this->Config->opertypes.clear();
00492         this->Config->operclass.clear();
00493 
00494         this->TIME = this->OLDTIME = this->startup_time = time(NULL);
00495         srand(this->TIME);
00496 
00497         *this->LogFileName = 0;
00498         strlcpy(this->ConfigFileName, CONFIG_FILE, MAXBUF);
00499 
00500         struct option longopts[] =
00501         {
00502                 { "nofork",     no_argument,            &do_nofork,     1       },
00503                 { "logfile",    required_argument,      NULL,           'f'     },
00504                 { "config",     required_argument,      NULL,           'c'     },
00505                 { "debug",      no_argument,            &do_debug,      1       },
00506                 { "nolog",      no_argument,            &do_nolog,      1       },
00507                 { "runasroot",  no_argument,            &do_root,       1       },
00508                 { "version",    no_argument,            &do_version,    1       },
00509                 { "testsuite",  no_argument,            &do_testsuite,  1       },
00510                 { 0, 0, 0, 0 }
00511         };
00512 
00513         while ((c = getopt_long_only(argc, argv, ":f:", longopts, NULL)) != -1)
00514         {
00515                 switch (c)
00516                 {
00517                         case 'f':
00518                                 /* Log filename was set */
00519                                 strlcpy(LogFileName, optarg, MAXBUF);
00520                         break;
00521                         case 'c':
00522                                 /* Config filename was set */
00523                                 strlcpy(ConfigFileName, optarg, MAXBUF);
00524                         break;
00525                         case 0:
00526                                 /* getopt_long_only() set an int variable, just keep going */
00527                         break;
00528                         default:
00529                                 /* Unknown parameter! DANGER, INTRUDER.... err.... yeah. */
00530                                 printf("Usage: %s [--nofork] [--nolog] [--debug] [--logfile <filename>]\n\
00531                                                   [--runasroot] [--version] [--config <config>] [--testsuite]\n", argv[0]);
00532                                 Exit(EXIT_STATUS_ARGV);
00533                         break;
00534                 }
00535         }
00536 
00537         if (do_testsuite)
00538                 do_nofork = do_debug = true;
00539 
00540         if (do_version)
00541         {
00542                 printf("\n%s r%s\n", VERSION, REVISION);
00543                 Exit(EXIT_STATUS_NOERROR);
00544         }
00545 
00546 #ifdef WIN32
00547 
00548         // Handle forking
00549         if(!do_nofork)
00550         {
00551                 DWORD ExitCode = WindowsForkStart(this);
00552                 if(ExitCode)
00553                         exit(ExitCode);
00554         }
00555 
00556         // Set up winsock
00557         WSADATA wsadata;
00558         WSAStartup(MAKEWORD(2,0), &wsadata);
00559         ChangeWindowsSpecificPointers(this);
00560 #endif
00561         strlcpy(Config->MyExecutable,argv[0],MAXBUF);
00562 
00563         /* Set the finished argument values */
00564         Config->nofork = do_nofork;
00565         Config->forcedebug = do_debug;
00566         Config->writelog = !do_nolog;
00567         Config->TestSuite = do_testsuite;
00568 
00569         if (!this->OpenLog(argv, argc))
00570         {
00571                 printf("ERROR: Could not open logfile %s: %s\n\n", Config->logpath.c_str(), strerror(errno));
00572                 Exit(EXIT_STATUS_LOG);
00573         }
00574 
00575         if (!ServerConfig::FileExists(this->ConfigFileName))
00576         {
00577                 printf("ERROR: Cannot open config file: %s\nExiting...\n", this->ConfigFileName);
00578                 this->Logs->Log("STARTUP",DEFAULT,"Unable to open config file %s", this->ConfigFileName);
00579                 Exit(EXIT_STATUS_CONFIG);
00580         }
00581 
00582         printf_c("\033[1;32mInspire Internet Relay Chat Server, compiled %s at %s\n",__DATE__,__TIME__);
00583         printf_c("(C) InspIRCd Development Team.\033[0m\n\n");
00584         printf_c("Developers:\n");
00585         printf_c("\t\033[1;32mBrain, FrostyCoolSlug, w00t, Om, Special\n");
00586         printf_c("\t\033[1;32mpippijn, peavey, aquanight, fez\033[0m\n\n");
00587         printf_c("Others:\t\t\t\033[1;32mSee /INFO Output\033[0m\n");
00588 
00589         Config->ClearStack();
00590 
00591         this->Modes = new ModeParser(this);
00592 
00593         if (!do_root)
00594                 this->CheckRoot();
00595         else
00596         {
00597                 printf("* WARNING * WARNING * WARNING * WARNING * WARNING * \n\n");
00598                 printf("YOU ARE RUNNING INSPIRCD AS ROOT. THIS IS UNSUPPORTED\n");
00599                 printf("AND IF YOU ARE HACKED, CRACKED, SPINDLED OR MUTILATED\n");
00600                 printf("OR ANYTHING ELSE UNEXPECTED HAPPENS TO YOU OR YOUR\n");
00601                 printf("SERVER, THEN IT IS YOUR OWN FAULT. IF YOU DID NOT MEAN\n");
00602                 printf("TO START INSPIRCD AS ROOT, HIT CTRL+C NOW AND RESTART\n");
00603                 printf("THE PROGRAM AS A NORMAL USER. YOU HAVE BEEN WARNED!\n");
00604                 printf("\nInspIRCd starting in 20 seconds, ctrl+c to abort...\n");
00605                 sleep(20);
00606         }
00607 
00608         this->SetSignals();
00609 
00610         if (!Config->nofork)
00611         {
00612                 if (!this->DaemonSeed())
00613                 {
00614                         printf("ERROR: could not go into daemon mode. Shutting down.\n");
00615                         Logs->Log("STARTUP", DEFAULT, "ERROR: could not go into daemon mode. Shutting down.");
00616                         Exit(EXIT_STATUS_FORK);
00617                 }
00618         }
00619 
00620         SE->RecoverFromFork();
00621 
00622         /* During startup we don't actually initialize this
00623          * in the thread engine.
00624          */
00625         this->ConfigThread = new ConfigReaderThread(this, true, "");
00626         ConfigThread->Run();
00627         delete ConfigThread;
00628         this->ConfigThread = NULL;
00629 
00630         this->Res = new DNS(this);
00631 
00632         this->AddServerName(Config->ServerName);
00633 
00634         /*
00635          * Initialise SID/UID.
00636          * For an explanation as to exactly how this works, and why it works this way, see GetUID().
00637          *   -- w00t
00638          */
00639         if (!*Config->sid)
00640         {
00641                 // Generate one
00642                 size_t sid = 0;
00643 
00644                 for (const char* x = Config->ServerName; *x; ++x)
00645                         sid = 5 * sid + *x;
00646                 for (const char* y = Config->ServerDesc; *y; ++y)
00647                         sid = 5 * sid + *y;
00648                 sid = sid % 999;
00649 
00650                 Config->sid[0] = (char)(sid / 100 + 48);
00651                 Config->sid[1] = (char)(((sid / 10) % 10) + 48);
00652                 Config->sid[2] = (char)(sid % 10 + 48);
00653                 Config->sid[3] = '\0';
00654         }
00655 
00656         /* set up fake client again this time with the correct uid */
00657         this->FakeClient = new User(this, "#INVALID");
00658         this->FakeClient->SetFd(FD_MAGIC_NUMBER);
00659 
00660         // Get XLine to do it's thing.
00661         this->XLines->CheckELines();
00662         this->XLines->ApplyLines();
00663 
00664         CheckDie();
00665         int bounditems = BindPorts(true, found_ports, pl);
00666 
00667         printf("\n");
00668 
00669         this->Modules->LoadAll();
00670         
00671         /* Just in case no modules were loaded - fix for bug #101 */
00672         this->BuildISupport();
00673         InitializeDisabledCommands(Config->DisabledCommands, this);
00674 
00675         if (Config->ports.size() != (unsigned int)found_ports)
00676         {
00677                 printf("\nWARNING: Not all your client ports could be bound --\nstarting anyway with %d of %d client ports bound.\n\n", bounditems, found_ports);
00678                 printf("The following port(s) failed to bind:\n");
00679                 printf("Hint: Try using a public IP instead of blank or *\n\n");
00680                 int j = 1;
00681                 for (FailedPortList::iterator i = pl.begin(); i != pl.end(); i++, j++)
00682                 {
00683                         printf("%d.\tAddress: %s\tReason: %s\n", j, i->first.empty() ? "<all>" : i->first.c_str(), i->second.c_str());
00684                 }
00685         }
00686 
00687         printf("\nInspIRCd is now running as '%s'[%s] with %d max open sockets\n", Config->ServerName,Config->GetSID().c_str(), SE->GetMaxFds());
00688         
00689 #ifndef WINDOWS
00690         if (!Config->nofork)
00691         {
00692                 if (kill(getppid(), SIGTERM) == -1)
00693                 {
00694                         printf("Error killing parent process: %s\n",strerror(errno));
00695                         Logs->Log("STARTUP", DEFAULT, "Error killing parent process: %s",strerror(errno));
00696                 }
00697         }
00698 
00699         if (isatty(0) && isatty(1) && isatty(2))
00700         {
00701                 /* We didn't start from a TTY, we must have started from a background process -
00702                  * e.g. we are restarting, or being launched by cron. Dont kill parent, and dont
00703                  * close stdin/stdout
00704                  */
00705                 if ((!do_nofork) && (!do_testsuite))
00706                 {
00707                         fclose(stdin);
00708                         fclose(stderr);
00709                         fclose(stdout);
00710                 }
00711                 else
00712                 {
00713                         Logs->Log("STARTUP", DEFAULT,"Keeping pseudo-tty open as we are running in the foreground.");
00714                 }
00715         }
00716 #else
00717         WindowsIPC = new IPC(this);
00718         if(!Config->nofork)
00719         {
00720                 WindowsForkKillOwner(this);
00721                 FreeConsole();
00722         }
00723         /* Set win32 service as running, if we are running as a service */
00724         SetServiceRunning();
00725 #endif
00726 
00727         Logs->Log("STARTUP", DEFAULT, "Startup complete as '%s'[%s], %d max open sockets", Config->ServerName,Config->GetSID().c_str(), SE->GetMaxFds());
00728 
00729         this->WritePID(Config->PID);
00730 }
00731 
00732 int InspIRCd::Run()
00733 {
00734         /* See if we're supposed to be running the test suite rather than entering the mainloop */
00735         if (Config->TestSuite)
00736         {
00737                 TestSuite* ts = new TestSuite(this);
00738                 delete ts;
00739                 Exit(0);
00740         }
00741 
00742         while (true)
00743         {
00744 #ifndef WIN32
00745                 static rusage ru;
00746 #else
00747                 static time_t uptime;
00748                 static struct tm * stime;
00749                 static char window_title[100];
00750 #endif
00751 
00752                 /* Check if there is a config thread which has finished executing but has not yet been freed */
00753                 if (this->ConfigThread && this->ConfigThread->GetExitFlag())
00754                 {
00755                         /* Rehash has completed */
00756                         this->Logs->Log("CONFIG",DEBUG,"Detected ConfigThread exiting, tidying up...");
00757 
00758                         /* IMPORTANT: This delete may hang if you fuck up your thread syncronization.
00759                          * It will hang waiting for the ConfigThread to 'join' to avoid race conditons,
00760                          * until the other thread is completed.
00761                          */
00762                         delete ConfigThread;
00763                         ConfigThread = NULL;
00764 
00765                         /* These are currently not known to be threadsafe, so they are executed outside
00766                          * of the thread. It would be pretty simple to move them to the thread Run method
00767                          * once they are known threadsafe with all the correct mutexes in place.
00768                          *
00769                          * XXX: The order of these is IMPORTANT, do not reorder them without testing
00770                          * thoroughly!!!
00771                          */
00772                         this->XLines->CheckELines();
00773                         this->XLines->ApplyLines();
00774                         this->Res->Rehash();
00775                         this->ResetMaxBans();
00776                         InitializeDisabledCommands(Config->DisabledCommands, this);
00777                         User* user = !Config->RehashUserUID.empty() ? FindNick(Config->RehashUserUID) : NULL;
00778                         FOREACH_MOD_I(this, I_OnRehash, OnRehash(user, Config->RehashParameter));
00779                         this->BuildISupport();
00780                 }
00781 
00782                 /* time() seems to be a pretty expensive syscall, so avoid calling it too much.
00783                  * Once per loop iteration is pleanty.
00784                  */
00785                 OLDTIME = TIME;
00786                 TIME = time(NULL);
00787 
00788                 /* Run background module timers every few seconds
00789                  * (the docs say modules shouldnt rely on accurate
00790                  * timing using this event, so we dont have to
00791                  * time this exactly).
00792                  */
00793                 if (TIME != OLDTIME)
00794                 {
00795                         /* Allow a buffer of two seconds drift on this so that ntpdate etc dont harass admins */
00796                         if (TIME < OLDTIME - 2)
00797                         {
00798                                 SNO->WriteToSnoMask('d', "\002EH?!\002 -- Time is flowing BACKWARDS in this dimension! Clock drifted backwards %lu secs.", (unsigned long)OLDTIME-TIME);
00799                         }
00800                         else if (TIME > OLDTIME + 2)
00801                         {
00802                                 SNO->WriteToSnoMask('d', "\002EH?!\002 -- Time is jumping FORWARDS! Clock skipped %lu secs.", (unsigned long)TIME - OLDTIME);
00803                         }
00804 
00805                         if ((TIME % 3600) == 0)
00806                         {
00807                                 this->RehashUsersAndChans();
00808                                 FOREACH_MOD_I(this, I_OnGarbageCollect, OnGarbageCollect());
00809                         }
00810 
00811                         Timers->TickTimers(TIME);
00812                         this->DoBackgroundUserStuff();
00813 
00814                         if ((TIME % 5) == 0)
00815                         {
00816                                 FOREACH_MOD_I(this,I_OnBackgroundTimer,OnBackgroundTimer(TIME));
00817                                 SNO->FlushSnotices();
00818                         }
00819 #ifndef WIN32
00820                         /* Same change as in cmd_stats.cpp, use RUSAGE_SELF rather than '0' -- Om */
00821                         if (!getrusage(RUSAGE_SELF, &ru))
00822                         {
00823                                 gettimeofday(&this->stats->LastSampled, NULL);
00824                                 this->stats->LastCPU = ru.ru_utime;
00825                         }
00826 #else
00827                         WindowsIPC->Check();    
00828 #endif
00829                 }
00830 
00831                 /* Call the socket engine to wait on the active
00832                  * file descriptors. The socket engine has everything's
00833                  * descriptors in its list... dns, modules, users,
00834                  * servers... so its nice and easy, just one call.
00835                  * This will cause any read or write events to be
00836                  * dispatched to their handlers.
00837                  */
00838                 this->SE->DispatchEvents();
00839 
00840                 /* if any users were quit, take them out */
00841                 this->GlobalCulls.Apply();
00842 
00843                 /* If any inspsockets closed, remove them */
00844                 this->BufferedSocketCull();
00845 
00846                 if (this->s_signal)
00847                 {
00848                         this->SignalHandler(s_signal);
00849                         this->s_signal = 0;
00850                 }
00851         }
00852 
00853         return 0;
00854 }
00855 
00856 void InspIRCd::BufferedSocketCull()
00857 {
00858         for (std::map<BufferedSocket*,BufferedSocket*>::iterator x = SocketCull.begin(); x != SocketCull.end(); ++x)
00859         {
00860                 this->Logs->Log("MISC",DEBUG,"Cull socket");
00861                 SE->DelFd(x->second);
00862                 x->second->Close();
00863                 delete x->second;
00864         }
00865         SocketCull.clear();
00866 }
00867 
00868 /**********************************************************************************/
00869 
00874 /* this returns true when all modules are satisfied that the user should be allowed onto the irc server
00875  * (until this returns true, a user will block in the waiting state, waiting to connect up to the
00876  * registration timeout maximum seconds)
00877  */
00878 bool InspIRCd::AllModulesReportReady(User* user)
00879 {
00880         for (EventHandlerIter i = Modules->EventHandlers[I_OnCheckReady].begin(); i != Modules->EventHandlers[I_OnCheckReady].end(); ++i)
00881         {
00882                 if (!(*i)->OnCheckReady(user))
00883                         return false;
00884         }
00885         return true;
00886 }
00887 
00888 time_t InspIRCd::Time()
00889 {
00890         return TIME;
00891 }
00892 
00893 void InspIRCd::SetSignal(int signal)
00894 {
00895         *mysig = signal;
00896 }
00897 
00898 /* On posix systems, the flow of the program starts right here, with
00899  * ENTRYPOINT being a #define that defines main(). On Windows, ENTRYPOINT
00900  * defines smain() and the real main() is in the service code under
00901  * win32service.cpp. This allows the service control manager to control
00902  * the process where we are running as a windows service.
00903  */
00904 ENTRYPOINT
00905 {
00906         SI = new InspIRCd(argc, argv);
00907         mysig = &SI->s_signal;
00908         SI->Run();
00909         delete SI;
00910         return 0;
00911 }