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