]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/inspircd_io.cpp
Fixes to make this actually WORK.
[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",CONFIG_FILE);
416         fclose(Config->log_file);
417         OpenLog(NULL,0);
418         Config->Read(false,NULL);
419 }
420
421
422
423 void Start (void)
424 {
425         printf("\033[1;32mInspire Internet Relay Chat Server, compiled %s at %s\n",__DATE__,__TIME__);
426         printf("(C) ChatSpike Development team.\033[0m\n\n");
427         printf("Developers:\033[1;32m     Brain, FrostyCoolSlug\033[0m\n");
428         printf("Documentation:\033[1;32m  FrostyCoolSlug, w00t\033[0m\n");
429         printf("Testers:\033[1;32m        typobox43, piggles, Lord_Zathras, CC\033[0m\n");
430         printf("Name concept:\033[1;32m   Lord_Zathras\033[0m\n\n");
431 }
432
433 void WritePID(std::string filename)
434 {
435         ofstream outfile(filename.c_str());
436         if (outfile.is_open())
437         {
438                 outfile << getpid();
439                 outfile.close();
440         }
441         else
442         {
443                 printf("Failed to write PID-file '%s', exiting.\n",filename.c_str());
444                 log(DEFAULT,"Failed to write PID-file '%s', exiting.",filename.c_str());
445                 Exit(0);
446         }
447 }
448
449 void SetSignals()
450 {
451         signal (SIGALRM, SIG_IGN);
452         signal (SIGHUP, Rehash);
453         signal (SIGPIPE, SIG_IGN);
454         signal (SIGTERM, Exit);
455         signal (SIGSEGV, Error);
456 }
457
458
459 int DaemonSeed (void)
460 {
461         int childpid;
462         if ((childpid = fork ()) < 0)
463                 return (ERROR);
464         else if (childpid > 0)
465                 exit (0);
466         setsid ();
467         umask (007);
468         printf("InspIRCd Process ID: \033[1;32m%lu\033[0m\n",(unsigned long)getpid());
469
470         setpriority(PRIO_PROCESS,(int)getpid(),15);
471
472         if (Config->unlimitcore)
473         {
474                 rlimit rl;
475                 if (getrlimit(RLIMIT_CORE, &rl) == -1)
476                 {
477                         log(DEFAULT,"Failed to getrlimit()!");
478                         return(FALSE);
479                 }
480                 else
481                 {
482                         rl.rlim_cur = rl.rlim_max;
483                         if (setrlimit(RLIMIT_CORE, &rl) == -1)
484                                 log(DEFAULT,"setrlimit() failed, cannot increase coredump size.");
485                 }
486         }
487   
488         return (TRUE);
489 }
490
491
492 /* Make Sure Modules Are Avaliable!
493  * (BugFix By Craig.. See? I do work! :p)
494  * Modified by brain, requires const char*
495  * to work with other API functions
496  */
497
498 bool FileExists (const char* file)
499 {
500         FILE *input;
501         if ((input = fopen (file, "r")) == NULL)
502         {
503                 return(false);
504         }
505         else
506         {
507                 fclose (input);
508                 return(true);
509         }
510 }
511
512 /* ConfProcess does the following things to a config line in the following order:
513  *
514  * Processes the line for syntax errors as shown below
515  *      (1) Line void of quotes or equals (a malformed, illegal tag format)
516  *      (2) Odd number of quotes on the line indicating a missing quote
517  *      (3) number of equals signs not equal to number of quotes / 2 (missing an equals sign)
518  *      (4) Spaces between the opening bracket (<) and the keyword
519  *      (5) Spaces between a keyword and an equals sign
520  *      (6) Spaces between an equals sign and a quote
521  * Removes trailing spaces
522  * Removes leading spaces
523  * Converts tabs to spaces
524  * Turns multiple spaces that are outside of quotes into single spaces
525  */
526
527 std::string ServerConfig::ConfProcess(char* buffer, long linenumber, std::stringstream* errorstream, bool &error, std::string filename)
528 {
529         long number_of_quotes = 0;
530         long number_of_equals = 0;
531         bool has_open_bracket = false;
532         bool in_quotes = false;
533         error = false;
534         if (!buffer)
535         {
536                 return "";
537         }
538         // firstly clean up the line by stripping spaces from the start and end and converting tabs to spaces
539         for (unsigned int d = 0; d < strlen(buffer); d++)
540                 if ((buffer[d]) == 9)
541                         buffer[d] = ' ';
542         while ((buffer[0] == ' ') && (strlen(buffer)>0)) buffer++;
543         while ((buffer[strlen(buffer)-1] == ' ') && (strlen(buffer)>0)) buffer[strlen(buffer)-1] = '\0';
544
545         // empty lines are syntactically valid, as are comments
546         if (!(*buffer) || buffer[0] == '#')
547                 return "";
548
549         for (unsigned int c = 0; c < strlen(buffer); c++)
550         {
551                 // convert all spaces that are OUTSIDE quotes into hardspace (0xA0) as this will make them easier to
552                 // search and replace later :)
553                 if ((!in_quotes) && (buffer[c] == ' '))
554                         buffer[c] = '\xA0';
555                 if ((buffer[c] == '<') && (!in_quotes))
556                 {
557                         has_open_bracket = true;
558                         if (strlen(buffer) == 1)
559                         {
560                                 *errorstream << "Tag without identifier at " << filename << ":" << linenumber << endl;
561                                 error = true;
562                                 return "";
563                         }
564                         else if ((tolower(buffer[c+1]) < 'a') || (tolower(buffer[c+1]) > 'z'))
565                         {
566                                 *errorstream << "Invalid characters in identifier at " << filename << ":" << linenumber << endl;
567                                 error = true;
568                                 return "";
569                         }
570                 }
571                 if (buffer[c] == '"')
572                 {
573                         number_of_quotes++;
574                         in_quotes = (!in_quotes);
575                 }
576                 if ((buffer[c] == '=') && (!in_quotes))
577                 {
578                         number_of_equals++;
579                         if (strlen(buffer) == c)
580                         {
581                                 *errorstream << "Variable without a value at " << filename << ":" << linenumber << endl;
582                                 error = true;
583                                 return "";
584                         }
585                         else if (buffer[c+1] != '"')
586                         {
587                                 *errorstream << "Variable name not followed immediately by its value at " << filename << ":" << linenumber << endl;
588                                 error = true;
589                                 return "";
590                         }
591                         else if (!c)
592                         {
593                                 *errorstream << "Value without a variable (line starts with '=') at " << filename << ":" << linenumber << endl;
594                                 error = true;
595                                 return "";
596                         }
597                         else if (buffer[c-1] == '\xA0')
598                         {
599                                 *errorstream << "Variable name not followed immediately by its value at " << filename << ":" << linenumber << endl;
600                                 error = true;
601                                 return "";
602                         }
603                 }
604         }
605         // no quotes, and no equals. something freaky.
606         if ((!number_of_quotes) || (!number_of_equals) && (strlen(buffer)>2) && (buffer[0]=='<'))
607         {
608                 *errorstream << "Malformed tag at " << filename << ":" << linenumber << endl;
609                 error = true;
610                 return "";
611         }
612         // odd number of quotes. thats just wrong.
613         if ((number_of_quotes % 2) != 0)
614         {
615                 *errorstream << "Missing \" at " << filename << ":" << linenumber << endl;
616                 error = true;
617                 return "";
618         }
619         if (number_of_equals < (number_of_quotes/2))
620         {
621                 *errorstream << "Missing '=' at " << filename << ":" << linenumber << endl;
622         }
623         if (number_of_equals > (number_of_quotes/2))
624         {
625                 *errorstream << "Too many '=' at " << filename << ":" << linenumber << endl;
626         }
627
628         std::string parsedata = buffer;
629         // turn multispace into single space
630         while (parsedata.find("\xA0\xA0") != std::string::npos)
631         {
632                 parsedata.erase(parsedata.find("\xA0\xA0"),1);
633         }
634
635         // turn our hardspace back into softspace
636         for (unsigned int d = 0; d < parsedata.length(); d++)
637         {
638                 if (parsedata[d] == '\xA0')
639                         parsedata[d] = ' ';
640         }
641
642         // and we're done, the line is fine!
643         return parsedata;
644 }
645
646 int ServerConfig::fgets_safe(char* buffer, size_t maxsize, FILE* &file)
647 {
648         char c_read = '\0';
649         unsigned int bufptr = 0;
650         while ((!feof(file)) && (c_read != '\n') && (c_read != '\r') && (bufptr < maxsize))
651         {
652                 c_read = fgetc(file);
653                 if ((c_read != '\n') && (c_read != '\r'))
654                         buffer[bufptr++] = c_read;
655         }
656         buffer[bufptr] = '\0';
657         return bufptr;
658 }
659
660 bool ServerConfig::LoadConf(const char* filename, std::stringstream *target, std::stringstream* errorstream)
661 {
662         target->str("");
663         errorstream->str("");
664         long linenumber = 1;
665         // first, check that the file exists before we try to do anything with it
666         if (!FileExists(filename))
667         {
668                 *errorstream << "File " << filename << " not found." << endl;
669                 return false;
670         }
671         // Fix the chmod of the file to restrict it to the current user and group
672         chmod(filename,0600);
673         for (unsigned int t = 0; t < include_stack.size(); t++)
674         {
675                 if (std::string(filename) == include_stack[t])
676                 {
677                         *errorstream << "File " << filename << " is included recursively (looped inclusion)." << endl;
678                         return false;
679                 }
680         }
681         include_stack.push_back(filename);
682         // now open it
683         FILE* conf = fopen(filename,"r");
684         char buffer[MAXBUF];
685         if (conf)
686         {
687                 while (!feof(conf))
688                 {
689                         if (fgets_safe(buffer, MAXBUF, conf))
690                         {
691                                 if ((!feof(conf)) && (buffer) && (strlen(buffer)))
692                                 {
693                                         if ((buffer[0] != '#') && (buffer[0] != '\r')  && (buffer[0] != '\n'))
694                                         {
695                                                 if (!strncmp(buffer,"<include file=\"",15))
696                                                 {
697                                                         char* buf = buffer;
698                                                         char confpath[10240],newconf[10240];
699                                                         // include file directive
700                                                         buf += 15;      // advance to filename
701                                                         for (unsigned int j = 0; j < strlen(buf); j++)
702                                                         {
703                                                                 if (buf[j] == '\\')
704                                                                         buf[j] = '/';
705                                                                 if (buf[j] == '"')
706                                                                 {
707                                                                         buf[j] = '\0';
708                                                                         break;
709                                                                 }
710                                                         }
711                                                         log(DEFAULT,"Opening included file '%s'",buf);
712                                                         if (*buf != '/')
713                                                         {
714                                                                 strlcpy(confpath,CONFIG_FILE,10240);
715                                                                 if (strstr(confpath,"/inspircd.conf"))
716                                                                 {
717                                                                         // leaves us with just the path
718                                                                         *(strstr(confpath,"/inspircd.conf")) = '\0';
719                                                                 }
720                                                                 snprintf(newconf,10240,"%s/%s",confpath,buf);
721                                                         }
722                                                         else strlcpy(newconf,buf,10240);
723                                                         std::stringstream merge(stringstream::in | stringstream::out);
724                                                         // recursively call LoadConf and get the new data, use the same errorstream
725                                                         if (LoadConf(newconf, &merge, errorstream))
726                                                         {
727                                                                 // append to the end of the file
728                                                                 std::string newstuff = merge.str();
729                                                                 *target << newstuff;
730                                                         }
731                                                         else
732                                                         {
733                                                                 // the error propogates up to its parent recursively
734                                                                 // causing the config reader to bail at the top level.
735                                                                 fclose(conf);
736                                                                 return false;
737                                                         }
738                                                 }
739                                                 else
740                                                 {
741                                                         bool error = false;
742                                                         std::string data = this->ConfProcess(buffer,linenumber++,errorstream,error,filename);
743                                                         if (error)
744                                                         {
745                                                                 return false;
746                                                         }
747                                                         *target << data;
748                                                 }
749                                         }
750                                         else linenumber++;
751                                 }
752                         }
753                 }
754                 fclose(conf);
755         }
756         target->seekg(0);
757         return true;
758 }
759
760 /* Counts the number of tags of a certain type within the config file, e.g. to enumerate opers */
761
762 int ServerConfig::EnumConf(std::stringstream *config, const char* tag)
763 {
764         int ptr = 0;
765         char buffer[MAXBUF], c_tag[MAXBUF], c, lastc;
766         int in_token, in_quotes, tptr, idx = 0;
767
768         const char* buf = config->str().c_str();
769         long bptr = 0;
770         long len = strlen(buf);
771         
772         ptr = 0;
773         in_token = 0;
774         in_quotes = 0;
775         lastc = '\0';
776         while (bptr<len)
777         {
778                 lastc = c;
779                 c = buf[bptr++];
780                 if ((c == '#') && (lastc == '\n'))
781                 {
782                         while ((c != '\n') && (bptr<len))
783                         {
784                                 lastc = c;
785                                 c = buf[bptr++];
786                         }
787                 }
788                 if ((c == '<') && (!in_quotes))
789                 {
790                         tptr = 0;
791                         in_token = 1;
792                         do {
793                                 c = buf[bptr++];
794                                 if (c != ' ')
795                                 {
796                                         c_tag[tptr++] = c;
797                                         c_tag[tptr] = '\0';
798                                 }
799                         } while (c != ' ');
800                 }
801                 if (c == '"')
802                 {
803                         in_quotes = (!in_quotes);
804                 }
805                 if ((c == '>') && (!in_quotes))
806                 {
807                         in_token = 0;
808                         if (!strcmp(c_tag,tag))
809                         {
810                                 /* correct tag, but wrong index */
811                                 idx++;
812                         }
813                         c_tag[0] = '\0';
814                         buffer[0] = '\0';
815                         ptr = 0;
816                         tptr = 0;
817                 }
818                 if (c != '>')
819                 {
820                         if ((in_token) && (c != '\n') && (c != '\r'))
821                         {
822                                 buffer[ptr++] = c;
823                                 buffer[ptr] = '\0';
824                         }
825                 }
826         }
827         return idx;
828 }
829
830 /* Counts the number of values within a certain tag */
831
832 int ServerConfig::EnumValues(std::stringstream *config, const char* tag, int index)
833 {
834         int ptr = 0;
835         char buffer[MAXBUF], c_tag[MAXBUF], c, lastc;
836         int in_token, in_quotes, tptr, idx = 0;
837         
838         bool correct_tag = false;
839         int num_items = 0;
840
841         const char* buf = config->str().c_str();
842         long bptr = 0;
843         long len = strlen(buf);
844         
845         ptr = 0;
846         in_token = 0;
847         in_quotes = 0;
848         lastc = '\0';
849         while (bptr<len)
850         {
851                 lastc = c;
852                 c = buf[bptr++];
853                 if ((c == '#') && (lastc == '\n'))
854                 {
855                         while ((c != '\n') && (bptr<len))
856                         {
857                                 lastc = c;
858                                 c = buf[bptr++];
859                         }
860                 }
861                 if ((c == '<') && (!in_quotes))
862                 {
863                         tptr = 0;
864                         in_token = 1;
865                         do {
866                                 c = buf[bptr++];
867                                 if (c != ' ')
868                                 {
869                                         c_tag[tptr++] = c;
870                                         c_tag[tptr] = '\0';
871                                         
872                                         if ((!strcmp(c_tag,tag)) && (idx == index))
873                                         {
874                                                 correct_tag = true;
875                                         }
876                                 }
877                         } while (c != ' ');
878                 }
879                 if (c == '"')
880                 {
881                         in_quotes = (!in_quotes);
882                 }
883                 
884                 if ( (correct_tag) && (!in_quotes) && ( (c == ' ') || (c == '\n') || (c == '\r') ) )
885                 {
886                         num_items++;
887                 }
888                 if ((c == '>') && (!in_quotes))
889                 {
890                         in_token = 0;
891                         if (correct_tag)
892                                 correct_tag = false;
893                         if (!strcmp(c_tag,tag))
894                         {
895                                 /* correct tag, but wrong index */
896                                 idx++;
897                         }
898                         c_tag[0] = '\0';
899                         buffer[0] = '\0';
900                         ptr = 0;
901                         tptr = 0;
902                 }
903                 if (c != '>')
904                 {
905                         if ((in_token) && (c != '\n') && (c != '\r'))
906                         {
907                                 buffer[ptr++] = c;
908                                 buffer[ptr] = '\0';
909                         }
910                 }
911         }
912         return num_items+1;
913 }
914
915
916
917 int ServerConfig::ConfValueEnum(char* tag, std::stringstream* config)
918 {
919         return EnumConf(config,tag);
920 }
921
922
923
924 /* Retrieves a value from the config file. If there is more than one value of the specified
925  * key and section (e.g. for opers etc) then the index value specifies which to retreive, e.g.
926  *
927  * ConfValue("oper","name",2,result);
928  */
929
930 int ServerConfig::ReadConf(std::stringstream *config, const char* tag, const char* var, int index, char *result)
931 {
932         int ptr = 0;
933         char buffer[65535], c_tag[MAXBUF], c, lastc;
934         int in_token, in_quotes, tptr, idx = 0;
935         char* key;
936
937         const char* buf = config->str().c_str();
938         long bptr = 0;
939         long len = config->str().length();
940         
941         ptr = 0;
942         in_token = 0;
943         in_quotes = 0;
944         lastc = '\0';
945         c_tag[0] = '\0';
946         buffer[0] = '\0';
947         while (bptr<len)
948         {
949                 lastc = c;
950                 c = buf[bptr++];
951                 // FIX: Treat tabs as spaces
952                 if (c == 9)
953                         c = 32;
954                 if ((c == '<') && (!in_quotes))
955                 {
956                         tptr = 0;
957                         in_token = 1;
958                         do {
959                                 c = buf[bptr++];
960                                 if (c != ' ')
961                                 {
962                                         c_tag[tptr++] = c;
963                                         c_tag[tptr] = '\0';
964                                 }
965                         // FIX: Tab can follow a tagname as well as space.
966                         } while ((c != ' ') && (c != 9));
967                 }
968                 if (c == '"')
969                 {
970                         in_quotes = (!in_quotes);
971                 }
972                 if ((c == '>') && (!in_quotes))
973                 {
974                         in_token = 0;
975                         if (idx == index)
976                         {
977                                 if (!strcmp(c_tag,tag))
978                                 {
979                                         if ((buffer) && (c_tag) && (var))
980                                         {
981                                                 key = strstr(buffer,var);
982                                                 if (!key)
983                                                 {
984                                                         /* value not found in tag */
985                                                         *result = 0;
986                                                         return 0;
987                                                 }
988                                                 else
989                                                 {
990                                                         key+=strlen(var);
991                                                         while (*key !='"')
992                                                         {
993                                                                 if (!*key)
994                                                                 {
995                                                                         /* missing quote */
996                                                                         *result = 0;
997                                                                         return 0;
998                                                                 }
999                                                                 key++;
1000                                                         }
1001                                                         key++;
1002                                                         for (unsigned j = 0; j < strlen(key); j++)
1003                                                         {
1004                                                                 if (key[j] == '"')
1005                                                                 {
1006                                                                         key[j] = '\0';
1007                                                                 }
1008                                                         }
1009                                                         strlcpy(result,key,MAXBUF);
1010                                                         return 1;
1011                                                 }
1012                                         }
1013                                 }
1014                         }
1015                         if (!strcmp(c_tag,tag))
1016                         {
1017                                 /* correct tag, but wrong index */
1018                                 idx++;
1019                         }
1020                         c_tag[0] = '\0';
1021                         buffer[0] = '\0';
1022                         ptr = 0;
1023                         tptr = 0;
1024                 }
1025                 if (c != '>')
1026                 {
1027                         if ((in_token) && (c != '\n') && (c != '\r'))
1028                         {
1029                                 buffer[ptr++] = c;
1030                                 buffer[ptr] = '\0';
1031                         }
1032                 }
1033         }
1034         *result = 0; // value or its tag not found at all
1035         return 0;
1036 }
1037
1038
1039
1040 int ServerConfig::ConfValue(char* tag, char* var, int index, char *result,std::stringstream *config)
1041 {
1042         ReadConf(config, tag, var, index, result);
1043         return 0;
1044 }
1045
1046
1047
1048 // This will bind a socket to a port. It works for UDP/TCP
1049 int BindSocket (int sockfd, struct sockaddr_in client, struct sockaddr_in server, int port, char* addr)
1050 {
1051         memset((char *)&server,0,sizeof(server));
1052         struct in_addr addy;
1053         inet_aton(addr,&addy);
1054         server.sin_family = AF_INET;
1055         if (!strcmp(addr,""))
1056         {
1057                 server.sin_addr.s_addr = htonl(INADDR_ANY);
1058         }
1059         else
1060         {
1061                 server.sin_addr = addy;
1062         }
1063         server.sin_port = htons(port);
1064         if (bind(sockfd,(struct sockaddr*)&server,sizeof(server))<0)
1065         {
1066                 return(ERROR);
1067         }
1068         else
1069         {
1070                 listen(sockfd, Config->MaxConn);
1071                 return(TRUE);
1072         }
1073 }
1074
1075
1076 // Open a TCP Socket
1077 int OpenTCPSocket (void)
1078 {
1079         int sockfd;
1080         int on = 1;
1081         struct linger linger = { 0 };
1082   
1083         if ((sockfd = socket (AF_INET, SOCK_STREAM, 0)) < 0)
1084                 return (ERROR);
1085         else
1086         {
1087                 setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, (const char*)&on, sizeof(on));
1088                 /* This is BSD compatible, setting l_onoff to 0 is *NOT* http://web.irc.org/mla/ircd-dev/msg02259.html */
1089                 linger.l_onoff = 1;
1090                 linger.l_linger = 1;
1091                 setsockopt(sockfd, SOL_SOCKET, SO_LINGER, (const char*)&linger,sizeof(linger));
1092                 return (sockfd);
1093         }
1094 }
1095
1096 int BindPorts()
1097 {
1098         char configToken[MAXBUF], Addr[MAXBUF], Type[MAXBUF];
1099         sockaddr_in client,server;
1100         int clientportcount = 0;
1101         int BoundPortCount = 0;
1102         for (int count = 0; count < Config->ConfValueEnum("bind",&Config->config_f); count++)
1103         {
1104                 Config->ConfValue("bind","port",count,configToken,&Config->config_f);
1105                 Config->ConfValue("bind","address",count,Addr,&Config->config_f);
1106                 Config->ConfValue("bind","type",count,Type,&Config->config_f);
1107                 if (strcmp(Type,"servers"))
1108                 {
1109                         // modules handle server bind types now,
1110                         // its not a typo in the strcmp.
1111                         Config->ports[clientportcount] = atoi(configToken);
1112                         strlcpy(Config->addrs[clientportcount],Addr,256);
1113                         clientportcount++;
1114                         log(DEBUG,"InspIRCd: startup: read binding %s:%s [%s] from config",Addr,configToken, Type);
1115                 }
1116         }
1117         int PortCount = clientportcount;
1118
1119         for (int count = 0; count < PortCount; count++)
1120         {
1121                 if ((openSockfd[BoundPortCount] = OpenTCPSocket()) == ERROR)
1122                 {
1123                         log(DEBUG,"InspIRCd: startup: bad fd %lu",(unsigned long)openSockfd[BoundPortCount]);
1124                         return(ERROR);
1125                 }
1126                 if (BindSocket(openSockfd[BoundPortCount],client,server,Config->ports[count],Config->addrs[count]) == ERROR)
1127                 {
1128                         log(DEFAULT,"InspIRCd: startup: failed to bind port %lu",(unsigned long)Config->ports[count]);
1129                 }
1130                 else    /* well we at least bound to one socket so we'll continue */
1131                 {
1132                         BoundPortCount++;
1133                 }
1134         }
1135
1136         /* if we didn't bind to anything then abort */
1137         if (!BoundPortCount)
1138         {
1139                 log(DEFAULT,"InspIRCd: startup: no ports bound, bailing!");
1140                 printf("\nERROR: Was not able to bind any of %lu ports! Please check your configuration.\n\n", (unsigned long)PortCount);
1141                 return (ERROR);
1142         }
1143
1144         return BoundPortCount;
1145 }
1146