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