]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/inspircd.cpp
Cache channel max bans value to save an O(n) loop of match() on every ban (etc) add
[user/henk/code/inspircd.git] / src / inspircd.cpp
1 /*       +------------------------------------+
2  *       | Inspire Internet Relay Chat Daemon |
3  *       +------------------------------------+
4  *
5  *  InspIRCd: (C) 2002-2007 InspIRCd Development Team
6  * See: http://www.inspircd.org/wiki/index.php/Credits
7  *
8  * This program is free but copyrighted software; see
9  *            the file COPYING for details.
10  *
11  * ---------------------------------------------------
12  */
13
14 #include "inspircd.h"
15 #include "configreader.h"
16 #include <signal.h>
17 #include <dirent.h>
18 #include <exception>
19 #include <fstream>
20 #include <unistd.h>
21 #include "modules.h"
22 #include "mode.h"
23 #include "xline.h"
24 #include "socketengine.h"
25 #include "inspircd_se_config.h"
26 #include "socket.h"
27 #include "typedefs.h"
28 #include "command_parse.h"
29 #include "exitcodes.h"
30 #include <dlfcn.h>
31 #include <getopt.h>
32
33
34 using irc::sockets::NonBlocking;
35 using irc::sockets::Blocking;
36 using irc::sockets::insp_ntoa;
37 using irc::sockets::insp_inaddr;
38 using irc::sockets::insp_sockaddr;
39
40 InspIRCd* SI = NULL;
41
42 void InspIRCd::AddServerName(const std::string &servername)
43 {
44         this->Log(DEBUG,"Adding server name: %s",servername.c_str());
45         
46         if(find(servernames.begin(), servernames.end(), servername) == servernames.end())
47                 servernames.push_back(servername); /* Wasn't already there. */
48 }
49
50 const char* InspIRCd::FindServerNamePtr(const std::string &servername)
51 {
52         servernamelist::iterator iter = find(servernames.begin(), servernames.end(), servername);
53         
54         if(iter == servernames.end())
55         {               
56                 AddServerName(servername);
57                 iter = --servernames.end();
58         }
59
60         return iter->c_str();
61 }
62
63 bool InspIRCd::FindServerName(const std::string &servername)
64 {
65         return (find(servernames.begin(), servernames.end(), servername) != servernames.end());
66 }
67
68 void InspIRCd::Exit(int status)
69 {
70         if (SI)
71         {
72                 SI->SendError("Exiting with status " + ConvToStr(status) + " (" + std::string(ExitCodes[status]) + ")");
73                 SI->Cleanup();
74         }
75         exit (status);
76 }
77
78 void InspIRCd::Cleanup()
79 {
80         std::vector<std::string> mymodnames;
81         int MyModCount = this->GetModuleCount();
82
83         for (unsigned int i = 0; i < stats->BoundPortCount; i++)
84         {
85                 /* This calls the constructor and closes the listening socket */
86                 delete Config->openSockfd[i];
87                 Config->openSockfd[i] = NULL;
88         }
89         stats->BoundPortCount = 0;
90
91         /* We do this more than once, so that any service providers get a
92          * chance to be unhooked by the modules using them, but then get
93          * a chance to be removed themsleves.
94          */
95         for (int tries = 0; tries < 3; tries++)
96         {
97                 MyModCount = this->GetModuleCount();
98                 mymodnames.clear();
99
100                 /* Unload all modules, so they get a chance to clean up their listeners */
101                 for (int j = 0; j <= MyModCount; j++)
102                         mymodnames.push_back(Config->module_names[j]);
103
104                 for (int k = 0; k <= MyModCount; k++)
105                         this->UnloadModule(mymodnames[k].c_str());
106         }
107
108         /* Close all client sockets, or the new process inherits them */
109         for (std::vector<userrec*>::const_iterator i = this->local_users.begin(); i != this->local_users.end(); i++)
110                 (*i)->CloseSocket();
111
112         /* Close logging */
113         this->Logger->Close();
114 }
115
116 void InspIRCd::Restart(const std::string &reason)
117 {
118         /* SendError flushes each client's queue,
119          * regardless of writeability state
120          */
121         this->SendError(reason);
122
123         this->Cleanup();
124
125         /* Figure out our filename (if theyve renamed it, we're boned) */
126         std::string me = Config->MyDir + "/inspircd";
127
128         if (execv(me.c_str(), Config->argv) == -1)
129         {
130                 /* Will raise a SIGABRT if not trapped */
131                 throw CoreException(std::string("Failed to execv()! error: ") + strerror(errno));
132         }
133 }
134
135 void InspIRCd::Start()
136 {
137         printf("\033[1;32mInspire Internet Relay Chat Server, compiled %s at %s\n",__DATE__,__TIME__);
138         printf("(C) InspIRCd Development Team.\033[0m\n\n");
139         printf("Developers:\t\t\033[1;32mBrain, FrostyCoolSlug, w00t, Om, Special, pippijn, peavey\033[0m\n");
140         printf("Others:\t\t\t\033[1;32mSee /INFO Output\033[0m\n");
141 }
142
143 void InspIRCd::Rehash(int status)
144 {
145         SI->WriteOpers("Rehashing config file %s due to SIGHUP",ServerConfig::CleanFilename(CONFIG_FILE));
146         SI->CloseLog();
147         SI->OpenLog(SI->Config->argv, SI->Config->argc);
148         SI->RehashUsersAndChans();
149         FOREACH_MOD_I(SI, I_OnGarbageCollect, OnGarbageCollect());
150         SI->Config->Read(false,NULL);
151         SI->ResetMaxBans();
152         SI->Res->Rehash();
153         FOREACH_MOD_I(SI,I_OnRehash,OnRehash(NULL,""));
154 }
155
156 void InspIRCd::ResetMaxBans()
157 {
158         for (chan_hash::const_iterator i = chanlist->begin(); i != chanlist->end(); i++)
159                 i->second->ResetMaxBans();
160 }
161
162
163 /** Because hash_map doesnt free its buckets when we delete items (this is a 'feature')
164  * we must occasionally rehash the hash (yes really).
165  * We do this by copying the entries from the old hash to a new hash, causing all
166  * empty buckets to be weeded out of the hash. We dont do this on a timer, as its
167  * very expensive, so instead we do it when the user types /REHASH and expects a
168  * short delay anyway.
169  */
170 void InspIRCd::RehashUsersAndChans()
171 {
172         user_hash* old_users = this->clientlist;
173         chan_hash* old_chans = this->chanlist;
174
175         this->clientlist = new user_hash();
176         this->chanlist = new chan_hash();
177
178         for (user_hash::const_iterator n = old_users->begin(); n != old_users->end(); n++)
179                 this->clientlist->insert(*n);
180
181         delete old_users;
182
183         for (chan_hash::const_iterator n = old_chans->begin(); n != old_chans->end(); n++)
184                 this->chanlist->insert(*n);
185
186         delete old_chans;
187 }
188
189 void InspIRCd::CloseLog()
190 {
191         this->Logger->Close();
192 }
193
194 void InspIRCd::SetSignals()
195 {
196         signal(SIGALRM, SIG_IGN);
197         signal(SIGHUP, InspIRCd::Rehash);
198         signal(SIGPIPE, SIG_IGN);
199         signal(SIGTERM, InspIRCd::Exit);
200         signal(SIGCHLD, SIG_IGN);
201 }
202
203 bool InspIRCd::DaemonSeed()
204 {
205         int childpid;
206         if ((childpid = fork ()) < 0)
207                 return false;
208         else if (childpid > 0)
209         {
210                 /* We wait here for the child process to kill us,
211                  * so that the shell prompt doesnt come back over
212                  * the output.
213                  * Sending a kill with a signal of 0 just checks
214                  * if the child pid is still around. If theyre not,
215                  * they threw an error and we should give up.
216                  */
217                 while (kill(childpid, 0) != -1)
218                         sleep(1);
219                 exit(0);
220         }
221         setsid ();
222         umask (007);
223         printf("InspIRCd Process ID: \033[1;32m%lu\033[0m\n",(unsigned long)getpid());
224
225         rlimit rl;
226         if (getrlimit(RLIMIT_CORE, &rl) == -1)
227         {
228                 this->Log(DEFAULT,"Failed to getrlimit()!");
229                 return false;
230         }
231         else
232         {
233                 rl.rlim_cur = rl.rlim_max;
234                 if (setrlimit(RLIMIT_CORE, &rl) == -1)
235                         this->Log(DEFAULT,"setrlimit() failed, cannot increase coredump size.");
236         }
237
238         return true;
239 }
240
241 void InspIRCd::WritePID(const std::string &filename)
242 {
243         std::string fname = (filename.empty() ? "inspircd.pid" : filename);
244         if (*(fname.begin()) != '/')
245         {
246                 std::string::size_type pos;
247                 std::string confpath = CONFIG_FILE;
248                 if ((pos = confpath.find("/inspircd.conf")) != std::string::npos)
249                 {
250                         /* Leaves us with just the path */
251                         fname = confpath.substr(0, pos) + std::string("/") + fname;
252                 }
253         }                                                                       
254         std::ofstream outfile(fname.c_str());
255         if (outfile.is_open())
256         {
257                 outfile << getpid();
258                 outfile.close();
259         }
260         else
261         {
262                 printf("Failed to write PID-file '%s', exiting.\n",fname.c_str());
263                 this->Log(DEFAULT,"Failed to write PID-file '%s', exiting.",fname.c_str());
264                 Exit(EXIT_STATUS_PID);
265         }
266 }
267
268 std::string InspIRCd::GetRevision()
269 {
270         return REVISION;
271 }
272
273 InspIRCd::InspIRCd(int argc, char** argv)
274         : ModCount(-1), duration_m(60), duration_h(60*60), duration_d(60*60*24), duration_w(60*60*24*7), duration_y(60*60*24*365)
275 {
276         int found_ports = 0;
277         FailedPortList pl;
278         int do_nofork = 0, do_debug = 0, do_nolog = 0;    /* flag variables */
279         char c = 0;
280
281         modules.resize(255);
282         factory.resize(255);
283
284         this->unregistered_count = 0;
285
286         this->clientlist = new user_hash();
287         this->chanlist = new chan_hash();
288
289         this->Config = new ServerConfig(this);
290
291         this->Config->argv = argv;
292         this->Config->argc = argc;
293
294         this->Config->opertypes.clear();
295         this->Config->operclass.clear();
296         this->SNO = new SnomaskManager(this);
297         this->Start();
298         this->TIME = this->OLDTIME = this->startup_time = time(NULL);
299         this->time_delta = 0;
300         this->next_call = this->TIME + 3;
301         srand(this->TIME);
302
303         if (!ServerConfig::FileExists(CONFIG_FILE))
304         {
305                 printf("ERROR: Cannot open config file: %s\nExiting...\n",CONFIG_FILE);
306                 this->Log(DEFAULT,"main: no config");
307                 printf("ERROR: Your config file is missing, this IRCd will self destruct in 10 seconds!\n");
308                 Exit(EXIT_STATUS_CONFIG);
309         }
310
311         *this->LogFileName = 0;
312
313         struct option longopts[] =
314         {
315                 { "nofork",     no_argument,            &do_nofork,     1       },
316                 { "logfile",    required_argument,      NULL,           'f'     },
317                 { "debug",      no_argument,            &do_debug,      1       },
318                 { "nolog",      no_argument,            &do_nolog,      1       },
319                 { 0, 0, 0, 0 }
320         };
321
322         while ((c = getopt_long_only(argc, argv, ":f:", longopts, NULL)) != -1)
323         {
324                 switch (c)
325                 {
326                         case 'f':
327                                 /* Log filename was set */
328                                 strlcpy(LogFileName, optarg, MAXBUF);
329                                 printf("LOG: Setting logfile to %s\n", LogFileName);
330                         break;
331                         case 0:
332                                 /* getopt_long_only() set an int variable, just keep going */
333                         break;
334                         default:
335                                 /* Unknown parameter! DANGER, INTRUDER.... err.... yeah. */
336                                 printf("Usage: %s [--nofork] [--nolog] [--debug] [--logfile <filename>]\n", argv[0]);
337                                 Exit(EXIT_STATUS_ARGV);
338                         break;
339                 }
340         }
341
342         /* Set the finished argument values */
343         Config->nofork = do_nofork;
344         Config->forcedebug = do_debug;
345         Config->writelog = !do_nolog;
346
347         strlcpy(Config->MyExecutable,argv[0],MAXBUF);
348
349         this->OpenLog(argv, argc);
350         this->stats = new serverstats();
351         this->Timers = new TimerManager();
352         this->Parser = new CommandParser(this);
353         this->XLines = new XLineManager(this);
354         Config->ClearStack();
355         Config->Read(true, NULL);
356         this->CheckRoot();
357         this->Modes = new ModeParser(this);
358         this->AddServerName(Config->ServerName);        
359         CheckDie();
360         InitializeDisabledCommands(Config->DisabledCommands, this);
361         stats->BoundPortCount = BindPorts(true, found_ports, pl);
362
363         for(int t = 0; t < 255; t++)
364                 Config->global_implementation[t] = 0;
365
366         memset(&Config->implement_lists,0,sizeof(Config->implement_lists));
367
368         printf("\n");
369         this->SetSignals();
370         if (!Config->nofork)
371         {
372                 if (!this->DaemonSeed())
373                 {
374                         printf("ERROR: could not go into daemon mode. Shutting down.\n");
375                         Exit(EXIT_STATUS_FORK);
376                 }
377         }
378
379         /* Because of limitations in kqueue on freebsd, we must fork BEFORE we
380          * initialize the socket engine.
381          */
382         SocketEngineFactory* SEF = new SocketEngineFactory();
383         SE = SEF->Create(this);
384         delete SEF;
385
386         this->Res = new DNS(this);
387
388         this->LoadAllModules();
389         /* Just in case no modules were loaded - fix for bug #101 */
390         this->BuildISupport();
391
392         if ((stats->BoundPortCount == 0) && (found_ports > 0))
393         {
394                 printf("\nERROR: I couldn't bind any ports! Are you sure you didn't start InspIRCd twice?\n");
395                 Exit(EXIT_STATUS_BIND);
396         }
397         
398         if (stats->BoundPortCount != (unsigned int)found_ports)
399         {
400                 printf("\nWARNING: Not all your client ports could be bound --\nstarting anyway with %ld of %d client ports bound.\n\n", stats->BoundPortCount, found_ports);
401                 printf("The following port%s failed to bind:\n", found_ports - stats->BoundPortCount != 1 ? "s" : "");
402                 int j = 1;
403                 for (FailedPortList::iterator i = pl.begin(); i != pl.end(); i++, j++)
404                 {
405                         printf("%d.\tIP: %s\tPort: %lu\n", j, i->first.empty() ? "<all>" : i->first.c_str(), (unsigned long)i->second);
406                 }
407         }
408
409         /* Add the listening sockets used for client inbound connections
410          * to the socket engine
411          */
412         this->Log(DEBUG,"%d listeners",stats->BoundPortCount);
413         for (unsigned long count = 0; count < stats->BoundPortCount; count++)
414         {
415                 this->Log(DEBUG,"Add listener: %d",Config->openSockfd[count]->GetFd());
416                 if (!SE->AddFd(Config->openSockfd[count]))
417                 {
418                         printf("\nEH? Could not add listener to socketengine. You screwed up, aborting.\n");
419                         Exit(EXIT_STATUS_INTERNAL);
420                 }
421         }
422
423         if (!Config->nofork)
424         {
425                 if (kill(getppid(), SIGTERM) == -1)
426                         printf("Error killing parent process: %s\n",strerror(errno));
427                 fclose(stdin);
428                 fclose(stderr);
429                 fclose(stdout);
430         }
431
432         printf("\nInspIRCd is now running!\n");
433
434         this->WritePID(Config->PID);
435 }
436
437 std::string InspIRCd::GetVersionString()
438 {
439         char versiondata[MAXBUF];
440         char dnsengine[] = "singlethread-object";
441         if (*Config->CustomVersion)
442         {
443                 snprintf(versiondata,MAXBUF,"%s %s :%s",VERSION,Config->ServerName,Config->CustomVersion);
444         }
445         else
446         {
447                 snprintf(versiondata,MAXBUF,"%s %s :%s [FLAGS=%lu,%s,%s]",VERSION,Config->ServerName,SYSTEM,(unsigned long)OPTIMISATION,SE->GetName().c_str(),dnsengine);
448         }
449         return versiondata;
450 }
451
452 char* InspIRCd::ModuleError()
453 {
454         return MODERR;
455 }
456
457 void InspIRCd::EraseFactory(int j)
458 {
459         int v = 0;
460         for (std::vector<ircd_module*>::iterator t = factory.begin(); t != factory.end(); t++)
461         {
462                 if (v == j)
463                 {
464                         delete *t;
465                         factory.erase(t);
466                         factory.push_back(NULL);
467                         return;
468                 }
469                 v++;
470         }
471 }
472
473 void InspIRCd::EraseModule(int j)
474 {
475         int v1 = 0;
476         for (ModuleList::iterator m = modules.begin(); m!= modules.end(); m++)
477         {
478                 if (v1 == j)
479                 {
480                         DELETE(*m);
481                         modules.erase(m);
482                         modules.push_back(NULL);
483                         break;
484                 }
485                 v1++;
486         }
487         int v2 = 0;
488         for (std::vector<std::string>::iterator v = Config->module_names.begin(); v != Config->module_names.end(); v++)
489         {
490                 if (v2 == j)
491                 {
492                        Config->module_names.erase(v);
493                        break;
494                 }
495                 v2++;
496         }
497
498 }
499
500 void InspIRCd::MoveTo(std::string modulename,int slot)
501 {
502         unsigned int v2 = 256;
503         for (unsigned int v = 0; v < Config->module_names.size(); v++)
504         {
505                 if (Config->module_names[v] == modulename)
506                 {
507                         // found an instance, swap it with the item at the end
508                         v2 = v;
509                         break;
510                 }
511         }
512         if ((v2 != (unsigned int)slot) && (v2 < 256))
513         {
514                 // Swap the module names over
515                 Config->module_names[v2] = Config->module_names[slot];
516                 Config->module_names[slot] = modulename;
517                 // now swap the module factories
518                 ircd_module* temp = factory[v2];
519                 factory[v2] = factory[slot];
520                 factory[slot] = temp;
521                 // now swap the module objects
522                 Module* temp_module = modules[v2];
523                 modules[v2] = modules[slot];
524                 modules[slot] = temp_module;
525                 // now swap the implement lists (we dont
526                 // need to swap the global or recount it)
527                 for (int n = 0; n < 255; n++)
528                 {
529                         char x = Config->implement_lists[v2][n];
530                         Config->implement_lists[v2][n] = Config->implement_lists[slot][n];
531                         Config->implement_lists[slot][n] = x;
532                 }
533         }
534         else
535         {
536                 this->Log(DEBUG,"Move of %s to slot failed!",modulename.c_str());
537         }
538 }
539
540 void InspIRCd::MoveAfter(std::string modulename, std::string after)
541 {
542         for (unsigned int v = 0; v < Config->module_names.size(); v++)
543         {
544                 if (Config->module_names[v] == after)
545                 {
546                         MoveTo(modulename, v);
547                         return;
548                 }
549         }
550 }
551
552 void InspIRCd::MoveBefore(std::string modulename, std::string before)
553 {
554         for (unsigned int v = 0; v < Config->module_names.size(); v++)
555         {
556                 if (Config->module_names[v] == before)
557                 {
558                         if (v > 0)
559                         {
560                                 MoveTo(modulename, v-1);
561                         }
562                         else
563                         {
564                                 MoveTo(modulename, v);
565                         }
566                         return;
567                 }
568         }
569 }
570
571 void InspIRCd::MoveToFirst(std::string modulename)
572 {
573         MoveTo(modulename,0);
574 }
575
576 void InspIRCd::MoveToLast(std::string modulename)
577 {
578         MoveTo(modulename,this->GetModuleCount());
579 }
580
581 void InspIRCd::BuildISupport()
582 {
583         // the neatest way to construct the initial 005 numeric, considering the number of configure constants to go in it...
584         std::stringstream v;
585         v << "WALLCHOPS WALLVOICES MODES=" << MAXMODES << " CHANTYPES=# PREFIX=" << this->Modes->BuildPrefixes() << " MAP MAXCHANNELS=" << MAXCHANS << " MAXBANS=60 VBANLIST NICKLEN=" << NICKMAX-1;
586         v << " CASEMAPPING=rfc1459 STATUSMSG=@%+ CHARSET=ascii TOPICLEN=" << MAXTOPIC << " KICKLEN=" << MAXKICK << " MAXTARGETS=" << Config->MaxTargets << " AWAYLEN=";
587         v << MAXAWAY << " CHANMODES=" << this->Modes->ChanModes() << " FNC NETWORK=" << Config->Network << " MAXPARA=32";
588         Config->data005 = v.str();
589         FOREACH_MOD_I(this,I_On005Numeric,On005Numeric(Config->data005));
590         Config->Update005();
591 }
592
593 bool InspIRCd::UnloadModule(const char* filename)
594 {
595         std::string filename_str = filename;
596         for (unsigned int j = 0; j != Config->module_names.size(); j++)
597         {
598                 if (Config->module_names[j] == filename_str)
599                 {
600                         if (modules[j]->GetVersion().Flags & VF_STATIC)
601                         {
602                                 this->Log(DEFAULT,"Failed to unload STATIC module %s",filename);
603                                 snprintf(MODERR,MAXBUF,"Module not unloadable (marked static)");
604                                 return false;
605                         }
606                         std::pair<int,std::string> intercount = GetInterfaceInstanceCount(modules[j]);
607                         if (intercount.first > 0)
608                         {
609                                 this->Log(DEFAULT,"Failed to unload module %s, being used by %d other(s) via interface '%s'",filename, intercount.first, intercount.second.c_str());
610                                 snprintf(MODERR,MAXBUF,"Module not unloadable (Still in use by %d other module%s which %s using its interface '%s') -- unload dependent modules first!",
611                                                 intercount.first,
612                                                 intercount.first > 1 ? "s" : "",
613                                                 intercount.first > 1 ? "are" : "is",
614                                                 intercount.second.c_str());
615                                 return false;
616                         }
617                         /* Give the module a chance to tidy out all its metadata */
618                         for (chan_hash::iterator c = this->chanlist->begin(); c != this->chanlist->end(); c++)
619                         {
620                                 modules[j]->OnCleanup(TYPE_CHANNEL,c->second);
621                         }
622                         for (user_hash::iterator u = this->clientlist->begin(); u != this->clientlist->end(); u++)
623                         {
624                                 modules[j]->OnCleanup(TYPE_USER,u->second);
625                         }
626
627                         /* Tidy up any dangling resolvers */
628                         this->Res->CleanResolvers(modules[j]);
629
630                         FOREACH_MOD_I(this,I_OnUnloadModule,OnUnloadModule(modules[j],Config->module_names[j]));
631
632                         for(int t = 0; t < 255; t++)
633                         {
634                                 Config->global_implementation[t] -= Config->implement_lists[j][t];
635                         }
636
637                         /* We have to renumber implement_lists after unload because the module numbers change!
638                          */
639                         for(int j2 = j; j2 < 254; j2++)
640                         {
641                                 for(int t = 0; t < 255; t++)
642                                 {
643                                         Config->implement_lists[j2][t] = Config->implement_lists[j2+1][t];
644                                 }
645                         }
646
647                         // found the module
648                         Parser->RemoveCommands(filename);
649                         this->EraseModule(j);
650                         this->EraseFactory(j);
651                         this->Log(DEFAULT,"Module %s unloaded",filename);
652                         this->ModCount--;
653                         BuildISupport();
654                         return true;
655                 }
656         }
657         this->Log(DEFAULT,"Module %s is not loaded, cannot unload it!",filename);
658         snprintf(MODERR,MAXBUF,"Module not loaded");
659         return false;
660 }
661
662 bool InspIRCd::LoadModule(const char* filename)
663 {
664         /* Do we have a glob pattern in the filename?
665          * The user wants to load multiple modules which
666          * match the pattern.
667          */
668         if (strchr(filename,'*') || (strchr(filename,'?')))
669         {
670                 int n_match = 0;
671                 DIR* library = opendir(Config->ModPath);
672                 if (library)
673                 {
674                         /* Try and locate and load all modules matching the pattern */
675                         dirent* entry = NULL;
676                         while ((entry = readdir(library)))
677                         {
678                                 if (this->MatchText(entry->d_name, filename))
679                                 {
680                                         if (!this->LoadModule(entry->d_name))
681                                                 n_match++;
682                                 }
683                         }
684                         closedir(library);
685                 }
686                 /* Loadmodule will now return false if any one of the modules failed
687                  * to load (but wont abort when it encounters a bad one) and when 1 or
688                  * more modules were actually loaded.
689                  */
690                 return (n_match > 0);
691         }
692
693         char modfile[MAXBUF];
694         snprintf(modfile,MAXBUF,"%s/%s",Config->ModPath,filename);
695         std::string filename_str = filename;
696
697         if (!ServerConfig::DirValid(modfile))
698         {
699                 this->Log(DEFAULT,"Module %s is not within the modules directory.",modfile);
700                 snprintf(MODERR,MAXBUF,"Module %s is not within the modules directory.",modfile);
701                 return false;
702         }
703         this->Log(DEBUG,"Loading module: %s",modfile);
704
705         if (ServerConfig::FileExists(modfile))
706         {
707
708                 for (unsigned int j = 0; j < Config->module_names.size(); j++)
709                 {
710                         if (Config->module_names[j] == filename_str)
711                         {
712                                 this->Log(DEFAULT,"Module %s is already loaded, cannot load a module twice!",modfile);
713                                 snprintf(MODERR,MAXBUF,"Module already loaded");
714                                 return false;
715                         }
716                 }
717                 try
718                 {
719                         ircd_module* a = new ircd_module(this, modfile);
720                         factory[this->ModCount+1] = a;
721                         if (factory[this->ModCount+1]->LastError())
722                         {
723                                 this->Log(DEFAULT,"Unable to load %s: %s",modfile,factory[this->ModCount+1]->LastError());
724                                 snprintf(MODERR,MAXBUF,"Loader/Linker error: %s",factory[this->ModCount+1]->LastError());
725                                 return false;
726                         }
727                         if ((long)factory[this->ModCount+1]->factory != -1)
728                         {
729                                 Module* m = factory[this->ModCount+1]->factory->CreateModule(this);
730
731                                 Version v = m->GetVersion();
732
733                                 if (v.API != API_VERSION)
734                                 {
735                                         delete m;
736                                         delete a;
737                                         this->Log(DEFAULT,"Unable to load %s: Incorrect module API version: %d (our version: %d)",modfile,v.API,API_VERSION);
738                                         snprintf(MODERR,MAXBUF,"Loader/Linker error: Incorrect module API version: %d (our version: %d)",v.API,API_VERSION);
739                                         return false;
740                                 }
741                                 else
742                                 {
743                                         this->Log(DEFAULT,"New module introduced: %s (API version %d, Module version %d.%d.%d.%d)%s", filename, v.API, v.Major, v.Minor, v.Revision, v.Build, (!(v.Flags & VF_VENDOR) ? " [3rd Party]" : " [Vendor]"));
744                                 }
745
746                                 modules[this->ModCount+1] = m;
747                                 /* save the module and the module's classfactory, if
748                                  * this isnt done, random crashes can occur :/ */
749                                 Config->module_names.push_back(filename);
750
751                                 char* x = &Config->implement_lists[this->ModCount+1][0];
752                                 for(int t = 0; t < 255; t++)
753                                         x[t] = 0;
754
755                                 modules[this->ModCount+1]->Implements(x);
756
757                                 for(int t = 0; t < 255; t++)
758                                         Config->global_implementation[t] += Config->implement_lists[this->ModCount+1][t];
759                         }
760                         else
761                         {
762                                 this->Log(DEFAULT,"Unable to load %s",modfile);
763                                 snprintf(MODERR,MAXBUF,"Factory function failed: Probably missing init_module() entrypoint.");
764                                 return false;
765                         }
766                 }
767                 catch (CoreException& modexcept)
768                 {
769                         this->Log(DEFAULT,"Unable to load %s: ",modfile,modexcept.GetReason());
770                         snprintf(MODERR,MAXBUF,"Factory function of %s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
771                         return false;
772                 }
773         }
774         else
775         {
776                 this->Log(DEFAULT,"InspIRCd: startup: Module Not Found %s",modfile);
777                 snprintf(MODERR,MAXBUF,"Module file could not be found");
778                 return false;
779         }
780         this->ModCount++;
781         FOREACH_MOD_I(this,I_OnLoadModule,OnLoadModule(modules[this->ModCount],filename_str));
782         // now work out which modules, if any, want to move to the back of the queue,
783         // and if they do, move them there.
784         std::vector<std::string> put_to_back;
785         std::vector<std::string> put_to_front;
786         std::map<std::string,std::string> put_before;
787         std::map<std::string,std::string> put_after;
788         for (unsigned int j = 0; j < Config->module_names.size(); j++)
789         {
790                 if (modules[j]->Prioritize() == PRIORITY_LAST)
791                         put_to_back.push_back(Config->module_names[j]);
792                 else if (modules[j]->Prioritize() == PRIORITY_FIRST)
793                         put_to_front.push_back(Config->module_names[j]);
794                 else if ((modules[j]->Prioritize() & 0xFF) == PRIORITY_BEFORE)
795                         put_before[Config->module_names[j]] = Config->module_names[modules[j]->Prioritize() >> 8];
796                 else if ((modules[j]->Prioritize() & 0xFF) == PRIORITY_AFTER)
797                         put_after[Config->module_names[j]] = Config->module_names[modules[j]->Prioritize() >> 8];
798         }
799         for (unsigned int j = 0; j < put_to_back.size(); j++)
800                 MoveToLast(put_to_back[j]);
801         for (unsigned int j = 0; j < put_to_front.size(); j++)
802                 MoveToFirst(put_to_front[j]);
803         for (std::map<std::string,std::string>::iterator j = put_before.begin(); j != put_before.end(); j++)
804                 MoveBefore(j->first,j->second);
805         for (std::map<std::string,std::string>::iterator j = put_after.begin(); j != put_after.end(); j++)
806                 MoveAfter(j->first,j->second);
807         BuildISupport();
808         return true;
809 }
810
811 void InspIRCd::DoOneIteration(bool process_module_sockets)
812 {
813         static rusage ru;
814
815         /* time() seems to be a pretty expensive syscall, so avoid calling it too much.
816          * Once per loop iteration is pleanty.
817          */
818         OLDTIME = TIME;
819         TIME = time(NULL);
820
821         /* Run background module timers every few seconds
822          * (the docs say modules shouldnt rely on accurate
823          * timing using this event, so we dont have to
824          * time this exactly).
825          */
826         if (TIME != OLDTIME)
827         {
828                 if (TIME < OLDTIME)
829                         WriteOpers("*** \002EH?!\002 -- Time is flowing BACKWARDS in this dimension! Clock drifted backwards %d secs.",abs(OLDTIME-TIME));
830                 if ((TIME % 3600) == 0)
831                 {
832                         this->RehashUsersAndChans();
833                         FOREACH_MOD_I(this, I_OnGarbageCollect, OnGarbageCollect());
834                 }
835                 Timers->TickTimers(TIME);
836                 this->DoBackgroundUserStuff(TIME);
837
838                 if ((TIME % 5) == 0)
839                 {
840                         XLines->expire_lines();
841                         FOREACH_MOD_I(this,I_OnBackgroundTimer,OnBackgroundTimer(TIME));
842                         Timers->TickMissedTimers(TIME);
843                 }
844
845                 if (!getrusage(0, &ru))
846                 {
847                         gettimeofday(&this->stats->LastSampled, NULL);
848                         this->stats->LastCPU = ru.ru_utime;
849                 }
850         }
851
852         /* Call the socket engine to wait on the active
853          * file descriptors. The socket engine has everything's
854          * descriptors in its list... dns, modules, users,
855          * servers... so its nice and easy, just one call.
856          * This will cause any read or write events to be 
857          * dispatched to their handlers.
858          */
859         SE->DispatchEvents();
860 }
861
862 bool InspIRCd::IsIdent(const char* n)
863 {
864         if (!n || !*n)
865                 return false;
866
867         for (char* i = (char*)n; *i; i++)
868         {
869                 if ((*i >= 'A') && (*i <= '}'))
870                 {
871                         continue;
872                 }
873                 if (((*i >= '0') && (*i <= '9')) || (*i == '-') || (*i == '.'))
874                 {
875                         continue;
876                 }
877                 return false;
878         }
879         return true;
880 }
881
882
883 int InspIRCd::Run()
884 {
885         while (true)
886         {
887                 DoOneIteration(true);
888         }
889         /* This is never reached -- we hope! */
890         return 0;
891 }
892
893 /**********************************************************************************/
894
895 /**
896  * An ircd in four lines! bwahahaha. ahahahahaha. ahahah *cough*.
897  */
898
899 int main(int argc, char** argv)
900 {
901         SI = new InspIRCd(argc, argv);
902         SI->Run();
903         delete SI;
904         return 0;
905 }
906
907 /* this returns true when all modules are satisfied that the user should be allowed onto the irc server
908  * (until this returns true, a user will block in the waiting state, waiting to connect up to the
909  * registration timeout maximum seconds)
910  */
911 bool InspIRCd::AllModulesReportReady(userrec* user)
912 {
913         if (!Config->global_implementation[I_OnCheckReady])
914                 return true;
915
916         for (int i = 0; i <= this->GetModuleCount(); i++)
917         {
918                 if (Config->implement_lists[i][I_OnCheckReady])
919                 {
920                         int res = modules[i]->OnCheckReady(user);
921                         if (!res)
922                                 return false;
923                 }
924         }
925         return true;
926 }
927
928 int InspIRCd::GetModuleCount()
929 {
930         return this->ModCount;
931 }
932
933 time_t InspIRCd::Time(bool delta)
934 {
935         if (delta)
936                 return TIME + time_delta;
937         return TIME;
938 }
939
940 int InspIRCd::SetTimeDelta(int delta)
941 {
942         int old = time_delta;
943         time_delta += delta;
944         this->Log(DEBUG, "Time delta set to %d (was %d)", time_delta, old);
945         return old;
946 }
947
948 void InspIRCd::AddLocalClone(userrec* user)
949 {
950         clonemap::iterator x = local_clones.find(user->GetIPString());
951         if (x != local_clones.end())
952                 x->second++;
953         else
954                 local_clones[user->GetIPString()] = 1;
955 }
956
957 void InspIRCd::AddGlobalClone(userrec* user)
958 {
959         clonemap::iterator y = global_clones.find(user->GetIPString());
960         if (y != global_clones.end())
961                 y->second++;
962         else
963                 global_clones[user->GetIPString()] = 1;
964 }
965
966 int InspIRCd::GetTimeDelta()
967 {
968         return time_delta;
969 }
970
971 bool FileLogger::Readable()
972 {
973         return false;
974 }
975
976 void FileLogger::HandleEvent(EventType et, int errornum)
977 {
978         this->WriteLogLine("");
979         if (log)
980                 ServerInstance->SE->DelFd(this);
981 }
982
983 void FileLogger::WriteLogLine(const std::string &line)
984 {
985         if (line.length())
986                 buffer.append(line);
987
988         if (log)
989         {
990                 int written = fprintf(log,"%s",buffer.c_str());
991                 if ((written >= 0) && (written < (int)buffer.length()))
992                 {
993                         buffer.erase(0, buffer.length());
994                         ServerInstance->SE->AddFd(this);
995                 }
996                 else if (written == -1)
997                 {
998                         if (errno == EAGAIN)
999                                 ServerInstance->SE->AddFd(this);
1000                 }
1001                 else
1002                 {
1003                         /* Wrote the whole buffer, and no need for write callback */
1004                         buffer = "";
1005                 }
1006         }
1007         if (writeops++ % 20)
1008         {
1009                 fflush(log);
1010         }
1011 }
1012
1013 void FileLogger::Close()
1014 {
1015         if (log)
1016         {
1017                 int flags = fcntl(fileno(log), F_GETFL, 0);
1018                 fcntl(fileno(log), F_SETFL, flags ^ O_NONBLOCK);
1019                 if (buffer.size())
1020                         fprintf(log,"%s",buffer.c_str());
1021
1022                 ServerInstance->SE->DelFd(this);
1023
1024                 fflush(log);
1025                 fclose(log);
1026         }
1027
1028         buffer = "";
1029 }
1030
1031 FileLogger::FileLogger(InspIRCd* Instance, FILE* logfile) : ServerInstance(Instance), log(logfile), writeops(0)
1032 {
1033         if (log)
1034         {
1035                 irc::sockets::NonBlocking(fileno(log));
1036                 this->SetFd(fileno(log));
1037                 buffer = "";
1038         }
1039 }
1040
1041 FileLogger::~FileLogger()
1042 {
1043         this->Close();
1044 }
1045