]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/inspircd_io.cpp
Fixed SIGHUP rehash to actually send rehash event to modules
[user/henk/code/inspircd.git] / src / inspircd_io.cpp
1 /*       +------------------------------------+
2  *       | Inspire Internet Relay Chat Daemon |
3  *       +------------------------------------+
4  *
5  *  InspIRCd is copyright (C) 2002-2006 ChatSpike-Dev.
6  *                       E-mail:
7  *                <brain@chatspike.net>
8  *                <Craig@chatspike.net>
9  *     
10  * Written by Craig Edwards, Craig McLure, and others.
11  * This program is free but copyrighted software; see
12  *            the file COPYING for details.
13  *
14  * ---------------------------------------------------
15  */
16
17 using namespace std;
18
19 #include "inspircd_config.h"
20 #include <sys/time.h>
21 #include <sys/resource.h>
22 #include <sys/types.h>
23 #include <string>
24 #include <unistd.h>
25 #include <sstream>
26 #include <iostream>
27 #include <fstream>
28 #include "inspircd.h"
29 #include "inspircd_io.h"
30 #include "inspstring.h"
31 #include "helperfuncs.h"
32 #include "userprocess.h"
33 #include "xline.h"
34
35 extern ServerConfig *Config;
36 extern InspIRCd* ServerInstance;
37 extern int openSockfd[MAXSOCKS];
38 extern time_t TIME;
39
40
41 ServerConfig::ServerConfig()
42 {
43         this->ClearStack();
44         *ServerName = *Network = *ServerDesc = *AdminName = '\0';
45         *AdminEmail = *AdminNick = *diepass = *restartpass = '\0';
46         *CustomVersion = *motd = *rules = *PrefixQuit = *DieValue = *DNSServer = '\0';
47         *OperOnlyStats = *ModPath = *MyExecutable = *DisabledCommands = *PID = '\0';
48         log_file = NULL;
49         nofork = false;
50         unlimitcore = false;
51         AllowHalfop = true;
52         dns_timeout = 5;
53         NetBufferSize = 10240;
54         SoftLimit = MAXCLIENTS;
55         MaxConn = SOMAXCONN;
56         MaxWhoResults = 100;
57         debugging = 0;
58         LogLevel = DEFAULT;
59         DieDelay = 5;
60 }
61
62 void ServerConfig::ClearStack()
63 {
64         include_stack.clear();
65 }
66
67 Module* ServerConfig::GetIOHook(int port)
68 {
69         std::map<int,Module*>::iterator x = IOHookModule.find(port);
70         return (x != IOHookModule.end() ? x->second : NULL);
71 }
72
73 bool ServerConfig::AddIOHook(int port, Module* iomod)
74 {
75         if (!GetIOHook(port))
76         {
77                 IOHookModule[port] = iomod;
78                 return true;
79         }
80         return false;
81 }
82
83 bool ServerConfig::DelIOHook(int port)
84 {
85         std::map<int,Module*>::iterator x = IOHookModule.find(port);
86         if (x != IOHookModule.end())
87         {
88                 IOHookModule.erase(x);
89                 return true;
90         }
91         return false;
92 }
93
94 bool ServerConfig::CheckOnce(char* tag, bool bail, userrec* user)
95 {
96         if (ConfValueEnum(tag,&Config->config_f) > 1)
97         {
98                 if (bail)
99                 {
100                         printf("There were errors in your configuration:\nYou have more than one <%s> tag, this is not permitted.\n",tag);
101                         Exit(0);
102                 }
103                 else
104                 {
105                         if (user)
106                         {
107                                 WriteServ(user->fd,"There were errors in your configuration:");
108                                 WriteServ(user->fd,"You have more than one <%s> tag, this is not permitted.\n",tag);
109                         }
110                         else
111                         {
112                                 WriteOpers("There were errors in the configuration file:");
113                                 WriteOpers("You have more than one <%s> tag, this is not permitted.\n",tag);
114                         }
115                 }
116                 return false;
117         }
118         return true;
119 }
120
121 void ServerConfig::Read(bool bail, userrec* user)
122 {
123         char dbg[MAXBUF],pauseval[MAXBUF],Value[MAXBUF],timeout[MAXBUF],NB[MAXBUF],flood[MAXBUF],MW[MAXBUF],MCON[MAXBUF];
124         char AH[MAXBUF],AP[MAXBUF],AF[MAXBUF],DNT[MAXBUF],pfreq[MAXBUF],thold[MAXBUF],sqmax[MAXBUF],rqmax[MAXBUF],SLIMT[MAXBUF];
125         ConnectClass c;
126         std::stringstream errstr;
127         include_stack.clear();
128
129         if (!LoadConf(CONFIG_FILE,&Config->config_f,&errstr))
130         {
131                 errstr.seekg(0);
132                 log(DEFAULT,"There were errors in your configuration:\n%s",errstr.str().c_str());
133                 if (bail)
134                 {
135                         printf("There were errors in your configuration:\n%s",errstr.str().c_str());
136                         Exit(0);
137                 }
138                 else
139                 {
140                         char dataline[1024];
141                         if (user)
142                         {
143                                 WriteServ(user->fd,"NOTICE %s :There were errors in the configuration file:",user->nick);
144                                 while (!errstr.eof())
145                                 {
146                                         errstr.getline(dataline,1024);
147                                         WriteServ(user->fd,"NOTICE %s :%s",user->nick,dataline);
148                                 }
149                         }
150                         else
151                         {
152                                 WriteOpers("There were errors in the configuration file:");
153                                 while (!errstr.eof())
154                                 {
155                                         errstr.getline(dataline,1024);
156                                         WriteOpers(dataline);
157                                 }
158                         }
159                         return;
160                 }
161         }
162
163         /* Check we dont have more than one of singular tags
164          */
165         if (!CheckOnce("server",bail,user) || !CheckOnce("admin",bail,user) || !CheckOnce("files",bail,user)
166                 || !CheckOnce("power",bail,user) || !CheckOnce("options",bail,user)
167                 || !CheckOnce("dns",bail,user) || !CheckOnce("options",bail,user)
168                 || !CheckOnce("disabled",bail,user) || !CheckOnce("pid",bail,user))
169         {
170                 return;
171         }
172
173         ConfValue("server","name",0,Config->ServerName,&Config->config_f);
174         ConfValue("server","description",0,Config->ServerDesc,&Config->config_f);
175         ConfValue("server","network",0,Config->Network,&Config->config_f);
176         ConfValue("admin","name",0,Config->AdminName,&Config->config_f);
177         ConfValue("admin","email",0,Config->AdminEmail,&Config->config_f);
178         ConfValue("admin","nick",0,Config->AdminNick,&Config->config_f);
179         ConfValue("files","motd",0,Config->motd,&Config->config_f);
180         ConfValue("files","rules",0,Config->rules,&Config->config_f);
181         ConfValue("power","diepass",0,Config->diepass,&Config->config_f);
182         ConfValue("power","pause",0,pauseval,&Config->config_f);
183         ConfValue("power","restartpass",0,Config->restartpass,&Config->config_f);
184         ConfValue("options","prefixquit",0,Config->PrefixQuit,&Config->config_f);
185         ConfValue("die","value",0,Config->DieValue,&Config->config_f);
186         ConfValue("options","loglevel",0,dbg,&Config->config_f);
187         ConfValue("options","netbuffersize",0,NB,&Config->config_f);
188         ConfValue("options","maxwho",0,MW,&Config->config_f);
189         ConfValue("options","allowhalfop",0,AH,&Config->config_f);
190         ConfValue("options","allowprotect",0,AP,&Config->config_f);
191         ConfValue("options","allowfounder",0,AF,&Config->config_f);
192         ConfValue("dns","server",0,Config->DNSServer,&Config->config_f);
193         ConfValue("dns","timeout",0,DNT,&Config->config_f);
194         ConfValue("options","moduledir",0,Config->ModPath,&Config->config_f);
195         ConfValue("disabled","commands",0,Config->DisabledCommands,&Config->config_f);
196         ConfValue("options","somaxconn",0,MCON,&Config->config_f);
197         ConfValue("options","softlimit",0,SLIMT,&Config->config_f);
198         ConfValue("options","operonlystats",0,Config->OperOnlyStats,&Config->config_f);
199         ConfValue("options","customversion",0,Config->CustomVersion,&Config->config_f);
200
201         Config->SoftLimit = atoi(SLIMT);
202         if ((Config->SoftLimit < 1) || (Config->SoftLimit > MAXCLIENTS))
203         {
204                 log(DEFAULT,"WARNING: <options:softlimit> value is greater than %d or less than 0, set to %d.",MAXCLIENTS,MAXCLIENTS);
205                 Config->SoftLimit = MAXCLIENTS;
206         }
207         Config->MaxConn = atoi(MCON);
208         if (Config->MaxConn > SOMAXCONN)
209                 log(DEFAULT,"WARNING: <options:somaxconn> value may be higher than the system-defined SOMAXCONN value!");
210         Config->NetBufferSize = atoi(NB);
211         Config->MaxWhoResults = atoi(MW);
212         Config->dns_timeout = atoi(DNT);
213         if (!Config->dns_timeout)
214                 Config->dns_timeout = 5;
215         if (!Config->MaxConn)
216                 Config->MaxConn = SOMAXCONN;
217         if (!*Config->DNSServer)
218                 strlcpy(Config->DNSServer,"127.0.0.1",MAXBUF);
219         if (!*Config->ModPath)
220                 strlcpy(Config->ModPath,MOD_PATH,MAXBUF);
221         Config->AllowHalfop = ((!strcasecmp(AH,"true")) || (!strcasecmp(AH,"1")) || (!strcasecmp(AH,"yes")));
222         if ((!Config->NetBufferSize) || (Config->NetBufferSize > 65535) || (Config->NetBufferSize < 1024))
223         {
224                 log(DEFAULT,"No NetBufferSize specified or size out of range, setting to default of 10240.");
225                 Config->NetBufferSize = 10240;
226         }
227         if ((!Config->MaxWhoResults) || (Config->MaxWhoResults > 65535) || (Config->MaxWhoResults < 1))
228         {
229                 log(DEFAULT,"No MaxWhoResults specified or size out of range, setting to default of 128.");
230                 Config->MaxWhoResults = 128;
231         }
232         Config->LogLevel = DEFAULT;
233         if (!strcmp(dbg,"debug"))
234         {
235                 Config->LogLevel = DEBUG;
236                 Config->debugging = 1;
237         }
238         if (!strcmp(dbg,"verbose"))
239                 Config->LogLevel = VERBOSE;
240         if (!strcmp(dbg,"default"))
241                 Config->LogLevel = DEFAULT;
242         if (!strcmp(dbg,"sparse"))
243                 Config->LogLevel = SPARSE;
244         if (!strcmp(dbg,"none"))
245                 Config->LogLevel = NONE;
246
247         readfile(Config->MOTD,Config->motd);
248         log(DEFAULT,"Reading message of the day...");
249         readfile(Config->RULES,Config->rules);
250         log(DEFAULT,"Reading connect classes...");
251         Classes.clear();
252         for (int i = 0; i < ConfValueEnum("connect",&Config->config_f); i++)
253         {
254                 *Value = 0;
255                 ConfValue("connect","allow",i,Value,&Config->config_f);
256                 ConfValue("connect","timeout",i,timeout,&Config->config_f);
257                 ConfValue("connect","flood",i,flood,&Config->config_f);
258                 ConfValue("connect","pingfreq",i,pfreq,&Config->config_f);
259                 ConfValue("connect","threshold",i,thold,&Config->config_f);
260                 ConfValue("connect","sendq",i,sqmax,&Config->config_f);
261                 ConfValue("connect","recvq",i,rqmax,&Config->config_f);
262                 if (*Value)
263                 {
264                         c.host = Value;
265                         c.type = CC_ALLOW;
266                         strlcpy(Value,"",MAXBUF);
267                         ConfValue("connect","password",i,Value,&Config->config_f);
268                         c.pass = Value;
269                         c.registration_timeout = 90; // default is 2 minutes
270                         c.pingtime = 120;
271                         c.flood = atoi(flood);
272                         c.threshold = 5;
273                         c.sendqmax = 262144; // 256k
274                         c.recvqmax = 4096;   // 4k
275                         if (atoi(thold)>0)
276                         {
277                                 c.threshold = atoi(thold);
278                         }
279                         if (atoi(sqmax)>0)
280                         {
281                                 c.sendqmax = atoi(sqmax);
282                         }
283                         if (atoi(rqmax)>0)
284                         {
285                                 c.recvqmax = atoi(rqmax);
286                         }
287                         if (atoi(timeout)>0)
288                         {
289                                 c.registration_timeout = atoi(timeout);
290                         }
291                         if (atoi(pfreq)>0)
292                         {
293                                 c.pingtime = atoi(pfreq);
294                         }
295                         Classes.push_back(c);
296                 }
297                 else
298                 {
299                         ConfValue("connect","deny",i,Value,&Config->config_f);
300                         c.host = Value;
301                         c.type = CC_DENY;
302                         Classes.push_back(c);
303                         log(DEBUG,"Read connect class type DENY, host=%s",c.host.c_str());
304                 }
305
306         }
307         log(DEFAULT,"Reading K lines,Q lines and Z lines from config...");
308         read_xline_defaults();
309         log(DEFAULT,"Applying K lines, Q lines and Z lines...");
310         apply_lines(APPLY_ALL);
311
312         ConfValue("pid","file",0,Config->PID,&Config->config_f);
313         // write once here, to try it out and make sure its ok
314         WritePID(Config->PID);
315
316         log(DEFAULT,"Done reading configuration file, InspIRCd is now starting.");
317         if (!bail)
318         {
319                 log(DEFAULT,"Adding and removing modules due to rehash...");
320
321                 std::vector<std::string> old_module_names, new_module_names, added_modules, removed_modules;
322
323                 // store the old module names
324                 for (std::vector<std::string>::iterator t = module_names.begin(); t != module_names.end(); t++)
325                 {
326                         old_module_names.push_back(*t);
327                 }
328
329                 // get the new module names
330                 for (int count2 = 0; count2 < ConfValueEnum("module",&Config->config_f); count2++)
331                 {
332                         ConfValue("module","name",count2,Value,&Config->config_f);
333                         new_module_names.push_back(Value);
334                 }
335
336                 // now create a list of new modules that are due to be loaded
337                 // and a seperate list of modules which are due to be unloaded
338                 for (std::vector<std::string>::iterator _new = new_module_names.begin(); _new != new_module_names.end(); _new++)
339                 {
340                         bool added = true;
341                         for (std::vector<std::string>::iterator old = old_module_names.begin(); old != old_module_names.end(); old++)
342                         {
343                                 if (*old == *_new)
344                                         added = false;
345                         }
346                         if (added)
347                                 added_modules.push_back(*_new);
348                 }
349                 for (std::vector<std::string>::iterator oldm = old_module_names.begin(); oldm != old_module_names.end(); oldm++)
350                 {
351                         bool removed = true;
352                         for (std::vector<std::string>::iterator newm = new_module_names.begin(); newm != new_module_names.end(); newm++)
353                         {
354                                 if (*newm == *oldm)
355                                         removed = false;
356                         }
357                         if (removed)
358                                 removed_modules.push_back(*oldm);
359                 }
360                 // now we have added_modules, a vector of modules to be loaded, and removed_modules, a vector of modules
361                 // to be removed.
362                 int rem = 0, add = 0;
363                 if (!removed_modules.empty())
364                 for (std::vector<std::string>::iterator removing = removed_modules.begin(); removing != removed_modules.end(); removing++)
365                 {
366                         if (ServerInstance->UnloadModule(removing->c_str()))
367                         {
368                                 WriteOpers("*** REHASH UNLOADED MODULE: %s",removing->c_str());
369                                 WriteServ(user->fd,"973 %s %s :Module %s successfully unloaded.",user->nick, removing->c_str(), removing->c_str());
370                                 rem++;
371                         }
372                         else
373                         {
374                                 WriteServ(user->fd,"972 %s %s :Failed to unload module %s: %s",user->nick, removing->c_str(), removing->c_str(), ServerInstance->ModuleError());
375                         }
376                 }
377                 if (!added_modules.empty())
378                 for (std::vector<std::string>::iterator adding = added_modules.begin(); adding != added_modules.end(); adding++)
379                 {
380                         if (ServerInstance->LoadModule(adding->c_str()))
381                         {
382                                 WriteOpers("*** REHASH LOADED MODULE: %s",adding->c_str());
383                                 WriteServ(user->fd,"975 %s %s :Module %s successfully loaded.",user->nick, adding->c_str(), adding->c_str());
384                                 add++;
385                         }
386                         else
387                         {
388                                 WriteServ(user->fd,"974 %s %s :Failed to load module %s: %s",user->nick, adding->c_str(), adding->c_str(), ServerInstance->ModuleError());
389                         }
390                 }
391                 log(DEFAULT,"Successfully unloaded %lu of %lu modules and loaded %lu of %lu modules.",(unsigned long)rem,(unsigned long)removed_modules.size(),
392                                                                                                         (unsigned long)add,(unsigned long)added_modules.size());
393         }
394 }
395
396
397 void Exit (int status)
398 {
399         if (Config->log_file)
400                 fclose(Config->log_file);
401         send_error("Server shutdown.");
402         exit (status);
403 }
404
405 void Killed(int status)
406 {
407         if (Config->log_file)
408                 fclose(Config->log_file);
409         send_error("Server terminated.");
410         exit(status);
411 }
412
413 void Rehash(int status)
414 {
415         WriteOpers("Rehashing config file %s due to SIGHUP",CleanFilename(CONFIG_FILE));
416         fclose(Config->log_file);
417         OpenLog(NULL,0);
418         Config->Read(false,NULL);
419         FOREACH_MOD(I_OnRehash,OnRehash(""));
420 }
421
422
423
424 void Start (void)
425 {
426         printf("\033[1;32mInspire Internet Relay Chat Server, compiled %s at %s\n",__DATE__,__TIME__);
427         printf("(C) ChatSpike Development team.\033[0m\n\n");
428         printf("Developers:\033[1;32m     Brain, FrostyCoolSlug\033[0m\n");
429         printf("Documentation:\033[1;32m  FrostyCoolSlug, w00t\033[0m\n");
430         printf("Testers:\033[1;32m        typobox43, piggles, Lord_Zathras, CC\033[0m\n");
431         printf("Name concept:\033[1;32m   Lord_Zathras\033[0m\n\n");
432 }
433
434 void WritePID(std::string filename)
435 {
436         ofstream outfile(filename.c_str());
437         if (outfile.is_open())
438         {
439                 outfile << getpid();
440                 outfile.close();
441         }
442         else
443         {
444                 printf("Failed to write PID-file '%s', exiting.\n",filename.c_str());
445                 log(DEFAULT,"Failed to write PID-file '%s', exiting.",filename.c_str());
446                 Exit(0);
447         }
448 }
449
450 void SetSignals()
451 {
452         signal (SIGALRM, SIG_IGN);
453         signal (SIGHUP, Rehash);
454         signal (SIGPIPE, SIG_IGN);
455         signal (SIGTERM, Exit);
456         signal (SIGSEGV, Error);
457 }
458
459
460 int DaemonSeed (void)
461 {
462         int childpid;
463         if ((childpid = fork ()) < 0)
464                 return (ERROR);
465         else if (childpid > 0)
466                 exit (0);
467         setsid ();
468         umask (007);
469         printf("InspIRCd Process ID: \033[1;32m%lu\033[0m\n",(unsigned long)getpid());
470
471         setpriority(PRIO_PROCESS,(int)getpid(),15);
472
473         if (Config->unlimitcore)
474         {
475                 rlimit rl;
476                 if (getrlimit(RLIMIT_CORE, &rl) == -1)
477                 {
478                         log(DEFAULT,"Failed to getrlimit()!");
479                         return(FALSE);
480                 }
481                 else
482                 {
483                         rl.rlim_cur = rl.rlim_max;
484                         if (setrlimit(RLIMIT_CORE, &rl) == -1)
485                                 log(DEFAULT,"setrlimit() failed, cannot increase coredump size.");
486                 }
487         }
488   
489         return (TRUE);
490 }
491
492
493 /* Make Sure Modules Are Avaliable!
494  * (BugFix By Craig.. See? I do work! :p)
495  * Modified by brain, requires const char*
496  * to work with other API functions
497  */
498
499 bool FileExists (const char* file)
500 {
501         FILE *input;
502         if ((input = fopen (file, "r")) == NULL)
503         {
504                 return(false);
505         }
506         else
507         {
508                 fclose (input);
509                 return(true);
510         }
511 }
512
513 /* ConfProcess does the following things to a config line in the following order:
514  *
515  * Processes the line for syntax errors as shown below
516  *      (1) Line void of quotes or equals (a malformed, illegal tag format)
517  *      (2) Odd number of quotes on the line indicating a missing quote
518  *      (3) number of equals signs not equal to number of quotes / 2 (missing an equals sign)
519  *      (4) Spaces between the opening bracket (<) and the keyword
520  *      (5) Spaces between a keyword and an equals sign
521  *      (6) Spaces between an equals sign and a quote
522  * Removes trailing spaces
523  * Removes leading spaces
524  * Converts tabs to spaces
525  * Turns multiple spaces that are outside of quotes into single spaces
526  */
527
528 std::string ServerConfig::ConfProcess(char* buffer, long linenumber, std::stringstream* errorstream, bool &error, std::string filename)
529 {
530         long number_of_quotes = 0;
531         long number_of_equals = 0;
532         bool has_open_bracket = false;
533         bool in_quotes = false;
534         error = false;
535         if (!buffer)
536         {
537                 return "";
538         }
539         // firstly clean up the line by stripping spaces from the start and end and converting tabs to spaces
540         for (unsigned int d = 0; d < strlen(buffer); d++)
541                 if ((buffer[d]) == 9)
542                         buffer[d] = ' ';
543         while ((buffer[0] == ' ') && (strlen(buffer)>0)) buffer++;
544         while ((buffer[strlen(buffer)-1] == ' ') && (strlen(buffer)>0)) buffer[strlen(buffer)-1] = '\0';
545
546         // empty lines are syntactically valid, as are comments
547         if (!(*buffer) || buffer[0] == '#')
548                 return "";
549
550         for (unsigned int c = 0; c < strlen(buffer); c++)
551         {
552                 // convert all spaces that are OUTSIDE quotes into hardspace (0xA0) as this will make them easier to
553                 // search and replace later :)
554                 if ((!in_quotes) && (buffer[c] == ' '))
555                         buffer[c] = '\xA0';
556                 if ((buffer[c] == '<') && (!in_quotes))
557                 {
558                         has_open_bracket = true;
559                         if (strlen(buffer) == 1)
560                         {
561                                 *errorstream << "Tag without identifier at " << filename << ":" << linenumber << endl;
562                                 error = true;
563                                 return "";
564                         }
565                         else if ((tolower(buffer[c+1]) < 'a') || (tolower(buffer[c+1]) > 'z'))
566                         {
567                                 *errorstream << "Invalid characters in identifier at " << filename << ":" << linenumber << endl;
568                                 error = true;
569                                 return "";
570                         }
571                 }
572                 if (buffer[c] == '"')
573                 {
574                         number_of_quotes++;
575                         in_quotes = (!in_quotes);
576                 }
577                 if ((buffer[c] == '=') && (!in_quotes))
578                 {
579                         number_of_equals++;
580                         if (strlen(buffer) == c)
581                         {
582                                 *errorstream << "Variable without a value at " << filename << ":" << linenumber << endl;
583                                 error = true;
584                                 return "";
585                         }
586                         else if (buffer[c+1] != '"')
587                         {
588                                 *errorstream << "Variable name not followed immediately by its value at " << filename << ":" << linenumber << endl;
589                                 error = true;
590                                 return "";
591                         }
592                         else if (!c)
593                         {
594                                 *errorstream << "Value without a variable (line starts with '=') at " << filename << ":" << linenumber << endl;
595                                 error = true;
596                                 return "";
597                         }
598                         else if (buffer[c-1] == '\xA0')
599                         {
600                                 *errorstream << "Variable name not followed immediately by its value at " << filename << ":" << linenumber << endl;
601                                 error = true;
602                                 return "";
603                         }
604                 }
605         }
606         // no quotes, and no equals. something freaky.
607         if ((!number_of_quotes) || (!number_of_equals) && (strlen(buffer)>2) && (buffer[0]=='<'))
608         {
609                 *errorstream << "Malformed tag at " << filename << ":" << linenumber << endl;
610                 error = true;
611                 return "";
612         }
613         // odd number of quotes. thats just wrong.
614         if ((number_of_quotes % 2) != 0)
615         {
616                 *errorstream << "Missing \" at " << filename << ":" << linenumber << endl;
617                 error = true;
618                 return "";
619         }
620         if (number_of_equals < (number_of_quotes/2))
621         {
622                 *errorstream << "Missing '=' at " << filename << ":" << linenumber << endl;
623         }
624         if (number_of_equals > (number_of_quotes/2))
625         {
626                 *errorstream << "Too many '=' at " << filename << ":" << linenumber << endl;
627         }
628
629         std::string parsedata = buffer;
630         // turn multispace into single space
631         while (parsedata.find("\xA0\xA0") != std::string::npos)
632         {
633                 parsedata.erase(parsedata.find("\xA0\xA0"),1);
634         }
635
636         // turn our hardspace back into softspace
637         for (unsigned int d = 0; d < parsedata.length(); d++)
638         {
639                 if (parsedata[d] == '\xA0')
640                         parsedata[d] = ' ';
641         }
642
643         // and we're done, the line is fine!
644         return parsedata;
645 }
646
647 int ServerConfig::fgets_safe(char* buffer, size_t maxsize, FILE* &file)
648 {
649         char c_read = '\0';
650         unsigned int bufptr = 0;
651         while ((!feof(file)) && (c_read != '\n') && (c_read != '\r') && (bufptr < maxsize))
652         {
653                 c_read = fgetc(file);
654                 if ((c_read != '\n') && (c_read != '\r'))
655                         buffer[bufptr++] = c_read;
656         }
657         buffer[bufptr] = '\0';
658         return bufptr;
659 }
660
661 bool ServerConfig::LoadConf(const char* filename, std::stringstream *target, std::stringstream* errorstream)
662 {
663         target->str("");
664         errorstream->str("");
665         long linenumber = 1;
666         // first, check that the file exists before we try to do anything with it
667         if (!FileExists(filename))
668         {
669                 *errorstream << "File " << filename << " not found." << endl;
670                 return false;
671         }
672         // Fix the chmod of the file to restrict it to the current user and group
673         chmod(filename,0600);
674         for (unsigned int t = 0; t < include_stack.size(); t++)
675         {
676                 if (std::string(filename) == include_stack[t])
677                 {
678                         *errorstream << "File " << filename << " is included recursively (looped inclusion)." << endl;
679                         return false;
680                 }
681         }
682         include_stack.push_back(filename);
683         // now open it
684         FILE* conf = fopen(filename,"r");
685         char buffer[MAXBUF];
686         if (conf)
687         {
688                 while (!feof(conf))
689                 {
690                         if (fgets_safe(buffer, MAXBUF, conf))
691                         {
692                                 if ((!feof(conf)) && (buffer) && (strlen(buffer)))
693                                 {
694                                         if ((buffer[0] != '#') && (buffer[0] != '\r')  && (buffer[0] != '\n'))
695                                         {
696                                                 if (!strncmp(buffer,"<include file=\"",15))
697                                                 {
698                                                         char* buf = buffer;
699                                                         char confpath[10240],newconf[10240];
700                                                         // include file directive
701                                                         buf += 15;      // advance to filename
702                                                         for (unsigned int j = 0; j < strlen(buf); j++)
703                                                         {
704                                                                 if (buf[j] == '\\')
705                                                                         buf[j] = '/';
706                                                                 if (buf[j] == '"')
707                                                                 {
708                                                                         buf[j] = '\0';
709                                                                         break;
710                                                                 }
711                                                         }
712                                                         log(DEFAULT,"Opening included file '%s'",buf);
713                                                         if (*buf != '/')
714                                                         {
715                                                                 strlcpy(confpath,CONFIG_FILE,10240);
716                                                                 if (strstr(confpath,"/inspircd.conf"))
717                                                                 {
718                                                                         // leaves us with just the path
719                                                                         *(strstr(confpath,"/inspircd.conf")) = '\0';
720                                                                 }
721                                                                 snprintf(newconf,10240,"%s/%s",confpath,buf);
722                                                         }
723                                                         else strlcpy(newconf,buf,10240);
724                                                         std::stringstream merge(stringstream::in | stringstream::out);
725                                                         // recursively call LoadConf and get the new data, use the same errorstream
726                                                         if (LoadConf(newconf, &merge, errorstream))
727                                                         {
728                                                                 // append to the end of the file
729                                                                 std::string newstuff = merge.str();
730                                                                 *target << newstuff;
731                                                         }
732                                                         else
733                                                         {
734                                                                 // the error propogates up to its parent recursively
735                                                                 // causing the config reader to bail at the top level.
736                                                                 fclose(conf);
737                                                                 return false;
738                                                         }
739                                                 }
740                                                 else
741                                                 {
742                                                         bool error = false;
743                                                         std::string data = this->ConfProcess(buffer,linenumber++,errorstream,error,filename);
744                                                         if (error)
745                                                         {
746                                                                 return false;
747                                                         }
748                                                         *target << data;
749                                                 }
750                                         }
751                                         else linenumber++;
752                                 }
753                         }
754                 }
755                 fclose(conf);
756         }
757         target->seekg(0);
758         return true;
759 }
760
761 /* Counts the number of tags of a certain type within the config file, e.g. to enumerate opers */
762
763 int ServerConfig::EnumConf(std::stringstream *config, const char* tag)
764 {
765         int ptr = 0;
766         char buffer[MAXBUF], c_tag[MAXBUF], c, lastc;
767         int in_token, in_quotes, tptr, idx = 0;
768
769         const char* buf = config->str().c_str();
770         long bptr = 0;
771         long len = strlen(buf);
772         
773         ptr = 0;
774         in_token = 0;
775         in_quotes = 0;
776         lastc = '\0';
777         while (bptr<len)
778         {
779                 lastc = c;
780                 c = buf[bptr++];
781                 if ((c == '#') && (lastc == '\n'))
782                 {
783                         while ((c != '\n') && (bptr<len))
784                         {
785                                 lastc = c;
786                                 c = buf[bptr++];
787                         }
788                 }
789                 if ((c == '<') && (!in_quotes))
790                 {
791                         tptr = 0;
792                         in_token = 1;
793                         do {
794                                 c = buf[bptr++];
795                                 if (c != ' ')
796                                 {
797                                         c_tag[tptr++] = c;
798                                         c_tag[tptr] = '\0';
799                                 }
800                         } while (c != ' ');
801                 }
802                 if (c == '"')
803                 {
804                         in_quotes = (!in_quotes);
805                 }
806                 if ((c == '>') && (!in_quotes))
807                 {
808                         in_token = 0;
809                         if (!strcmp(c_tag,tag))
810                         {
811                                 /* correct tag, but wrong index */
812                                 idx++;
813                         }
814                         c_tag[0] = '\0';
815                         buffer[0] = '\0';
816                         ptr = 0;
817                         tptr = 0;
818                 }
819                 if (c != '>')
820                 {
821                         if ((in_token) && (c != '\n') && (c != '\r'))
822                         {
823                                 buffer[ptr++] = c;
824                                 buffer[ptr] = '\0';
825                         }
826                 }
827         }
828         return idx;
829 }
830
831 /* Counts the number of values within a certain tag */
832
833 int ServerConfig::EnumValues(std::stringstream *config, const char* tag, int index)
834 {
835         int ptr = 0;
836         char buffer[MAXBUF], c_tag[MAXBUF], c, lastc;
837         int in_token, in_quotes, tptr, idx = 0;
838         
839         bool correct_tag = false;
840         int num_items = 0;
841
842         const char* buf = config->str().c_str();
843         long bptr = 0;
844         long len = strlen(buf);
845         
846         ptr = 0;
847         in_token = 0;
848         in_quotes = 0;
849         lastc = '\0';
850         while (bptr<len)
851         {
852                 lastc = c;
853                 c = buf[bptr++];
854                 if ((c == '#') && (lastc == '\n'))
855                 {
856                         while ((c != '\n') && (bptr<len))
857                         {
858                                 lastc = c;
859                                 c = buf[bptr++];
860                         }
861                 }
862                 if ((c == '<') && (!in_quotes))
863                 {
864                         tptr = 0;
865                         in_token = 1;
866                         do {
867                                 c = buf[bptr++];
868                                 if (c != ' ')
869                                 {
870                                         c_tag[tptr++] = c;
871                                         c_tag[tptr] = '\0';
872                                         
873                                         if ((!strcmp(c_tag,tag)) && (idx == index))
874                                         {
875                                                 correct_tag = true;
876                                         }
877                                 }
878                         } while (c != ' ');
879                 }
880                 if (c == '"')
881                 {
882                         in_quotes = (!in_quotes);
883                 }
884                 
885                 if ( (correct_tag) && (!in_quotes) && ( (c == ' ') || (c == '\n') || (c == '\r') ) )
886                 {
887                         num_items++;
888                 }
889                 if ((c == '>') && (!in_quotes))
890                 {
891                         in_token = 0;
892                         if (correct_tag)
893                                 correct_tag = false;
894                         if (!strcmp(c_tag,tag))
895                         {
896                                 /* correct tag, but wrong index */
897                                 idx++;
898                         }
899                         c_tag[0] = '\0';
900                         buffer[0] = '\0';
901                         ptr = 0;
902                         tptr = 0;
903                 }
904                 if (c != '>')
905                 {
906                         if ((in_token) && (c != '\n') && (c != '\r'))
907                         {
908                                 buffer[ptr++] = c;
909                                 buffer[ptr] = '\0';
910                         }
911                 }
912         }
913         return num_items+1;
914 }
915
916
917
918 int ServerConfig::ConfValueEnum(char* tag, std::stringstream* config)
919 {
920         return EnumConf(config,tag);
921 }
922
923
924
925 /* Retrieves a value from the config file. If there is more than one value of the specified
926  * key and section (e.g. for opers etc) then the index value specifies which to retreive, e.g.
927  *
928  * ConfValue("oper","name",2,result);
929  */
930
931 int ServerConfig::ReadConf(std::stringstream *config, const char* tag, const char* var, int index, char *result)
932 {
933         int ptr = 0;
934         char buffer[65535], c_tag[MAXBUF], c, lastc;
935         int in_token, in_quotes, tptr, idx = 0;
936         char* key;
937
938         const char* buf = config->str().c_str();
939         long bptr = 0;
940         long len = config->str().length();
941         
942         ptr = 0;
943         in_token = 0;
944         in_quotes = 0;
945         lastc = '\0';
946         c_tag[0] = '\0';
947         buffer[0] = '\0';
948         while (bptr<len)
949         {
950                 lastc = c;
951                 c = buf[bptr++];
952                 // FIX: Treat tabs as spaces
953                 if (c == 9)
954                         c = 32;
955                 if ((c == '<') && (!in_quotes))
956                 {
957                         tptr = 0;
958                         in_token = 1;
959                         do {
960                                 c = buf[bptr++];
961                                 if (c != ' ')
962                                 {
963                                         c_tag[tptr++] = c;
964                                         c_tag[tptr] = '\0';
965                                 }
966                         // FIX: Tab can follow a tagname as well as space.
967                         } while ((c != ' ') && (c != 9));
968                 }
969                 if (c == '"')
970                 {
971                         in_quotes = (!in_quotes);
972                 }
973                 if ((c == '>') && (!in_quotes))
974                 {
975                         in_token = 0;
976                         if (idx == index)
977                         {
978                                 if (!strcmp(c_tag,tag))
979                                 {
980                                         if ((buffer) && (c_tag) && (var))
981                                         {
982                                                 key = strstr(buffer,var);
983                                                 if (!key)
984                                                 {
985                                                         /* value not found in tag */
986                                                         *result = 0;
987                                                         return 0;
988                                                 }
989                                                 else
990                                                 {
991                                                         key+=strlen(var);
992                                                         while (*key !='"')
993                                                         {
994                                                                 if (!*key)
995                                                                 {
996                                                                         /* missing quote */
997                                                                         *result = 0;
998                                                                         return 0;
999                                                                 }
1000                                                                 key++;
1001                                                         }
1002                                                         key++;
1003                                                         for (unsigned j = 0; j < strlen(key); j++)
1004                                                         {
1005                                                                 if (key[j] == '"')
1006                                                                 {
1007                                                                         key[j] = '\0';
1008                                                                 }
1009                                                         }
1010                                                         strlcpy(result,key,MAXBUF);
1011                                                         return 1;
1012                                                 }
1013                                         }
1014                                 }
1015                         }
1016                         if (!strcmp(c_tag,tag))
1017                         {
1018                                 /* correct tag, but wrong index */
1019                                 idx++;
1020                         }
1021                         c_tag[0] = '\0';
1022                         buffer[0] = '\0';
1023                         ptr = 0;
1024                         tptr = 0;
1025                 }
1026                 if (c != '>')
1027                 {
1028                         if ((in_token) && (c != '\n') && (c != '\r'))
1029                         {
1030                                 buffer[ptr++] = c;
1031                                 buffer[ptr] = '\0';
1032                         }
1033                 }
1034         }
1035         *result = 0; // value or its tag not found at all
1036         return 0;
1037 }
1038
1039
1040
1041 int ServerConfig::ConfValue(char* tag, char* var, int index, char *result,std::stringstream *config)
1042 {
1043         ReadConf(config, tag, var, index, result);
1044         return 0;
1045 }
1046
1047
1048
1049 // This will bind a socket to a port. It works for UDP/TCP
1050 int BindSocket (int sockfd, struct sockaddr_in client, struct sockaddr_in server, int port, char* addr)
1051 {
1052         memset((char *)&server,0,sizeof(server));
1053         struct in_addr addy;
1054         inet_aton(addr,&addy);
1055         server.sin_family = AF_INET;
1056         if (!strcmp(addr,""))
1057         {
1058                 server.sin_addr.s_addr = htonl(INADDR_ANY);
1059         }
1060         else
1061         {
1062                 server.sin_addr = addy;
1063         }
1064         server.sin_port = htons(port);
1065         if (bind(sockfd,(struct sockaddr*)&server,sizeof(server))<0)
1066         {
1067                 return(ERROR);
1068         }
1069         else
1070         {
1071                 listen(sockfd, Config->MaxConn);
1072                 return(TRUE);
1073         }
1074 }
1075
1076
1077 // Open a TCP Socket
1078 int OpenTCPSocket (void)
1079 {
1080         int sockfd;
1081         int on = 1;
1082         struct linger linger = { 0 };
1083   
1084         if ((sockfd = socket (AF_INET, SOCK_STREAM, 0)) < 0)
1085                 return (ERROR);
1086         else
1087         {
1088                 setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, (const char*)&on, sizeof(on));
1089                 /* This is BSD compatible, setting l_onoff to 0 is *NOT* http://web.irc.org/mla/ircd-dev/msg02259.html */
1090                 linger.l_onoff = 1;
1091                 linger.l_linger = 1;
1092                 setsockopt(sockfd, SOL_SOCKET, SO_LINGER, (const char*)&linger,sizeof(linger));
1093                 return (sockfd);
1094         }
1095 }
1096
1097 int BindPorts()
1098 {
1099         char configToken[MAXBUF], Addr[MAXBUF], Type[MAXBUF];
1100         sockaddr_in client,server;
1101         int clientportcount = 0;
1102         int BoundPortCount = 0;
1103         for (int count = 0; count < Config->ConfValueEnum("bind",&Config->config_f); count++)
1104         {
1105                 Config->ConfValue("bind","port",count,configToken,&Config->config_f);
1106                 Config->ConfValue("bind","address",count,Addr,&Config->config_f);
1107                 Config->ConfValue("bind","type",count,Type,&Config->config_f);
1108                 if (strcmp(Type,"servers"))
1109                 {
1110                         // modules handle server bind types now,
1111                         // its not a typo in the strcmp.
1112                         Config->ports[clientportcount] = atoi(configToken);
1113                         strlcpy(Config->addrs[clientportcount],Addr,256);
1114                         clientportcount++;
1115                         log(DEBUG,"InspIRCd: startup: read binding %s:%s [%s] from config",Addr,configToken, Type);
1116                 }
1117         }
1118         int PortCount = clientportcount;
1119
1120         for (int count = 0; count < PortCount; count++)
1121         {
1122                 if ((openSockfd[BoundPortCount] = OpenTCPSocket()) == ERROR)
1123                 {
1124                         log(DEBUG,"InspIRCd: startup: bad fd %lu",(unsigned long)openSockfd[BoundPortCount]);
1125                         return(ERROR);
1126                 }
1127                 if (BindSocket(openSockfd[BoundPortCount],client,server,Config->ports[count],Config->addrs[count]) == ERROR)
1128                 {
1129                         log(DEFAULT,"InspIRCd: startup: failed to bind port %lu",(unsigned long)Config->ports[count]);
1130                 }
1131                 else    /* well we at least bound to one socket so we'll continue */
1132                 {
1133                         BoundPortCount++;
1134                 }
1135         }
1136
1137         /* if we didn't bind to anything then abort */
1138         if (!BoundPortCount)
1139         {
1140                 log(DEFAULT,"InspIRCd: startup: no ports bound, bailing!");
1141                 printf("\nERROR: Was not able to bind any of %lu ports! Please check your configuration.\n\n", (unsigned long)PortCount);
1142                 return (ERROR);
1143         }
1144
1145         return BoundPortCount;
1146 }
1147