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