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