]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/helperfuncs.cpp
Added OnGetServerDescription (mainly for link modules)
[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         std::string description = "";
381         FOREACH_MOD OnGetServerDescription(servername,description);
382         if (description != "")
383         {
384                 return description;
385         }
386         else
387         {
388                 return ServerDesc; // not a remote server that can be found, it must be me.
389         }
390 }
391
392 /* write a formatted string to all users who share at least one common
393  * channel, including the source user e.g. for use in NICK */
394
395 void WriteCommon(userrec *u, char* text, ...)
396 {
397         if (!u)
398         {
399                 log(DEFAULT,"*** BUG *** WriteCommon was given an invalid parameter");
400                 return;
401         }
402
403         if (u->registered != 7) {
404                 log(DEFAULT,"*** BUG *** WriteCommon on an unregistered user");
405                 return;
406         }
407
408         char textbuffer[MAXBUF];
409         va_list argsPtr;
410         va_start (argsPtr, text);
411         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
412         va_end(argsPtr);
413
414         // FIX: Stops a message going to the same person more than once
415         memset(&already_sent,0,65536);
416
417         bool sent_to_at_least_one = false;
418
419         for (int i = 0; i < MAXCHANS; i++)
420         {
421                 if (u->chans[i].channel)
422                 {
423                         std::vector<char*> *ulist = u->chans[i].channel->GetUsers();
424                         for (unsigned int j = 0; j < ulist->size(); j++)
425                         {
426                                 char* o = (*ulist)[j];
427                                 userrec* otheruser = (userrec*)o;
428                                 if ((otheruser->fd > 0) && (!already_sent[otheruser->fd]))
429                                 {
430                                         already_sent[otheruser->fd] = 1;
431                                         WriteFrom(otheruser->fd,u,"%s",textbuffer);
432                                         sent_to_at_least_one = true;
433                                 }
434                         }
435                 }
436         }
437         // if the user was not in any channels, no users will receive the text. Make sure the user
438         // receives their OWN message for WriteCommon
439         if (!sent_to_at_least_one)
440         {
441                 WriteFrom(u->fd,u,"%s",textbuffer);
442         }
443 }
444
445 /* write a formatted string to all users who share at least one common
446  * channel, NOT including the source user e.g. for use in QUIT */
447
448 void WriteCommonExcept(userrec *u, char* text, ...)
449 {
450         if (!u)
451         {
452                 log(DEFAULT,"*** BUG *** WriteCommon was given an invalid parameter");
453                 return;
454         }
455
456         if (u->registered != 7) {
457                 log(DEFAULT,"*** BUG *** WriteCommon on an unregistered user");
458                 return;
459         }
460
461         char textbuffer[MAXBUF];
462         va_list argsPtr;
463         va_start (argsPtr, text);
464         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
465         va_end(argsPtr);
466
467         memset(&already_sent,0,65536);
468
469         for (int i = 0; i < MAXCHANS; i++)
470         {
471                 if (u->chans[i].channel)
472                 {
473                         std::vector<char*> *ulist = u->chans[i].channel->GetUsers();
474                         for (unsigned int j = 0; j < ulist->size(); j++)
475                         {
476                                 char* o = (*ulist)[j];
477                                 userrec* otheruser = (userrec*)o;
478                                 if (u != otheruser)
479                                 {
480                                         if ((otheruser->fd > 0) && (!already_sent[otheruser->fd]))
481                                         {
482                                                 already_sent[otheruser->fd] = 1;
483                                                 WriteFrom(otheruser->fd,u,"%s",textbuffer);
484                                         }
485                                 }
486                         }
487                 }
488         }
489 }
490
491 void WriteOpers(char* text, ...)
492 {
493         if (!text)
494         {
495                 log(DEFAULT,"*** BUG *** WriteOpers was given an invalid parameter");
496                 return;
497         }
498
499         char textbuffer[MAXBUF];
500         va_list argsPtr;
501         va_start (argsPtr, text);
502         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
503         va_end(argsPtr);
504
505         for (std::vector<userrec*>::iterator i = all_opers.begin(); i != all_opers.end(); i++)
506         {
507                 userrec* a = *i;
508                 if ((a) && (a->fd != FD_MAGIC_NUMBER))
509                 {
510                         if (strchr(a->modes,'s'))
511                         {
512                                 // send server notices to all with +s
513                                 WriteServ(a->fd,"NOTICE %s :%s",a->nick,textbuffer);
514                         }
515                 }
516         }
517 }
518
519 void NoticeAllOpers(userrec *source, bool local_only, char* text, ...)
520 {
521         if ((!text) || (!source))
522         {
523                 log(DEFAULT,"*** BUG *** NoticeAllOpers was given an invalid parameter");
524                 return;
525         }
526
527         char textbuffer[MAXBUF];
528         va_list argsPtr;
529         va_start (argsPtr, text);
530         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
531         va_end(argsPtr);
532
533         for (std::vector<userrec*>::iterator i = all_opers.begin(); i != all_opers.end(); i++)
534         {
535                 userrec* a = *i;
536                 if ((a) && (a->fd != FD_MAGIC_NUMBER))
537                 {
538                         if (strchr(a->modes,'s'))
539                         {
540                                 // send server notices to all with +s
541                                 WriteServ(a->fd,"NOTICE %s :*** Notice From %s: %s",a->nick,source->nick,textbuffer);
542                         }
543                 }
544         }
545
546 }
547 // returns TRUE of any users on channel C occupy server 'servername'.
548
549 bool ChanAnyOnThisServer(chanrec *c,char* servername)
550 {
551         log(DEBUG,"ChanAnyOnThisServer");
552
553         std::vector<char*> *ulist = c->GetUsers();
554         for (unsigned int j = 0; j < ulist->size(); j++)
555         {
556                 char* o = (*ulist)[j];
557                 userrec* user = (userrec*)o;
558                 if (!strcasecmp(user->server,servername))
559                         return true;
560         }
561         return false;
562 }
563
564 // returns true if user 'u' shares any common channels with any users on server 'servername'
565
566 bool CommonOnThisServer(userrec* u,const char* servername)
567 {
568         log(DEBUG,"ChanAnyOnThisServer");
569
570         for (int i = 0; i < MAXCHANS; i++)
571         {
572                 if (u->chans[i].channel)
573                 {
574                         std::vector<char*> *ulist = u->chans[i].channel->GetUsers();
575                         for (unsigned int j = 0; j < ulist->size(); j++)
576                         {
577                                 char* o = (*ulist)[j];
578                                 userrec* user = (userrec*)o;
579                                 if (!strcasecmp(user->server,servername))
580                                         return true;
581                         }
582                 }
583         }
584         return false;
585 }
586
587
588 void WriteMode(const char* modes, int flags, const char* text, ...)
589 {
590         if ((!text) || (!modes) || (!flags))
591         {
592                 log(DEFAULT,"*** BUG *** WriteMode was given an invalid parameter");
593                 return;
594         }
595
596         char textbuffer[MAXBUF];
597         va_list argsPtr;
598         va_start (argsPtr, text);
599         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
600         va_end(argsPtr);
601         int modelen = strlen(modes);
602
603         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
604         {
605                 if ((i->second) && (i->second->fd != FD_MAGIC_NUMBER))
606                 {
607                         bool send_to_user = false;
608
609                         if (flags == WM_AND)
610                         {
611                                 send_to_user = true;
612                                 for (int n = 0; n < modelen; n++)
613                                 {
614                                         if (!hasumode(i->second,modes[n]))
615                                         {
616                                                 send_to_user = false;
617                                                 break;
618                                         }
619                                 }
620                         }
621                         else if (flags == WM_OR)
622                         {
623                                 send_to_user = false;
624                                 for (int n = 0; n < modelen; n++)
625                                 {
626                                         if (hasumode(i->second,modes[n]))
627                                         {
628                                                 send_to_user = true;
629                                                 break;
630                                         }
631                                 }
632                         }
633
634                         if (send_to_user)
635                         {
636                                 WriteServ(i->second->fd,"NOTICE %s :%s",i->second->nick,textbuffer);
637                         }
638                 }
639         }
640 }
641
642 void NoticeAll(userrec *source, bool local_only, char* text, ...)
643 {
644         if ((!text) || (!source))
645         {
646                 log(DEFAULT,"*** BUG *** NoticeAll was given an invalid parameter");
647                 return;
648         }
649
650         char textbuffer[MAXBUF];
651         va_list argsPtr;
652         va_start (argsPtr, text);
653         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
654         va_end(argsPtr);
655
656         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
657         {
658                 if ((i->second) && (i->second->fd != FD_MAGIC_NUMBER))
659                 {
660                         WriteFrom(i->second->fd,source,"NOTICE $* :%s",textbuffer);
661                 }
662         }
663
664 }
665
666
667 void WriteWallOps(userrec *source, bool local_only, char* text, ...)
668 {
669         if ((!text) || (!source))
670         {
671                 log(DEFAULT,"*** BUG *** WriteOpers was given an invalid parameter");
672                 return;
673         }
674
675         char textbuffer[MAXBUF];
676         va_list argsPtr;
677         va_start (argsPtr, text);
678         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
679         va_end(argsPtr);
680
681         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
682         {
683                 if ((i->second) && (i->second->fd != FD_MAGIC_NUMBER))
684                 {
685                         if (strchr(i->second->modes,'w'))
686                         {
687                                 WriteTo(source,i->second,"WALLOPS :%s",textbuffer);
688                         }
689                 }
690         }
691 }
692
693 /* convert a string to lowercase. Note following special circumstances
694  * taken from RFC 1459. Many "official" server branches still hold to this
695  * rule so i will too;
696  *
697  *  Because of IRC's scandanavian origin, the characters {}| are
698  *  considered to be the lower case equivalents of the characters []\,
699  *  respectively. This is a critical issue when determining the
700  *  equivalence of two nicknames.
701  */
702
703 void strlower(char *n)
704 {
705         if (n)
706         {
707                 for (char* t = n; *t; t++)
708                         *t = lowermap[(unsigned)*t];
709         }
710 }
711
712 /* Find a user record by nickname and return a pointer to it */
713
714 userrec* Find(std::string nick)
715 {
716         user_hash::iterator iter = clientlist.find(nick);
717
718         if (iter == clientlist.end())
719                 /* Couldn't find it */
720                 return NULL;
721
722         return iter->second;
723 }
724
725 /* find a channel record by channel name and return a pointer to it */
726
727 chanrec* FindChan(const char* chan)
728 {
729         if (!chan)
730         {
731                 log(DEFAULT,"*** BUG *** Findchan was given an invalid parameter");
732                 return NULL;
733         }
734
735         chan_hash::iterator iter = chanlist.find(chan);
736
737         if (iter == chanlist.end())
738                 /* Couldn't find it */
739                 return NULL;
740
741         return iter->second;
742 }
743
744
745 long GetMaxBans(char* name)
746 {
747         char CM[MAXBUF];
748         for (int count = 0; count < ConfValueEnum("banlist",&config_f); count++)
749         {
750                 ConfValue("banlist","chan",count,CM,&config_f);
751                 if (match(name,CM))
752                 {
753                         ConfValue("banlist","limit",count,CM,&config_f);
754                         return atoi(CM);
755                 }
756         }
757         return 64;
758 }
759
760 void purge_empty_chans(userrec* u)
761 {
762
763         int go_again = 1, purge = 0;
764
765         // firstly decrement the count on each channel
766         for (int f = 0; f < MAXCHANS; f++)
767         {
768                 if (u->chans[f].channel)
769                 {
770                         u->chans[f].channel->DelUser((char*)u);
771                 }
772         }
773
774         for (int i = 0; i < MAXCHANS; i++)
775         {
776                 if (u->chans[i].channel)
777                 {
778                         if (!usercount(u->chans[i].channel))
779                         {
780                                 chan_hash::iterator i2 = chanlist.find(u->chans[i].channel->name);
781                                 /* kill the record */
782                                 if (i2 != chanlist.end())
783                                 {
784                                         log(DEBUG,"del_channel: destroyed: %s",i2->second->name);
785                                         if (i2->second)
786                                                 delete i2->second;
787                                         chanlist.erase(i2);
788                                         go_again = 1;
789                                         purge++;
790                                         u->chans[i].channel = NULL;
791                                 }
792                         }
793                         else
794                         {
795                                 log(DEBUG,"skipped purge for %s",u->chans[i].channel->name);
796                         }
797                 }
798         }
799         log(DEBUG,"completed channel purge, killed %lu",(unsigned long)purge);
800
801         DeleteOper(u);
802 }
803
804
805 char scratch[MAXBUF];
806 char sparam[MAXBUF];
807
808 char* chanmodes(chanrec *chan)
809 {
810         if (!chan)
811         {
812                 log(DEFAULT,"*** BUG *** chanmodes was given an invalid parameter");
813                 strcpy(scratch,"");
814                 return scratch;
815         }
816
817         strcpy(scratch,"");
818         strcpy(sparam,"");
819         if (chan->binarymodes & CM_NOEXTERNAL)
820         {
821                 strlcat(scratch,"n",MAXMODES);
822         }
823         if (chan->binarymodes & CM_TOPICLOCK)
824         {
825                 strlcat(scratch,"t",MAXMODES);
826         }
827         if (chan->key[0])
828         {
829                 strlcat(scratch,"k",MAXMODES);
830         }
831         if (chan->limit)
832         {
833                 strlcat(scratch,"l",MAXMODES);
834         }
835         if (chan->binarymodes & CM_INVITEONLY)
836         {
837                 strlcat(scratch,"i",MAXMODES);
838         }
839         if (chan->binarymodes & CM_MODERATED)
840         {
841                 strlcat(scratch,"m",MAXMODES);
842         }
843         if (chan->binarymodes & CM_SECRET)
844         {
845                 strlcat(scratch,"s",MAXMODES);
846         }
847         if (chan->binarymodes & CM_PRIVATE)
848         {
849                 strlcat(scratch,"p",MAXMODES);
850         }
851         if (chan->key[0])
852         {
853                 strlcat(sparam," ",MAXBUF);
854                 strlcat(sparam,chan->key,MAXBUF);
855         }
856         if (chan->limit)
857         {
858                 char foo[24];
859                 sprintf(foo," %lu",(unsigned long)chan->limit);
860                 strlcat(sparam,foo,MAXBUF);
861         }
862         if (*chan->custom_modes)
863         {
864                 strlcat(scratch,chan->custom_modes,MAXMODES);
865                 for (int z = 0; chan->custom_modes[z] != 0; z++)
866                 {
867                         std::string extparam = chan->GetModeParameter(chan->custom_modes[z]);
868                         if (extparam != "")
869                         {
870                                 strlcat(sparam," ",MAXBUF);
871                                 strlcat(sparam,extparam.c_str(),MAXBUF);
872                         }
873                 }
874         }
875         log(DEBUG,"chanmodes: %s %s%s",chan->name,scratch,sparam);
876         strlcat(scratch,sparam,MAXMODES);
877         return scratch;
878 }
879
880
881 /* compile a userlist of a channel into a string, each nick seperated by
882  * spaces and op, voice etc status shown as @ and + */
883
884 void userlist(userrec *user,chanrec *c)
885 {
886         if ((!c) || (!user))
887         {
888                 log(DEFAULT,"*** BUG *** userlist was given an invalid parameter");
889                 return;
890         }
891
892         snprintf(list,MAXBUF,"353 %s = %s :", user->nick, c->name);
893
894         std::vector<char*> *ulist = c->GetUsers();
895         for (unsigned int i = 0; i < ulist->size(); i++)
896         {
897                 char* o = (*ulist)[i];
898                 userrec* otheruser = (userrec*)o;
899                 if ((!has_channel(user,c)) && (strchr(otheruser->modes,'i')))
900                 {
901                         /* user is +i, and source not on the channel, does not show
902                          * nick in NAMES list */
903                         continue;
904                 }
905                 strlcat(list,cmode(otheruser,c),MAXBUF);
906                 strlcat(list,otheruser->nick,MAXBUF);
907                 strlcat(list," ",MAXBUF);
908                 if (strlen(list)>(480-NICKMAX))
909                 {
910                         /* list overflowed into
911                          * multiple numerics */
912                         WriteServ(user->fd,"%s",list);
913                         snprintf(list,MAXBUF,"353 %s = %s :", user->nick, c->name);
914                 }
915         }
916         /* if whats left in the list isnt empty, send it */
917         if (list[strlen(list)-1] != ':')
918         {
919                 WriteServ(user->fd,"%s",list);
920         }
921 }
922
923 /* return a count of the users on a specific channel accounting for
924  * invisible users who won't increase the count. e.g. for /LIST */
925
926 int usercount_i(chanrec *c)
927 {
928         int count = 0;
929
930         if (!c)
931         {
932                 log(DEFAULT,"*** BUG *** usercount_i was given an invalid parameter");
933                 return 0;
934         }
935
936         strcpy(list,"");
937         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
938         {
939                 if (i->second)
940                 {
941                         if (has_channel(i->second,c))
942                         {
943                                 if (isnick(i->second->nick))
944                                 {
945                                         if ((!has_channel(i->second,c)) && (strchr(i->second->modes,'i')))
946                                         {
947                                                 /* user is +i, and source not on the channel, does not show
948                                                  * nick in NAMES list */
949                                                 continue;
950                                         }
951                                         count++;
952                                 }
953                         }
954                 }
955         }
956         log(DEBUG,"usercount_i: %s %lu",c->name,(unsigned long)count);
957         return count;
958 }
959
960
961 int usercount(chanrec *c)
962 {
963         if (!c)
964         {
965                 log(DEFAULT,"*** BUG *** usercount was given an invalid parameter");
966                 return 0;
967         }
968         int count = c->GetUserCounter();
969         log(DEBUG,"usercount: %s %lu",c->name,(unsigned long)count);
970         return count;
971 }
972
973
974 // looks up a users password for their connection class (<ALLOW>/<DENY> tags)
975
976 char* Passwd(userrec *user)
977 {
978         for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
979         {
980                 if (match(user->host,i->host) && (i->type == CC_ALLOW))
981                 {
982                         return i->pass;
983                 }
984         }
985         return "";
986 }
987
988 bool IsDenied(userrec *user)
989 {
990         for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
991         {
992                 if (match(user->host,i->host) && (i->type == CC_DENY))
993                 {
994                         return true;
995                 }
996         }
997         return false;
998 }
999
1000
1001
1002
1003 /* sends out an error notice to all connected clients (not to be used
1004  * lightly!) */
1005
1006 void send_error(char *s)
1007 {
1008         log(DEBUG,"send_error: %s",s);
1009         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1010         {
1011                 if (isnick(i->second->nick))
1012                 {
1013                         WriteServ(i->second->fd,"NOTICE %s :%s",i->second->nick,s);
1014                 }
1015                 else
1016                 {
1017                         // fix - unregistered connections receive ERROR, not NOTICE
1018                         Write(i->second->fd,"ERROR :%s",s);
1019                 }
1020         }
1021 }
1022
1023 void Error(int status)
1024 {
1025         signal (SIGALRM, SIG_IGN);
1026         signal (SIGPIPE, SIG_IGN);
1027         signal (SIGTERM, SIG_IGN);
1028         signal (SIGABRT, SIG_IGN);
1029         signal (SIGSEGV, SIG_IGN);
1030         signal (SIGURG, SIG_IGN);
1031         signal (SIGKILL, SIG_IGN);
1032         log(DEFAULT,"*** fell down a pothole in the road to perfection ***");
1033         send_error("Error! Segmentation fault! save meeeeeeeeeeeeee *splat!*");
1034         Exit(status);
1035 }
1036
1037 // this function counts all users connected, wether they are registered or NOT.
1038 int usercnt(void)
1039 {
1040         return clientlist.size();
1041 }
1042
1043 // this counts only registered users, so that the percentages in /MAP don't mess up when users are sitting in an unregistered state
1044 int registered_usercount(void)
1045 {
1046         int c = 0;
1047         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1048         {
1049                 if ((i->second->fd) && (isnick(i->second->nick))) c++;
1050         }
1051         return c;
1052 }
1053
1054 int usercount_invisible(void)
1055 {
1056         int c = 0;
1057
1058         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1059         {
1060                 if ((i->second->fd) && (isnick(i->second->nick)) && (strchr(i->second->modes,'i'))) c++;
1061         }
1062         return c;
1063 }
1064
1065 int usercount_opers(void)
1066 {
1067         int c = 0;
1068
1069         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1070         {
1071                 if ((i->second->fd) && (isnick(i->second->nick)) && (strchr(i->second->modes,'o'))) c++;
1072         }
1073         return c;
1074 }
1075
1076 int usercount_unknown(void)
1077 {
1078         int c = 0;
1079
1080         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1081         {
1082                 if ((i->second->fd) && (i->second->registered != 7))
1083                         c++;
1084         }
1085         return c;
1086 }
1087
1088 long chancount(void)
1089 {
1090         return chanlist.size();
1091 }
1092
1093 long count_servs(void)
1094 {
1095         return 0;
1096 }
1097
1098 long servercount(void)
1099 {
1100         return count_servs()+1;
1101 }
1102
1103 long local_count()
1104 {
1105         int c = 0;
1106         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1107         {
1108                 if ((i->second->fd) && (isnick(i->second->nick)) && (!strcasecmp(i->second->server,ServerName))) c++;
1109         }
1110         return c;
1111 }
1112
1113 void ShowMOTD(userrec *user)
1114 {
1115         char buf[65536];
1116         std::string WholeMOTD = "";
1117         if (!MOTD.size())
1118         {
1119                 WriteServ(user->fd,"422 %s :Message of the day file is missing.",user->nick);
1120                 return;
1121         }
1122         snprintf(buf,65535,":%s 375 %s :- %s message of the day\r\n", ServerName, user->nick, ServerName);
1123         WholeMOTD = WholeMOTD + buf;
1124         for (unsigned int i = 0; i != MOTD.size(); i++)
1125         {
1126                 snprintf(buf,65535,":%s 372 %s :- %s\r\n", ServerName, user->nick, MOTD[i].c_str());
1127                 WholeMOTD = WholeMOTD + buf;
1128         }
1129         snprintf(buf,65535,":%s 376 %s :End of message of the day.\r\n", ServerName, user->nick);
1130         WholeMOTD = WholeMOTD + buf;
1131         // only one write operation
1132         user->AddWriteBuf(WholeMOTD);
1133         statsSent += WholeMOTD.length();
1134 }
1135
1136 void ShowRULES(userrec *user)
1137 {
1138         if (!RULES.size())
1139         {
1140                 WriteServ(user->fd,"NOTICE %s :Rules file is missing.",user->nick);
1141                 return;
1142         }
1143         WriteServ(user->fd,"NOTICE %s :%s rules",user->nick,ServerName);
1144         for (unsigned int i = 0; i != RULES.size(); i++)
1145         {
1146                                 WriteServ(user->fd,"NOTICE %s :%s",user->nick,RULES[i].c_str());
1147         }
1148         WriteServ(user->fd,"NOTICE %s :End of %s rules.",user->nick,ServerName);
1149 }
1150
1151 // this returns 1 when all modules are satisfied that the user should be allowed onto the irc server
1152 // (until this returns true, a user will block in the waiting state, waiting to connect up to the
1153 // registration timeout maximum seconds)
1154 bool AllModulesReportReady(userrec* user)
1155 {
1156         for (int i = 0; i <= MODCOUNT; i++)
1157         {
1158                 int res = modules[i]->OnCheckReady(user);
1159                         if (!res)
1160                                 return false;
1161         }
1162         return true;
1163 }
1164
1165 char islast(const char* s)
1166 {
1167         return '+';
1168 }
1169
1170 long map_count(const char* s)
1171 {
1172         int c = 0;
1173         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1174         {
1175                 if ((i->second->fd) && (isnick(i->second->nick)) && (!strcasecmp(i->second->server,s))) c++;
1176         }
1177         return c;
1178 }
1179
1180 void createcommand(char* cmd, handlerfunc f, char flags, int minparams,char* source)
1181 {
1182         command_t comm;
1183         /* create the command and push it onto the table */
1184         strlcpy(comm.command,cmd,MAXBUF);
1185         strlcpy(comm.source,source,MAXBUF);
1186         comm.handler_function = f;
1187         comm.flags_needed = flags;
1188         comm.min_params = minparams;
1189         comm.use_count = 0;
1190         comm.total_bytes = 0;
1191         cmdlist.push_back(comm);
1192         log(DEBUG,"Added command %s (%lu parameters)",cmd,(unsigned long)minparams);
1193 }
1194
1195
1196 void SetupCommandTable(void)
1197 {
1198         createcommand("USER",handle_user,0,4,"<core>");
1199         createcommand("NICK",handle_nick,0,1,"<core>");
1200         createcommand("QUIT",handle_quit,0,0,"<core>");
1201         createcommand("VERSION",handle_version,0,0,"<core>");
1202         createcommand("PING",handle_ping,0,1,"<core>");
1203         createcommand("PONG",handle_pong,0,1,"<core>");
1204         createcommand("ADMIN",handle_admin,0,0,"<core>");
1205         createcommand("PRIVMSG",handle_privmsg,0,2,"<core>");
1206         createcommand("INFO",handle_info,0,0,"<core>");
1207         createcommand("TIME",handle_time,0,0,"<core>");
1208         createcommand("WHOIS",handle_whois,0,1,"<core>");
1209         createcommand("WALLOPS",handle_wallops,'o',1,"<core>");
1210         createcommand("NOTICE",handle_notice,0,2,"<core>");
1211         createcommand("JOIN",handle_join,0,1,"<core>");
1212         createcommand("NAMES",handle_names,0,0,"<core>");
1213         createcommand("PART",handle_part,0,1,"<core>");
1214         createcommand("KICK",handle_kick,0,2,"<core>");
1215         createcommand("MODE",handle_mode,0,1,"<core>");
1216         createcommand("TOPIC",handle_topic,0,1,"<core>");
1217         createcommand("WHO",handle_who,0,1,"<core>");
1218         createcommand("MOTD",handle_motd,0,0,"<core>");
1219         createcommand("RULES",handle_rules,0,0,"<core>");
1220         createcommand("OPER",handle_oper,0,2,"<core>");
1221         createcommand("LIST",handle_list,0,0,"<core>");
1222         createcommand("DIE",handle_die,'o',1,"<core>");
1223         createcommand("RESTART",handle_restart,'o',1,"<core>");
1224         createcommand("KILL",handle_kill,'o',2,"<core>");
1225         createcommand("REHASH",handle_rehash,'o',0,"<core>");
1226         createcommand("LUSERS",handle_lusers,0,0,"<core>");
1227         createcommand("STATS",handle_stats,0,1,"<core>");
1228         createcommand("USERHOST",handle_userhost,0,1,"<core>");
1229         createcommand("AWAY",handle_away,0,0,"<core>");
1230         createcommand("ISON",handle_ison,0,0,"<core>");
1231         createcommand("SUMMON",handle_summon,0,0,"<core>");
1232         createcommand("USERS",handle_users,0,0,"<core>");
1233         createcommand("INVITE",handle_invite,0,0,"<core>");
1234         createcommand("PASS",handle_pass,0,1,"<core>");
1235         createcommand("TRACE",handle_trace,'o',0,"<core>");
1236         createcommand("WHOWAS",handle_whowas,0,1,"<core>");
1237         createcommand("CONNECT",handle_connect,'o',1,"<core>");
1238         createcommand("SQUIT",handle_squit,'o',0,"<core>");
1239         createcommand("MODULES",handle_modules,0,0,"<core>");
1240         createcommand("LINKS",handle_links,0,0,"<core>");
1241         createcommand("MAP",handle_map,0,0,"<core>");
1242         createcommand("KLINE",handle_kline,'o',1,"<core>");
1243         createcommand("GLINE",handle_gline,'o',1,"<core>");
1244         createcommand("ZLINE",handle_zline,'o',1,"<core>");
1245         createcommand("QLINE",handle_qline,'o',1,"<core>");
1246         createcommand("ELINE",handle_eline,'o',1,"<core>");
1247         createcommand("LOADMODULE",handle_loadmodule,'o',1,"<core>");
1248         createcommand("UNLOADMODULE",handle_unloadmodule,'o',1,"<core>");
1249         createcommand("SERVER",handle_server,0,0,"<core>");
1250         createcommand("COMMANDS",handle_commands,0,0,"<core>");
1251 }
1252
1253 bool DirValid(char* dirandfile)
1254 {
1255         char work[MAXBUF];
1256         strlcpy(work,dirandfile,MAXBUF);
1257         int p = strlen(work);
1258         // we just want the dir
1259         while (strlen(work))
1260         {
1261                 if (work[p] == '/')
1262                 {
1263                         work[p] = '\0';
1264                         break;
1265                 }
1266                 work[p--] = '\0';
1267         }
1268         char buffer[MAXBUF], otherdir[MAXBUF];
1269         // Get the current working directory
1270         if( getcwd( buffer, MAXBUF ) == NULL )
1271                 return false;
1272         chdir(work);
1273         if( getcwd( otherdir, MAXBUF ) == NULL )
1274                 return false;
1275         chdir(buffer);
1276         if (strlen(otherdir) >= strlen(work))
1277         {
1278                 otherdir[strlen(work)] = '\0';
1279                 if (!strcmp(otherdir,work))
1280                 {
1281                         return true;
1282                 }
1283                 return false;
1284         }
1285         else return false;
1286 }
1287
1288 std::string GetFullProgDir(char** argv, int argc)
1289 {
1290         char work[MAXBUF];
1291         strlcpy(work,argv[0],MAXBUF);
1292         int p = strlen(work);
1293         // we just want the dir
1294         while (strlen(work))
1295         {
1296                 if (work[p] == '/')
1297                 {
1298                         work[p] = '\0';
1299                         break;
1300                 }
1301                 work[p--] = '\0';
1302         }
1303         char buffer[MAXBUF], otherdir[MAXBUF];
1304         // Get the current working directory
1305         if( getcwd( buffer, MAXBUF ) == NULL )
1306                 return "";
1307         chdir(work);
1308         if( getcwd( otherdir, MAXBUF ) == NULL )
1309                 return "";
1310         chdir(buffer);
1311         return otherdir;
1312 }
1313