]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/helperfuncs.cpp
Added proper administrativia notices to CONNECT and inbound connections
[user/henk/code/inspircd.git] / src / helperfuncs.cpp
1 /*       +------------------------------------+
2  *       | Inspire Internet Relay Chat Daemon |
3  *       +------------------------------------+
4  *
5  *  Inspire is copyright (C) 2002-2004 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 using namespace std;
18
19 #include "inspircd_config.h"
20 #include "inspircd.h"
21 #include "inspircd_io.h"
22 #include "inspircd_util.h"
23 #include <unistd.h>
24 #include <fcntl.h>
25 #include <sys/errno.h>
26 #include <time.h>
27 #include <string>
28 #ifdef GCC3
29 #include <ext/hash_map>
30 #else
31 #include <hash_map>
32 #endif
33 #include <sstream>
34 #include <vector>
35 #include <deque>
36 #include <stdarg.h>
37 #include "connection.h"
38 #include "users.h"
39 #include "ctables.h"
40 #include "globals.h"
41 #include "modules.h"
42 #include "dynamic.h"
43 #include "wildcard.h"
44 #include "message.h"
45 #include "mode.h"
46 #include "xline.h"
47 #include "commands.h"
48 #include "inspstring.h"
49 #include "helperfuncs.h"
50 #include "hashcomp.h"
51
52 extern int MODCOUNT;
53 extern std::vector<Module*> modules;
54
55 extern time_t TIME;
56 extern bool nofork;
57 extern char lowermap[255];
58 extern char ServerName[MAXBUF];
59 extern char Network[MAXBUF];
60 extern char ServerDesc[MAXBUF];
61 extern char list[MAXBUF];
62
63 extern int debugging;
64 extern int LogLevel;
65
66 extern std::stringstream config_f;
67
68
69
70 extern FILE *log_file;
71 extern userrec* fd_ref_table[65536];
72
73 extern int statsAccept, statsRefused, statsUnknown, statsCollisions, statsDns, statsDnsGood, statsDnsBad, statsConnects, statsSent, statsRecv;
74
75 static char already_sent[65536];
76 extern std::vector<userrec*> all_opers;
77
78 extern ClassVector Classes;
79
80 typedef nspace::hash_map<std::string, userrec*, nspace::hash<string>, irc::StrHashComp> user_hash;
81 typedef nspace::hash_map<std::string, chanrec*, nspace::hash<string>, irc::StrHashComp> chan_hash;
82 typedef std::deque<command_t> command_table;
83
84 extern user_hash clientlist;
85 extern chan_hash chanlist;
86 extern command_table cmdlist;
87 extern file_cache MOTD;
88 extern file_cache RULES;
89
90 void log(int level,char *text, ...)
91 {
92         char textbuffer[MAXBUF];
93         va_list argsPtr;
94         time_t rawtime;
95         struct tm * timeinfo;
96         if (level < LogLevel)
97                 return;
98
99         time(&rawtime);
100         timeinfo = localtime (&rawtime);
101
102         if (log_file)
103         {
104                 char b[MAXBUF];
105                 va_start (argsPtr, text);
106                 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
107                 va_end(argsPtr);
108                 strlcpy(b,asctime(timeinfo),MAXBUF);
109                 b[24] = ':';    // we know this is the end of the time string
110                 fprintf(log_file,"%s %s\n",b,textbuffer);
111                 if (nofork)
112                 {
113                         // nofork enabled? display it on terminal too
114                         printf("%s %s\n",b,textbuffer);
115                 }
116         }
117 }
118
119 void readfile(file_cache &F, const char* fname)
120 {
121         FILE* file;
122         char linebuf[MAXBUF];
123
124         log(DEBUG,"readfile: loading %s",fname);
125         F.clear();
126         file =  fopen(fname,"r");
127         if (file)
128         {
129                 while (!feof(file))
130                 {
131                         fgets(linebuf,sizeof(linebuf),file);
132                         linebuf[strlen(linebuf)-1]='\0';
133                         if (linebuf[0] == 0)
134                         {
135                                 strcpy(linebuf,"  ");
136                         }
137                         if (!feof(file))
138                         {
139                                 F.push_back(linebuf);
140                         }
141                 }
142                 fclose(file);
143         }
144         else
145         {
146                 log(DEBUG,"readfile: failed to load file: %s",fname);
147         }
148         log(DEBUG,"readfile: loaded %s, %lu lines",fname,(unsigned long)F.size());
149 }
150
151 void Write(int sock,char *text, ...)
152 {
153         if (sock < 0)
154                 return;
155         if (!text)
156         {
157                 log(DEFAULT,"*** BUG *** Write was given an invalid parameter");
158                 return;
159         }
160         char textbuffer[MAXBUF];
161         va_list argsPtr;
162         char tb[MAXBUF];
163
164         va_start (argsPtr, text);
165         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
166         va_end(argsPtr);
167         int bytes = snprintf(tb,MAXBUF,"%s\r\n",textbuffer);
168         chop(tb);
169         if (fd_ref_table[sock])
170         {
171                 int MOD_RESULT = 0;
172                 FOREACH_RESULT(OnRawSocketWrite(sock,tb,bytes));
173                 fd_ref_table[sock]->AddWriteBuf(tb);
174                 statsSent += bytes;
175         }
176         else log(DEFAULT,"ERROR! attempted write to a user with no fd_ref_table entry!!!");
177 }
178
179 /* write a server formatted numeric response to a single socket */
180
181 void WriteServ(int sock, char* text, ...)
182 {
183         if (sock < 0)
184                 return;
185         if (!text)
186         {
187                 log(DEFAULT,"*** BUG *** WriteServ was given an invalid parameter");
188                 return;
189         }
190         char textbuffer[MAXBUF],tb[MAXBUF];
191         va_list argsPtr;
192         va_start (argsPtr, text);
193
194         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
195         va_end(argsPtr);
196         int bytes = snprintf(tb,MAXBUF,":%s %s\r\n",ServerName,textbuffer);
197         chop(tb);
198         if (fd_ref_table[sock])
199         {
200                 int MOD_RESULT = 0;
201                 FOREACH_RESULT(OnRawSocketWrite(sock,tb,bytes));
202                 fd_ref_table[sock]->AddWriteBuf(tb);
203                 statsSent += bytes;
204         }
205         else log(DEFAULT,"ERROR! attempted write to a user with no fd_ref_table entry!!!");
206 }
207
208 /* write text from an originating user to originating user */
209
210 void WriteFrom(int sock, userrec *user,char* text, ...)
211 {
212         if (sock < 0)
213                 return;
214         if ((!text) || (!user))
215         {
216                 log(DEFAULT,"*** BUG *** WriteFrom was given an invalid parameter");
217                 return;
218         }
219         char textbuffer[MAXBUF],tb[MAXBUF];
220         va_list argsPtr;
221         va_start (argsPtr, text);
222
223         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
224         va_end(argsPtr);
225         int bytes = snprintf(tb,MAXBUF,":%s!%s@%s %s\r\n",user->nick,user->ident,user->dhost,textbuffer);
226         chop(tb);
227         if (fd_ref_table[sock])
228         {
229                 int MOD_RESULT = 0;
230                 FOREACH_RESULT(OnRawSocketWrite(sock,tb,bytes));
231                 fd_ref_table[sock]->AddWriteBuf(tb);
232                 statsSent += bytes;
233         }
234         else log(DEFAULT,"ERROR! attempted write to a user with no fd_ref_table entry!!!");
235 }
236
237 /* write text to an destination user from a source user (e.g. user privmsg) */
238
239 void WriteTo(userrec *source, userrec *dest,char *data, ...)
240 {
241         if ((!dest) || (!data))
242         {
243                 log(DEFAULT,"*** BUG *** WriteTo was given an invalid parameter");
244                 return;
245         }
246         if (dest->fd == FD_MAGIC_NUMBER)
247                 return;
248         char textbuffer[MAXBUF],tb[MAXBUF];
249         va_list argsPtr;
250         va_start (argsPtr, data);
251         vsnprintf(textbuffer, MAXBUF, data, argsPtr);
252         va_end(argsPtr);
253         chop(tb);
254
255         // if no source given send it from the server.
256         if (!source)
257         {
258                 WriteServ(dest->fd,":%s %s",ServerName,textbuffer);
259         }
260         else
261         {
262                 WriteFrom(dest->fd,source,"%s",textbuffer);
263         }
264 }
265
266 /* write formatted text from a source user to all users on a channel
267  * including the sender (NOT for privmsg, notice etc!) */
268
269 void WriteChannel(chanrec* Ptr, userrec* user, char* text, ...)
270 {
271         if ((!Ptr) || (!user) || (!text))
272         {
273                 log(DEFAULT,"*** BUG *** WriteChannel was given an invalid parameter");
274                 return;
275         }
276         char textbuffer[MAXBUF];
277         va_list argsPtr;
278         va_start (argsPtr, text);
279         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
280         va_end(argsPtr);
281
282         std::vector<char*> *ulist = Ptr->GetUsers();
283         for (unsigned int j = 0; j < ulist->size(); j++)
284         {
285                 char* o = (*ulist)[j];
286                 userrec* otheruser = (userrec*)o;
287                 if (otheruser->fd != FD_MAGIC_NUMBER)
288                         WriteTo(user,otheruser,"%s",textbuffer);
289         }
290 }
291
292 /* write formatted text from a source user to all users on a channel
293  * including the sender (NOT for privmsg, notice etc!) doesnt send to
294  * users on remote servers */
295
296 void WriteChannelLocal(chanrec* Ptr, userrec* user, char* text, ...)
297 {
298         if ((!Ptr) || (!text))
299         {
300                 log(DEFAULT,"*** BUG *** WriteChannel was given an invalid parameter");
301                 return;
302         }
303         char textbuffer[MAXBUF];
304         va_list argsPtr;
305         va_start (argsPtr, text);
306         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
307         va_end(argsPtr);
308
309         std::vector<char*> *ulist = Ptr->GetUsers();
310         for (unsigned int j = 0; j < ulist->size(); j++)
311         {
312                 char* o = (*ulist)[j];
313                 userrec* otheruser = (userrec*)o;
314                 if ((otheruser->fd != FD_MAGIC_NUMBER) && (otheruser->fd != -1) && (otheruser != user))
315                 {
316                         if (!user)
317                         {
318                                 WriteServ(otheruser->fd,"%s",textbuffer);
319                         }
320                         else
321                         {
322                                 WriteTo(user,otheruser,"%s",textbuffer);
323                         }
324                 }
325         }
326 }
327
328 void WriteChannelWithServ(char* ServName, chanrec* Ptr, char* text, ...)
329 {
330         if ((!Ptr) || (!text))
331         {
332                 log(DEFAULT,"*** BUG *** WriteChannelWithServ was given an invalid parameter");
333                 return;
334         }
335         char textbuffer[MAXBUF];
336         va_list argsPtr;
337         va_start (argsPtr, text);
338         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
339         va_end(argsPtr);
340
341
342         std::vector<char*> *ulist = Ptr->GetUsers();
343         for (unsigned int j = 0; j < ulist->size(); j++)
344         {
345                 char* o = (*ulist)[j];
346                 userrec* otheruser = (userrec*)o;
347                 if (otheruser->fd != FD_MAGIC_NUMBER)
348                         WriteServ(otheruser->fd,"%s",textbuffer);
349         }
350 }
351
352 /* write formatted text from a source user to all users on a channel except
353  * for the sender (for privmsg etc) */
354
355 void ChanExceptSender(chanrec* Ptr, userrec* user, char* text, ...)
356 {
357         if ((!Ptr) || (!user) || (!text))
358         {
359                 log(DEFAULT,"*** BUG *** ChanExceptSender was given an invalid parameter");
360                 return;
361         }
362         char textbuffer[MAXBUF];
363         va_list argsPtr;
364         va_start (argsPtr, text);
365         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
366         va_end(argsPtr);
367
368         std::vector<char*> *ulist = Ptr->GetUsers();
369         for (unsigned int j = 0; j < ulist->size(); j++)
370         {
371                 char* o = (*ulist)[j];
372                 userrec* otheruser = (userrec*)o;
373                 if ((otheruser->fd != FD_MAGIC_NUMBER) && (user != otheruser))
374                         WriteFrom(otheruser->fd,user,"%s",textbuffer);
375         }
376 }
377
378 std::string GetServerDescription(char* servername)
379 {
380         return ServerDesc; // not a remote server that can be found, it must be me.
381 }
382
383 /* write a formatted string to all users who share at least one common
384  * channel, including the source user e.g. for use in NICK */
385
386 void WriteCommon(userrec *u, char* text, ...)
387 {
388         if (!u)
389         {
390                 log(DEFAULT,"*** BUG *** WriteCommon was given an invalid parameter");
391                 return;
392         }
393
394         if (u->registered != 7) {
395                 log(DEFAULT,"*** BUG *** WriteCommon on an unregistered user");
396                 return;
397         }
398
399         char textbuffer[MAXBUF];
400         va_list argsPtr;
401         va_start (argsPtr, text);
402         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
403         va_end(argsPtr);
404
405         // FIX: Stops a message going to the same person more than once
406         memset(&already_sent,0,65536);
407
408         bool sent_to_at_least_one = false;
409
410         for (int i = 0; i < MAXCHANS; i++)
411         {
412                 if (u->chans[i].channel)
413                 {
414                         std::vector<char*> *ulist = u->chans[i].channel->GetUsers();
415                         for (unsigned int j = 0; j < ulist->size(); j++)
416                         {
417                                 char* o = (*ulist)[j];
418                                 userrec* otheruser = (userrec*)o;
419                                 if ((otheruser->fd > 0) && (!already_sent[otheruser->fd]))
420                                 {
421                                         already_sent[otheruser->fd] = 1;
422                                         WriteFrom(otheruser->fd,u,"%s",textbuffer);
423                                         sent_to_at_least_one = true;
424                                 }
425                         }
426                 }
427         }
428         // if the user was not in any channels, no users will receive the text. Make sure the user
429         // receives their OWN message for WriteCommon
430         if (!sent_to_at_least_one)
431         {
432                 WriteFrom(u->fd,u,"%s",textbuffer);
433         }
434 }
435
436 /* write a formatted string to all users who share at least one common
437  * channel, NOT including the source user e.g. for use in QUIT */
438
439 void WriteCommonExcept(userrec *u, char* text, ...)
440 {
441         if (!u)
442         {
443                 log(DEFAULT,"*** BUG *** WriteCommon was given an invalid parameter");
444                 return;
445         }
446
447         if (u->registered != 7) {
448                 log(DEFAULT,"*** BUG *** WriteCommon on an unregistered user");
449                 return;
450         }
451
452         char textbuffer[MAXBUF];
453         va_list argsPtr;
454         va_start (argsPtr, text);
455         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
456         va_end(argsPtr);
457
458         memset(&already_sent,0,65536);
459
460         for (int i = 0; i < MAXCHANS; i++)
461         {
462                 if (u->chans[i].channel)
463                 {
464                         std::vector<char*> *ulist = u->chans[i].channel->GetUsers();
465                         for (unsigned int j = 0; j < ulist->size(); j++)
466                         {
467                                 char* o = (*ulist)[j];
468                                 userrec* otheruser = (userrec*)o;
469                                 if (u != otheruser)
470                                 {
471                                         if ((otheruser->fd > 0) && (!already_sent[otheruser->fd]))
472                                         {
473                                                 already_sent[otheruser->fd] = 1;
474                                                 WriteFrom(otheruser->fd,u,"%s",textbuffer);
475                                         }
476                                 }
477                         }
478                 }
479         }
480 }
481
482 void WriteOpers(char* text, ...)
483 {
484         if (!text)
485         {
486                 log(DEFAULT,"*** BUG *** WriteOpers was given an invalid parameter");
487                 return;
488         }
489
490         char textbuffer[MAXBUF];
491         va_list argsPtr;
492         va_start (argsPtr, text);
493         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
494         va_end(argsPtr);
495
496         for (std::vector<userrec*>::iterator i = all_opers.begin(); i != all_opers.end(); i++)
497         {
498                 userrec* a = *i;
499                 if ((a) && (a->fd != FD_MAGIC_NUMBER))
500                 {
501                         if (strchr(a->modes,'s'))
502                         {
503                                 // send server notices to all with +s
504                                 WriteServ(a->fd,"NOTICE %s :%s",a->nick,textbuffer);
505                         }
506                 }
507         }
508 }
509
510 void NoticeAllOpers(userrec *source, bool local_only, char* text, ...)
511 {
512         if ((!text) || (!source))
513         {
514                 log(DEFAULT,"*** BUG *** NoticeAllOpers was given an invalid parameter");
515                 return;
516         }
517
518         char textbuffer[MAXBUF];
519         va_list argsPtr;
520         va_start (argsPtr, text);
521         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
522         va_end(argsPtr);
523
524         for (std::vector<userrec*>::iterator i = all_opers.begin(); i != all_opers.end(); i++)
525         {
526                 userrec* a = *i;
527                 if ((a) && (a->fd != FD_MAGIC_NUMBER))
528                 {
529                         if (strchr(a->modes,'s'))
530                         {
531                                 // send server notices to all with +s
532                                 WriteServ(a->fd,"NOTICE %s :*** Notice From %s: %s",a->nick,source->nick,textbuffer);
533                         }
534                 }
535         }
536
537 }
538 // returns TRUE of any users on channel C occupy server 'servername'.
539
540 bool ChanAnyOnThisServer(chanrec *c,char* servername)
541 {
542         log(DEBUG,"ChanAnyOnThisServer");
543
544         std::vector<char*> *ulist = c->GetUsers();
545         for (unsigned int j = 0; j < ulist->size(); j++)
546         {
547                 char* o = (*ulist)[j];
548                 userrec* user = (userrec*)o;
549                 if (!strcasecmp(user->server,servername))
550                         return true;
551         }
552         return false;
553 }
554
555 // returns true if user 'u' shares any common channels with any users on server 'servername'
556
557 bool CommonOnThisServer(userrec* u,const char* servername)
558 {
559         log(DEBUG,"ChanAnyOnThisServer");
560
561         for (int i = 0; i < MAXCHANS; i++)
562         {
563                 if (u->chans[i].channel)
564                 {
565                         std::vector<char*> *ulist = u->chans[i].channel->GetUsers();
566                         for (unsigned int j = 0; j < ulist->size(); j++)
567                         {
568                                 char* o = (*ulist)[j];
569                                 userrec* user = (userrec*)o;
570                                 if (!strcasecmp(user->server,servername))
571                                         return true;
572                         }
573                 }
574         }
575         return false;
576 }
577
578
579 void WriteMode(const char* modes, int flags, const char* text, ...)
580 {
581         if ((!text) || (!modes) || (!flags))
582         {
583                 log(DEFAULT,"*** BUG *** WriteMode was given an invalid parameter");
584                 return;
585         }
586
587         char textbuffer[MAXBUF];
588         va_list argsPtr;
589         va_start (argsPtr, text);
590         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
591         va_end(argsPtr);
592         int modelen = strlen(modes);
593
594         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
595         {
596                 if ((i->second) && (i->second->fd != FD_MAGIC_NUMBER))
597                 {
598                         bool send_to_user = false;
599
600                         if (flags == WM_AND)
601                         {
602                                 send_to_user = true;
603                                 for (int n = 0; n < modelen; n++)
604                                 {
605                                         if (!hasumode(i->second,modes[n]))
606                                         {
607                                                 send_to_user = false;
608                                                 break;
609                                         }
610                                 }
611                         }
612                         else if (flags == WM_OR)
613                         {
614                                 send_to_user = false;
615                                 for (int n = 0; n < modelen; n++)
616                                 {
617                                         if (hasumode(i->second,modes[n]))
618                                         {
619                                                 send_to_user = true;
620                                                 break;
621                                         }
622                                 }
623                         }
624
625                         if (send_to_user)
626                         {
627                                 WriteServ(i->second->fd,"NOTICE %s :%s",i->second->nick,textbuffer);
628                         }
629                 }
630         }
631 }
632
633 void NoticeAll(userrec *source, bool local_only, char* text, ...)
634 {
635         if ((!text) || (!source))
636         {
637                 log(DEFAULT,"*** BUG *** NoticeAll was given an invalid parameter");
638                 return;
639         }
640
641         char textbuffer[MAXBUF];
642         va_list argsPtr;
643         va_start (argsPtr, text);
644         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
645         va_end(argsPtr);
646
647         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
648         {
649                 if ((i->second) && (i->second->fd != FD_MAGIC_NUMBER))
650                 {
651                         WriteFrom(i->second->fd,source,"NOTICE $* :%s",textbuffer);
652                 }
653         }
654
655 }
656
657
658 void WriteWallOps(userrec *source, bool local_only, char* text, ...)
659 {
660         if ((!text) || (!source))
661         {
662                 log(DEFAULT,"*** BUG *** WriteOpers was given an invalid parameter");
663                 return;
664         }
665
666         char textbuffer[MAXBUF];
667         va_list argsPtr;
668         va_start (argsPtr, text);
669         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
670         va_end(argsPtr);
671
672         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
673         {
674                 if ((i->second) && (i->second->fd != FD_MAGIC_NUMBER))
675                 {
676                         if (strchr(i->second->modes,'w'))
677                         {
678                                 WriteTo(source,i->second,"WALLOPS :%s",textbuffer);
679                         }
680                 }
681         }
682 }
683
684 /* convert a string to lowercase. Note following special circumstances
685  * taken from RFC 1459. Many "official" server branches still hold to this
686  * rule so i will too;
687  *
688  *  Because of IRC's scandanavian origin, the characters {}| are
689  *  considered to be the lower case equivalents of the characters []\,
690  *  respectively. This is a critical issue when determining the
691  *  equivalence of two nicknames.
692  */
693
694 void strlower(char *n)
695 {
696         if (n)
697         {
698                 for (char* t = n; *t; t++)
699                         *t = lowermap[(unsigned)*t];
700         }
701 }
702
703 /* Find a user record by nickname and return a pointer to it */
704
705 userrec* Find(std::string nick)
706 {
707         user_hash::iterator iter = clientlist.find(nick);
708
709         if (iter == clientlist.end())
710                 /* Couldn't find it */
711                 return NULL;
712
713         return iter->second;
714 }
715
716 /* find a channel record by channel name and return a pointer to it */
717
718 chanrec* FindChan(const char* chan)
719 {
720         if (!chan)
721         {
722                 log(DEFAULT,"*** BUG *** Findchan was given an invalid parameter");
723                 return NULL;
724         }
725
726         chan_hash::iterator iter = chanlist.find(chan);
727
728         if (iter == chanlist.end())
729                 /* Couldn't find it */
730                 return NULL;
731
732         return iter->second;
733 }
734
735
736 long GetMaxBans(char* name)
737 {
738         char CM[MAXBUF];
739         for (int count = 0; count < ConfValueEnum("banlist",&config_f); count++)
740         {
741                 ConfValue("banlist","chan",count,CM,&config_f);
742                 if (match(name,CM))
743                 {
744                         ConfValue("banlist","limit",count,CM,&config_f);
745                         return atoi(CM);
746                 }
747         }
748         return 64;
749 }
750
751 void purge_empty_chans(userrec* u)
752 {
753
754         int go_again = 1, purge = 0;
755
756         // firstly decrement the count on each channel
757         for (int f = 0; f < MAXCHANS; f++)
758         {
759                 if (u->chans[f].channel)
760                 {
761                         u->chans[f].channel->DelUser((char*)u);
762                 }
763         }
764
765         for (int i = 0; i < MAXCHANS; i++)
766         {
767                 if (u->chans[i].channel)
768                 {
769                         if (!usercount(u->chans[i].channel))
770                         {
771                                 chan_hash::iterator i2 = chanlist.find(u->chans[i].channel->name);
772                                 /* kill the record */
773                                 if (i2 != chanlist.end())
774                                 {
775                                         log(DEBUG,"del_channel: destroyed: %s",i2->second->name);
776                                         if (i2->second)
777                                                 delete i2->second;
778                                         chanlist.erase(i2);
779                                         go_again = 1;
780                                         purge++;
781                                         u->chans[i].channel = NULL;
782                                 }
783                         }
784                         else
785                         {
786                                 log(DEBUG,"skipped purge for %s",u->chans[i].channel->name);
787                         }
788                 }
789         }
790         log(DEBUG,"completed channel purge, killed %lu",(unsigned long)purge);
791
792         DeleteOper(u);
793 }
794
795
796 char scratch[MAXBUF];
797 char sparam[MAXBUF];
798
799 char* chanmodes(chanrec *chan)
800 {
801         if (!chan)
802         {
803                 log(DEFAULT,"*** BUG *** chanmodes was given an invalid parameter");
804                 strcpy(scratch,"");
805                 return scratch;
806         }
807
808         strcpy(scratch,"");
809         strcpy(sparam,"");
810         if (chan->binarymodes & CM_NOEXTERNAL)
811         {
812                 strlcat(scratch,"n",MAXMODES);
813         }
814         if (chan->binarymodes & CM_TOPICLOCK)
815         {
816                 strlcat(scratch,"t",MAXMODES);
817         }
818         if (chan->key[0])
819         {
820                 strlcat(scratch,"k",MAXMODES);
821         }
822         if (chan->limit)
823         {
824                 strlcat(scratch,"l",MAXMODES);
825         }
826         if (chan->binarymodes & CM_INVITEONLY)
827         {
828                 strlcat(scratch,"i",MAXMODES);
829         }
830         if (chan->binarymodes & CM_MODERATED)
831         {
832                 strlcat(scratch,"m",MAXMODES);
833         }
834         if (chan->binarymodes & CM_SECRET)
835         {
836                 strlcat(scratch,"s",MAXMODES);
837         }
838         if (chan->binarymodes & CM_PRIVATE)
839         {
840                 strlcat(scratch,"p",MAXMODES);
841         }
842         if (chan->key[0])
843         {
844                 strlcat(sparam," ",MAXBUF);
845                 strlcat(sparam,chan->key,MAXBUF);
846         }
847         if (chan->limit)
848         {
849                 char foo[24];
850                 sprintf(foo," %lu",(unsigned long)chan->limit);
851                 strlcat(sparam,foo,MAXBUF);
852         }
853         if (*chan->custom_modes)
854         {
855                 strlcat(scratch,chan->custom_modes,MAXMODES);
856                 for (int z = 0; chan->custom_modes[z] != 0; z++)
857                 {
858                         std::string extparam = chan->GetModeParameter(chan->custom_modes[z]);
859                         if (extparam != "")
860                         {
861                                 strlcat(sparam," ",MAXBUF);
862                                 strlcat(sparam,extparam.c_str(),MAXBUF);
863                         }
864                 }
865         }
866         log(DEBUG,"chanmodes: %s %s%s",chan->name,scratch,sparam);
867         strlcat(scratch,sparam,MAXMODES);
868         return scratch;
869 }
870
871
872 /* compile a userlist of a channel into a string, each nick seperated by
873  * spaces and op, voice etc status shown as @ and + */
874
875 void userlist(userrec *user,chanrec *c)
876 {
877         if ((!c) || (!user))
878         {
879                 log(DEFAULT,"*** BUG *** userlist was given an invalid parameter");
880                 return;
881         }
882
883         snprintf(list,MAXBUF,"353 %s = %s :", user->nick, c->name);
884
885         std::vector<char*> *ulist = c->GetUsers();
886         for (unsigned int i = 0; i < ulist->size(); i++)
887         {
888                 char* o = (*ulist)[i];
889                 userrec* otheruser = (userrec*)o;
890                 if ((!has_channel(user,c)) && (strchr(otheruser->modes,'i')))
891                 {
892                         /* user is +i, and source not on the channel, does not show
893                          * nick in NAMES list */
894                         continue;
895                 }
896                 strlcat(list,cmode(otheruser,c),MAXBUF);
897                 strlcat(list,otheruser->nick,MAXBUF);
898                 strlcat(list," ",MAXBUF);
899                 if (strlen(list)>(480-NICKMAX))
900                 {
901                         /* list overflowed into
902                          * multiple numerics */
903                         WriteServ(user->fd,"%s",list);
904                         snprintf(list,MAXBUF,"353 %s = %s :", user->nick, c->name);
905                 }
906         }
907         /* if whats left in the list isnt empty, send it */
908         if (list[strlen(list)-1] != ':')
909         {
910                 WriteServ(user->fd,"%s",list);
911         }
912 }
913
914 /* return a count of the users on a specific channel accounting for
915  * invisible users who won't increase the count. e.g. for /LIST */
916
917 int usercount_i(chanrec *c)
918 {
919         int count = 0;
920
921         if (!c)
922         {
923                 log(DEFAULT,"*** BUG *** usercount_i was given an invalid parameter");
924                 return 0;
925         }
926
927         strcpy(list,"");
928         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
929         {
930                 if (i->second)
931                 {
932                         if (has_channel(i->second,c))
933                         {
934                                 if (isnick(i->second->nick))
935                                 {
936                                         if ((!has_channel(i->second,c)) && (strchr(i->second->modes,'i')))
937                                         {
938                                                 /* user is +i, and source not on the channel, does not show
939                                                  * nick in NAMES list */
940                                                 continue;
941                                         }
942                                         count++;
943                                 }
944                         }
945                 }
946         }
947         log(DEBUG,"usercount_i: %s %lu",c->name,(unsigned long)count);
948         return count;
949 }
950
951
952 int usercount(chanrec *c)
953 {
954         if (!c)
955         {
956                 log(DEFAULT,"*** BUG *** usercount was given an invalid parameter");
957                 return 0;
958         }
959         int count = c->GetUserCounter();
960         log(DEBUG,"usercount: %s %lu",c->name,(unsigned long)count);
961         return count;
962 }
963
964
965 // looks up a users password for their connection class (<ALLOW>/<DENY> tags)
966
967 char* Passwd(userrec *user)
968 {
969         for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
970         {
971                 if (match(user->host,i->host) && (i->type == CC_ALLOW))
972                 {
973                         return i->pass;
974                 }
975         }
976         return "";
977 }
978
979 bool IsDenied(userrec *user)
980 {
981         for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
982         {
983                 if (match(user->host,i->host) && (i->type == CC_DENY))
984                 {
985                         return true;
986                 }
987         }
988         return false;
989 }
990
991
992
993
994 /* sends out an error notice to all connected clients (not to be used
995  * lightly!) */
996
997 void send_error(char *s)
998 {
999         log(DEBUG,"send_error: %s",s);
1000         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1001         {
1002                 if (isnick(i->second->nick))
1003                 {
1004                         WriteServ(i->second->fd,"NOTICE %s :%s",i->second->nick,s);
1005                 }
1006                 else
1007                 {
1008                         // fix - unregistered connections receive ERROR, not NOTICE
1009                         Write(i->second->fd,"ERROR :%s",s);
1010                 }
1011         }
1012 }
1013
1014 void Error(int status)
1015 {
1016         signal (SIGALRM, SIG_IGN);
1017         signal (SIGPIPE, SIG_IGN);
1018         signal (SIGTERM, SIG_IGN);
1019         signal (SIGABRT, SIG_IGN);
1020         signal (SIGSEGV, SIG_IGN);
1021         signal (SIGURG, SIG_IGN);
1022         signal (SIGKILL, SIG_IGN);
1023         log(DEFAULT,"*** fell down a pothole in the road to perfection ***");
1024         send_error("Error! Segmentation fault! save meeeeeeeeeeeeee *splat!*");
1025         Exit(status);
1026 }
1027
1028 // this function counts all users connected, wether they are registered or NOT.
1029 int usercnt(void)
1030 {
1031         return clientlist.size();
1032 }
1033
1034 // this counts only registered users, so that the percentages in /MAP don't mess up when users are sitting in an unregistered state
1035 int registered_usercount(void)
1036 {
1037         int c = 0;
1038         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1039         {
1040                 if ((i->second->fd) && (isnick(i->second->nick))) c++;
1041         }
1042         return c;
1043 }
1044
1045 int usercount_invisible(void)
1046 {
1047         int c = 0;
1048
1049         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1050         {
1051                 if ((i->second->fd) && (isnick(i->second->nick)) && (strchr(i->second->modes,'i'))) c++;
1052         }
1053         return c;
1054 }
1055
1056 int usercount_opers(void)
1057 {
1058         int c = 0;
1059
1060         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1061         {
1062                 if ((i->second->fd) && (isnick(i->second->nick)) && (strchr(i->second->modes,'o'))) c++;
1063         }
1064         return c;
1065 }
1066
1067 int usercount_unknown(void)
1068 {
1069         int c = 0;
1070
1071         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1072         {
1073                 if ((i->second->fd) && (i->second->registered != 7))
1074                         c++;
1075         }
1076         return c;
1077 }
1078
1079 long chancount(void)
1080 {
1081         return chanlist.size();
1082 }
1083
1084 long count_servs(void)
1085 {
1086         return 0;
1087 }
1088
1089 long servercount(void)
1090 {
1091         return count_servs()+1;
1092 }
1093
1094 long local_count()
1095 {
1096         int c = 0;
1097         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1098         {
1099                 if ((i->second->fd) && (isnick(i->second->nick)) && (!strcasecmp(i->second->server,ServerName))) c++;
1100         }
1101         return c;
1102 }
1103
1104 void ShowMOTD(userrec *user)
1105 {
1106         char buf[65536];
1107         std::string WholeMOTD = "";
1108         if (!MOTD.size())
1109         {
1110                 WriteServ(user->fd,"422 %s :Message of the day file is missing.",user->nick);
1111                 return;
1112         }
1113         snprintf(buf,65535,":%s 375 %s :- %s message of the day\r\n", ServerName, user->nick, ServerName);
1114         WholeMOTD = WholeMOTD + buf;
1115         for (unsigned int i = 0; i != MOTD.size(); i++)
1116         {
1117                 snprintf(buf,65535,":%s 372 %s :- %s\r\n", ServerName, user->nick, MOTD[i].c_str());
1118                 WholeMOTD = WholeMOTD + buf;
1119         }
1120         snprintf(buf,65535,":%s 376 %s :End of message of the day.\r\n", ServerName, user->nick);
1121         WholeMOTD = WholeMOTD + buf;
1122         // only one write operation
1123         user->AddWriteBuf(WholeMOTD);
1124         statsSent += WholeMOTD.length();
1125 }
1126
1127 void ShowRULES(userrec *user)
1128 {
1129         if (!RULES.size())
1130         {
1131                 WriteServ(user->fd,"NOTICE %s :Rules file is missing.",user->nick);
1132                 return;
1133         }
1134         WriteServ(user->fd,"NOTICE %s :%s rules",user->nick,ServerName);
1135         for (unsigned int i = 0; i != RULES.size(); i++)
1136         {
1137                                 WriteServ(user->fd,"NOTICE %s :%s",user->nick,RULES[i].c_str());
1138         }
1139         WriteServ(user->fd,"NOTICE %s :End of %s rules.",user->nick,ServerName);
1140 }
1141
1142 // this returns 1 when all modules are satisfied that the user should be allowed onto the irc server
1143 // (until this returns true, a user will block in the waiting state, waiting to connect up to the
1144 // registration timeout maximum seconds)
1145 bool AllModulesReportReady(userrec* user)
1146 {
1147         for (int i = 0; i <= MODCOUNT; i++)
1148         {
1149                 int res = modules[i]->OnCheckReady(user);
1150                         if (!res)
1151                                 return false;
1152         }
1153         return true;
1154 }
1155
1156 char islast(const char* s)
1157 {
1158         return '+';
1159 }
1160
1161 long map_count(const char* s)
1162 {
1163         int c = 0;
1164         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1165         {
1166                 if ((i->second->fd) && (isnick(i->second->nick)) && (!strcasecmp(i->second->server,s))) c++;
1167         }
1168         return c;
1169 }
1170
1171 void createcommand(char* cmd, handlerfunc f, char flags, int minparams,char* source)
1172 {
1173         command_t comm;
1174         /* create the command and push it onto the table */
1175         strlcpy(comm.command,cmd,MAXBUF);
1176         strlcpy(comm.source,source,MAXBUF);
1177         comm.handler_function = f;
1178         comm.flags_needed = flags;
1179         comm.min_params = minparams;
1180         comm.use_count = 0;
1181         comm.total_bytes = 0;
1182         cmdlist.push_back(comm);
1183         log(DEBUG,"Added command %s (%lu parameters)",cmd,(unsigned long)minparams);
1184 }
1185
1186
1187 void SetupCommandTable(void)
1188 {
1189         createcommand("USER",handle_user,0,4,"<core>");
1190         createcommand("NICK",handle_nick,0,1,"<core>");
1191         createcommand("QUIT",handle_quit,0,0,"<core>");
1192         createcommand("VERSION",handle_version,0,0,"<core>");
1193         createcommand("PING",handle_ping,0,1,"<core>");
1194         createcommand("PONG",handle_pong,0,1,"<core>");
1195         createcommand("ADMIN",handle_admin,0,0,"<core>");
1196         createcommand("PRIVMSG",handle_privmsg,0,2,"<core>");
1197         createcommand("INFO",handle_info,0,0,"<core>");
1198         createcommand("TIME",handle_time,0,0,"<core>");
1199         createcommand("WHOIS",handle_whois,0,1,"<core>");
1200         createcommand("WALLOPS",handle_wallops,'o',1,"<core>");
1201         createcommand("NOTICE",handle_notice,0,2,"<core>");
1202         createcommand("JOIN",handle_join,0,1,"<core>");
1203         createcommand("NAMES",handle_names,0,0,"<core>");
1204         createcommand("PART",handle_part,0,1,"<core>");
1205         createcommand("KICK",handle_kick,0,2,"<core>");
1206         createcommand("MODE",handle_mode,0,1,"<core>");
1207         createcommand("TOPIC",handle_topic,0,1,"<core>");
1208         createcommand("WHO",handle_who,0,1,"<core>");
1209         createcommand("MOTD",handle_motd,0,0,"<core>");
1210         createcommand("RULES",handle_rules,0,0,"<core>");
1211         createcommand("OPER",handle_oper,0,2,"<core>");
1212         createcommand("LIST",handle_list,0,0,"<core>");
1213         createcommand("DIE",handle_die,'o',1,"<core>");
1214         createcommand("RESTART",handle_restart,'o',1,"<core>");
1215         createcommand("KILL",handle_kill,'o',2,"<core>");
1216         createcommand("REHASH",handle_rehash,'o',0,"<core>");
1217         createcommand("LUSERS",handle_lusers,0,0,"<core>");
1218         createcommand("STATS",handle_stats,0,1,"<core>");
1219         createcommand("USERHOST",handle_userhost,0,1,"<core>");
1220         createcommand("AWAY",handle_away,0,0,"<core>");
1221         createcommand("ISON",handle_ison,0,0,"<core>");
1222         createcommand("SUMMON",handle_summon,0,0,"<core>");
1223         createcommand("USERS",handle_users,0,0,"<core>");
1224         createcommand("INVITE",handle_invite,0,0,"<core>");
1225         createcommand("PASS",handle_pass,0,1,"<core>");
1226         createcommand("TRACE",handle_trace,'o',0,"<core>");
1227         createcommand("WHOWAS",handle_whowas,0,1,"<core>");
1228         createcommand("CONNECT",handle_connect,'o',1,"<core>");
1229         createcommand("SQUIT",handle_squit,'o',0,"<core>");
1230         createcommand("MODULES",handle_modules,0,0,"<core>");
1231         createcommand("LINKS",handle_links,0,0,"<core>");
1232         createcommand("MAP",handle_map,0,0,"<core>");
1233         createcommand("KLINE",handle_kline,'o',1,"<core>");
1234         createcommand("GLINE",handle_gline,'o',1,"<core>");
1235         createcommand("ZLINE",handle_zline,'o',1,"<core>");
1236         createcommand("QLINE",handle_qline,'o',1,"<core>");
1237         createcommand("ELINE",handle_eline,'o',1,"<core>");
1238         createcommand("LOADMODULE",handle_loadmodule,'o',1,"<core>");
1239         createcommand("UNLOADMODULE",handle_unloadmodule,'o',1,"<core>");
1240         createcommand("SERVER",handle_server,0,0,"<core>");
1241         createcommand("COMMANDS",handle_commands,0,0,"<core>");
1242 }
1243
1244 bool DirValid(char* dirandfile)
1245 {
1246         char work[MAXBUF];
1247         strlcpy(work,dirandfile,MAXBUF);
1248         int p = strlen(work);
1249         // we just want the dir
1250         while (strlen(work))
1251         {
1252                 if (work[p] == '/')
1253                 {
1254                         work[p] = '\0';
1255                         break;
1256                 }
1257                 work[p--] = '\0';
1258         }
1259         char buffer[MAXBUF], otherdir[MAXBUF];
1260         // Get the current working directory
1261         if( getcwd( buffer, MAXBUF ) == NULL )
1262                 return false;
1263         chdir(work);
1264         if( getcwd( otherdir, MAXBUF ) == NULL )
1265                 return false;
1266         chdir(buffer);
1267         if (strlen(otherdir) >= strlen(work))
1268         {
1269                 otherdir[strlen(work)] = '\0';
1270                 if (!strcmp(otherdir,work))
1271                 {
1272                         return true;
1273                 }
1274                 return false;
1275         }
1276         else return false;
1277 }
1278
1279 std::string GetFullProgDir(char** argv, int argc)
1280 {
1281         char work[MAXBUF];
1282         strlcpy(work,argv[0],MAXBUF);
1283         int p = strlen(work);
1284         // we just want the dir
1285         while (strlen(work))
1286         {
1287                 if (work[p] == '/')
1288                 {
1289                         work[p] = '\0';
1290                         break;
1291                 }
1292                 work[p--] = '\0';
1293         }
1294         char buffer[MAXBUF], otherdir[MAXBUF];
1295         // Get the current working directory
1296         if( getcwd( buffer, MAXBUF ) == NULL )
1297                 return "";
1298         chdir(work);
1299         if( getcwd( otherdir, MAXBUF ) == NULL )
1300                 return "";
1301         chdir(buffer);
1302         return otherdir;
1303 }
1304