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