]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/helperfuncs.cpp
3efa58bba44150c111d2e109ab5f14d6cb6f39e6
[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         return FindUUID(uid.c_str());
105 }
106
107 User *InspIRCd::FindUUID(const char *uid)
108 {
109         user_hash::iterator finduuid = this->Users->uuidlist->find(uid);
110
111         if (finduuid == this->Users->uuidlist->end())
112                 return NULL;
113
114         return finduuid->second;
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 (std::vector<LocalUser*>::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 /* true for valid channel name, false else */
227 bool IsChannelHandler::Call(const char *chname, size_t max)
228 {
229         const char *c = chname + 1;
230
231         /* check for no name - don't check for !*chname, as if it is empty, it won't be '#'! */
232         if (!chname || *chname != '#')
233         {
234                 return false;
235         }
236
237         while (*c)
238         {
239                 switch (*c)
240                 {
241                         case ' ':
242                         case ',':
243                         case 7:
244                                 return false;
245                 }
246
247                 c++;
248         }
249
250         size_t len = c - chname;
251         /* too long a name - note funky pointer arithmetic here. */
252         if (len > max)
253         {
254                         return false;
255         }
256
257         return true;
258 }
259
260 /* true for valid nickname, false else */
261 bool IsNickHandler::Call(const char* n, size_t max)
262 {
263         if (!n || !*n)
264                 return false;
265
266         unsigned int p = 0;
267         for (const char* i = n; *i; i++, p++)
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))
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         /* too long? or not -- pointer arithmetic rocks */
286         return (p < max);
287 }
288
289 /* return true for good ident, false else */
290 bool IsIdentHandler::Call(const char* n)
291 {
292         if (!n || !*n)
293                 return false;
294
295         for (const char* i = n; *i; i++)
296         {
297                 if ((*i >= 'A') && (*i <= '}'))
298                 {
299                         continue;
300                 }
301
302                 if (((*i >= '0') && (*i <= '9')) || (*i == '-') || (*i == '.'))
303                 {
304                         continue;
305                 }
306
307                 return false;
308         }
309
310         return true;
311 }
312
313 bool IsSIDHandler::Call(const std::string &str)
314 {
315         /* Returns true if the string given is exactly 3 characters long,
316          * starts with a digit, and the other two characters are A-Z or digits
317          */
318         return ((str.length() == 3) && isdigit(str[0]) &&
319                         ((str[1] >= 'A' && str[1] <= 'Z') || isdigit(str[1])) &&
320                          ((str[2] >= 'A' && str[2] <= 'Z') || isdigit(str[2])));
321 }
322
323 /* open the proper logfile */
324 bool InspIRCd::OpenLog(char**, int)
325 {
326         if (!Config->cmdline.writelog) return true; // Skip opening default log if -nolog
327
328         if (Config->cmdline.startup_log.empty())
329                 Config->cmdline.startup_log = LOG_PATH "/startup.log";
330         FILE* startup = fopen(Config->cmdline.startup_log.c_str(), "a+");
331
332         if (!startup)
333         {
334                 return false;
335         }
336
337         FileWriter* fw = new FileWriter(startup);
338         FileLogStream *f = new FileLogStream((Config->cmdline.forcedebug ? DEBUG : DEFAULT), fw);
339
340         this->Logs->AddLogType("*", f, true);
341
342         return true;
343 }
344
345 void InspIRCd::CheckRoot()
346 {
347 #ifndef _WIN32
348         if (geteuid() == 0)
349         {
350                 std::cout << "ERROR: You are running an irc server as root! DO NOT DO THIS!" << std::endl << std::endl;
351                 this->Logs->Log("STARTUP",DEFAULT,"Can't start as root");
352                 Exit(EXIT_STATUS_ROOT);
353         }
354 #endif
355 }
356
357 void InspIRCd::SendWhoisLine(User* user, User* dest, int numeric, const std::string &text)
358 {
359         std::string copy_text = text;
360
361         ModResult MOD_RESULT;
362         FIRST_MOD_RESULT(OnWhoisLine, MOD_RESULT, (user, dest, numeric, copy_text));
363
364         if (MOD_RESULT != MOD_RES_DENY)
365                 user->WriteServ("%d %s", numeric, copy_text.c_str());
366 }
367
368 void InspIRCd::SendWhoisLine(User* user, User* dest, int numeric, const char* format, ...)
369 {
370         char textbuffer[MAXBUF];
371         va_list argsPtr;
372         va_start (argsPtr, format);
373         vsnprintf(textbuffer, MAXBUF, format, argsPtr);
374         va_end(argsPtr);
375
376         this->SendWhoisLine(user, dest, numeric, std::string(textbuffer));
377 }
378
379 /** Refactored by Brain, Jun 2009. Much faster with some clever O(1) array
380  * lookups and pointer maths.
381  */
382 long InspIRCd::Duration(const std::string &str)
383 {
384         unsigned char multiplier = 0;
385         long total = 0;
386         long times = 1;
387         long subtotal = 0;
388
389         /* Iterate each item in the string, looking for number or multiplier */
390         for (std::string::const_reverse_iterator i = str.rbegin(); i != str.rend(); ++i)
391         {
392                 /* Found a number, queue it onto the current number */
393                 if ((*i >= '0') && (*i <= '9'))
394                 {
395                         subtotal = subtotal + ((*i - '0') * times);
396                         times = times * 10;
397                 }
398                 else
399                 {
400                         /* Found something thats not a number, find out how much
401                          * it multiplies the built up number by, multiply the total
402                          * and reset the built up number.
403                          */
404                         if (subtotal)
405                                 total += subtotal * duration_multi[multiplier];
406
407                         /* Next subtotal please */
408                         subtotal = 0;
409                         multiplier = *i;
410                         times = 1;
411                 }
412         }
413         if (multiplier)
414         {
415                 total += subtotal * duration_multi[multiplier];
416                 subtotal = 0;
417         }
418         /* Any trailing values built up are treated as raw seconds */
419         return total + subtotal;
420 }
421
422 bool InspIRCd::ULine(const std::string& sserver)
423 {
424         if (sserver.empty())
425                 return true;
426
427         return (Config->ulines.find(sserver.c_str()) != Config->ulines.end());
428 }
429
430 bool InspIRCd::SilentULine(const std::string& sserver)
431 {
432         std::map<irc::string,bool>::iterator n = Config->ulines.find(sserver.c_str());
433         if (n != Config->ulines.end())
434                 return n->second;
435         else
436                 return false;
437 }
438
439 std::string InspIRCd::TimeString(time_t curtime)
440 {
441         return std::string(ctime(&curtime),24);
442 }
443
444 // You should only pass a single character to this.
445 void InspIRCd::AddExtBanChar(char c)
446 {
447         std::string &tok = Config->data005;
448         std::string::size_type ebpos = tok.find(" EXTBAN=,");
449
450         if (ebpos == std::string::npos)
451         {
452                 tok.append(" EXTBAN=,");
453                 tok.push_back(c);
454         }
455         else
456         {
457                 ebpos += 9;
458                 while (isalpha(tok[ebpos]) && tok[ebpos] < c)
459                         ebpos++;
460                 tok.insert(ebpos, 1, c);
461         }
462 }
463
464 std::string InspIRCd::GenRandomStr(int length, bool printable)
465 {
466         char* buf = new char[length];
467         GenRandom(buf, length);
468         std::string rv;
469         rv.resize(length);
470         for(int i=0; i < length; i++)
471                 rv[i] = printable ? 0x3F + (buf[i] & 0x3F) : buf[i];
472         delete[] buf;
473         return rv;
474 }
475
476 // NOTE: this has a slight bias for lower values if max is not a power of 2.
477 // Don't use it if that matters.
478 unsigned long InspIRCd::GenRandomInt(unsigned long max)
479 {
480         unsigned long rv;
481         GenRandom((char*)&rv, sizeof(rv));
482         return rv % max;
483 }
484
485 // This is overridden by a higher-quality algorithm when SSL support is loaded
486 void GenRandomHandler::Call(char *output, size_t max)
487 {
488         for(unsigned int i=0; i < max; i++)
489 #ifdef _WIN32
490         {
491                 unsigned int uTemp;
492                 if(rand_s(&uTemp) != 0)
493                         output[i] = rand();
494                 else
495                         output[i] = uTemp;
496         }
497 #else
498                 output[i] = random();
499 #endif
500 }
501
502 ModResult OnCheckExemptionHandler::Call(User* user, Channel* chan, const std::string& restriction)
503 {
504         unsigned int mypfx = chan->GetPrefixValue(user);
505         char minmode = 0;
506         std::string current;
507
508         irc::spacesepstream defaultstream(ServerInstance->Config->ConfValue("options")->getString("exemptchanops"));
509
510         while (defaultstream.GetToken(current))
511         {
512                 std::string::size_type pos = current.find(':');
513                 if (pos == std::string::npos)
514                         continue;
515                 if (current.substr(0,pos) == restriction)
516                         minmode = current[pos+1];
517         }
518
519         ModeHandler* mh = ServerInstance->Modes->FindMode(minmode, MODETYPE_CHANNEL);
520         if (mh && mypfx >= mh->GetPrefixRank())
521                 return MOD_RES_ALLOW;
522         if (mh || minmode == '*')
523                 return MOD_RES_DENY;
524         return MOD_RES_PASSTHRU;
525 }