]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/helperfuncs.cpp
Remove dead code from UserManager::AddUser()
[user/henk/code/inspircd.git] / src / helperfuncs.cpp
1 /*
2  * InspIRCd -- Internet Relay Chat Daemon
3  *
4  *   Copyright (C) 2009-2010 Daniel De Graaf <danieldg@inspircd.org>
5  *   Copyright (C) 2006-2008 Robin Burchell <robin+git@viroteck.net>
6  *   Copyright (C) 2005-2008 Craig Edwards <craigedwards@brainbox.cc>
7  *   Copyright (C) 2008 Thomas Stagner <aquanight@inspircd.org>
8  *   Copyright (C) 2006-2007 Oliver Lupton <oliverlupton@gmail.com>
9  *   Copyright (C) 2007 Dennis Friis <peavey@inspircd.org>
10  *
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.
14  *
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
18  * details.
19  *
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/>.
22  */
23
24
25 #ifdef _WIN32
26 #define _CRT_RAND_S
27 #include <stdlib.h>
28 #endif
29
30 #include "inspircd.h"
31 #include "xline.h"
32 #include "exitcodes.h"
33 #include <iostream>
34
35 /* Find a user record by nickname and return a pointer to it */
36 User* InspIRCd::FindNick(const std::string &nick)
37 {
38         if (!nick.empty() && isdigit(*nick.begin()))
39                 return FindUUID(nick);
40
41         user_hash::iterator iter = this->Users->clientlist.find(nick);
42
43         if (iter == this->Users->clientlist.end())
44                 /* Couldn't find it */
45                 return NULL;
46
47         return iter->second;
48 }
49
50 User* InspIRCd::FindNickOnly(const std::string &nick)
51 {
52         user_hash::iterator iter = this->Users->clientlist.find(nick);
53
54         if (iter == this->Users->clientlist.end())
55                 return NULL;
56
57         return iter->second;
58 }
59
60 User *InspIRCd::FindUUID(const std::string &uid)
61 {
62         user_hash::iterator finduuid = this->Users->uuidlist.find(uid);
63
64         if (finduuid == this->Users->uuidlist.end())
65                 return NULL;
66
67         return finduuid->second;
68 }
69 /* find a channel record by channel name and return a pointer to it */
70
71 Channel* InspIRCd::FindChan(const std::string &chan)
72 {
73         chan_hash::iterator iter = chanlist.find(chan);
74
75         if (iter == chanlist.end())
76                 /* Couldn't find it */
77                 return NULL;
78
79         return iter->second;
80 }
81
82 bool InspIRCd::IsValidMask(const std::string &mask)
83 {
84         const char* dest = mask.c_str();
85         int exclamation = 0;
86         int atsign = 0;
87
88         for (const char* i = dest; *i; i++)
89         {
90                 /* out of range character, bad mask */
91                 if (*i < 32 || *i > 126)
92                 {
93                         return false;
94                 }
95
96                 switch (*i)
97                 {
98                         case '!':
99                                 exclamation++;
100                                 break;
101                         case '@':
102                                 atsign++;
103                                 break;
104                 }
105         }
106
107         /* valid masks only have 1 ! and @ */
108         if (exclamation != 1 || atsign != 1)
109                 return false;
110
111         if (mask.length() > 250)
112                 return false;
113
114         return true;
115 }
116
117 void InspIRCd::StripColor(std::string &sentence)
118 {
119         /* refactor this completely due to SQUIT bug since the old code would strip last char and replace with \0 --peavey */
120         int seq = 0;
121
122         for (std::string::iterator i = sentence.begin(); i != sentence.end();)
123         {
124                 if (*i == 3)
125                         seq = 1;
126                 else if (seq && (( ((*i >= '0') && (*i <= '9')) || (*i == ',') ) ))
127                 {
128                         seq++;
129                         if ( (seq <= 4) && (*i == ',') )
130                                 seq = 1;
131                         else if (seq > 3)
132                                 seq = 0;
133                 }
134                 else
135                         seq = 0;
136
137                 if (seq || ((*i == 2) || (*i == 15) || (*i == 22) || (*i == 21) || (*i == 31)))
138                         i = sentence.erase(i);
139                 else
140                         ++i;
141         }
142 }
143
144 void InspIRCd::ProcessColors(file_cache& input)
145 {
146         /*
147          * Replace all color codes from the special[] array to actual
148          * color code chars using C++ style escape sequences. You
149          * can append other chars to replace if you like -- Justasic
150          */
151         static struct special_chars
152         {
153                 std::string character;
154                 std::string replace;
155                 special_chars(const std::string &c, const std::string &r) : character(c), replace(r) { }
156         }
157
158         special[] = {
159                 special_chars("\\002", "\002"),  // Bold
160                 special_chars("\\037", "\037"),  // underline
161                 special_chars("\\003", "\003"),  // Color
162                 special_chars("\\017", "\017"), // Stop colors
163                 special_chars("\\u", "\037"),    // Alias for underline
164                 special_chars("\\b", "\002"),    // Alias for Bold
165                 special_chars("\\x", "\017"),    // Alias for stop
166                 special_chars("\\c", "\003"),    // Alias for color
167                 special_chars("", "")
168         };
169
170         for(file_cache::iterator it = input.begin(), it_end = input.end(); it != it_end; it++)
171         {
172                 std::string ret = *it;
173                 for(int i = 0; special[i].character.empty() == false; ++i)
174                 {
175                         std::string::size_type pos = ret.find(special[i].character);
176                         if(pos == std::string::npos) // Couldn't find the character, skip this line
177                                 continue;
178
179                         if((pos > 0) && (ret[pos-1] == '\\') && (ret[pos] == '\\'))
180                                 continue; // Skip double slashes.
181
182                         // Replace all our characters in the array
183                         while(pos != std::string::npos)
184                         {
185                                 ret = ret.substr(0, pos) + special[i].replace + ret.substr(pos + special[i].character.size());
186                                 pos = ret.find(special[i].character, pos + special[i].replace.size());
187                         }
188                 }
189
190                 // Replace double slashes with a single slash before we return
191                 std::string::size_type pos = ret.find("\\\\");
192                 while(pos != std::string::npos)
193                 {
194                         ret = ret.substr(0, pos) + "\\" + ret.substr(pos + 2);
195                         pos = ret.find("\\\\", pos + 1);
196                 }
197                 *it = ret;
198         }
199 }
200
201 /* true for valid channel name, false else */
202 bool IsChannelHandler::Call(const std::string& chname)
203 {
204         if (chname.empty() || chname.length() > ServerInstance->Config->Limits.ChanMax)
205                 return false;
206
207         if (chname[0] != '#')
208                 return false;
209
210         for (std::string::const_iterator i = chname.begin()+1; i != chname.end(); ++i)
211         {
212                 switch (*i)
213                 {
214                         case ' ':
215                         case ',':
216                         case 7:
217                                 return false;
218                 }
219         }
220
221         return true;
222 }
223
224 /* true for valid nickname, false else */
225 bool IsNickHandler::Call(const std::string& n)
226 {
227         if (n.empty() || n.length() > ServerInstance->Config->Limits.NickMax)
228                 return false;
229
230         for (std::string::const_iterator i = n.begin(); i != n.end(); ++i)
231         {
232                 if ((*i >= 'A') && (*i <= '}'))
233                 {
234                         /* "A"-"}" can occur anywhere in a nickname */
235                         continue;
236                 }
237
238                 if ((((*i >= '0') && (*i <= '9')) || (*i == '-')) && (i != n.begin()))
239                 {
240                         /* "0"-"9", "-" can occur anywhere BUT the first char of a nickname */
241                         continue;
242                 }
243
244                 /* invalid character! abort */
245                 return false;
246         }
247
248         return true;
249 }
250
251 /* return true for good ident, false else */
252 bool IsIdentHandler::Call(const std::string& n)
253 {
254         if (n.empty())
255                 return false;
256
257         for (std::string::const_iterator i = n.begin(); i != n.end(); ++i)
258         {
259                 if ((*i >= 'A') && (*i <= '}'))
260                 {
261                         continue;
262                 }
263
264                 if (((*i >= '0') && (*i <= '9')) || (*i == '-') || (*i == '.'))
265                 {
266                         continue;
267                 }
268
269                 return false;
270         }
271
272         return true;
273 }
274
275 bool InspIRCd::IsSID(const std::string &str)
276 {
277         /* Returns true if the string given is exactly 3 characters long,
278          * starts with a digit, and the other two characters are A-Z or digits
279          */
280         return ((str.length() == 3) && isdigit(str[0]) &&
281                         ((str[1] >= 'A' && str[1] <= 'Z') || isdigit(str[1])) &&
282                          ((str[2] >= 'A' && str[2] <= 'Z') || isdigit(str[2])));
283 }
284
285 void InspIRCd::CheckRoot()
286 {
287 #ifndef _WIN32
288         if (geteuid() == 0)
289         {
290                 std::cout << "ERROR: You are running an irc server as root! DO NOT DO THIS!" << std::endl << std::endl;
291                 this->Logs->Log("STARTUP", LOG_DEFAULT, "Can't start as root");
292                 Exit(EXIT_STATUS_ROOT);
293         }
294 #endif
295 }
296
297 /** Refactored by Brain, Jun 2009. Much faster with some clever O(1) array
298  * lookups and pointer maths.
299  */
300 unsigned long InspIRCd::Duration(const std::string &str)
301 {
302         unsigned char multiplier = 0;
303         long total = 0;
304         long times = 1;
305         long subtotal = 0;
306
307         /* Iterate each item in the string, looking for number or multiplier */
308         for (std::string::const_reverse_iterator i = str.rbegin(); i != str.rend(); ++i)
309         {
310                 /* Found a number, queue it onto the current number */
311                 if ((*i >= '0') && (*i <= '9'))
312                 {
313                         subtotal = subtotal + ((*i - '0') * times);
314                         times = times * 10;
315                 }
316                 else
317                 {
318                         /* Found something thats not a number, find out how much
319                          * it multiplies the built up number by, multiply the total
320                          * and reset the built up number.
321                          */
322                         if (subtotal)
323                                 total += subtotal * duration_multi[multiplier];
324
325                         /* Next subtotal please */
326                         subtotal = 0;
327                         multiplier = *i;
328                         times = 1;
329                 }
330         }
331         if (multiplier)
332         {
333                 total += subtotal * duration_multi[multiplier];
334                 subtotal = 0;
335         }
336         /* Any trailing values built up are treated as raw seconds */
337         return total + subtotal;
338 }
339
340 const char* InspIRCd::Format(va_list &vaList, const char* formatString)
341 {
342         static std::vector<char> formatBuffer(1024);
343
344         while (true)
345         {
346                 va_list dst;
347                 va_copy(dst, vaList);
348
349                 int vsnret = vsnprintf(&formatBuffer[0], formatBuffer.size(), formatString, dst);
350                 va_end(dst);
351
352                 if (vsnret > 0 && static_cast<unsigned>(vsnret) < formatBuffer.size())
353                 {
354                         break;
355                 }
356
357                 formatBuffer.resize(formatBuffer.size() * 2);
358         }
359
360         return &formatBuffer[0];
361 }
362
363 const char* InspIRCd::Format(const char* formatString, ...)
364 {
365         const char* ret;
366         VAFORMAT(ret, formatString, formatString);
367         return ret;
368 }
369
370 std::string InspIRCd::TimeString(time_t curtime, const char* format, bool utc)
371 {
372 #ifdef _WIN32
373         if (curtime < 0)
374                 curtime = 0;
375 #endif
376
377         struct tm* timeinfo = utc ? gmtime(&curtime) : localtime(&curtime);
378         if (!timeinfo)
379         {
380                 curtime = 0;
381                 timeinfo = localtime(&curtime);
382         }
383
384         // If the calculated year exceeds four digits or is less than the year 1000,
385         // the behavior of asctime() is undefined
386         if (timeinfo->tm_year + 1900 > 9999)
387                 timeinfo->tm_year = 9999 - 1900;
388         else if (timeinfo->tm_year + 1900 < 1000)
389                 timeinfo->tm_year = 0;
390
391         // This is the default format used by asctime without the terminating new line.
392         if (!format)
393                 format = "%a %b %d %H:%M:%S %Y";
394
395         char buffer[512];
396         if (!strftime(buffer, sizeof(buffer), format, timeinfo))
397                 buffer[0] = '\0';
398
399         return buffer;
400 }
401
402 std::string InspIRCd::GenRandomStr(int length, bool printable)
403 {
404         char* buf = new char[length];
405         GenRandom(buf, length);
406         std::string rv;
407         rv.resize(length);
408         for(int i=0; i < length; i++)
409                 rv[i] = printable ? 0x3F + (buf[i] & 0x3F) : buf[i];
410         delete[] buf;
411         return rv;
412 }
413
414 // NOTE: this has a slight bias for lower values if max is not a power of 2.
415 // Don't use it if that matters.
416 unsigned long InspIRCd::GenRandomInt(unsigned long max)
417 {
418         unsigned long rv;
419         GenRandom((char*)&rv, sizeof(rv));
420         return rv % max;
421 }
422
423 // This is overridden by a higher-quality algorithm when SSL support is loaded
424 void GenRandomHandler::Call(char *output, size_t max)
425 {
426         for(unsigned int i=0; i < max; i++)
427 #ifdef _WIN32
428         {
429                 unsigned int uTemp;
430                 if(rand_s(&uTemp) != 0)
431                         output[i] = rand();
432                 else
433                         output[i] = uTemp;
434         }
435 #else
436                 output[i] = random();
437 #endif
438 }
439
440 ModResult OnCheckExemptionHandler::Call(User* user, Channel* chan, const std::string& restriction)
441 {
442         unsigned int mypfx = chan->GetPrefixValue(user);
443         char minmode = 0;
444         std::string current;
445
446         irc::spacesepstream defaultstream(ServerInstance->Config->ConfValue("options")->getString("exemptchanops"));
447
448         while (defaultstream.GetToken(current))
449         {
450                 std::string::size_type pos = current.find(':');
451                 if (pos == std::string::npos)
452                         continue;
453                 if (!current.compare(0, pos, restriction))
454                         minmode = current[pos+1];
455         }
456
457         PrefixMode* mh = ServerInstance->Modes->FindPrefixMode(minmode);
458         if (mh && mypfx >= mh->GetPrefixRank())
459                 return MOD_RES_ALLOW;
460         if (mh || minmode == '*')
461                 return MOD_RES_DENY;
462         return MOD_RES_PASSTHRU;
463 }