]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/hashcomp.cpp
b5740d95bc8c04429b6c5a53c9f3f7fcc0cc1ab2
[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 #ifndef WIN32
17 #include <ext/hash_map>
18 #define nspace __gnu_cxx
19 #else
20 #include <hash_map>
21 #define nspace stdext
22 using stdext::hash_map;
23 #endif
24
25 /******************************************************
26  *
27  * The hash functions of InspIRCd are the centrepoint
28  * of the entire system. If these functions are
29  * inefficient or wasteful, the whole program suffers
30  * as a result. A lot of C programmers in the ircd
31  * scene spend a lot of time debating (arguing) about
32  * the best way to write hash functions to hash irc
33  * nicknames, channels etc.
34  * We are lucky as C++ developers as hash_map does
35  * a lot of this for us. It does intellegent memory
36  * requests, bucketing, search functions, insertion
37  * and deletion etc. All we have to do is write some
38  * overloaded comparison and hash value operators which
39  * cause it to act in an irc-like way. The features we
40  * add to the standard hash_map are:
41  *
42  * Case insensitivity: The hash_map will be case
43  * insensitive.
44  *
45  * Scandanavian Comparisons: The characters [, ], \ will
46  * be considered the lowercase of {, } and |.
47  *
48  ******************************************************/
49
50 using namespace irc::sockets;
51
52 /* convert a string to lowercase. Note following special circumstances
53  * taken from RFC 1459. Many "official" server branches still hold to this
54  * rule so i will too;
55  *
56  *  Because of IRC's scandanavian origin, the characters {}| are
57  *  considered to be the lower case equivalents of the characters []\,
58  *  respectively. This is a critical issue when determining the
59  *  equivalence of two nicknames.
60  */
61 void nspace::strlower(char *n)
62 {
63         if (n)
64         {
65                 for (char* t = n; *t; t++)
66                         *t = lowermap[(unsigned char)*t];
67         }
68 }
69
70 #ifndef WIN32
71 size_t nspace::hash<string>::operator()(const string &s) const
72 #else
73 size_t nspace::hash_compare<string, std::less<string> >::operator()(const string &s) const
74 #endif
75 {
76         /* XXX: NO DATA COPIES! :)
77          * The hash function here is practically
78          * a copy of the one in STL's hash_fun.h,
79          * only with *x replaced with lowermap[*x].
80          * This avoids a copy to use hash<const char*>
81          */
82         register size_t t = 0;
83         for (std::string::const_iterator x = s.begin(); x != s.end(); ++x) /* ++x not x++, as its faster */
84                 t = 5 * t + lowermap[(unsigned char)*x];
85         return t;
86 }
87
88 #ifndef WIN32
89 size_t nspace::hash<irc::string>::operator()(const irc::string &s) const
90 #else
91 size_t nspace::hash_compare<irc::string, std::less<irc::string> >::operator()(const irc::string &s) const
92 #endif
93 {
94         register size_t t = 0;
95         for (irc::string::const_iterator x = s.begin(); x != s.end(); ++x) /* ++x not x++, as its faster */
96                 t = 5 * t + lowermap[(unsigned char)*x];
97         return t;
98 }
99
100 bool irc::StrHashComp::operator()(const std::string& s1, const std::string& s2) const
101 {
102         unsigned char* n1 = (unsigned char*)s1.c_str();
103         unsigned char* n2 = (unsigned char*)s2.c_str();
104         for (; *n1 && *n2; n1++, n2++)
105                 if (lowermap[*n1] != lowermap[*n2])
106                         return false;
107         return (lowermap[*n1] == lowermap[*n2]);
108 }
109
110 /******************************************************
111  *
112  * This is the implementation of our special irc::string
113  * class which is a case-insensitive equivalent to
114  * std::string which is not only case-insensitive but
115  * can also do scandanavian comparisons, e.g. { = [, etc.
116  *
117  * This class depends on the const array 'lowermap'.
118  *
119  ******************************************************/
120
121 bool irc::irc_char_traits::eq(char c1st, char c2nd)
122 {
123         return lowermap[(unsigned char)c1st] == lowermap[(unsigned char)c2nd];
124 }
125
126 bool irc::irc_char_traits::ne(char c1st, char c2nd)
127 {
128         return lowermap[(unsigned char)c1st] != lowermap[(unsigned char)c2nd];
129 }
130
131 bool irc::irc_char_traits::lt(char c1st, char c2nd)
132 {
133         return lowermap[(unsigned char)c1st] < lowermap[(unsigned char)c2nd];
134 }
135
136 int irc::irc_char_traits::compare(const char* str1, const char* str2, size_t n)
137 {
138         for(unsigned int i = 0; i < n; i++)
139         {
140                 if(lowermap[(unsigned char)*str1] > lowermap[(unsigned char)*str2])
141                         return 1;
142
143                 if(lowermap[(unsigned char)*str1] < lowermap[(unsigned char)*str2])
144                         return -1;
145
146                 if(*str1 == 0 || *str2 == 0)
147                         return 0;
148
149                 str1++;
150                 str2++;
151         }
152         return 0;
153 }
154
155 const char* irc::irc_char_traits::find(const char* s1, int  n, char c)
156 {
157         while(n-- > 0 && lowermap[(unsigned char)*s1] != lowermap[(unsigned char)c])
158                 s1++;
159         return s1;
160 }
161
162 irc::tokenstream::tokenstream(const std::string &source) : tokens(source), last_pushed(false)
163 {
164         /* Record starting position and current position */
165         last_starting_position = tokens.begin();
166         n = tokens.begin();
167 }
168
169 irc::tokenstream::~tokenstream()
170 {
171 }
172
173 bool irc::tokenstream::GetToken(std::string &token)
174 {
175         std::string::iterator lsp = last_starting_position;
176
177         while (n != tokens.end())
178         {
179                 /** Skip multi space, converting "  " into " "
180                  */
181                 while ((n+1 != tokens.end()) && (*n == ' ') && (*(n+1) == ' '))
182                         n++;
183
184                 if ((last_pushed) && (*n == ':'))
185                 {
186                         /* If we find a token thats not the first and starts with :,
187                          * this is the last token on the line
188                          */
189                         std::string::iterator curr = ++n;
190                         n = tokens.end();
191                         token = std::string(curr, tokens.end());
192                         return true;
193                 }
194
195                 last_pushed = false;
196
197                 if ((*n == ' ') || (n+1 == tokens.end()))
198                 {
199                         /* If we find a space, or end of string, this is the end of a token.
200                          */
201                         last_starting_position = n+1;
202                         last_pushed = true;
203
204                         std::string strip(lsp, n+1 == tokens.end() ? n+1  : n++);
205                         while ((strip.length()) && (strip.find_last_of(' ') == strip.length() - 1))
206                                 strip.erase(strip.end() - 1);
207
208                         token = strip;
209                         return !token.empty();
210                 }
211
212                 n++;
213         }
214         token.clear();
215         return false;
216 }
217
218 bool irc::tokenstream::GetToken(irc::string &token)
219 {
220         std::string stdstring;
221         bool returnval = GetToken(stdstring);
222         token = assign(stdstring);
223         return returnval;
224 }
225
226 bool irc::tokenstream::GetToken(int &token)
227 {
228         std::string tok;
229         bool returnval = GetToken(tok);
230         token = ConvToInt(tok);
231         return returnval;
232 }
233
234 bool irc::tokenstream::GetToken(long &token)
235 {
236         std::string tok;
237         bool returnval = GetToken(tok);
238         token = ConvToInt(tok);
239         return returnval;
240 }
241
242 irc::sepstream::sepstream(const std::string &source, char seperator) : tokens(source), sep(seperator)
243 {
244         last_starting_position = tokens.begin();
245         n = tokens.begin();
246 }
247
248 const std::string irc::sepstream::GetToken()
249 {
250         std::string::iterator lsp = last_starting_position;
251
252         while (n != tokens.end())
253         {
254                 /** Skip multi seps, converting "<sep><sep>" into "<sep>"
255                  */
256                 while ((n+1 != tokens.end()) && (*n == sep) && (*(n+1) == sep))
257                         n++;
258
259                 if ((*n == sep) || (n+1 == tokens.end()))
260                 {
261                         last_starting_position = n+1;
262                         std::string strip = std::string(lsp, n+1 == tokens.end() ? n+1  : n++);
263
264                         while ((strip.length()) && (strip.find_last_of(sep) == strip.length() - 1))
265                                 strip.erase(strip.end() - 1);
266
267                         return strip;
268                 }
269
270                 n++;
271         }
272
273         return "";
274 }
275
276 const std::string irc::sepstream::GetRemaining()
277 {
278         return std::string(n, tokens.end());
279 }
280
281 bool irc::sepstream::StreamEnd()
282 {
283         return ((n + 1) == tokens.end());
284 }
285
286 irc::sepstream::~sepstream()
287 {
288 }
289
290 std::string irc::hex(const unsigned char *raw, size_t rawsz)
291 {
292         if (!rawsz)
293                 return "";
294
295         /* EWW! This used to be using sprintf, which is WAY inefficient. -Special */
296         
297         const char *hex = "0123456789abcdef";
298         static char hexbuf[MAXBUF];
299
300         size_t i, j;
301         for (i = 0, j = 0; j < rawsz; ++j)
302         {
303                 hexbuf[i++] = hex[raw[j] / 16];
304                 hexbuf[i++] = hex[raw[j] % 16];
305         }
306         hexbuf[i] = 0;
307
308         return hexbuf;
309 }
310
311 CoreExport const char* irc::Spacify(const 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, int max_line_size)
350 {
351         if (sequence.empty())
352         {
353                 result.clear();
354                 return 0;
355         }
356
357         int n = 0;
358         int size = 1; /* Account for initial +/- char */
359         int nextsize = 0;
360         result.clear();
361         result.push_back(adding ? "+" : "-");
362
363         if (sequence.size() > 1)
364                 nextsize = sequence[1].length() + 2;
365
366         while (!sequence[0].empty() && (sequence.size() > 1) && (result.size() < MAXMODES) && ((size + nextsize) < max_line_size))
367         {
368                 result[0] += *(sequence[0].begin());
369                 if (!sequence[1].empty())
370                 {
371                         result.push_back(sequence[1]);
372                         size += nextsize; /* Account for mode character and whitespace */
373                 }
374                 sequence[0].erase(sequence[0].begin());
375                 sequence.erase(sequence.begin() + 1);
376
377                 if (sequence.size() > 1)
378                         nextsize = sequence[1].length() + 2;
379
380                 n++;
381         }
382
383         return n;
384 }
385
386 irc::stringjoiner::stringjoiner(const std::string &seperator, const std::vector<std::string> &sequence, int begin, int end)
387 {
388         for (int v = begin; v < end; v++)
389                 joined.append(sequence[v]).append(seperator);
390         joined.append(sequence[end]);
391 }
392
393 irc::stringjoiner::stringjoiner(const std::string &seperator, const std::deque<std::string> &sequence, int begin, int end)
394 {
395         for (int v = begin; v < end; v++)
396                 joined.append(sequence[v]).append(seperator);
397         joined.append(sequence[end]);
398 }
399
400 irc::stringjoiner::stringjoiner(const std::string &seperator, const char** sequence, int begin, int end)
401 {
402         for (int v = begin; v < end; v++)
403                 joined.append(sequence[v]).append(seperator);
404         joined.append(sequence[end]);
405 }
406
407 std::string& irc::stringjoiner::GetJoined()
408 {
409         return joined;
410 }
411
412 irc::portparser::portparser(const std::string &source, bool allow_overlapped) : in_range(0), range_begin(0), range_end(0), overlapped(allow_overlapped)
413 {
414         sep = new irc::commasepstream(source);
415         overlap_set.clear();
416 }
417
418 irc::portparser::~portparser()
419 {
420         delete sep;
421 }
422
423 bool irc::portparser::Overlaps(long val)
424 {
425         if (!overlapped)
426                 return false;
427
428         if (overlap_set.find(val) == overlap_set.end())
429         {
430                 overlap_set[val] = true;
431                 return false;
432         }
433         else
434                 return true;
435 }
436
437 long irc::portparser::GetToken()
438 {
439         if (in_range > 0)
440         {
441                 in_range++;
442                 if (in_range <= range_end)
443                 {
444                         if (!Overlaps(in_range))
445                         {
446                                 return in_range;
447                         }
448                         else
449                         {
450                                 while (((Overlaps(in_range)) && (in_range <= range_end)))
451                                         in_range++;
452                                 
453                                 if (in_range <= range_end)
454                                         return in_range;
455                         }
456                 }
457                 else
458                         in_range = 0;
459         }
460
461         std::string x = sep->GetToken();
462
463         if (x.empty())
464                 return 0;
465
466         while (Overlaps(atoi(x.c_str())))
467         {
468                 x = sep->GetToken();
469
470                 if (x.empty())
471                         return 0;
472         }
473
474         std::string::size_type dash = x.rfind('-');
475         if (dash != std::string::npos)
476         {
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());
481
482                 if ((range_begin > 0) && (range_end > 0) && (range_begin < 65536) && (range_end < 65536) && (range_begin < range_end))
483                 {
484                         in_range = range_begin;
485                         return in_range;
486                 }
487                 else
488                 {
489                         /* Assume its just the one port */
490                         return atoi(sbegin.c_str());
491                 }
492         }
493         else
494         {
495                 return atoi(x.c_str());
496         }
497 }
498
499 irc::dynamicbitmask::dynamicbitmask() : bits_size(4)
500 {
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.
504          */
505         bits = new unsigned char[bits_size];
506         memset(bits, 0, bits_size);
507 }
508
509 irc::dynamicbitmask::~dynamicbitmask()
510 {
511         /* Tidy up the entire used memory on delete */
512         delete[] bits;
513 }
514
515 irc::bitfield irc::dynamicbitmask::Allocate()
516 {
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.
520          */
521         unsigned char* freebits = this->GetFreeBits();
522         for (unsigned char i = 0; i < bits_size; i++)
523         {
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.
527                  */
528                 for (unsigned char current_pos = 1; current_pos; current_pos = current_pos << 1)
529                 {
530                         if (!(freebits[i] & current_pos))
531                         {
532                                 freebits[i] |= current_pos;
533                                 return std::make_pair(i, current_pos);
534                         }
535                 }
536         }
537         /* We dont have any free space left, increase by one */
538
539         if (bits_size == 255)
540                 /* Oh dear, cant grow it any further */
541                 throw std::bad_alloc();
542
543         unsigned char old_bits_size = bits_size;
544         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 */
552         delete[] bits;
553         delete[] freebits;
554         /* Swap the pointers over so now the new 
555          * pointers point to our member values
556          */
557         bits = temp_bits;
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
563          */
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
568          */
569         return std::make_pair(old_bits_size, 1);
570 }
571
572 bool irc::dynamicbitmask::Deallocate(irc::bitfield &pos)
573 {
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
580          * byte.
581          */
582         if (pos.first < bits_size)
583         {
584                 this->GetFreeBits()[pos.first] &= ~pos.second;
585                 return true;
586         }
587         /* They gave a bitfield outside of the
588          * length of our array. BAD programmer.
589          */
590         return false;
591 }
592
593 void irc::dynamicbitmask::Toggle(irc::bitfield &pos, bool state)
594 {
595         /* Range check the value */
596         if (pos.first < bits_size)
597         {
598                 if (state)
599                         /* Set state, OR the state in */
600                         bits[pos.first] |= pos.second;
601                 else
602                         /* Clear state, AND the !state out */
603                         bits[pos.first] &= ~pos.second;
604         }
605 }
606
607 bool irc::dynamicbitmask::Get(irc::bitfield &pos)
608 {
609         /* Range check the value */
610         if (pos.first < bits_size)
611                 return (bits[pos.first] & pos.second);
612         else
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).
616                  */
617                 throw ModuleException("irc::dynamicbitmask::Get(): Invalid bitfield, out of range");
618 }
619
620 unsigned char irc::dynamicbitmask::GetSize()
621 {
622         return bits_size;
623 }
624