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