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