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