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