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