]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/inspircd.cpp
Removed excessive debug for something thats now fixed
[user/henk/code/inspircd.git] / src / inspircd.cpp
1 /*       +------------------------------------+
2  *       | Inspire Internet Relay Chat Daemon |
3  *       +------------------------------------+
4  *
5  *  InspIRCd is copyright (C) 2002-2006 ChatSpike-Dev.
6  *                       E-mail:
7  *                <brain@chatspike.net>
8  *                <Craig@chatspike.net>
9  *     
10  * Written by Craig Edwards, Craig McLure, and others.
11  * This program is free but copyrighted software; see
12  *            the file COPYING for details.
13  *
14  * ---------------------------------------------------
15  */
16
17 /* Now with added unF! ;) */
18
19 using namespace std;
20
21 #include "inspircd_config.h"
22 #include "inspircd.h"
23 #include "inspircd_io.h"
24 #include <unistd.h>
25 #include <fcntl.h>
26 #include <sys/errno.h>
27 #include <sys/ioctl.h>
28 #include <sys/utsname.h>
29 #include <time.h>
30 #include <string>
31 #ifdef GCC3
32 #include <ext/hash_map>
33 #else
34 #include <hash_map>
35 #endif
36 #include <map>
37 #include <sstream>
38 #include <vector>
39 #include <deque>
40 #ifdef THREADED_DNS
41 #include <pthread.h>
42 #endif
43 #include "users.h"
44 #include "ctables.h"
45 #include "globals.h"
46 #include "modules.h"
47 #include "dynamic.h"
48 #include "wildcard.h"
49 #include "message.h"
50 #include "mode.h"
51 #include "commands.h"
52 #include "xline.h"
53 #include "inspstring.h"
54 #include "dnsqueue.h"
55 #include "helperfuncs.h"
56 #include "hashcomp.h"
57 #include "socketengine.h"
58 #include "userprocess.h"
59 #include "socket.h"
60 #include "typedefs.h"
61 #include "command_parse.h"
62
63 InspIRCd* ServerInstance;
64
65 int WHOWAS_STALE = 48; // default WHOWAS Entries last 2 days before they go 'stale'
66 int WHOWAS_MAX = 100;  // default 100 people maximum in the WHOWAS list
67
68 extern std::vector<Module*> modules;
69 extern std::vector<ircd_module*> factory;
70
71 std::vector<InspSocket*> module_sockets;
72 std::vector<userrec*> local_users;
73
74 extern int MODCOUNT;
75 int openSockfd[MAXSOCKS];
76 sockaddr_in client,server;
77 socklen_t length;
78
79 extern InspSocket* socket_ref[MAX_DESCRIPTORS];
80
81 time_t TIME = time(NULL), OLDTIME = time(NULL);
82
83 // This table references users by file descriptor.
84 // its an array to make it VERY fast, as all lookups are referenced
85 // by an integer, meaning there is no need for a scan/search operation.
86 userrec* fd_ref_table[MAX_DESCRIPTORS];
87
88 Server* MyServer = new Server;
89 ServerConfig *Config = new ServerConfig;
90
91 user_hash clientlist;
92 chan_hash chanlist;
93 whowas_hash whowas;
94 servernamelist servernames;
95 char lowermap[255];
96
97 void AddServerName(std::string servername)
98 {
99         log(DEBUG,"Adding server name: %s",servername.c_str());
100         for (servernamelist::iterator a = servernames.begin(); a < servernames.end(); a++)
101         {
102                 if (*a == servername)
103                         return;
104         }
105         servernames.push_back(servername);
106 }
107
108 const char* FindServerNamePtr(std::string servername)
109 {
110         for (servernamelist::iterator a = servernames.begin(); a < servernames.end(); a++)
111         {
112                 if (*a == servername)
113                         return a->c_str();
114         }
115         AddServerName(servername);
116         return FindServerNamePtr(servername);
117 }
118
119 std::string InspIRCd::GetRevision()
120 {
121         /* w00t got me to replace a bunch of strtok_r
122          * with something nicer, so i did this. Its the
123          * same thing really, only in C++. It places the
124          * text into a std::stringstream which is a readable
125          * and writeable buffer stream, and then pops two
126          * words off it, space delimited. Because it reads
127          * into the same variable twice, the first word
128          * is discarded, and the second one returned.
129          */
130         std::stringstream Revision("$Revision$");
131         std::string single;
132         Revision >> single >> single;
133         return single;
134 }
135
136 void InspIRCd::MakeLowerMap()
137 {
138         // initialize the lowercase mapping table
139         for (unsigned int cn = 0; cn < 256; cn++)
140                 lowermap[cn] = cn;
141         // lowercase the uppercase chars
142         for (unsigned int cn = 65; cn < 91; cn++)
143                 lowermap[cn] = tolower(cn);
144         // now replace the specific chars for scandanavian comparison
145         lowermap[(unsigned)'['] = '{';
146         lowermap[(unsigned)']'] = '}';
147         lowermap[(unsigned)'\\'] = '|';
148 }
149
150 InspIRCd::InspIRCd(int argc, char** argv)
151 {
152         Start();
153         module_sockets.clear();
154         this->startup_time = time(NULL);
155         srand(time(NULL));
156         log(DEBUG,"*** InspIRCd starting up!");
157         if (!FileExists(CONFIG_FILE))
158         {
159                 printf("ERROR: Cannot open config file: %s\nExiting...\n",CONFIG_FILE);
160                 log(DEFAULT,"main: no config");
161                 printf("ERROR: Your config file is missing, this IRCd will self destruct in 10 seconds!\n");
162                 Exit(ERROR);
163         }
164         if (argc > 1) {
165                 for (int i = 1; i < argc; i++)
166                 {
167                         if (!strcmp(argv[i],"-nofork")) {
168                                 Config->nofork = true;
169                         }
170                         if (!strcmp(argv[i],"-wait")) {
171                                 sleep(6);
172                         }
173                         if (!strcmp(argv[i],"-nolimit")) {
174                                 Config->unlimitcore = true;
175                         }
176                 }
177         }
178
179         strlcpy(Config->MyExecutable,argv[0],MAXBUF);
180
181         this->MakeLowerMap();
182
183         OpenLog(argv, argc);
184         Config->ClearStack();
185         Config->Read(true,NULL);
186         CheckRoot();
187         this->ModeGrok = new ModeParser();
188         this->Parser = new CommandParser();
189         this->stats = new serverstats();
190         AddServerName(Config->ServerName);
191         CheckDie();
192         stats->BoundPortCount = BindPorts();
193
194         for(int t = 0; t < 255; t++)
195                 Config->global_implementation[t] = 0;
196
197         memset(&Config->implement_lists,0,sizeof(Config->implement_lists));
198
199         printf("\n");
200         SetSignals();
201         if (!Config->nofork)
202         {
203                 if (DaemonSeed() == ERROR)
204                 {
205                         printf("ERROR: could not go into daemon mode. Shutting down.\n");
206                         Exit(ERROR);
207                 }
208         }
209
210         /* Because of limitations in kqueue on freebsd, we must fork BEFORE we
211          * initialize the socket engine.
212          */
213         SE = new SocketEngine();
214
215         /* We must load the modules AFTER initializing the socket engine, now */
216
217         return;
218 }
219
220 std::string InspIRCd::GetVersionString()
221 {
222         char versiondata[MAXBUF];
223 #ifdef THREADED_DNS
224         char dnsengine[] = "multithread";
225 #else
226         char dnsengine[] = "singlethread";
227 #endif
228         if (*Config->CustomVersion)
229         {
230                 snprintf(versiondata,MAXBUF,"%s Rev. %s %s :%s",VERSION,GetRevision().c_str(),Config->ServerName,Config->CustomVersion);
231         }
232         else
233         {
234                 snprintf(versiondata,MAXBUF,"%s Rev. %s %s :%s [FLAGS=%lu,%s,%s]",VERSION,GetRevision().c_str(),Config->ServerName,SYSTEM,(unsigned long)OPTIMISATION,SE->GetName().c_str(),dnsengine);
235         }
236         return versiondata;
237 }
238
239 char* InspIRCd::ModuleError()
240 {
241         return MODERR;
242 }
243
244 void InspIRCd::erase_factory(int j)
245 {
246         int v = 0;
247         for (std::vector<ircd_module*>::iterator t = factory.begin(); t != factory.end(); t++)
248         {
249                 if (v == j)
250                 {
251                         factory.erase(t);
252                         factory.push_back(NULL);
253                         return;
254                 }
255                 v++;
256         }
257 }
258
259 void InspIRCd::erase_module(int j)
260 {
261         int v1 = 0;
262         for (std::vector<Module*>::iterator m = modules.begin(); m!= modules.end(); m++)
263         {
264                 if (v1 == j)
265                 {
266                         delete *m;
267                         modules.erase(m);
268                         modules.push_back(NULL);
269                         break;
270                 }
271                 v1++;
272         }
273         int v2 = 0;
274         for (std::vector<std::string>::iterator v = Config->module_names.begin(); v != Config->module_names.end(); v++)
275         {
276                 if (v2 == j)
277                 {
278                        Config->module_names.erase(v);
279                        break;
280                 }
281                 v2++;
282         }
283
284 }
285
286 void InspIRCd::MoveTo(std::string modulename,int slot)
287 {
288         unsigned int v2 = 256;
289         log(DEBUG,"Moving %s to slot %d",modulename.c_str(),slot);
290         for (unsigned int v = 0; v < Config->module_names.size(); v++)
291         {
292                 if (Config->module_names[v] == modulename)
293                 {
294                         // found an instance, swap it with the item at MODCOUNT
295                         v2 = v;
296                         break;
297                 }
298         }
299         if (v2 == (unsigned int)slot)
300         {
301                 log(DEBUG,"Item %s already in slot %d!",modulename.c_str(),slot);
302         }
303         else if (v2 < 256)
304         {
305                 // Swap the module names over
306                 Config->module_names[v2] = Config->module_names[slot];
307                 Config->module_names[slot] = modulename;
308                 // now swap the module factories
309                 ircd_module* temp = factory[v2];
310                 factory[v2] = factory[slot];
311                 factory[slot] = temp;
312                 // now swap the module objects
313                 Module* temp_module = modules[v2];
314                 modules[v2] = modules[slot];
315                 modules[slot] = temp_module;
316                 // now swap the implement lists (we dont
317                 // need to swap the global or recount it)
318                 for (int n = 0; n < 255; n++)
319                 {
320                         char x = Config->implement_lists[v2][n];
321                         Config->implement_lists[v2][n] = Config->implement_lists[slot][n];
322                         Config->implement_lists[slot][n] = x;
323                 }
324                 log(DEBUG,"Moved %s to slot successfully",modulename.c_str());
325         }
326         else
327         {
328                 log(DEBUG,"Move of %s to slot failed!",modulename.c_str());
329         }
330 }
331
332 void InspIRCd::MoveAfter(std::string modulename, std::string after)
333 {
334         log(DEBUG,"Move %s after %s...",modulename.c_str(),after.c_str());
335         for (unsigned int v = 0; v < Config->module_names.size(); v++)
336         {
337                 if (Config->module_names[v] == after)
338                 {
339                         MoveTo(modulename, v);
340                         return;
341                 }
342         }
343 }
344
345 void InspIRCd::MoveBefore(std::string modulename, std::string before)
346 {
347         log(DEBUG,"Move %s before %s...",modulename.c_str(),before.c_str());
348         for (unsigned int v = 0; v < Config->module_names.size(); v++)
349         {
350                 if (Config->module_names[v] == before)
351                 {
352                         if (v > 0)
353                         {
354                                 MoveTo(modulename, v-1);
355                         }
356                         else
357                         {
358                                 MoveTo(modulename, v);
359                         }
360                         return;
361                 }
362         }
363 }
364
365 void InspIRCd::MoveToFirst(std::string modulename)
366 {
367         MoveTo(modulename,0);
368 }
369
370 void InspIRCd::MoveToLast(std::string modulename)
371 {
372         MoveTo(modulename,MODCOUNT);
373 }
374
375 void InspIRCd::BuildISupport()
376 {
377         // the neatest way to construct the initial 005 numeric, considering the number of configure constants to go in it...
378         std::stringstream v;
379         v << "WALLCHOPS MODES=" << MAXMODES << " CHANTYPES=# PREFIX=(ohv)@%+ MAP SAFELIST MAXCHANNELS=" << MAXCHANS << " MAXBANS=60 NICKLEN=" << NICKMAX-1;
380         v << " CASEMAPPING=rfc1459 STATUSMSG=@+ CHARSET=ascii TOPICLEN=" << MAXTOPIC << " KICKLEN=" << MAXKICK << " MAXTARGETS=" << Config->MaxTargets << " AWAYLEN=";
381         v << MAXAWAY << " CHANMODES=b,k,l,psmnti NETWORK=" << Config->Network;
382         Config->data005 = v.str();
383         FOREACH_MOD(I_On005Numeric,On005Numeric(Config->data005));
384 }
385
386 bool InspIRCd::UnloadModule(const char* filename)
387 {
388         std::string filename_str = filename;
389         for (unsigned int j = 0; j != Config->module_names.size(); j++)
390         {
391                 if (Config->module_names[j] == filename_str)
392                 {
393                         if (modules[j]->GetVersion().Flags & VF_STATIC)
394                         {
395                                 log(DEFAULT,"Failed to unload STATIC module %s",filename);
396                                 snprintf(MODERR,MAXBUF,"Module not unloadable (marked static)");
397                                 return false;
398                         }
399                         /* Give the module a chance to tidy out all its metadata */
400                         for (chan_hash::iterator c = chanlist.begin(); c != chanlist.end(); c++)
401                         {
402                                 modules[j]->OnCleanup(TYPE_CHANNEL,c->second);
403                         }
404                         for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
405                         {
406                                 modules[j]->OnCleanup(TYPE_USER,u->second);
407                         }
408
409                         FOREACH_MOD(I_OnUnloadModule,OnUnloadModule(modules[j],Config->module_names[j]));
410
411                         for(int t = 0; t < 255; t++)
412                         {
413                                 Config->global_implementation[t] -= Config->implement_lists[j][t];
414                         }
415
416                         /* We have to renumber implement_lists after unload because the module numbers change!
417                          */
418                         for(int j2 = j; j2 < 254; j2++)
419                         {
420                                 for(int t = 0; t < 255; t++)
421                                 {
422                                         Config->implement_lists[j2][t] = Config->implement_lists[j2+1][t];
423                                 }
424                         }
425
426                         // found the module
427                         log(DEBUG,"Deleting module...");
428                         erase_module(j);
429                         log(DEBUG,"Erasing module entry...");
430                         erase_factory(j);
431                         log(DEBUG,"Removing dependent commands...");
432                         Parser->RemoveCommands(filename);
433                         log(DEFAULT,"Module %s unloaded",filename);
434                         MODCOUNT--;
435                         BuildISupport();
436                         return true;
437                 }
438         }
439         log(DEFAULT,"Module %s is not loaded, cannot unload it!",filename);
440         snprintf(MODERR,MAXBUF,"Module not loaded");
441         return false;
442 }
443
444 bool InspIRCd::LoadModule(const char* filename)
445 {
446         char modfile[MAXBUF];
447 #ifdef STATIC_LINK
448         strlcpy(modfile,filename,MAXBUF);
449 #else
450         snprintf(modfile,MAXBUF,"%s/%s",Config->ModPath,filename);
451 #endif
452         std::string filename_str = filename;
453 #ifndef STATIC_LINK
454         if (!DirValid(modfile))
455         {
456                 log(DEFAULT,"Module %s is not within the modules directory.",modfile);
457                 snprintf(MODERR,MAXBUF,"Module %s is not within the modules directory.",modfile);
458                 return false;
459         }
460 #endif
461         log(DEBUG,"Loading module: %s",modfile);
462 #ifndef STATIC_LINK
463         if (FileExists(modfile))
464         {
465 #endif
466                 for (unsigned int j = 0; j < Config->module_names.size(); j++)
467                 {
468                         if (Config->module_names[j] == filename_str)
469                         {
470                                 log(DEFAULT,"Module %s is already loaded, cannot load a module twice!",modfile);
471                                 snprintf(MODERR,MAXBUF,"Module already loaded");
472                                 return false;
473                         }
474                 }
475                 ircd_module* a = new ircd_module(modfile);
476                 factory[MODCOUNT+1] = a;
477                 if (factory[MODCOUNT+1]->LastError())
478                 {
479                         log(DEFAULT,"Unable to load %s: %s",modfile,factory[MODCOUNT+1]->LastError());
480                         snprintf(MODERR,MAXBUF,"Loader/Linker error: %s",factory[MODCOUNT+1]->LastError());
481                         MODCOUNT--;
482                         return false;
483                 }
484                 if (factory[MODCOUNT+1]->factory)
485                 {
486                         Module* m = factory[MODCOUNT+1]->factory->CreateModule(MyServer);
487                         modules[MODCOUNT+1] = m;
488                         /* save the module and the module's classfactory, if
489                          * this isnt done, random crashes can occur :/ */
490                         Config->module_names.push_back(filename);
491
492                         char* x = &Config->implement_lists[MODCOUNT+1][0];
493                         for(int t = 0; t < 255; t++)
494                                 x[t] = 0;
495
496                         modules[MODCOUNT+1]->Implements(x);
497
498                         for(int t = 0; t < 255; t++)
499                         {
500                                 Config->global_implementation[t] += Config->implement_lists[MODCOUNT+1][t];
501                                 if (Config->implement_lists[MODCOUNT+1][t])
502                                 {
503                                         log(DEBUG,"Add global implementation: %d %d => %d",MODCOUNT+1,t,Config->global_implementation[t]);
504                                 }
505                         }
506                 }
507                 else
508                 {
509                         log(DEFAULT,"Unable to load %s",modfile);
510                         snprintf(MODERR,MAXBUF,"Factory function failed!");
511                         return false;
512                 }
513 #ifndef STATIC_LINK
514         }
515         else
516         {
517                 log(DEFAULT,"InspIRCd: startup: Module Not Found %s",modfile);
518                 snprintf(MODERR,MAXBUF,"Module file could not be found");
519                 return false;
520         }
521 #endif
522         MODCOUNT++;
523         FOREACH_MOD(I_OnLoadModule,OnLoadModule(modules[MODCOUNT],filename_str));
524         // now work out which modules, if any, want to move to the back of the queue,
525         // and if they do, move them there.
526         std::vector<std::string> put_to_back;
527         std::vector<std::string> put_to_front;
528         std::map<std::string,std::string> put_before;
529         std::map<std::string,std::string> put_after;
530         for (unsigned int j = 0; j < Config->module_names.size(); j++)
531         {
532                 if (modules[j]->Prioritize() == PRIORITY_LAST)
533                 {
534                         put_to_back.push_back(Config->module_names[j]);
535                 }
536                 else if (modules[j]->Prioritize() == PRIORITY_FIRST)
537                 {
538                         put_to_front.push_back(Config->module_names[j]);
539                 }
540                 else if ((modules[j]->Prioritize() & 0xFF) == PRIORITY_BEFORE)
541                 {
542                         log(DEBUG,"Module %d wants PRIORITY_BEFORE",j);
543                         put_before[Config->module_names[j]] = Config->module_names[modules[j]->Prioritize() >> 8];
544                         log(DEBUG,"Before: %s",Config->module_names[modules[j]->Prioritize() >> 8].c_str());
545                 }
546                 else if ((modules[j]->Prioritize() & 0xFF) == PRIORITY_AFTER)
547                 {
548                         log(DEBUG,"Module %d wants PRIORITY_AFTER",j);
549                         put_after[Config->module_names[j]] = Config->module_names[modules[j]->Prioritize() >> 8];
550                         log(DEBUG,"After: %s",Config->module_names[modules[j]->Prioritize() >> 8].c_str());
551                 }
552         }
553         for (unsigned int j = 0; j < put_to_back.size(); j++)
554         {
555                 MoveToLast(put_to_back[j]);
556         }
557         for (unsigned int j = 0; j < put_to_front.size(); j++)
558         {
559                 MoveToFirst(put_to_front[j]);
560         }
561         for (std::map<std::string,std::string>::iterator j = put_before.begin(); j != put_before.end(); j++)
562         {
563                 MoveBefore(j->first,j->second);
564         }
565         for (std::map<std::string,std::string>::iterator j = put_after.begin(); j != put_after.end(); j++)
566         {
567                 MoveAfter(j->first,j->second);
568         }
569         BuildISupport();
570         return true;
571 }
572
573 int InspIRCd::Run()
574 {
575         bool expire_run = false;
576         int activefds[MAX_DESCRIPTORS];
577         int incomingSockfd;
578         int in_port;
579         userrec* cu = NULL;
580         InspSocket* s = NULL;
581         InspSocket* s_del = NULL;
582         char* target;
583         unsigned int numberactive;
584         sockaddr_in sock_us;     // our port number
585         socklen_t uslen;         // length of our port number
586
587         /* Until THIS point, ServerInstance == NULL */
588         
589         LoadAllModules(this);
590
591         printf("\nInspIRCd is now running!\n");
592         
593         if (!Config->nofork)
594         {
595                 freopen("/dev/null","w",stdout);
596                 freopen("/dev/null","w",stderr);
597         }
598
599         /* Add the listening sockets used for client inbound connections
600          * to the socket engine
601          */
602         for (int count = 0; count < stats->BoundPortCount; count++)
603                 SE->AddFd(openSockfd[count],true,X_LISTEN);
604
605         WritePID(Config->PID);
606
607         /* main loop, this never returns */
608         for (;;)
609         {
610                 /* time() seems to be a pretty expensive syscall, so avoid calling it too much.
611                  * Once per loop iteration is pleanty.
612                  */
613                 OLDTIME = TIME;
614                 TIME = time(NULL);
615
616                 /* Run background module timers every few seconds
617                  * (the docs say modules shouldnt rely on accurate
618                  * timing using this event, so we dont have to
619                  * time this exactly).
620                  */
621                 if (((TIME % 8) == 0) && (!expire_run))
622                 {
623                         expire_lines();
624                         FOREACH_MOD(I_OnBackgroundTimer,OnBackgroundTimer(TIME));
625                         expire_run = true;
626                         continue;
627                 }
628                 else if ((TIME % 8) == 1)
629                 {
630                         expire_run = false;
631                 }
632                 
633                 /* Once a second, do the background processing */
634                 if (TIME != OLDTIME)
635                         DoBackgroundUserStuff(TIME);
636
637                 /* Call the socket engine to wait on the active
638                  * file descriptors. The socket engine has everything's
639                  * descriptors in its list... dns, modules, users,
640                  * servers... so its nice and easy, just one call.
641                  */
642                 if (!(numberactive = SE->Wait(activefds)))
643                         continue;
644
645                 /**
646                  * Now process each of the fd's. For users, we have a fast
647                  * lookup table which can find a user by file descriptor, so
648                  * processing them by fd isnt expensive. If we have a lot of
649                  * listening ports or module sockets though, things could get
650                  * ugly.
651                  */
652                 for (unsigned int activefd = 0; activefd < numberactive; activefd++)
653                 {
654                         int socket_type = SE->GetType(activefds[activefd]);
655                         switch (socket_type)
656                         {
657                                 case X_ESTAB_CLIENT:
658
659                                         cu = fd_ref_table[activefds[activefd]];
660                                         if (cu)
661                                                 ProcessUser(cu);
662
663                                 break;
664
665                                 case X_ESTAB_MODULE:
666
667                                         /* Process module-owned sockets.
668                                          * Modules are encouraged to inherit their sockets from
669                                          * InspSocket so we can process them neatly like this.
670                                          */
671                                         s = socket_ref[activefds[activefd]];
672
673                                         if ((s) && (!s->Poll()))
674                                         {
675                                                 log(DEBUG,"Socket poll returned false, close and bail");
676                                                 SE->DelFd(s->GetFd());
677                                                 for (std::vector<InspSocket*>::iterator a = module_sockets.begin(); a < module_sockets.end(); a++)
678                                                 {
679                                                         s_del = (InspSocket*)*a;
680                                                         if ((s_del) && (s_del->GetFd() == activefds[activefd]))
681                                                         {
682                                                                 module_sockets.erase(a);
683                                                                 break;
684                                                         }
685                                                 }
686                                                 s->Close();
687                                                 delete s;
688                                         }
689
690                                 break;
691
692                                 case X_ESTAB_DNS:
693
694                                         /* When we are using single-threaded dns,
695                                          * the sockets for dns end up in our mainloop.
696                                          * When we are using multi-threaded dns,
697                                          * each thread has its own basic poll() loop
698                                          * within it, making them 'fire and forget'
699                                          * and independent of the mainloop.
700                                          */
701 #ifndef THREADED_DNS
702                                         dns_poll(activefds[activefd]);
703 #endif
704                                 break;
705                                 
706                                 case X_LISTEN:
707
708                                         /* It's a listener */
709                                         uslen = sizeof(sock_us);
710                                         length = sizeof(client);
711                                         incomingSockfd = accept (activefds[activefd],(struct sockaddr*)&client,&length);
712                                         
713                                         if ((incomingSockfd > -1) && (!getsockname(incomingSockfd,(sockaddr*)&sock_us,&uslen)))
714                                         {
715                                                 in_port = ntohs(sock_us.sin_port);
716                                                 log(DEBUG,"Accepted socket %d",incomingSockfd);
717                                                 target = (char*)inet_ntoa(client.sin_addr);
718                                                 /* Years and years ago, we used to resolve here
719                                                  * using gethostbyaddr(). That is sucky and we
720                                                  * don't do that any more...
721                                                  */
722                                                 NonBlocking(incomingSockfd);
723                                                 if (Config->GetIOHook(in_port))
724                                                 {
725                                                         Config->GetIOHook(in_port)->OnRawSocketAccept(incomingSockfd, target, in_port);
726                                                 }
727                                                 stats->statsAccept++;
728                                                 AddClient(incomingSockfd, target, in_port, false, target);
729                                                 log(DEBUG,"Adding client on port %lu fd=%lu",(unsigned long)in_port,(unsigned long)incomingSockfd);
730                                         }
731                                         else
732                                         {
733                                                 log(DEBUG,"Accept failed on fd %lu: %s",(unsigned long)incomingSockfd,strerror(errno));
734                                                 shutdown(incomingSockfd,2);
735                                                 close(incomingSockfd);
736                                                 stats->statsRefused++;
737                                         }
738                                 break;
739
740                                 default:
741                                         /* Something went wrong if we're in here.
742                                          * In fact, so wrong, im not quite sure
743                                          * what we would do, so for now, its going
744                                          * to safely do bugger all.
745                                          */
746                                 break;
747                         }
748                 }
749
750         }
751         /* This is never reached -- we hope! */
752         return 0;
753 }
754
755 /**********************************************************************************/
756
757 /**
758  * An ircd in four lines! bwahahaha. ahahahahaha. ahahah *cough*.
759  */
760
761 int main(int argc, char** argv)
762 {
763         ServerInstance = new InspIRCd(argc, argv);
764         ServerInstance->Run();
765         delete ServerInstance;
766         return 0;
767 }
768