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