]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/helperfuncs.cpp
Remove do_log() prototypes
[user/henk/code/inspircd.git] / src / helperfuncs.cpp
1 /*       +------------------------------------+
2  *       | Inspire Internet Relay Chat Daemon |
3  *       +------------------------------------+
4  *
5  *  InspIRCd is copyright (C) 2002-2006 ChatSpike-Dev.
6  *                     E-mail:
7  *              <brain@chatspike.net>
8  *              <Craig@chatspike.net>
9  *
10  * Written by Craig Edwards, Craig McLure, and others.
11  * This program is free but copyrighted software; see
12  *          the file COPYING for details.
13  *
14  * ---------------------------------------------------
15  */
16
17 #include <stdarg.h>
18 #include "inspircd_config.h"
19 #include "inspircd.h"
20 #include "configreader.h"
21 #include <unistd.h>
22 #include <fcntl.h>
23 #include <sys/errno.h>
24 #include <signal.h>
25 #include <time.h>
26 #include <string>
27 #include <sstream>
28 #ifdef HAS_EXECINFO
29 #include <execinfo.h>
30 #endif
31 #include "connection.h"
32 #include "users.h"
33 #include "ctables.h"
34 #include "globals.h"
35 #include "modules.h"
36 #include "dynamic.h"
37 #include "wildcard.h"
38 #include "message.h"
39 #include "mode.h"
40 #include "xline.h"
41 #include "commands.h"
42 #include "inspstring.h"
43 #include "helperfuncs.h"
44 #include "hashcomp.h"
45 #include "typedefs.h"
46
47 extern int MODCOUNT;
48 extern ModuleList modules;
49 extern InspIRCd* ServerInstance;
50 extern time_t TIME;
51 extern char lowermap[255];
52 extern userrec* fd_ref_table[MAX_DESCRIPTORS];
53 extern std::vector<userrec*> all_opers;
54 extern user_hash clientlist;
55 extern chan_hash chanlist;
56
57 char LOG_FILE[MAXBUF];
58
59 extern std::vector<userrec*> local_users;
60
61 static char TIMESTR[26];
62 static time_t LAST = 0;
63
64 /** log()
65  *  Write a line of text `text' to the logfile (and stdout, if in nofork) if the level `level'
66  *  is greater than the configured loglevel.
67  */
68 void InspIRCd::Log(int level, const char* text, ...)
69 {
70         va_list argsPtr;
71         char textbuffer[MAXBUF];
72
73         va_start(argsPtr, text);
74         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
75         va_end(argsPtr);
76
77         InspIRCd::Log(level, std::string(textbuffer));
78 }
79
80 void InspIRCd::Log(int level, const std::string &text)
81 {
82         if (!ServerInstance || !ServerInstance->Config)
83                 return;
84
85         /* If we were given -debug we output all messages, regardless of configured loglevel */
86         if ((level < ServerInstance->Config->LogLevel) && !ServerInstance->Config->forcedebug)
87                 return;
88
89         if (TIME != LAST)
90         {
91                 struct tm *timeinfo = localtime(&TIME);
92
93                 strlcpy(TIMESTR,asctime(timeinfo),26);
94                 TIMESTR[24] = ':';
95                 LAST = TIME;
96         }
97
98         if (ServerInstance->Config->log_file && ServerInstance->Config->writelog)
99         {
100                 fprintf(ServerInstance->Config->log_file,"%s %s\n",TIMESTR,text.c_str());
101                 fflush(ServerInstance->Config->log_file);
102         }
103
104         if (ServerInstance->Config->nofork)
105         {
106                 printf("%s %s\n", TIMESTR, text.c_str());
107         }
108 }
109
110 /** readfile()
111  *  Read the contents of a file located by `fname' into a file_cache pointed at by `F'.
112  *
113  *  XXX - we may want to consider returning a file_cache or pointer to one, less confusing.
114  */
115 void readfile(file_cache &F, const char* fname)
116 {
117         FILE* file;
118         char linebuf[MAXBUF];
119
120         log(DEBUG,"readfile: loading %s",fname);
121         F.clear();
122         file =  fopen(fname,"r");
123
124         if (file)
125         {
126                 while (!feof(file))
127                 {
128                         fgets(linebuf,sizeof(linebuf),file);
129                         linebuf[strlen(linebuf)-1]='\0';
130
131                         if (!*linebuf)
132                         {
133                                 strcpy(linebuf,"  ");
134                         }
135
136                         if (!feof(file))
137                         {
138                                 F.push_back(linebuf);
139                         }
140                 }
141
142                 fclose(file);
143         }
144         else
145         {
146                 log(DEBUG,"readfile: failed to load file: %s",fname);
147         }
148
149         log(DEBUG,"readfile: loaded %s, %lu lines",fname,(unsigned long)F.size());
150 }
151
152
153 std::string GetServerDescription(const char* servername)
154 {
155         std::string description = "";
156
157         FOREACH_MOD(I_OnGetServerDescription,OnGetServerDescription(servername,description));
158
159         if (description != "")
160         {
161                 return description;
162         }
163         else
164         {
165                 // not a remote server that can be found, it must be me.
166                 return ServerInstance->Config->ServerDesc;
167         }
168 }
169
170 /* XXX - We don't use WriteMode for this because WriteMode is very slow and
171  * this isnt. Basically WriteMode has to iterate ALL the users 'n' times for
172  * the number of modes provided, e.g. if you send WriteMode 'og' to write to
173  * opers with globops, and you have 2000 users, thats 4000 iterations. WriteOpers
174  * uses the oper list, which means if you have 2000 users but only 5 opers,
175  * it iterates 5 times.
176  */
177 void WriteOpers(const char* text, ...)
178 {
179         char textbuffer[MAXBUF];
180         va_list argsPtr;
181
182         if (!text)
183         {
184                 log(DEFAULT,"*** BUG *** WriteOpers was given an invalid parameter");
185                 return;
186         }
187
188         va_start(argsPtr, text);
189         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
190         va_end(argsPtr);
191
192         WriteOpers_NoFormat(textbuffer);
193 }
194
195 void WriteOpers_NoFormat(const char* text)
196 {
197         if (!text)
198         {
199                 log(DEFAULT,"*** BUG *** WriteOpers_NoFormat was given an invalid parameter");
200                 return;
201         }
202
203         for (std::vector<userrec*>::iterator i = all_opers.begin(); i != all_opers.end(); i++)
204         {
205                 userrec* a = *i;
206
207                 if (IS_LOCAL(a))
208                 {
209                         if (a->modes[UM_SERVERNOTICE])
210                         {
211                                 // send server notices to all with +s
212                                 a->WriteServ("NOTICE %s :%s",a->nick,text);
213                         }
214                 }
215         }
216 }
217
218 void ServerNoticeAll(char* text, ...)
219 {
220         if (!text)
221                 return;
222
223         char textbuffer[MAXBUF];
224         char formatbuffer[MAXBUF];
225         va_list argsPtr;
226         va_start (argsPtr, text);
227         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
228         va_end(argsPtr);
229
230         snprintf(formatbuffer,MAXBUF,"NOTICE $%s :%s",ServerInstance->Config->ServerName,textbuffer);
231
232         for (std::vector<userrec*>::const_iterator i = local_users.begin(); i != local_users.end(); i++)
233         {
234                 userrec* t = *i;
235                 t->WriteServ(std::string(formatbuffer));
236         }
237 }
238
239 void ServerPrivmsgAll(char* text, ...)
240 {
241         if (!text)
242                 return;
243
244         char textbuffer[MAXBUF];
245         char formatbuffer[MAXBUF];
246         va_list argsPtr;
247         va_start (argsPtr, text);
248         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
249         va_end(argsPtr);
250
251         snprintf(formatbuffer,MAXBUF,"PRIVMSG $%s :%s",ServerInstance->Config->ServerName,textbuffer);
252
253         for (std::vector<userrec*>::const_iterator i = local_users.begin(); i != local_users.end(); i++)
254         {
255                 userrec* t = *i;
256                 t->WriteServ(std::string(formatbuffer));
257         }
258 }
259
260 void WriteMode(const char* modes, int flags, const char* text, ...)
261 {
262         char textbuffer[MAXBUF];
263         int modelen;
264         va_list argsPtr;
265
266         if ((!text) || (!modes) || (!flags))
267         {
268                 log(DEFAULT,"*** BUG *** WriteMode was given an invalid parameter");
269                 return;
270         }
271
272         va_start(argsPtr, text);
273         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
274         va_end(argsPtr);
275         modelen = strlen(modes);
276
277         for (std::vector<userrec*>::const_iterator i = local_users.begin(); i != local_users.end(); i++)
278         {
279                 userrec* t = (userrec*)(*i);
280                 bool send_to_user = false;
281
282                 if (flags == WM_AND)
283                 {
284                         send_to_user = true;
285
286                         for (int n = 0; n < modelen; n++)
287                         {
288                                 if (!t->modes[modes[n]-65])
289                                 {
290                                         send_to_user = false;
291                                         break;
292                                 }
293                         }
294                 }
295                 else if (flags == WM_OR)
296                 {
297                         send_to_user = false;
298
299                         for (int n = 0; n < modelen; n++)
300                         {
301                                 if (t->modes[modes[n]-65])
302                                 {
303                                         send_to_user = true;
304                                         break;
305                                 }
306                         }
307                 }
308
309                 if (send_to_user)
310                 {
311                         t->WriteServ("NOTICE %s :%s",t->nick,textbuffer);
312                 }
313         }
314 }
315
316 void NoticeAll(userrec *source, bool local_only, char* text, ...)
317 {
318         char textbuffer[MAXBUF];
319         char formatbuffer[MAXBUF];
320         va_list argsPtr;
321
322         if ((!text) || (!source))
323         {
324                 log(DEFAULT,"*** BUG *** NoticeAll was given an invalid parameter");
325                 return;
326         }
327
328         va_start(argsPtr, text);
329         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
330         va_end(argsPtr);
331
332         snprintf(formatbuffer,MAXBUF,"NOTICE $* :%s",textbuffer);
333
334         for (std::vector<userrec*>::const_iterator i = local_users.begin(); i != local_users.end(); i++)
335         {
336                 userrec* t = *i;
337                 t->WriteFrom(source,std::string(formatbuffer));
338         }
339 }
340
341
342 /* convert a string to lowercase. Note following special circumstances
343  * taken from RFC 1459. Many "official" server branches still hold to this
344  * rule so i will too;
345  *
346  *  Because of IRC's scandanavian origin, the characters {}| are
347  *  considered to be the lower case equivalents of the characters []\,
348  *  respectively. This is a critical issue when determining the
349  *  equivalence of two nicknames.
350  */
351 void strlower(char *n)
352 {
353         if (n)
354         {
355                 for (char* t = n; *t; t++)
356                         *t = lowermap[(unsigned char)*t];
357         }
358 }
359
360 /* Find a user record by nickname and return a pointer to it */
361
362 userrec* Find(const std::string &nick)
363 {
364         user_hash::iterator iter = clientlist.find(nick);
365
366         if (iter == clientlist.end())
367                 /* Couldn't find it */
368                 return NULL;
369
370         return iter->second;
371 }
372
373 userrec* Find(const char* nick)
374 {
375         user_hash::iterator iter;
376
377         if (!nick)
378                 return NULL;
379
380         iter = clientlist.find(nick);
381         
382         if (iter == clientlist.end())
383                 return NULL;
384
385         return iter->second;
386 }
387
388 /* find a channel record by channel name and return a pointer to it */
389
390 chanrec* FindChan(const char* chan)
391 {
392         chan_hash::iterator iter;
393
394         if (!chan)
395         {
396                 log(DEFAULT,"*** BUG *** Findchan was given an invalid parameter");
397                 return NULL;
398         }
399
400         iter = chanlist.find(chan);
401
402         if (iter == chanlist.end())
403                 /* Couldn't find it */
404                 return NULL;
405
406         return iter->second;
407 }
408
409
410 long GetMaxBans(char* name)
411 {
412         std::string x;
413         for (std::map<std::string,int>::iterator n = ServerInstance->Config->maxbans.begin(); n != ServerInstance->Config->maxbans.end(); n++)
414         {
415                 x = n->first;
416                 if (match(name,x.c_str()))
417                 {
418                         return n->second;
419                 }
420         }
421         return 64;
422 }
423
424 void purge_empty_chans(userrec* u)
425 {
426         std::vector<chanrec*> to_delete;
427
428         // firstly decrement the count on each channel
429         for (std::vector<ucrec*>::iterator f = u->chans.begin(); f != u->chans.end(); f++)
430         {
431                 ucrec* uc = (ucrec*)(*f);
432                 if (uc->channel)
433                 {
434                         if (uc->channel->DelUser(u) == 0)
435                         {
436                                 /* No users left in here, mark it for deletion */
437                                 to_delete.push_back(uc->channel);
438                                 uc->channel = NULL;
439                         }
440                 }
441         }
442
443         log(DEBUG,"purge_empty_chans: %d channels to delete",to_delete.size());
444
445         for (std::vector<chanrec*>::iterator n = to_delete.begin(); n != to_delete.end(); n++)
446         {
447                 chanrec* thischan = (chanrec*)*n;
448                 chan_hash::iterator i2 = chanlist.find(thischan->name);
449                 if (i2 != chanlist.end())
450                 {
451                         FOREACH_MOD(I_OnChannelDelete,OnChannelDelete(i2->second));
452                         DELETE(i2->second);
453                         chanlist.erase(i2);
454                 }
455         }
456
457         u->UnOper();
458 }
459
460
461 char* chanmodes(chanrec *chan, bool showkey)
462 {
463         static char scratch[MAXBUF];
464         static char sparam[MAXBUF];
465         char* offset = scratch;
466         std::string extparam = "";
467
468         if (!chan)
469         {
470                 log(DEFAULT,"*** BUG *** chanmodes was given an invalid parameter");
471                 *scratch = '\0';
472                 return scratch;
473         }
474
475         *scratch = '\0';
476         *sparam = '\0';
477
478         /* This was still iterating up to 190, chanrec::custom_modes is only 64 elements -- Om */
479         for(int n = 0; n < 64; n++)
480         {
481                 if(chan->modes[n])
482                 {
483                         *offset++ = n+65;
484                         extparam = "";
485                         switch (n)
486                         {
487                                 case CM_KEY:
488                                         extparam = (showkey ? chan->key : "<key>");
489                                 break;
490                                 case CM_LIMIT:
491                                         extparam = ConvToStr(chan->limit);
492                                 break;
493                                 case CM_NOEXTERNAL:
494                                 case CM_TOPICLOCK:
495                                 case CM_INVITEONLY:
496                                 case CM_MODERATED:
497                                 case CM_SECRET:
498                                 case CM_PRIVATE:
499                                         /* We know these have no parameters */
500                                 break;
501                                 default:
502                                         extparam = chan->GetModeParameter(n+65);
503                                 break;
504                         }
505                         if (extparam != "")
506                         {
507                                 charlcat(sparam,' ',MAXBUF);
508                                 strlcat(sparam,extparam.c_str(),MAXBUF);
509                         }
510                 }
511         }
512
513         /* Null terminate scratch */
514         *offset = '\0';
515         strlcat(scratch,sparam,MAXBUF);
516         return scratch;
517 }
518
519
520 /* compile a userlist of a channel into a string, each nick seperated by
521  * spaces and op, voice etc status shown as @ and + */
522
523 void userlist(userrec *user,chanrec *c)
524 {
525         if ((!c) || (!user))
526         {
527                 log(DEFAULT,"*** BUG *** userlist was given an invalid parameter");
528                 return;
529         }
530
531         char list[MAXBUF];
532         size_t dlen, curlen;
533
534         dlen = curlen = snprintf(list,MAXBUF,"353 %s = %s :", user->nick, c->name);
535
536         int numusers = 0;
537         char* ptr = list + dlen;
538
539         CUList *ulist= c->GetUsers();
540
541         /* Improvement by Brain - this doesnt change in value, so why was it inside
542          * the loop?
543          */
544         bool has_user = c->HasUser(user);
545
546         for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
547         {
548                 if ((!has_user) && (i->second->modes[UM_INVISIBLE]))
549                 {
550                         /*
551                          * user is +i, and source not on the channel, does not show
552                          * nick in NAMES list
553                          */
554                         continue;
555                 }
556
557                 size_t ptrlen = snprintf(ptr, MAXBUF, "%s%s ", cmode(i->second, c), i->second->nick);
558
559                 curlen += ptrlen;
560                 ptr += ptrlen;
561
562                 numusers++;
563
564                 if (curlen > (480-NICKMAX))
565                 {
566                         /* list overflowed into multiple numerics */
567                         user->WriteServ(list);
568
569                         /* reset our lengths */
570                         dlen = curlen = snprintf(list,MAXBUF,"353 %s = %s :", user->nick, c->name);
571                         ptr = list + dlen;
572
573                         ptrlen = 0;
574                         numusers = 0;
575                 }
576         }
577
578         /* if whats left in the list isnt empty, send it */
579         if (numusers)
580         {
581                 user->WriteServ(list);
582         }
583 }
584
585 /*
586  * return a count of the users on a specific channel accounting for
587  * invisible users who won't increase the count. e.g. for /LIST
588  */
589 int usercount_i(chanrec *c)
590 {
591         int count = 0;
592
593         if (!c)
594                 return 0;
595
596         CUList *ulist= c->GetUsers();
597         for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
598         {
599                 if (!(i->second->modes[UM_INVISIBLE]))
600                         count++;
601         }
602
603         return count;
604 }
605
606 int usercount(chanrec *c)
607 {
608         return (c ? c->GetUserCounter() : 0);
609 }
610
611
612 /* looks up a users password for their connection class (<ALLOW>/<DENY> tags)
613  * NOTE: If the <ALLOW> or <DENY> tag specifies an ip, and this user resolves,
614  * then their ip will be taken as 'priority' anyway, so for example,
615  * <connect allow="127.0.0.1"> will match joe!bloggs@localhost
616  */
617 ConnectClass GetClass(userrec *user)
618 {
619         for (ClassVector::iterator i = ServerInstance->Config->Classes.begin(); i != ServerInstance->Config->Classes.end(); i++)
620         {
621                 if ((match(user->GetIPString(),i->host.c_str(),true)) || (match(user->host,i->host.c_str())))
622                 {
623                         return *i;
624                 }
625         }
626
627         return *(ServerInstance->Config->Classes.begin());
628 }
629
630 /*
631  * sends out an error notice to all connected clients (not to be used
632  * lightly!)
633  */
634 void send_error(char *s)
635 {
636         log(DEBUG,"send_error: %s",s);
637
638         for (std::vector<userrec*>::const_iterator i = local_users.begin(); i != local_users.end(); i++)
639         {
640                 userrec* t = (userrec*)(*i);
641                 if (t->registered == REG_ALL)
642                 {
643                         t->WriteServ("NOTICE %s :%s",t->nick,s);
644                 }
645                 else
646                 {
647                         // fix - unregistered connections receive ERROR, not NOTICE
648                         t->Write("ERROR :%s",s);
649                 }
650         }
651 }
652
653 void Error(int status)
654 {
655         void *array[300];
656         size_t size;
657         char **strings;
658
659         signal(SIGALRM, SIG_IGN);
660         signal(SIGPIPE, SIG_IGN);
661         signal(SIGTERM, SIG_IGN);
662         signal(SIGABRT, SIG_IGN);
663         signal(SIGSEGV, SIG_IGN);
664         signal(SIGURG, SIG_IGN);
665         signal(SIGKILL, SIG_IGN);
666         log(DEFAULT,"*** fell down a pothole in the road to perfection ***");
667 #ifdef HAS_EXECINFO
668         log(DEFAULT,"Please report the backtrace lines shown below with any bugreport to the bugtracker at http://www.inspircd.org/bugtrack/");
669         size = backtrace(array, 30);
670         strings = backtrace_symbols(array, size);
671         for (size_t i = 0; i < size; i++) {
672                 log(DEFAULT,"[%d] %s", i, strings[i]);
673         }
674         free(strings);
675         WriteOpers("*** SIGSEGV: Please see the ircd.log for backtrace and report the error to http://www.inspircd.org/bugtrack/");
676 #else
677         log(DEFAULT,"You do not have execinfo.h so i could not backtrace -- on FreeBSD, please install the libexecinfo port.");
678 #endif
679         send_error("Somebody screwed up... Whoops. IRC Server terminating.");
680         signal(SIGSEGV, SIG_DFL);
681         if (raise(SIGSEGV) == -1)
682         {
683                 log(DEFAULT,"What the hell, i couldnt re-raise SIGSEGV! Error: %s",strerror(errno));
684         }
685         Exit(status);
686 }
687
688 // this function counts all users connected, wether they are registered or NOT.
689 int usercnt(void)
690 {
691         return clientlist.size();
692 }
693
694 // this counts only registered users, so that the percentages in /MAP don't mess up when users are sitting in an unregistered state
695 int registered_usercount(void)
696 {
697         int c = 0;
698
699         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
700         {
701                 c += (i->second->registered == REG_ALL);
702         }
703
704         return c;
705 }
706
707 int usercount_invisible(void)
708 {
709         int c = 0;
710
711         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
712         {
713                 c += ((i->second->registered == REG_ALL) && (i->second->modes[UM_INVISIBLE]));
714         }
715
716         return c;
717 }
718
719 int usercount_opers(void)
720 {
721         int c = 0;
722
723         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
724         {
725                 if (*(i->second->oper))
726                         c++;
727         }
728         return c;
729 }
730
731 int usercount_unknown(void)
732 {
733         int c = 0;
734
735         for (std::vector<userrec*>::const_iterator i = local_users.begin(); i != local_users.end(); i++)
736         {
737                 userrec* t = (userrec*)(*i);
738                 if (t->registered != REG_ALL)
739                         c++;
740         }
741
742         return c;
743 }
744
745 long chancount(void)
746 {
747         return chanlist.size();
748 }
749
750 long local_count()
751 {
752         int c = 0;
753
754         for (std::vector<userrec*>::const_iterator i = local_users.begin(); i != local_users.end(); i++)
755         {
756                 userrec* t = (userrec*)(*i);
757                 if (t->registered == REG_ALL)
758                         c++;
759         }
760
761         return c;
762 }
763
764 void ShowMOTD(userrec *user)
765 {
766         if (!ServerInstance->Config->MOTD.size())
767         {
768                 user->WriteServ("422 %s :Message of the day file is missing.",user->nick);
769                 return;
770         }
771         user->WriteServ("375 %s :%s message of the day", user->nick, ServerInstance->Config->ServerName);
772
773         for (unsigned int i = 0; i < ServerInstance->Config->MOTD.size(); i++)
774                 user->WriteServ("372 %s :- %s",user->nick,ServerInstance->Config->MOTD[i].c_str());
775
776         user->WriteServ("376 %s :End of message of the day.", user->nick);
777 }
778
779 void ShowRULES(userrec *user)
780 {
781         if (!ServerInstance->Config->RULES.size())
782         {
783                 user->WriteServ("NOTICE %s :Rules file is missing.",user->nick);
784                 return;
785         }
786         user->WriteServ("NOTICE %s :%s rules",user->nick,ServerInstance->Config->ServerName);
787
788         for (unsigned int i = 0; i < ServerInstance->Config->RULES.size(); i++)
789                 user->WriteServ("NOTICE %s :%s",user->nick,ServerInstance->Config->RULES[i].c_str());
790
791         user->WriteServ("NOTICE %s :End of %s rules.",user->nick,ServerInstance->Config->ServerName);
792 }
793
794 // this returns 1 when all modules are satisfied that the user should be allowed onto the irc server
795 // (until this returns true, a user will block in the waiting state, waiting to connect up to the
796 // registration timeout maximum seconds)
797 bool AllModulesReportReady(userrec* user)
798 {
799         if (!ServerInstance->Config->global_implementation[I_OnCheckReady])
800                 return true;
801
802         for (int i = 0; i <= MODCOUNT; i++)
803         {
804                 if (ServerInstance->Config->implement_lists[i][I_OnCheckReady])
805                 {
806                         int res = modules[i]->OnCheckReady(user);
807                         if (!res)
808                                 return false;
809                 }
810         }
811
812         return true;
813 }
814
815 /* Make Sure Modules Are Avaliable!
816  * (BugFix By Craig.. See? I do work! :p)
817  * Modified by brain, requires const char*
818  * to work with other API functions
819  */
820
821 /* XXX - Needed? */
822 bool FileExists (const char* file)
823 {
824         FILE *input;
825         if ((input = fopen (file, "r")) == NULL)
826         {
827                 return(false);
828         }
829         else
830         {
831                 fclose (input);
832                 return(true);
833         }
834 }
835
836 char* CleanFilename(char* name)
837 {
838         char* p = name + strlen(name);
839         while ((p != name) && (*p != '/')) p--;
840         return (p != name ? ++p : p);
841 }
842
843 bool DirValid(char* dirandfile)
844 {
845         char work[MAXBUF];
846         char buffer[MAXBUF];
847         char otherdir[MAXBUF];
848         int p;
849
850         strlcpy(work, dirandfile, MAXBUF);
851         p = strlen(work);
852
853         // we just want the dir
854         while (*work)
855         {
856                 if (work[p] == '/')
857                 {
858                         work[p] = '\0';
859                         break;
860                 }
861
862                 work[p--] = '\0';
863         }
864
865         // Get the current working directory
866         if (getcwd(buffer, MAXBUF ) == NULL )
867                 return false;
868
869         chdir(work);
870
871         if (getcwd(otherdir, MAXBUF ) == NULL )
872                 return false;
873
874         chdir(buffer);
875
876         size_t t = strlen(work);
877
878         if (strlen(otherdir) >= t)
879         {
880                 otherdir[t] = '\0';
881
882                 if (!strcmp(otherdir,work))
883                 {
884                         return true;
885                 }
886
887                 return false;
888         }
889         else
890         {
891                 return false;
892         }
893 }
894
895 std::string GetFullProgDir(char** argv, int argc)
896 {
897         char work[MAXBUF];
898         char buffer[MAXBUF];
899         char otherdir[MAXBUF];
900         int p;
901
902         strlcpy(work,argv[0],MAXBUF);
903         p = strlen(work);
904
905         // we just want the dir
906         while (*work)
907         {
908                 if (work[p] == '/')
909                 {
910                         work[p] = '\0';
911                         break;
912                 }
913
914                 work[p--] = '\0';
915         }
916
917         // Get the current working directory
918         if (getcwd(buffer, MAXBUF) == NULL)
919                 return "";
920
921         chdir(work);
922
923         if (getcwd(otherdir, MAXBUF) == NULL)
924                 return "";
925
926         chdir(buffer);
927         return otherdir;
928 }
929
930 int InsertMode(std::string &output, const char* mode, unsigned short section)
931 {
932         unsigned short currsection = 1;
933         unsigned int pos = output.find("CHANMODES=", 0) + 10; // +10 for the length of "CHANMODES="
934         
935         if(section > 4 || section == 0)
936         {
937                 log(DEBUG, "InsertMode: CHANMODES doesn't have a section %dh :/", section);
938                 return 0;
939         }
940         
941         for(; pos < output.size(); pos++)
942         {
943                 if(section == currsection)
944                         break;
945                         
946                 if(output[pos] == ',')
947                         currsection++;
948         }
949         
950         output.insert(pos, mode);
951         return 1;
952 }
953
954 bool IsValidChannelName(const char *chname)
955 {
956         char *c;
957
958         /* check for no name - don't check for !*chname, as if it is empty, it won't be '#'! */
959         if (!chname || *chname != '#')
960         {
961                 return false;
962         }
963
964         c = (char *)chname + 1;
965         while (*c)
966         {
967                 switch (*c)
968                 {
969                         case ' ':
970                         case ',':
971                         case 7:
972                                 return false;
973                 }
974
975                 c++;
976         }
977                 
978         /* too long a name - note funky pointer arithmetic here. */
979         if ((c - chname) > CHANMAX)
980         {
981                         return false;
982         }
983
984         return true;
985 }
986
987 inline int charlcat(char* x,char y,int z)
988 {
989         char* x__n = x;
990         int v = 0;
991
992         while(*x__n++)
993                 v++;
994
995         if (v < z - 1)
996         {
997                 *--x__n = y;
998                 *++x__n = 0;
999         }
1000
1001         return v;
1002 }
1003
1004 bool charremove(char* mp, char remove)
1005 {
1006         char* mptr = mp;
1007         bool shift_down = false;
1008
1009         while (*mptr)
1010         {
1011                 if (*mptr == remove)
1012                 shift_down = true;
1013
1014                 if (shift_down)
1015                         *mptr = *(mptr+1);
1016
1017                 mptr++;
1018         }
1019
1020         return shift_down;
1021 }
1022
1023 void OpenLog(char** argv, int argc)
1024 {
1025         if (!*LOG_FILE)
1026         {
1027                 if (ServerInstance->Config->logpath == "")
1028                 {
1029                         ServerInstance->Config->logpath = GetFullProgDir(argv,argc) + "/ircd.log";
1030                 }
1031         }
1032         else
1033         {
1034                 ServerInstance->Config->log_file = fopen(LOG_FILE,"a+");
1035
1036                 if (!ServerInstance->Config->log_file)
1037                 {
1038                         printf("ERROR: Could not write to logfile %s, bailing!\n\n",ServerInstance->Config->logpath.c_str());
1039                         Exit(ERROR);
1040                 }
1041                 
1042                 return;
1043         }
1044
1045         ServerInstance->Config->log_file = fopen(ServerInstance->Config->logpath.c_str(),"a+");
1046
1047         if (!ServerInstance->Config->log_file)
1048         {
1049                 printf("ERROR: Could not write to logfile %s, bailing!\n\n",ServerInstance->Config->logpath.c_str());
1050                 Exit(ERROR);
1051         }
1052 }
1053
1054 void CheckRoot()
1055 {
1056         if (geteuid() == 0)
1057         {
1058                 printf("WARNING!!! You are running an irc server as ROOT!!! DO NOT DO THIS!!!\n\n");
1059                 log(DEFAULT,"InspIRCd: startup: not starting with UID 0!");
1060                 Exit(ERROR);
1061         }
1062 }
1063
1064 void CheckDie()
1065 {
1066         if (*ServerInstance->Config->DieValue)
1067         {
1068                 printf("WARNING: %s\n\n",ServerInstance->Config->DieValue);
1069                 log(DEFAULT,"Uh-Oh, somebody didn't read their config file: '%s'",ServerInstance->Config->DieValue);
1070                 Exit(ERROR);
1071         }
1072 }
1073
1074 /* We must load the modules AFTER initializing the socket engine, now */
1075 void LoadAllModules(InspIRCd* ServerInstance)
1076 {
1077         char configToken[MAXBUF];
1078         ServerInstance->Config->module_names.clear();
1079         MODCOUNT = -1;
1080
1081         for (int count = 0; count < ServerInstance->Config->ConfValueEnum(ServerInstance->Config->config_data, "module"); count++)
1082         {
1083                 ServerInstance->Config->ConfValue(ServerInstance->Config->config_data, "module","name",count,configToken,MAXBUF);
1084                 printf("[\033[1;32m*\033[0m] Loading module:\t\033[1;32m%s\033[0m\n",configToken);
1085                 
1086                 if (!ServerInstance->LoadModule(configToken))           
1087                 {
1088                         log(DEFAULT,"Exiting due to a module loader error.");
1089                         printf("\nThere was an error loading a module: %s\n\n",ServerInstance->ModuleError());
1090                         Exit(0);
1091                 }
1092         }
1093         
1094         log(DEFAULT,"Total loaded modules: %lu",(unsigned long)MODCOUNT+1);
1095 }