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