]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/helperfuncs.cpp
First phase of conversion to dynamic limits on all the lengths, configured via the...
[user/henk/code/inspircd.git] / src / helperfuncs.cpp
1 /*       +------------------------------------+
2  *       | Inspire Internet Relay Chat Daemon |
3  *       +------------------------------------+
4  *
5  *  InspIRCd: (C) 2002-2008 InspIRCd Development Team
6  * See: http://www.inspircd.org/wiki/index.php/Credits
7  *
8  * This program is free but copyrighted software; see
9  *          the file COPYING for details.
10  *
11  * ---------------------------------------------------
12  */
13
14 /* $Core: libIRCDhelper */
15
16 #include "inspircd.h"
17 #include "wildcard.h"
18 #include "xline.h"
19 #include "exitcodes.h"
20
21 std::string InspIRCd::GetServerDescription(const char* servername)
22 {
23         std::string description;
24
25         FOREACH_MOD_I(this,I_OnGetServerDescription,OnGetServerDescription(servername,description));
26
27         if (!description.empty())
28         {
29                 return description;
30         }
31         else
32         {
33                 // not a remote server that can be found, it must be me.
34                 return Config->ServerDesc;
35         }
36 }
37
38 /* Find a user record by nickname and return a pointer to it */
39 User* InspIRCd::FindNick(const std::string &nick)
40 {
41         if (!nick.empty() && isdigit(*nick.begin()))
42                 return FindUUID(nick);
43
44         user_hash::iterator iter = this->Users->clientlist->find(nick);
45
46         if (iter == this->Users->clientlist->end())
47                 /* Couldn't find it */
48                 return NULL;
49
50         return iter->second;
51 }
52
53 User* InspIRCd::FindNick(const char* nick)
54 {
55         if (isdigit(*nick))
56                 return FindUUID(nick);
57
58         user_hash::iterator iter = this->Users->clientlist->find(nick);
59         
60         if (iter == this->Users->clientlist->end())
61                 return NULL;
62
63         return iter->second;
64 }
65
66 User* InspIRCd::FindNickOnly(const std::string &nick)
67 {
68         user_hash::iterator iter = this->Users->clientlist->find(nick);
69
70         if (iter == this->Users->clientlist->end())
71                 return NULL;
72
73         return iter->second;
74 }
75
76 User* InspIRCd::FindNickOnly(const char* nick)
77 {
78         user_hash::iterator iter = this->Users->clientlist->find(nick);
79
80         if (iter == this->Users->clientlist->end())
81                 return NULL;
82
83         return iter->second;
84 }
85
86 User *InspIRCd::FindUUID(const std::string &uid)
87 {
88         return FindUUID(uid.c_str());
89 }
90
91 User *InspIRCd::FindUUID(const char *uid)
92 {
93         user_hash::iterator finduuid = this->Users->uuidlist->find(uid);
94
95         if (finduuid == this->Users->uuidlist->end())
96                 return NULL;
97
98         return finduuid->second;
99 }
100
101 /* find a channel record by channel name and return a pointer to it */
102 Channel* InspIRCd::FindChan(const char* chan)
103 {
104         chan_hash::iterator iter = chanlist->find(chan);
105
106         if (iter == chanlist->end())
107                 /* Couldn't find it */
108                 return NULL;
109
110         return iter->second;
111 }
112
113 Channel* InspIRCd::FindChan(const std::string &chan)
114 {
115         chan_hash::iterator iter = chanlist->find(chan);
116
117         if (iter == chanlist->end())
118                 /* Couldn't find it */
119                 return NULL;
120
121         return iter->second;
122 }
123
124 /* Send an error notice to all users, registered or not */
125 void InspIRCd::SendError(const std::string &s)
126 {
127         for (std::vector<User*>::const_iterator i = this->Users->local_users.begin(); i != this->Users->local_users.end(); i++)
128         {
129                 if ((*i)->registered == REG_ALL)
130                 {
131                         (*i)->WriteServ("NOTICE %s :%s",(*i)->nick.c_str(),s.c_str());
132                 }
133                 else
134                 {
135                         /* Unregistered connections receive ERROR, not a NOTICE */
136                         (*i)->Write("ERROR :" + s);
137                 }
138                 /* This might generate a whole load of EAGAIN, but we dont really
139                  * care about this, as if we call SendError something catastrophic
140                  * has occured anyway, and we wont receive the events for these.
141                  */
142                 (*i)->FlushWriteBuf();
143         }
144 }
145
146 /* return channel count */
147 long InspIRCd::ChannelCount()
148 {
149         return chanlist->size();
150 }
151
152 bool InspIRCd::IsValidMask(const std::string &mask)
153 {
154         char* dest = (char*)mask.c_str();
155         int exclamation = 0;
156         int atsign = 0;
157
158         for (char* i = dest; *i; i++)
159         {
160                 /* out of range character, bad mask */
161                 if (*i < 32 || *i > 126)
162                 {
163                         return false;
164                 }
165
166                 switch (*i)
167                 {
168                         case '!':
169                                 exclamation++;
170                                 break;
171                         case '@':
172                                 atsign++;
173                                 break;
174                 }
175         }
176
177         /* valid masks only have 1 ! and @ */
178         if (exclamation != 1 || atsign != 1)
179                 return false;
180
181         return true;
182 }
183
184 /* true for valid channel name, false else */
185 bool IsChannelHandler::Call(const char *chname, size_t max)
186 {
187         const char *c = chname + 1;
188
189         /* check for no name - don't check for !*chname, as if it is empty, it won't be '#'! */
190         if (!chname || *chname != '#')
191         {
192                 return false;
193         }
194
195         while (*c)
196         {
197                 switch (*c)
198                 {
199                         case ' ':
200                         case ',':
201                         case 7:
202                                 return false;
203                 }
204
205                 c++;
206         }
207
208         size_t len = c - chname;        
209         /* too long a name - note funky pointer arithmetic here. */
210         if (len > max)
211         {
212                         return false;
213         }
214
215         return true;
216 }
217
218 /* true for valid nickname, false else */
219 bool IsNickHandler::Call(const char* n, size_t max)
220 {
221         if (!n || !*n)
222                 return false;
223  
224         unsigned int p = 0;
225         for (const char* i = n; *i; i++, p++)
226         {
227                 if ((*i >= 'A') && (*i <= '}'))
228                 {
229                         /* "A"-"}" can occur anywhere in a nickname */
230                         continue;
231                 }
232
233                 if ((((*i >= '0') && (*i <= '9')) || (*i == '-')) && (i > n))
234                 {
235                         /* "0"-"9", "-" can occur anywhere BUT the first char of a nickname */
236                         continue;
237                 }
238
239                 /* invalid character! abort */
240                 return false;
241         }
242
243         /* too long? or not -- pointer arithmetic rocks */
244         return (p < max);
245 }
246
247 /* return true for good ident, false else */
248 bool IsIdentHandler::Call(const char* n)
249 {
250         if (!n || !*n)
251                 return false;
252
253         for (const char* i = n; *i; i++)
254         {
255                 if ((*i >= 'A') && (*i <= '}'))
256                 {
257                         continue;
258                 }
259
260                 if (((*i >= '0') && (*i <= '9')) || (*i == '-') || (*i == '.'))
261                 {
262                         continue;
263                 }
264
265                 return false;
266         }
267
268         return true;
269 }
270
271 bool IsSIDHandler::Call(const std::string &str)
272 {
273         /* Returns true if the string given is exactly 3 characters long,
274          * starts with a digit, and the other two characters are A-Z or digits
275          */
276         return ((str.length() == 3) && isdigit(str[0]) &&
277                         ((str[1] >= 'A' && str[1] <= 'Z') || isdigit(str[1])) &&
278                          ((str[2] >= 'A' && str[2] <= 'Z') || isdigit(str[2])));
279 }
280
281 /* open the proper logfile */
282 bool InspIRCd::OpenLog(char**, int)
283 {
284         /* This function only happens at startup now */
285         if (Config->nofork)
286         {
287                 this->Logs->SetupNoFork();
288         }
289         Config->MyDir = Config->GetFullProgDir();
290
291         /* Attempt to find home directory, portable to windows */
292         const char* home = getenv("HOME");
293         if (!home)
294         {
295                 /* No $HOME, log to %USERPROFILE% */
296                 home = getenv("USERPROFILE");
297                 if (!home)
298                 {
299                         /* Nothing could be found at all, log to current dir */
300                         Config->logpath = "./startup.log";
301                 }
302         }
303
304         if (!Config->writelog) return true; // Skip opening default log if -nolog
305
306         if (!*this->LogFileName)
307         {
308                 if (Config->logpath.empty())
309                 {
310                         std::string path = std::string(home) + "/.inspircd";
311                         // This tries to create the ~/.inspircd. If it succeeds, then we go ahead and use it.
312                         // If it fails due to an existing target, then we use it anyway.
313                         // Either way, we make sure we can get write access to the log at this point.
314                         if (!mkdir(path.c_str(), 0700) || errno == EEXIST)
315                         {
316                                 /* Log to ~/.inspircd/ircd.log */
317                                 Config->logpath = path + "/startup.log";
318                                 FILE* fd = fopen(Config->logpath.c_str(), "a+");
319                                 if (!fd)
320                                 {
321                                         // Could not get write access... Why?
322                                         if (errno == ENOTDIR)
323                                                 // ~/.inspircd is not actually a directory!
324                                                 printf("\nWARNING: Unable to create directory: %s (Exists and is not a directory)\n", path.c_str());
325                                         else
326                                                 // Not writable for some other reason (no +w access, readonly fs, file too big, whatever).
327                                                 printf("\nWARNING: No write access to %s (%s)\n", Config->logpath.c_str(), strerror(errno));
328                                         Config->logpath = "./startup.log";
329                                 }
330                                 else
331                                 {
332                                         Config->log_file = fd;
333                                 }
334                         }
335                         else
336                         {
337                                 /* Couldn't make ~/.inspircd directory, log to current dir */
338                                 Config->logpath = "./startup.log";
339                                 printf("\nWARNING: Unable to create directory: %s (%s)\n", path.c_str(), strerror(errno));
340                         }
341                 }
342
343                 if (!Config->log_file)
344                         Config->log_file = fopen(Config->logpath.c_str(),"a+");
345         }
346         else
347         {
348                 Config->log_file = fopen(this->LogFileName,"a+");
349         }
350
351         if (!Config->log_file)
352         {
353                 return false;
354         }
355
356         FileWriter* fw = new FileWriter(this, Config->log_file);
357         FileLogStream *f = new FileLogStream(this, (Config->forcedebug ? DEBUG : DEFAULT), fw);
358
359         this->Logs->AddLogType("*", f, true);
360
361         return true;
362 }
363
364 void InspIRCd::CheckRoot()
365 {
366         if (geteuid() == 0)
367         {
368                 printf("WARNING!!! You are running an irc server as ROOT!!! DO NOT DO THIS!!!\n\n");
369                 this->Logs->Log("STARTUP",DEFAULT,"Cant start as root");
370                 Exit(EXIT_STATUS_ROOT);
371         }
372 }
373
374 void InspIRCd::CheckDie()
375 {
376         if (*Config->DieValue)
377         {
378                 printf("WARNING: %s\n\n",Config->DieValue);
379                 this->Logs->Log("CONFIG",DEFAULT,"Died because of <die> tag: %s",Config->DieValue);
380                 Exit(EXIT_STATUS_DIETAG);
381         }
382 }
383
384 void InspIRCd::SendWhoisLine(User* user, User* dest, int numeric, const std::string &text)
385 {
386         std::string copy_text = text;
387
388         int MOD_RESULT = 0;
389         FOREACH_RESULT_I(this, I_OnWhoisLine, OnWhoisLine(user, dest, numeric, copy_text));
390
391         if (!MOD_RESULT)
392                 user->WriteServ("%d %s", numeric, copy_text.c_str());
393 }
394
395 void InspIRCd::SendWhoisLine(User* user, User* dest, int numeric, const char* format, ...)
396 {
397         char textbuffer[MAXBUF];
398         va_list argsPtr;
399         va_start (argsPtr, format);
400         vsnprintf(textbuffer, MAXBUF, format, argsPtr);
401         va_end(argsPtr);
402
403         this->SendWhoisLine(user, dest, numeric, std::string(textbuffer));
404 }
405
406 /** Refactored by Brain, Jun 2008. Much faster with some clever O(1) array
407  * lookups and pointer maths.
408  */
409 long InspIRCd::Duration(const std::string &str)
410 {
411         unsigned char multiplier = 0;
412         long total = 0;
413         long times = 1;
414         long subtotal = 0;
415
416         /* Iterate each item in the string, looking for number or multiplier */
417         for (std::string::const_reverse_iterator i = str.rbegin(); i != str.rend(); ++i)
418         {
419                 /* Found a number, queue it onto the current number */
420                 if ((*i >= '0') && (*i <= '9'))
421                 {
422                         subtotal = subtotal + ((*i - '0') * times);
423                         times = times * 10;
424                 }
425                 else
426                 {
427                         /* Found something thats not a number, find out how much
428                          * it multiplies the built up number by, multiply the total
429                          * and reset the built up number.
430                          */
431                         if (subtotal)
432                                 total += subtotal * duration_multi[multiplier];
433
434                         /* Next subtotal please */
435                         subtotal = 0;
436                         multiplier = *i;
437                         times = 1;
438                 }
439         }
440         if (multiplier)
441         {
442                 total += subtotal * duration_multi[multiplier];
443                 subtotal = 0;
444         }
445         /* Any trailing values built up are treated as raw seconds */
446         return total + subtotal;
447 }
448
449 bool InspIRCd::ULine(const char* sserver)
450 {
451         if (!sserver)
452                 return false;
453         if (!*sserver)
454                 return true;
455
456         return (Config->ulines.find(sserver) != Config->ulines.end());
457 }
458
459 bool InspIRCd::SilentULine(const char* sserver)
460 {
461         std::map<irc::string,bool>::iterator n = Config->ulines.find(sserver);
462         if (n != Config->ulines.end())
463                 return n->second;
464         else return false;
465 }
466
467 std::string InspIRCd::TimeString(time_t curtime)
468 {
469         return std::string(ctime(&curtime),24);
470 }
471