]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/hashcomp.cpp
55b3f9b5848ff47e4321e5c90b1e14d2519c4ef8
[user/henk/code/inspircd.git] / src / hashcomp.cpp
1 /*       +------------------------------------+
2  *       | Inspire Internet Relay Chat Daemon |
3  *       +------------------------------------+
4  *
5  *  InspIRCd: (C) 2002-2007 InspIRCd Development Team
6  * See: http://www.inspircd.org/wiki/index.php/Credits
7  *
8  * This program is free but copyrighted software; see
9  *            the file COPYING for details.
10  *
11  * ---------------------------------------------------
12  */
13
14 #include "inspircd.h"
15 #include "hashcomp.h"
16 #include <ext/hash_map>
17 #define nspace __gnu_cxx
18
19 /******************************************************
20  *
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:
35  *
36  * Case insensitivity: The hash_map will be case
37  * insensitive.
38  *
39  * Scandanavian Comparisons: The characters [, ], \ will
40  * be considered the lowercase of {, } and |.
41  *
42  * This file also contains hashing methods for hashing
43  * insp_inaddr structs, we use this if we want to cache IP
44  * addresses.
45  *
46  ******************************************************/
47
48 using namespace irc::sockets;
49
50 /* convert a string to lowercase. Note following special circumstances
51  * taken from RFC 1459. Many "official" server branches still hold to this
52  * rule so i will too;
53  *
54  *  Because of IRC's scandanavian origin, the characters {}| are
55  *  considered to be the lower case equivalents of the characters []\,
56  *  respectively. This is a critical issue when determining the
57  *  equivalence of two nicknames.
58  */
59 void nspace::strlower(char *n)
60 {
61         if (n)
62         {
63                 for (char* t = n; *t; t++)
64                         *t = lowermap[(unsigned char)*t];
65         }
66 }
67
68 size_t nspace::hash<insp_inaddr>::operator()(const insp_inaddr &a) const
69 {
70         size_t q;
71         memcpy(&q,&a,sizeof(size_t));
72         return q;
73 }
74
75 size_t nspace::hash<string>::operator()(const string &s) const
76 {
77         /* XXX: NO DATA COPIES! :)
78          * The hash function here is practically
79          * a copy of the one in STL's hash_fun.h,
80          * only with *x replaced with lowermap[*x].
81          * This avoids a copy to use hash<const char*>
82          */
83         register size_t t = 0;
84         for (std::string::const_iterator x = s.begin(); x != s.end(); ++x) /* ++x not x++, as its faster */
85                 t = 5 * t + lowermap[(unsigned char)*x];
86         return t;
87 }
88
89 size_t nspace::hash<irc::string>::operator()(const irc::string &s) const
90 {
91         register size_t t = 0;
92         for (irc::string::const_iterator x = s.begin(); x != s.end(); ++x) /* ++x not x++, as its faster */
93                 t = 5 * t + lowermap[(unsigned char)*x];
94         return t;
95 }
96
97 bool irc::StrHashComp::operator()(const std::string& s1, const std::string& s2) const
98 {
99         unsigned char* n1 = (unsigned char*)s1.c_str();
100         unsigned char* n2 = (unsigned char*)s2.c_str();
101         for (; *n1 && *n2; n1++, n2++)
102                 if (lowermap[*n1] != lowermap[*n2])
103                         return false;
104         return (lowermap[*n1] == lowermap[*n2]);
105 }
106
107 bool irc::InAddr_HashComp::operator()(const insp_inaddr &s1, const insp_inaddr &s2) const
108 {
109 #ifdef IPV6
110         for (int n = 0; n < 16; n++)
111                 if (s2.s6_addr[n] != s1.s6_addr[n])
112                         return false;
113         return true;
114 #else
115         return (s1.s_addr == s1.s_addr);
116 #endif
117 }
118
119 /******************************************************
120  *
121  * This is the implementation of our special irc::string
122  * class which is a case-insensitive equivalent to
123  * std::string which is not only case-insensitive but
124  * can also do scandanavian comparisons, e.g. { = [, etc.
125  *
126  * This class depends on the const array 'lowermap'.
127  *
128  ******************************************************/
129
130 bool irc::irc_char_traits::eq(char c1st, char c2nd)
131 {
132         return lowermap[(unsigned char)c1st] == lowermap[(unsigned char)c2nd];
133 }
134
135 bool irc::irc_char_traits::ne(char c1st, char c2nd)
136 {
137         return lowermap[(unsigned char)c1st] != lowermap[(unsigned char)c2nd];
138 }
139
140 bool irc::irc_char_traits::lt(char c1st, char c2nd)
141 {
142         return lowermap[(unsigned char)c1st] < lowermap[(unsigned char)c2nd];
143 }
144
145 int irc::irc_char_traits::compare(const char* str1, const char* str2, size_t n)
146 {
147         for(unsigned int i = 0; i < n; i++)
148         {
149                 if(lowermap[(unsigned char)*str1] > lowermap[(unsigned char)*str2])
150                         return 1;
151
152                 if(lowermap[(unsigned char)*str1] < lowermap[(unsigned char)*str2])
153                         return -1;
154
155                 if(*str1 == 0 || *str2 == 0)
156                         return 0;
157
158                 str1++;
159                 str2++;
160         }
161         return 0;
162 }
163
164 std::string operator+ (std::string& leftval, irc::string& rightval)
165 {
166         return leftval + std::string(rightval.c_str());
167 }
168
169 irc::string operator+ (irc::string& leftval, std::string& rightval)
170 {
171         return leftval + irc::string(rightval.c_str());
172 }
173
174 bool operator== (std::string& leftval, irc::string& rightval)
175 {
176         return (leftval.c_str() == rightval);
177 }
178
179 bool operator== (irc::string& leftval, std::string& rightval)
180 {
181         return (leftval == rightval.c_str());
182 }
183
184 const char* irc::irc_char_traits::find(const char* s1, int  n, char c)
185 {
186         while(n-- > 0 && lowermap[(unsigned char)*s1] != lowermap[(unsigned char)c])
187                 s1++;
188         return s1;
189 }
190
191 /* See hashcomp.h if you care about these... */
192 std::ostream& operator<<(std::ostream &os, const irc::string &str)
193 {
194         return os << str.c_str();
195 }
196
197 std::istream& operator>>(std::istream &is, irc::string &str)
198 {
199         std::string tmp;
200         is >> tmp;
201         str = tmp.c_str();
202         return is;
203 }
204
205 irc::tokenstream::tokenstream(const std::string &source) : tokens(source), last_pushed(false)
206 {
207         /* Record starting position and current position */
208         last_starting_position = tokens.begin();
209         n = tokens.begin();
210 }
211
212 irc::tokenstream::~tokenstream()
213 {
214 }
215
216 const std::string irc::tokenstream::GetToken()
217 {
218         std::string::iterator lsp = last_starting_position;
219
220         while (n != tokens.end())
221         {
222                 /** Skip multi space, converting "  " into " "
223                  */
224                 while ((n+1 != tokens.end()) && (*n == ' ') && (*(n+1) == ' '))
225                         n++;
226
227                 if ((last_pushed) && (*n == ':'))
228                 {
229                         /* If we find a token thats not the first and starts with :,
230                          * this is the last token on the line
231                          */
232                         std::string::iterator curr = ++n;
233                         n = tokens.end();
234                         return std::string(curr, tokens.end());
235                 }
236
237                 last_pushed = false;
238
239                 if ((*n == ' ') || (n+1 == tokens.end()))
240                 {
241                         /* If we find a space, or end of string, this is the end of a token.
242                          */
243                         last_starting_position = n+1;
244                         last_pushed = true;
245
246                         std::string strip(lsp, n+1 == tokens.end() ? n+1  : n++);
247                         while ((strip.length()) && (strip.find_last_of(' ') == strip.length() - 1))
248                                 strip.erase(strip.end() - 1);
249
250                         return strip;
251                 }
252
253                 n++;
254         }
255         return "";
256 }
257
258 irc::sepstream::sepstream(const std::string &source, char seperator) : tokens(source), sep(seperator)
259 {
260         last_starting_position = tokens.begin();
261         n = tokens.begin();
262 }
263
264 const std::string irc::sepstream::GetToken()
265 {
266         std::string::iterator lsp = last_starting_position;
267
268         while (n != tokens.end())
269         {
270                 if ((*n == sep) || (n+1 == tokens.end()))
271                 {
272                         last_starting_position = n+1;
273                         std::string strip = std::string(lsp, n+1 == tokens.end() ? n+1  : n++);
274
275                         while ((strip.length()) && (strip.find_last_of(sep) == strip.length() - 1))
276                                 strip.erase(strip.end() - 1);
277
278                         return strip;
279                 }
280
281                 n++;
282         }
283
284         return "";
285 }
286
287 bool irc::sepstream::StreamEnd()
288 {
289         return ((n + 1) == tokens.end());
290 }
291
292 irc::sepstream::~sepstream()
293 {
294 }
295
296 std::string irc::hex(const unsigned char *raw, size_t rawsz)
297 {
298         if (!rawsz)
299                 return "";
300
301         /* EWW! This used to be using sprintf, which is WAY inefficient. -Special */
302         
303         const char *hex = "0123456789abcdef";
304         
305         char buf[rawsz*2+1];
306
307         size_t i, j;
308         for (i = 0, j = 0; j < rawsz; ++j)
309         {
310                 buf[i++] = hex[raw[j] / 16];
311                 buf[i++] = hex[raw[j] % 16];
312         }
313         buf[i] = '\0';
314
315         return buf;
316 }
317
318 const char* irc::Spacify(const char* n)
319 {
320         static char x[MAXBUF];
321         strlcpy(x,n,MAXBUF);
322         for (char* y = x; *y; y++)
323                 if (*y == '_')
324                         *y = ' ';
325         return x;
326 }
327
328
329 irc::modestacker::modestacker(bool add) : adding(add)
330 {
331         sequence.clear();
332         sequence.push_back("");
333 }
334
335 void irc::modestacker::Push(char modeletter, const std::string &parameter)
336 {
337         *(sequence.begin()) += modeletter;
338         sequence.push_back(parameter);
339 }
340
341 void irc::modestacker::Push(char modeletter)
342 {
343         this->Push(modeletter,"");
344 }
345
346 void irc::modestacker::PushPlus()
347 {
348         this->Push('+',"");
349 }
350
351 void irc::modestacker::PushMinus()
352 {
353         this->Push('-',"");
354 }
355
356 int irc::modestacker::GetStackedLine(std::deque<std::string> &result)
357 {
358         int n = 0;
359         result.clear();
360         result.push_back(adding ? "+" : "-");
361
362         while (!sequence[0].empty() && (sequence.size() > 1) && (result.size() < MAXMODES+1))
363         {
364                 result[0] += *(sequence[0].begin());
365                 if (!sequence[1].empty())
366                         result.push_back(sequence[1]);
367                 sequence[0].erase(sequence[0].begin());
368                 sequence.erase(sequence.begin() + 1);
369                 n++;
370         }
371
372         return n;
373 }
374
375 irc::stringjoiner::stringjoiner(const std::string &seperator, const std::vector<std::string> &sequence, int begin, int end)
376 {
377         for (int v = begin; v < end; v++)
378                 joined.append(sequence[v]).append(seperator);
379         joined.append(sequence[end]);
380 }
381
382 irc::stringjoiner::stringjoiner(const std::string &seperator, const std::deque<std::string> &sequence, int begin, int end)
383 {
384         for (int v = begin; v < end; v++)
385                 joined.append(sequence[v]).append(seperator);
386         joined.append(sequence[end]);
387 }
388
389 irc::stringjoiner::stringjoiner(const std::string &seperator, const char** sequence, int begin, int end)
390 {
391         for (int v = begin; v < end; v++)
392                 joined.append(sequence[v]).append(seperator);
393         joined.append(sequence[end]);
394 }
395
396 std::string& irc::stringjoiner::GetJoined()
397 {
398         return joined;
399 }
400
401 irc::portparser::portparser(const std::string &source, bool allow_overlapped) : in_range(0), range_begin(0), range_end(0), overlapped(allow_overlapped)
402 {
403         sep = new irc::commasepstream(source);
404         overlap_set.clear();
405 }
406
407 irc::portparser::~portparser()
408 {
409         delete sep;
410 }
411
412 bool irc::portparser::Overlaps(long val)
413 {
414         if (!overlapped)
415                 return false;
416
417         if (overlap_set.find(val) == overlap_set.end())
418         {
419                 overlap_set[val] = true;
420                 return false;
421         }
422         else
423                 return true;
424 }
425
426 long irc::portparser::GetToken()
427 {
428         if (in_range > 0)
429         {
430                 in_range++;
431                 if (in_range <= range_end)
432                 {
433                         if (!Overlaps(in_range))
434                         {
435                                 return in_range;
436                         }
437                         else
438                         {
439                                 while (((Overlaps(in_range)) && (in_range <= range_end)))
440                                         in_range++;
441                                 
442                                 if (in_range <= range_end)
443                                         return in_range;
444                         }
445                 }
446                 else
447                         in_range = 0;
448         }
449
450         std::string x = sep->GetToken();
451
452         if (x == "")
453                 return 0;
454
455         while (Overlaps(atoi(x.c_str())))
456         {
457                 x = sep->GetToken();
458
459                 if (x == "")
460                         return 0;
461         }
462
463         std::string::size_type dash = x.rfind('-');
464         if (dash != std::string::npos)
465         {
466                 std::string sbegin = x.substr(0, dash);
467                 std::string send = x.substr(dash+1, x.length());
468                 range_begin = atoi(sbegin.c_str());
469                 range_end = atoi(send.c_str());
470
471                 if ((range_begin > 0) && (range_end > 0) && (range_begin < 65536) && (range_end < 65536) && (range_begin < range_end))
472                 {
473                         in_range = range_begin;
474                         return in_range;
475                 }
476                 else
477                 {
478                         /* Assume its just the one port */
479                         return atoi(sbegin.c_str());
480                 }
481         }
482         else
483         {
484                 return atoi(x.c_str());
485         }
486 }
487
488 irc::dynamicbitmask::dynamicbitmask() : bits_size(4)
489 {
490         /* We start with 4 bytes allocated which is room
491          * for 4 items. Something makes me doubt its worth
492          * allocating less than 4 bytes.
493          */
494         bits = new unsigned char[bits_size];
495         memset(bits, 0, bits_size);
496 }
497
498 irc::dynamicbitmask::~dynamicbitmask()
499 {
500         /* Tidy up the entire used memory on delete */
501         delete[] bits;
502 }
503                           
504 irc::bitfield irc::dynamicbitmask::Allocate()
505 {
506         /* Yeah, this isnt too efficient, however a module or the core
507          * should only be allocating bitfields on load, the Toggle and
508          * Get methods are O(1) as these are called much more often.
509          */
510         unsigned char* freebits = this->GetFreeBits();
511         for (unsigned char i = 0; i < bits_size; i++)
512         {
513                 /* Yes, this is right. You'll notice we terminate the  loop when !current_pos,
514                  * this is because we logic shift our bit off the end of unsigned char, and its
515                  * lost, making the loop counter 0 when we're done.
516                  */
517                 for (unsigned char current_pos = 1; current_pos; current_pos = current_pos << 1)
518                 {
519                         if (!(freebits[i] & current_pos))
520                         {
521                                 freebits[i] |= current_pos;
522                                 return std::make_pair(i, current_pos);
523                         }
524                 }
525         }
526         /* We dont have any free space left, increase by one */
527
528         if (bits_size == 255)
529                 /* Oh dear, cant grow it any further */
530                 throw std::bad_alloc();
531
532         unsigned char old_bits_size = bits_size;
533         bits_size++;
534         /* Allocate new bitfield space */
535         unsigned char* temp_bits = new unsigned char[bits_size];
536         unsigned char* temp_freebits = new unsigned char[bits_size];
537         /* Copy the old data in */
538         memcpy(temp_bits, bits, old_bits_size);
539         memcpy(temp_freebits, freebits, old_bits_size);
540         /* Delete the old data pointers */
541         delete[] bits;
542         delete[] freebits;
543         /* Swap the pointers over so now the new 
544          * pointers point to our member values
545          */
546         bits = temp_bits;
547         freebits = temp_freebits;
548         this->SetFreeBits(freebits);
549         /* Initialize the new byte on the end of
550          * the bitfields, pre-allocate the one bit
551          * for this allocation
552          */
553         bits[old_bits_size] = 0;
554         freebits[old_bits_size] = 1;
555         /* We already know where we just allocated
556          * the bitfield, so no loop needed
557          */
558         return std::make_pair(old_bits_size, 1);
559 }
560
561 bool irc::dynamicbitmask::Deallocate(irc::bitfield &pos)
562 {
563         /* We dont bother to shrink the bitfield
564          * on deallocation, the most we could do
565          * is save one byte (!) and this would cost
566          * us a loop (ugly O(n) stuff) so we just
567          * clear the bit and leave the memory
568          * claimed -- nobody will care about one
569          * byte.
570          */
571         if (pos.first < bits_size)
572         {
573                 this->GetFreeBits()[pos.first] &= ~pos.second;
574                 return true;
575         }
576         /* They gave a bitfield outside of the
577          * length of our array. BAD programmer.
578          */
579         return false;
580 }
581
582 void irc::dynamicbitmask::Toggle(irc::bitfield &pos, bool state)
583 {
584         /* Range check the value */
585         if (pos.first < bits_size)
586         {
587                 if (state)
588                         /* Set state, OR the state in */
589                         bits[pos.first] |= pos.second;
590                 else
591                         /* Clear state, AND the !state out */
592                         bits[pos.first] &= ~pos.second;
593         }
594 }
595
596 bool irc::dynamicbitmask::Get(irc::bitfield &pos)
597 {
598         /* Range check the value */
599         if (pos.first < bits_size)
600                 return (bits[pos.first] & pos.second);
601         else
602                 /* We can't return false, otherwise we can't
603                  * distinguish between failure and a cleared bit!
604                  * Our only sensible choice is to throw (ew).
605                  */
606                 throw ModuleException("irc::dynamicbitmask::Get(): Invalid bitfield, out of range");
607 }
608
609 unsigned char irc::dynamicbitmask::GetSize()
610 {
611         return bits_size;
612 }
613
614 std::string assign(const irc::string &other)
615 {
616         return other.c_str();
617 }
618
619 irc::string assign(const std::string &other)
620 {
621         return other.c_str();
622 }
623