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