]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/helperfuncs.cpp
Windows support. Tested and working to compile on freebsd and linux. Next step is...
[user/henk/code/inspircd.git] / src / helperfuncs.cpp
1 /*       +------------------------------------+
2  *       | Inspire Internet Relay Chat Daemon |
3  *       +------------------------------------+
4  *
5  *  InspIRCd: (C) 2002-2007 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 #include <stdarg.h>
15 #include "configreader.h"
16 #include "users.h"
17 #include "modules.h"
18 #include "wildcard.h"
19 #include "mode.h"
20 #include "xline.h"
21 #include "inspircd.h"
22 #include "exitcodes.h"
23
24 static char TIMESTR[26];
25 static time_t LAST = 0;
26
27 /** Log()
28  *  Write a line of text `text' to the logfile (and stdout, if in nofork) if the level `level'
29  *  is greater than the configured loglevel.
30  */
31 void InspIRCd::Log(int level, const char* text, ...)
32 {
33         /* Do this check again here so that we save pointless vsnprintf calls */
34         if ((level < Config->LogLevel) && !Config->forcedebug)
35                 return;
36
37         va_list argsPtr;
38         char textbuffer[65536];
39
40         va_start(argsPtr, text);
41         vsnprintf(textbuffer, 65536, text, argsPtr);
42         va_end(argsPtr);
43
44         this->Log(level, std::string(textbuffer));
45 }
46
47 void InspIRCd::Log(int level, const std::string &text)
48 {
49         if (!this->Config)
50                 return;
51
52         /* If we were given -debug we output all messages, regardless of configured loglevel */
53         if ((level < Config->LogLevel) && !Config->forcedebug)
54                 return;
55
56         if (Time() != LAST)
57         {
58                 time_t local = Time();
59                 struct tm *timeinfo = localtime(&local);
60
61                 strlcpy(TIMESTR,asctime(timeinfo),26);
62                 TIMESTR[24] = ':';
63                 LAST = Time();
64         }
65
66         if (Config->log_file && Config->writelog)
67         {
68                 std::string out = std::string(TIMESTR) + " " + text.c_str() + "\n";
69                 this->Logger->WriteLogLine(out);
70         }
71
72         if (Config->nofork)
73         {
74                 printf("%s %s\n", TIMESTR, text.c_str());
75         }
76 }
77
78 std::string InspIRCd::GetServerDescription(const char* servername)
79 {
80         std::string description;
81
82         FOREACH_MOD_I(this,I_OnGetServerDescription,OnGetServerDescription(servername,description));
83
84         if (description != "")
85         {
86                 return description;
87         }
88         else
89         {
90                 // not a remote server that can be found, it must be me.
91                 return Config->ServerDesc;
92         }
93 }
94
95 /* XXX - We don't use WriteMode for this because WriteMode is very slow and
96  * this isnt. Basically WriteMode has to iterate ALL the users 'n' times for
97  * the number of modes provided, e.g. if you send WriteMode 'og' to write to
98  * opers with globops, and you have 2000 users, thats 4000 iterations. WriteOpers
99  * uses the oper list, which means if you have 2000 users but only 5 opers,
100  * it iterates 5 times.
101  */
102 void InspIRCd::WriteOpers(const char* text, ...)
103 {
104         char textbuffer[MAXBUF];
105         va_list argsPtr;
106
107         va_start(argsPtr, text);
108         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
109         va_end(argsPtr);
110
111         this->WriteOpers(std::string(textbuffer));
112 }
113
114 void InspIRCd::WriteOpers(const std::string &text)
115 {
116         for (std::vector<userrec*>::iterator i = this->all_opers.begin(); i != this->all_opers.end(); i++)
117         {
118                 userrec* a = *i;
119                 if (IS_LOCAL(a) && a->modes[UM_SERVERNOTICE])
120                 {
121                         // send server notices to all with +s
122                         a->WriteServ("NOTICE %s :%s",a->nick,text.c_str());
123                 }
124         }
125 }
126
127 void InspIRCd::ServerNoticeAll(char* text, ...)
128 {
129         if (!text)
130                 return;
131
132         char textbuffer[MAXBUF];
133         char formatbuffer[MAXBUF];
134         va_list argsPtr;
135         va_start (argsPtr, text);
136         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
137         va_end(argsPtr);
138
139         snprintf(formatbuffer,MAXBUF,"NOTICE $%s :%s",Config->ServerName,textbuffer);
140
141         for (std::vector<userrec*>::const_iterator i = local_users.begin(); i != local_users.end(); i++)
142         {
143                 userrec* t = *i;
144                 t->WriteServ(std::string(formatbuffer));
145         }
146 }
147
148 void InspIRCd::ServerPrivmsgAll(char* text, ...)
149 {
150         if (!text)
151                 return;
152
153         char textbuffer[MAXBUF];
154         char formatbuffer[MAXBUF];
155         va_list argsPtr;
156         va_start (argsPtr, text);
157         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
158         va_end(argsPtr);
159
160         snprintf(formatbuffer,MAXBUF,"PRIVMSG $%s :%s",Config->ServerName,textbuffer);
161
162         for (std::vector<userrec*>::const_iterator i = local_users.begin(); i != local_users.end(); i++)
163         {
164                 userrec* t = *i;
165                 t->WriteServ(std::string(formatbuffer));
166         }
167 }
168
169 void InspIRCd::WriteMode(const char* modes, int flags, const char* text, ...)
170 {
171         char textbuffer[MAXBUF];
172         int modelen;
173         va_list argsPtr;
174
175         if (!text || !modes || !flags)
176         {
177                 this->Log(DEFAULT,"*** BUG *** WriteMode was given an invalid parameter");
178                 return;
179         }
180
181         va_start(argsPtr, text);
182         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
183         va_end(argsPtr);
184         modelen = strlen(modes);
185
186         if (flags == WM_AND)
187         {
188                 for (std::vector<userrec*>::const_iterator i = local_users.begin(); i != local_users.end(); i++)
189                 {
190                         userrec* t = *i;
191                         bool send_to_user = true;
192
193                         for (int n = 0; n < modelen; n++)
194                         {
195                                 if (!t->modes[modes[n]-65])
196                                 {
197                                         send_to_user = false;
198                                         break;
199                                 }
200                         }
201                         if (send_to_user)
202                                 t->WriteServ("NOTICE %s :%s",t->nick,textbuffer);
203                 }
204         }
205         else
206         if (flags == WM_OR)
207         {
208                 for (std::vector<userrec*>::const_iterator i = local_users.begin(); i != local_users.end(); i++)
209                 {
210                         userrec* t = *i;
211                         bool send_to_user = false;
212
213                         for (int n = 0; n < modelen; n++)
214                         {
215                                 if (t->modes[modes[n]-65])
216                                 {
217                                         send_to_user = true;
218                                         break;
219                                 }
220                         }
221                         if (send_to_user)
222                                 t->WriteServ("NOTICE %s :%s",t->nick,textbuffer);
223                 }
224         }
225 }
226
227 /* Find a user record by nickname and return a pointer to it */
228
229 userrec* InspIRCd::FindNick(const std::string &nick)
230 {
231         user_hash::iterator iter = clientlist->find(nick);
232
233         if (iter == clientlist->end())
234                 /* Couldn't find it */
235                 return NULL;
236
237         return iter->second;
238 }
239
240 userrec* InspIRCd::FindNick(const char* nick)
241 {
242         user_hash::iterator iter = clientlist->find(nick);
243         
244         if (iter == clientlist->end())
245                 return NULL;
246
247         return iter->second;
248 }
249
250 /* find a channel record by channel name and return a pointer to it */
251
252 chanrec* InspIRCd::FindChan(const char* chan)
253 {
254         chan_hash::iterator iter = chanlist->find(chan);
255
256         if (iter == chanlist->end())
257                 /* Couldn't find it */
258                 return NULL;
259
260         return iter->second;
261 }
262
263 chanrec* InspIRCd::FindChan(const std::string &chan)
264 {
265         chan_hash::iterator iter = chanlist->find(chan);
266
267         if (iter == chanlist->end())
268                 /* Couldn't find it */
269                 return NULL;
270
271         return iter->second;
272 }
273
274 /*
275  * sends out an error notice to all connected clients (not to be used
276  * lightly!)
277  */
278 void InspIRCd::SendError(const std::string &s)
279 {
280         for (std::vector<userrec*>::const_iterator i = this->local_users.begin(); i != this->local_users.end(); i++)
281         {
282                 if ((*i)->registered == REG_ALL)
283                 {
284                         (*i)->WriteServ("NOTICE %s :%s",(*i)->nick,s.c_str());
285                 }
286                 else
287                 {
288                         /* Unregistered connections receive ERROR, not a NOTICE */
289                         (*i)->Write("ERROR :" + s);
290                 }
291                 /* This might generate a whole load of EAGAIN, but we dont really
292                  * care about this, as if we call SendError something catastrophic
293                  * has occured anyway, and we wont receive the events for these.
294                  */
295                 (*i)->FlushWriteBuf();
296         }
297 }
298
299 // this function counts all users connected, wether they are registered or NOT.
300 int InspIRCd::UserCount()
301 {
302         return clientlist->size();
303 }
304
305 // this counts only registered users, so that the percentages in /MAP don't mess up when users are sitting in an unregistered state
306 int InspIRCd::RegisteredUserCount()
307 {
308         return clientlist->size() - this->UnregisteredUserCount();
309 }
310
311 int InspIRCd::ModeCount(const char mode)
312 {
313         ModeHandler* mh = this->Modes->FindMode(mode, MODETYPE_USER);
314
315         if (mh)
316                 return mh->GetCount();
317         else
318                 return 0;
319 }
320
321 int InspIRCd::InvisibleUserCount()
322 {
323         return ModeCount('i');
324 }
325
326 int InspIRCd::OperCount()
327 {
328         return this->all_opers.size();
329 }
330
331 int InspIRCd::UnregisteredUserCount()
332 {
333         return this->unregistered_count;
334 }
335
336 long InspIRCd::ChannelCount()
337 {
338         return chanlist->size();
339 }
340
341 long InspIRCd::LocalUserCount()
342 {
343         /* Doesnt count unregistered clients */
344         return (local_users.size() - this->UnregisteredUserCount());
345 }
346         
347 bool InspIRCd::IsChannel(const char *chname)
348 {
349         char *c;
350
351         /* check for no name - don't check for !*chname, as if it is empty, it won't be '#'! */
352         if (!chname || *chname != '#')
353         {
354                 return false;
355         }
356
357         c = (char *)chname + 1;
358         while (*c)
359         {
360                 switch (*c)
361                 {
362                         case ' ':
363                         case ',':
364                         case 7:
365                                 return false;
366                 }
367
368                 c++;
369         }
370                 
371         /* too long a name - note funky pointer arithmetic here. */
372         if ((c - chname) > CHANMAX)
373         {
374                         return false;
375         }
376
377         return true;
378 }
379
380 bool InspIRCd::IsNick(const char* n)
381 {
382         if (!n || !*n)
383                 return false;
384  
385         int p = 0;
386         for (char* i = (char*)n; *i; i++, p++)
387         {
388                 if ((*i >= 'A') && (*i <= '}'))
389                 {
390                         /* "A"-"}" can occur anywhere in a nickname */
391                         continue;
392                 }
393
394                 if ((((*i >= '0') && (*i <= '9')) || (*i == '-')) && (i > n))
395                 {
396                         /* "0"-"9", "-" can occur anywhere BUT the first char of a nickname */
397                         continue;
398                 }
399
400                 /* invalid character! abort */
401                 return false;
402         }
403
404         /* too long? or not -- pointer arithmetic rocks */
405         return (p < NICKMAX - 1);
406 }
407
408
409 bool InspIRCd::IsIdent(const char* n)
410 {
411         if (!n || !*n)
412                 return false;
413
414         for (char* i = (char*)n; *i; i++)
415         {
416                 if ((*i >= 'A') && (*i <= '}'))
417                 {
418                         continue;
419                 }
420
421                 if (((*i >= '0') && (*i <= '9')) || (*i == '-') || (*i == '.'))
422                 {
423                         continue;
424                 }
425
426                 return false;
427         }
428
429         return true;
430 }
431
432 void InspIRCd::OpenLog(char** argv, int argc)
433 {
434         Config->MyDir = ServerConfig::GetFullProgDir(argv,argc);
435
436         if (!*this->LogFileName)
437         {
438                 if (Config->logpath == "")
439                 {
440                         Config->logpath = Config->MyDir + "/ircd.log";
441                 }
442
443                 Config->log_file = fopen(Config->logpath.c_str(),"a+");
444         }
445         else
446         {
447                 Config->log_file = fopen(this->LogFileName,"a+");
448         }
449
450         if (!Config->log_file)
451         {
452                 printf("ERROR: Could not write to logfile %s: %s\n\n", Config->logpath.c_str(), strerror(errno));
453                 Exit(EXIT_STATUS_LOG);
454         }
455
456         this->Logger = new FileLogger(this, Config->log_file);
457 }
458
459 void InspIRCd::CheckRoot()
460 {
461         if (geteuid() == 0)
462         {
463                 printf("WARNING!!! You are running an irc server as ROOT!!! DO NOT DO THIS!!!\n\n");
464                 this->Log(DEFAULT,"Cant start as root");
465                 Exit(EXIT_STATUS_ROOT);
466         }
467 }
468
469 void InspIRCd::CheckDie()
470 {
471         if (*Config->DieValue)
472         {
473                 printf("WARNING: %s\n\n",Config->DieValue);
474                 this->Log(DEFAULT,"Died because of <die> tag: %s",Config->DieValue);
475                 Exit(EXIT_STATUS_DIETAG);
476         }
477 }
478
479 /* We must load the modules AFTER initializing the socket engine, now */
480 void InspIRCd::LoadAllModules()
481 {
482         char configToken[MAXBUF];
483         Config->module_names.clear();
484         this->ModCount = -1;
485
486         for (int count = 0; count < Config->ConfValueEnum(Config->config_data, "module"); count++)
487         {
488                 Config->ConfValue(Config->config_data, "module", "name", count, configToken, MAXBUF);
489                 printf_c("[\033[1;32m*\033[0m] Loading module:\t\033[1;32m%s\033[0m\n",configToken);
490                 
491                 if (!this->LoadModule(configToken))             
492                 {
493                         this->Log(DEFAULT,"There was an error loading the module '%s': %s", configToken, this->ModuleError());
494                         printf_c("\n[\033[1;31m*\033[0m] There was an error loading the module '%s': %s\n\n", configToken, this->ModuleError());
495                         Exit(EXIT_STATUS_MODULE);
496                 }
497         }
498         printf_c("\nA total of \033[1;32m%d\033[0m module%s been loaded.\n", this->ModCount+1, this->ModCount+1 == 1 ? " has" : "s have");
499         this->Log(DEFAULT,"Total loaded modules: %d", this->ModCount+1);
500 }
501
502 void InspIRCd::SendWhoisLine(userrec* user, userrec* dest, int numeric, const std::string &text)
503 {
504         std::string copy_text = text;
505
506         int MOD_RESULT = 0;
507         FOREACH_RESULT_I(this, I_OnWhoisLine, OnWhoisLine(user, dest, numeric, copy_text));
508
509         if (!MOD_RESULT)
510                 user->WriteServ("%d %s", numeric, copy_text.c_str());
511 }
512
513 void InspIRCd::SendWhoisLine(userrec* user, userrec* dest, int numeric, const char* format, ...)
514 {
515         char textbuffer[MAXBUF];
516         va_list argsPtr;
517         va_start (argsPtr, format);
518         vsnprintf(textbuffer, MAXBUF, format, argsPtr);
519         va_end(argsPtr);
520
521         this->SendWhoisLine(user, dest, numeric, std::string(textbuffer));
522 }
523