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