1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * InspIRCd: (C) 2002-2007 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 * ---------------------------------------------------
16 #include <ext/hash_map>
17 #define nspace __gnu_cxx
19 /******************************************************
21 * The hash functions of InspIRCd are the centrepoint
22 * of the entire system. If these functions are
23 * inefficient or wasteful, the whole program suffers
24 * as a result. A lot of C programmers in the ircd
25 * scene spend a lot of time debating (arguing) about
26 * the best way to write hash functions to hash irc
27 * nicknames, channels etc.
28 * We are lucky as C++ developers as hash_map does
29 * a lot of this for us. It does intellegent memory
30 * requests, bucketing, search functions, insertion
31 * and deletion etc. All we have to do is write some
32 * overloaded comparison and hash value operators which
33 * cause it to act in an irc-like way. The features we
34 * add to the standard hash_map are:
36 * Case insensitivity: The hash_map will be case
39 * Scandanavian Comparisons: The characters [, ], \ will
40 * be considered the lowercase of {, } and |.
42 * This file also contains hashing methods for hashing
43 * insp_inaddr structs, we use this if we want to cache IP
46 ******************************************************/
49 using namespace irc::sockets;
51 /* convert a string to lowercase. Note following special circumstances
52 * taken from RFC 1459. Many "official" server branches still hold to this
55 * Because of IRC's scandanavian origin, the characters {}| are
56 * considered to be the lower case equivalents of the characters []\,
57 * respectively. This is a critical issue when determining the
58 * equivalence of two nicknames.
60 void nspace::strlower(char *n)
64 for (char* t = n; *t; t++)
65 *t = lowermap[(unsigned char)*t];
69 size_t nspace::hash<insp_inaddr>::operator()(const insp_inaddr &a) const
72 memcpy(&q,&a,sizeof(size_t));
76 size_t nspace::hash<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];
90 size_t nspace::hash<irc::string>::operator()(const irc::string &s) const
92 register size_t t = 0;
93 for (irc::string::const_iterator x = s.begin(); x != s.end(); ++x) /* ++x not x++, as its faster */
94 t = 5 * t + lowermap[(unsigned char)*x];
98 bool irc::StrHashComp::operator()(const std::string& s1, const std::string& s2) const
100 unsigned char* n1 = (unsigned char*)s1.c_str();
101 unsigned char* n2 = (unsigned char*)s2.c_str();
102 for (; *n1 && *n2; n1++, n2++)
103 if (lowermap[*n1] != lowermap[*n2])
105 return (lowermap[*n1] == lowermap[*n2]);
108 bool irc::InAddr_HashComp::operator()(const insp_inaddr &s1, const insp_inaddr &s2) const
111 for (int n = 0; n < 16; n++)
112 if (s2.s6_addr[n] != s1.s6_addr[n])
116 return (s1.s_addr == s1.s_addr);
120 /******************************************************
122 * This is the implementation of our special irc::string
123 * class which is a case-insensitive equivalent to
124 * std::string which is not only case-insensitive but
125 * can also do scandanavian comparisons, e.g. { = [, etc.
127 * This class depends on the const array 'lowermap'.
129 ******************************************************/
131 bool irc::irc_char_traits::eq(char c1st, char c2nd)
133 return lowermap[(unsigned char)c1st] == lowermap[(unsigned char)c2nd];
136 bool irc::irc_char_traits::ne(char c1st, char c2nd)
138 return lowermap[(unsigned char)c1st] != lowermap[(unsigned char)c2nd];
141 bool irc::irc_char_traits::lt(char c1st, char c2nd)
143 return lowermap[(unsigned char)c1st] < lowermap[(unsigned char)c2nd];
146 int irc::irc_char_traits::compare(const char* str1, const char* str2, size_t n)
148 for(unsigned int i = 0; i < n; i++)
150 if(lowermap[(unsigned char)*str1] > lowermap[(unsigned char)*str2])
153 if(lowermap[(unsigned char)*str1] < lowermap[(unsigned char)*str2])
156 if(*str1 == 0 || *str2 == 0)
165 std::string operator+ (std::string& leftval, irc::string& rightval)
167 return leftval + std::string(rightval.c_str());
170 irc::string operator+ (irc::string& leftval, std::string& rightval)
172 return leftval + irc::string(rightval.c_str());
175 bool operator== (std::string& leftval, irc::string& rightval)
177 return (leftval.c_str() == rightval);
180 bool operator== (irc::string& leftval, std::string& rightval)
182 return (leftval == rightval.c_str());
185 const char* irc::irc_char_traits::find(const char* s1, int n, char c)
187 while(n-- > 0 && lowermap[(unsigned char)*s1] != lowermap[(unsigned char)c])
192 /* See hashcomp.h if you care about these... */
193 std::ostream& operator<<(std::ostream &os, const irc::string &str)
195 return os << str.c_str();
198 std::istream& operator>>(std::istream &is, irc::string &str)
206 irc::tokenstream::tokenstream(const std::string &source) : tokens(source), last_pushed(false)
208 /* Record starting position and current position */
209 last_starting_position = tokens.begin();
213 irc::tokenstream::~tokenstream()
217 const std::string irc::tokenstream::GetToken()
219 std::string::iterator lsp = last_starting_position;
221 while (n != tokens.end())
223 /** Skip multi space, converting " " into " "
225 while ((n+1 != tokens.end()) && (*n == ' ') && (*(n+1) == ' '))
228 if ((last_pushed) && (*n == ':'))
230 /* If we find a token thats not the first and starts with :,
231 * this is the last token on the line
233 std::string::iterator curr = ++n;
235 return std::string(curr, tokens.end());
240 if ((*n == ' ') || (n+1 == tokens.end()))
242 /* If we find a space, or end of string, this is the end of a token.
244 last_starting_position = n+1;
247 std::string strip(lsp, n+1 == tokens.end() ? n+1 : n++);
248 while ((strip.length()) && (strip.find_last_of(' ') == strip.length() - 1))
249 strip.erase(strip.end() - 1);
259 irc::sepstream::sepstream(const std::string &source, char seperator) : tokens(source), sep(seperator)
261 last_starting_position = tokens.begin();
265 const std::string irc::sepstream::GetToken()
267 std::string::iterator lsp = last_starting_position;
269 while (n != tokens.end())
271 if ((*n == sep) || (n+1 == tokens.end()))
273 last_starting_position = n+1;
274 std::string strip = std::string(lsp, n+1 == tokens.end() ? n+1 : n++);
276 while ((strip.length()) && (strip.find_last_of(sep) == strip.length() - 1))
277 strip.erase(strip.end() - 1);
288 irc::sepstream::~sepstream()
292 std::string irc::hex(const unsigned char *raw, size_t rawsz)
297 /* EWW! This used to be using sprintf, which is WAY inefficient. -Special */
299 const char *hex = "0123456789abcdef";
304 for (i = 0, j = 0; j < rawsz; ++j)
306 buf[i++] = hex[raw[j] / 16];
307 buf[i++] = hex[raw[j] % 16];
314 const char* irc::Spacify(char* n)
316 static char x[MAXBUF];
318 for (char* y = x; *y; y++)
325 irc::modestacker::modestacker(bool add) : adding(add)
328 sequence.push_back("");
331 void irc::modestacker::Push(char modeletter, const std::string ¶meter)
333 *(sequence.begin()) += modeletter;
334 sequence.push_back(parameter);
337 void irc::modestacker::Push(char modeletter)
339 this->Push(modeletter,"");
342 void irc::modestacker::PushPlus()
347 void irc::modestacker::PushMinus()
352 int irc::modestacker::GetStackedLine(std::deque<std::string> &result)
356 result.push_back(adding ? "+" : "-");
358 while (!sequence[0].empty() && (sequence.size() > 1) && (result.size() < MAXMODES+1))
360 result[0] += *(sequence[0].begin());
361 if (!sequence[1].empty())
362 result.push_back(sequence[1]);
363 sequence[0].erase(sequence[0].begin());
364 sequence.erase(sequence.begin() + 1);
371 irc::stringjoiner::stringjoiner(const std::string &seperator, const std::vector<std::string> &sequence, int begin, int end)
373 for (int v = begin; v < end; v++)
374 joined.append(sequence[v]).append(seperator);
375 joined.append(sequence[end]);
378 irc::stringjoiner::stringjoiner(const std::string &seperator, const std::deque<std::string> &sequence, int begin, int end)
380 for (int v = begin; v < end; v++)
381 joined.append(sequence[v]).append(seperator);
382 joined.append(sequence[end]);
385 irc::stringjoiner::stringjoiner(const std::string &seperator, const char** sequence, int begin, int end)
387 for (int v = begin; v < end; v++)
388 joined.append(sequence[v]).append(seperator);
389 joined.append(sequence[end]);
392 std::string& irc::stringjoiner::GetJoined()
397 irc::portparser::portparser(const std::string &source, bool allow_overlapped) : in_range(0), range_begin(0), range_end(0), overlapped(allow_overlapped)
399 sep = new irc::commasepstream(source);
403 irc::portparser::~portparser()
408 bool irc::portparser::Overlaps(long val)
413 if (overlap_set.find(val) == overlap_set.end())
415 overlap_set[val] = true;
422 long irc::portparser::GetToken()
427 if (in_range <= range_end)
429 if (!Overlaps(in_range))
435 while (((Overlaps(in_range)) && (in_range <= range_end)))
438 if (in_range <= range_end)
446 std::string x = sep->GetToken();
451 while (Overlaps(atoi(x.c_str())))
459 std::string::size_type dash = x.rfind('-');
460 if (dash != std::string::npos)
462 std::string sbegin = x.substr(0, dash);
463 std::string send = x.substr(dash+1, x.length());
464 range_begin = atoi(sbegin.c_str());
465 range_end = atoi(send.c_str());
467 if ((range_begin > 0) && (range_end > 0) && (range_begin < 65536) && (range_end < 65536) && (range_begin < range_end))
469 in_range = range_begin;
474 /* Assume its just the one port */
475 return atoi(sbegin.c_str());
480 return atoi(x.c_str());
484 irc::dynamicbitmask::dynamicbitmask() : bits_size(4)
486 /* We start with 4 bytes allocated which is room
487 * for 4 items. Something makes me doubt its worth
488 * allocating less than 4 bytes.
490 bits = new unsigned char[bits_size];
491 memset(bits, 0, bits_size);
494 irc::dynamicbitmask::~dynamicbitmask()
496 /* Tidy up the entire used memory on delete */
500 irc::bitfield irc::dynamicbitmask::Allocate()
502 /* Yeah, this isnt too efficient, however a module or the core
503 * should only be allocating bitfields on load, the Toggle and
504 * Get methods are O(1) as these are called much more often.
506 unsigned char* freebits = this->GetFreeBits();
507 for (unsigned char i = 0; i < bits_size; i++)
509 /* Yes, this is right. You'll notice we terminate the loop when !current_pos,
510 * this is because we logic shift our bit off the end of unsigned char, and its
511 * lost, making the loop counter 0 when we're done.
513 for (unsigned char current_pos = 1; current_pos; current_pos = current_pos << 1)
515 if (!(freebits[i] & current_pos))
517 freebits[i] |= current_pos;
518 return std::make_pair(i, current_pos);
522 /* We dont have any free space left, increase by one */
524 if (bits_size == 255)
525 /* Oh dear, cant grow it any further */
526 throw std::bad_alloc();
528 unsigned char old_bits_size = bits_size;
530 /* Allocate new bitfield space */
531 unsigned char* temp_bits = new unsigned char[bits_size];
532 unsigned char* temp_freebits = new unsigned char[bits_size];
533 /* Copy the old data in */
534 memcpy(temp_bits, bits, old_bits_size);
535 memcpy(temp_freebits, freebits, old_bits_size);
536 /* Delete the old data pointers */
539 /* Swap the pointers over so now the new
540 * pointers point to our member values
543 freebits = temp_freebits;
544 this->SetFreeBits(freebits);
545 /* Initialize the new byte on the end of
546 * the bitfields, pre-allocate the one bit
547 * for this allocation
549 bits[old_bits_size] = 0;
550 freebits[old_bits_size] = 1;
551 /* We already know where we just allocated
552 * the bitfield, so no loop needed
554 return std::make_pair(old_bits_size, 1);
557 bool irc::dynamicbitmask::Deallocate(irc::bitfield &pos)
559 /* We dont bother to shrink the bitfield
560 * on deallocation, the most we could do
561 * is save one byte (!) and this would cost
562 * us a loop (ugly O(n) stuff) so we just
563 * clear the bit and leave the memory
564 * claimed -- nobody will care about one
567 if (pos.first < bits_size)
569 this->GetFreeBits()[pos.first] &= ~pos.second;
572 /* They gave a bitfield outside of the
573 * length of our array. BAD programmer.
578 void irc::dynamicbitmask::Toggle(irc::bitfield &pos, bool state)
580 /* Range check the value */
581 if (pos.first < bits_size)
584 /* Set state, OR the state in */
585 bits[pos.first] |= pos.second;
587 /* Clear state, AND the !state out */
588 bits[pos.first] &= ~pos.second;
592 bool irc::dynamicbitmask::Get(irc::bitfield &pos)
594 /* Range check the value */
595 if (pos.first < bits_size)
596 return (bits[pos.first] & pos.second);
598 /* We can't return false, otherwise we can't
599 * distinguish between failure and a cleared bit!
600 * Our only sensible choice is to throw (ew).
602 throw ModuleException("irc::dynamicbitmask::Get(): Invalid bitfield, out of range");
605 unsigned char irc::dynamicbitmask::GetSize()
610 std::string assign(const irc::string &other)
612 return other.c_str();
615 irc::string assign(const std::string &other)
617 return other.c_str();