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