X-Git-Url: https://git.netwichtig.de/gitweb/?a=blobdiff_plain;f=src%2Finspircd_io.cpp;h=eb5229252277c7cd6e2100abaf9d4697f337f43e;hb=aa36987ef707f79042a21dc793feec5586f01edb;hp=e8ef405a41cef6e7d70e7eb5106fa296abf9b2b6;hpb=91f65dd50cebda218d7cdc7ff6ba73fb8ad5852f;p=user%2Fhenk%2Fcode%2Finspircd.git diff --git a/src/inspircd_io.cpp b/src/inspircd_io.cpp index e8ef405a4..eb5229252 100644 --- a/src/inspircd_io.cpp +++ b/src/inspircd_io.cpp @@ -35,7 +35,7 @@ using namespace std; extern ServerConfig *Config; extern InspIRCd* ServerInstance; -extern int openSockfd[MAXSOCKS]; +extern int openSockfd[MAX_DESCRIPTORS]; extern time_t TIME; extern int MODCOUNT; @@ -52,7 +52,7 @@ ServerConfig::ServerConfig() *CustomVersion = *motd = *rules = *PrefixQuit = *DieValue = *DNSServer = '\0'; *OperOnlyStats = *ModPath = *MyExecutable = *DisabledCommands = *PID = '\0'; log_file = NULL; - nofork = HideBans = HideSplits = unlimitcore = false; + OperSpyWhois = nofork = HideBans = HideSplits = false; AllowHalfop = true; dns_timeout = DieDelay = 5; MaxTargets = 20; @@ -104,7 +104,8 @@ bool ServerConfig::DelIOHook(int port) bool ServerConfig::CheckOnce(char* tag, bool bail, userrec* user) { - int count = ConfValueEnum(tag,&Config->config_f); + int count = ConfValueEnum(Config->config_data, tag); + if (count > 1) { if (bail) @@ -262,7 +263,25 @@ bool ValidateServerName(const char* tag, const char* value, void* data) log(DEFAULT,"WARNING: '%s' is not a fully-qualified domain name. Changed to '%s%c'",x,x,'.'); charlcat(x,'.',MAXBUF); } - strlower(x); + //strlower(x); + return true; +} + +bool ValidateNetworkName(const char* tag, const char* value, void* data) +{ + char* x = (char*)data; + + log(DEFAULT," '%s'",x); + + return true; +} + +bool ValidateServerDesc(const char* tag, const char* value, void* data) +{ + char* x = (char*)data; + + log(DEFAULT," '%s'",x); + return true; } @@ -510,49 +529,48 @@ bool DoneMaxBans(const char* tag) void ServerConfig::Read(bool bail, userrec* user) { char debug[MAXBUF]; /* Temporary buffer for debugging value */ - char dataline[1024]; /* Temporary buffer for error output */ - char* convert; /* Temporary buffer used for reading singular values into */ char* data[12]; /* Temporary buffers for reading multiple occurance tags into */ void* ptr[12]; /* Temporary pointers for passing to callbacks */ int r_i[12]; /* Temporary array for casting */ int rem = 0, add = 0; /* Number of modules added, number of modules removed */ - std::stringstream errstr; /* String stream containing the error output */ + std::ostringstream errstr; /* String stream containing the error output */ /* These tags MUST occur and must ONLY occur once in the config file */ static char* Once[] = { "server", "admin", "files", "power", "options", "pid", NULL }; /* These tags can occur ONCE or not at all */ static InitialConfig Values[] = { - {"options", "softlimit", &this->SoftLimit, DT_INTEGER, ValidateSoftLimit}, - {"options", "somaxconn", &this->MaxConn, DT_INTEGER, ValidateMaxConn}, - {"server", "name", &this->ServerName, DT_CHARPTR, ValidateServerName}, - {"server", "description", &this->ServerDesc, DT_CHARPTR, NoValidation}, - {"server", "network", &this->Network, DT_CHARPTR, NoValidation}, - {"admin", "name", &this->AdminName, DT_CHARPTR, NoValidation}, - {"admin", "email", &this->AdminEmail, DT_CHARPTR, NoValidation}, - {"admin", "nick", &this->AdminNick, DT_CHARPTR, NoValidation}, - {"files", "motd", &this->motd, DT_CHARPTR, ValidateMotd}, - {"files", "rules", &this->rules, DT_CHARPTR, ValidateRules}, - {"power", "diepass", &this->diepass, DT_CHARPTR, NoValidation}, - {"power", "pauseval", &this->DieDelay, DT_INTEGER, NoValidation}, - {"power", "restartpass", &this->restartpass, DT_CHARPTR, NoValidation}, - {"options", "prefixquit", &this->PrefixQuit, DT_CHARPTR, NoValidation}, - {"die", "value", &this->DieValue, DT_CHARPTR, NoValidation}, - {"options", "loglevel", &debug, DT_CHARPTR, ValidateLogLevel}, - {"options", "netbuffersize", &this->NetBufferSize, DT_INTEGER, ValidateNetBufferSize}, - {"options", "maxwho", &this->MaxWhoResults, DT_INTEGER, ValidateMaxWho}, - {"options", "allowhalfop", &this->AllowHalfop, DT_BOOLEAN, NoValidation}, - {"dns", "server", &this->DNSServer, DT_CHARPTR, ValidateDnsServer}, - {"dns", "timeout", &this->dns_timeout, DT_INTEGER, ValidateDnsTimeout}, - {"options", "moduledir", &this->ModPath, DT_CHARPTR, ValidateModPath}, - {"disabled", "commands", &this->DisabledCommands, DT_CHARPTR, NoValidation}, - {"options", "operonlystats", &this->OperOnlyStats, DT_CHARPTR, NoValidation}, - {"options", "customversion", &this->CustomVersion, DT_CHARPTR, NoValidation}, - {"options", "hidesplits", &this->HideSplits, DT_BOOLEAN, NoValidation}, - {"options", "hidebans", &this->HideBans, DT_BOOLEAN, NoValidation}, - {"options", "hidewhois", &this->HideWhoisServer, DT_CHARPTR, NoValidation}, - {"options", "tempdir", &this->TempDir, DT_CHARPTR, ValidateTempDir}, - {"pid", "file", &this->PID, DT_CHARPTR, NoValidation}, + {"options", "softlimit", &this->SoftLimit, DT_INTEGER, ValidateSoftLimit}, + {"options", "somaxconn", &this->MaxConn, DT_INTEGER, ValidateMaxConn}, + {"server", "name", &this->ServerName, DT_CHARPTR, ValidateServerName}, + {"server", "description", &this->ServerDesc, DT_CHARPTR, ValidateServerDesc}, + {"server", "network", &this->Network, DT_CHARPTR, ValidateNetworkName}, + {"admin", "name", &this->AdminName, DT_CHARPTR, NoValidation}, + {"admin", "email", &this->AdminEmail, DT_CHARPTR, NoValidation}, + {"admin", "nick", &this->AdminNick, DT_CHARPTR, NoValidation}, + {"files", "motd", &this->motd, DT_CHARPTR, ValidateMotd}, + {"files", "rules", &this->rules, DT_CHARPTR, ValidateRules}, + {"power", "diepass", &this->diepass, DT_CHARPTR, NoValidation}, + {"power", "pauseval", &this->DieDelay, DT_INTEGER, NoValidation}, + {"power", "restartpass", &this->restartpass, DT_CHARPTR, NoValidation}, + {"options", "prefixquit", &this->PrefixQuit, DT_CHARPTR, NoValidation}, + {"die", "value", &this->DieValue, DT_CHARPTR, NoValidation}, + {"options", "loglevel", &debug, DT_CHARPTR, ValidateLogLevel}, + {"options", "netbuffersize", &this->NetBufferSize, DT_INTEGER, ValidateNetBufferSize}, + {"options", "maxwho", &this->MaxWhoResults, DT_INTEGER, ValidateMaxWho}, + {"options", "allowhalfop", &this->AllowHalfop, DT_BOOLEAN, NoValidation}, + {"dns", "server", &this->DNSServer, DT_CHARPTR, ValidateDnsServer}, + {"dns", "timeout", &this->dns_timeout, DT_INTEGER, ValidateDnsTimeout}, + {"options", "moduledir", &this->ModPath, DT_CHARPTR, ValidateModPath}, + {"disabled", "commands", &this->DisabledCommands, DT_CHARPTR, NoValidation}, + {"options", "operonlystats", &this->OperOnlyStats, DT_CHARPTR, NoValidation}, + {"options", "customversion", &this->CustomVersion, DT_CHARPTR, NoValidation}, + {"options", "hidesplits", &this->HideSplits, DT_BOOLEAN, NoValidation}, + {"options", "hidebans", &this->HideBans, DT_BOOLEAN, NoValidation}, + {"options", "hidewhois", &this->HideWhoisServer, DT_CHARPTR, NoValidation}, + {"options", "operspywhois", &this->OperSpyWhois, DT_BOOLEAN, NoValidation}, + {"options", "tempdir", &this->TempDir, DT_CHARPTR, ValidateTempDir}, + {"pid", "file", &this->PID, DT_CHARPTR, NoValidation}, {NULL} }; @@ -618,36 +636,70 @@ void ServerConfig::Read(bool bail, userrec* user) include_stack.clear(); - /* Initially, load the config into memory, bail if there are errors - */ - if (!LoadConf(CONFIG_FILE,&Config->config_f,&errstr)) + /* Load and parse the config file, if there are any errors then explode */ + + /* Make a copy here so if it fails then we can carry on running with an unaffected config */ + ConfigDataHash newconfig; + + if (this->LoadConf(newconfig, CONFIG_FILE, errstr)) { - errstr.seekg(0); - log(DEFAULT,"There were errors in your configuration:\n%s",errstr.str().c_str()); + /* If we succeeded, set the ircd config to the new one */ + Config->config_data = newconfig; + +/* int c = 1; + std::string last; + + for(ConfigDataHash::const_iterator i = this->config_data.begin(); i != this->config_data.end(); i++) + { + c = (i->first != last) ? 1 : c+1; + last = i->first; + + std::cout << "[" << i->first << " " << c << "/" << this->config_data.count(i->first) << "]" << std::endl; + + for(KeyValList::const_iterator j = i->second.begin(); j != i->second.end(); j++) + std::cout << "\t" << j->first << " = " << j->second << std::endl; + + std::cout << "[/" << i->first << " " << c << "/" << this->config_data.count(i->first) << "]" << std::endl; + } + */ } + else + { + log(DEFAULT, "There were errors in your configuration:\n%s", errstr.str().c_str()); if (bail) { + /* Unneeded because of the log() aboive? */ printf("There were errors in your configuration:\n%s",errstr.str().c_str()); Exit(0); } else { + std::string errors = errstr.str(); + std::string::size_type start; + unsigned int prefixlen; + + start = 0; + /* ":Config->ServerName NOTICE user->nick :" */ + prefixlen = strlen(Config->ServerName) + strlen(user->nick) + 11; + if (user) { WriteServ(user->fd,"NOTICE %s :There were errors in the configuration file:",user->nick); - while (!errstr.eof()) + + while(start < errors.length()) { - errstr.getline(dataline,1024); - WriteServ(user->fd,"NOTICE %s :%s",user->nick,dataline); + WriteServ(user->fd, "NOTICE %s :%s",user->nick, errors.substr(start, 510 - prefixlen).c_str()); + start += 510 - prefixlen; } } else { WriteOpers("There were errors in the configuration file:"); - while (!errstr.eof()) + + while(start < errors.length()) { - errstr.getline(dataline,1024); - WriteOpers(dataline); + WriteOpers(errors.substr(start, 360).c_str()); + start += 360; } } @@ -671,21 +723,16 @@ void ServerConfig::Read(bool bail, userrec* user) switch (Values[Index].datatype) { case DT_CHARPTR: - ConfValue(Values[Index].tag, Values[Index].value, 0, val_c, &this->config_f); + /* Assuming MAXBUF here, potentially unsafe */ + ConfValue(this->config_data, Values[Index].tag, Values[Index].value, 0, val_c, MAXBUF); break; case DT_INTEGER: - convert = new char[MAXBUF]; - ConfValue(Values[Index].tag, Values[Index].value, 0, convert, &this->config_f); - *val_i = atoi(convert); - delete[] convert; + ConfValueInteger(this->config_data, Values[Index].tag, Values[Index].value, 0, *val_i); break; case DT_BOOLEAN: - convert = new char[MAXBUF]; - ConfValue(Values[Index].tag, Values[Index].value, 0, convert, &this->config_f); - *val_i = ((*convert == tolower('y')) || (*convert == tolower('t')) || (*convert == '1')); - delete[] convert; + *val_i = ConfValueBool(this->config_data, Values[Index].tag, Values[Index].value, 0); break; case DT_NOTHING: @@ -704,17 +751,19 @@ void ServerConfig::Read(bool bail, userrec* user) * and call the callbacks associated with them. We have three * callbacks for these, a 'start', 'item' and 'end' callback. */ + + /* XXX - Make this use ConfValueInteger and so on */ for (int Index = 0; MultiValues[Index].tag; Index++) { MultiValues[Index].init_function(MultiValues[Index].tag); - int number_of_tags = ConfValueEnum((char*)MultiValues[Index].tag, &this->config_f); + int number_of_tags = ConfValueEnum(this->config_data, MultiValues[Index].tag); for (int tagnum = 0; tagnum < number_of_tags; tagnum++) { for (int valuenum = 0; MultiValues[Index].items[valuenum]; valuenum++) { - ConfValue((char*)MultiValues[Index].tag,(char*)MultiValues[Index].items[valuenum], tagnum, data[valuenum], &this->config_f); + ConfValue(this->config_data, MultiValues[Index].tag, MultiValues[Index].items[valuenum], tagnum, data[valuenum], MAXBUF); switch (MultiValues[Index].datatype[valuenum]) { @@ -753,6 +802,8 @@ void ServerConfig::Read(bool bail, userrec* user) */ if (!bail) { + ServerInstance->stats->BoundPortCount = BindPorts(false); + if (!removed_modules.empty()) for (std::vector::iterator removing = removed_modules.begin(); removing != removed_modules.end(); removing++) { @@ -795,7 +846,7 @@ void ServerConfig::Read(bool bail, userrec* user) } } -void Exit (int status) +void Exit(int status) { if (Config->log_file) fclose(Config->log_file); @@ -830,7 +881,7 @@ void Rehash(int status) -void Start (void) +void Start() { printf("\033[1;32mInspire Internet Relay Chat Server, compiled %s at %s\n",__DATE__,__TIME__); printf("(C) ChatSpike Development team.\033[0m\n\n"); @@ -839,7 +890,7 @@ void Start (void) printf("Name concept:\t\t\033[1;32mLord_Zathras\033[0m\n\n"); } -void WritePID(std::string filename) +void WritePID(const std::string &filename) { ofstream outfile(filename.c_str()); if (outfile.is_open()) @@ -865,7 +916,7 @@ void SetSignals() } -int DaemonSeed (void) +bool DaemonSeed() { int childpid; if ((childpid = fork ()) < 0) @@ -880,23 +931,20 @@ int DaemonSeed (void) umask (007); printf("InspIRCd Process ID: \033[1;32m%lu\033[0m\n",(unsigned long)getpid()); - if (Config->unlimitcore) + rlimit rl; + if (getrlimit(RLIMIT_CORE, &rl) == -1) { - rlimit rl; - if (getrlimit(RLIMIT_CORE, &rl) == -1) - { - log(DEFAULT,"Failed to getrlimit()!"); - return(FALSE); - } - else - { - rl.rlim_cur = rl.rlim_max; - if (setrlimit(RLIMIT_CORE, &rl) == -1) - log(DEFAULT,"setrlimit() failed, cannot increase coredump size."); - } + log(DEFAULT,"Failed to getrlimit()!"); + return false; + } + else + { + rl.rlim_cur = rl.rlim_max; + if (setrlimit(RLIMIT_CORE, &rl) == -1) + log(DEFAULT,"setrlimit() failed, cannot increase coredump size."); } - return (TRUE); + return true; } @@ -906,6 +954,7 @@ int DaemonSeed (void) * to work with other API functions */ +/* XXX - Needed? */ bool FileExists (const char* file) { FILE *input; @@ -920,549 +969,415 @@ bool FileExists (const char* file) } } -/* ConfProcess does the following things to a config line in the following order: - * - * Processes the line for syntax errors as shown below - * (1) Line void of quotes or equals (a malformed, illegal tag format) - * (2) Odd number of quotes on the line indicating a missing quote - * (3) number of equals signs not equal to number of quotes / 2 (missing an equals sign) - * (4) Spaces between the opening bracket (<) and the keyword - * (5) Spaces between a keyword and an equals sign - * (6) Spaces between an equals sign and a quote - * Removes trailing spaces - * Removes leading spaces - * Converts tabs to spaces - * Turns multiple spaces that are outside of quotes into single spaces - */ - -std::string ServerConfig::ConfProcess(char* buffer, long linenumber, std::stringstream* errorstream, bool &error, std::string filename) +bool ServerConfig::LoadConf(ConfigDataHash &target, const char* filename, std::ostringstream &errorstream) { - long number_of_quotes = 0; - long number_of_equals = 0; - bool has_open_bracket = false; - bool in_quotes = false; - char* trailing; - - error = false; - if (!buffer) + std::ifstream conf(filename); + std::string line; + char ch; + long linenumber; + bool in_tag; + bool in_quote; + bool in_comment; + + linenumber = 1; + in_tag = false; + in_quote = false; + in_comment = false; + + /* Check if the file open failed first */ + if (!conf) { - return ""; + errorstream << "LoadConf: Couldn't open config file: " << filename << std::endl; + return false; } - // firstly clean up the line by stripping spaces from the start and end and converting tabs to spaces - for (char* d = buffer; *d; d++) - if (*d == 9) - *d = ' '; - while (*buffer == ' ') buffer++; - trailing = buffer + strlen(buffer) - 1; - while (*trailing == ' ') *trailing-- = '\0'; - - // empty lines are syntactically valid, as are comments - if (!(*buffer) || buffer[0] == '#') - return ""; - - for (char* c = buffer; *c; c++) + + /* Fix the chmod of the file to restrict it to the current user and group */ + chmod(filename,0600); + + for (unsigned int t = 0; t < include_stack.size(); t++) { - // convert all spaces that are OUTSIDE quotes into hardspace (0xA0) as this will make them easier to - // search and replace later :) - if ((!in_quotes) && (*c == ' ')) - *c = '\xA0'; - if ((*c == '<') && (!in_quotes)) + if (std::string(filename) == include_stack[t]) { - has_open_bracket = true; - if (!(*(buffer+1))) - { - *errorstream << "Tag without identifier at " << filename << ":" << linenumber << endl; - error = true; - return ""; - } - else if ((tolower(*(c+1)) < 'a') || (tolower(*(c+1)) > 'z')) - { - *errorstream << "Invalid characters in identifier at " << filename << ":" << linenumber << endl; - error = true; - return ""; - } + errorstream << "File " << filename << " is included recursively (looped inclusion)." << std::endl; + return false; + } + } + + /* It's not already included, add it to the list of files we've loaded */ + include_stack.push_back(filename); + + /* Start reading characters... */ + while(conf.get(ch)) + { + /* + * Here we try and get individual tags on separate lines, + * this would be so easy if we just made people format + * their config files like that, but they don't so... + * We check for a '<' and then know the line is over when + * we get a '>' not inside quotes. If we find two '<' and + * no '>' then die with an error. + */ + + if((ch == '#') && !in_quote) + in_comment = true; + + if(((ch == '\n') || (ch == '\r')) && in_quote) + { + errorstream << "Got a newline within a quoted section, this is probably a typo: " << filename << ":" << linenumber << std::endl; + return false; } - if (*c == '"') + + switch(ch) { - number_of_quotes++; - in_quotes = (!in_quotes); + case '\n': + linenumber++; + case '\r': + in_comment = false; + case '\0': + continue; + case '\t': + ch = ' '; } - if ((*c == '=') && (!in_quotes)) + + if(in_comment) + continue; + + line += ch; + + if(ch == '<') { - number_of_equals++; - if (*(c+1) == 0) + if(in_tag) { - *errorstream << "Variable without a value at " << filename << ":" << linenumber << endl; - error = true; - return ""; + if(!in_quote) + { + errorstream << "Got another opening < when the first one wasn't closed: " << filename << ":" << linenumber << std::endl; + return false; + } } - else if (*(c+1) != '"') + else { - *errorstream << "Variable name not followed immediately by its value at " << filename << ":" << linenumber << endl; - error = true; - return ""; + if(in_quote) + { + errorstream << "We're in a quote but outside a tag, interesting. " << filename << ":" << linenumber << std::endl; + return false; + } + else + { + // errorstream << "Opening new config tag on line " << linenumber << std::endl; + in_tag = true; + } } - else if (c == buffer) + } + else if(ch == '"') + { + if(in_tag) { - *errorstream << "Value without a variable (line starts with '=') at " << filename << ":" << linenumber << endl; - error = true; - return ""; + if(in_quote) + { + // errorstream << "Closing quote in config tag on line " << linenumber << std::endl; + in_quote = false; + } + else + { + // errorstream << "Opening quote in config tag on line " << linenumber << std::endl; + in_quote = true; + } } - else if (*(c-1) == '\xA0') + else { - *errorstream << "Variable name not followed immediately by its value at " << filename << ":" << linenumber << endl; - error = true; - return ""; + if(in_quote) + { + errorstream << "Found a (closing) \" outside a tag: " << filename << ":" << linenumber << std::endl; + } + else + { + errorstream << "Found a (opening) \" outside a tag: " << filename << ":" << linenumber << std::endl; + } } } - } - // no quotes, and no equals. something freaky. - if ((!number_of_quotes) || (!number_of_equals) && (strlen(buffer)>2) && (*buffer == '<')) - { - *errorstream << "Malformed tag at " << filename << ":" << linenumber << endl; - error = true; - return ""; - } - // odd number of quotes. thats just wrong. - if ((number_of_quotes % 2) != 0) - { - *errorstream << "Missing \" at " << filename << ":" << linenumber << endl; - error = true; - return ""; - } - if (number_of_equals < (number_of_quotes/2)) - { - *errorstream << "Missing '=' at " << filename << ":" << linenumber << endl; - } - if (number_of_equals > (number_of_quotes/2)) - { - *errorstream << "Too many '=' at " << filename << ":" << linenumber << endl; - } - - std::string parsedata = buffer; - // turn multispace into single space - while (parsedata.find("\xA0\xA0") != std::string::npos) - { - parsedata.erase(parsedata.find("\xA0\xA0"),1); - } + else if(ch == '>') + { + if(!in_quote) + { + if(in_tag) + { + // errorstream << "Closing config tag on line " << linenumber << std::endl; + in_tag = false; - // turn our hardspace back into softspace - for (unsigned int d = 0; d < parsedata.length(); d++) - { - if (parsedata[d] == '\xA0') - parsedata[d] = ' '; + /* + * If this finds an then ParseLine can simply call + * LoadConf() and load the included config into the same ConfigDataHash + */ + + if(!this->ParseLine(target, line, linenumber, errorstream)) + return false; + + line.clear(); + } + else + { + errorstream << "Got a closing > when we weren't inside a tag: " << filename << ":" << linenumber << std::endl; + return false; + } + } + } } - - // and we're done, the line is fine! - return parsedata; + + return true; } -int ServerConfig::fgets_safe(char* buffer, size_t maxsize, FILE* &file) +bool ServerConfig::LoadConf(ConfigDataHash &target, const std::string &filename, std::ostringstream &errorstream) { - char c_read = 0; - size_t n = 0; - char* bufptr = buffer; - while ((!feof(file)) && (c_read != '\n') && (c_read != '\r') && (n < maxsize)) - { - c_read = fgetc(file); - if ((c_read != '\n') && (c_read != '\r')) - { - *bufptr++ = c_read; - n++; - } - } - *bufptr = 0; - return bufptr - buffer; + return this->LoadConf(target, filename.c_str(), errorstream); } -bool ServerConfig::LoadConf(const char* filename, std::stringstream *target, std::stringstream* errorstream) +bool ServerConfig::ParseLine(ConfigDataHash &target, std::string &line, long linenumber, std::ostringstream &errorstream) { - target->str(""); - errorstream->str(""); - long linenumber = 1; - // first, check that the file exists before we try to do anything with it - if (!FileExists(filename)) - { - *errorstream << "File " << filename << " not found." << endl; - return false; - } - // Fix the chmod of the file to restrict it to the current user and group - chmod(filename,0600); - for (unsigned int t = 0; t < include_stack.size(); t++) + std::string tagname; + std::string current_key; + std::string current_value; + KeyValList results; + bool got_name; + bool got_key; + bool in_quote; + + got_name = got_key = in_quote = false; + + // std::cout << "ParseLine(data, '" << line << "', " << linenumber << ", stream)" << std::endl; + + for(std::string::iterator c = line.begin(); c != line.end(); c++) { - if (std::string(filename) == include_stack[t]) + if(!got_name) { - *errorstream << "File " << filename << " is included recursively (looped inclusion)." << endl; - return false; + /* We don't know the tag name yet. */ + + if(*c != ' ') + { + if(*c != '<') + { + tagname += *c; + } + } + else + { + /* We got to a space, we should have the tagname now. */ + if(tagname.length()) + { + got_name = true; + } + } } - } - include_stack.push_back(filename); - // now open it - FILE* conf = fopen(filename,"r"); - char buffer[MAXBUF]; - if (conf) - { - while (!feof(conf)) + else { - if (fgets_safe(buffer, MAXBUF, conf)) + /* We have the tag name */ + if(!got_key) { - if ((!feof(conf)) && (buffer) && (*buffer)) + /* We're still reading the key name */ + if(*c != '=') { - if ((buffer[0] != '#') && (buffer[0] != '\r') && (buffer[0] != '\n')) + if(*c != ' ') { - if (!strncmp(buffer," " << current_value << std::endl; + + in_quote = false; + got_key = false; + + if((tagname == "include") && (current_key == "file")) { - bool error = false; - std::string data = this->ConfProcess(buffer,linenumber++,errorstream,error,filename); - if (error) - { + if(!this->DoInclude(target, current_value, errorstream)) return false; - } - *target << data; } + + current_key.clear(); + current_value.clear(); + } + } + else + { + if(in_quote) + { + current_value += *c; } - else linenumber++; } } } - fclose(conf); } - target->seekg(0); + + /* Finished parsing the tag, add it to the config hash */ + target.insert(std::pair (tagname, results)); + return true; } -/* Counts the number of tags of a certain type within the config file, e.g. to enumerate opers */ - -int ServerConfig::EnumConf(std::stringstream *config, const char* tag) +bool ServerConfig::DoInclude(ConfigDataHash &target, const std::string &file, std::ostringstream &errorstream) { - int ptr = 0; - char buffer[MAXBUF], c_tag[MAXBUF], c, lastc; - int in_token, in_quotes, tptr, idx = 0; - - std::string x = config->str(); - const char* buf = x.c_str(); - char* bptr = (char*)buf; + std::string confpath; + std::string newfile; + std::string::size_type pos; + + confpath = CONFIG_FILE; + newfile = file; - ptr = 0; - in_token = 0; - in_quotes = 0; - lastc = '\0'; - while (*bptr) + for (std::string::iterator c = newfile.begin(); c != newfile.end(); c++) { - lastc = c; - c = *bptr++; - if ((c == '#') && (lastc == '\n')) - { - while ((c != '\n') && (*bptr)) - { - lastc = c; - c = *bptr++; - } - } - if ((c == '<') && (!in_quotes)) + if (*c == '\\') { - tptr = 0; - in_token = 1; - do { - c = *bptr++; - if (c != ' ') - { - c_tag[tptr++] = c; - c_tag[tptr] = '\0'; - } - } while (c != ' '); + *c = '/'; } - if (c == '"') - { - in_quotes = (!in_quotes); - } - if ((c == '>') && (!in_quotes)) + } + + if (file[0] != '/') + { + if((pos = confpath.find("/inspircd.conf")) != std::string::npos) { - in_token = 0; - if (!strcmp(c_tag,tag)) - { - /* correct tag, but wrong index */ - idx++; - } - c_tag[0] = '\0'; - buffer[0] = '\0'; - ptr = 0; - tptr = 0; + /* Leaves us with just the path */ + newfile = confpath.substr(0, pos) + std::string("/") + newfile; } - if (c != '>') + else { - if ((in_token) && (c != '\n') && (c != '\r')) - { - buffer[ptr++] = c; - buffer[ptr] = '\0'; - } + errorstream << "Couldn't get config path from: " << confpath << std::endl; + return false; } } - return idx; + + return LoadConf(target, newfile, errorstream); } -/* Counts the number of values within a certain tag */ +bool ServerConfig::ConfValue(ConfigDataHash &target, const char* tag, const char* var, int index, char* result, int length) +{ + std::string value; + bool r = ConfValue(target, std::string(tag), std::string(var), index, value); + strlcpy(result, value.c_str(), length); + return r; +} -int ServerConfig::EnumValues(std::stringstream *config, const char* tag, int index) +bool ServerConfig::ConfValue(ConfigDataHash &target, const std::string &tag, const std::string &var, int index, std::string &result) { - int ptr = 0; - char buffer[MAXBUF], c_tag[MAXBUF], c, lastc; - int in_token, in_quotes, tptr, idx = 0; - bool correct_tag = false; - int num_items = 0; - const char* buf = config->str().c_str(); - char* bptr = (char*)buf; - - ptr = 0; - in_token = 0; - in_quotes = 0; - lastc = 0; - - while (*bptr) + ConfigDataHash::size_type pos = index; + if((pos >= 0) && (pos < target.count(tag))) { - lastc = c; - c = *bptr++; - if ((c == '#') && (lastc == '\n')) - { - while ((c != '\n') && (*bptr)) - { - lastc = c; - c = *bptr++; - } - } - if ((c == '<') && (!in_quotes)) - { - tptr = 0; - in_token = 1; - do { - c = *bptr++; - if (c != ' ') - { - c_tag[tptr++] = c; - c_tag[tptr] = '\0'; - - if ((!strcmp(c_tag,tag)) && (idx == index)) - { - correct_tag = true; - } - } - } while (c != ' '); - } - if (c == '"') - { - in_quotes = (!in_quotes); - } + ConfigDataHash::const_iterator iter = target.find(tag); - if ( (correct_tag) && (!in_quotes) && ( (c == ' ') || (c == '\n') || (c == '\r') ) ) - { - num_items++; - } - if ((c == '>') && (!in_quotes)) - { - in_token = 0; - if (correct_tag) - correct_tag = false; - if (!strcmp(c_tag,tag)) - { - /* correct tag, but wrong index */ - idx++; - } - c_tag[0] = '\0'; - buffer[0] = '\0'; - ptr = 0; - tptr = 0; - } - if (c != '>') + for(int i = 0; i < index; i++) + iter++; + + for(KeyValList::const_iterator j = iter->second.begin(); j != iter->second.end(); j++) { - if ((in_token) && (c != '\n') && (c != '\r')) + if(j->first == var) { - buffer[ptr++] = c; - buffer[ptr] = '\0'; + result = j->second; + return true; } } } - return num_items+1; + else + { + log(DEBUG, "ConfValue got an out-of-range index %d", pos); + } + + return false; } - - -int ServerConfig::ConfValueEnum(char* tag, std::stringstream* config) + +bool ServerConfig::ConfValueInteger(ConfigDataHash &target, const char* tag, const char* var, int index, int &result) { - return EnumConf(config,tag); + return ConfValueInteger(target, std::string(tag), std::string(var), index, result); } - -int ServerConfig::ReadConf(std::stringstream *config, const char* tag, const char* var, int index, char *result) +bool ServerConfig::ConfValueInteger(ConfigDataHash &target, const std::string &tag, const std::string &var, int index, int &result) { - int ptr = 0; - char buffer[65535], c_tag[MAXBUF], c, lastc; - int in_token, in_quotes, tptr, idx = 0; - char* key; - std::string x = config->str(); - const char* buf = x.c_str(); - char* bptr = (char*)buf; + std::string value; + std::istringstream stream; + bool r = ConfValue(target, tag, var, index, value); + stream.str(value); + if(!(stream >> result)) + return false; + return r; +} - ptr = 0; - in_token = 0; - in_quotes = 0; - lastc = 0; - c_tag[0] = 0; - buffer[0] = 0; - - while (*bptr) - { - lastc = c; - c = *bptr++; - // FIX: Treat tabs as spaces - if (c == 9) - c = 32; - if ((c == '<') && (!in_quotes)) - { - tptr = 0; - in_token = 1; - do { - c = *bptr++; - if (c != ' ') - { - c_tag[tptr++] = c; - c_tag[tptr] = '\0'; - } - // FIX: Tab can follow a tagname as well as space. - } while ((c != ' ') && (c != 9)); - } - if (c == '"') - { - in_quotes = (!in_quotes); - } - if ((c == '>') && (!in_quotes)) - { - in_token = 0; - if (idx == index) - { - if (!strcmp(c_tag,tag)) - { - if ((buffer) && (c_tag) && (var)) - { - key = strstr(buffer,var); - if (!key) - { - /* value not found in tag */ - *result = 0; - return 0; - } - else - { - key+=strlen(var); - while (*key !='"') - { - if (!*key) - { - /* missing quote */ - *result = 0; - return 0; - } - key++; - } - key++; - for (char* j = key; *j; j++) - { - if (*j == '"') - { - *j = 0; - break; - } - } - strlcpy(result,key,MAXBUF); - return 1; - } - } - } - } - if (!strcmp(c_tag,tag)) - { - /* correct tag, but wrong index */ - idx++; - } - c_tag[0] = '\0'; - buffer[0] = '\0'; - ptr = 0; - tptr = 0; - } - if (c != '>') - { - if ((in_token) && (c != '\n') && (c != '\r')) - { - buffer[ptr++] = c; - buffer[ptr] = '\0'; - } - } - } - *result = 0; // value or its tag not found at all - return 0; +bool ServerConfig::ConfValueBool(ConfigDataHash &target, const char* tag, const char* var, int index) +{ + return ConfValueBool(target, std::string(tag), std::string(var), index); } +bool ServerConfig::ConfValueBool(ConfigDataHash &target, const std::string &tag, const std::string &var, int index) +{ + std::string result; + if(!ConfValue(target, tag, var, index, result)) + return false; + + return ((result == "yes") || (result == "true") || (result == "1")); +} + +int ServerConfig::ConfValueEnum(ConfigDataHash &target, const char* tag) +{ + return ConfValueEnum(target, std::string(tag)); +} - -int ServerConfig::ConfValue(char* tag, char* var, int index, char *result,std::stringstream *config) +int ServerConfig::ConfValueEnum(ConfigDataHash &target, const std::string &tag) { - ReadConf(config, tag, var, index, result); - return 0; + return target.count(tag); +} + +int ServerConfig::ConfVarEnum(ConfigDataHash &target, const char* tag, int index) +{ + return 1; } -int ServerConfig::ConfValueInteger(char* tag, char* var, int index, std::stringstream *config) +int ServerConfig::ConfVarEnum(ConfigDataHash &target, const std::string &tag, int index) { - char result[MAXBUF]; - ReadConf(config, tag, var, index, result); - return atoi(result); + ConfigDataHash::size_type pos = index; + + if((pos >= 0) && (pos < target.count(tag))) + { + ConfigDataHash::const_iterator iter = target.find(tag); + + for(int i = 0; i < index; i++) + iter++; + + return iter->second.size(); + } + else + { + log(DEBUG, "ConfVarEnum got an out-of-range index %d", pos); + } + + return 0; } -// This will bind a socket to a port. It works for UDP/TCP -int BindSocket (int sockfd, struct sockaddr_in client, struct sockaddr_in server, int port, char* addr) +/** This will bind a socket to a port. It works for UDP/TCP. + * If a hostname is given to bind to, the function will first + * attempt to resolve the hostname, then bind to the IP the + * hostname resolves to. This is a blocking lookup blocking for + * a maximum of one second before it times out, using the DNS + * server specified in the configuration file. + */ +bool BindSocket(int sockfd, struct sockaddr_in client, struct sockaddr_in server, int port, char* addr) { - memset((char *)&server,0,sizeof(server)); + memset(&server,0,sizeof(server)); struct in_addr addy; bool resolved = false; char resolved_addr[128]; @@ -1483,7 +1398,7 @@ int BindSocket (int sockfd, struct sockaddr_in client, struct sockaddr_in server else { log(DEFAULT,"WARNING: Could not resolve '%s' to an IP for binding to on port %d",addr,port); - return(FALSE); + return false; } } server.sin_family = AF_INET; @@ -1501,7 +1416,7 @@ int BindSocket (int sockfd, struct sockaddr_in client, struct sockaddr_in server server.sin_port = htons(port); if (bind(sockfd,(struct sockaddr*)&server,sizeof(server)) < 0) { - return(ERROR); + return false; } else { @@ -1509,48 +1424,117 @@ int BindSocket (int sockfd, struct sockaddr_in client, struct sockaddr_in server if (listen(sockfd, Config->MaxConn) == -1) { log(DEFAULT,"ERROR in listen(): %s",strerror(errno)); - return(FALSE); + return false; } else { - return(TRUE); + NonBlocking(sockfd); + return true; } } } // Open a TCP Socket -int OpenTCPSocket (void) +int OpenTCPSocket() { int sockfd; int on = 1; struct linger linger = { 0 }; if ((sockfd = socket (AF_INET, SOCK_STREAM, 0)) < 0) + { + log(DEFAULT,"Error creating TCP socket: %s",strerror(errno)); return (ERROR); + } else { - setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, (const char*)&on, sizeof(on)); + setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)); /* This is BSD compatible, setting l_onoff to 0 is *NOT* http://web.irc.org/mla/ircd-dev/msg02259.html */ linger.l_onoff = 1; linger.l_linger = 1; - setsockopt(sockfd, SOL_SOCKET, SO_LINGER, (const char*)&linger,sizeof(linger)); + setsockopt(sockfd, SOL_SOCKET, SO_LINGER, &linger,sizeof(linger)); return (sockfd); } } -int BindPorts() +bool HasPort(int port, char* addr) +{ + for (int count = 0; count < ServerInstance->stats->BoundPortCount; count++) + { + if ((port == Config->ports[count]) && (!strcasecmp(Config->addrs[count],addr))) + { + return true; + } + } + return false; +} + +int BindPorts(bool bail) { char configToken[MAXBUF], Addr[MAXBUF], Type[MAXBUF]; sockaddr_in client,server; int clientportcount = 0; int BoundPortCount = 0; - for (int count = 0; count < Config->ConfValueEnum("bind",&Config->config_f); count++) + if (!bail) + { + int InitialPortCount = ServerInstance->stats->BoundPortCount; + log(DEBUG,"Initial port count: %d",InitialPortCount); + + for (int count = 0; count < Config->ConfValueEnum(Config->config_data, "bind"); count++) + { + Config->ConfValue(Config->config_data, "bind", "port", count, configToken, MAXBUF); + Config->ConfValue(Config->config_data, "bind", "address", count, Addr, MAXBUF); + Config->ConfValue(Config->config_data, "bind", "type", count, Type, MAXBUF); + + if (((!*Type) || (!strcmp(Type,"clients"))) && (!HasPort(atoi(configToken),Addr))) + { + // modules handle server bind types now + Config->ports[clientportcount+InitialPortCount] = atoi(configToken); + if (*Addr == '*') + *Addr = 0; + + strlcpy(Config->addrs[clientportcount+InitialPortCount],Addr,256); + clientportcount++; + log(DEBUG,"NEW binding %s:%s [%s] from config",Addr,configToken, Type); + } + } + int PortCount = clientportcount; + if (PortCount) + { + for (int count = InitialPortCount; count < InitialPortCount + PortCount; count++) + { + if ((openSockfd[count] = OpenTCPSocket()) == ERROR) + { + log(DEBUG,"Bad fd %d binding port [%s:%d]",openSockfd[count],Config->addrs[count],Config->ports[count]); + return ERROR; + } + if (!BindSocket(openSockfd[count],client,server,Config->ports[count],Config->addrs[count])) + { + log(DEFAULT,"Failed to bind port [%s:%d]: %s",Config->addrs[count],Config->ports[count],strerror(errno)); + } + else + { + /* Associate the new open port with a slot in the socket engine */ + ServerInstance->SE->AddFd(openSockfd[count],true,X_LISTEN); + BoundPortCount++; + } + } + return InitialPortCount + BoundPortCount; + } + else + { + log(DEBUG,"There is nothing new to bind!"); + } + return InitialPortCount; + } + + for (int count = 0; count < Config->ConfValueEnum(Config->config_data, "bind"); count++) { - Config->ConfValue("bind","port",count,configToken,&Config->config_f); - Config->ConfValue("bind","address",count,Addr,&Config->config_f); - Config->ConfValue("bind","type",count,Type,&Config->config_f); + Config->ConfValue(Config->config_data, "bind", "port", count, configToken, MAXBUF); + Config->ConfValue(Config->config_data, "bind", "address", count, Addr, MAXBUF); + Config->ConfValue(Config->config_data, "bind", "type", count, Type, MAXBUF); if ((!*Type) || (!strcmp(Type,"clients"))) { @@ -1566,7 +1550,7 @@ int BindPorts() strlcpy(Config->addrs[clientportcount],Addr,256); clientportcount++; - log(DEBUG,"InspIRCd: startup: read binding %s:%s [%s] from config",Addr,configToken, Type); + log(DEBUG,"Binding %s:%s [%s] from config",Addr,configToken, Type); } } @@ -1576,13 +1560,13 @@ int BindPorts() { if ((openSockfd[BoundPortCount] = OpenTCPSocket()) == ERROR) { - log(DEBUG,"InspIRCd: startup: bad fd %lu binding port [%s:%d]",(unsigned long)openSockfd[BoundPortCount],Config->addrs[count],(unsigned long)Config->ports[count]); - return(ERROR); + log(DEBUG,"Bad fd %d binding port [%s:%d]",openSockfd[BoundPortCount],Config->addrs[count],Config->ports[count]); + return ERROR; } - if (BindSocket(openSockfd[BoundPortCount],client,server,Config->ports[count],Config->addrs[count]) == ERROR) + if (!BindSocket(openSockfd[BoundPortCount],client,server,Config->ports[count],Config->addrs[count])) { - log(DEFAULT,"InspIRCd: startup: failed to bind port [%s:%lu]: %s",Config->addrs[count],(unsigned long)Config->ports[count],strerror(errno)); + log(DEFAULT,"Failed to bind port [%s:%d]: %s",Config->addrs[count],Config->ports[count],strerror(errno)); } else { @@ -1594,11 +1578,10 @@ int BindPorts() /* if we didn't bind to anything then abort */ if (!BoundPortCount) { - log(DEFAULT,"InspIRCd: startup: no ports bound, bailing!"); - printf("\nERROR: Was not able to bind any of %lu ports! Please check your configuration.\n\n", (unsigned long)PortCount); - return (ERROR); + log(DEFAULT,"No ports bound, bailing!"); + printf("\nERROR: Could not bind any of %d ports! Please check your configuration.\n\n", PortCount); + return ERROR; } return BoundPortCount; } -