]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/helperfuncs.cpp
Add userrec::HasMode, fix some typos.
[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 static char already_sent[MAX_DESCRIPTORS];
55 extern std::vector<userrec*> all_opers;
56 extern user_hash clientlist;
57 extern chan_hash chanlist;
58
59 char LOG_FILE[MAXBUF];
60
61 extern std::vector<userrec*> local_users;
62
63 static char TIMESTR[26];
64 static time_t LAST = 0;
65
66 /** log()
67  *  Write a line of text `text' to the logfile (and stdout, if in nofork) if the level `level'
68  *  is greater than the configured loglevel.
69  */
70 void do_log(int level, const char *text, ...)
71 {
72         va_list argsPtr;
73         char textbuffer[MAXBUF];
74
75         /* If we were given -debug we output all messages, regardless of configured loglevel */
76         if ((level < Config->LogLevel) && !Config->forcedebug)
77                 return;
78
79         if (TIME != LAST)
80         {
81                 struct tm *timeinfo = localtime(&TIME);
82
83                 strlcpy(TIMESTR,asctime(timeinfo),26);
84                 TIMESTR[24] = ':';
85                 LAST = TIME;
86         }
87
88         if (Config->log_file)
89         {
90                 va_start(argsPtr, text);
91                 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
92                 va_end(argsPtr);
93
94                 if (Config->writelog)
95                 {
96                         fprintf(Config->log_file,"%s %s\n",TIMESTR,textbuffer);
97                         fflush(Config->log_file);
98                 }
99         }
100         
101         if (Config->nofork)
102         {
103                 printf("%s %s\n", TIMESTR, textbuffer);
104         }
105 }
106
107 /** readfile()
108  *  Read the contents of a file located by `fname' into a file_cache pointed at by `F'.
109  *
110  *  XXX - we may want to consider returning a file_cache or pointer to one, less confusing.
111  */
112 void readfile(file_cache &F, const char* fname)
113 {
114         FILE* file;
115         char linebuf[MAXBUF];
116
117         log(DEBUG,"readfile: loading %s",fname);
118         F.clear();
119         file =  fopen(fname,"r");
120
121         if (file)
122         {
123                 while (!feof(file))
124                 {
125                         fgets(linebuf,sizeof(linebuf),file);
126                         linebuf[strlen(linebuf)-1]='\0';
127
128                         if (!*linebuf)
129                         {
130                                 strcpy(linebuf,"  ");
131                         }
132
133                         if (!feof(file))
134                         {
135                                 F.push_back(linebuf);
136                         }
137                 }
138
139                 fclose(file);
140         }
141         else
142         {
143                 log(DEBUG,"readfile: failed to load file: %s",fname);
144         }
145
146         log(DEBUG,"readfile: loaded %s, %lu lines",fname,(unsigned long)F.size());
147 }
148
149 /** Write_NoFormat()
150  *  Writes a given string in `text' to the socket on fd `sock' - only if the socket
151  *  is a valid entry in the local FD table.
152  */
153 void Write_NoFormat(int sock, const char *text)
154 {
155         char tb[MAXBUF];
156         int bytes;
157
158         if ((sock < 0) || (!text) || (sock > MAX_DESCRIPTORS))
159                 return;
160
161         if (fd_ref_table[sock])
162         {
163                 bytes = snprintf(tb,MAXBUF,"%s\r\n",text);
164                 chop(tb);
165
166                 if (Config->GetIOHook(fd_ref_table[sock]->port))
167                 {
168                         try
169                         {
170                                 Config->GetIOHook(fd_ref_table[sock]->port)->OnRawSocketWrite(sock,tb,bytes);
171                         }
172                         catch (ModuleException& modexcept)
173                         {
174                                 log(DEBUG,"Module exception caught: %s",modexcept.GetReason());
175                         }
176                 }
177                 else
178                 {
179                         fd_ref_table[sock]->AddWriteBuf(tb);
180                 }
181                 ServerInstance->stats->statsSent += bytes;
182         }
183         else
184                 log(DEFAULT,"ERROR! attempted write to a user with no fd_ref_table entry!!!");
185 }
186
187 /** Write()
188  *  Same as Write_NoFormat(), but formatted printf() style first.
189  */
190 void Write(int sock, char *text, ...)
191 {
192         va_list argsPtr;
193         char textbuffer[MAXBUF];
194         char tb[MAXBUF];
195         int bytes;
196
197         if ((sock < 0) || (sock > MAX_DESCRIPTORS))
198                 return;
199
200         if (!text)
201         {
202                 log(DEFAULT,"*** BUG *** Write was given an invalid parameter");
203                 return;
204         }
205
206         if (fd_ref_table[sock])
207         {
208
209                 va_start(argsPtr, text);
210                 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
211                 va_end(argsPtr);
212                 bytes = snprintf(tb,MAXBUF,"%s\r\n",textbuffer);
213                 chop(tb);
214
215                 if (Config->GetIOHook(fd_ref_table[sock]->port))
216                 {
217                         try
218                         {
219                                 Config->GetIOHook(fd_ref_table[sock]->port)->OnRawSocketWrite(sock,tb,bytes);
220                         }
221                         catch (ModuleException& modexcept)
222                         {
223                                 log(DEBUG,"Module exception caught: %s",modexcept.GetReason());
224                         }                                               
225                 }
226                 else
227                 {
228                         fd_ref_table[sock]->AddWriteBuf(tb);
229                 }
230                 ServerInstance->stats->statsSent += bytes;
231         }
232         else
233                 log(DEFAULT,"ERROR! attempted write to a user with no fd_ref_table entry!!!");
234 }
235
236 /** WriteServ_NoFormat()
237  *  Same as Write_NoFormat(), except prefixes `text' with `:server.name '.
238  */
239 void WriteServ_NoFormat(int sock, const char* text)
240 {
241         char tb[MAXBUF];
242         int bytes;
243
244         if ((sock < 0) || (!text) || (sock > MAX_DESCRIPTORS))
245                 return;
246
247         if (fd_ref_table[sock])
248         {
249                 bytes = snprintf(tb,MAXBUF,":%s %s\r\n",Config->ServerName,text);
250                 chop(tb);
251
252                 if (Config->GetIOHook(fd_ref_table[sock]->port))
253                 {
254                         try
255                         {
256                                 Config->GetIOHook(fd_ref_table[sock]->port)->OnRawSocketWrite(sock,tb,bytes);
257                         }
258                         catch (ModuleException& modexcept)
259                         {
260                                 log(DEBUG,"Module exception caught: %s",modexcept.GetReason());
261                         }
262                 }
263                 else
264                 {
265                         fd_ref_table[sock]->AddWriteBuf(tb);
266                 }
267                 ServerInstance->stats->statsSent += bytes;
268         }
269         else
270                 log(DEFAULT,"ERROR! attempted write to a user with no fd_ref_table entry!!!");
271 }
272
273 /** WriteServ()
274  *  Same as Write(), except `text' is prefixed with `:server.name '.
275  */
276 void WriteServ(int sock, char* text, ...)
277 {
278         va_list argsPtr;
279         char textbuffer[MAXBUF];
280
281         if ((sock < 0) || (sock > MAX_DESCRIPTORS))
282                 return;
283
284         if (!text)
285         {
286                 log(DEFAULT,"*** BUG *** WriteServ was given an invalid parameter");
287                 return;
288         }
289
290         if (!fd_ref_table[sock])
291                 return;
292
293         va_start(argsPtr, text);
294         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
295         va_end(argsPtr);
296         
297         WriteServ_NoFormat(sock, textbuffer);
298 }
299
300 /** WriteFrom_NoFormat()
301  * Write `text' to a socket with fd `sock' prefixed with `:n!u@h' - taken from
302  * the nick, user, and host of `user'.
303  */
304 void WriteFrom_NoFormat(int sock, userrec *user, const char* text)
305 {
306         char tb[MAXBUF];
307         int bytes;
308
309         if ((sock < 0) || (!text) || (!user) || (sock > MAX_DESCRIPTORS))
310                 return;
311
312         if (fd_ref_table[sock])
313         {
314                 bytes = snprintf(tb,MAXBUF,":%s %s\r\n",user->GetFullHost(),text);
315                 chop(tb);
316
317                 if (Config->GetIOHook(fd_ref_table[sock]->port))
318                 {
319                         try
320                         {
321                                 Config->GetIOHook(fd_ref_table[sock]->port)->OnRawSocketWrite(sock,tb,bytes);
322                         }
323                         catch (ModuleException& modexcept)
324                         {
325                                 log(DEBUG,"Module exception caught: %s",modexcept.GetReason());
326                         }
327                 }
328                 else
329                 {
330                         fd_ref_table[sock]->AddWriteBuf(tb);
331                 }
332                 ServerInstance->stats->statsSent += bytes;
333         }
334         else
335                 log(DEFAULT,"ERROR! attempted write to a user with no fd_ref_table entry!!!");
336 }
337
338 /* write text from an originating user to originating user */
339
340 void WriteFrom(int sock, userrec *user,char* text, ...)
341 {
342         va_list argsPtr;
343         char textbuffer[MAXBUF];
344         char tb[MAXBUF];
345         int bytes;
346
347         if ((sock < 0) || (sock > MAX_DESCRIPTORS))
348                 return;
349
350         if ((!text) || (!user))
351         {
352                 log(DEFAULT,"*** BUG *** WriteFrom was given an invalid parameter");
353                 return;
354         }
355
356         if (fd_ref_table[sock])
357         {
358
359                 va_start(argsPtr, text);
360                 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
361                 va_end(argsPtr);
362                 bytes = snprintf(tb,MAXBUF,":%s %s\r\n",user->GetFullHost(),textbuffer);
363                 chop(tb);
364
365                 if (Config->GetIOHook(fd_ref_table[sock]->port))
366                 {
367                         try
368                         {
369                                 Config->GetIOHook(fd_ref_table[sock]->port)->OnRawSocketWrite(sock,tb,bytes);
370                         }
371                         catch (ModuleException& modexcept)
372                         {
373                                 log(DEBUG,"Module exception caught: %s",modexcept.GetReason());
374                         }
375                 }
376                 else
377                 {
378                         fd_ref_table[sock]->AddWriteBuf(tb);
379                 }
380
381                 ServerInstance->stats->statsSent += bytes;
382         }
383         else
384                 log(DEFAULT,"ERROR! attempted write to a user with no fd_ref_table entry!!!");
385 }
386
387 /* write text to an destination user from a source user (e.g. user privmsg) */
388
389 void WriteTo(userrec *source, userrec *dest,char *data, ...)
390 {
391         char textbuffer[MAXBUF];
392         va_list argsPtr;
393
394         if ((!dest) || (!data))
395         {
396                 log(DEFAULT,"*** BUG *** WriteTo was given an invalid parameter");
397                 return;
398         }
399
400         if (!IS_LOCAL(dest))
401                 return;
402
403         va_start(argsPtr, data);
404         vsnprintf(textbuffer, MAXBUF, data, argsPtr);
405         va_end(argsPtr);
406         chop(textbuffer);
407
408         // if no source given send it from the server.
409         if (!source)
410         {
411                 WriteServ_NoFormat(dest->fd,textbuffer);
412         }
413         else
414         {
415                 WriteFrom_NoFormat(dest->fd,source,textbuffer);
416         }
417 }
418
419 void WriteTo_NoFormat(userrec *source, userrec *dest, const char *data)
420 {
421         if ((!dest) || (!data))
422                 return;
423
424         if (!source)
425         {
426                 WriteServ_NoFormat(dest->fd,data);
427         }
428         else
429         {
430                 WriteFrom_NoFormat(dest->fd,source,data);
431         }
432 }
433
434 /* write formatted text from a source user to all users on a channel
435  * including the sender (NOT for privmsg, notice etc!) */
436
437 void WriteChannel(chanrec* Ptr, userrec* user, char* text, ...)
438 {
439         char textbuffer[MAXBUF];
440         va_list argsPtr;
441         CUList *ulist;
442
443         if ((!Ptr) || (!user) || (!text))
444         {
445                 log(DEFAULT,"*** BUG *** WriteChannel was given an invalid parameter");
446                 return;
447         }
448
449         va_start(argsPtr, text);
450         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
451         va_end(argsPtr);
452
453         ulist = Ptr->GetUsers();
454
455         for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
456         {
457                 if (i->second->fd != FD_MAGIC_NUMBER)
458                         WriteTo_NoFormat(user,i->second,textbuffer);
459         }
460 }
461
462 void WriteChannel_NoFormat(chanrec* Ptr, userrec* user, const char* text)
463 {
464         CUList *ulist;
465
466         if ((!Ptr) || (!user) || (!text))
467         {
468                 log(DEFAULT,"*** BUG *** WriteChannel was given an invalid parameter");
469                 return;
470         }
471
472         ulist = Ptr->GetUsers();
473
474         for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
475         {
476                 if (i->second->fd != FD_MAGIC_NUMBER)
477                         WriteTo_NoFormat(user,i->second,text);
478         }
479 }
480
481
482 /* write formatted text from a source user to all users on a channel
483  * including the sender (NOT for privmsg, notice etc!) doesnt send to
484  * users on remote servers */
485
486 void WriteChannelLocal(chanrec* Ptr, userrec* user, char* text, ...)
487 {
488         char textbuffer[MAXBUF];
489         va_list argsPtr;
490         CUList *ulist;
491
492         if ((!Ptr) || (!text))
493         {
494                 log(DEFAULT,"*** BUG *** WriteChannel was given an invalid parameter");
495                 return;
496         }
497
498         va_start(argsPtr, text);
499         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
500         va_end(argsPtr);
501
502         ulist = Ptr->GetUsers();
503
504         for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
505         {
506                 if ((i->second->fd != FD_MAGIC_NUMBER) && (i->second != user))
507                 {
508                         if (!user)
509                         {
510                                 WriteServ_NoFormat(i->second->fd,textbuffer);
511                         }
512                         else
513                         {
514                                 WriteTo_NoFormat(user,i->second,textbuffer);
515                         }
516                 }
517         }
518 }
519
520 void WriteChannelLocal_NoFormat(chanrec* Ptr, userrec* user, const char* text)
521 {
522         CUList *ulist;
523
524         if ((!Ptr) || (!text))
525         {
526                 log(DEFAULT,"*** BUG *** WriteChannel was given an invalid parameter");
527                 return;
528         }
529
530         ulist = Ptr->GetUsers();
531
532         for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
533         {
534                 if ((i->second->fd != FD_MAGIC_NUMBER) && (i->second != user))
535                 {
536                         if (!user)
537                         {
538                                 WriteServ_NoFormat(i->second->fd,text);
539                         }
540                         else
541                         {
542                                 WriteTo_NoFormat(user,i->second,text);
543                         }
544                 }
545         }
546 }
547
548
549
550 void WriteChannelWithServ(const char* ServName, chanrec* Ptr, const char* text, ...)
551 {
552         char textbuffer[MAXBUF];
553         va_list argsPtr;
554         CUList *ulist;
555
556         if ((!Ptr) || (!text))
557         {
558                 log(DEFAULT,"*** BUG *** WriteChannelWithServ was given an invalid parameter");
559                 return;
560         }
561
562         va_start(argsPtr, text);
563         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
564         va_end(argsPtr);
565
566         ulist = Ptr->GetUsers();
567
568         for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
569         {
570                 if (IS_LOCAL(i->second))
571                         WriteServ_NoFormat(i->second->fd,textbuffer);
572         }
573 }
574
575 void WriteChannelWithServ_NoFormat(const char* ServName, chanrec* Ptr, const char* text)
576 {
577         CUList *ulist;
578
579         if ((!Ptr) || (!text))
580         {
581                 log(DEFAULT,"*** BUG *** WriteChannelWithServ was given an invalid parameter");
582                 return;
583         }
584
585         ulist = Ptr->GetUsers();
586
587         for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
588         {
589                 if (IS_LOCAL(i->second))
590                         WriteServ_NoFormat(i->second->fd,text);
591         }
592 }
593
594
595
596 /* write formatted text from a source user to all users on a channel except
597  * for the sender (for privmsg etc) */
598
599 void ChanExceptSender(chanrec* Ptr, userrec* user, char status, char* text, ...)
600 {
601         char textbuffer[MAXBUF];
602         va_list argsPtr;
603         CUList *ulist;
604
605         if ((!Ptr) || (!user) || (!text))
606         {
607                 log(DEFAULT,"*** BUG *** ChanExceptSender was given an invalid parameter");
608                 return;
609         }
610
611         va_start(argsPtr, text);
612         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
613         va_end(argsPtr);
614
615         switch (status)
616         {
617                 case '@':
618                         ulist = Ptr->GetOppedUsers();
619                         break;
620                 case '%':
621                         ulist = Ptr->GetHalfoppedUsers();
622                         break;
623                 case '+':
624                         ulist = Ptr->GetVoicedUsers();
625                         break;
626                 default:
627                         ulist = Ptr->GetUsers();
628                         break;
629         }
630
631         log(DEBUG,"%d users to write to",ulist->size());
632
633         for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
634         {
635                 if ((IS_LOCAL(i->second)) && (user != i->second))
636                         WriteFrom_NoFormat(i->second->fd,user,textbuffer);
637         }
638 }
639
640 void ChanExceptSender_NoFormat(chanrec* Ptr, userrec* user, char status, const char* text)
641 {
642         CUList *ulist;
643
644         if ((!Ptr) || (!user) || (!text))
645         {
646                 log(DEFAULT,"*** BUG *** ChanExceptSender was given an invalid parameter");
647                 return;
648         }
649
650         switch (status)
651         {
652                 case '@':
653                         ulist = Ptr->GetOppedUsers();
654                         break;  
655                 case '%':
656                         ulist = Ptr->GetHalfoppedUsers();
657                         break;
658                 case '+':
659                         ulist = Ptr->GetVoicedUsers();
660                         break;
661                 default:
662                         ulist = Ptr->GetUsers();
663                         break;
664         }
665
666         for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
667         {
668                 if ((IS_LOCAL(i->second)) && (user != i->second))
669                         WriteFrom_NoFormat(i->second->fd,user,text);
670         }
671 }
672
673 std::string GetServerDescription(const char* servername)
674 {
675         std::string description = "";
676
677         FOREACH_MOD(I_OnGetServerDescription,OnGetServerDescription(servername,description));
678
679         if (description != "")
680         {
681                 return description;
682         }
683         else
684         {
685                 // not a remote server that can be found, it must be me.
686                 return Config->ServerDesc;
687         }
688 }
689
690 /* write a formatted string to all users who share at least one common
691  * channel, including the source user e.g. for use in NICK */
692
693 void WriteCommon(userrec *u, char* text, ...)
694 {
695         char textbuffer[MAXBUF];
696         va_list argsPtr;
697         bool sent_to_at_least_one = false;
698
699         if (!u)
700         {
701                 log(DEFAULT,"*** BUG *** WriteCommon was given an invalid parameter");
702                 return;
703         }
704
705         if (u->registered != 7)
706         {
707                 log(DEFAULT,"*** BUG *** WriteCommon on an unregistered user");
708                 return;
709         }
710
711         va_start(argsPtr, text);
712         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
713         va_end(argsPtr);
714
715         // FIX: Stops a message going to the same person more than once
716         memset(&already_sent,0,MAX_DESCRIPTORS);
717
718         for (std::vector<ucrec*>::const_iterator v = u->chans.begin(); v != u->chans.end(); v++)
719         {
720                 if (((ucrec*)(*v))->channel)
721                 {
722                         CUList *ulist= ((ucrec*)(*v))->channel->GetUsers();
723
724                         for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
725                         {
726                                 if ((i->second->fd > -1) && (!already_sent[i->second->fd]))
727                                 {
728                                         already_sent[i->second->fd] = 1;
729                                         WriteFrom_NoFormat(i->second->fd,u,textbuffer);
730                                         sent_to_at_least_one = true;
731                                 }
732                         }
733                 }
734         }
735
736         /*
737          * if the user was not in any channels, no users will receive the text. Make sure the user
738          * receives their OWN message for WriteCommon
739          */
740         if (!sent_to_at_least_one)
741         {
742                 WriteFrom_NoFormat(u->fd,u,textbuffer);
743         }
744 }
745
746 void WriteCommon_NoFormat(userrec *u, const char* text)
747 {
748         bool sent_to_at_least_one = false;
749
750         if (!u)
751         {
752                 log(DEFAULT,"*** BUG *** WriteCommon was given an invalid parameter");
753                 return;
754         }
755
756         if (u->registered != 7)
757         {
758                 log(DEFAULT,"*** BUG *** WriteCommon on an unregistered user");
759                 return;
760         }
761
762         // FIX: Stops a message going to the same person more than once
763         memset(&already_sent,0,MAX_DESCRIPTORS);
764
765         for (std::vector<ucrec*>::const_iterator v = u->chans.begin(); v != u->chans.end(); v++)
766         {
767                 if (((ucrec*)(*v))->channel)
768                 {
769                         CUList *ulist= ((ucrec*)(*v))->channel->GetUsers();
770
771                         for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
772                         {
773                                 if ((i->second->fd > -1) && (!already_sent[i->second->fd]))
774                                 {
775                                         already_sent[i->second->fd] = 1;
776                                         WriteFrom_NoFormat(i->second->fd,u,text);
777                                         sent_to_at_least_one = true;
778                                 }
779                         }
780                 }
781         }
782
783         /*
784          * if the user was not in any channels, no users will receive the text. Make sure the user
785          * receives their OWN message for WriteCommon
786          */
787         if (!sent_to_at_least_one)
788         {
789                 WriteFrom_NoFormat(u->fd,u,text);
790         }
791 }
792
793
794 /* write a formatted string to all users who share at least one common
795  * channel, NOT including the source user e.g. for use in QUIT
796  */
797
798 void WriteCommonExcept(userrec *u, char* text, ...)
799 {
800         char textbuffer[MAXBUF];
801         char oper_quit[MAXBUF];
802         bool quit_munge = false;
803         va_list argsPtr;
804         int total;
805
806         if (!u)
807         {
808                 log(DEFAULT,"*** BUG *** WriteCommon was given an invalid parameter");
809                 return;
810         }
811
812         if (u->registered != 7)
813         {
814                 log(DEFAULT,"*** BUG *** WriteCommon on an unregistered user");
815                 return;
816         }
817
818         va_start(argsPtr, text);
819         total = vsnprintf(textbuffer, MAXBUF, text, argsPtr);
820         va_end(argsPtr);
821
822         if ((Config->HideSplits) && (total > 6))
823         {
824                 /* Yeah yeah, this is ugly. But its fast, live with it. */
825                 char* check = textbuffer;
826
827                 if ((*check++ == 'Q') && (*check++ == 'U') && (*check++ == 'I') && (*check++ == 'T') && (*check++ == ' ') && (*check++ == ':'))
828                 {
829                         std::stringstream split(check);
830                         std::string server_one;
831                         std::string server_two;
832
833                         split >> server_one;
834                         split >> server_two;
835
836                         if ((FindServerName(server_one)) && (FindServerName(server_two)))
837                         {
838                                 strlcpy(oper_quit,textbuffer,MAXQUIT);
839                                 strlcpy(check,"*.net *.split",MAXQUIT);
840                                 quit_munge = true;
841                         }
842                 }
843         }
844
845         if ((Config->HideBans) && (total > 13) && (!quit_munge))
846         {
847                 char* check = textbuffer;
848
849                 /* XXX - as above */
850                 if ((*check++ == 'Q') && (*check++ == 'U') && (*check++ == 'I') && (*check++ == 'T') && (*check++ == ' ') && (*check++ == ':'))
851                 {
852                         check++;
853
854                         if ((*check++ == '-') && (*check++ == 'L') && (*check++ == 'i') && (*check++ == 'n') && (*check++ == 'e') && (*check++ == 'd') && (*check++ == ':'))
855                         {
856                                 strlcpy(oper_quit,textbuffer,MAXQUIT);
857                                 *(--check) = 0;         // We don't need to strlcpy, we just chop it from the :
858                                 quit_munge = true;
859                         }
860                 }
861         }
862
863         memset(&already_sent,0,MAX_DESCRIPTORS);
864
865         for (std::vector<ucrec*>::const_iterator v = u->chans.begin(); v != u->chans.end(); v++)
866         {
867                 if (((ucrec*)(*v))->channel)
868                 {
869                         CUList *ulist= ((ucrec*)(*v))->channel->GetUsers();
870
871                         for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
872                         {
873                                 if (u != i->second)
874                                 {
875                                         if ((i->second->fd > -1) && (!already_sent[i->second->fd]))
876                                         {
877                                                 already_sent[i->second->fd] = 1;
878
879                                                 if (quit_munge)
880                                                 {
881                                                         WriteFrom_NoFormat(i->second->fd,u,*i->second->oper ? oper_quit : textbuffer);
882                                                 }
883                                                 else
884                                                         WriteFrom_NoFormat(i->second->fd,u,textbuffer);
885                                         }
886                                 }
887                         }
888                 }
889         }
890 }
891
892 void WriteCommonExcept_NoFormat(userrec *u, const char* text)
893 {
894         if (!u)
895         {
896                 log(DEFAULT,"*** BUG *** WriteCommon was given an invalid parameter");
897                 return;
898         }
899  
900         if (u->registered != 7)
901         {
902                 log(DEFAULT,"*** BUG *** WriteCommon on an unregistered user");
903                 return;
904         }
905
906         memset(&already_sent,0,MAX_DESCRIPTORS);
907
908         for (std::vector<ucrec*>::const_iterator v = u->chans.begin(); v != u->chans.end(); v++)
909         {
910                 if (((ucrec*)(*v))->channel)
911                 {
912                         CUList *ulist= ((ucrec*)(*v))->channel->GetUsers();
913
914                         for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
915                         {
916                                 if (u != i->second)
917                                 {
918                                         if ((i->second->fd > -1) && (!already_sent[i->second->fd]))
919                                         {
920                                                 already_sent[i->second->fd] = 1;
921                                                 WriteFrom_NoFormat(i->second->fd,u,text);
922                                         }
923                                 }
924                         }
925                 }
926         }
927 }
928
929
930 /* XXX - We don't use WriteMode for this because WriteMode is very slow and
931  * this isnt. Basically WriteMode has to iterate ALL the users 'n' times for
932  * the number of modes provided, e.g. if you send WriteMode 'og' to write to
933  * opers with globops, and you have 2000 users, thats 4000 iterations. WriteOpers
934  * uses the oper list, which means if you have 2000 users but only 5 opers,
935  * it iterates 5 times.
936  */
937 void WriteOpers(const char* text, ...)
938 {
939         char textbuffer[MAXBUF];
940         va_list argsPtr;
941
942         if (!text)
943         {
944                 log(DEFAULT,"*** BUG *** WriteOpers was given an invalid parameter");
945                 return;
946         }
947
948         va_start(argsPtr, text);
949         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
950         va_end(argsPtr);
951
952         WriteOpers_NoFormat(textbuffer);
953 }
954
955 void WriteOpers_NoFormat(const char* text)
956 {
957         if (!text)
958         {
959                 log(DEFAULT,"*** BUG *** WriteOpers_NoFormat was given an invalid parameter");
960                 return;
961         }
962
963         for (std::vector<userrec*>::iterator i = all_opers.begin(); i != all_opers.end(); i++)
964         {
965                 userrec* a = *i;
966
967                 if (IS_LOCAL(a))
968                 {
969                         if (a->modes[UM_SERVERNOTICE])
970                         {
971                                 // send server notices to all with +s
972                                 WriteServ(a->fd,"NOTICE %s :%s",a->nick,text);
973                         }
974                 }
975         }
976 }
977
978 void ServerNoticeAll(char* text, ...)
979 {
980         if (!text)
981                 return;
982
983         char textbuffer[MAXBUF];
984         char formatbuffer[MAXBUF];
985         va_list argsPtr;
986         va_start (argsPtr, text);
987         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
988         va_end(argsPtr);
989
990         snprintf(formatbuffer,MAXBUF,"NOTICE $%s :%s",Config->ServerName,textbuffer);
991
992         for (std::vector<userrec*>::const_iterator i = local_users.begin(); i != local_users.end(); i++)
993         {
994                 userrec* t = (userrec*)(*i);
995                 WriteServ_NoFormat(t->fd,formatbuffer);
996         }
997 }
998
999 void ServerPrivmsgAll(char* text, ...)
1000 {
1001         if (!text)
1002                 return;
1003
1004         char textbuffer[MAXBUF];
1005         char formatbuffer[MAXBUF];
1006         va_list argsPtr;
1007         va_start (argsPtr, text);
1008         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1009         va_end(argsPtr);
1010
1011         snprintf(formatbuffer,MAXBUF,"PRIVMSG $%s :%s",Config->ServerName,textbuffer);
1012
1013         for (std::vector<userrec*>::const_iterator i = local_users.begin(); i != local_users.end(); i++)
1014         {
1015                 userrec* t = (userrec*)(*i);
1016                 WriteServ_NoFormat(t->fd,formatbuffer);
1017         }
1018 }
1019
1020 void WriteMode(const char* modes, int flags, const char* text, ...)
1021 {
1022         char textbuffer[MAXBUF];
1023         int modelen;
1024         va_list argsPtr;
1025
1026         if ((!text) || (!modes) || (!flags))
1027         {
1028                 log(DEFAULT,"*** BUG *** WriteMode was given an invalid parameter");
1029                 return;
1030         }
1031
1032         va_start(argsPtr, text);
1033         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1034         va_end(argsPtr);
1035         modelen = strlen(modes);
1036
1037         for (std::vector<userrec*>::const_iterator i = local_users.begin(); i != local_users.end(); i++)
1038         {
1039                 userrec* t = (userrec*)(*i);
1040                 bool send_to_user = false;
1041
1042                 if (flags == WM_AND)
1043                 {
1044                         send_to_user = true;
1045
1046                         for (int n = 0; n < modelen; n++)
1047                         {
1048                                 if (!t->modes[modes[n]-65])
1049                                 {
1050                                         send_to_user = false;
1051                                         break;
1052                                 }
1053                         }
1054                 }
1055                 else if (flags == WM_OR)
1056                 {
1057                         send_to_user = false;
1058
1059                         for (int n = 0; n < modelen; n++)
1060                         {
1061                                 if (t->modes[modes[n]-65])
1062                                 {
1063                                         send_to_user = true;
1064                                         break;
1065                                 }
1066                         }
1067                 }
1068
1069                 if (send_to_user)
1070                 {
1071                         WriteServ(t->fd,"NOTICE %s :%s",t->nick,textbuffer);
1072                 }
1073         }
1074 }
1075
1076 void NoticeAll(userrec *source, bool local_only, char* text, ...)
1077 {
1078         char textbuffer[MAXBUF];
1079         char formatbuffer[MAXBUF];
1080         va_list argsPtr;
1081
1082         if ((!text) || (!source))
1083         {
1084                 log(DEFAULT,"*** BUG *** NoticeAll was given an invalid parameter");
1085                 return;
1086         }
1087
1088         va_start(argsPtr, text);
1089         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1090         va_end(argsPtr);
1091
1092         snprintf(formatbuffer,MAXBUF,"NOTICE $* :%s",textbuffer);
1093
1094         for (std::vector<userrec*>::const_iterator i = local_users.begin(); i != local_users.end(); i++)
1095         {
1096                 userrec* t = (userrec*)(*i);
1097                 WriteFrom_NoFormat(t->fd,source,formatbuffer);
1098         }
1099 }
1100
1101
1102 void WriteWallOps(userrec *source, bool local_only, char* text, ...)
1103 {
1104         char textbuffer[MAXBUF];
1105         char formatbuffer[MAXBUF];
1106         va_list argsPtr;
1107
1108         if ((!text) || (!source))
1109         {
1110                 log(DEFAULT,"*** BUG *** WriteOpers was given an invalid parameter");
1111                 return;
1112         }
1113
1114         va_start(argsPtr, text);
1115         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1116         va_end(argsPtr);
1117
1118         snprintf(formatbuffer,MAXBUF,"WALLOPS :%s",textbuffer);
1119
1120         for (std::vector<userrec*>::const_iterator i = local_users.begin(); i != local_users.end(); i++)
1121         {
1122                 userrec* t = (userrec*)(*i);
1123
1124                 if ((IS_LOCAL(t)) && (t->modes[UM_WALLOPS]))
1125                 {
1126                         WriteTo_NoFormat(source,t,formatbuffer);
1127                 }
1128         }
1129 }
1130
1131 /* convert a string to lowercase. Note following special circumstances
1132  * taken from RFC 1459. Many "official" server branches still hold to this
1133  * rule so i will too;
1134  *
1135  *  Because of IRC's scandanavian origin, the characters {}| are
1136  *  considered to be the lower case equivalents of the characters []\,
1137  *  respectively. This is a critical issue when determining the
1138  *  equivalence of two nicknames.
1139  */
1140 void strlower(char *n)
1141 {
1142         if (n)
1143         {
1144                 for (char* t = n; *t; t++)
1145                         *t = lowermap[(unsigned char)*t];
1146         }
1147 }
1148
1149 /* Find a user record by nickname and return a pointer to it */
1150
1151 userrec* Find(const std::string &nick)
1152 {
1153         user_hash::iterator iter = clientlist.find(nick);
1154
1155         if (iter == clientlist.end())
1156                 /* Couldn't find it */
1157                 return NULL;
1158
1159         return iter->second;
1160 }
1161
1162 userrec* Find(const char* nick)
1163 {
1164         user_hash::iterator iter;
1165
1166         if (!nick)
1167                 return NULL;
1168
1169         iter = clientlist.find(nick);
1170         
1171         if (iter == clientlist.end())
1172                 return NULL;
1173
1174         return iter->second;
1175 }
1176
1177 /* find a channel record by channel name and return a pointer to it */
1178
1179 chanrec* FindChan(const char* chan)
1180 {
1181         chan_hash::iterator iter;
1182
1183         if (!chan)
1184         {
1185                 log(DEFAULT,"*** BUG *** Findchan was given an invalid parameter");
1186                 return NULL;
1187         }
1188
1189         iter = chanlist.find(chan);
1190
1191         if (iter == chanlist.end())
1192                 /* Couldn't find it */
1193                 return NULL;
1194
1195         return iter->second;
1196 }
1197
1198
1199 long GetMaxBans(char* name)
1200 {
1201         std::string x;
1202         for (std::map<std::string,int>::iterator n = Config->maxbans.begin(); n != Config->maxbans.end(); n++)
1203         {
1204                 x = n->first;
1205                 if (match(name,x.c_str()))
1206                 {
1207                         return n->second;
1208                 }
1209         }
1210         return 64;
1211 }
1212
1213 void purge_empty_chans(userrec* u)
1214 {
1215         std::vector<chanrec*> to_delete;
1216
1217         // firstly decrement the count on each channel
1218         for (std::vector<ucrec*>::iterator f = u->chans.begin(); f != u->chans.end(); f++)
1219         {
1220                 if (((ucrec*)(*f))->channel)
1221                 {
1222                         if (((ucrec*)(*f))->channel->DelUser(u) == 0)
1223                         {
1224                                 /* No users left in here, mark it for deletion */
1225                                 to_delete.push_back(((ucrec*)(*f))->channel);
1226                                 ((ucrec*)(*f))->channel = NULL;
1227                         }
1228                 }
1229         }
1230
1231         log(DEBUG,"purge_empty_chans: %d channels to delete",to_delete.size());
1232
1233         for (std::vector<chanrec*>::iterator n = to_delete.begin(); n != to_delete.end(); n++)
1234         {
1235                 chanrec* thischan = (chanrec*)*n;
1236                 chan_hash::iterator i2 = chanlist.find(thischan->name);
1237                 if (i2 != chanlist.end())
1238                 {
1239                         FOREACH_MOD(I_OnChannelDelete,OnChannelDelete(i2->second));
1240                         DELETE(i2->second);
1241                         chanlist.erase(i2);
1242                 }
1243         }
1244
1245         if (*u->oper)
1246                 DeleteOper(u);
1247 }
1248
1249
1250 char* chanmodes(chanrec *chan, bool showkey)
1251 {
1252         static char scratch[MAXBUF];
1253         static char sparam[MAXBUF];
1254         char* offset = scratch;
1255         std::string extparam = "";
1256
1257         if (!chan)
1258         {
1259                 log(DEFAULT,"*** BUG *** chanmodes was given an invalid parameter");
1260                 *scratch = '\0';
1261                 return scratch;
1262         }
1263
1264         *scratch = '\0';
1265         *sparam = '\0';
1266
1267         /* This was still iterating up to 190, chanrec::custom_modes is only 64 elements -- Om */
1268         for(int n = 0; n < 64; n++)
1269         {
1270                 if(chan->modes[n])
1271                 {
1272                         *offset++ = n+65;
1273                         extparam = "";
1274                         switch (n)
1275                         {
1276                                 case CM_KEY:
1277                                         extparam = (showkey ? chan->key : "<key>");
1278                                 break;
1279                                 case CM_LIMIT:
1280                                         extparam = ConvToStr(chan->limit);
1281                                 break;
1282                                 case CM_NOEXTERNAL:
1283                                 case CM_TOPICLOCK:
1284                                 case CM_INVITEONLY:
1285                                 case CM_MODERATED:
1286                                 case CM_SECRET:
1287                                 case CM_PRIVATE:
1288                                         /* We know these have no parameters */
1289                                 break;
1290                                 default:
1291                                         extparam = chan->GetModeParameter(n+65);
1292                                 break;
1293                         }
1294                         if (extparam != "")
1295                         {
1296                                 charlcat(sparam,' ',MAXBUF);
1297                                 strlcat(sparam,extparam.c_str(),MAXBUF);
1298                         }
1299                 }
1300         }
1301
1302         /* Null terminate scratch */
1303         *offset = '\0';
1304         strlcat(scratch,sparam,MAXBUF);
1305         return scratch;
1306 }
1307
1308
1309 /* compile a userlist of a channel into a string, each nick seperated by
1310  * spaces and op, voice etc status shown as @ and + */
1311
1312 void userlist(userrec *user,chanrec *c)
1313 {
1314         if ((!c) || (!user))
1315         {
1316                 log(DEFAULT,"*** BUG *** userlist was given an invalid parameter");
1317                 return;
1318         }
1319
1320         char list[MAXBUF];
1321         size_t dlen, curlen;
1322
1323         dlen = curlen = snprintf(list,MAXBUF,"353 %s = %s :", user->nick, c->name);
1324
1325         int numusers = 0;
1326         char* ptr = list + dlen;
1327
1328         CUList *ulist= c->GetUsers();
1329
1330         /* Improvement by Brain - this doesnt change in value, so why was it inside
1331          * the loop?
1332          */
1333         bool has_user = c->HasUser(user);
1334
1335         for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
1336         {
1337                 if ((!has_user) && (i->second->modes[UM_INVISIBLE]))
1338                 {
1339                         /*
1340                          * user is +i, and source not on the channel, does not show
1341                          * nick in NAMES list
1342                          */
1343                         continue;
1344                 }
1345
1346                 size_t ptrlen = snprintf(ptr, MAXBUF, "%s%s ", cmode(i->second, c), i->second->nick);
1347
1348                 curlen += ptrlen;
1349                 ptr += ptrlen;
1350
1351                 numusers++;
1352
1353                 if (curlen > (480-NICKMAX))
1354                 {
1355                         /* list overflowed into multiple numerics */
1356                         WriteServ_NoFormat(user->fd,list);
1357
1358                         /* reset our lengths */
1359                         dlen = curlen = snprintf(list,MAXBUF,"353 %s = %s :", user->nick, c->name);
1360                         ptr = list + dlen;
1361
1362                         ptrlen = 0;
1363                         numusers = 0;
1364                 }
1365         }
1366
1367         /* if whats left in the list isnt empty, send it */
1368         if (numusers)
1369         {
1370                 WriteServ_NoFormat(user->fd,list);
1371         }
1372 }
1373
1374 /*
1375  * return a count of the users on a specific channel accounting for
1376  * invisible users who won't increase the count. e.g. for /LIST
1377  */
1378 int usercount_i(chanrec *c)
1379 {
1380         int count = 0;
1381
1382         if (!c)
1383                 return 0;
1384
1385         CUList *ulist= c->GetUsers();
1386         for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
1387         {
1388                 if (!(i->second->modes[UM_INVISIBLE]))
1389                         count++;
1390         }
1391
1392         return count;
1393 }
1394
1395 int usercount(chanrec *c)
1396 {
1397         return (c ? c->GetUserCounter() : 0);
1398 }
1399
1400
1401 /* looks up a users password for their connection class (<ALLOW>/<DENY> tags)
1402  * NOTE: If the <ALLOW> or <DENY> tag specifies an ip, and this user resolves,
1403  * then their ip will be taken as 'priority' anyway, so for example,
1404  * <connect allow="127.0.0.1"> will match joe!bloggs@localhost
1405  */
1406 ConnectClass GetClass(userrec *user)
1407 {
1408         for (ClassVector::iterator i = Config->Classes.begin(); i != Config->Classes.end(); i++)
1409         {
1410                 if ((match(inet_ntoa(user->ip4),i->host.c_str())) || (match(user->host,i->host.c_str())))
1411                 {
1412                         return *i;
1413                 }
1414         }
1415
1416         return *(Config->Classes.begin());
1417 }
1418
1419 /*
1420  * sends out an error notice to all connected clients (not to be used
1421  * lightly!)
1422  */
1423 void send_error(char *s)
1424 {
1425         log(DEBUG,"send_error: %s",s);
1426
1427         for (std::vector<userrec*>::const_iterator i = local_users.begin(); i != local_users.end(); i++)
1428         {
1429                 userrec* t = (userrec*)(*i);
1430                 if (t->registered == 7)
1431                 {
1432                         WriteServ(t->fd,"NOTICE %s :%s",t->nick,s);
1433                 }
1434                 else
1435                 {
1436                         // fix - unregistered connections receive ERROR, not NOTICE
1437                         Write(t->fd,"ERROR :%s",s);
1438                 }
1439         }
1440 }
1441
1442 void Error(int status)
1443 {
1444         void *array[300];
1445         size_t size;
1446         char **strings;
1447
1448         signal(SIGALRM, SIG_IGN);
1449         signal(SIGPIPE, SIG_IGN);
1450         signal(SIGTERM, SIG_IGN);
1451         signal(SIGABRT, SIG_IGN);
1452         signal(SIGSEGV, SIG_IGN);
1453         signal(SIGURG, SIG_IGN);
1454         signal(SIGKILL, SIG_IGN);
1455         log(DEFAULT,"*** fell down a pothole in the road to perfection ***");
1456 #ifdef HAS_EXECINFO
1457         log(DEFAULT,"Please report the backtrace lines shown below with any bugreport to the bugtracker at http://www.inspircd.org/bugtrack/");
1458         size = backtrace(array, 30);
1459         strings = backtrace_symbols(array, size);
1460         for (size_t i = 0; i < size; i++) {
1461                 log(DEFAULT,"[%d] %s", i, strings[i]);
1462         }
1463         free(strings);
1464         WriteOpers("*** SIGSEGV: Please see the ircd.log for backtrace and report the error to http://www.inspircd.org/bugtrack/");
1465 #else
1466         log(DEFAULT,"You do not have execinfo.h so i could not backtrace -- on FreeBSD, please install the libexecinfo port.");
1467 #endif
1468         send_error("Somebody screwed up... Whoops. IRC Server terminating.");
1469         signal(SIGSEGV, SIG_DFL);
1470         if (raise(SIGSEGV) == -1)
1471         {
1472                 log(DEFAULT,"What the hell, i couldnt re-raise SIGSEGV! Error: %s",strerror(errno));
1473         }
1474         Exit(status);
1475 }
1476
1477 // this function counts all users connected, wether they are registered or NOT.
1478 int usercnt(void)
1479 {
1480         return clientlist.size();
1481 }
1482
1483 // this counts only registered users, so that the percentages in /MAP don't mess up when users are sitting in an unregistered state
1484 int registered_usercount(void)
1485 {
1486         int c = 0;
1487
1488         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1489         {
1490                 if (i->second->registered == 7) c++;
1491         }
1492
1493         return c;
1494 }
1495
1496 int usercount_invisible(void)
1497 {
1498         int c = 0;
1499
1500         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1501         {
1502                 if ((i->second->registered == 7) && (i->second->modes[UM_INVISIBLE]))
1503                         c++;
1504         }
1505
1506         return c;
1507 }
1508
1509 int usercount_opers(void)
1510 {
1511         int c = 0;
1512
1513         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1514         {
1515                 if (*(i->second->oper))
1516                         c++;
1517         }
1518         return c;
1519 }
1520
1521 int usercount_unknown(void)
1522 {
1523         int c = 0;
1524
1525         for (std::vector<userrec*>::const_iterator i = local_users.begin(); i != local_users.end(); i++)
1526         {
1527                 userrec* t = (userrec*)(*i);
1528                 if (t->registered != 7)
1529                         c++;
1530         }
1531
1532         return c;
1533 }
1534
1535 long chancount(void)
1536 {
1537         return chanlist.size();
1538 }
1539
1540 long local_count()
1541 {
1542         int c = 0;
1543
1544         for (std::vector<userrec*>::const_iterator i = local_users.begin(); i != local_users.end(); i++)
1545         {
1546                 userrec* t = (userrec*)(*i);
1547                 if (t->registered == 7)
1548                         c++;
1549         }
1550
1551         return c;
1552 }
1553
1554 void ShowMOTD(userrec *user)
1555 {
1556         static char mbuf[MAXBUF];
1557         static char crud[MAXBUF];
1558         std::string WholeMOTD = "";
1559
1560         if (!Config->MOTD.size())
1561         {
1562                 WriteServ(user->fd,"422 %s :Message of the day file is missing.",user->nick);
1563                 return;
1564         }
1565
1566         snprintf(crud,MAXBUF,":%s 372 %s :- ", Config->ServerName, user->nick);
1567         snprintf(mbuf,MAXBUF,":%s 375 %s :- %s message of the day\r\n", Config->ServerName, user->nick, Config->ServerName);
1568         WholeMOTD = WholeMOTD + mbuf;
1569
1570         for (unsigned int i = 0; i < Config->MOTD.size(); i++)
1571                 WholeMOTD = WholeMOTD + std::string(crud) + Config->MOTD[i].c_str() + std::string("\r\n");
1572
1573         snprintf(mbuf,MAXBUF,":%s 376 %s :End of message of the day.\r\n", Config->ServerName, user->nick);
1574         WholeMOTD = WholeMOTD + mbuf;
1575
1576         // only one write operation
1577         if (Config->GetIOHook(user->port))
1578         {
1579                 try
1580                 {
1581                         Config->GetIOHook(user->port)->OnRawSocketWrite(user->fd,(char*)WholeMOTD.c_str(),WholeMOTD.length());
1582                 }
1583                 catch (ModuleException& modexcept)
1584                 {
1585                         log(DEBUG,"Module exception caught: %s",modexcept.GetReason());
1586                 }
1587         }
1588         else
1589         {
1590                 user->AddWriteBuf(WholeMOTD);
1591         }
1592
1593         ServerInstance->stats->statsSent += WholeMOTD.length();
1594 }
1595
1596 void ShowRULES(userrec *user)
1597 {
1598         if (!Config->RULES.size())
1599         {
1600                 WriteServ(user->fd,"NOTICE %s :Rules file is missing.",user->nick);
1601                 return;
1602         }
1603         WriteServ(user->fd,"NOTICE %s :%s rules",user->nick,Config->ServerName);
1604
1605         for (unsigned int i = 0; i < Config->RULES.size(); i++)
1606                 WriteServ(user->fd,"NOTICE %s :%s",user->nick,Config->RULES[i].c_str());
1607
1608         WriteServ(user->fd,"NOTICE %s :End of %s rules.",user->nick,Config->ServerName);
1609 }
1610
1611 // this returns 1 when all modules are satisfied that the user should be allowed onto the irc server
1612 // (until this returns true, a user will block in the waiting state, waiting to connect up to the
1613 // registration timeout maximum seconds)
1614 bool AllModulesReportReady(userrec* user)
1615 {
1616         if (!Config->global_implementation[I_OnCheckReady])
1617                 return true;
1618
1619         for (int i = 0; i <= MODCOUNT; i++)
1620         {
1621                 if (Config->implement_lists[i][I_OnCheckReady])
1622                 {
1623                         int res = modules[i]->OnCheckReady(user);
1624                         if (!res)
1625                                 return false;
1626                 }
1627         }
1628
1629         return true;
1630 }
1631
1632 /* Make Sure Modules Are Avaliable!
1633  * (BugFix By Craig.. See? I do work! :p)
1634  * Modified by brain, requires const char*
1635  * to work with other API functions
1636  */
1637
1638 /* XXX - Needed? */
1639 bool FileExists (const char* file)
1640 {
1641         FILE *input;
1642         if ((input = fopen (file, "r")) == NULL)
1643         {
1644                 return(false);
1645         }
1646         else
1647         {
1648                 fclose (input);
1649                 return(true);
1650         }
1651 }
1652
1653 char* CleanFilename(char* name)
1654 {
1655         char* p = name + strlen(name);
1656         while ((p != name) && (*p != '/')) p--;
1657         return (p != name ? ++p : p);
1658 }
1659
1660 bool DirValid(char* dirandfile)
1661 {
1662         char work[MAXBUF];
1663         char buffer[MAXBUF];
1664         char otherdir[MAXBUF];
1665         int p;
1666
1667         strlcpy(work, dirandfile, MAXBUF);
1668         p = strlen(work);
1669
1670         // we just want the dir
1671         while (*work)
1672         {
1673                 if (work[p] == '/')
1674                 {
1675                         work[p] = '\0';
1676                         break;
1677                 }
1678
1679                 work[p--] = '\0';
1680         }
1681
1682         // Get the current working directory
1683         if (getcwd(buffer, MAXBUF ) == NULL )
1684                 return false;
1685
1686         chdir(work);
1687
1688         if (getcwd(otherdir, MAXBUF ) == NULL )
1689                 return false;
1690
1691         chdir(buffer);
1692
1693         size_t t = strlen(work);
1694
1695         if (strlen(otherdir) >= t)
1696         {
1697                 otherdir[t] = '\0';
1698
1699                 if (!strcmp(otherdir,work))
1700                 {
1701                         return true;
1702                 }
1703
1704                 return false;
1705         }
1706         else
1707         {
1708                 return false;
1709         }
1710 }
1711
1712 std::string GetFullProgDir(char** argv, int argc)
1713 {
1714         char work[MAXBUF];
1715         char buffer[MAXBUF];
1716         char otherdir[MAXBUF];
1717         int p;
1718
1719         strlcpy(work,argv[0],MAXBUF);
1720         p = strlen(work);
1721
1722         // we just want the dir
1723         while (*work)
1724         {
1725                 if (work[p] == '/')
1726                 {
1727                         work[p] = '\0';
1728                         break;
1729                 }
1730
1731                 work[p--] = '\0';
1732         }
1733
1734         // Get the current working directory
1735         if (getcwd(buffer, MAXBUF) == NULL)
1736                 return "";
1737
1738         chdir(work);
1739
1740         if (getcwd(otherdir, MAXBUF) == NULL)
1741                 return "";
1742
1743         chdir(buffer);
1744         return otherdir;
1745 }
1746
1747 int InsertMode(std::string &output, const char* mode, unsigned short section)
1748 {
1749         unsigned short currsection = 1;
1750         unsigned int pos = output.find("CHANMODES=", 0) + 10; // +10 for the length of "CHANMODES="
1751         
1752         if(section > 4 || section == 0)
1753         {
1754                 log(DEBUG, "InsertMode: CHANMODES doesn't have a section %dh :/", section);
1755                 return 0;
1756         }
1757         
1758         for(; pos < output.size(); pos++)
1759         {
1760                 if(section == currsection)
1761                         break;
1762                         
1763                 if(output[pos] == ',')
1764                         currsection++;
1765         }
1766         
1767         output.insert(pos, mode);
1768         return 1;
1769 }
1770
1771 bool IsValidChannelName(const char *chname)
1772 {
1773         char *c;
1774
1775         /* check for no name - don't check for !*chname, as if it is empty, it won't be '#'! */
1776         if (!chname || *chname != '#')
1777         {
1778                 return false;
1779         }
1780
1781         c = (char *)chname + 1;
1782         while (*c)
1783         {
1784                 switch (*c)
1785                 {
1786                         case ' ':
1787                         case ',':
1788                         case 7:
1789                                 return false;
1790                 }
1791
1792                 c++;
1793         }
1794                 
1795         /* too long a name - note funky pointer arithmetic here. */
1796         if ((c - chname) > CHANMAX)
1797         {
1798                         return false;
1799         }
1800
1801         return true;
1802 }
1803
1804 inline int charlcat(char* x,char y,int z)
1805 {
1806         char* x__n = x;
1807         int v = 0;
1808
1809         while(*x__n++)
1810                 v++;
1811
1812         if (v < z - 1)
1813         {
1814                 *--x__n = y;
1815                 *++x__n = 0;
1816         }
1817
1818         return v;
1819 }
1820
1821 bool charremove(char* mp, char remove)
1822 {
1823         char* mptr = mp;
1824         bool shift_down = false;
1825
1826         while (*mptr)
1827         {
1828                 if (*mptr == remove)
1829                 shift_down = true;
1830
1831                 if (shift_down)
1832                         *mptr = *(mptr+1);
1833
1834                 mptr++;
1835         }
1836
1837         return shift_down;
1838 }
1839
1840 void OpenLog(char** argv, int argc)
1841 {
1842         if (!*LOG_FILE)
1843         {
1844                 if (Config->logpath == "")
1845                 {
1846                         Config->logpath = GetFullProgDir(argv,argc) + "/ircd.log";
1847                 }
1848         }
1849         else
1850         {
1851                 Config->log_file = fopen(LOG_FILE,"a+");
1852
1853                 if (!Config->log_file)
1854                 {
1855                         printf("ERROR: Could not write to logfile %s, bailing!\n\n",Config->logpath.c_str());
1856                         Exit(ERROR);
1857                 }
1858                 
1859                 return;
1860         }
1861
1862         Config->log_file = fopen(Config->logpath.c_str(),"a+");
1863
1864         if (!Config->log_file)
1865         {
1866                 printf("ERROR: Could not write to logfile %s, bailing!\n\n",Config->logpath.c_str());
1867                 Exit(ERROR);
1868         }
1869 }
1870
1871 void CheckRoot()
1872 {
1873         if (geteuid() == 0)
1874         {
1875                 printf("WARNING!!! You are running an irc server as ROOT!!! DO NOT DO THIS!!!\n\n");
1876                 log(DEFAULT,"InspIRCd: startup: not starting with UID 0!");
1877                 Exit(ERROR);
1878         }
1879 }
1880
1881 void CheckDie()
1882 {
1883         if (*Config->DieValue)
1884         {
1885                 printf("WARNING: %s\n\n",Config->DieValue);
1886                 log(DEFAULT,"Uh-Oh, somebody didn't read their config file: '%s'",Config->DieValue);
1887                 Exit(ERROR);
1888         }
1889 }
1890
1891 /* We must load the modules AFTER initializing the socket engine, now */
1892 void LoadAllModules(InspIRCd* ServerInstance)
1893 {
1894         char configToken[MAXBUF];
1895         Config->module_names.clear();
1896         MODCOUNT = -1;
1897
1898         for (int count = 0; count < Config->ConfValueEnum(Config->config_data, "module"); count++)
1899         {
1900                 Config->ConfValue(Config->config_data, "module","name",count,configToken,MAXBUF);
1901                 printf("[\033[1;32m*\033[0m] Loading module:\t\033[1;32m%s\033[0m\n",configToken);
1902                 
1903                 if (!ServerInstance->LoadModule(configToken))                
1904                 {
1905                         log(DEFAULT,"Exiting due to a module loader error.");
1906                         printf("\nThere was an error loading a module: %s\n\n",ServerInstance->ModuleError());
1907                         Exit(0);
1908                 }
1909         }
1910         
1911         log(DEFAULT,"Total loaded modules: %lu",(unsigned long)MODCOUNT+1);
1912 }