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