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;
112 /** The irc_char_traits class is used for RFC-style comparison of strings.
113 * This class is used to implement irc::string, a case-insensitive, RFC-
114 * comparing string class.
116 struct irc_char_traits : std::char_traits<char> {
118 /** Check if two chars match.
119 * @param c1st First character
120 * @param c2nd Second character
121 * @return true if the characters are equal
123 static bool eq(char c1st, char c2nd);
125 /** Check if two chars do NOT match.
126 * @param c1st First character
127 * @param c2nd Second character
128 * @return true if the characters are unequal
130 static bool ne(char c1st, char c2nd);
132 /** Check if one char is less than another.
133 * @param c1st First character
134 * @param c2nd Second character
135 * @return true if c1st is less than c2nd
137 static bool lt(char c1st, char c2nd);
139 /** Compare two strings of size n.
140 * @param str1 First string
141 * @param str2 Second string
142 * @param n Length to compare to
143 * @return similar to strcmp, zero for equal, less than zero for str1
144 * being less and greater than zero for str1 being greater than str2.
146 static CoreExport int compare(const char* str1, const char* str2, size_t n);
148 /** Find a char within a string up to position n.
149 * @param s1 String to find in
150 * @param n Position to search up to
151 * @param c Character to search for
152 * @return Pointer to the first occurance of c in s1
154 static CoreExport const char* find(const char* s1, int n, char c);
157 /** Compose a hex string from raw data.
158 * @param raw The raw data to compose hex from
159 * @param rawsz The size of the raw data buffer
160 * @return The hex string.
162 CoreExport std::string hex(const unsigned char *raw, size_t rawsz);
164 /** This typedef declares irc::string based upon irc_char_traits.
166 typedef std::basic_string<char, irc_char_traits, std::allocator<char> > string;
168 /** irc::stringjoiner joins string lists into a string, using
169 * the given seperator string.
170 * This class can join a vector of std::string, a deque of
171 * std::string, or a const char* const* array, using overloaded
174 class CoreExport stringjoiner
184 /** Join elements of a vector, between (and including) begin and end
185 * @param seperator The string to seperate values with
186 * @param sequence One or more items to seperate
187 * @param begin The starting element in the sequence to be joined
188 * @param end The ending element in the sequence to be joined
190 stringjoiner(const std::string &seperator, const std::vector<std::string> &sequence, int begin, int end);
192 /** Join elements of a deque, between (and including) begin and end
193 * @param seperator The string to seperate values with
194 * @param sequence One or more items to seperate
195 * @param begin The starting element in the sequence to be joined
196 * @param end The ending element in the sequence to be joined
198 stringjoiner(const std::string &seperator, const std::deque<std::string> &sequence, int begin, int end);
200 /** Join elements of an array of char arrays, between (and including) begin and end
201 * @param seperator The string to seperate values with
202 * @param sequence One or more items to seperate
203 * @param begin The starting element in the sequence to be joined
204 * @param end The ending element in the sequence to be joined
206 stringjoiner(const std::string &seperator, const char* const* sequence, int begin, int end);
208 /** Get the joined sequence
209 * @return A reference to the joined string
211 std::string& GetJoined();
214 /** irc::modestacker stacks mode sequences into a list.
215 * It can then reproduce this list, clamped to a maximum of MAXMODES
218 class CoreExport modestacker
221 /** The mode sequence and its parameters
223 std::deque<std::string> sequence;
225 /** True if the mode sequence is initially adding
226 * characters, false if it is initially removing
232 /** Construct a new modestacker.
233 * @param add True if the stack is adding modes,
234 * false if it is removing them
236 modestacker(bool add);
238 /** Push a modeletter and its parameter onto the stack.
239 * No checking is performed as to if this mode actually
240 * requires a parameter. If you stack invalid mode
241 * sequences, they will be tidied if and when they are
242 * passed to a mode parser.
243 * @param modeletter The mode letter to insert
244 * @param parameter The parameter for the mode
246 void Push(char modeletter, const std::string ¶meter);
248 /** Push a modeletter without parameter onto the stack.
249 * No checking is performed as to if this mode actually
250 * requires a parameter. If you stack invalid mode
251 * sequences, they will be tidied if and when they are
252 * passed to a mode parser.
253 * @param modeletter The mode letter to insert
255 void Push(char modeletter);
257 /** Push a '+' symbol onto the stack.
261 /** Push a '-' symbol onto the stack.
265 /** Return zero or more elements which form the
266 * mode line. This will be clamped to a max of
267 * MAXMODES items (MAXMODES-1 mode parameters and
268 * one mode sequence string), and max_line_size
269 * characters. As specified below, this function
270 * should be called in a loop until it returns zero,
271 * indicating there are no more modes to return.
272 * @param result The vector to populate. This will not
273 * be cleared before it is used.
274 * @param max_line_size The maximum size of the line
275 * to build, in characters, seperate to MAXMODES.
276 * @return The number of elements in the deque.
277 * The function should be called repeatedly until it
278 * returns 0, in case there are multiple lines of
279 * mode changes to be obtained.
281 int GetStackedLine(std::vector<std::string> &result, int max_line_size = 360);
285 /** irc::tokenstream reads a string formatted as per RFC1459 and RFC2812.
286 * It will split the string into 'tokens' each containing one parameter
288 * For instance, if it is instantiated with the string:
289 * "PRIVMSG #test :foo bar baz qux"
290 * then each successive call to tokenstream::GetToken() will return
291 * "PRIVMSG", "#test", "foo bar baz qux", "".
292 * Note that if the whole string starts with a colon this is not taken
293 * to mean the string is all one parameter, and the first item in the
294 * list will be ":item". This is to allow for parsing 'source' fields
297 class CoreExport tokenstream
305 /** Last position of a seperator token
307 std::string::iterator last_starting_position;
309 /** Current string position
311 std::string::iterator n;
313 /** True if the last value was an ending value
318 /** Create a tokenstream and fill it with the provided data
320 tokenstream(const std::string &source);
326 /** Fetch the next token from the stream as a std::string
327 * @param token The next token available, or an empty string if none remain
328 * @return True if tokens are left to be read, false if the last token was just retrieved.
330 bool GetToken(std::string &token);
332 /** Fetch the next token from the stream as an irc::string
333 * @param token The next token available, or an empty string if none remain
334 * @return True if tokens are left to be read, false if the last token was just retrieved.
336 bool GetToken(irc::string &token);
338 /** Fetch the next token from the stream as an integer
339 * @param token The next token available, or undefined if none remain
340 * @return True if tokens are left to be read, false if the last token was just retrieved.
342 bool GetToken(int &token);
344 /** Fetch the next token from the stream as a long integer
345 * @param token The next token available, or undefined if none remain
346 * @return True if tokens are left to be read, false if the last token was just retrieved.
348 bool GetToken(long &token);
351 /** irc::sepstream allows for splitting token seperated lists.
352 * Each successive call to sepstream::GetToken() returns
353 * the next token, until none remain, at which point the method returns
356 class CoreExport sepstream
362 /** Last position of a seperator token
364 std::string::iterator last_starting_position;
365 /** Current string position
367 std::string::iterator n;
372 /** Create a sepstream and fill it with the provided data
374 sepstream(const std::string &source, char seperator);
378 virtual ~sepstream();
380 /** Fetch the next token from the stream
381 * @param token The next token from the stream is placed here
382 * @return True if tokens still remain, false if there are none left
384 virtual bool GetToken(std::string &token);
386 /** Fetch the entire remaining stream, without tokenizing
387 * @return The remaining part of the stream
389 virtual const std::string GetRemaining();
391 /** Returns true if the end of the stream has been reached
392 * @return True if the end of the stream has been reached, otherwise false
394 virtual bool StreamEnd();
397 /** A derived form of sepstream, which seperates on commas
399 class CoreExport commasepstream : public sepstream
402 /** Initialize with comma seperator
404 commasepstream(const std::string &source) : sepstream(source, ',')
409 /** A derived form of sepstream, which seperates on spaces
411 class CoreExport spacesepstream : public sepstream
414 /** Initialize with space seperator
416 spacesepstream(const std::string &source) : sepstream(source, ' ')
421 /** The portparser class seperates out a port range into integers.
422 * A port range may be specified in the input string in the form
423 * "6660,6661,6662-6669,7020". The end of the stream is indicated by
424 * a return value of 0 from portparser::GetToken(). If you attempt
425 * to specify an illegal range (e.g. one where start >= end, or
426 * start or end < 0) then GetToken() will return the first element
427 * of the pair of numbers.
429 class CoreExport portparser
433 /** Used to split on commas
437 /** Current position in a range of ports
441 /** Starting port in a range of ports
445 /** Ending port in a range of ports
449 /** Allow overlapped port ranges
453 /** Used to determine overlapping of ports
454 * without O(n) algorithm being used
456 std::set<long> overlap_set;
458 /** Returns true if val overlaps an existing range
460 bool Overlaps(long val);
463 /** Create a portparser and fill it with the provided data
464 * @param source The source text to parse from
465 * @param allow_overlapped Allow overlapped ranges
467 portparser(const std::string &source, bool allow_overlapped = true);
469 /** Fetch the next token from the stream
470 * @return The next port number is returned, or 0 if none remain
475 /** Turn _ characters in a string into spaces
476 * @param n String to translate
477 * @return The new value with _ translated to space.
479 CoreExport const char* Spacify(const char* n);
483 /** Hash an irc::string using RFC1459 case sensitivity rules
484 * @param s A string to hash
485 * @return The hash value
487 size_t CoreExport operator()(const irc::string &s) const;
491 /* Define operators for using >> and << with irc::string to an ostream on an istream. */
492 /* This was endless fun. No. Really. */
493 /* It was also the first core change Ommeh made, if anyone cares */
495 /** Operator << for irc::string
497 inline std::ostream& operator<<(std::ostream &os, const irc::string &str) { return os << str.c_str(); }
499 /** Operator >> for irc::string
501 inline std::istream& operator>>(std::istream &is, irc::string &str)
509 /* Define operators for + and == with irc::string to std::string for easy assignment
514 inline std::string operator+ (std::string& leftval, irc::string& rightval)
516 return leftval + std::string(rightval.c_str());
519 /* Define operators for + and == with irc::string to std::string for easy assignment
524 inline irc::string operator+ (irc::string& leftval, std::string& rightval)
526 return leftval + irc::string(rightval.c_str());
529 /* Define operators for + and == with irc::string to std::string for easy assignment
534 inline bool operator== (const std::string& leftval, const irc::string& rightval)
536 return (leftval.c_str() == rightval);
539 /* Define operators for + and == with irc::string to std::string for easy assignment
544 inline bool operator== (const irc::string& leftval, const std::string& rightval)
546 return (leftval == rightval.c_str());
549 /* Define operators != for irc::string to std::string for easy comparison
551 inline bool operator!= (const irc::string& leftval, const std::string& rightval)
553 return !(leftval == rightval.c_str());
556 /* Define operators != for std::string to irc::string for easy comparison
558 inline bool operator!= (const std::string& leftval, const irc::string& rightval)
560 return !(leftval.c_str() == rightval);
563 /** Assign an irc::string to a std::string.
565 inline std::string assign(const irc::string &other) { return other.c_str(); }
567 /** Assign a std::string to an irc::string.
569 inline irc::string assign(const std::string &other) { return other.c_str(); }
571 /** Trim the leading and trailing spaces from a std::string.
573 inline std::string& trim(std::string &str)
575 std::string::size_type start = str.find_first_not_of(" ");
576 std::string::size_type end = str.find_last_not_of(" ");
577 if (start == std::string::npos || end == std::string::npos)
580 str = str.substr(start, end-start+1);
592 size_t CoreExport operator()(const std::string &s) const;
595 /** Convert a string to lower case respecting RFC1459
596 * @param n A string to lowercase
598 void strlower(char *n);