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