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