2 * InspIRCd -- Internet Relay Chat Daemon
4 * Copyright (C) 2011 Adam <Adam@anope.org>
5 * Copyright (C) 2009 Daniel De Graaf <danieldg@inspircd.org>
6 * Copyright (C) 2007, 2009 Dennis Friis <peavey@inspircd.org>
7 * Copyright (C) 2005-2009 Craig Edwards <craigedwards@brainbox.cc>
8 * Copyright (C) 2007-2008 Robin Burchell <robin+git@viroteck.net>
9 * Copyright (C) 2008 Pippijn van Steenhoven <pip88nl@gmail.com>
11 * This file is part of InspIRCd. InspIRCd is free software: you can
12 * redistribute it and/or modify it under the terms of the GNU General Public
13 * License as published by the Free Software Foundation, version 2.
15 * This program is distributed in the hope that it will be useful, but WITHOUT
16 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
17 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
20 * You should have received a copy of the GNU General Public License
21 * along with this program. If not, see <http://www.gnu.org/licenses/>.
35 /*******************************************************
36 * This file contains classes and templates that deal
37 * with the comparison and hashing of 'irc strings'.
38 * An 'irc string' is a string which compares in a
39 * case insensitive manner, and as per RFC 1459 will
40 * treat [ identical to {, ] identical to }, and \
43 * Our hashing functions are designed to accept
44 * std::string and compare/hash them as type irc::string
45 * by converting them internally. This makes them
46 * backwards compatible with other code which is not
47 * aware of irc::string.
48 *******************************************************/
50 /** Seperate from the other casemap tables so that code *can* still exclusively rely on RFC casemapping
53 * This is provided as a pointer so that modules can change it to their custom mapping tables,
54 * e.g. for national character support.
56 CoreExport extern unsigned const char *national_case_insensitive_map;
58 /** A mapping of uppercase to lowercase, including scandinavian
59 * 'oddities' as specified by RFC1459, e.g. { -> [, and | -> \
61 CoreExport extern unsigned const char rfc_case_insensitive_map[256];
63 /** Case insensitive map, ASCII rules.
67 CoreExport extern unsigned const char ascii_case_insensitive_map[256];
69 /** Case sensitive (identity) map.
71 CoreExport extern unsigned const char rfc_case_sensitive_map[256];
73 template<typename T> const T& SearchAndReplace(T& text, const T& pattern, const T& replace)
76 if ((!pattern.empty()) && (!text.empty()))
78 for (std::string::size_type n = 0; n != text.length(); ++n)
80 if (text.length() >= pattern.length() && text.substr(n, pattern.length()) == pattern)
82 /* Found the pattern in the text, replace it, and advance */
83 replacement.append(replace);
84 n = n + pattern.length() - 1;
88 replacement += text[n];
96 /** The irc namespace contains a number of helper classes.
101 /** This class returns true if two strings match.
102 * Case sensitivity is ignored, and the RFC 'character set'
105 struct CoreExport StrHashComp
107 /** The operator () does the actual comparison in hash_map
109 bool operator()(const std::string& s1, const std::string& s2) const;
114 size_t CoreExport operator()(const std::string &s) const;
117 /** The irc_char_traits class is used for RFC-style comparison of strings.
118 * This class is used to implement irc::string, a case-insensitive, RFC-
119 * comparing string class.
121 struct irc_char_traits : std::char_traits<char> {
123 /** Check if two chars match.
124 * @param c1st First character
125 * @param c2nd Second character
126 * @return true if the characters are equal
128 static bool eq(char c1st, char c2nd);
130 /** Check if two chars do NOT match.
131 * @param c1st First character
132 * @param c2nd Second character
133 * @return true if the characters are unequal
135 static bool ne(char c1st, char c2nd);
137 /** Check if one char is less than another.
138 * @param c1st First character
139 * @param c2nd Second character
140 * @return true if c1st is less than c2nd
142 static bool lt(char c1st, char c2nd);
144 /** Compare two strings of size n.
145 * @param str1 First string
146 * @param str2 Second string
147 * @param n Length to compare to
148 * @return similar to strcmp, zero for equal, less than zero for str1
149 * being less and greater than zero for str1 being greater than str2.
151 static CoreExport int compare(const char* str1, const char* str2, size_t n);
153 /** Find a char within a string up to position n.
154 * @param s1 String to find in
155 * @param n Position to search up to
156 * @param c Character to search for
157 * @return Pointer to the first occurance of c in s1
159 static CoreExport const char* find(const char* s1, int n, char c);
162 /** This typedef declares irc::string based upon irc_char_traits.
164 typedef std::basic_string<char, irc_char_traits, std::allocator<char> > string;
166 /** irc::stringjoiner joins string lists into a string, using
167 * space as the separator.
168 * This class can join a vector of std::string.
170 class CoreExport stringjoiner
180 /** Join all elements of a vector, in the resulting string
181 * each element will be seperated by a single space character.
182 * @param sequence Zero or more items to seperate
184 stringjoiner(const std::vector<std::string>& sequence);
186 /** Get the joined sequence
187 * @return A constant reference to the joined string
189 const std::string& GetJoined() const { return joined; }
192 /** irc::modestacker stacks mode sequences into a list.
193 * It can then reproduce this list, clamped to a maximum of MAXMODES
196 class CoreExport modestacker
199 /** The mode sequence and its parameters
201 std::deque<std::string> sequence;
203 /** True if the mode sequence is initially adding
204 * characters, false if it is initially removing
210 /** Construct a new modestacker.
211 * @param add True if the stack is adding modes,
212 * false if it is removing them
214 modestacker(bool add);
216 /** Push a modeletter and its parameter onto the stack.
217 * No checking is performed as to if this mode actually
218 * requires a parameter. If you stack invalid mode
219 * sequences, they will be tidied if and when they are
220 * passed to a mode parser.
221 * @param modeletter The mode letter to insert
222 * @param parameter The parameter for the mode
224 void Push(char modeletter, const std::string ¶meter);
226 /** Push a modeletter without parameter onto the stack.
227 * No checking is performed as to if this mode actually
228 * requires a parameter. If you stack invalid mode
229 * sequences, they will be tidied if and when they are
230 * passed to a mode parser.
231 * @param modeletter The mode letter to insert
233 void Push(char modeletter);
235 /** Push a '+' symbol onto the stack.
239 /** Push a '-' symbol onto the stack.
243 /** Return zero or more elements which form the
244 * mode line. This will be clamped to a max of
245 * MAXMODES items (MAXMODES-1 mode parameters and
246 * one mode sequence string), and max_line_size
247 * characters. As specified below, this function
248 * should be called in a loop until it returns zero,
249 * indicating there are no more modes to return.
250 * @param result The vector to populate. This will not
251 * be cleared before it is used.
252 * @param max_line_size The maximum size of the line
253 * to build, in characters, seperate to MAXMODES.
254 * @return The number of elements in the deque.
255 * The function should be called repeatedly until it
256 * returns 0, in case there are multiple lines of
257 * mode changes to be obtained.
259 int GetStackedLine(std::vector<std::string> &result, int max_line_size = 360);
263 /** irc::sepstream allows for splitting token seperated lists.
264 * Each successive call to sepstream::GetToken() returns
265 * the next token, until none remain, at which point the method returns
268 class CoreExport sepstream
277 /** Current string position
280 /** If set then GetToken() can return an empty string
284 /** Create a sepstream and fill it with the provided data
286 sepstream(const std::string &source, char separator, bool allowempty = false);
288 /** Fetch the next token from the stream
289 * @param token The next token from the stream is placed here
290 * @return True if tokens still remain, false if there are none left
292 bool GetToken(std::string& token);
294 /** Fetch the entire remaining stream, without tokenizing
295 * @return The remaining part of the stream
297 const std::string GetRemaining();
299 /** Returns true if the end of the stream has been reached
300 * @return True if the end of the stream has been reached, otherwise false
305 /** A derived form of sepstream, which seperates on commas
307 class CoreExport commasepstream : public sepstream
310 /** Initialize with comma separator
312 commasepstream(const std::string &source, bool allowempty = false) : sepstream(source, ',', allowempty)
317 /** A derived form of sepstream, which seperates on spaces
319 class CoreExport spacesepstream : public sepstream
322 /** Initialize with space separator
324 spacesepstream(const std::string &source, bool allowempty = false) : sepstream(source, ' ', allowempty)
329 /** irc::tokenstream reads a string formatted as per RFC1459 and RFC2812.
330 * It will split the string into 'tokens' each containing one parameter
332 * For instance, if it is instantiated with the string:
333 * "PRIVMSG #test :foo bar baz qux"
334 * then each successive call to tokenstream::GetToken() will return
335 * "PRIVMSG", "#test", "foo bar baz qux", "".
336 * Note that if the whole string starts with a colon this is not taken
337 * to mean the string is all one parameter, and the first item in the
338 * list will be ":item". This is to allow for parsing 'source' fields
341 class CoreExport tokenstream : private spacesepstream
344 /** Create a tokenstream and fill it with the provided data
346 tokenstream(const std::string &source);
348 /** Fetch the next token from the stream as a std::string
349 * @param token The next token available, or an empty string if none remain
350 * @return True if tokens are left to be read, false if the last token was just retrieved.
352 bool GetToken(std::string &token);
354 /** Fetch the next token from the stream as an irc::string
355 * @param token The next token available, or an empty string if none remain
356 * @return True if tokens are left to be read, false if the last token was just retrieved.
358 bool GetToken(irc::string &token);
360 /** Fetch the next token from the stream as an integer
361 * @param token The next token available, or undefined if none remain
362 * @return True if tokens are left to be read, false if the last token was just retrieved.
364 bool GetToken(int &token);
366 /** Fetch the next token from the stream as a long integer
367 * @param token The next token available, or undefined if none remain
368 * @return True if tokens are left to be read, false if the last token was just retrieved.
370 bool GetToken(long &token);
373 /** The portparser class seperates out a port range into integers.
374 * A port range may be specified in the input string in the form
375 * "6660,6661,6662-6669,7020". The end of the stream is indicated by
376 * a return value of 0 from portparser::GetToken(). If you attempt
377 * to specify an illegal range (e.g. one where start >= end, or
378 * start or end < 0) then GetToken() will return the first element
379 * of the pair of numbers.
381 class CoreExport portparser
385 /** Used to split on commas
389 /** Current position in a range of ports
393 /** Starting port in a range of ports
397 /** Ending port in a range of ports
401 /** Allow overlapped port ranges
405 /** Used to determine overlapping of ports
406 * without O(n) algorithm being used
408 std::set<long> overlap_set;
410 /** Returns true if val overlaps an existing range
412 bool Overlaps(long val);
415 /** Create a portparser and fill it with the provided data
416 * @param source The source text to parse from
417 * @param allow_overlapped Allow overlapped ranges
419 portparser(const std::string &source, bool allow_overlapped = true);
421 /** Fetch the next token from the stream
422 * @return The next port number is returned, or 0 if none remain
429 /** Hash an irc::string using RFC1459 case sensitivity rules
430 * @param s A string to hash
431 * @return The hash value
433 size_t CoreExport operator()(const irc::string &s) const;
437 /* Define operators for using >> and << with irc::string to an ostream on an istream. */
438 /* This was endless fun. No. Really. */
439 /* It was also the first core change Ommeh made, if anyone cares */
441 /** Operator << for irc::string
443 inline std::ostream& operator<<(std::ostream &os, const irc::string &str) { return os << str.c_str(); }
445 /** Operator >> for irc::string
447 inline std::istream& operator>>(std::istream &is, irc::string &str)
455 /* Define operators for + and == with irc::string to std::string for easy assignment
460 inline std::string operator+ (std::string& leftval, irc::string& rightval)
462 return leftval + std::string(rightval.c_str());
465 /* Define operators for + and == with irc::string to std::string for easy assignment
470 inline irc::string operator+ (irc::string& leftval, std::string& rightval)
472 return leftval + irc::string(rightval.c_str());
475 /* Define operators for + and == with irc::string to std::string for easy assignment
480 inline bool operator== (const std::string& leftval, const irc::string& rightval)
482 return (leftval.c_str() == rightval);
485 /* Define operators for + and == with irc::string to std::string for easy assignment
490 inline bool operator== (const irc::string& leftval, const std::string& rightval)
492 return (leftval == rightval.c_str());
495 /* Define operators != for irc::string to std::string for easy comparison
497 inline bool operator!= (const irc::string& leftval, const std::string& rightval)
499 return !(leftval == rightval.c_str());
502 /* Define operators != for std::string to irc::string for easy comparison
504 inline bool operator!= (const std::string& leftval, const irc::string& rightval)
506 return !(leftval.c_str() == rightval);
509 /** Assign an irc::string to a std::string.
511 inline std::string assign(const irc::string &other) { return other.c_str(); }
513 /** Assign a std::string to an irc::string.
515 inline irc::string assign(const std::string &other) { return other.c_str(); }
517 /** Trim the leading and trailing spaces from a std::string.
519 inline std::string& trim(std::string &str)
521 std::string::size_type start = str.find_first_not_of(" ");
522 std::string::size_type end = str.find_last_not_of(" ");
523 if (start == std::string::npos || end == std::string::npos)
526 str = str.substr(start, end-start+1);