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