2 * InspIRCd -- Internet Relay Chat Daemon
4 * Copyright (C) 2009-2010 Daniel De Graaf <danieldg@inspircd.org>
5 * Copyright (C) 2006-2008 Robin Burchell <robin+git@viroteck.net>
6 * Copyright (C) 2005-2008 Craig Edwards <craigedwards@brainbox.cc>
7 * Copyright (C) 2008 Thomas Stagner <aquanight@inspircd.org>
8 * Copyright (C) 2006-2007 Oliver Lupton <oliverlupton@gmail.com>
9 * Copyright (C) 2007 Dennis Friis <peavey@inspircd.org>
11 * This file is part of InspIRCd. InspIRCd is free software: you can
12 * redistribute it and/or modify it under the terms of the GNU General Public
13 * License as published by the Free Software Foundation, version 2.
15 * This program is distributed in the hope that it will be useful, but WITHOUT
16 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
17 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
20 * You should have received a copy of the GNU General Public License
21 * along with this program. If not, see <http://www.gnu.org/licenses/>.
32 #include "exitcodes.h"
35 /* Find a user record by nickname and return a pointer to it */
36 User* InspIRCd::FindNick(const std::string &nick)
38 if (!nick.empty() && isdigit(*nick.begin()))
39 return FindUUID(nick);
40 return FindNickOnly(nick);
43 User* InspIRCd::FindNickOnly(const std::string &nick)
45 user_hash::iterator iter = this->Users->clientlist.find(nick);
47 if (iter == this->Users->clientlist.end())
53 User *InspIRCd::FindUUID(const std::string &uid)
55 user_hash::iterator finduuid = this->Users->uuidlist.find(uid);
57 if (finduuid == this->Users->uuidlist.end())
60 return finduuid->second;
62 /* find a channel record by channel name and return a pointer to it */
64 Channel* InspIRCd::FindChan(const std::string &chan)
66 chan_hash::iterator iter = chanlist.find(chan);
68 if (iter == chanlist.end())
69 /* Couldn't find it */
75 bool InspIRCd::IsValidMask(const std::string &mask)
77 const char* dest = mask.c_str();
81 for (const char* i = dest; *i; i++)
83 /* out of range character, bad mask */
84 if (*i < 32 || *i > 126)
100 /* valid masks only have 1 ! and @ */
101 if (exclamation != 1 || atsign != 1)
104 if (mask.length() > ServerInstance->Config->Limits.GetMaxMask())
110 void InspIRCd::StripColor(std::string &sentence)
112 /* refactor this completely due to SQUIT bug since the old code would strip last char and replace with \0 --peavey */
115 for (std::string::iterator i = sentence.begin(); i != sentence.end();)
119 else if (seq && (( ((*i >= '0') && (*i <= '9')) || (*i == ',') ) ))
122 if ( (seq <= 4) && (*i == ',') )
130 // Strip all control codes too except \001 for CTCP
131 if (seq || ((*i >= 0) && (*i < 32) && (*i != 1)))
132 i = sentence.erase(i);
138 void InspIRCd::ProcessColors(file_cache& input)
141 * Replace all color codes from the special[] array to actual
142 * color code chars using C++ style escape sequences. You
143 * can append other chars to replace if you like -- Justasic
145 static struct special_chars
147 std::string character;
149 special_chars(const std::string& c, const std::string& r)
155 special_chars("\\b", "\x02"), // Bold
156 special_chars("\\c", "\x03"), // Color
157 special_chars("\\i", "\x1D"), // Italic
158 special_chars("\\m", "\x11"), // Monospace
159 special_chars("\\s", "\x1E"), // Strikethrough
160 special_chars("\\u", "\x1F"), // Underline
161 special_chars("\\x", "\x0F"), // Reset
162 special_chars("\\", "")
165 for(file_cache::iterator it = input.begin(), it_end = input.end(); it != it_end; it++)
167 std::string ret = *it;
168 for(int i = 0; special[i].character.empty() == false; ++i)
170 std::string::size_type pos = ret.find(special[i].character);
171 if(pos == std::string::npos) // Couldn't find the character, skip this line
174 if((pos > 0) && (ret[pos-1] == '\\') && (ret[pos] == '\\'))
175 continue; // Skip double slashes.
177 // Replace all our characters in the array
178 while(pos != std::string::npos)
180 ret = ret.substr(0, pos) + special[i].replace + ret.substr(pos + special[i].character.size());
181 pos = ret.find(special[i].character, pos + special[i].replace.size());
185 // Replace double slashes with a single slash before we return
186 std::string::size_type pos = ret.find("\\\\");
187 while(pos != std::string::npos)
189 ret = ret.substr(0, pos) + "\\" + ret.substr(pos + 2);
190 pos = ret.find("\\\\", pos + 1);
196 /* true for valid channel name, false else */
197 bool InspIRCd::DefaultIsChannel(const std::string& chname)
199 if (chname.empty() || chname.length() > ServerInstance->Config->Limits.ChanMax)
202 if (chname[0] != '#')
205 for (std::string::const_iterator i = chname.begin()+1; i != chname.end(); ++i)
219 /* true for valid nickname, false else */
220 bool InspIRCd::DefaultIsNick(const std::string& n)
222 if (n.empty() || n.length() > ServerInstance->Config->Limits.NickMax)
225 for (std::string::const_iterator i = n.begin(); i != n.end(); ++i)
227 if ((*i >= 'A') && (*i <= '}'))
229 /* "A"-"}" can occur anywhere in a nickname */
233 if ((((*i >= '0') && (*i <= '9')) || (*i == '-')) && (i != n.begin()))
235 /* "0"-"9", "-" can occur anywhere BUT the first char of a nickname */
239 /* invalid character! abort */
246 /* return true for good ident, false else */
247 bool InspIRCd::DefaultIsIdent(const std::string& n)
252 for (std::string::const_iterator i = n.begin(); i != n.end(); ++i)
254 if ((*i >= 'A') && (*i <= '}'))
259 if (((*i >= '0') && (*i <= '9')) || (*i == '-') || (*i == '.'))
270 bool InspIRCd::IsHost(const std::string& host)
272 // Hostnames must be non-empty and shorter than the maximum hostname length.
273 if (host.empty() || host.length() > ServerInstance->Config->Limits.MaxHost)
276 unsigned int numdashes = 0;
277 unsigned int numdots = 0;
278 bool seendot = false;
279 const std::string::const_iterator hostend = host.end() - 1;
280 for (std::string::const_iterator iter = host.begin(); iter != host.end(); ++iter)
282 unsigned char chr = static_cast<unsigned char>(*iter);
284 // If the current character is a label separator.
289 // Consecutive separators are not allowed and dashes can not exist at the start or end
290 // of labels and separators must only exist between labels.
291 if (seendot || numdashes || iter == host.begin() || iter == hostend)
298 // If this point is reached then the character is not a dot.
301 // If the current character is a dash.
304 // Consecutive separators are not allowed and dashes can not exist at the start or end
305 // of labels and separators must only exist between labels.
306 if (seendot || numdashes >= 2 || iter == host.begin() || iter == hostend)
313 // If this point is reached then the character is not a dash.
316 // Alphanumeric characters are allowed at any position.
317 if ((chr >= '0' && chr <= '9') || (chr >= 'A' && chr <= 'Z') || (chr >= 'a' && chr <= 'z'))
323 // Whilst simple hostnames (e.g. localhost) are valid we do not allow the server to use
324 // them to prevent issues with clients that differentiate between short client and server
325 // prefixes by checking whether the nickname contains a dot.
329 bool InspIRCd::IsSID(const std::string &str)
331 /* Returns true if the string given is exactly 3 characters long,
332 * starts with a digit, and the other two characters are A-Z or digits
334 return ((str.length() == 3) && isdigit(str[0]) &&
335 ((str[1] >= 'A' && str[1] <= 'Z') || isdigit(str[1])) &&
336 ((str[2] >= 'A' && str[2] <= 'Z') || isdigit(str[2])));
339 void InspIRCd::CheckRoot()
344 std::cout << "ERROR: You are running an irc server as root! DO NOT DO THIS!" << std::endl << std::endl;
345 this->Logs->Log("STARTUP", LOG_DEFAULT, "Can't start as root");
346 Exit(EXIT_STATUS_ROOT);
351 /** Refactored by Brain, Jun 2009. Much faster with some clever O(1) array
352 * lookups and pointer maths.
354 unsigned long InspIRCd::Duration(const std::string &str)
356 unsigned char multiplier = 0;
361 /* Iterate each item in the string, looking for number or multiplier */
362 for (std::string::const_reverse_iterator i = str.rbegin(); i != str.rend(); ++i)
364 /* Found a number, queue it onto the current number */
365 if ((*i >= '0') && (*i <= '9'))
367 subtotal = subtotal + ((*i - '0') * times);
372 /* Found something thats not a number, find out how much
373 * it multiplies the built up number by, multiply the total
374 * and reset the built up number.
377 total += subtotal * duration_multi[multiplier];
379 /* Next subtotal please */
387 total += subtotal * duration_multi[multiplier];
390 /* Any trailing values built up are treated as raw seconds */
391 return total + subtotal;
394 std::string InspIRCd::Format(va_list& vaList, const char* formatString)
396 static std::vector<char> formatBuffer(1024);
401 va_copy(dst, vaList);
403 int vsnret = vsnprintf(&formatBuffer[0], formatBuffer.size(), formatString, dst);
406 if (vsnret > 0 && static_cast<unsigned>(vsnret) < formatBuffer.size())
411 formatBuffer.resize(formatBuffer.size() * 2);
414 return std::string(&formatBuffer[0]);
417 std::string InspIRCd::Format(const char* formatString, ...)
420 VAFORMAT(ret, formatString, formatString);
424 std::string InspIRCd::TimeString(time_t curtime, const char* format, bool utc)
431 struct tm* timeinfo = utc ? gmtime(&curtime) : localtime(&curtime);
435 timeinfo = localtime(&curtime);
438 // If the calculated year exceeds four digits or is less than the year 1000,
439 // the behavior of asctime() is undefined
440 if (timeinfo->tm_year + 1900 > 9999)
441 timeinfo->tm_year = 9999 - 1900;
442 else if (timeinfo->tm_year + 1900 < 1000)
443 timeinfo->tm_year = 0;
445 // This is the default format used by asctime without the terminating new line.
447 format = "%a %b %d %Y %H:%M:%S";
450 if (!strftime(buffer, sizeof(buffer), format, timeinfo))
456 std::string InspIRCd::GenRandomStr(unsigned int length, bool printable)
458 char* buf = new char[length];
459 GenRandom(buf, length);
462 for(size_t i = 0; i < length; i++)
463 rv[i] = printable ? 0x3F + (buf[i] & 0x3F) : buf[i];
468 // NOTE: this has a slight bias for lower values if max is not a power of 2.
469 // Don't use it if that matters.
470 unsigned long InspIRCd::GenRandomInt(unsigned long max)
473 GenRandom((char*)&rv, sizeof(rv));
477 // This is overridden by a higher-quality algorithm when SSL support is loaded
478 void InspIRCd::DefaultGenRandom(char* output, size_t max)
480 #if defined HAS_ARC4RANDOM_BUF
481 arc4random_buf(output, max);
483 for (unsigned int i = 0; i < max; ++i)
487 if(rand_s(&uTemp) != 0)
493 output[i] = random();