]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/inspircd.cpp
Fixed typos
[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         if (!Config->nofork)
203         {
204                 if (DaemonSeed() == ERROR)
205                 {
206                         printf("ERROR: could not go into daemon mode. Shutting down.\n");
207                         Exit(ERROR);
208                 }
209         }
210
211         /* Because of limitations in kqueue on freebsd, we must fork BEFORE we
212          * initialize the socket engine.
213          */
214         SE = new SocketEngine();
215
216         /* We must load the modules AFTER initializing the socket engine, now */
217
218         return;
219 }
220
221 std::string InspIRCd::GetVersionString()
222 {
223         char versiondata[MAXBUF];
224 #ifdef THREADED_DNS
225         char dnsengine[] = "multithread";
226 #else
227         char dnsengine[] = "singlethread";
228 #endif
229         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);
230         return versiondata;
231 }
232
233 char* InspIRCd::ModuleError()
234 {
235         return MODERR;
236 }
237
238 void InspIRCd::erase_factory(int j)
239 {
240         int v = 0;
241         for (std::vector<ircd_module*>::iterator t = factory.begin(); t != factory.end(); t++)
242         {
243                 if (v == j)
244                 {
245                         factory.erase(t);
246                         factory.push_back(NULL);
247                         return;
248                 }
249                 v++;
250         }
251 }
252
253 void InspIRCd::erase_module(int j)
254 {
255         int v1 = 0;
256         for (std::vector<Module*>::iterator m = modules.begin(); m!= modules.end(); m++)
257         {
258                 if (v1 == j)
259                 {
260                         delete *m;
261                         modules.erase(m);
262                         modules.push_back(NULL);
263                         break;
264                 }
265                 v1++;
266         }
267         int v2 = 0;
268         for (std::vector<std::string>::iterator v = Config->module_names.begin(); v != Config->module_names.end(); v++)
269         {
270                 if (v2 == j)
271                 {
272                        Config->module_names.erase(v);
273                        break;
274                 }
275                 v2++;
276         }
277
278 }
279
280 bool InspIRCd::UnloadModule(const char* filename)
281 {
282         std::string filename_str = filename;
283         for (unsigned int j = 0; j != Config->module_names.size(); j++)
284         {
285                 if (Config->module_names[j] == filename_str)
286                 {
287                         if (modules[j]->GetVersion().Flags & VF_STATIC)
288                         {
289                                 log(DEFAULT,"Failed to unload STATIC module %s",filename);
290                                 snprintf(MODERR,MAXBUF,"Module not unloadable (marked static)");
291                                 return false;
292                         }
293                         /* Give the module a chance to tidy out all its metadata */
294                         for (chan_hash::iterator c = chanlist.begin(); c != chanlist.end(); c++)
295                         {
296                                 modules[j]->OnCleanup(TYPE_CHANNEL,c->second);
297                         }
298                         for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
299                         {
300                                 modules[j]->OnCleanup(TYPE_USER,u->second);
301                         }
302
303                         for(int t = 0; t < 255; t++)
304                         {
305                                 Config->global_implementation[t] -= Config->implement_lists[j][t];
306                         }
307
308                         FOREACH_MOD(I_OnUnloadModule,OnUnloadModule(modules[j],Config->module_names[j]));
309                         // found the module
310                         log(DEBUG,"Deleting module...");
311                         erase_module(j);
312                         log(DEBUG,"Erasing module entry...");
313                         erase_factory(j);
314                         log(DEBUG,"Removing dependent commands...");
315                         Parser->RemoveCommands(filename);
316                         log(DEFAULT,"Module %s unloaded",filename);
317                         MODCOUNT--;
318                         return true;
319                 }
320         }
321         log(DEFAULT,"Module %s is not loaded, cannot unload it!",filename);
322         snprintf(MODERR,MAXBUF,"Module not loaded");
323         return false;
324 }
325
326 bool InspIRCd::LoadModule(const char* filename)
327 {
328         char modfile[MAXBUF];
329 #ifdef STATIC_LINK
330         snprintf(modfile,MAXBUF,"%s",filename);
331 #else
332         snprintf(modfile,MAXBUF,"%s/%s",Config->ModPath,filename);
333 #endif
334         std::string filename_str = filename;
335 #ifndef STATIC_LINK
336         if (!DirValid(modfile))
337         {
338                 log(DEFAULT,"Module %s is not within the modules directory.",modfile);
339                 snprintf(MODERR,MAXBUF,"Module %s is not within the modules directory.",modfile);
340                 return false;
341         }
342 #endif
343         log(DEBUG,"Loading module: %s",modfile);
344 #ifndef STATIC_LINK
345         if (FileExists(modfile))
346         {
347 #endif
348                 for (unsigned int j = 0; j < Config->module_names.size(); j++)
349                 {
350                         if (Config->module_names[j] == filename_str)
351                         {
352                                 log(DEFAULT,"Module %s is already loaded, cannot load a module twice!",modfile);
353                                 snprintf(MODERR,MAXBUF,"Module already loaded");
354                                 return false;
355                         }
356                 }
357                 ircd_module* a = new ircd_module(modfile);
358                 factory[MODCOUNT+1] = a;
359                 if (factory[MODCOUNT+1]->LastError())
360                 {
361                         log(DEFAULT,"Unable to load %s: %s",modfile,factory[MODCOUNT+1]->LastError());
362                         snprintf(MODERR,MAXBUF,"Loader/Linker error: %s",factory[MODCOUNT+1]->LastError());
363                         MODCOUNT--;
364                         return false;
365                 }
366                 if (factory[MODCOUNT+1]->factory)
367                 {
368                         Module* m = factory[MODCOUNT+1]->factory->CreateModule(MyServer);
369                         modules[MODCOUNT+1] = m;
370                         /* save the module and the module's classfactory, if
371                          * this isnt done, random crashes can occur :/ */
372                         Config->module_names.push_back(filename);
373
374                         char* x = &Config->implement_lists[MODCOUNT+1][0];
375                         for(int t = 0; t < 255; t++)
376                                 x[t] = 0;
377
378                         modules[MODCOUNT+1]->Implements(x);
379
380                         for(int t = 0; t < 255; t++)
381                         {
382                                 Config->global_implementation[t] += Config->implement_lists[MODCOUNT+1][t];
383                                 if (Config->implement_lists[MODCOUNT+1][t])
384                                 {
385                                         log(DEBUG,"Add global implementation: %d %d => %d",MODCOUNT+1,t,Config->global_implementation[t]);
386                                 }
387                         }
388                 }
389                 else
390                 {
391                         log(DEFAULT,"Unable to load %s",modfile);
392                         snprintf(MODERR,MAXBUF,"Factory function failed!");
393                         return false;
394                 }
395 #ifndef STATIC_LINK
396         }
397         else
398         {
399                 log(DEFAULT,"InspIRCd: startup: Module Not Found %s",modfile);
400                 snprintf(MODERR,MAXBUF,"Module file could not be found");
401                 return false;
402         }
403 #endif
404         MODCOUNT++;
405         FOREACH_MOD(I_OnLoadModule,OnLoadModule(modules[MODCOUNT],filename_str));
406         return true;
407 }
408
409 int InspIRCd::Run()
410 {
411         bool expire_run = false;
412         std::vector<int> activefds;
413         int incomingSockfd;
414         int in_port;
415         userrec* cu = NULL;
416         InspSocket* s = NULL;
417         InspSocket* s_del = NULL;
418         char* target;
419         unsigned int numberactive;
420         sockaddr_in sock_us;     // our port number
421         socklen_t uslen;         // length of our port number
422
423         /* Until THIS point, ServerInstance == NULL */
424         
425         LoadAllModules(this);
426
427         printf("\nInspIRCd is now running!\n");
428         
429         if (!Config->nofork)
430         {
431                 freopen("/dev/null","w",stdout);
432                 freopen("/dev/null","w",stderr);
433         }
434
435         /* Add the listening sockets used for client inbound connections
436          * to the socket engine
437          */
438         for (int count = 0; count < stats->BoundPortCount; count++)
439                 SE->AddFd(openSockfd[count],true,X_LISTEN);
440
441         WritePID(Config->PID);
442
443         /* main loop, this never returns */
444         for (;;)
445         {
446                 /* time() seems to be a pretty expensive syscall, so avoid calling it too much.
447                  * Once per loop iteration is pleanty.
448                  */
449                 OLDTIME = TIME;
450                 TIME = time(NULL);
451
452                 /* Run background module timers every few seconds
453                  * (the docs say modules shouldnt rely on accurate
454                  * timing using this event, so we dont have to
455                  * time this exactly).
456                  */
457                 if (((TIME % 8) == 0) && (!expire_run))
458                 {
459                         expire_lines();
460                         FOREACH_MOD(I_OnBackgroundTimer,OnBackgroundTimer(TIME));
461                         expire_run = true;
462                         continue;
463                 }
464                 if ((TIME % 8) == 1)
465                         expire_run = false;
466                 
467                 /* Once a second, do the background processing */
468                 if (TIME != OLDTIME)
469                         while (DoBackgroundUserStuff(TIME));
470
471                 /* Call the socket engine to wait on the active
472                  * file descriptors. The socket engine has everything's
473                  * descriptors in its list... dns, modules, users,
474                  * servers... so its nice and easy, just one call.
475                  */
476                 SE->Wait(activefds);
477
478                 /**
479                  * Now process each of the fd's. For users, we have a fast
480                  * lookup table which can find a user by file descriptor, so
481                  * processing them by fd isnt expensive. If we have a lot of
482                  * listening ports or module sockets though, things could get
483                  * ugly.
484                  */
485                 numberactive = activefds.size();
486                 for (unsigned int activefd = 0; activefd < numberactive; activefd++)
487                 {
488                         int socket_type = SE->GetType(activefds[activefd]);
489                         switch (socket_type)
490                         {
491                                 case X_ESTAB_CLIENT:
492
493                                         cu = fd_ref_table[activefds[activefd]];
494                                         if (cu)
495                                                 ProcessUser(cu);
496
497                                 break;
498
499                                 case X_ESTAB_MODULE:
500
501                                         /* Process module-owned sockets.
502                                          * Modules are encouraged to inherit their sockets from
503                                          * InspSocket so we can process them neatly like this.
504                                          */
505                                         s = socket_ref[activefds[activefd]];
506
507                                         if ((s) && (!s->Poll()))
508                                         {
509                                                 log(DEBUG,"Socket poll returned false, close and bail");
510                                                 SE->DelFd(s->GetFd());
511                                                 for (std::vector<InspSocket*>::iterator a = module_sockets.begin(); a < module_sockets.end(); a++)
512                                                 {
513                                                         s_del = (InspSocket*)*a;
514                                                         if ((s_del) && (s_del->GetFd() == activefds[activefd]))
515                                                         {
516                                                                 module_sockets.erase(a);
517                                                                 break;
518                                                         }
519                                                 }
520                                                 s->Close();
521                                                 delete s;
522                                         }
523
524                                 break;
525
526                                 case X_ESTAB_DNS:
527
528                                         /* When we are using single-threaded dns,
529                                          * the sockets for dns end up in our mainloop.
530                                          * When we are using multi-threaded dns,
531                                          * each thread has its own basic poll() loop
532                                          * within it, making them 'fire and forget'
533                                          * and independent of the mainloop.
534                                          */
535 #ifndef THREADED_DNS
536                                         dns_poll(activefds[activefd]);
537 #endif
538                                 break;
539                                 
540                                 case X_LISTEN:
541
542                                         /* It's a listener */
543                                         uslen = sizeof(sock_us);
544                                         length = sizeof(client);
545                                         incomingSockfd = accept (activefds[activefd],(struct sockaddr*)&client,&length);
546                                         if (!getsockname(incomingSockfd,(sockaddr*)&sock_us,&uslen))
547                                         {
548                                                 in_port = ntohs(sock_us.sin_port);
549                                                 log(DEBUG,"Accepted socket %d",incomingSockfd);
550                                                 target = (char*)inet_ntoa(client.sin_addr);
551                                                 /* Years and years ago, we used to resolve here
552                                                  * using gethostbyaddr(). That is sucky and we
553                                                  * don't do that any more...
554                                                  */
555                                                 if (incomingSockfd >= 0)
556                                                 {
557                                                         NonBlocking(incomingSockfd);
558                                                         if (Config->GetIOHook(in_port))
559                                                         {
560                                                                 Config->GetIOHook(in_port)->OnRawSocketAccept(incomingSockfd, target, in_port);
561                                                         }
562                                                         stats->statsAccept++;
563                                                         AddClient(incomingSockfd, target, in_port, false, target);
564                                                         log(DEBUG,"Adding client on port %lu fd=%lu",(unsigned long)in_port,(unsigned long)incomingSockfd);
565                                                 }
566                                                 else
567                                                 {
568                                                         WriteOpers("*** WARNING: accept() failed on port %lu (%s)",(unsigned long)in_port,target);
569                                                         log(DEBUG,"accept failed: %lu",(unsigned long)in_port);
570                                                         stats->statsRefused++;
571                                                 }
572                                         }
573                                         else
574                                         {
575                                                 log(DEBUG,"Couldnt look up the port number for fd %lu (OS BROKEN?!)",incomingSockfd);
576                                                 shutdown(incomingSockfd,2);
577                                                 close(incomingSockfd);
578                                         }
579                                 break;
580
581                                 default:
582                                         /* Something went wrong if we're in here.
583                                          * In fact, so wrong, im not quite sure
584                                          * what we would do, so for now, its going
585                                          * to safely do bugger all.
586                                          */
587                                 break;
588                         }
589                 }
590
591         }
592         /* This is never reached -- we hope! */
593         return 0;
594 }
595
596 /**********************************************************************************/
597
598 /**
599  * An ircd in four lines! bwahahaha. ahahahahaha. ahahah *cough*.
600  */
601
602 int main(int argc, char** argv)
603 {
604         ServerInstance = new InspIRCd(argc, argv);
605         ServerInstance->Run();
606         delete ServerInstance;
607         return 0;
608 }
609