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/>.
34 #include "exitcodes.h"
37 std::string InspIRCd::GetServerDescription(const std::string& servername)
39 std::string description;
41 FOREACH_MOD(I_OnGetServerDescription,OnGetServerDescription(servername,description));
43 if (!description.empty())
49 // not a remote server that can be found, it must be me.
50 return Config->ServerDesc;
54 /* Find a user record by nickname and return a pointer to it */
55 User* InspIRCd::FindNick(const std::string &nick)
57 if (!nick.empty() && isdigit(*nick.begin()))
58 return FindUUID(nick);
60 user_hash::iterator iter = this->Users->clientlist->find(nick);
62 if (iter == this->Users->clientlist->end())
63 /* Couldn't find it */
69 User* InspIRCd::FindNick(const char* nick)
72 return FindUUID(nick);
74 user_hash::iterator iter = this->Users->clientlist->find(nick);
76 if (iter == this->Users->clientlist->end())
82 User* InspIRCd::FindNickOnly(const std::string &nick)
84 user_hash::iterator iter = this->Users->clientlist->find(nick);
86 if (iter == this->Users->clientlist->end())
92 User* InspIRCd::FindNickOnly(const char* nick)
94 user_hash::iterator iter = this->Users->clientlist->find(nick);
96 if (iter == this->Users->clientlist->end())
102 User *InspIRCd::FindUUID(const std::string &uid)
104 user_hash::iterator finduuid = this->Users->uuidlist->find(uid);
106 if (finduuid == this->Users->uuidlist->end())
109 return finduuid->second;
112 User *InspIRCd::FindUUID(const char *uid)
114 return FindUUID(std::string(uid));
117 /* find a channel record by channel name and return a pointer to it */
118 Channel* InspIRCd::FindChan(const char* chan)
120 chan_hash::iterator iter = chanlist->find(chan);
122 if (iter == chanlist->end())
123 /* Couldn't find it */
129 Channel* InspIRCd::FindChan(const std::string &chan)
131 chan_hash::iterator iter = chanlist->find(chan);
133 if (iter == chanlist->end())
134 /* Couldn't find it */
140 /* Send an error notice to all users, registered or not */
141 void InspIRCd::SendError(const std::string &s)
143 for (LocalUserList::const_iterator i = this->Users->local_users.begin(); i != this->Users->local_users.end(); i++)
146 if (u->registered == REG_ALL)
148 u->WriteServ("NOTICE %s :%s",u->nick.c_str(),s.c_str());
152 /* Unregistered connections receive ERROR, not a NOTICE */
153 u->Write("ERROR :" + s);
158 /* return channel count */
159 long InspIRCd::ChannelCount()
161 return chanlist->size();
164 bool InspIRCd::IsValidMask(const std::string &mask)
166 const char* dest = mask.c_str();
170 for (const char* i = dest; *i; i++)
172 /* out of range character, bad mask */
173 if (*i < 32 || *i > 126)
189 /* valid masks only have 1 ! and @ */
190 if (exclamation != 1 || atsign != 1)
193 if (mask.length() > 250)
199 void InspIRCd::StripColor(std::string &sentence)
201 /* refactor this completely due to SQUIT bug since the old code would strip last char and replace with \0 --peavey */
204 for (std::string::iterator i = sentence.begin(); i != sentence.end();)
208 else if (seq && (( ((*i >= '0') && (*i <= '9')) || (*i == ',') ) ))
211 if ( (seq <= 4) && (*i == ',') )
219 if (seq || ((*i == 2) || (*i == 15) || (*i == 22) || (*i == 21) || (*i == 31)))
220 i = sentence.erase(i);
226 void InspIRCd::ProcessColors(file_cache& input)
229 * Replace all color codes from the special[] array to actual
230 * color code chars using C++ style escape sequences. You
231 * can append other chars to replace if you like -- Justasic
233 static struct special_chars
235 std::string character;
237 special_chars(const std::string &c, const std::string &r) : character(c), replace(r) { }
241 special_chars("\\002", "\002"), // Bold
242 special_chars("\\037", "\037"), // underline
243 special_chars("\\003", "\003"), // Color
244 special_chars("\\017", "\017"), // Stop colors
245 special_chars("\\u", "\037"), // Alias for underline
246 special_chars("\\b", "\002"), // Alias for Bold
247 special_chars("\\x", "\017"), // Alias for stop
248 special_chars("\\c", "\003"), // Alias for color
249 special_chars("", "")
252 for(file_cache::iterator it = input.begin(), it_end = input.end(); it != it_end; it++)
254 std::string ret = *it;
255 for(int i = 0; special[i].character.empty() == false; ++i)
257 std::string::size_type pos = ret.find(special[i].character);
258 if(pos == std::string::npos) // Couldn't find the character, skip this line
261 if((pos > 0) && (ret[pos-1] == '\\') && (ret[pos] == '\\'))
262 continue; // Skip double slashes.
264 // Replace all our characters in the array
265 while(pos != std::string::npos)
267 ret = ret.substr(0, pos) + special[i].replace + ret.substr(pos + special[i].character.size());
268 pos = ret.find(special[i].character, pos + special[i].replace.size());
272 // Replace double slashes with a single slash before we return
273 std::string::size_type pos = ret.find("\\\\");
274 while(pos != std::string::npos)
276 ret = ret.substr(0, pos) + "\\" + ret.substr(pos + 2);
277 pos = ret.find("\\\\", pos + 1);
283 /* true for valid channel name, false else */
284 bool IsChannelHandler::Call(const std::string& chname, size_t max)
286 if (chname.empty() || chname.length() > max)
289 if (chname[0] != '#')
292 for (std::string::const_iterator i = chname.begin()+1; i != chname.end(); ++i)
306 /* true for valid nickname, false else */
307 bool IsNickHandler::Call(const std::string& n, size_t max)
309 if (n.empty() || n.length() > max)
312 for (std::string::const_iterator i = n.begin(); i != n.end(); ++i)
314 if ((*i >= 'A') && (*i <= '}'))
316 /* "A"-"}" can occur anywhere in a nickname */
320 if ((((*i >= '0') && (*i <= '9')) || (*i == '-')) && (i != n.begin()))
322 /* "0"-"9", "-" can occur anywhere BUT the first char of a nickname */
326 /* invalid character! abort */
333 /* return true for good ident, false else */
334 bool IsIdentHandler::Call(const std::string& n)
339 for (std::string::const_iterator i = n.begin(); i != n.end(); ++i)
341 if ((*i >= 'A') && (*i <= '}'))
346 if (((*i >= '0') && (*i <= '9')) || (*i == '-') || (*i == '.'))
357 bool InspIRCd::IsSID(const std::string &str)
359 /* Returns true if the string given is exactly 3 characters long,
360 * starts with a digit, and the other two characters are A-Z or digits
362 return ((str.length() == 3) && isdigit(str[0]) &&
363 ((str[1] >= 'A' && str[1] <= 'Z') || isdigit(str[1])) &&
364 ((str[2] >= 'A' && str[2] <= 'Z') || isdigit(str[2])));
367 /* open the proper logfile */
368 bool InspIRCd::OpenLog(char**, int)
370 if (!Config->cmdline.writelog) return true; // Skip opening default log if -nolog
372 if (Config->cmdline.startup_log.empty())
373 Config->cmdline.startup_log = LOG_PATH "/startup.log";
374 FILE* startup = fopen(Config->cmdline.startup_log.c_str(), "a+");
381 FileWriter* fw = new FileWriter(startup);
382 FileLogStream *f = new FileLogStream((Config->cmdline.forcedebug ? DEBUG : DEFAULT), fw);
384 this->Logs->AddLogType("*", f, true);
389 void InspIRCd::CheckRoot()
394 std::cout << "ERROR: You are running an irc server as root! DO NOT DO THIS!" << std::endl << std::endl;
395 this->Logs->Log("STARTUP",DEFAULT,"Can't start as root");
396 Exit(EXIT_STATUS_ROOT);
401 void InspIRCd::SendWhoisLine(User* user, User* dest, int numeric, const std::string &text)
403 std::string copy_text = text;
405 ModResult MOD_RESULT;
406 FIRST_MOD_RESULT(OnWhoisLine, MOD_RESULT, (user, dest, numeric, copy_text));
408 if (MOD_RESULT != MOD_RES_DENY)
409 user->WriteServ("%d %s", numeric, copy_text.c_str());
412 void InspIRCd::SendWhoisLine(User* user, User* dest, int numeric, const char* format, ...)
414 char textbuffer[MAXBUF];
416 va_start (argsPtr, format);
417 vsnprintf(textbuffer, MAXBUF, format, argsPtr);
420 this->SendWhoisLine(user, dest, numeric, std::string(textbuffer));
423 /** Refactored by Brain, Jun 2009. Much faster with some clever O(1) array
424 * lookups and pointer maths.
426 long InspIRCd::Duration(const std::string &str)
428 unsigned char multiplier = 0;
433 /* Iterate each item in the string, looking for number or multiplier */
434 for (std::string::const_reverse_iterator i = str.rbegin(); i != str.rend(); ++i)
436 /* Found a number, queue it onto the current number */
437 if ((*i >= '0') && (*i <= '9'))
439 subtotal = subtotal + ((*i - '0') * times);
444 /* Found something thats not a number, find out how much
445 * it multiplies the built up number by, multiply the total
446 * and reset the built up number.
449 total += subtotal * duration_multi[multiplier];
451 /* Next subtotal please */
459 total += subtotal * duration_multi[multiplier];
462 /* Any trailing values built up are treated as raw seconds */
463 return total + subtotal;
466 bool InspIRCd::ULine(const std::string& sserver)
471 return (Config->ulines.find(sserver.c_str()) != Config->ulines.end());
474 bool InspIRCd::SilentULine(const std::string& sserver)
476 std::map<irc::string,bool>::iterator n = Config->ulines.find(sserver.c_str());
477 if (n != Config->ulines.end())
483 std::string InspIRCd::TimeString(time_t curtime)
485 return std::string(ctime(&curtime),24);
488 // You should only pass a single character to this.
489 void InspIRCd::AddExtBanChar(char c)
491 std::string &tok = Config->data005;
492 std::string::size_type ebpos = tok.find(" EXTBAN=,");
494 if (ebpos == std::string::npos)
496 tok.append(" EXTBAN=,");
502 while (isalpha(tok[ebpos]) && tok[ebpos] < c)
504 tok.insert(ebpos, 1, c);
508 std::string InspIRCd::GenRandomStr(int length, bool printable)
510 char* buf = new char[length];
511 GenRandom(buf, length);
514 for(int i=0; i < length; i++)
515 rv[i] = printable ? 0x3F + (buf[i] & 0x3F) : buf[i];
520 // NOTE: this has a slight bias for lower values if max is not a power of 2.
521 // Don't use it if that matters.
522 unsigned long InspIRCd::GenRandomInt(unsigned long max)
525 GenRandom((char*)&rv, sizeof(rv));
529 // This is overridden by a higher-quality algorithm when SSL support is loaded
530 void GenRandomHandler::Call(char *output, size_t max)
532 for(unsigned int i=0; i < max; i++)
536 if(rand_s(&uTemp) != 0)
542 output[i] = random();
546 ModResult OnCheckExemptionHandler::Call(User* user, Channel* chan, const std::string& restriction)
548 unsigned int mypfx = chan->GetPrefixValue(user);
552 irc::spacesepstream defaultstream(ServerInstance->Config->ConfValue("options")->getString("exemptchanops"));
554 while (defaultstream.GetToken(current))
556 std::string::size_type pos = current.find(':');
557 if (pos == std::string::npos)
559 if (current.substr(0,pos) == restriction)
560 minmode = current[pos+1];
563 ModeHandler* mh = ServerInstance->Modes->FindMode(minmode, MODETYPE_CHANNEL);
564 if (mh && mypfx >= mh->GetPrefixRank())
565 return MOD_RES_ALLOW;
566 if (mh || minmode == '*')
568 return MOD_RES_PASSTHRU;