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