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