]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/helperfuncs.cpp
Merge pull request #1018 from SaberUK/insp20+hidekills
[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::FindNick(const char* nick)
70 {
71         if (isdigit(*nick))
72                 return FindUUID(nick);
73
74         user_hash::iterator iter = this->Users->clientlist->find(nick);
75
76         if (iter == this->Users->clientlist->end())
77                 return NULL;
78
79         return iter->second;
80 }
81
82 User* InspIRCd::FindNickOnly(const std::string &nick)
83 {
84         user_hash::iterator iter = this->Users->clientlist->find(nick);
85
86         if (iter == this->Users->clientlist->end())
87                 return NULL;
88
89         return iter->second;
90 }
91
92 User* InspIRCd::FindNickOnly(const char* nick)
93 {
94         user_hash::iterator iter = this->Users->clientlist->find(nick);
95
96         if (iter == this->Users->clientlist->end())
97                 return NULL;
98
99         return iter->second;
100 }
101
102 User *InspIRCd::FindUUID(const std::string &uid)
103 {
104         user_hash::iterator finduuid = this->Users->uuidlist->find(uid);
105
106         if (finduuid == this->Users->uuidlist->end())
107                 return NULL;
108
109         return finduuid->second;
110 }
111
112 User *InspIRCd::FindUUID(const char *uid)
113 {
114         return FindUUID(std::string(uid));
115 }
116
117 /* find a channel record by channel name and return a pointer to it */
118 Channel* InspIRCd::FindChan(const char* chan)
119 {
120         chan_hash::iterator iter = chanlist->find(chan);
121
122         if (iter == chanlist->end())
123                 /* Couldn't find it */
124                 return NULL;
125
126         return iter->second;
127 }
128
129 Channel* InspIRCd::FindChan(const std::string &chan)
130 {
131         chan_hash::iterator iter = chanlist->find(chan);
132
133         if (iter == chanlist->end())
134                 /* Couldn't find it */
135                 return NULL;
136
137         return iter->second;
138 }
139
140 /* Send an error notice to all users, registered or not */
141 void InspIRCd::SendError(const std::string &s)
142 {
143         for (LocalUserList::const_iterator i = this->Users->local_users.begin(); i != this->Users->local_users.end(); i++)
144         {
145                 User* u = *i;
146                 if (u->registered == REG_ALL)
147                 {
148                         u->WriteServ("NOTICE %s :%s",u->nick.c_str(),s.c_str());
149                 }
150                 else
151                 {
152                         /* Unregistered connections receive ERROR, not a NOTICE */
153                         u->Write("ERROR :" + s);
154                 }
155         }
156 }
157
158 /* return channel count */
159 long InspIRCd::ChannelCount()
160 {
161         return chanlist->size();
162 }
163
164 bool InspIRCd::IsValidMask(const std::string &mask)
165 {
166         const char* dest = mask.c_str();
167         int exclamation = 0;
168         int atsign = 0;
169
170         for (const char* i = dest; *i; i++)
171         {
172                 /* out of range character, bad mask */
173                 if (*i < 32 || *i > 126)
174                 {
175                         return false;
176                 }
177
178                 switch (*i)
179                 {
180                         case '!':
181                                 exclamation++;
182                                 break;
183                         case '@':
184                                 atsign++;
185                                 break;
186                 }
187         }
188
189         /* valid masks only have 1 ! and @ */
190         if (exclamation != 1 || atsign != 1)
191                 return false;
192
193         if (mask.length() > 250)
194                 return false;
195
196         return true;
197 }
198
199 void InspIRCd::StripColor(std::string &sentence)
200 {
201         /* refactor this completely due to SQUIT bug since the old code would strip last char and replace with \0 --peavey */
202         int seq = 0;
203
204         for (std::string::iterator i = sentence.begin(); i != sentence.end();)
205         {
206                 if (*i == 3)
207                         seq = 1;
208                 else if (seq && (( ((*i >= '0') && (*i <= '9')) || (*i == ',') ) ))
209                 {
210                         seq++;
211                         if ( (seq <= 4) && (*i == ',') )
212                                 seq = 1;
213                         else if (seq > 3)
214                                 seq = 0;
215                 }
216                 else
217                         seq = 0;
218
219                 if (seq || ((*i == 2) || (*i == 15) || (*i == 22) || (*i == 21) || (*i == 31)))
220                         i = sentence.erase(i);
221                 else
222                         ++i;
223         }
224 }
225
226 void InspIRCd::ProcessColors(file_cache& input)
227 {
228         /*
229          * Replace all color codes from the special[] array to actual
230          * color code chars using C++ style escape sequences. You
231          * can append other chars to replace if you like -- Justasic
232          */
233         static struct special_chars
234         {
235                 std::string character;
236                 std::string replace;
237                 special_chars(const std::string &c, const std::string &r) : character(c), replace(r) { }
238         }
239
240         special[] = {
241                 special_chars("\\002", "\002"),  // Bold
242                 special_chars("\\037", "\037"),  // underline
243                 special_chars("\\003", "\003"),  // Color
244                 special_chars("\\017", "\017"), // Stop colors
245                 special_chars("\\u", "\037"),    // Alias for underline
246                 special_chars("\\b", "\002"),    // Alias for Bold
247                 special_chars("\\x", "\017"),    // Alias for stop
248                 special_chars("\\c", "\003"),    // Alias for color
249                 special_chars("", "")
250         };
251
252         for(file_cache::iterator it = input.begin(), it_end = input.end(); it != it_end; it++)
253         {
254                 std::string ret = *it;
255                 for(int i = 0; special[i].character.empty() == false; ++i)
256                 {
257                         std::string::size_type pos = ret.find(special[i].character);
258                         if(pos == std::string::npos) // Couldn't find the character, skip this line
259                                 continue;
260
261                         if((pos > 0) && (ret[pos-1] == '\\') && (ret[pos] == '\\'))
262                                 continue; // Skip double slashes.
263
264                         // Replace all our characters in the array
265                         while(pos != std::string::npos)
266                         {
267                                 ret = ret.substr(0, pos) + special[i].replace + ret.substr(pos + special[i].character.size());
268                                 pos = ret.find(special[i].character, pos + special[i].replace.size());
269                         }
270                 }
271
272                 // Replace double slashes with a single slash before we return
273                 std::string::size_type pos = ret.find("\\\\");
274                 while(pos != std::string::npos)
275                 {
276                         ret = ret.substr(0, pos) + "\\" + ret.substr(pos + 2);
277                         pos = ret.find("\\\\", pos + 1);
278                 }
279                 *it = ret;
280         }
281 }
282
283 /* true for valid channel name, false else */
284 bool IsChannelHandler::Call(const char *chname, size_t max)
285 {
286         const char *c = chname + 1;
287
288         /* check for no name - don't check for !*chname, as if it is empty, it won't be '#'! */
289         if (!chname || *chname != '#')
290         {
291                 return false;
292         }
293
294         while (*c)
295         {
296                 switch (*c)
297                 {
298                         case ' ':
299                         case ',':
300                         case 7:
301                                 return false;
302                 }
303
304                 c++;
305         }
306
307         size_t len = c - chname;
308         /* too long a name - note funky pointer arithmetic here. */
309         if (len > max)
310         {
311                         return false;
312         }
313
314         return true;
315 }
316
317 /* true for valid nickname, false else */
318 bool IsNickHandler::Call(const char* n, size_t max)
319 {
320         if (!n || !*n)
321                 return false;
322
323         unsigned int p = 0;
324         for (const char* i = n; *i; i++, p++)
325         {
326                 if ((*i >= 'A') && (*i <= '}'))
327                 {
328                         /* "A"-"}" can occur anywhere in a nickname */
329                         continue;
330                 }
331
332                 if ((((*i >= '0') && (*i <= '9')) || (*i == '-')) && (i > n))
333                 {
334                         /* "0"-"9", "-" can occur anywhere BUT the first char of a nickname */
335                         continue;
336                 }
337
338                 /* invalid character! abort */
339                 return false;
340         }
341
342         /* too long? or not */
343         return (p <= max);
344 }
345
346 /* return true for good ident, false else */
347 bool IsIdentHandler::Call(const char* n)
348 {
349         if (!n || !*n)
350                 return false;
351
352         for (const char* i = n; *i; i++)
353         {
354                 if ((*i >= 'A') && (*i <= '}'))
355                 {
356                         continue;
357                 }
358
359                 if (((*i >= '0') && (*i <= '9')) || (*i == '-') || (*i == '.'))
360                 {
361                         continue;
362                 }
363
364                 return false;
365         }
366
367         return true;
368 }
369
370 bool IsSIDHandler::Call(const std::string &str)
371 {
372         /* Returns true if the string given is exactly 3 characters long,
373          * starts with a digit, and the other two characters are A-Z or digits
374          */
375         return ((str.length() == 3) && isdigit(str[0]) &&
376                         ((str[1] >= 'A' && str[1] <= 'Z') || isdigit(str[1])) &&
377                          ((str[2] >= 'A' && str[2] <= 'Z') || isdigit(str[2])));
378 }
379
380 /* open the proper logfile */
381 bool InspIRCd::OpenLog(char**, int)
382 {
383         if (!Config->cmdline.writelog) return true; // Skip opening default log if -nolog
384
385         if (Config->cmdline.startup_log.empty())
386                 Config->cmdline.startup_log = LOG_PATH "/startup.log";
387         FILE* startup = fopen(Config->cmdline.startup_log.c_str(), "a+");
388
389         if (!startup)
390         {
391                 return false;
392         }
393
394         FileWriter* fw = new FileWriter(startup);
395         FileLogStream *f = new FileLogStream((Config->cmdline.forcedebug ? DEBUG : DEFAULT), fw);
396
397         this->Logs->AddLogType("*", f, true);
398
399         return true;
400 }
401
402 void InspIRCd::CheckRoot()
403 {
404 #ifndef _WIN32
405         if (geteuid() == 0)
406         {
407                 std::cout << "ERROR: You are running an irc server as root! DO NOT DO THIS!" << std::endl << std::endl;
408                 this->Logs->Log("STARTUP",DEFAULT,"Can't start as root");
409                 Exit(EXIT_STATUS_ROOT);
410         }
411 #endif
412 }
413
414 void InspIRCd::SendWhoisLine(User* user, User* dest, int numeric, const std::string &text)
415 {
416         std::string copy_text = text;
417
418         ModResult MOD_RESULT;
419         FIRST_MOD_RESULT(OnWhoisLine, MOD_RESULT, (user, dest, numeric, copy_text));
420
421         if (MOD_RESULT != MOD_RES_DENY)
422                 user->WriteServ("%d %s", numeric, copy_text.c_str());
423 }
424
425 void InspIRCd::SendWhoisLine(User* user, User* dest, int numeric, const char* format, ...)
426 {
427         char textbuffer[MAXBUF];
428         va_list argsPtr;
429         va_start (argsPtr, format);
430         vsnprintf(textbuffer, MAXBUF, format, argsPtr);
431         va_end(argsPtr);
432
433         this->SendWhoisLine(user, dest, numeric, std::string(textbuffer));
434 }
435
436 /** Refactored by Brain, Jun 2009. Much faster with some clever O(1) array
437  * lookups and pointer maths.
438  */
439 long InspIRCd::Duration(const std::string &str)
440 {
441         unsigned char multiplier = 0;
442         long total = 0;
443         long times = 1;
444         long subtotal = 0;
445
446         /* Iterate each item in the string, looking for number or multiplier */
447         for (std::string::const_reverse_iterator i = str.rbegin(); i != str.rend(); ++i)
448         {
449                 /* Found a number, queue it onto the current number */
450                 if ((*i >= '0') && (*i <= '9'))
451                 {
452                         subtotal = subtotal + ((*i - '0') * times);
453                         times = times * 10;
454                 }
455                 else
456                 {
457                         /* Found something thats not a number, find out how much
458                          * it multiplies the built up number by, multiply the total
459                          * and reset the built up number.
460                          */
461                         if (subtotal)
462                                 total += subtotal * duration_multi[multiplier];
463
464                         /* Next subtotal please */
465                         subtotal = 0;
466                         multiplier = *i;
467                         times = 1;
468                 }
469         }
470         if (multiplier)
471         {
472                 total += subtotal * duration_multi[multiplier];
473                 subtotal = 0;
474         }
475         /* Any trailing values built up are treated as raw seconds */
476         return total + subtotal;
477 }
478
479 bool InspIRCd::ULine(const std::string& sserver)
480 {
481         if (sserver.empty())
482                 return true;
483
484         return (Config->ulines.find(sserver.c_str()) != Config->ulines.end());
485 }
486
487 bool InspIRCd::SilentULine(const std::string& sserver)
488 {
489         std::map<irc::string,bool>::iterator n = Config->ulines.find(sserver.c_str());
490         if (n != Config->ulines.end())
491                 return n->second;
492         else
493                 return false;
494 }
495
496 std::string InspIRCd::TimeString(time_t curtime)
497 {
498 #ifdef _WIN32
499         if (curtime < 0)
500                 curtime = 0;
501 #endif
502
503         struct tm* timeinfo = localtime(&curtime);
504         if (!timeinfo)
505         {
506                 curtime = 0;
507                 timeinfo = localtime(&curtime);
508         }
509
510         // If the calculated year exceeds four digits or is less than the year 1000,
511         // the behavior of asctime() is undefined
512         if (timeinfo->tm_year + 1900 > 9999)
513                 timeinfo->tm_year = 9999 - 1900;
514         else if (timeinfo->tm_year + 1900 < 1000)
515                 timeinfo->tm_year = 0;
516
517         return std::string(asctime(timeinfo),24);
518 }
519
520 // You should only pass a single character to this.
521 void InspIRCd::AddExtBanChar(char c)
522 {
523         std::string &tok = Config->data005;
524         std::string::size_type ebpos = tok.find(" EXTBAN=,");
525
526         if (ebpos == std::string::npos)
527         {
528                 tok.append(" EXTBAN=,");
529                 tok.push_back(c);
530         }
531         else
532         {
533                 ebpos += 9;
534                 while (isalpha(tok[ebpos]) && tok[ebpos] < c)
535                         ebpos++;
536                 tok.insert(ebpos, 1, c);
537         }
538 }
539
540 std::string InspIRCd::GenRandomStr(int length, bool printable)
541 {
542         char* buf = new char[length];
543         GenRandom(buf, length);
544         std::string rv;
545         rv.resize(length);
546         for(int i=0; i < length; i++)
547                 rv[i] = printable ? 0x3F + (buf[i] & 0x3F) : buf[i];
548         delete[] buf;
549         return rv;
550 }
551
552 // NOTE: this has a slight bias for lower values if max is not a power of 2.
553 // Don't use it if that matters.
554 unsigned long InspIRCd::GenRandomInt(unsigned long max)
555 {
556         unsigned long rv;
557         GenRandom((char*)&rv, sizeof(rv));
558         return rv % max;
559 }
560
561 // This is overridden by a higher-quality algorithm when SSL support is loaded
562 void GenRandomHandler::Call(char *output, size_t max)
563 {
564         for(unsigned int i=0; i < max; i++)
565 #ifdef _WIN32
566         {
567                 unsigned int uTemp;
568                 if(rand_s(&uTemp) != 0)
569                         output[i] = rand();
570                 else
571                         output[i] = uTemp;
572         }
573 #else
574                 output[i] = random();
575 #endif
576 }
577
578 ModResult OnCheckExemptionHandler::Call(User* user, Channel* chan, const std::string& restriction)
579 {
580         unsigned int mypfx = chan->GetPrefixValue(user);
581         char minmode = 0;
582         std::string current;
583
584         irc::spacesepstream defaultstream(ServerInstance->Config->ConfValue("options")->getString("exemptchanops"));
585
586         while (defaultstream.GetToken(current))
587         {
588                 std::string::size_type pos = current.find(':');
589                 if (pos == std::string::npos)
590                         continue;
591                 if (current.substr(0,pos) == restriction)
592                         minmode = current[pos+1];
593         }
594
595         ModeHandler* mh = ServerInstance->Modes->FindMode(minmode, MODETYPE_CHANNEL);
596         if (mh && mypfx >= mh->GetPrefixRank())
597                 return MOD_RES_ALLOW;
598         if (mh || minmode == '*')
599                 return MOD_RES_DENY;
600         return MOD_RES_PASSTHRU;
601 }