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