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