1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * InspIRCd: (C) 2002-2008 InspIRCd Development Team
6 * See: http://www.inspircd.org/wiki/index.php/Credits
8 * This program is free but copyrighted software; see
9 * the file COPYING for details.
11 * ---------------------------------------------------
14 /* $Core: libIRCDhash */
19 #include <ext/hash_map>
20 #define nspace __gnu_cxx
24 using stdext::hash_map;
27 /******************************************************
29 * The hash functions of InspIRCd are the centrepoint
30 * of the entire system. If these functions are
31 * inefficient or wasteful, the whole program suffers
32 * as a result. A lot of C programmers in the ircd
33 * scene spend a lot of time debating (arguing) about
34 * the best way to write hash functions to hash irc
35 * nicknames, channels etc.
36 * We are lucky as C++ developers as hash_map does
37 * a lot of this for us. It does intellegent memory
38 * requests, bucketing, search functions, insertion
39 * and deletion etc. All we have to do is write some
40 * overloaded comparison and hash value operators which
41 * cause it to act in an irc-like way. The features we
42 * add to the standard hash_map are:
44 * Case insensitivity: The hash_map will be case
47 * Scandanavian Comparisons: The characters [, ], \ will
48 * be considered the lowercase of {, } and |.
50 ******************************************************/
52 using namespace irc::sockets;
54 /* convert a string to lowercase. Note following special circumstances
55 * taken from RFC 1459. Many "official" server branches still hold to this
58 * Because of IRC's scandanavian origin, the characters {}| are
59 * considered to be the lower case equivalents of the characters []\,
60 * respectively. This is a critical issue when determining the
61 * equivalence of two nicknames.
63 void nspace::strlower(char *n)
67 for (char* t = n; *t; t++)
68 *t = lowermap[(unsigned char)*t];
73 size_t nspace::hash<string>::operator()(const string &s) const
75 size_t nspace::hash_compare<string, std::less<string> >::operator()(const string &s) const
78 /* XXX: NO DATA COPIES! :)
79 * The hash function here is practically
80 * a copy of the one in STL's hash_fun.h,
81 * only with *x replaced with lowermap[*x].
82 * This avoids a copy to use hash<const char*>
84 register size_t t = 0;
85 for (std::string::const_iterator x = s.begin(); x != s.end(); ++x) /* ++x not x++, as its faster */
86 t = 5 * t + lowermap[(unsigned char)*x];
91 size_t nspace::hash<irc::string>::operator()(const irc::string &s) const
93 size_t nspace::hash_compare<irc::string, std::less<irc::string> >::operator()(const irc::string &s) const
96 register size_t t = 0;
97 for (irc::string::const_iterator x = s.begin(); x != s.end(); ++x) /* ++x not x++, as its faster */
98 t = 5 * t + lowermap[(unsigned char)*x];
102 bool irc::StrHashComp::operator()(const std::string& s1, const std::string& s2) const
104 unsigned char* n1 = (unsigned char*)s1.c_str();
105 unsigned char* n2 = (unsigned char*)s2.c_str();
106 for (; *n1 && *n2; n1++, n2++)
107 if (lowermap[*n1] != lowermap[*n2])
109 return (lowermap[*n1] == lowermap[*n2]);
112 /******************************************************
114 * This is the implementation of our special irc::string
115 * class which is a case-insensitive equivalent to
116 * std::string which is not only case-insensitive but
117 * can also do scandanavian comparisons, e.g. { = [, etc.
119 * This class depends on the const array 'lowermap'.
121 ******************************************************/
123 bool irc::irc_char_traits::eq(char c1st, char c2nd)
125 return lowermap[(unsigned char)c1st] == lowermap[(unsigned char)c2nd];
128 bool irc::irc_char_traits::ne(char c1st, char c2nd)
130 return lowermap[(unsigned char)c1st] != lowermap[(unsigned char)c2nd];
133 bool irc::irc_char_traits::lt(char c1st, char c2nd)
135 return lowermap[(unsigned char)c1st] < lowermap[(unsigned char)c2nd];
138 int irc::irc_char_traits::compare(const char* str1, const char* str2, size_t n)
140 for(unsigned int i = 0; i < n; i++)
142 if(lowermap[(unsigned char)*str1] > lowermap[(unsigned char)*str2])
145 if(lowermap[(unsigned char)*str1] < lowermap[(unsigned char)*str2])
148 if(*str1 == 0 || *str2 == 0)
157 const char* irc::irc_char_traits::find(const char* s1, int n, char c)
159 while(n-- > 0 && lowermap[(unsigned char)*s1] != lowermap[(unsigned char)c])
164 irc::tokenstream::tokenstream(const std::string &source) : tokens(source), last_pushed(false)
166 /* Record starting position and current position */
167 last_starting_position = tokens.begin();
171 irc::tokenstream::~tokenstream()
175 bool irc::tokenstream::GetToken(std::string &token)
177 std::string::iterator lsp = last_starting_position;
179 while (n != tokens.end())
181 /** Skip multi space, converting " " into " "
183 while ((n+1 != tokens.end()) && (*n == ' ') && (*(n+1) == ' '))
186 if ((last_pushed) && (*n == ':'))
188 /* If we find a token thats not the first and starts with :,
189 * this is the last token on the line
191 std::string::iterator curr = ++n;
193 token = std::string(curr, tokens.end());
199 if ((*n == ' ') || (n+1 == tokens.end()))
201 /* If we find a space, or end of string, this is the end of a token.
203 last_starting_position = n+1;
206 std::string strip(lsp, n+1 == tokens.end() ? n+1 : n++);
207 while ((strip.length()) && (strip.find_last_of(' ') == strip.length() - 1))
208 strip.erase(strip.end() - 1);
211 return !token.empty();
220 bool irc::tokenstream::GetToken(irc::string &token)
222 std::string stdstring;
223 bool returnval = GetToken(stdstring);
224 token = assign(stdstring);
228 bool irc::tokenstream::GetToken(int &token)
231 bool returnval = GetToken(tok);
232 token = ConvToInt(tok);
236 bool irc::tokenstream::GetToken(long &token)
239 bool returnval = GetToken(tok);
240 token = ConvToInt(tok);
244 irc::sepstream::sepstream(const std::string &source, char seperator) : tokens(source), sep(seperator)
246 last_starting_position = tokens.begin();
250 bool irc::sepstream::GetToken(std::string &token)
252 std::string::iterator lsp = last_starting_position;
254 while (n != tokens.end())
256 if ((*n == sep) || (n+1 == tokens.end()))
258 last_starting_position = n+1;
259 token = std::string(lsp, n+1 == tokens.end() ? n+1 : n++);
261 while ((token.length()) && (token.find_last_of(sep) == token.length() - 1))
262 token.erase(token.end() - 1);
267 return n == tokens.end() ? false : true;
277 const std::string irc::sepstream::GetRemaining()
279 return std::string(n, tokens.end());
282 bool irc::sepstream::StreamEnd()
284 return ((n + 1) == tokens.end());
287 irc::sepstream::~sepstream()
291 std::string irc::hex(const unsigned char *raw, size_t rawsz)
296 /* EWW! This used to be using sprintf, which is WAY inefficient. -Special */
298 const char *hex = "0123456789abcdef";
299 static char hexbuf[MAXBUF];
302 for (i = 0, j = 0; j < rawsz; ++j)
304 hexbuf[i++] = hex[raw[j] / 16];
305 hexbuf[i++] = hex[raw[j] % 16];
312 CoreExport const char* irc::Spacify(const char* n)
314 static char x[MAXBUF];
316 for (char* y = x; *y; y++)
323 irc::modestacker::modestacker(bool add) : adding(add)
326 sequence.push_back("");
329 void irc::modestacker::Push(char modeletter, const std::string ¶meter)
331 *(sequence.begin()) += modeletter;
332 sequence.push_back(parameter);
335 void irc::modestacker::Push(char modeletter)
337 this->Push(modeletter,"");
340 void irc::modestacker::PushPlus()
345 void irc::modestacker::PushMinus()
350 int irc::modestacker::GetStackedLine(std::deque<std::string> &result, int max_line_size)
352 if (sequence.empty())
359 int size = 1; /* Account for initial +/- char */
362 result.push_back(adding ? "+" : "-");
364 if (sequence.size() > 1)
365 nextsize = sequence[1].length() + 2;
367 while (!sequence[0].empty() && (sequence.size() > 1) && (result.size() < MAXMODES) && ((size + nextsize) < max_line_size))
369 result[0] += *(sequence[0].begin());
370 if (!sequence[1].empty())
372 result.push_back(sequence[1]);
373 size += nextsize; /* Account for mode character and whitespace */
375 sequence[0].erase(sequence[0].begin());
376 sequence.erase(sequence.begin() + 1);
378 if (sequence.size() > 1)
379 nextsize = sequence[1].length() + 2;
387 irc::stringjoiner::stringjoiner(const std::string &seperator, const std::vector<std::string> &sequence, int begin, int end)
389 for (int v = begin; v < end; v++)
390 joined.append(sequence[v]).append(seperator);
391 joined.append(sequence[end]);
394 irc::stringjoiner::stringjoiner(const std::string &seperator, const std::deque<std::string> &sequence, int begin, int end)
396 for (int v = begin; v < end; v++)
397 joined.append(sequence[v]).append(seperator);
398 joined.append(sequence[end]);
401 irc::stringjoiner::stringjoiner(const std::string &seperator, const char** sequence, int begin, int end)
403 for (int v = begin; v < end; v++)
404 joined.append(sequence[v]).append(seperator);
405 joined.append(sequence[end]);
408 std::string& irc::stringjoiner::GetJoined()
413 irc::portparser::portparser(const std::string &source, bool allow_overlapped) : in_range(0), range_begin(0), range_end(0), overlapped(allow_overlapped)
415 sep = new irc::commasepstream(source);
419 irc::portparser::~portparser()
424 bool irc::portparser::Overlaps(long val)
429 if (overlap_set.find(val) == overlap_set.end())
431 overlap_set[val] = true;
438 long irc::portparser::GetToken()
443 if (in_range <= range_end)
445 if (!Overlaps(in_range))
451 while (((Overlaps(in_range)) && (in_range <= range_end)))
454 if (in_range <= range_end)
468 while (Overlaps(atoi(x.c_str())))
470 if (!sep->GetToken(x))
474 std::string::size_type dash = x.rfind('-');
475 if (dash != std::string::npos)
477 std::string sbegin = x.substr(0, dash);
478 std::string send = x.substr(dash+1, x.length());
479 range_begin = atoi(sbegin.c_str());
480 range_end = atoi(send.c_str());
482 if ((range_begin > 0) && (range_end > 0) && (range_begin < 65536) && (range_end < 65536) && (range_begin < range_end))
484 in_range = range_begin;
489 /* Assume its just the one port */
490 return atoi(sbegin.c_str());
495 return atoi(x.c_str());
499 irc::dynamicbitmask::dynamicbitmask() : bits_size(4)
501 /* We start with 4 bytes allocated which is room
502 * for 4 items. Something makes me doubt its worth
503 * allocating less than 4 bytes.
505 bits = new unsigned char[bits_size];
506 memset(bits, 0, bits_size);
509 irc::dynamicbitmask::~dynamicbitmask()
511 /* Tidy up the entire used memory on delete */
515 irc::bitfield irc::dynamicbitmask::Allocate()
517 /* Yeah, this isnt too efficient, however a module or the core
518 * should only be allocating bitfields on load, the Toggle and
519 * Get methods are O(1) as these are called much more often.
521 unsigned char* freebits = this->GetFreeBits();
522 for (unsigned char i = 0; i < bits_size; i++)
524 /* Yes, this is right. You'll notice we terminate the loop when !current_pos,
525 * this is because we logic shift our bit off the end of unsigned char, and its
526 * lost, making the loop counter 0 when we're done.
528 for (unsigned char current_pos = 1; current_pos; current_pos = current_pos << 1)
530 if (!(freebits[i] & current_pos))
532 freebits[i] |= current_pos;
533 return std::make_pair(i, current_pos);
537 /* We dont have any free space left, increase by one */
539 if (bits_size == 255)
540 /* Oh dear, cant grow it any further */
541 throw std::bad_alloc();
543 unsigned char old_bits_size = bits_size;
545 /* Allocate new bitfield space */
546 unsigned char* temp_bits = new unsigned char[bits_size];
547 unsigned char* temp_freebits = new unsigned char[bits_size];
548 /* Copy the old data in */
549 memcpy(temp_bits, bits, old_bits_size);
550 memcpy(temp_freebits, freebits, old_bits_size);
551 /* Delete the old data pointers */
554 /* Swap the pointers over so now the new
555 * pointers point to our member values
558 freebits = temp_freebits;
559 this->SetFreeBits(freebits);
560 /* Initialize the new byte on the end of
561 * the bitfields, pre-allocate the one bit
562 * for this allocation
564 bits[old_bits_size] = 0;
565 freebits[old_bits_size] = 1;
566 /* We already know where we just allocated
567 * the bitfield, so no loop needed
569 return std::make_pair(old_bits_size, 1);
572 bool irc::dynamicbitmask::Deallocate(irc::bitfield &pos)
574 /* We dont bother to shrink the bitfield
575 * on deallocation, the most we could do
576 * is save one byte (!) and this would cost
577 * us a loop (ugly O(n) stuff) so we just
578 * clear the bit and leave the memory
579 * claimed -- nobody will care about one
582 if (pos.first < bits_size)
584 this->GetFreeBits()[pos.first] &= ~pos.second;
587 /* They gave a bitfield outside of the
588 * length of our array. BAD programmer.
593 void irc::dynamicbitmask::Toggle(irc::bitfield &pos, bool state)
595 /* Range check the value */
596 if (pos.first < bits_size)
599 /* Set state, OR the state in */
600 bits[pos.first] |= pos.second;
602 /* Clear state, AND the !state out */
603 bits[pos.first] &= ~pos.second;
607 bool irc::dynamicbitmask::Get(irc::bitfield &pos)
609 /* Range check the value */
610 if (pos.first < bits_size)
611 return (bits[pos.first] & pos.second);
613 /* We can't return false, otherwise we can't
614 * distinguish between failure and a cleared bit!
615 * Our only sensible choice is to throw (ew).
617 throw ModuleException("irc::dynamicbitmask::Get(): Invalid bitfield, out of range");
620 unsigned char irc::dynamicbitmask::GetSize()