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