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