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