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