]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/inspircd.cpp
Signal handlers were not being set when -nofork was enabled
[user/henk/code/inspircd.git] / src / inspircd.cpp
1 /*       +------------------------------------+
2  *       | Inspire Internet Relay Chat Daemon |
3  *       +------------------------------------+
4  *
5  *  Inspire is copyright (C) 2002-2005 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[65535];
80
81 time_t TIME = time(NULL), OLDTIME = time(NULL);
82
83 SocketEngine* SE = NULL;
84
85 // This table references users by file descriptor.
86 // its an array to make it VERY fast, as all lookups are referenced
87 // by an integer, meaning there is no need for a scan/search operation.
88 userrec* fd_ref_table[65536];
89
90 Server* MyServer = new Server;
91 ServerConfig *Config = new ServerConfig;
92
93 user_hash clientlist;
94 chan_hash chanlist;
95 whowas_hash whowas;
96 servernamelist servernames;
97 char lowermap[255];
98
99 void AddServerName(std::string servername)
100 {
101         log(DEBUG,"Adding server name: %s",servername.c_str());
102         for (servernamelist::iterator a = servernames.begin(); a < servernames.end(); a++)
103         {
104                 if (*a == servername)
105                         return;
106         }
107         servernames.push_back(servername);
108 }
109
110 const char* FindServerNamePtr(std::string servername)
111 {
112         for (servernamelist::iterator a = servernames.begin(); a < servernames.end(); a++)
113         {
114                 if (*a == servername)
115                         return a->c_str();
116         }
117         AddServerName(servername);
118         return FindServerNamePtr(servername);
119 }
120
121 std::string InspIRCd::GetRevision()
122 {
123         /* w00t got me to replace a bunch of strtok_r
124          * with something nicer, so i did this. Its the
125          * same thing really, only in C++. It places the
126          * text into a std::stringstream which is a readable
127          * and writeable buffer stream, and then pops two
128          * words off it, space delimited. Because it reads
129          * into the same variable twice, the first word
130          * is discarded, and the second one returned.
131          */
132         std::stringstream Revision("$Revision$");
133         std::string single;
134         Revision >> single >> single;
135         return single;
136 }
137
138 void InspIRCd::MakeLowerMap()
139 {
140         // initialize the lowercase mapping table
141         for (unsigned int cn = 0; cn < 256; cn++)
142                 lowermap[cn] = cn;
143         // lowercase the uppercase chars
144         for (unsigned int cn = 65; cn < 91; cn++)
145                 lowermap[cn] = tolower(cn);
146         // now replace the specific chars for scandanavian comparison
147         lowermap[(unsigned)'['] = '{';
148         lowermap[(unsigned)']'] = '}';
149         lowermap[(unsigned)'\\'] = '|';
150 }
151
152 InspIRCd::InspIRCd(int argc, char** argv)
153 {
154         Start();
155         module_sockets.clear();
156         this->startup_time = time(NULL);
157         srand(time(NULL));
158         log(DEBUG,"*** InspIRCd starting up!");
159         if (!FileExists(CONFIG_FILE))
160         {
161                 printf("ERROR: Cannot open config file: %s\nExiting...\n",CONFIG_FILE);
162                 log(DEFAULT,"main: no config");
163                 printf("ERROR: Your config file is missing, this IRCd will self destruct in 10 seconds!\n");
164                 Exit(ERROR);
165         }
166         if (argc > 1) {
167                 for (int i = 1; i < argc; i++)
168                 {
169                         if (!strcmp(argv[i],"-nofork")) {
170                                 Config->nofork = true;
171                         }
172                         if (!strcmp(argv[i],"-wait")) {
173                                 sleep(6);
174                         }
175                         if (!strcmp(argv[i],"-nolimit")) {
176                                 Config->unlimitcore = true;
177                         }
178                 }
179         }
180
181         strlcpy(Config->MyExecutable,argv[0],MAXBUF);
182
183         this->MakeLowerMap();
184
185         OpenLog(argv, argc);
186         Config->ClearStack();
187         Config->Read(true,NULL);
188         CheckRoot();
189         this->ModeGrok = new ModeParser();
190         this->Parser = new CommandParser();
191         this->stats = new serverstats();
192         AddServerName(Config->ServerName);
193         CheckDie();
194         stats->BoundPortCount = BindPorts();
195
196         for(int t = 0; t < 255; t++)
197                 Config->global_implementation[t] = 0;
198
199         memset(&Config->implement_lists,0,sizeof(Config->implement_lists));
200
201         printf("\n");
202         SetSignals();
203         if (!Config->nofork)
204         {
205                 if (DaemonSeed() == ERROR)
206                 {
207                         printf("ERROR: could not go into daemon mode. Shutting down.\n");
208                         Exit(ERROR);
209                 }
210         }
211
212         /* Because of limitations in kqueue on freebsd, we must fork BEFORE we
213          * initialize the socket engine.
214          */
215         SE = new SocketEngine();
216
217         /* We must load the modules AFTER initializing the socket engine, now */
218
219         return;
220 }
221
222 std::string InspIRCd::GetVersionString()
223 {
224         char versiondata[MAXBUF];
225 #ifdef THREADED_DNS
226         char dnsengine[] = "multithread";
227 #else
228         char dnsengine[] = "singlethread";
229 #endif
230         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);
231         return versiondata;
232 }
233
234 char* InspIRCd::ModuleError()
235 {
236         return MODERR;
237 }
238
239 void InspIRCd::erase_factory(int j)
240 {
241         int v = 0;
242         for (std::vector<ircd_module*>::iterator t = factory.begin(); t != factory.end(); t++)
243         {
244                 if (v == j)
245                 {
246                         factory.erase(t);
247                         factory.push_back(NULL);
248                         return;
249                 }
250                 v++;
251         }
252 }
253
254 void InspIRCd::erase_module(int j)
255 {
256         int v1 = 0;
257         for (std::vector<Module*>::iterator m = modules.begin(); m!= modules.end(); m++)
258         {
259                 if (v1 == j)
260                 {
261                         delete *m;
262                         modules.erase(m);
263                         modules.push_back(NULL);
264                         break;
265                 }
266                 v1++;
267         }
268         int v2 = 0;
269         for (std::vector<std::string>::iterator v = Config->module_names.begin(); v != Config->module_names.end(); v++)
270         {
271                 if (v2 == j)
272                 {
273                        Config->module_names.erase(v);
274                        break;
275                 }
276                 v2++;
277         }
278
279 }
280
281 bool InspIRCd::UnloadModule(const char* filename)
282 {
283         std::string filename_str = filename;
284         for (unsigned int j = 0; j != Config->module_names.size(); j++)
285         {
286                 if (Config->module_names[j] == filename_str)
287                 {
288                         if (modules[j]->GetVersion().Flags & VF_STATIC)
289                         {
290                                 log(DEFAULT,"Failed to unload STATIC module %s",filename);
291                                 snprintf(MODERR,MAXBUF,"Module not unloadable (marked static)");
292                                 return false;
293                         }
294                         /* Give the module a chance to tidy out all its metadata */
295                         for (chan_hash::iterator c = chanlist.begin(); c != chanlist.end(); c++)
296                         {
297                                 modules[j]->OnCleanup(TYPE_CHANNEL,c->second);
298                         }
299                         for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
300                         {
301                                 modules[j]->OnCleanup(TYPE_USER,u->second);
302                         }
303
304                         for(int t = 0; t < 255; t++)
305                         {
306                                 Config->global_implementation[t] -= Config->implement_lists[j][t];
307                         }
308
309                         FOREACH_MOD(I_OnUnloadModule,OnUnloadModule(modules[j],Config->module_names[j]));
310                         // found the module
311                         log(DEBUG,"Deleting module...");
312                         erase_module(j);
313                         log(DEBUG,"Erasing module entry...");
314                         erase_factory(j);
315                         log(DEBUG,"Removing dependent commands...");
316                         Parser->RemoveCommands(filename);
317                         log(DEFAULT,"Module %s unloaded",filename);
318                         MODCOUNT--;
319                         return true;
320                 }
321         }
322         log(DEFAULT,"Module %s is not loaded, cannot unload it!",filename);
323         snprintf(MODERR,MAXBUF,"Module not loaded");
324         return false;
325 }
326
327 bool InspIRCd::LoadModule(const char* filename)
328 {
329         char modfile[MAXBUF];
330 #ifdef STATIC_LINK
331         snprintf(modfile,MAXBUF,"%s",filename);
332 #else
333         snprintf(modfile,MAXBUF,"%s/%s",Config->ModPath,filename);
334 #endif
335         std::string filename_str = filename;
336 #ifndef STATIC_LINK
337         if (!DirValid(modfile))
338         {
339                 log(DEFAULT,"Module %s is not within the modules directory.",modfile);
340                 snprintf(MODERR,MAXBUF,"Module %s is not within the modules directory.",modfile);
341                 return false;
342         }
343 #endif
344         log(DEBUG,"Loading module: %s",modfile);
345 #ifndef STATIC_LINK
346         if (FileExists(modfile))
347         {
348 #endif
349                 for (unsigned int j = 0; j < Config->module_names.size(); j++)
350                 {
351                         if (Config->module_names[j] == filename_str)
352                         {
353                                 log(DEFAULT,"Module %s is already loaded, cannot load a module twice!",modfile);
354                                 snprintf(MODERR,MAXBUF,"Module already loaded");
355                                 return false;
356                         }
357                 }
358                 ircd_module* a = new ircd_module(modfile);
359                 factory[MODCOUNT+1] = a;
360                 if (factory[MODCOUNT+1]->LastError())
361                 {
362                         log(DEFAULT,"Unable to load %s: %s",modfile,factory[MODCOUNT+1]->LastError());
363                         snprintf(MODERR,MAXBUF,"Loader/Linker error: %s",factory[MODCOUNT+1]->LastError());
364                         MODCOUNT--;
365                         return false;
366                 }
367                 if (factory[MODCOUNT+1]->factory)
368                 {
369                         Module* m = factory[MODCOUNT+1]->factory->CreateModule(MyServer);
370                         modules[MODCOUNT+1] = m;
371                         /* save the module and the module's classfactory, if
372                          * this isnt done, random crashes can occur :/ */
373                         Config->module_names.push_back(filename);
374
375                         char* x = &Config->implement_lists[MODCOUNT+1][0];
376                         for(int t = 0; t < 255; t++)
377                                 x[t] = 0;
378
379                         modules[MODCOUNT+1]->Implements(x);
380
381                         for(int t = 0; t < 255; t++)
382                         {
383                                 Config->global_implementation[t] += Config->implement_lists[MODCOUNT+1][t];
384                                 if (Config->implement_lists[MODCOUNT+1][t])
385                                 {
386                                         log(DEBUG,"Add global implementation: %d %d => %d",MODCOUNT+1,t,Config->global_implementation[t]);
387                                 }
388                         }
389                 }
390                 else
391                 {
392                         log(DEFAULT,"Unable to load %s",modfile);
393                         snprintf(MODERR,MAXBUF,"Factory function failed!");
394                         return false;
395                 }
396 #ifndef STATIC_LINK
397         }
398         else
399         {
400                 log(DEFAULT,"InspIRCd: startup: Module Not Found %s",modfile);
401                 snprintf(MODERR,MAXBUF,"Module file could not be found");
402                 return false;
403         }
404 #endif
405         MODCOUNT++;
406         FOREACH_MOD(I_OnLoadModule,OnLoadModule(modules[MODCOUNT],filename_str));
407         return true;
408 }
409
410 int InspIRCd::Run()
411 {
412         bool expire_run = false;
413         std::vector<int> activefds;
414         int incomingSockfd;
415         int in_port;
416         userrec* cu = NULL;
417         InspSocket* s = NULL;
418         InspSocket* s_del = NULL;
419         char* target;
420         unsigned int numberactive;
421         sockaddr_in sock_us;     // our port number
422         socklen_t uslen;         // length of our port number
423
424         /* Until THIS point, ServerInstance == NULL */
425         
426         LoadAllModules(this);
427
428         printf("\nInspIRCd is now running!\n");
429         
430         if (!Config->nofork)
431         {
432                 freopen("/dev/null","w",stdout);
433                 freopen("/dev/null","w",stderr);
434         }
435
436         /* Add the listening sockets used for client inbound connections
437          * to the socket engine
438          */
439         for (int count = 0; count < stats->BoundPortCount; count++)
440                 SE->AddFd(openSockfd[count],true,X_LISTEN);
441
442         WritePID(Config->PID);
443
444         /* main loop, this never returns */
445         for (;;)
446         {
447                 /* time() seems to be a pretty expensive syscall, so avoid calling it too much.
448                  * Once per loop iteration is pleanty.
449                  */
450                 OLDTIME = TIME;
451                 TIME = time(NULL);
452
453                 /* Run background module timers every few seconds
454                  * (the docs say modules shouldnt rely on accurate
455                  * timing using this event, so we dont have to
456                  * time this exactly).
457                  */
458                 if (((TIME % 8) == 0) && (!expire_run))
459                 {
460                         expire_lines();
461                         FOREACH_MOD(I_OnBackgroundTimer,OnBackgroundTimer(TIME));
462                         expire_run = true;
463                         continue;
464                 }
465                 if ((TIME % 8) == 1)
466                         expire_run = false;
467                 
468                 /* Once a second, do the background processing */
469                 if (TIME != OLDTIME)
470                         while (DoBackgroundUserStuff(TIME));
471
472                 /* Call the socket engine to wait on the active
473                  * file descriptors. The socket engine has everything's
474                  * descriptors in its list... dns, modules, users,
475                  * servers... so its nice and easy, just one call.
476                  */
477                 SE->Wait(activefds);
478
479                 /**
480                  * Now process each of the fd's. For users, we have a fast
481                  * lookup table which can find a user by file descriptor, so
482                  * processing them by fd isnt expensive. If we have a lot of
483                  * listening ports or module sockets though, things could get
484                  * ugly.
485                  */
486                 numberactive = activefds.size();
487                 for (unsigned int activefd = 0; activefd < numberactive; activefd++)
488                 {
489                         int socket_type = SE->GetType(activefds[activefd]);
490                         switch (socket_type)
491                         {
492                                 case X_ESTAB_CLIENT:
493
494                                         cu = fd_ref_table[activefds[activefd]];
495                                         if (cu)
496                                                 ProcessUser(cu);
497
498                                 break;
499
500                                 case X_ESTAB_MODULE:
501
502                                         /* Process module-owned sockets.
503                                          * Modules are encouraged to inherit their sockets from
504                                          * InspSocket so we can process them neatly like this.
505                                          */
506                                         s = socket_ref[activefds[activefd]];
507
508                                         if ((s) && (!s->Poll()))
509                                         {
510                                                 log(DEBUG,"Socket poll returned false, close and bail");
511                                                 SE->DelFd(s->GetFd());
512                                                 for (std::vector<InspSocket*>::iterator a = module_sockets.begin(); a < module_sockets.end(); a++)
513                                                 {
514                                                         s_del = (InspSocket*)*a;
515                                                         if ((s_del) && (s_del->GetFd() == activefds[activefd]))
516                                                         {
517                                                                 module_sockets.erase(a);
518                                                                 break;
519                                                         }
520                                                 }
521                                                 s->Close();
522                                                 delete s;
523                                         }
524
525                                 break;
526
527                                 case X_ESTAB_DNS:
528
529                                         /* When we are using single-threaded dns,
530                                          * the sockets for dns end up in our mainloop.
531                                          * When we are using multi-threaded dns,
532                                          * each thread has its own basic poll() loop
533                                          * within it, making them 'fire and forget'
534                                          * and independent of the mainloop.
535                                          */
536 #ifndef THREADED_DNS
537                                         dns_poll(activefds[activefd]);
538 #endif
539                                 break;
540                                 
541                                 case X_LISTEN:
542
543                                         /* It's a listener */
544                                         uslen = sizeof(sock_us);
545                                         length = sizeof(client);
546                                         incomingSockfd = accept (activefds[activefd],(struct sockaddr*)&client,&length);
547                                         if (!getsockname(incomingSockfd,(sockaddr*)&sock_us,&uslen))
548                                         {
549                                                 in_port = ntohs(sock_us.sin_port);
550                                                 log(DEBUG,"Accepted socket %d",incomingSockfd);
551                                                 target = (char*)inet_ntoa(client.sin_addr);
552                                                 /* Years and years ago, we used to resolve here
553                                                  * using gethostbyaddr(). That is sucky and we
554                                                  * don't do that any more...
555                                                  */
556                                                 if (incomingSockfd >= 0)
557                                                 {
558                                                         NonBlocking(incomingSockfd);
559                                                         if (Config->GetIOHook(in_port))
560                                                         {
561                                                                 Config->GetIOHook(in_port)->OnRawSocketAccept(incomingSockfd, target, in_port);
562                                                         }
563                                                         stats->statsAccept++;
564                                                         AddClient(incomingSockfd, target, in_port, false, target);
565                                                         log(DEBUG,"Adding client on port %lu fd=%lu",(unsigned long)in_port,(unsigned long)incomingSockfd);
566                                                 }
567                                                 else
568                                                 {
569                                                         WriteOpers("*** WARNING: accept() failed on port %lu (%s)",(unsigned long)in_port,target);
570                                                         log(DEBUG,"accept failed: %lu",(unsigned long)in_port);
571                                                         stats->statsRefused++;
572                                                 }
573                                         }
574                                         else
575                                         {
576                                                 log(DEBUG,"Couldnt look up the port number for fd %lu (OS BROKEN?!)",incomingSockfd);
577                                                 shutdown(incomingSockfd,2);
578                                                 close(incomingSockfd);
579                                         }
580                                 break;
581
582                                 default:
583                                         /* Something went wrong if we're in here.
584                                          * In fact, so wrong, im not quite sure
585                                          * what we would do, so for now, its going
586                                          * to safely do bugger all.
587                                          */
588                                 break;
589                         }
590                 }
591
592         }
593         /* This is never reached -- we hope! */
594         return 0;
595 }
596
597 /**********************************************************************************/
598
599 /**
600  * An ircd in four lines! bwahahaha. ahahahahaha. ahahah *cough*.
601  */
602
603 int main(int argc, char** argv)
604 {
605         ServerInstance = new InspIRCd(argc, argv);
606         ServerInstance->Run();
607         delete ServerInstance;
608         return 0;
609 }
610