]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/inspircd.cpp
Add some stuff to change how we process a token sepeperated stream
[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
18 #ifndef WIN32
19         #include <dirent.h>
20         #include <unistd.h>
21         #include <sys/resource.h>
22         #include <dlfcn.h>
23         #include <getopt.h>
24
25         /* Some systems don't define RUSAGE_SELF. This should fix them. */
26         #ifndef RUSAGE_SELF
27                 #define RUSAGE_SELF 0
28         #endif
29 #endif
30
31 #include <exception>
32 #include <fstream>
33 #include "modules.h"
34 #include "mode.h"
35 #include "xline.h"
36 #include "socketengine.h"
37 #include "inspircd_se_config.h"
38 #include "socket.h"
39 #include "typedefs.h"
40 #include "command_parse.h"
41 #include "exitcodes.h"
42 #include "caller.h"
43
44 using irc::sockets::NonBlocking;
45 using irc::sockets::Blocking;
46 using irc::sockets::insp_ntoa;
47 using irc::sockets::insp_inaddr;
48 using irc::sockets::insp_sockaddr;
49
50 InspIRCd* SI = NULL;
51 int* mysig = NULL;
52
53
54 /* Burlex: Moved from exitcodes.h -- due to duplicate symbols */
55 const char* ExitCodes[] =
56 {
57                 "No error", /* 0 */
58                 "DIE command", /* 1 */
59                 "execv() failed", /* 2 */
60                 "Internal error", /* 3 */
61                 "Config file error", /* 4 */
62                 "Logfile error", /* 5 */
63                 "POSIX fork failed", /* 6 */
64                 "Bad commandline parameters", /* 7 */
65                 "No ports could be bound", /* 8 */
66                 "Can't write PID file", /* 9 */
67                 "SocketEngine could not initialize", /* 10 */
68                 "Refusing to start up as root", /* 11 */
69                 "Found a <die> tag!", /* 12 */
70                 "Couldn't load module on startup", /* 13 */
71                 "Could not create windows forked process", /* 14 */
72                 "Received SIGTERM", /* 15 */
73 };
74
75 void InspIRCd::Cleanup()
76 {
77         std::vector<std::string> mymodnames;
78         int MyModCount = this->GetModuleCount();
79
80         for (unsigned int i = 0; i < Config->ports.size(); i++)
81         {
82                 /* This calls the constructor and closes the listening socket */
83                 delete Config->ports[i];
84         }
85
86         Config->ports.clear();
87
88         /* Close all client sockets, or the new process inherits them */
89         for (std::vector<userrec*>::const_iterator i = this->local_users.begin(); i != this->local_users.end(); i++)
90         {
91                 (*i)->SetWriteError("Server shutdown");
92                 (*i)->CloseSocket();
93         }
94
95         /* We do this more than once, so that any service providers get a
96          * chance to be unhooked by the modules using them, but then get
97          * a chance to be removed themsleves.
98          */
99         for (int tries = 0; tries < 3; tries++)
100         {
101                 MyModCount = this->GetModuleCount();
102                 mymodnames.clear();
103
104                 /* Unload all modules, so they get a chance to clean up their listeners */
105                 for (int j = 0; j <= MyModCount; j++)
106                         mymodnames.push_back(Config->module_names[j]);
107
108                 for (int k = 0; k <= MyModCount; k++)
109                         this->UnloadModule(mymodnames[k].c_str());
110         }
111
112         /* Close logging */
113         this->Logger->Close();
114
115         /* Cleanup Server Names */
116         for(servernamelist::iterator itr = servernames.begin(); itr != servernames.end(); ++itr)
117                 delete (*itr);
118
119 #ifdef WINDOWS
120         /* WSACleanup */
121         WSACleanup();
122 #endif
123 }
124
125 void InspIRCd::Restart(const std::string &reason)
126 {
127         /* SendError flushes each client's queue,
128          * regardless of writeability state
129          */
130         this->SendError(reason);
131
132         this->Cleanup();
133
134         /* Figure out our filename (if theyve renamed it, we're boned) */
135         std::string me;
136
137 #ifdef WINDOWS
138         char module[MAX_PATH];
139         if (GetModuleFileName(NULL, module, MAX_PATH))
140                 me = module;
141 #else
142         me = Config->MyDir + "/inspircd";
143 #endif
144
145         if (execv(me.c_str(), Config->argv) == -1)
146         {
147                 /* Will raise a SIGABRT if not trapped */
148                 throw CoreException(std::string("Failed to execv()! error: ") + strerror(errno));
149         }
150 }
151
152 void InspIRCd::ResetMaxBans()
153 {
154         for (chan_hash::const_iterator i = chanlist->begin(); i != chanlist->end(); i++)
155                 i->second->ResetMaxBans();
156 }
157
158 /** Because hash_map doesnt free its buckets when we delete items (this is a 'feature')
159  * we must occasionally rehash the hash (yes really).
160  * We do this by copying the entries from the old hash to a new hash, causing all
161  * empty buckets to be weeded out of the hash. We dont do this on a timer, as its
162  * very expensive, so instead we do it when the user types /REHASH and expects a
163  * short delay anyway.
164  */
165 void InspIRCd::RehashUsersAndChans()
166 {
167         user_hash* old_users = this->clientlist;
168         chan_hash* old_chans = this->chanlist;
169
170         this->clientlist = new user_hash();
171         this->chanlist = new chan_hash();
172
173         for (user_hash::const_iterator n = old_users->begin(); n != old_users->end(); n++)
174                 this->clientlist->insert(*n);
175
176         delete old_users;
177
178         for (chan_hash::const_iterator n = old_chans->begin(); n != old_chans->end(); n++)
179                 this->chanlist->insert(*n);
180
181         delete old_chans;
182 }
183
184 void InspIRCd::CloseLog()
185 {
186         this->Logger->Close();
187 }
188
189 void InspIRCd::SetSignals()
190 {
191 #ifndef WIN32
192         signal(SIGALRM, SIG_IGN);
193         signal(SIGHUP, InspIRCd::SetSignal);
194         signal(SIGPIPE, SIG_IGN);
195         signal(SIGCHLD, SIG_IGN);
196 #endif
197         signal(SIGTERM, InspIRCd::SetSignal);
198 }
199
200 void InspIRCd::QuickExit(int status)
201 {
202         exit(0);
203 }
204
205 bool InspIRCd::DaemonSeed()
206 {
207 #ifdef WINDOWS
208         printf_c("InspIRCd Process ID: \033[1;32m%lu\033[0m\n", GetCurrentProcessId());
209         return true;
210 #else
211         signal(SIGTERM, InspIRCd::QuickExit);
212
213         int childpid;
214         if ((childpid = fork ()) < 0)
215                 return false;
216         else if (childpid > 0)
217         {
218                 /* We wait here for the child process to kill us,
219                  * so that the shell prompt doesnt come back over
220                  * the output.
221                  * Sending a kill with a signal of 0 just checks
222                  * if the child pid is still around. If theyre not,
223                  * they threw an error and we should give up.
224                  */
225                 while (kill(childpid, 0) != -1)
226                         sleep(1);
227                 exit(0);
228         }
229         setsid ();
230         umask (007);
231         printf("InspIRCd Process ID: \033[1;32m%lu\033[0m\n",(unsigned long)getpid());
232
233         signal(SIGTERM, InspIRCd::SetSignal);
234
235         rlimit rl;
236         if (getrlimit(RLIMIT_CORE, &rl) == -1)
237         {
238                 this->Log(DEFAULT,"Failed to getrlimit()!");
239                 return false;
240         }
241         else
242         {
243                 rl.rlim_cur = rl.rlim_max;
244                 if (setrlimit(RLIMIT_CORE, &rl) == -1)
245                         this->Log(DEFAULT,"setrlimit() failed, cannot increase coredump size.");
246         }
247
248         return true;
249 #endif
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 InspIRCd::InspIRCd(int argc, char** argv)
280         : ModCount(0),
281           GlobalCulls(this),
282
283          /* Functor initialisation. Note that the ordering here is very important. */
284          HandleProcessUser(this),
285          HandleIsNick(this),
286          HandleIsIdent(this),
287          HandleFindDescriptor(this),
288          HandleFloodQuitUser(this),
289
290          /* Functor pointer initialisation. Must match the order of the list above */
291          ProcessUser(&HandleProcessUser),
292          IsNick(&HandleIsNick),
293          IsIdent(&HandleIsIdent),
294          FindDescriptor(&HandleFindDescriptor),
295          FloodQuitUser(&HandleFloodQuitUser)
296
297 {
298
299         int found_ports = 0;
300         FailedPortList pl;
301         int do_version = 0, do_nofork = 0, do_debug = 0, do_nolog = 0, do_root = 0;    /* flag variables */
302         char c = 0;
303
304         modules.resize(255);
305         factory.resize(255);
306         memset(&server, 0, sizeof(server));
307         memset(&client, 0, sizeof(client));
308
309         this->s_signal = 0;
310
311         this->unregistered_count = 0;
312
313         this->clientlist = new user_hash();
314         this->chanlist = new chan_hash();
315
316         this->Config = new ServerConfig(this);
317
318         this->Config->argv = argv;
319         this->Config->argc = argc;
320
321         if (chdir(Config->GetFullProgDir().c_str()))
322         {
323                 printf("Unable to change to my directory: %s\nAborted.", strerror(errno));
324                 exit(0);
325         }
326
327         this->Config->opertypes.clear();
328         this->Config->operclass.clear();
329         this->SNO = new SnomaskManager(this);
330         this->TIME = this->OLDTIME = this->startup_time = time(NULL);
331         this->time_delta = 0;
332         this->next_call = this->TIME + 3;
333         srand(this->TIME);
334
335         *this->LogFileName = 0;
336         strlcpy(this->ConfigFileName, CONFIG_FILE, MAXBUF);
337
338         struct option longopts[] =
339         {
340                 { "nofork",     no_argument,            &do_nofork,     1       },
341                 { "logfile",    required_argument,      NULL,           'f'     },
342                 { "config",     required_argument,      NULL,           'c'     },
343                 { "debug",      no_argument,            &do_debug,      1       },
344                 { "nolog",      no_argument,            &do_nolog,      1       },
345                 { "runasroot",  no_argument,            &do_root,       1       },
346                 { "version",    no_argument,            &do_version,    1       },
347                 { 0, 0, 0, 0 }
348         };
349
350         while ((c = getopt_long_only(argc, argv, ":f:", longopts, NULL)) != -1)
351         {
352                 switch (c)
353                 {
354                         case 'f':
355                                 /* Log filename was set */
356                                 strlcpy(LogFileName, optarg, MAXBUF);
357                         break;
358                         case 'c':
359                                 /* Config filename was set */
360                                 strlcpy(ConfigFileName, optarg, MAXBUF);
361                         break;
362                         case 0:
363                                 /* getopt_long_only() set an int variable, just keep going */
364                         break;
365                         default:
366                                 /* Unknown parameter! DANGER, INTRUDER.... err.... yeah. */
367                                 printf("Usage: %s [--nofork] [--nolog] [--debug] [--logfile <filename>] [--runasroot] [--version] [--config <config>]\n", argv[0]);
368                                 Exit(EXIT_STATUS_ARGV);
369                         break;
370                 }
371         }
372
373         if (do_version)
374         {
375                 printf("\n%s r%s\n", VERSION, REVISION);
376                 Exit(EXIT_STATUS_NOERROR);
377         }
378
379 #ifdef WIN32
380
381         // Handle forking
382         if(!do_nofork)
383         {
384                 DWORD ExitCode = WindowsForkStart(this);
385                 if(ExitCode)
386                         Exit(ExitCode);
387         }
388
389         // Set up winsock
390         WSADATA wsadata;
391         WSAStartup(MAKEWORD(2,0), &wsadata);
392
393         ChangeWindowsSpecificPointers(this);
394 #endif
395         if (!ServerConfig::FileExists(this->ConfigFileName))
396         {
397                 printf("ERROR: Cannot open config file: %s\nExiting...\n", this->ConfigFileName);
398                 this->Log(DEFAULT,"Unable to open config file %s", this->ConfigFileName);
399                 Exit(EXIT_STATUS_CONFIG);
400         }
401
402         printf_c("\033[1;32mInspire Internet Relay Chat Server, compiled %s at %s\n",__DATE__,__TIME__);
403         printf_c("(C) InspIRCd Development Team.\033[0m\n\n");
404         printf_c("Developers:\t\t\033[1;32mBrain, FrostyCoolSlug, w00t, Om, Special, pippijn, peavey, Burlex\033[0m\n");
405         printf_c("Others:\t\t\t\033[1;32mSee /INFO Output\033[0m\n");
406
407         /* Set the finished argument values */
408         Config->nofork = do_nofork;
409         Config->forcedebug = do_debug;
410         Config->writelog = !do_nolog;
411
412         strlcpy(Config->MyExecutable,argv[0],MAXBUF);
413
414         this->OpenLog(argv, argc);
415
416         this->stats = new serverstats();
417         this->Timers = new TimerManager(this);
418         this->Parser = new CommandParser(this);
419         this->XLines = new XLineManager(this);
420         Config->ClearStack();
421         Config->Read(true, NULL);
422
423         if (!do_root)
424                 this->CheckRoot();
425         else
426         {
427                 printf("* WARNING * WARNING * WARNING * WARNING * WARNING * \n\n");
428                 printf("YOU ARE RUNNING INSPIRCD AS ROOT. THIS IS UNSUPPORTED\n");
429                 printf("AND IF YOU ARE HACKED, CRACKED, SPINDLED OR MUTILATED\n");
430                 printf("OR ANYTHING ELSE UNEXPECTED HAPPENS TO YOU OR YOUR\n");
431                 printf("SERVER, THEN IT IS YOUR OWN FAULT. IF YOU DID NOT MEAN\n");
432                 printf("TO START INSPIRCD AS ROOT, HIT CTRL+C NOW AND RESTART\n");
433                 printf("THE PROGRAM AS A NORMAL USER. YOU HAVE BEEN WARNED!\n");
434                 printf("\nInspIRCd starting in 20 seconds, ctrl+c to abort...\n");
435                 sleep(20);
436         }
437
438         this->SetSignals();
439
440         if (!Config->nofork)
441         {
442                 if (!this->DaemonSeed())
443                 {
444                         printf("ERROR: could not go into daemon mode. Shutting down.\n");
445                         Log(DEFAULT,"ERROR: could not go into daemon mode. Shutting down.");
446                         Exit(EXIT_STATUS_FORK);
447                 }
448         }
449
450
451         /* Because of limitations in kqueue on freebsd, we must fork BEFORE we
452          * initialize the socket engine.
453          */
454         SocketEngineFactory* SEF = new SocketEngineFactory();
455         SE = SEF->Create(this);
456         delete SEF;
457
458         this->Modes = new ModeParser(this);
459         this->AddServerName(Config->ServerName);
460         CheckDie();
461         int bounditems = BindPorts(true, found_ports, pl);
462
463         for(int t = 0; t < 255; t++)
464                 Config->global_implementation[t] = 0;
465
466         memset(&Config->implement_lists,0,sizeof(Config->implement_lists));
467
468         printf("\n");
469
470         this->Res = new DNS(this);
471
472         this->LoadAllModules();
473         /* Just in case no modules were loaded - fix for bug #101 */
474         this->BuildISupport();
475         InitializeDisabledCommands(Config->DisabledCommands, this);
476
477         if ((Config->ports.size() == 0) && (found_ports > 0))
478         {
479                 printf("\nERROR: I couldn't bind any ports! Are you sure you didn't start InspIRCd twice?\n");
480                 Log(DEFAULT,"ERROR: I couldn't bind any ports! Are you sure you didn't start InspIRCd twice?");
481                 Exit(EXIT_STATUS_BIND);
482         }
483
484         if (Config->ports.size() != (unsigned int)found_ports)
485         {
486                 printf("\nWARNING: Not all your client ports could be bound --\nstarting anyway with %d of %d client ports bound.\n\n", bounditems, found_ports);
487                 printf("The following port(s) failed to bind:\n");
488                 int j = 1;
489                 for (FailedPortList::iterator i = pl.begin(); i != pl.end(); i++, j++)
490                 {
491                         printf("%d.\tIP: %s\tPort: %lu\n", j, i->first.empty() ? "<all>" : i->first.c_str(), (unsigned long)i->second);
492                 }
493         }
494 #ifndef WINDOWS
495         if (!Config->nofork)
496         {
497                 if (kill(getppid(), SIGTERM) == -1)
498                 {
499                         printf("Error killing parent process: %s\n",strerror(errno));
500                         Log(DEFAULT,"Error killing parent process: %s",strerror(errno));
501                 }
502         }
503
504         if (isatty(0) && isatty(1) && isatty(2))
505         {
506                 /* We didn't start from a TTY, we must have started from a background process -
507                  * e.g. we are restarting, or being launched by cron. Dont kill parent, and dont
508                  * close stdin/stdout
509                  */
510                 if (!do_nofork)
511                 {
512                         fclose(stdin);
513                         fclose(stderr);
514                         fclose(stdout);
515                 }
516                 else
517                 {
518                         Log(DEFAULT,"Keeping pseudo-tty open as we are running in the foreground.");
519                 }
520         }
521 #else
522         WindowsIPC = new IPC(this);
523         if(!Config->nofork)
524         {
525                 WindowsForkKillOwner(this);
526                 FreeConsole();
527         }
528 #endif
529         printf("\nInspIRCd is now running!\n");
530         Log(DEFAULT,"Startup complete.");
531
532         this->WritePID(Config->PID);
533 }
534
535 void InspIRCd::DoOneIteration(bool process_module_sockets)
536 {
537 #ifndef WIN32
538         static rusage ru;
539 #else
540         static time_t uptime;
541         static struct tm * stime;
542         static char window_title[100];
543 #endif
544
545         /* time() seems to be a pretty expensive syscall, so avoid calling it too much.
546          * Once per loop iteration is pleanty.
547          */
548         OLDTIME = TIME;
549         TIME = time(NULL);
550
551         /* Run background module timers every few seconds
552          * (the docs say modules shouldnt rely on accurate
553          * timing using this event, so we dont have to
554          * time this exactly).
555          */
556         if (TIME != OLDTIME)
557         {
558                 if (TIME < OLDTIME)
559                         WriteOpers("*** \002EH?!\002 -- Time is flowing BACKWARDS in this dimension! Clock drifted backwards %d secs.",abs(OLDTIME-TIME));
560                 if ((TIME % 3600) == 0)
561                 {
562                         this->RehashUsersAndChans();
563                         FOREACH_MOD_I(this, I_OnGarbageCollect, OnGarbageCollect());
564                 }
565                 Timers->TickTimers(TIME);
566                 this->DoBackgroundUserStuff(TIME);
567
568                 if ((TIME % 5) == 0)
569                 {
570                         XLines->expire_lines();
571                         FOREACH_MOD_I(this,I_OnBackgroundTimer,OnBackgroundTimer(TIME));
572                         Timers->TickMissedTimers(TIME);
573                 }
574 #ifndef WIN32
575                 /* Same change as in cmd_stats.cpp, use RUSAGE_SELF rather than '0' -- Om */
576                 if (!getrusage(RUSAGE_SELF, &ru))
577                 {
578                         gettimeofday(&this->stats->LastSampled, NULL);
579                         this->stats->LastCPU = ru.ru_utime;
580                 }
581 #else
582                 WindowsIPC->Check();
583
584                 if(Config->nofork)
585                 {
586                         uptime = Time() - startup_time;
587                         stime = gmtime(&uptime);
588                         snprintf(window_title, 100, "InspIRCd - %u clients, %u accepted connections - Up %u days, %.2u:%.2u:%.2u",
589                                 LocalUserCount(), stats->statsAccept, stime->tm_yday, stime->tm_hour, stime->tm_min, stime->tm_sec);
590                         SetConsoleTitle(window_title);
591                 }
592 #endif
593         }
594
595         /* Call the socket engine to wait on the active
596          * file descriptors. The socket engine has everything's
597          * descriptors in its list... dns, modules, users,
598          * servers... so its nice and easy, just one call.
599          * This will cause any read or write events to be
600          * dispatched to their handlers.
601          */
602         this->SE->DispatchEvents();
603
604         /* if any users was quit, take them out */
605         this->GlobalCulls.Apply();
606
607         /* If any inspsockets closed, remove them */
608         this->InspSocketCull();
609
610         if (this->s_signal)
611         {
612                 this->SignalHandler(s_signal);
613                 this->s_signal = 0;
614         }
615
616 }
617
618 void InspIRCd::InspSocketCull()
619 {
620         for (std::map<InspSocket*,InspSocket*>::iterator x = SocketCull.begin(); x != SocketCull.end(); ++x)
621         {
622                 SE->DelFd(x->second);
623                 x->second->Close();
624                 delete x->second;
625         }
626         SocketCull.clear();
627 }
628
629 int InspIRCd::Run()
630 {
631         while (true)
632         {
633                 DoOneIteration(true);
634         }
635         /* This is never reached -- we hope! */
636         return 0;
637 }
638
639 /**********************************************************************************/
640
641 /**
642  * An ircd in four lines! bwahahaha. ahahahahaha. ahahah *cough*.
643  */
644
645 int main(int argc, char** argv)
646 {
647         SI = new InspIRCd(argc, argv);
648         mysig = &SI->s_signal;
649         SI->Run();
650         delete SI;
651         return 0;
652 }
653
654 /* this returns true when all modules are satisfied that the user should be allowed onto the irc server
655  * (until this returns true, a user will block in the waiting state, waiting to connect up to the
656  * registration timeout maximum seconds)
657  */
658 bool InspIRCd::AllModulesReportReady(userrec* user)
659 {
660         if (!Config->global_implementation[I_OnCheckReady])
661                 return true;
662
663         for (int i = 0; i <= this->GetModuleCount(); i++)
664         {
665                 if (Config->implement_lists[i][I_OnCheckReady])
666                 {
667                         int res = modules[i]->OnCheckReady(user);
668                         if (!res)
669                                 return false;
670                 }
671         }
672         return true;
673 }
674
675 int InspIRCd::GetModuleCount()
676 {
677         return this->ModCount;
678 }
679
680 time_t InspIRCd::Time(bool delta)
681 {
682         if (delta)
683                 return TIME + time_delta;
684         return TIME;
685 }
686
687 int InspIRCd::SetTimeDelta(int delta)
688 {
689         int old = time_delta;
690         time_delta = delta;
691         this->Log(DEBUG, "Time delta set to %d (was %d)", time_delta, old);
692         return old;
693 }
694
695 void InspIRCd::AddLocalClone(userrec* user)
696 {
697         clonemap::iterator x = local_clones.find(user->GetIPString());
698         if (x != local_clones.end())
699                 x->second++;
700         else
701                 local_clones[user->GetIPString()] = 1;
702 }
703
704 void InspIRCd::AddGlobalClone(userrec* user)
705 {
706         clonemap::iterator y = global_clones.find(user->GetIPString());
707         if (y != global_clones.end())
708                 y->second++;
709         else
710                 global_clones[user->GetIPString()] = 1;
711 }
712
713 int InspIRCd::GetTimeDelta()
714 {
715         return time_delta;
716 }
717
718 void InspIRCd::SetSignal(int signal)
719 {
720         *mysig = signal;
721 }
722