]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/inspircd.cpp
Added support for OnWhois, OnOper, OnInfo and SendToModeMask in the API
[user/henk/code/inspircd.git] / src / inspircd.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 /* Now with added unF! ;) */
18
19 #include "inspircd.h"
20 #include "inspircd_io.h"
21 #include "inspircd_util.h"
22 #include "inspircd_config.h"
23 #include <unistd.h>
24 #include <fcntl.h>
25 #include <sys/errno.h>
26 #include <sys/ioctl.h>
27 #include <sys/utsname.h>
28 #include <cstdio>
29 #include <time.h>
30 #include <string>
31 #ifdef GCC3
32 #include <ext/hash_map>
33 #else
34 #include <hash_map>
35 #endif
36 #include <map>
37 #include <sstream>
38 #include <vector>
39 #include <errno.h>
40 #include <deque>
41 #include "connection.h"
42 #include "users.h"
43 #include "servers.h"
44 #include "ctables.h"
45 #include "globals.h"
46 #include "modules.h"
47 #include "dynamic.h"
48 #include "wildcard.h"
49
50 using namespace std;
51
52 #ifdef GCC3
53 #define nspace __gnu_cxx
54 #else
55 #define nspace std
56 #endif
57
58 int LogLevel = DEFAULT;
59 char ServerName[MAXBUF];
60 char Network[MAXBUF];
61 char ServerDesc[MAXBUF];
62 char AdminName[MAXBUF];
63 char AdminEmail[MAXBUF];
64 char AdminNick[MAXBUF];
65 char diepass[MAXBUF];
66 char restartpass[MAXBUF];
67 char motd[MAXBUF];
68 char rules[MAXBUF];
69 char list[MAXBUF];
70 char PrefixQuit[MAXBUF];
71 char DieValue[MAXBUF];
72 int debugging =  0;
73 int WHOWAS_STALE = 48; // default WHOWAS Entries last 2 days before they go 'stale'
74 int WHOWAS_MAX = 100;  // default 100 people maximum in the WHOWAS list
75 int DieDelay  =  5;
76 time_t startup_time = time(NULL);
77
78 extern vector<Module*> modules;
79 vector<string> module_names;
80 extern vector<ircd_module*> factory;
81 vector<int> fd_reap;
82
83 extern int MODCOUNT;
84
85 bool nofork = false;
86
87 namespace nspace
88 {
89         template<> struct nspace::hash<in_addr>
90         {
91                 size_t operator()(const struct in_addr &a) const
92                 {
93                         size_t q;
94                         memcpy(&q,&a,sizeof(size_t));
95                         return q;
96                 }
97         };
98
99         template<> struct nspace::hash<string>
100         {
101                 size_t operator()(const string &s) const
102                 {
103                         char a[MAXBUF];
104                         static struct hash<const char *> strhash;
105                         strcpy(a,s.c_str());
106                         strlower(a);
107                         return strhash(a);
108                 }
109         };
110 }       
111
112
113 struct StrHashComp
114 {
115
116         bool operator()(const string& s1, const string& s2) const
117         {
118                 char a[MAXBUF],b[MAXBUF];
119                 strcpy(a,s1.c_str());
120                 strcpy(b,s2.c_str());
121                 return (strcasecmp(a,b) == 0);
122         }
123
124 };
125
126 struct InAddr_HashComp
127 {
128
129         bool operator()(const in_addr &s1, const in_addr &s2) const
130         {
131                 size_t q;
132                 size_t p;
133                 
134                 memcpy(&q,&s1,sizeof(size_t));
135                 memcpy(&p,&s2,sizeof(size_t));
136                 
137                 return (q == p);
138         }
139
140 };
141
142
143 typedef nspace::hash_map<std::string, userrec*, nspace::hash<string>, StrHashComp> user_hash;
144 typedef nspace::hash_map<std::string, chanrec*, nspace::hash<string>, StrHashComp> chan_hash;
145 typedef nspace::hash_map<in_addr,string*, nspace::hash<in_addr>, InAddr_HashComp> address_cache;
146 typedef std::deque<command_t> command_table;
147
148 serverrec* me[32];
149 serverrec* servers[255];
150
151 FILE *log_file;
152
153 user_hash clientlist;
154 chan_hash chanlist;
155 user_hash whowas;
156 command_table cmdlist;
157 file_cache MOTD;
158 file_cache RULES;
159 address_cache IP;
160
161 ClassVector Classes;
162
163 struct linger linger = { 0 };
164 char bannerBuffer[MAXBUF];
165 int boundPortCount = 0;
166 int portCount = 0, UDPportCount = 0, ports[MAXSOCKS];
167 int defaultRoute = 0;
168
169 connection C;
170
171 long MyKey = C.GenKey();
172
173 /* prototypes */
174
175 int has_channel(userrec *u, chanrec *c);
176 int usercount(chanrec *c);
177 int usercount_i(chanrec *c);
178 void update_stats_l(int fd,int data_out);
179 char* Passwd(userrec *user);
180 bool IsDenied(userrec *user);
181 void AddWhoWas(userrec* u);
182
183
184 void safedelete(userrec *p)
185 {
186         if (p)
187         {
188                 log(DEBUG,"deleting %s %s %s %s",p->nick,p->ident,p->dhost,p->fullname);
189                 log(DEBUG,"safedelete(userrec*): pointer is safe to delete");
190                 delete p;
191         }
192         else
193         {
194                 log(DEBUG,"safedelete(userrec*): unsafe pointer operation squished");
195         }
196 }
197
198 void safedelete(chanrec *p)
199 {
200         if (p)
201         {
202                 delete p;
203                 log(DEBUG,"safedelete(chanrec*): pointer is safe to delete");
204         }
205         else
206         {
207                 log(DEBUG,"safedelete(chanrec*): unsafe pointer operation squished");
208         }
209 }
210
211
212 void tidystring(char* str)
213 {
214         // strips out double spaces before a : parameter
215         
216         char temp[MAXBUF];
217         bool go_again = true;
218         
219         if (!str)
220         {
221                 return;
222         }
223         
224         while ((str[0] == ' ') && (strlen(str)>0))
225         {
226                 str++;
227         }
228         
229         while (go_again)
230         {
231                 bool noparse = false;
232                 int t = 0, a = 0;
233                 go_again = false;
234                 while (a < strlen(str))
235                 {
236                         if ((a<strlen(str)-1) && (noparse==false))
237                         {
238                                 if ((str[a] == ' ') && (str[a+1] == ' '))
239                                 {
240                                         log(DEBUG,"Tidied extra space out of string: %s",str);
241                                         go_again = true;
242                                         a++;
243                                 }
244                         }
245                         
246                         if (a<strlen(str)-1)
247                         {
248                                 if ((str[a] == ' ') && (str[a+1] == ':'))
249                                 {
250                                         noparse = true;
251                                 }
252                         }
253                         
254                         temp[t++] = str[a++];
255                 }
256                 temp[t] = '\0';
257                 strncpy(str,temp,MAXBUF);
258         }
259 }
260
261 /* chop a string down to 512 characters and preserve linefeed (irc max
262  * line length) */
263
264 void chop(char* str)
265 {
266
267   string temp = str;
268   FOREACH_MOD OnServerRaw(temp,false);
269   const char* str2 = temp.c_str();
270   sprintf(str,"%s",str2);
271   
272
273   if (strlen(str) >= 512)
274   {
275         str[509] = '\r';
276         str[510] = '\n';
277         str[511] = '\0';
278   }
279 }
280
281
282 std::string getservername()
283 {
284         return ServerName;
285 }
286
287 std::string getserverdesc()
288 {
289         return ServerDesc;
290 }
291
292 std::string getnetworkname()
293 {
294         return Network;
295 }
296
297 std::string getadminname()
298 {
299         return AdminName;
300 }
301
302 std::string getadminemail()
303 {
304         return AdminEmail;
305 }
306
307 std::string getadminnick()
308 {
309         return AdminNick;
310 }
311
312 void log(int level,char *text, ...)
313 {
314         char textbuffer[MAXBUF];
315         va_list argsPtr;
316         time_t rawtime;
317         struct tm * timeinfo;
318         if (level < LogLevel)
319                 return;
320
321         time(&rawtime);
322         timeinfo = localtime (&rawtime);
323
324         if (log_file)
325         {
326                 char b[MAXBUF];
327                 va_start (argsPtr, text);
328                 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
329                 va_end(argsPtr);
330                 strcpy(b,asctime(timeinfo));
331                 b[strlen(b)-1] = ':';
332                 fprintf(log_file,"%s %s\n",b,textbuffer);
333                 if (nofork)
334                 {
335                         // nofork enabled? display it on terminal too
336                         printf("%s %s\n",b,textbuffer);
337                 }
338         }
339 }
340
341 void readfile(file_cache &F, const char* fname)
342 {
343   FILE* file;
344   char linebuf[MAXBUF];
345
346   log(DEBUG,"readfile: loading %s",fname);
347   F.clear();
348   file =  fopen(fname,"r");
349   if (file)
350   {
351         while (!feof(file))
352         {
353                 fgets(linebuf,sizeof(linebuf),file);
354                 linebuf[strlen(linebuf)-1]='\0';
355                 if (!strcmp(linebuf,""))
356                 {
357                         strcpy(linebuf,"  ");
358                 }
359                 if (!feof(file))
360                 {
361                         F.push_back(linebuf);
362                 }
363         }
364         fclose(file);
365   }
366   else
367   {
368           log(DEBUG,"readfile: failed to load file: %s",fname);
369   }
370   log(DEBUG,"readfile: loaded %s, %d lines",fname,F.size());
371 }
372
373 void ReadConfig(void)
374 {
375   char dbg[MAXBUF],pauseval[MAXBUF],Value[MAXBUF],timeout[MAXBUF];
376   ConnectClass c;
377
378   ConfValue("server","name",0,ServerName);
379   ConfValue("server","description",0,ServerDesc);
380   ConfValue("server","network",0,Network);
381   ConfValue("admin","name",0,AdminName);
382   ConfValue("admin","email",0,AdminEmail);
383   ConfValue("admin","nick",0,AdminNick);
384   ConfValue("files","motd",0,motd);
385   ConfValue("files","rules",0,rules);
386   ConfValue("power","diepass",0,diepass);
387   ConfValue("power","pause",0,pauseval);
388   ConfValue("power","restartpass",0,restartpass);
389   ConfValue("options","prefixquit",0,PrefixQuit);
390   ConfValue("die","value",0,DieValue);
391   ConfValue("options","loglevel",0,dbg);
392   if (!strcmp(dbg,"debug"))
393         LogLevel = DEBUG;
394   if (!strcmp(dbg,"verbose"))
395         LogLevel = VERBOSE;
396   if (!strcmp(dbg,"default"))
397         LogLevel = DEFAULT;
398   if (!strcmp(dbg,"sparse"))
399         LogLevel = SPARSE;
400   if (!strcmp(dbg,"none"))
401         LogLevel = NONE;
402   readfile(MOTD,motd);
403   log(DEBUG,"Reading message of the day");
404   readfile(RULES,rules);
405   log(DEBUG,"Reading connect classes");
406   Classes.clear();
407   for (int i = 0; i < ConfValueEnum("connect"); i++)
408   {
409         strcpy(Value,"");
410         ConfValue("connect","allow",i,Value);
411         ConfValue("connect","timeout",i,timeout);
412         if (strcmp(Value,""))
413         {
414                 strcpy(c.host,Value);
415                 c.type = CC_ALLOW;
416                 strcpy(Value,"");
417                 ConfValue("connect","password",i,Value);
418                 strcpy(c.pass,Value);
419                 c.registration_timeout = 90; // default is 2 minutes
420                 if (atoi(timeout)>0)
421                 {
422                         c.registration_timeout = atoi(timeout);
423                 }
424                 Classes.push_back(c);
425                 log(DEBUG,"Read connect class type ALLOW, host=%s password=%s",c.host,c.pass);
426         }
427         else
428         {
429                 ConfValue("connect","deny",i,Value);
430                 strcpy(c.host,Value);
431                 c.type = CC_DENY;
432                 Classes.push_back(c);
433                 log(DEBUG,"Read connect class type DENY, host=%s",c.host);
434         }
435         
436   }
437 }
438
439 void Blocking(int s)
440 {
441   int flags;
442   log(DEBUG,"Blocking: %d",s);
443   flags = fcntl(s, F_GETFL, 0);
444   fcntl(s, F_SETFL, flags ^ O_NONBLOCK);
445 }
446
447 void NonBlocking(int s)
448 {
449   int flags;
450   log(DEBUG,"NonBlocking: %d",s);
451   flags = fcntl(s, F_GETFL, 0);
452   fcntl(s, F_SETFL, flags | O_NONBLOCK);
453 }
454
455
456 int CleanAndResolve (char *resolvedHost, const char *unresolvedHost)
457 {
458   struct hostent *hostPtr = NULL;
459   struct in_addr addr;
460
461   memset (resolvedHost, '\0',MAXBUF);
462   if(unresolvedHost == NULL)
463         return(ERROR);
464   if ((inet_aton(unresolvedHost,&addr)) == 0)
465         return(ERROR);
466   hostPtr = gethostbyaddr ((char *)&addr.s_addr,sizeof(addr.s_addr),AF_INET);
467   if (hostPtr != NULL)
468         snprintf(resolvedHost,MAXBUF,"%s",hostPtr->h_name);
469   else
470         snprintf(resolvedHost,MAXBUF,"%s",unresolvedHost);
471   return (TRUE);
472 }
473
474 /* write formatted text to a socket, in same format as printf */
475
476 void Write(int sock,char *text, ...)
477 {
478   if (!text)
479   {
480         log(DEFAULT,"*** BUG *** Write was given an invalid parameter");
481         return;
482   }
483   char textbuffer[MAXBUF];
484   va_list argsPtr;
485   char tb[MAXBUF];
486
487   va_start (argsPtr, text);
488   vsnprintf(textbuffer, MAXBUF, text, argsPtr);
489   va_end(argsPtr);
490   sprintf(tb,"%s\r\n",textbuffer);
491   chop(tb);
492   write(sock,tb,strlen(tb));
493   update_stats_l(sock,strlen(tb)); /* add one line-out to stats L for this fd */
494 }
495
496 /* write a server formatted numeric response to a single socket */
497
498 void WriteServ(int sock, char* text, ...)
499 {
500   if (!text)
501   {
502         log(DEFAULT,"*** BUG *** WriteServ was given an invalid parameter");
503         return;
504   }
505   char textbuffer[MAXBUF],tb[MAXBUF];
506   va_list argsPtr;
507   va_start (argsPtr, text);
508
509   vsnprintf(textbuffer, MAXBUF, text, argsPtr);
510   va_end(argsPtr);
511   sprintf(tb,":%s %s\r\n",ServerName,textbuffer);
512   chop(tb);
513   write(sock,tb,strlen(tb));
514   update_stats_l(sock,strlen(tb)); /* add one line-out to stats L for this fd */
515 }
516
517 /* write text from an originating user to originating user */
518
519 void WriteFrom(int sock, userrec *user,char* text, ...)
520 {
521   if ((!text) || (!user))
522   {
523         log(DEFAULT,"*** BUG *** WriteFrom was given an invalid parameter");
524         return;
525   }
526   char textbuffer[MAXBUF],tb[MAXBUF];
527   va_list argsPtr;
528   va_start (argsPtr, text);
529
530   vsnprintf(textbuffer, MAXBUF, text, argsPtr);
531   va_end(argsPtr);
532   sprintf(tb,":%s!%s@%s %s\r\n",user->nick,user->ident,user->dhost,textbuffer);
533   chop(tb);
534   write(sock,tb,strlen(tb));
535   update_stats_l(sock,strlen(tb)); /* add one line-out to stats L for this fd */
536 }
537
538 /* write text to an destination user from a source user (e.g. user privmsg) */
539
540 void WriteTo(userrec *source, userrec *dest,char *data, ...)
541 {
542         if ((!source) || (!dest) || (!data))
543         {
544                 log(DEFAULT,"*** BUG *** WriteTo was given an invalid parameter");
545                 return;
546         }
547         char textbuffer[MAXBUF],tb[MAXBUF];
548         va_list argsPtr;
549         va_start (argsPtr, data);
550         vsnprintf(textbuffer, MAXBUF, data, argsPtr);
551         va_end(argsPtr);
552         chop(tb);
553         WriteFrom(dest->fd,source,"%s",textbuffer);
554 }
555
556 /* write formatted text from a source user to all users on a channel
557  * including the sender (NOT for privmsg, notice etc!) */
558
559 void WriteChannel(chanrec* Ptr, userrec* user, char* text, ...)
560 {
561         if ((!Ptr) || (!user) || (!text))
562         {
563                 log(DEFAULT,"*** BUG *** WriteChannel was given an invalid parameter");
564                 return;
565         }
566         char textbuffer[MAXBUF];
567         va_list argsPtr;
568         va_start (argsPtr, text);
569         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
570         va_end(argsPtr);
571         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
572         {
573                 if (has_channel(i->second,Ptr))
574                 {
575                         WriteTo(user,i->second,"%s",textbuffer);
576                 }
577         }
578 }
579
580 void WriteChannelWithServ(char* ServerName, chanrec* Ptr, userrec* user, char* text, ...)
581 {
582         if ((!Ptr) || (!user) || (!text))
583         {
584                 log(DEFAULT,"*** BUG *** WriteChannelWithServ was given an invalid parameter");
585                 return;
586         }
587         char textbuffer[MAXBUF];
588         va_list argsPtr;
589         va_start (argsPtr, text);
590         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
591         va_end(argsPtr);
592         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
593         {
594                 if (i->second)
595                 {
596                         if (has_channel(i->second,Ptr))
597                         {
598                                 WriteServ(i->second->fd,"%s",textbuffer);
599                         }
600                 }
601         }
602 }
603
604
605 /* write formatted text from a source user to all users on a channel except
606  * for the sender (for privmsg etc) */
607
608 void ChanExceptSender(chanrec* Ptr, userrec* user, char* text, ...)
609 {
610         if ((!Ptr) || (!user) || (!text))
611         {
612                 log(DEFAULT,"*** BUG *** ChanExceptSender was given an invalid parameter");
613                 return;
614         }
615         char textbuffer[MAXBUF];
616         va_list argsPtr;
617         va_start (argsPtr, text);
618         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
619         va_end(argsPtr);
620
621         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
622         {
623                 if (i->second)
624                 {
625                         if (has_channel(i->second,Ptr) && (user != i->second))
626                         {
627                                 WriteTo(user,i->second,"%s",textbuffer);
628                         }
629                 }
630         }
631 }
632
633 int c_count(userrec* u)
634 {
635         int z = 0;
636         for (int i =0; i != MAXCHANS; i++)
637                 if (u->chans[i].channel != NULL)
638                         z++;
639         return z;
640
641 }
642
643 /* return 0 or 1 depending if users u and u2 share one or more common channels
644  * (used by QUIT, NICK etc which arent channel specific notices) */
645
646 int common_channels(userrec *u, userrec *u2)
647 {
648         int i = 0;
649         int z = 0;
650
651         if ((!u) || (!u2))
652         {
653                 log(DEFAULT,"*** BUG *** common_channels was given an invalid parameter");
654                 return 0;
655         }
656         for (i = 0; i != MAXCHANS; i++)
657         {
658                 for (z = 0; z != MAXCHANS; z++)
659                 {
660                         if ((u->chans[i].channel != NULL) && (u2->chans[z].channel != NULL))
661                         {
662                                 if ((u->chans[i].channel == u2->chans[z].channel) && (u->chans[i].channel) && (u2->chans[z].channel) && (u->registered == 7) && (u2->registered == 7))
663                                 {
664                                         if ((c_count(u)) && (c_count(u2)))
665                                         {
666                                                 return 1;
667                                         }
668                                 }
669                         }
670                 }
671         }
672         return 0;
673 }
674
675 /* write a formatted string to all users who share at least one common
676  * channel, including the source user e.g. for use in NICK */
677
678 void WriteCommon(userrec *u, char* text, ...)
679 {
680         if (!u)
681         {
682                 log(DEFAULT,"*** BUG *** WriteCommon was given an invalid parameter");
683                 return;
684         }
685
686         if (u->registered != 7) {
687                 log(DEFAULT,"*** BUG *** WriteCommon on an unregistered user");
688                 return;
689         }
690         
691         char textbuffer[MAXBUF];
692         va_list argsPtr;
693         va_start (argsPtr, text);
694         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
695         va_end(argsPtr);
696
697         WriteFrom(u->fd,u,"%s",textbuffer);
698
699         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
700         {
701                 if (i->second)
702                 {
703                         if (common_channels(u,i->second) && (i->second != u))
704                         {
705                                 WriteFrom(i->second->fd,u,"%s",textbuffer);
706                         }
707                 }
708         }
709 }
710
711 /* write a formatted string to all users who share at least one common
712  * channel, NOT including the source user e.g. for use in QUIT */
713
714 void WriteCommonExcept(userrec *u, char* text, ...)
715 {
716         if (!u)
717         {
718                 log(DEFAULT,"*** BUG *** WriteCommon was given an invalid parameter");
719                 return;
720         }
721
722         if (u->registered != 7) {
723                 log(DEFAULT,"*** BUG *** WriteCommon on an unregistered user");
724                 return;
725         }
726
727         char textbuffer[MAXBUF];
728         va_list argsPtr;
729         va_start (argsPtr, text);
730         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
731         va_end(argsPtr);
732
733         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
734         {
735                 if (i->second)
736                 {
737                         if ((common_channels(u,i->second)) && (u != i->second))
738                         {
739                                 WriteFrom(i->second->fd,u,"%s",textbuffer);
740                         }
741                 }
742         }
743 }
744
745 void WriteOpers(char* text, ...)
746 {
747         if (!text)
748         {
749                 log(DEFAULT,"*** BUG *** WriteOpers was given an invalid parameter");
750                 return;
751         }
752
753         char textbuffer[MAXBUF];
754         va_list argsPtr;
755         va_start (argsPtr, text);
756         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
757         va_end(argsPtr);
758
759         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
760         {
761                 if (i->second)
762                 {
763                         if (strchr(i->second->modes,'o'))
764                         {
765                                 if (strchr(i->second->modes,'s'))
766                                 {
767                                         // send server notices to all with +s
768                                         // (TODO: needs SNOMASKs)
769                                         WriteServ(i->second->fd,"NOTICE %s :%s",i->second->nick,textbuffer);
770                                 }
771                         }
772                 }
773         }
774 }
775
776 bool hasumode(userrec* user, char mode)
777 {
778         if (user)
779         {
780                 return (strchr(user->modes,mode)>0);
781         }
782         else return false;
783 }
784
785 void WriteMode(const char* modes, int flags, const char* text, ...)
786 {
787         if ((!text) || (!modes) || (!flags))
788         {
789                 log(DEFAULT,"*** BUG *** WriteMode was given an invalid parameter");
790                 return;
791         }
792
793         char textbuffer[MAXBUF];
794         va_list argsPtr;
795         va_start (argsPtr, text);
796         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
797         va_end(argsPtr);
798
799         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
800         {
801                 if (i->second)
802                 {
803                         bool send_to_user = false;
804                         
805                         if (flags == WM_AND)
806                         {
807                                 send_to_user = true;
808                                 for (int n = 0; n < strlen(modes); n++)
809                                 {
810                                         if (!hasumode(i->second,modes[n]))
811                                         {
812                                                 send_to_user = false;
813                                                 break;
814                                         }
815                                 }
816                         }
817                         else if (flags == WM_OR)
818                         {
819                                 send_to_user = false;
820                                 for (int n = 0; n < strlen(modes); n++)
821                                 {
822                                         if (hasumode(i->second,modes[n]))
823                                         {
824                                                 send_to_user = true;
825                                                 break;
826                                         }
827                                 }
828                         }
829
830                         if (send_to_user)
831                         {
832                                 WriteServ(i->second->fd,"NOTICE %s :%s",i->second->nick,textbuffer);
833                         }
834                 }
835         }
836 }
837
838 void WriteWallOps(userrec *source, char* text, ...)  
839 {  
840         if ((!text) || (!source))
841         {
842                 log(DEFAULT,"*** BUG *** WriteOpers was given an invalid parameter");
843                 return;
844         }
845
846         int i = 0;  
847         char textbuffer[MAXBUF];  
848         va_list argsPtr;  
849         va_start (argsPtr, text);  
850         vsnprintf(textbuffer, MAXBUF, text, argsPtr);  
851         va_end(argsPtr);  
852   
853         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
854         {
855                 if (i->second)
856                 {
857                         if (strchr(i->second->modes,'w'))
858                         {  
859                                 WriteTo(source,i->second,"WALLOPS %s",textbuffer);
860                         }
861                 }
862         }
863 }  
864
865 /* convert a string to lowercase. Note following special circumstances
866  * taken from RFC 1459. Many "official" server branches still hold to this
867  * rule so i will too;
868  *
869  *  Because of IRC's scandanavian origin, the characters {}| are
870  *  considered to be the lower case equivalents of the characters []\,
871  *  respectively. This is a critical issue when determining the
872  *  equivalence of two nicknames.
873  */
874
875 void strlower(char *n)
876 {
877         if (!n)
878         {
879                 return;
880         }
881         for (int i = 0; i != strlen(n); i++)
882         {
883                 n[i] = tolower(n[i]);
884                 if (n[i] == '[')
885                         n[i] = '{';
886                 if (n[i] == ']')
887                         n[i] = '}';
888                 if (n[i] == '\\')
889                         n[i] = '|';
890         }
891 }
892
893 /* verify that a user's ident and nickname is valid */
894
895 int isident(const char* n)
896 {
897         int i = 0;
898         char v[MAXBUF];
899         if (!n)
900
901         {
902                 return 0;
903         }
904         if (!strcmp(n,""))
905         {
906                 return 0;
907         }
908         for (i = 0; i != strlen(n); i++)
909         {
910                 if ((n[i] < 33) || (n[i] > 125))
911                 {
912                         return 0;
913                 }
914                 /* can't occur ANYWHERE in an Ident! */
915                 if (strchr("<>,./?:;@'~#=+()*&%$£ \"!",n[i]))
916                 {
917                         return 0;
918                 }
919         }
920         return 1;
921 }
922
923
924 int isnick(const char* n)
925 {
926         int i = 0;
927         char v[MAXBUF];
928         if (!n)
929         {
930                 return 0;
931         }
932         if (!strcmp(n,""))
933         {
934                 return 0;
935         }
936         if (strlen(n) > NICKMAX-1)
937         {
938                 return 0;
939         }
940         for (i = 0; i != strlen(n); i++)
941         {
942                 if ((n[i] < 33) || (n[i] > 125))
943                 {
944                         return 0;
945                 }
946                 /* can't occur ANYWHERE in a nickname! */
947                 if (strchr("<>,./?:;@'~#=+()*&%$£ \"!",n[i]))
948                 {
949                         return 0;
950                 }
951                 /* can't occur as the first char of a nickname... */
952                 if ((strchr("0123456789",n[i])) && (!i))
953                 {
954                         return 0;
955                 }
956         }
957         return 1;
958 }
959
960 /* Find a user record by nickname and return a pointer to it */
961
962 userrec* Find(string nick)
963 {
964         user_hash::iterator iter = clientlist.find(nick);
965
966         if (iter == clientlist.end())
967                 /* Couldn't find it */
968                 return NULL;
969
970         return iter->second;
971 }
972
973 void update_stats_l(int fd,int data_out) /* add one line-out to stats L for this fd */
974 {
975         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
976         {
977                 if (i->second)
978                 {
979                         if (i->second->fd == fd)
980                         {
981                                 i->second->bytes_out+=data_out;
982                                 i->second->cmds_out++;
983                         }
984                 }
985         }
986 }
987
988
989 /* find a channel record by channel name and return a pointer to it */
990
991 chanrec* FindChan(const char* chan)
992 {
993         if (!chan)
994         {
995                 log(DEFAULT,"*** BUG *** Findchan was given an invalid parameter");
996                 return NULL;
997         }
998
999         chan_hash::iterator iter = chanlist.find(chan);
1000
1001         if (iter == chanlist.end())
1002                 /* Couldn't find it */
1003                 return NULL;
1004
1005         return iter->second;
1006 }
1007
1008
1009 void purge_empty_chans(void)
1010 {
1011         int go_again = 1, purge = 0;
1012         
1013         while (go_again)
1014         {
1015                 go_again = 0;
1016                 for (chan_hash::iterator i = chanlist.begin(); i != chanlist.end(); i++)
1017                 {
1018                         if (i->second) {
1019                                 if (!usercount(i->second))
1020                                 {
1021                                         /* kill the record */
1022                                         if (i != chanlist.end())
1023                                         {
1024                                                 log(DEBUG,"del_channel: destroyed: %s",i->second->name);
1025                                                 delete i->second;
1026                                                 chanlist.erase(i);
1027                                                 go_again = 1;
1028                                                 purge++;
1029                                                 break;
1030                                         }
1031                                 }
1032                                 else
1033                                 {
1034                                         log(DEBUG,"skipped purge for %s",i->second->name);
1035                                 }
1036                         }
1037                 }
1038         }
1039         log(DEBUG,"completed channel purge, killed %d",purge);
1040 }
1041
1042 /* returns the status character for a given user on a channel, e.g. @ for op,
1043  * % for halfop etc. If the user has several modes set, the highest mode
1044  * the user has must be returned. */
1045
1046 char* cmode(userrec *user, chanrec *chan)
1047 {
1048         if ((!user) || (!chan))
1049         {
1050                 log(DEFAULT,"*** BUG *** cmode was given an invalid parameter");
1051                 return "";
1052         }
1053
1054         int i;
1055         for (i = 0; i != MAXCHANS; i++)
1056         {
1057                 if ((user->chans[i].channel == chan) && (chan != NULL))
1058                 {
1059                         if ((user->chans[i].uc_modes & UCMODE_OP) > 0)
1060                         {
1061                                 return "@";
1062                         }
1063                         if ((user->chans[i].uc_modes & UCMODE_HOP) > 0)
1064                         {
1065                                 return "%";
1066                         }
1067                         if ((user->chans[i].uc_modes & UCMODE_VOICE) > 0)
1068                         {
1069                                 return "+";
1070                         }
1071                         return "";
1072                 }
1073         }
1074 }
1075
1076 char scratch[MAXBUF];
1077 char sparam[MAXBUF];
1078
1079 char* chanmodes(chanrec *chan)
1080 {
1081         if (!chan)
1082         {
1083                 log(DEFAULT,"*** BUG *** chanmodes was given an invalid parameter");
1084                 strcpy(scratch,"");
1085                 return scratch;
1086         }
1087
1088         strcpy(scratch,"");
1089         strcpy(sparam,"");
1090         if (chan->noexternal)
1091         {
1092                 strncat(scratch,"n",MAXMODES);
1093         }
1094         if (chan->topiclock)
1095         {
1096                 strncat(scratch,"t",MAXMODES);
1097         }
1098         if (strcmp(chan->key,""))
1099         {
1100                 strncat(scratch,"k",MAXMODES);
1101         }
1102         if (chan->limit)
1103         {
1104                 strncat(scratch,"l",MAXMODES);
1105         }
1106         if (chan->inviteonly)
1107         {
1108                 strncat(scratch,"i",MAXMODES);
1109         }
1110         if (chan->moderated)
1111         {
1112                 strncat(scratch,"m",MAXMODES);
1113         }
1114         if (chan->secret)
1115         {
1116                 strncat(scratch,"s",MAXMODES);
1117         }
1118         if (chan->c_private)
1119         {
1120                 strncat(scratch,"p",MAXMODES);
1121         }
1122         if (strcmp(chan->key,""))
1123         {
1124                 strncat(sparam,chan->key,MAXBUF);
1125         }
1126         if (chan->limit)
1127         {
1128                 char foo[24];
1129                 sprintf(foo," %d",chan->limit);
1130                 strncat(sparam,foo,MAXBUF);
1131         }
1132         if (strlen(chan->custom_modes))
1133         {
1134                 strncat(scratch,chan->custom_modes,MAXMODES);
1135                 for (int z = 0; z < strlen(chan->custom_modes); z++)
1136                 {
1137                         std::string extparam = chan->GetModeParameter(chan->custom_modes[z]);
1138                         if (extparam != "")
1139                         {
1140                                 strncat(sparam," ",MAXBUF);
1141                                 strncat(sparam,extparam.c_str(),MAXBUF);
1142                         }
1143                 }
1144         }
1145         log(DEBUG,"chanmodes: %s %s%s",chan->name,scratch,sparam);
1146         strncat(scratch,sparam,MAXMODES);
1147         return scratch;
1148 }
1149
1150 /* returns the status value for a given user on a channel, e.g. STATUS_OP for
1151  * op, STATUS_VOICE for voice etc. If the user has several modes set, the
1152  * highest mode the user has must be returned. */
1153
1154 int cstatus(userrec *user, chanrec *chan)
1155 {
1156         if ((!chan) || (!user))
1157         {
1158                 log(DEFAULT,"*** BUG *** cstatus was given an invalid parameter");
1159                 return 0;
1160         }
1161
1162         int i;
1163         for (i = 0; i != MAXCHANS; i++)
1164         {
1165                 if ((user->chans[i].channel == chan) && (chan != NULL))
1166                 {
1167                         if ((user->chans[i].uc_modes & UCMODE_OP) > 0)
1168                         {
1169                                 return STATUS_OP;
1170                         }
1171                         if ((user->chans[i].uc_modes & UCMODE_HOP) > 0)
1172                         {
1173                                 return STATUS_HOP;
1174                         }
1175                         if ((user->chans[i].uc_modes & UCMODE_VOICE) > 0)
1176                         {
1177                                 return STATUS_VOICE;
1178                         }
1179                         return STATUS_NORMAL;
1180                 }
1181         }
1182 }
1183
1184
1185 /* compile a userlist of a channel into a string, each nick seperated by
1186  * spaces and op, voice etc status shown as @ and + */
1187
1188 void userlist(userrec *user,chanrec *c)
1189 {
1190         if ((!c) || (!user))
1191         {
1192                 log(DEFAULT,"*** BUG *** userlist was given an invalid parameter");
1193                 return;
1194         }
1195
1196         sprintf(list,"353 %s = %s :", user->nick, c->name);
1197         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1198         {
1199                 if (has_channel(i->second,c))
1200                 {
1201                         if (isnick(i->second->nick))
1202                         {
1203                                 if ((!has_channel(i->second,c)) && (strchr(i->second->modes,'i')))
1204                                 {
1205                                         /* user is +i, and source not on the channel, does not show
1206                                          * nick in NAMES list */
1207                                         continue;
1208                                 }
1209                                 strcat(list,cmode(i->second,c));
1210                                 strcat(list,i->second->nick);
1211                                 strcat(list," ");
1212                                 if (strlen(list)>(480-NICKMAX))
1213                                 {
1214                                         /* list overflowed into
1215                                          * multiple numerics */
1216                                         WriteServ(user->fd,list);
1217                                         sprintf(list,"353 %s = %s :", user->nick, c->name);
1218                                 }
1219                         }
1220                 }
1221         }
1222         /* if whats left in the list isnt empty, send it */
1223         if (list[strlen(list)-1] != ':')
1224         {
1225                 WriteServ(user->fd,list);
1226         }
1227 }
1228
1229 /* return a count of the users on a specific channel accounting for
1230  * invisible users who won't increase the count. e.g. for /LIST */
1231
1232 int usercount_i(chanrec *c)
1233 {
1234         int i = 0;
1235         int count = 0;
1236         
1237         if (!c)
1238         {
1239                 log(DEFAULT,"*** BUG *** usercount_i was given an invalid parameter");
1240                 return 0;
1241         }
1242
1243         strcpy(list,"");
1244         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1245         {
1246                 if (i->second)
1247                 {
1248                         if (has_channel(i->second,c))
1249                         {
1250                                 if (isnick(i->second->nick))
1251                                 {
1252                                         if ((!has_channel(i->second,c)) && (strchr(i->second->modes,'i')))
1253                                         {
1254                                                 /* user is +i, and source not on the channel, does not show
1255                                                  * nick in NAMES list */
1256                                                 continue;
1257                                         }
1258                                         count++;
1259                                 }
1260                         }
1261                 }
1262         }
1263         log(DEBUG,"usercount_i: %s %d",c->name,count);
1264         return count;
1265 }
1266
1267
1268 int usercount(chanrec *c)
1269 {
1270         int i = 0;
1271         int count = 0;
1272         
1273         if (!c)
1274         {
1275                 log(DEFAULT,"*** BUG *** usercount was given an invalid parameter");
1276                 return 0;
1277         }
1278
1279         strcpy(list,"");
1280         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1281         {
1282                 if (i->second)
1283                 {
1284                         if (has_channel(i->second,c))
1285                         {
1286                                 if ((isnick(i->second->nick)) && (i->second->registered == 7))
1287                                 {
1288                                         count++;
1289                                 }
1290                         }
1291                 }
1292         }
1293         log(DEBUG,"usercount: %s %d",c->name,count);
1294         return count;
1295 }
1296
1297
1298 /* add a channel to a user, creating the record for it if needed and linking
1299  * it to the user record */
1300
1301 chanrec* add_channel(userrec *user, char* cname, char* key)
1302 {
1303
1304         if ((!user) || (!cname))
1305         {
1306                 log(DEFAULT,"*** BUG *** add_channel was given an invalid parameter");
1307                 return 0;
1308         }
1309
1310         int i = 0;
1311         chanrec* Ptr;
1312         int created = 0;
1313         
1314         // we MUST declare this wherever we use FOREACH_RESULT
1315         int MOD_RESULT = 0;
1316
1317         if ((!cname) || (!user))
1318         {
1319                 return NULL;
1320         }
1321         if (strlen(cname) > CHANMAX-1)
1322         {
1323                 cname[CHANMAX-1] = '\0';
1324         }
1325
1326         log(DEBUG,"add_channel: %s %s",user->nick,cname);
1327         
1328         if ((FindChan(cname)) && (has_channel(user,FindChan(cname))))
1329         {
1330                 return NULL; // already on the channel!
1331         }
1332
1333
1334         if (!FindChan(cname))
1335         {
1336                 FOREACH_RESULT(OnUserPreJoin(user,NULL,cname));
1337                 if (MOD_RESULT) {
1338                         return NULL;
1339                 }
1340
1341                 /* create a new one */
1342                 log(DEBUG,"add_channel: creating: %s",cname);
1343                 {
1344                         chanlist[cname] = new chanrec();
1345
1346                         strcpy(chanlist[cname]->name, cname);
1347                         chanlist[cname]->topiclock = 1;
1348                         chanlist[cname]->noexternal = 1;
1349                         chanlist[cname]->created = time(NULL);
1350                         strcpy(chanlist[cname]->topic, "");
1351                         strncpy(chanlist[cname]->setby, user->nick,NICKMAX);
1352                         chanlist[cname]->topicset = 0;
1353                         Ptr = chanlist[cname];
1354                         log(DEBUG,"add_channel: created: %s",cname);
1355                         /* set created to 2 to indicate user
1356                          * is the first in the channel
1357                          * and should be given ops */
1358                         created = 2;
1359                 }
1360         }
1361         else
1362         {
1363                 /* channel exists, just fish out a pointer to its struct */
1364                 Ptr = FindChan(cname);
1365                 if (Ptr)
1366                 {
1367                         FOREACH_RESULT(OnUserPreJoin(user,Ptr,cname));
1368                         if (MOD_RESULT) {
1369                                 return NULL;
1370                         }
1371                         
1372                         log(DEBUG,"add_channel: joining to: %s",Ptr->name);
1373                         if (strcmp(Ptr->key,""))
1374                         {
1375                                 log(DEBUG,"add_channel: %s has key %s",Ptr->name,Ptr->key);
1376                                 if (!key)
1377                                 {
1378                                         log(DEBUG,"add_channel: no key given in JOIN");
1379                                         WriteServ(user->fd,"475 %s %s :Cannot join channel (Requires key)",user->nick, Ptr->name);
1380                                         return NULL;
1381                                 }
1382                                 else
1383                                 {
1384                                         log(DEBUG,"key at %p is %s",key,key);
1385                                         if (strcasecmp(key,Ptr->key))
1386                                         {
1387                                                 log(DEBUG,"add_channel: bad key given in JOIN");
1388                                                 WriteServ(user->fd,"475 %s %s :Cannot join channel (Incorrect key)",user->nick, Ptr->name);
1389                                                 return NULL;
1390                                         }
1391                                 }
1392                         }
1393                         log(DEBUG,"add_channel: no key");
1394
1395                         if (Ptr->inviteonly)
1396                         {
1397                                 log(DEBUG,"add_channel: channel is +i");
1398                                 if (user->IsInvited(Ptr->name))
1399                                 {
1400                                         /* user was invited to channel */
1401                                         /* there may be an optional channel NOTICE here */
1402                                 }
1403                                 else
1404                                 {
1405                                         WriteServ(user->fd,"473 %s %s :Cannot join channel (Invite only)",user->nick, Ptr->name);
1406                                         return NULL;
1407                                 }
1408                         }
1409                         log(DEBUG,"add_channel: channel is not +i");
1410
1411                         if (Ptr->limit)
1412                         {
1413                                 if (usercount(Ptr) == Ptr->limit)
1414                                 {
1415                                         WriteServ(user->fd,"471 %s %s :Cannot join channel (Channel is full)",user->nick, Ptr->name);
1416                                         return NULL;
1417                                 }
1418                         }
1419                         
1420                         log(DEBUG,"add_channel: about to walk banlist");
1421
1422                         /* check user against the channel banlist */
1423                         for (BanList::iterator i = Ptr->bans.begin(); i != Ptr->bans.end(); i++)
1424                         {
1425                                 if (match(user->GetFullHost(),i->data))
1426                                 {
1427                                         WriteServ(user->fd,"474 %s %s :Cannot join channel (You're banned)",user->nick, Ptr->name);
1428                                         return NULL;
1429                                 }
1430                         }
1431
1432                         log(DEBUG,"add_channel: bans checked");
1433
1434                         user->RemoveInvite(Ptr->name);
1435
1436                         log(DEBUG,"add_channel: invites removed");
1437                         
1438                 }
1439                 created = 1;
1440         }
1441
1442         log(DEBUG,"Passed channel checks");
1443         
1444         for (i =0; i != MAXCHANS; i++)
1445         {
1446                 if (user->chans[i].channel == NULL)
1447                 {
1448                         log(DEBUG,"Adding into their channel list");
1449
1450                         if (created == 2) 
1451                         {
1452                                 /* first user in is given ops */
1453                                 user->chans[i].uc_modes = UCMODE_OP;
1454                         }
1455                         else
1456                         {
1457                                 user->chans[i].uc_modes = 0;
1458                         }
1459                         user->chans[i].channel = Ptr;
1460                         WriteChannel(Ptr,user,"JOIN :%s",Ptr->name);
1461
1462                         log(DEBUG,"Sent JOIN to client");
1463
1464                         if (Ptr->topicset)
1465                         {
1466                                 WriteServ(user->fd,"332 %s %s :%s", user->nick, Ptr->name, Ptr->topic);
1467                                 WriteServ(user->fd,"333 %s %s %s %d", user->nick, Ptr->name, Ptr->setby, Ptr->topicset);
1468                         }
1469                         userlist(user,Ptr);
1470                         WriteServ(user->fd,"366 %s %s :End of /NAMES list.", user->nick, Ptr->name);
1471                         WriteServ(user->fd,"324 %s %s +%s",user->nick, Ptr->name,chanmodes(Ptr));
1472                         WriteServ(user->fd,"329 %s %s %d", user->nick, Ptr->name, Ptr->created);
1473                         FOREACH_MOD OnUserJoin(user,Ptr);
1474                         return Ptr;
1475                 }
1476         }
1477         log(DEBUG,"add_channel: user channel max exceeded: %s %s",user->nick,cname);
1478         WriteServ(user->fd,"405 %s %s :You are on too many channels",user->nick, cname);
1479         return NULL;
1480 }
1481
1482 /* remove a channel from a users record, and remove the record from memory
1483  * if the channel has become empty */
1484
1485 chanrec* del_channel(userrec *user, char* cname, char* reason)
1486 {
1487         if ((!user) || (!cname))
1488         {
1489                 log(DEFAULT,"*** BUG *** del_channel was given an invalid parameter");
1490                 return NULL;
1491         }
1492
1493         int i = 0;
1494         chanrec* Ptr;
1495         int created = 0;
1496
1497         if ((!cname) || (!user))
1498         {
1499                 return NULL;
1500         }
1501
1502         Ptr = FindChan(cname);
1503         
1504         if (!Ptr)
1505         {
1506                 return NULL;
1507         }
1508
1509         FOREACH_MOD OnUserPart(user,Ptr);
1510         log(DEBUG,"del_channel: removing: %s %s",user->nick,Ptr->name);
1511         
1512         for (i =0; i != MAXCHANS; i++)
1513         {
1514                 /* zap it from the channel list of the user */
1515                 if (user->chans[i].channel == Ptr)
1516                 {
1517                         if (reason)
1518                         {
1519                                 WriteChannel(Ptr,user,"PART %s :%s",Ptr->name, reason);
1520                         }
1521                         else
1522                         {
1523                                 WriteChannel(Ptr,user,"PART :%s",Ptr->name);
1524                         }
1525                         user->chans[i].uc_modes = 0;
1526                         user->chans[i].channel = NULL;
1527                         log(DEBUG,"del_channel: unlinked: %s %s",user->nick,Ptr->name);
1528                         break;
1529                 }
1530         }
1531         
1532         /* if there are no users left on the channel */
1533         if (!usercount(Ptr))
1534         {
1535                 chan_hash::iterator iter = chanlist.find(Ptr->name);
1536
1537                 log(DEBUG,"del_channel: destroying channel: %s",Ptr->name);
1538
1539                 /* kill the record */
1540                 if (iter != chanlist.end())
1541                 {
1542                         log(DEBUG,"del_channel: destroyed: %s",Ptr->name);
1543                         delete iter->second;
1544                         chanlist.erase(iter);
1545                 }
1546         }
1547 }
1548
1549
1550 void kick_channel(userrec *src,userrec *user, chanrec *Ptr, char* reason)
1551 {
1552         if ((!src) || (!user) || (!Ptr) || (!reason))
1553         {
1554                 log(DEFAULT,"*** BUG *** kick_channel was given an invalid parameter");
1555                 return;
1556         }
1557
1558         int i = 0;
1559         int created = 0;
1560
1561         if ((!Ptr) || (!user) || (!src))
1562         {
1563                 return;
1564         }
1565
1566         log(DEBUG,"kick_channel: removing: %s %s %s",user->nick,Ptr->name,src->nick);
1567
1568         if (!has_channel(user,Ptr))
1569         {
1570                 WriteServ(src->fd,"441 %s %s %s :They are not on that channel",src->nick, user->nick, Ptr->name);
1571                 return;
1572         }
1573         if ((cstatus(src,Ptr) < STATUS_HOP) || (cstatus(src,Ptr) < cstatus(user,Ptr)))
1574         {
1575                 if (cstatus(src,Ptr) == STATUS_HOP)
1576                 {
1577                         WriteServ(src->fd,"482 %s %s :You must be a channel operator",src->nick, Ptr->name);
1578                 }
1579                 else
1580                 {
1581                         WriteServ(src->fd,"482 %s %s :You must be at least a half-operator",src->nick, Ptr->name);
1582                 }
1583                 
1584                 return;
1585         }
1586         
1587         for (i =0; i != MAXCHANS; i++)
1588         {
1589                 /* zap it from the channel list of the user */
1590                 if (user->chans[i].channel == Ptr)
1591                 {
1592                         WriteChannel(Ptr,src,"KICK %s %s :%s",Ptr->name, user->nick, reason);
1593                         user->chans[i].uc_modes = 0;
1594                         user->chans[i].channel = NULL;
1595                         log(DEBUG,"del_channel: unlinked: %s %s",user->nick,Ptr->name);
1596                         break;
1597                 }
1598         }
1599         
1600         /* if there are no users left on the channel */
1601         if (!usercount(Ptr))
1602         {
1603                 chan_hash::iterator iter = chanlist.find(Ptr->name);
1604
1605                 log(DEBUG,"del_channel: destroying channel: %s",Ptr->name);
1606
1607                 /* kill the record */
1608                 if (iter != chanlist.end())
1609                 {
1610                         log(DEBUG,"del_channel: destroyed: %s",Ptr->name);
1611                         delete iter->second;
1612                         chanlist.erase(iter);
1613                 }
1614         }
1615 }
1616
1617
1618 /* returns 1 if user u has channel c in their record, 0 if not */
1619
1620 int has_channel(userrec *u, chanrec *c)
1621 {
1622         int i = 0;
1623
1624         if ((!u) || (!c))
1625         {
1626                 log(DEFAULT,"*** BUG *** has_channel was given an invalid parameter");
1627                 return 0;
1628         }
1629         for (i =0; i != MAXCHANS; i++)
1630         {
1631                 if (u->chans[i].channel == c)
1632                 {
1633                         return 1;
1634                 }
1635         }
1636         return 0;
1637 }
1638
1639 int give_ops(userrec *user,char *dest,chanrec *chan,int status)
1640 {
1641         userrec *d;
1642         int i;
1643         
1644         if ((!user) || (!dest) || (!chan))
1645         {
1646                 log(DEFAULT,"*** BUG *** give_ops was given an invalid parameter");
1647                 return 0;
1648         }
1649         if (status != STATUS_OP)
1650         {
1651                 WriteServ(user->fd,"482 %s %s :You're not a channel operator",user->nick, chan->name);
1652                 return 0;
1653         }
1654         else
1655         {
1656                 if (!isnick(dest))
1657                 {
1658                         WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1659                         return 0;
1660                 }
1661                 d = Find(dest);
1662                 if (!d)
1663                 {
1664                         WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1665                         return 0;
1666                 }
1667                 else
1668                 {
1669                         for (i = 0; i != MAXCHANS; i++)
1670                         {
1671                                 if ((d->chans[i].channel == chan) && (chan != NULL))
1672                                 {
1673                                         if (d->chans[i].uc_modes & UCMODE_OP)
1674                                         {
1675                                                 /* mode already set on user, dont allow multiple */
1676                                                 return 0;
1677                                         }
1678                                         d->chans[i].uc_modes = d->chans[i].uc_modes | UCMODE_OP;
1679                                         log(DEBUG,"gave ops: %s %s",d->chans[i].channel->name,d->nick);
1680                                 }
1681                         }
1682                 }
1683         }
1684         return 1;
1685 }
1686
1687 int give_hops(userrec *user,char *dest,chanrec *chan,int status)
1688 {
1689         userrec *d;
1690         int i;
1691         
1692         if ((!user) || (!dest) || (!chan))
1693         {
1694                 log(DEFAULT,"*** BUG *** give_hops was given an invalid parameter");
1695                 return 0;
1696         }
1697         if (status != STATUS_OP)
1698         {
1699                 WriteServ(user->fd,"482 %s %s :You're not a channel operator",user->nick, chan->name);
1700                 return 0;
1701         }
1702         else
1703         {
1704                 d = Find(dest);
1705                 if (!isnick(dest))
1706                 {
1707                         WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1708                         return 0;
1709                 }
1710                 if (!d)
1711                 {
1712                         WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1713                         return 0;
1714                 }
1715                 else
1716                 {
1717                         for (i = 0; i != MAXCHANS; i++)
1718                         {
1719                                 if ((d->chans[i].channel == chan) && (chan != NULL))
1720                                 {
1721                                         if (d->chans[i].uc_modes & UCMODE_HOP)
1722                                         {
1723                                                 /* mode already set on user, dont allow multiple */
1724                                                 return 0;
1725                                         }
1726                                         d->chans[i].uc_modes = d->chans[i].uc_modes | UCMODE_HOP;
1727                                         log(DEBUG,"gave h-ops: %s %s",d->chans[i].channel->name,d->nick);
1728                                 }
1729                         }
1730                 }
1731         }
1732         return 1;
1733 }
1734
1735 int give_voice(userrec *user,char *dest,chanrec *chan,int status)
1736 {
1737         userrec *d;
1738         int i;
1739         
1740         if ((!user) || (!dest) || (!chan))
1741         {
1742                 log(DEFAULT,"*** BUG *** give_voice was given an invalid parameter");
1743                 return 0;
1744         }
1745         if (status < STATUS_HOP)
1746         {
1747                 WriteServ(user->fd,"482 %s %s :You must be at least a half-operator",user->nick, chan->name);
1748                 return 0;
1749         }
1750         else
1751         {
1752                 d = Find(dest);
1753                 if (!isnick(dest))
1754                 {
1755                         WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1756                         return 0;
1757                 }
1758                 if (!d)
1759                 {
1760                         WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1761                         return 0;
1762                 }
1763                 else
1764                 {
1765                         for (i = 0; i != MAXCHANS; i++)
1766                         {
1767                                 if ((d->chans[i].channel == chan) && (chan != NULL))
1768                                 {
1769                                         if (d->chans[i].uc_modes & UCMODE_VOICE)
1770                                         {
1771                                                 /* mode already set on user, dont allow multiple */
1772                                                 return 0;
1773                                         }
1774                                         d->chans[i].uc_modes = d->chans[i].uc_modes | UCMODE_VOICE;
1775                                         log(DEBUG,"gave voice: %s %s",d->chans[i].channel->name,d->nick);
1776                                 }
1777                         }
1778                 }
1779         }
1780         return 1;
1781 }
1782
1783 int take_ops(userrec *user,char *dest,chanrec *chan,int status)
1784 {
1785         userrec *d;
1786         int i;
1787         
1788         if ((!user) || (!dest) || (!chan))
1789         {
1790                 log(DEFAULT,"*** BUG *** take_ops was given an invalid parameter");
1791                 return 0;
1792         }
1793         if (status != STATUS_OP)
1794         {
1795                 WriteServ(user->fd,"482 %s %s :You're not a channel operator",user->nick, chan->name);
1796                 return 0;
1797         }
1798         else
1799         {
1800                 d = Find(dest);
1801                 if (!isnick(dest))
1802                 {
1803                         WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1804                         return 0;
1805                 }
1806                 if (!d)
1807                 {
1808                         WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1809                         return 0;
1810                 }
1811                 else
1812                 {
1813                         for (i = 0; i != MAXCHANS; i++)
1814                         {
1815                                 if ((d->chans[i].channel == chan) && (chan != NULL))
1816                                 {
1817                                         if ((d->chans[i].uc_modes & UCMODE_OP) == 0)
1818                                         {
1819                                                 /* mode already set on user, dont allow multiple */
1820                                                 return 0;
1821                                         }
1822                                         d->chans[i].uc_modes ^= UCMODE_OP;
1823                                         log(DEBUG,"took ops: %s %s",d->chans[i].channel->name,d->nick);
1824                                 }
1825                         }
1826                 }
1827         }
1828         return 1;
1829 }
1830
1831 int take_hops(userrec *user,char *dest,chanrec *chan,int status)
1832 {
1833         userrec *d;
1834         int i;
1835         
1836         if ((!user) || (!dest) || (!chan))
1837         {
1838                 log(DEFAULT,"*** BUG *** take_hops was given an invalid parameter");
1839                 return 0;
1840         }
1841         if (status != STATUS_OP)
1842         {
1843                 WriteServ(user->fd,"482 %s %s :You're not a channel operator",user->nick, chan->name);
1844                 return 0;
1845         }
1846         else
1847         {
1848                 d = Find(dest);
1849                 if (!isnick(dest))
1850                 {
1851                         WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1852                         return 0;
1853                 }
1854                 if (!d)
1855                 {
1856                         WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1857                         return 0;
1858                 }
1859                 else
1860                 {
1861                         for (i = 0; i != MAXCHANS; i++)
1862                         {
1863                                 if ((d->chans[i].channel == chan) && (chan != NULL))
1864                                 {
1865                                         if ((d->chans[i].uc_modes & UCMODE_HOP) == 0)
1866                                         {
1867                                                 /* mode already set on user, dont allow multiple */
1868                                                 return 0;
1869                                         }
1870                                         d->chans[i].uc_modes ^= UCMODE_HOP;
1871                                         log(DEBUG,"took h-ops: %s %s",d->chans[i].channel->name,d->nick);
1872                                 }
1873                         }
1874                 }
1875         }
1876         return 1;
1877 }
1878
1879 int take_voice(userrec *user,char *dest,chanrec *chan,int status)
1880 {
1881         userrec *d;
1882         int i;
1883         
1884         if ((!user) || (!dest) || (!chan))
1885         {
1886                 log(DEFAULT,"*** BUG *** take_voice was given an invalid parameter");
1887                 return 0;
1888         }
1889         if (status < STATUS_HOP)
1890         {
1891                 WriteServ(user->fd,"482 %s %s :You must be at least a half-operator",user->nick, chan->name);
1892                 return 0;
1893         }
1894         else
1895         {
1896                 d = Find(dest);
1897                 if (!isnick(dest))
1898                 {
1899                         WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1900                         return 0;
1901                 }
1902                 if (!d)
1903                 {
1904                         WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1905                         return 0;
1906                 }
1907                 else
1908                 {
1909                         for (i = 0; i != MAXCHANS; i++)
1910                         {
1911                                 if ((d->chans[i].channel == chan) && (chan != NULL))
1912                                 {
1913                                         if ((d->chans[i].uc_modes & UCMODE_VOICE) == 0)
1914                                         {
1915                                                 /* mode already set on user, dont allow multiple */
1916                                                 return 0;
1917                                         }
1918                                         d->chans[i].uc_modes ^= UCMODE_VOICE;
1919                                         log(DEBUG,"took voice: %s %s",d->chans[i].channel->name,d->nick);
1920                                 }
1921                         }
1922                 }
1923         }
1924         return 1;
1925 }
1926
1927 void TidyBan(char *ban)
1928 {
1929         if (!ban) {
1930                 log(DEFAULT,"*** BUG *** TidyBan was given an invalid parameter");
1931                 return;
1932         }
1933         
1934         char temp[MAXBUF],NICK[MAXBUF],IDENT[MAXBUF],HOST[MAXBUF];
1935
1936         strcpy(temp,ban);
1937
1938         char* pos_of_pling = strchr(temp,'!');
1939         char* pos_of_at = strchr(temp,'@');
1940
1941         pos_of_pling[0] = '\0';
1942         pos_of_at[0] = '\0';
1943         pos_of_pling++;
1944         pos_of_at++;
1945
1946         strncpy(NICK,temp,NICKMAX);
1947         strncpy(IDENT,pos_of_pling,IDENTMAX+1);
1948         strncpy(HOST,pos_of_at,160);
1949
1950         sprintf(ban,"%s!%s@%s",NICK,IDENT,HOST);
1951 }
1952
1953 int add_ban(userrec *user,char *dest,chanrec *chan,int status)
1954 {
1955         if ((!user) || (!dest) || (!chan)) {
1956                 log(DEFAULT,"*** BUG *** add_ban was given an invalid parameter");
1957                 return 0;
1958         }
1959
1960         BanItem b;
1961         if ((!user) || (!dest) || (!chan))
1962                 return 0;
1963         if (strchr(dest,'!')==0)
1964                 return 0;
1965         if (strchr(dest,'@')==0)
1966                 return 0;
1967         for (int i = 0; i < strlen(dest); i++)
1968                 if (dest[i] < 32)
1969                         return 0;
1970         for (int i = 0; i < strlen(dest); i++)
1971                 if (dest[i] > 126)
1972                         return 0;
1973         int c = 0;
1974         for (int i = 0; i < strlen(dest); i++)
1975                 if (dest[i] == '!')
1976                         c++;
1977         if (c>1)
1978                 return 0;
1979         c = 0;
1980         for (int i = 0; i < strlen(dest); i++)
1981                 if (dest[i] == '@')
1982                         c++;
1983         if (c>1)
1984                 return 0;
1985         log(DEBUG,"add_ban: %s %s",chan->name,user->nick);
1986
1987         TidyBan(dest);
1988         for (BanList::iterator i = chan->bans.begin(); i != chan->bans.end(); i++)
1989         {
1990                 if (!strcasecmp(i->data,dest))
1991                 {
1992                         // dont allow a user to set the same ban twice
1993                         return 0;
1994                 }
1995         }
1996
1997         b.set_time = time(NULL);
1998         strncpy(b.data,dest,MAXBUF);
1999         strncpy(b.set_by,user->nick,NICKMAX);
2000         chan->bans.push_back(b);
2001         return 1;
2002 }
2003
2004 int take_ban(userrec *user,char *dest,chanrec *chan,int status)
2005 {
2006         if ((!user) || (!dest) || (!chan)) {
2007                 log(DEFAULT,"*** BUG *** take_ban was given an invalid parameter");
2008                 return 0;
2009         }
2010
2011         log(DEBUG,"del_ban: %s %s",chan->name,user->nick);
2012         for (BanList::iterator i = chan->bans.begin(); i != chan->bans.end(); i++)
2013         {
2014                 if (!strcasecmp(i->data,dest))
2015                 {
2016                         chan->bans.erase(i);
2017                         return 1;
2018                 }
2019         }
2020         return 0;
2021 }
2022
2023 void process_modes(char **parameters,userrec* user,chanrec *chan,int status, int pcnt, bool servermode)
2024 {
2025         if ((!parameters) || (!user)) {
2026                 log(DEFAULT,"*** BUG *** process_modes was given an invalid parameter");
2027                 return;
2028         }
2029
2030
2031         char modelist[MAXBUF];
2032         char outlist[MAXBUF];
2033         char outstr[MAXBUF];
2034         char outpars[32][MAXBUF];
2035         int param = 2;
2036         int pc = 0;
2037         int ptr = 0;
2038         int mdir = 1;
2039         int r = 0;
2040         bool k_set = false, l_set = false;
2041
2042         if (pcnt < 2)
2043         {
2044                 return;
2045         }
2046
2047         log(DEBUG,"process_modes: start");
2048
2049         strcpy(modelist,parameters[1]); /* mode list, e.g. +oo-o */
2050                                         /* parameters[2] onwards are parameters for
2051                                          * modes that require them :) */
2052         strcpy(outlist,"+");
2053         mdir = 1;
2054
2055         log(DEBUG,"process_modes: modelist: %s",modelist);
2056
2057         for (ptr = 0; ptr < strlen(modelist); ptr++)
2058         {
2059                 r = 0;
2060
2061                 {
2062                         log(DEBUG,"process_modes: modechar: %c",modelist[ptr]);
2063                         char modechar = modelist[ptr];
2064                         switch (modelist[ptr])
2065                         {
2066                                 case '-':
2067                                         if (mdir != 0)
2068                                         {
2069                                                 if ((outlist[strlen(outlist)-1] == '+') || (outlist[strlen(outlist)-1] == '-'))
2070                                                 {
2071                                                         outlist[strlen(outlist)-1] = '-';
2072                                                 }
2073                                                 else
2074                                                 {
2075                                                         strcat(outlist,"-");
2076                                                 }
2077                                         }
2078                                         mdir = 0;
2079                                         
2080                                 break;                  
2081
2082                                 case '+':
2083                                         if (mdir != 1)
2084                                         {
2085                                                 if ((outlist[strlen(outlist)-1] == '+') || (outlist[strlen(outlist)-1] == '-'))
2086                                                 {
2087                                                         outlist[strlen(outlist)-1] = '+';
2088                                                 }
2089                                                 else
2090                                                 {
2091                                                         strcat(outlist,"+");
2092                                                 }
2093                                         }
2094                                         mdir = 1;
2095                                 break;
2096
2097                                 case 'o':
2098                                         if ((param >= pcnt)) break;
2099                                         if (mdir == 1)
2100                                         {
2101                                                 r = give_ops(user,parameters[param++],chan,status);
2102                                         }
2103                                         else
2104                                         {
2105                                                 r = take_ops(user,parameters[param++],chan,status);
2106                                         }
2107                                         if (r)
2108                                         {
2109                                                 strcat(outlist,"o");
2110                                                 strcpy(outpars[pc++],parameters[param-1]);
2111                                         }
2112                                 break;
2113                         
2114                                 case 'h':
2115                                         if ((param >= pcnt)) break;
2116                                         if (mdir == 1)
2117                                         {
2118                                                 r = give_hops(user,parameters[param++],chan,status);
2119                                         }
2120                                         else
2121                                         {
2122                                                 r = take_hops(user,parameters[param++],chan,status);
2123                                         }
2124                                         if (r)
2125                                         {
2126                                                 strcat(outlist,"h");
2127                                                 strcpy(outpars[pc++],parameters[param-1]);
2128                                         }
2129                                 break;
2130                         
2131                                 
2132                                 case 'v':
2133                                         if ((param >= pcnt)) break;
2134                                         if (mdir == 1)
2135                                         {
2136                                                 r = give_voice(user,parameters[param++],chan,status);
2137                                         }
2138                                         else
2139                                         {
2140                                                 r = take_voice(user,parameters[param++],chan,status);
2141                                         }
2142                                         if (r)
2143                                         {
2144                                                 strcat(outlist,"v");
2145                                                 strcpy(outpars[pc++],parameters[param-1]);
2146                                         }
2147                                 break;
2148                                 
2149                                 case 'b':
2150                                         if ((param >= pcnt)) break;
2151                                         if (mdir == 1)
2152                                         {
2153                                                 r = add_ban(user,parameters[param++],chan,status);
2154                                         }
2155                                         else
2156                                         {
2157                                                 r = take_ban(user,parameters[param++],chan,status);
2158                                         }
2159                                         if (r)
2160                                         {
2161                                                 strcat(outlist,"b");
2162                                                 strcpy(outpars[pc++],parameters[param-1]);
2163                                         }
2164                                 break;
2165
2166
2167                                 case 'k':
2168                                         if ((param >= pcnt))
2169                                                 break;
2170
2171                                         if (mdir == 1)
2172                                         {
2173                                                 if (k_set)
2174                                                         break;
2175                                                 
2176                                                 if (!strcmp(chan->key,""))
2177                                                 {
2178                                                         strcat(outlist,"k");
2179                                                         char key[MAXBUF];
2180                                                         strcpy(key,parameters[param++]);
2181                                                         if (strlen(key)>32) {
2182                                                                 key[31] = '\0';
2183                                                         }
2184                                                         strcpy(outpars[pc++],key);
2185                                                         strcpy(chan->key,key);
2186                                                         k_set = true;
2187                                                 }
2188                                         }
2189                                         else
2190                                         {
2191                                                 /* checks on -k are case sensitive and only accurate to the
2192                                                    first 32 characters */
2193                                                 char key[MAXBUF];
2194                                                 strcpy(key,parameters[param++]);
2195                                                 if (strlen(key)>32) {
2196                                                         key[31] = '\0';
2197                                                 }
2198                                                 /* only allow -k if correct key given */
2199                                                 if (!strcmp(chan->key,key))
2200                                                 {
2201                                                         strcat(outlist,"k");
2202                                                         strcpy(chan->key,"");
2203                                                         strcpy(outpars[pc++],key);
2204                                                 }
2205                                         }
2206                                 break;
2207                                 
2208                                 case 'l':
2209                                         if (mdir == 0)
2210                                         {
2211                                                 if (chan->limit)
2212                                                 {
2213                                                         strcat(outlist,"l");
2214                                                         chan->limit = 0;
2215                                                 }
2216                                         }
2217                                         
2218                                         if ((param >= pcnt)) break;
2219                                         if (mdir == 1)
2220                                         {
2221                                                 if (l_set)
2222                                                         break;
2223                                                 
2224                                                 bool invalid = false;
2225                                                 for (int i = 0; i < strlen(parameters[param]); i++)
2226                                                 {
2227                                                         if ((parameters[param][i] < '0') || (parameters[param][i] > '9'))
2228                                                         {
2229                                                                 invalid = true;
2230                                                         }
2231                                                 }
2232                                                 if (atoi(parameters[param]) < 1)
2233                                                 {
2234                                                         invalid = true;
2235                                                 }
2236
2237                                                 if (invalid)
2238                                                         break;
2239                                                 
2240                                                 chan->limit = atoi(parameters[param]);
2241                                                 if (chan->limit)
2242                                                 {
2243                                                         strcat(outlist,"l");
2244                                                         strcpy(outpars[pc++],parameters[param++]);
2245                                                         l_set = true;
2246                                                 }
2247                                         }
2248                                 break;
2249                                 
2250                                 case 'i':
2251                                         if (chan->inviteonly != mdir)
2252                                         {
2253                                                 strcat(outlist,"i");
2254                                         }
2255                                         chan->inviteonly = mdir;
2256                                 break;
2257                                 
2258                                 case 't':
2259                                         if (chan->topiclock != mdir)
2260                                         {
2261                                                 strcat(outlist,"t");
2262                                         }
2263                                         chan->topiclock = mdir;
2264                                 break;
2265                                 
2266                                 case 'n':
2267                                         if (chan->noexternal != mdir)
2268                                         {
2269                                                 strcat(outlist,"n");
2270                                         }
2271                                         chan->noexternal = mdir;
2272                                 break;
2273                                 
2274                                 case 'm':
2275                                         if (chan->moderated != mdir)
2276                                         {
2277                                                 strcat(outlist,"m");
2278                                         }
2279                                         chan->moderated = mdir;
2280                                 break;
2281                                 
2282                                 case 's':
2283                                         if (chan->secret != mdir)
2284                                         {
2285                                                 strcat(outlist,"s");
2286                                                 if (chan->c_private)
2287                                                 {
2288                                                         chan->c_private = 0;
2289                                                         if (mdir)
2290                                                         {
2291                                                                 strcat(outlist,"-p+");
2292                                                         }
2293                                                         else
2294                                                         {
2295                                                                 strcat(outlist,"+p-");
2296                                                         }
2297                                                 }
2298                                         }
2299                                         chan->secret = mdir;
2300                                 break;
2301                                 
2302                                 case 'p':
2303                                         if (chan->c_private != mdir)
2304                                         {
2305                                                 strcat(outlist,"p");
2306                                                 if (chan->secret)
2307                                                 {
2308                                                         chan->secret = 0;
2309                                                         if (mdir)
2310                                                         {
2311                                                                 strcat(outlist,"-s+");
2312                                                         }
2313                                                         else
2314                                                         {
2315                                                                 strcat(outlist,"+s-");
2316                                                         }
2317                                                 }
2318                                         }
2319                                         chan->c_private = mdir;
2320                                 break;
2321                                 
2322                                 default:
2323                                         log(DEBUG,"Preprocessing custom mode %c",modechar);
2324                                         string_list p;
2325                                         p.clear();
2326                                         if (((!strchr(chan->custom_modes,modechar)) && (!mdir)) || ((strchr(chan->custom_modes,modechar)) && (mdir)))
2327                                         {
2328                                                 log(DEBUG,"Mode %c isnt set on %s but trying to remove!",modechar,chan->name);
2329                                                 break;
2330                                         }
2331                                         if (ModeDefined(modechar,MT_CHANNEL))
2332                                         {
2333                                                 log(DEBUG,"A module has claimed this mode");
2334                                                 if (param<pcnt)
2335                                                 {
2336                                                         if ((ModeDefinedOn(modechar,MT_CHANNEL)>0) && (mdir))
2337                                                         {
2338                                                                 p.push_back(parameters[param]);
2339                                                         }
2340                                                         if ((ModeDefinedOff(modechar,MT_CHANNEL)>0) && (!mdir))
2341                                                         {
2342                                                                 p.push_back(parameters[param]);
2343                                                         }
2344                                                 }
2345                                                 bool handled = false;
2346                                                 if (param>=pcnt)
2347                                                 {
2348                                                         log(DEBUG,"Not enough parameters for module-mode %c",modechar);
2349                                                         // we're supposed to have a parameter, but none was given... so dont handle the mode.
2350                                                         if (((ModeDefinedOn(modechar,MT_CHANNEL)>0) && (mdir)) || ((ModeDefinedOff(modechar,MT_CHANNEL)>0) && (!mdir))) 
2351                                                         {
2352                                                                 handled = true;
2353                                                                 param++;
2354                                                         }
2355                                                 }
2356                                                 for (int i = 0; i <= MODCOUNT; i++)
2357                                                 {
2358                                                         if (!handled)
2359                                                         {
2360                                                                 if (modules[i]->OnExtendedMode(user,chan,modechar,MT_CHANNEL,mdir,p))
2361                                                                 {
2362                                                                         log(DEBUG,"OnExtendedMode returned nonzero for a module");
2363                                                                         char app[] = {modechar, 0};
2364                                                                         if (ptr>0)
2365                                                                         {
2366                                                                                 if ((modelist[ptr-1] == '+') || (modelist[ptr-1] == '-'))
2367                                                                                 {
2368                                                                                         strcat(outlist, app);
2369                                                                                 }
2370                                                                                 else if (!strchr(outlist,modechar))
2371                                                                                 {
2372                                                                                         strcat(outlist, app);
2373                                                                                 }
2374                                                                         }
2375                                                                         chan->SetCustomMode(modechar,mdir);
2376                                                                         // include parameters in output if mode has them
2377                                                                         if ((ModeDefinedOn(modechar,MT_CHANNEL)>0) && (mdir))
2378                                                                         {
2379                                                                                 chan->SetCustomModeParam(modelist[ptr],parameters[param],mdir);
2380                                                                                 strcpy(outpars[pc++],parameters[param++]);
2381                                                                         }
2382                                                                         // break, because only one module can handle the mode.
2383                                                                         handled = true;
2384                                                                 }
2385                                                         }
2386                                                 }
2387                                         }
2388                                 break;
2389                                 
2390                         }
2391                 }
2392         }
2393
2394         /* this ensures only the *valid* modes are sent out onto the network */
2395         while ((outlist[strlen(outlist)-1] == '-') || (outlist[strlen(outlist)-1] == '+'))
2396         {
2397                 outlist[strlen(outlist)-1] = '\0';
2398         }
2399         if (strcmp(outlist,""))
2400         {
2401                 strcpy(outstr,outlist);
2402                 for (ptr = 0; ptr < pc; ptr++)
2403                 {
2404                         strcat(outstr," ");
2405                         strcat(outstr,outpars[ptr]);
2406                 }
2407                 if (servermode)
2408                 {
2409                         WriteChannelWithServ(ServerName,chan,user,"MODE %s %s",chan->name,outstr);
2410                 }
2411                 else
2412                 {
2413                         WriteChannel(chan,user,"MODE %s %s",chan->name,outstr);
2414                 }
2415         }
2416 }
2417
2418 // based on sourcemodes, return true or false to determine if umode is a valid mode a user may set on themselves or others.
2419
2420 bool allowed_umode(char umode, char* sourcemodes,bool adding)
2421 {
2422         log(DEBUG,"Allowed_umode: %c %s",umode,sourcemodes);
2423         // RFC1459 specified modes
2424         if ((umode == 'w') || (umode == 's') || (umode == 'i'))
2425         {
2426                 log(DEBUG,"umode %c allowed by RFC1459 scemantics",umode);
2427                 return true;
2428         }
2429         
2430         // user may not +o themselves or others, but an oper may de-oper other opers or themselves
2431         if ((strchr(sourcemodes,'o')) && (!adding))
2432         {
2433                 log(DEBUG,"umode %c allowed by RFC1459 scemantics",umode);
2434                 return true;
2435         }
2436         else if (umode == 'o')
2437         {
2438                 log(DEBUG,"umode %c allowed by RFC1459 scemantics",umode);
2439                 return false;
2440         }
2441         
2442         // process any module-defined modes that need oper
2443         if ((ModeDefinedOper(umode,MT_CLIENT)) && (strchr(sourcemodes,'o')))
2444         {
2445                 log(DEBUG,"umode %c allowed by module handler (oper only mode)",umode);
2446                 return true;
2447         }
2448         else
2449         if (ModeDefined(umode,MT_CLIENT))
2450         {
2451                 // process any module-defined modes that don't need oper
2452                 log(DEBUG,"umode %c allowed by module handler (non-oper mode)",umode);
2453                 if ((ModeDefinedOper(umode,MT_CLIENT)) && (!strchr(sourcemodes,'o')))
2454                 {
2455                         // no, this mode needs oper, and this user 'aint got what it takes!
2456                         return false;
2457                 }
2458                 return true;
2459         }
2460
2461         // anything else - return false.
2462         log(DEBUG,"umode %c not known by any ruleset",umode);
2463         return false;
2464 }
2465
2466 bool process_module_umode(char umode, userrec* source, void* dest, bool adding)
2467 {
2468         string_list p;
2469         p.clear();
2470         if (ModeDefined(umode,MT_CLIENT))
2471         {
2472                 for (int i = 0; i <= MODCOUNT; i++)
2473                 {
2474                         if (modules[i]->OnExtendedMode(source,(void*)dest,umode,MT_CLIENT,adding,p))
2475                         {
2476                                 log(DEBUG,"Module claims umode %c",umode);
2477                                 return true;
2478                         }
2479                 }
2480                 log(DEBUG,"No module claims umode %c",umode);
2481                 return false;
2482         }
2483         else
2484         {
2485                 log(DEBUG,"*** BUG *** Non-module umode passed to process_module_umode!");
2486                 return false;
2487         }
2488 }
2489
2490 void handle_mode(char **parameters, int pcnt, userrec *user)
2491 {
2492         chanrec* Ptr;
2493         userrec* dest;
2494         int can_change,i;
2495         int direction = 1;
2496         char outpars[MAXBUF];
2497
2498         dest = Find(parameters[0]);
2499
2500         if ((dest) && (pcnt == 1))
2501         {
2502                 WriteServ(user->fd,"221 %s :+%s",user->nick,user->modes);
2503                 return;
2504         }
2505
2506         if ((dest) && (pcnt > 1))
2507         {
2508                 char dmodes[MAXBUF];
2509                 strncpy(dmodes,dest->modes,MAXBUF);
2510                 log(DEBUG,"pulled up dest user modes: %s",dmodes);
2511         
2512                 can_change = 0;
2513                 if (user != dest)
2514                 {
2515                         if (strchr(user->modes,'o'))
2516                         {
2517                                 can_change = 1;
2518                         }
2519                 }
2520                 else
2521                 {
2522                         can_change = 1;
2523                 }
2524                 if (!can_change)
2525                 {
2526                         WriteServ(user->fd,"482 %s :Can't change mode for other users",user->nick);
2527                         return;
2528                 }
2529                 
2530                 strcpy(outpars,"+");
2531                 direction = 1;
2532
2533                 if ((parameters[1][0] != '+') && (parameters[1][0] != '-'))
2534                         return;
2535
2536                 for (i = 0; i < strlen(parameters[1]); i++)
2537                 {
2538                         if (parameters[1][i] == '+')
2539                         {
2540                                 if (direction != 1)
2541                                 {
2542                                         if ((outpars[strlen(outpars)-1] == '+') || (outpars[strlen(outpars)-1] == '-'))
2543                                         {
2544                                                 outpars[strlen(outpars)-1] = '+';
2545                                         }
2546                                         else
2547                                         {
2548                                                 strcat(outpars,"+");
2549                                         }
2550                                 }
2551                                 direction = 1;
2552                         }
2553                         else
2554                         if (parameters[1][i] == '-')
2555                         {
2556                                 if (direction != 0)
2557                                 {
2558                                         if ((outpars[strlen(outpars)-1] == '+') || (outpars[strlen(outpars)-1] == '-'))
2559                                         {
2560                                                 outpars[strlen(outpars)-1] = '-';
2561                                         }
2562                                         else
2563                                         {
2564                                                 strcat(outpars,"-");
2565                                         }
2566                                 }
2567                                 direction = 0;
2568                         }
2569                         else
2570                         {
2571                                 can_change = 0;
2572                                 if (strchr(user->modes,'o'))
2573                                 {
2574                                         can_change = 1;
2575                                 }
2576                                 else
2577                                 {
2578                                         if ((parameters[1][i] == 'i') || (parameters[1][i] == 'w') || (parameters[1][i] == 's') || (allowed_umode(parameters[1][i],user->modes,direction)))
2579                                         {
2580                                                 can_change = 1;
2581                                         }
2582                                 }
2583                                 if (can_change)
2584                                 {
2585                                         if (direction == 1)
2586                                         {
2587                                                 if ((!strchr(dmodes,parameters[1][i])) && (allowed_umode(parameters[1][i],user->modes,true)))
2588                                                 {
2589                                                         char umode = parameters[1][i];
2590                                                         if ((process_module_umode(umode, user, dest, direction)) || (umode == 'i') || (umode == 's') || (umode == 'w') || (umode == 'o'))
2591                                                         {
2592                                                                 dmodes[strlen(dmodes)+1]='\0';
2593                                                                 dmodes[strlen(dmodes)] = parameters[1][i];
2594                                                                 outpars[strlen(outpars)+1]='\0';
2595                                                                 outpars[strlen(outpars)] = parameters[1][i];
2596                                                         }
2597                                                 }
2598                                         }
2599                                         else
2600                                         {
2601                                                 if ((allowed_umode(parameters[1][i],user->modes,false)) && (strchr(dmodes,parameters[1][i])))
2602                                                 {
2603                                                         char umode = parameters[1][i];
2604                                                         if ((process_module_umode(umode, user, dest, direction)) || (umode == 'i') || (umode == 's') || (umode == 'w') || (umode == 'o'))
2605                                                         {
2606                                                                 int q = 0;
2607                                                                 char temp[MAXBUF];      
2608                                                                 char moo[MAXBUF];       
2609
2610                                                                 outpars[strlen(outpars)+1]='\0';
2611                                                                 outpars[strlen(outpars)] = parameters[1][i];
2612                                                         
2613                                                                 strcpy(temp,"");
2614                                                                 for (q = 0; q < strlen(dmodes); q++)
2615                                                                 {
2616                                                                         if (dmodes[q] != parameters[1][i])
2617                                                                         {
2618                                                                                 moo[0] = dmodes[q];
2619                                                                                 moo[1] = '\0';
2620                                                                                 strcat(temp,moo);
2621                                                                         }
2622                                                                 }
2623                                                                 strcpy(dmodes,temp);
2624                                                         }
2625                                                 }
2626                                         }
2627                                 }
2628                         }
2629                 }
2630                 if (strlen(outpars))
2631                 {
2632                         char b[MAXBUF];
2633                         strcpy(b,"");
2634                         int z = 0;
2635                         int i = 0;
2636                         while (i < strlen (outpars))
2637                         {
2638                                 b[z++] = outpars[i++];
2639                                 b[z] = '\0';
2640                                 if (i<strlen(outpars)-1)
2641                                 {
2642                                         if (((outpars[i] == '-') || (outpars[i] == '+')) && ((outpars[i+1] == '-') || (outpars[i+1] == '+')))
2643                                         {
2644                                                 // someones playing silly buggers and trying
2645                                                 // to put a +- or -+ into the line...
2646                                                 i++;
2647                                         }
2648                                 }
2649                                 if (i == strlen(outpars)-1)
2650                                 {
2651                                         if ((outpars[i] == '-') || (outpars[i] == '+'))
2652                                         {
2653                                                 i++;
2654                                         }
2655                                 }
2656                         }
2657
2658                         z = strlen(b)-1;
2659                         if ((b[z] == '-') || (b[z] == '+'))
2660                                 b[z] == '\0';
2661
2662                         if ((!strcmp(b,"+")) || (!strcmp(b,"-")))
2663                                 return;
2664
2665                         WriteTo(user, dest, "MODE %s :%s", dest->nick, b);
2666
2667                         if (strlen(dmodes)>MAXMODES)
2668                         {
2669                                 dmodes[MAXMODES-1] = '\0';
2670                         }
2671                         log(DEBUG,"Stripped mode line");
2672                         log(DEBUG,"Line dest is now %s",dmodes);
2673                         strncpy(dest->modes,dmodes,MAXMODES);
2674
2675                 }
2676
2677                 return;
2678         }
2679         
2680         Ptr = FindChan(parameters[0]);
2681         if (Ptr)
2682         {
2683                 if (pcnt == 1)
2684                 {
2685                         /* just /modes #channel */
2686                         WriteServ(user->fd,"324 %s %s +%s",user->nick, Ptr->name, chanmodes(Ptr));
2687                         WriteServ(user->fd,"329 %s %s %d", user->nick, Ptr->name, Ptr->created);
2688                         return;
2689                 }
2690                 else
2691                 if (pcnt == 2)
2692                 {
2693                         if ((!strcmp(parameters[1],"+b")) || (!strcmp(parameters[1],"b")))
2694                         {
2695
2696                                 for (BanList::iterator i = Ptr->bans.begin(); i != Ptr->bans.end(); i++)
2697                                 {
2698                                         WriteServ(user->fd,"367 %s %s %s %s %d",user->nick, Ptr->name, i->data, i->set_by, i->set_time);
2699                                 }
2700                                 WriteServ(user->fd,"368 %s %s :End of channel ban list",user->nick, Ptr->name);
2701                         }
2702                 }
2703
2704                 if ((cstatus(user,Ptr) < STATUS_HOP) && (Ptr))
2705                 {
2706                         WriteServ(user->fd,"482 %s %s :You must be at least a half-operator",user->nick, Ptr->name);
2707                         return;
2708                 }
2709
2710                 process_modes(parameters,user,Ptr,cstatus(user,Ptr),pcnt,false);
2711         }
2712         else
2713         {
2714                 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
2715         }
2716 }
2717
2718
2719
2720
2721 void server_mode(char **parameters, int pcnt, userrec *user)
2722 {
2723         chanrec* Ptr;
2724         userrec* dest;
2725         int can_change,i;
2726         int direction = 1;
2727         char outpars[MAXBUF];
2728
2729         dest = Find(parameters[0]);
2730         
2731         // fix: ChroNiCk found this - we cant use this as debug if its null!
2732         if (dest)
2733         {
2734                 log(DEBUG,"server_mode on %s",dest->nick);
2735         }
2736
2737         if ((dest) && (pcnt > 1))
2738         {
2739                 log(DEBUG,"params > 1");
2740
2741                 char dmodes[MAXBUF];
2742                 strncpy(dmodes,dest->modes,MAXBUF);
2743
2744                 strcpy(outpars,"+");
2745                 direction = 1;
2746
2747                 if ((parameters[1][0] != '+') && (parameters[1][0] != '-'))
2748                         return;
2749
2750                 for (i = 0; i < strlen(parameters[1]); i++)
2751                 {
2752                         if (parameters[1][i] == '+')
2753                         {
2754                                 if (direction != 1)
2755                                 {
2756                                         if ((outpars[strlen(outpars)-1] == '+') || (outpars[strlen(outpars)-1] == '-'))
2757                                         {
2758                                                 outpars[strlen(outpars)-1] = '+';
2759                                         }
2760                                         else
2761                                         {
2762                                                 strcat(outpars,"+");
2763                                         }
2764                                 }
2765                                 direction = 1;
2766                         }
2767                         else
2768                         if (parameters[1][i] == '-')
2769                         {
2770                                 if (direction != 0)
2771                                 {
2772                                         if ((outpars[strlen(outpars)-1] == '+') || (outpars[strlen(outpars)-1] == '-'))
2773                                         {
2774                                                 outpars[strlen(outpars)-1] = '-';
2775                                         }
2776                                         else
2777                                         {
2778                                                 strcat(outpars,"-");
2779                                         }
2780                                 }
2781                                 direction = 0;
2782                         }
2783                         else
2784                         {
2785                                 log(DEBUG,"begin mode processing entry");
2786                                 can_change = 1;
2787                                 if (can_change)
2788                                 {
2789                                         if (direction == 1)
2790                                         {
2791                                                 log(DEBUG,"umode %c being added",parameters[1][i]);
2792                                                 if ((!strchr(dmodes,parameters[1][i])) && (allowed_umode(parameters[1][i],user->modes,true)))
2793                                                 {
2794                                                         char umode = parameters[1][i];
2795                                                         log(DEBUG,"umode %c is an allowed umode",umode);
2796                                                         if ((process_module_umode(umode, user, dest, direction)) || (umode == 'i') || (umode == 's') || (umode == 'w') || (umode == 'o'))
2797                                                         {
2798                                                                 dmodes[strlen(dmodes)+1]='\0';
2799                                                                 dmodes[strlen(dmodes)] = parameters[1][i];
2800                                                                 outpars[strlen(outpars)+1]='\0';
2801                                                                 outpars[strlen(outpars)] = parameters[1][i];
2802                                                         }
2803                                                 }
2804                                         }
2805                                         else
2806                                         {
2807                                                 // can only remove a mode they already have
2808                                                 log(DEBUG,"umode %c being removed",parameters[1][i]);
2809                                                 if ((allowed_umode(parameters[1][i],user->modes,false)) && (strchr(dmodes,parameters[1][i])))
2810                                                 {
2811                                                         char umode = parameters[1][i];
2812                                                         log(DEBUG,"umode %c is an allowed umode",umode);
2813                                                         if ((process_module_umode(umode, user, dest, direction)) || (umode == 'i') || (umode == 's') || (umode == 'w') || (umode == 'o'))
2814                                                         {
2815                                                                 int q = 0;
2816                                                                 char temp[MAXBUF];
2817                                                                 char moo[MAXBUF];       
2818
2819                                                                 outpars[strlen(outpars)+1]='\0';
2820                                                                 outpars[strlen(outpars)] = parameters[1][i];
2821                                                         
2822                                                                 strcpy(temp,"");
2823                                                                 for (q = 0; q < strlen(dmodes); q++)
2824                                                                 {
2825                                                                         if (dmodes[q] != parameters[1][i])
2826                                                                         {
2827                                                                                 moo[0] = dmodes[q];
2828                                                                                 moo[1] = '\0';
2829                                                                                 strcat(temp,moo);
2830                                                                         }
2831                                                                 }
2832                                                                 strcpy(dmodes,temp);
2833                                                         }
2834                                                 }
2835                                         }
2836                                 }
2837                         }
2838                 }
2839                 if (strlen(outpars))
2840                 {
2841                         char b[MAXBUF];
2842                         strcpy(b,"");
2843                         int z = 0;
2844                         int i = 0;
2845                         while (i < strlen (outpars))
2846                         {
2847                                 b[z++] = outpars[i++];
2848                                 b[z] = '\0';
2849                                 if (i<strlen(outpars)-1)
2850                                 {
2851                                         if (((outpars[i] == '-') || (outpars[i] == '+')) && ((outpars[i+1] == '-') || (outpars[i+1] == '+')))
2852                                         {
2853                                                 // someones playing silly buggers and trying
2854                                                 // to put a +- or -+ into the line...
2855                                                 i++;
2856                                         }
2857                                 }
2858                                 if (i == strlen(outpars)-1)
2859                                 {
2860                                         if ((outpars[i] == '-') || (outpars[i] == '+'))
2861                                         {
2862                                                 i++;
2863                                         }
2864                                 }
2865                         }
2866
2867                         z = strlen(b)-1;
2868                         if ((b[z] == '-') || (b[z] == '+'))
2869                                 b[z] == '\0';
2870
2871                         if ((!strcmp(b,"+")) || (!strcmp(b,"-")))
2872                                 return;
2873
2874                         WriteTo(user, dest, "MODE %s :%s", dest->nick, b);
2875
2876                         if (strlen(dmodes)>MAXMODES)
2877                         {
2878                                 dmodes[MAXMODES-1] = '\0';
2879                         }
2880                         log(DEBUG,"Stripped mode line");
2881                         log(DEBUG,"Line dest is now %s",dmodes);
2882                         strncpy(dest->modes,dmodes,MAXMODES);
2883
2884                 }
2885
2886                 return;
2887         }
2888         
2889         Ptr = FindChan(parameters[0]);
2890         if (Ptr)
2891         {
2892                 process_modes(parameters,user,Ptr,STATUS_OP,pcnt,true);
2893         }
2894         else
2895         {
2896                 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
2897         }
2898 }
2899
2900
2901 /* This function pokes and hacks at a parameter list like the following:
2902  *
2903  * PART #winbot, #darkgalaxy :m00!
2904  *
2905  * to turn it into a series of individual calls like this:
2906  *
2907  * PART #winbot :m00!
2908  * PART #darkgalaxy :m00!
2909  *
2910  * The seperate calls are sent to a callback function provided by the caller
2911  * (the caller will usually call itself recursively). The callback function
2912  * must be a command handler. Calling this function on a line with no list causes
2913  * no action to be taken. You must provide a starting and ending parameter number
2914  * where the range of the list can be found, useful if you have a terminating
2915  * parameter as above which is actually not part of the list, or parameters
2916  * before the actual list as well. This code is used by many functions which
2917  * can function as "one to list" (see the RFC) */
2918
2919 int loop_call(handlerfunc fn, char **parameters, int pcnt, userrec *u, int start, int end, int joins)
2920 {
2921         char plist[MAXBUF];
2922         char *param;
2923         char *pars[32];
2924         char blog[32][MAXBUF];
2925         char blog2[32][MAXBUF];
2926         int i = 0, j = 0, q = 0, total = 0, t = 0, t2 = 0, total2 = 0;
2927         char keystr[MAXBUF];
2928         char moo[MAXBUF];
2929
2930         for (i = 0; i <32; i++)
2931                 strcpy(blog[i],"");
2932
2933         for (i = 0; i <32; i++)
2934                 strcpy(blog2[i],"");
2935
2936         strcpy(moo,"");
2937         for (i = 0; i <10; i++)
2938         {
2939                 if (!parameters[i])
2940                 {
2941                         parameters[i] = moo;
2942                 }
2943         }
2944         if (joins)
2945         {
2946                 if (pcnt > 1) /* we have a key to copy */
2947                 {
2948                         strcpy(keystr,parameters[1]);
2949                 }
2950         }
2951
2952         if (!parameters[start])
2953         {
2954                 return 0;
2955         }
2956         if (!strchr(parameters[start],','))
2957         {
2958                 return 0;
2959         }
2960         strcpy(plist,"");
2961         for (i = start; i <= end; i++)
2962         {
2963                 if (parameters[i])
2964                 {
2965                         strcat(plist,parameters[i]);
2966                 }
2967         }
2968         
2969         j = 0;
2970         param = plist;
2971
2972         t = strlen(plist);
2973         for (i = 0; i < t; i++)
2974         {
2975                 if (plist[i] == ',')
2976                 {
2977                         plist[i] = '\0';
2978                         strcpy(blog[j++],param);
2979                         param = plist+i+1;
2980                 }
2981         }
2982         strcpy(blog[j++],param);
2983         total = j;
2984
2985         if ((joins) && (keystr) && (total>0)) // more than one channel and is joining
2986         {
2987                 strcat(keystr,",");
2988         }
2989         
2990         if ((joins) && (keystr))
2991         {
2992                 if (strchr(keystr,','))
2993                 {
2994                         j = 0;
2995                         param = keystr;
2996                         t2 = strlen(keystr);
2997                         for (i = 0; i < t2; i++)
2998                         {
2999                                 if (keystr[i] == ',')
3000                                 {
3001                                         keystr[i] = '\0';
3002                                         strcpy(blog2[j++],param);
3003                                         param = keystr+i+1;
3004                                 }
3005                         }
3006                         strcpy(blog2[j++],param);
3007                         total2 = j;
3008                 }
3009         }
3010
3011         for (j = 0; j < total; j++)
3012         {
3013                 if (blog[j])
3014                 {
3015                         pars[0] = blog[j];
3016                 }
3017                 for (q = end; q < pcnt-1; q++)
3018                 {
3019                         if (parameters[q+1])
3020                         {
3021                                 pars[q-end+1] = parameters[q+1];
3022                         }
3023                 }
3024                 if ((joins) && (parameters[1]))
3025                 {
3026                         if (pcnt > 1)
3027                         {
3028                                 pars[1] = blog2[j];
3029                         }
3030                         else
3031                         {
3032                                 pars[1] = NULL;
3033                         }
3034                 }
3035                 /* repeatedly call the function with the hacked parameter list */
3036                 if ((joins) && (pcnt > 1))
3037                 {
3038                         if (pars[1])
3039                         {
3040                                 // pars[1] already set up and containing key from blog2[j]
3041                                 fn(pars,2,u);
3042                         }
3043                         else
3044                         {
3045                                 pars[1] = parameters[1];
3046                                 fn(pars,2,u);
3047                         }
3048                 }
3049                 else
3050                 {
3051                         fn(pars,pcnt-(end-start),u);
3052                 }
3053         }
3054
3055         return 1;
3056 }
3057
3058
3059 void handle_join(char **parameters, int pcnt, userrec *user)
3060 {
3061         chanrec* Ptr;
3062         int i = 0;
3063         
3064         if (loop_call(handle_join,parameters,pcnt,user,0,0,1))
3065                 return;
3066         if (parameters[0][0] == '#')
3067         {
3068                 Ptr = add_channel(user,parameters[0],parameters[1]);
3069         }
3070 }
3071
3072
3073 void handle_part(char **parameters, int pcnt, userrec *user)
3074 {
3075         chanrec* Ptr;
3076
3077         if (pcnt > 1)
3078         {
3079                 if (loop_call(handle_part,parameters,pcnt,user,0,pcnt-2,0))
3080                         return;
3081                 del_channel(user,parameters[0],parameters[1]);
3082         }
3083         else
3084         {
3085                 if (loop_call(handle_part,parameters,pcnt,user,0,pcnt-1,0))
3086                         return;
3087                 del_channel(user,parameters[0],NULL);
3088         }
3089 }
3090
3091 void handle_kick(char **parameters, int pcnt, userrec *user)
3092 {
3093         chanrec* Ptr = FindChan(parameters[0]);
3094         userrec* u   = Find(parameters[1]);
3095
3096         if ((!u) || (!Ptr))
3097         {
3098                 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
3099                 return;
3100         }
3101         
3102         if (!has_channel(u,Ptr))
3103         {
3104                 WriteServ(user->fd,"442 %s %s :You're not on that channel!",user->nick, parameters[0]);
3105                 return;
3106         }
3107         
3108         if (pcnt > 2)
3109         {
3110                 char reason[MAXBUF];
3111                 strncpy(reason,parameters[2],MAXBUF);
3112                 if (strlen(reason)>MAXKICK)
3113                 {
3114                         reason[MAXKICK-1] = '\0';
3115                 }
3116
3117                 kick_channel(user,u,Ptr,reason);
3118         }
3119         else
3120         {
3121                 kick_channel(user,u,Ptr,user->nick);
3122         }
3123 }
3124
3125
3126 void handle_die(char **parameters, int pcnt, userrec *user)
3127 {
3128         log(DEBUG,"die: %s",user->nick);
3129         if (!strcmp(parameters[0],diepass))
3130         {
3131                 WriteOpers("*** DIE command from %s!%s@%s, terminating...",user->nick,user->ident,user->host);
3132                 sleep(DieDelay);
3133                 Exit(ERROR);
3134         }
3135         else
3136         {
3137                 WriteOpers("*** Failed DIE Command from %s!%s@%s.",user->nick,user->ident,user->host);
3138         }
3139 }
3140
3141 void handle_restart(char **parameters, int pcnt, userrec *user)
3142 {
3143         log(DEBUG,"restart: %s",user->nick);
3144         if (!strcmp(parameters[0],restartpass))
3145         {
3146                 WriteOpers("*** RESTART command from %s!%s@%s, Pretending to restart till this is finished :D",user->nick,user->ident,user->host);
3147                 sleep(DieDelay);
3148                 Exit(ERROR);
3149                 /* Will finish this later when i can be arsed :) */
3150         }
3151         else
3152         {
3153                 WriteOpers("*** Failed RESTART Command from %s!%s@%s.",user->nick,user->ident,user->host);
3154         }
3155 }
3156
3157
3158 void kill_link(userrec *user,char* reason)
3159 {
3160         user_hash::iterator iter = clientlist.find(user->nick);
3161
3162         if (strlen(reason)>MAXQUIT)
3163         {
3164                 reason[MAXQUIT-1] = '\0';
3165         }
3166
3167         log(DEBUG,"kill_link: %s '%s'",user->nick,reason);
3168         Write(user->fd,"ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,reason);
3169         log(DEBUG,"closing fd %d",user->fd);
3170
3171         /* bugfix, cant close() a nonblocking socket (sux!) */
3172         if (user->registered == 7) {
3173                 FOREACH_MOD OnUserQuit(user);
3174                 WriteCommonExcept(user,"QUIT :%s",reason);
3175         }
3176
3177         /* push the socket on a stack of sockets due to be closed at the next opportunity */
3178         fd_reap.push_back(user->fd);
3179         
3180         bool do_purge = false;
3181         
3182         if (user->registered == 7) {
3183                 WriteOpers("*** Client exiting: %s!%s@%s [%s]",user->nick,user->ident,user->host,reason);
3184                 AddWhoWas(user);
3185         }
3186
3187         if (iter != clientlist.end())
3188         {
3189                 log(DEBUG,"deleting user hash value %d",iter->second);
3190                 if ((iter->second) && (user->registered == 7)) {
3191                         delete iter->second;
3192                 }
3193                 clientlist.erase(iter);
3194         }
3195
3196         if (user->registered == 7) {
3197                 purge_empty_chans();
3198         }
3199 }
3200
3201
3202 void handle_kill(char **parameters, int pcnt, userrec *user)
3203 {
3204         userrec *u = Find(parameters[0]);
3205         char killreason[MAXBUF];
3206         
3207         log(DEBUG,"kill: %s %s",parameters[0],parameters[1]);
3208         if (u)
3209         {
3210                 WriteTo(user, u, "KILL %s :%s!%s!%s (%s)", u->nick, ServerName,user->dhost,user->nick,parameters[1]);
3211                 // :Brain!brain@NetAdmin.chatspike.net KILL [Brain] :homer!NetAdmin.chatspike.net!Brain (test kill)
3212                 WriteOpers("*** Local Kill by %s: %s!%s@%s (%s)",user->nick,u->nick,u->ident,u->host,parameters[1]);
3213                 sprintf(killreason,"Killed (%s (%s))",user->nick,parameters[1]);
3214                 kill_link(u,killreason);
3215         }
3216         else
3217         {
3218                 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
3219         }
3220 }
3221
3222 void handle_summon(char **parameters, int pcnt, userrec *user)
3223 {
3224         WriteServ(user->fd,"445 %s :SUMMON has been disabled (depreciated command)",user->nick);
3225 }
3226
3227 void handle_users(char **parameters, int pcnt, userrec *user)
3228 {
3229         WriteServ(user->fd,"445 %s :USERS has been disabled (depreciated command)",user->nick);
3230 }
3231
3232
3233 // looks up a users password for their connection class (<ALLOW>/<DENY> tags)
3234
3235 char* Passwd(userrec *user)
3236 {
3237         for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
3238         {
3239                 if (match(user->host,i->host) && (i->type == CC_ALLOW))
3240                 {
3241                         return i->pass;
3242                 }
3243         }
3244         return "";
3245 }
3246
3247 bool IsDenied(userrec *user)
3248 {
3249         for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
3250         {
3251                 if (match(user->host,i->host) && (i->type == CC_DENY))
3252                 {
3253                         return true;
3254                 }
3255         }
3256         return false;
3257 }
3258
3259
3260
3261 void handle_pass(char **parameters, int pcnt, userrec *user)
3262 {
3263         if (!strcasecmp(parameters[0],Passwd(user)))
3264         {
3265                 user->haspassed = true;
3266         }
3267 }
3268
3269 void handle_invite(char **parameters, int pcnt, userrec *user)
3270 {
3271         userrec* u = Find(parameters[0]);
3272         chanrec* c = FindChan(parameters[1]);
3273
3274         if ((!c) || (!u))
3275         {
3276                 if (!c)
3277                 {
3278                         WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[1]);
3279                 }
3280                 else
3281                 {
3282                         if (c->inviteonly)
3283                         {
3284                                 WriteServ(user->fd,"401 %s %s :No such nick/channel",user->nick, parameters[0]);
3285                         }
3286                 }
3287
3288                 return;
3289         }
3290
3291         if (c->inviteonly)
3292         {
3293                 if (cstatus(user,c) < STATUS_HOP)
3294                 {
3295                         WriteServ(user->fd,"482 %s %s :You must be at least a half-operator",user->nick, c->name);
3296                         return;
3297                 }
3298
3299                 u->InviteTo(c->name);
3300                 WriteFrom(u->fd,user,"INVITE %s :%s",u->nick,c->name);
3301                 WriteServ(user->fd,"341 %s %s %s",user->nick,u->nick,c->name);
3302         }
3303 }
3304
3305 void handle_topic(char **parameters, int pcnt, userrec *user)
3306 {
3307         chanrec* Ptr;
3308
3309         if (pcnt == 1)
3310         {
3311                 if (strlen(parameters[0]) <= CHANMAX)
3312                 {
3313                         Ptr = FindChan(parameters[0]);
3314                         if (Ptr)
3315                         {
3316                                 if (Ptr->topicset)
3317                                 {
3318                                         WriteServ(user->fd,"332 %s %s :%s", user->nick, Ptr->name, Ptr->topic);
3319                                         WriteServ(user->fd,"333 %s %s %s %d", user->nick, Ptr->name, Ptr->setby, Ptr->topicset);
3320                                 }
3321                                 else
3322                                 {
3323                                         WriteServ(user->fd,"331 %s %s :No topic is set.", user->nick, Ptr->name);
3324                                 }
3325                         }
3326                         else
3327                         {
3328                                 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
3329                         }
3330                 }
3331                 return;
3332         }
3333         else if (pcnt>1)
3334         {
3335                 if (strlen(parameters[0]) <= CHANMAX)
3336                 {
3337                         Ptr = FindChan(parameters[0]);
3338                         if (Ptr)
3339                         {
3340                                 if ((Ptr->topiclock) && (cstatus(user,Ptr)<STATUS_HOP))
3341                                 {
3342                                         WriteServ(user->fd,"482 %s %s :You must be at least a half-operator", user->nick, Ptr->name);
3343                                         return;
3344                                 }
3345                                 
3346                                 char topic[MAXBUF];
3347                                 strncpy(topic,parameters[1],MAXBUF);
3348                                 if (strlen(topic)>MAXTOPIC)
3349                                 {
3350                                         topic[MAXTOPIC-1] = '\0';
3351                                 }
3352                                         
3353                                 strcpy(Ptr->topic,topic);
3354                                 strcpy(Ptr->setby,user->nick);
3355                                 Ptr->topicset = time(NULL);
3356                                 WriteChannel(Ptr,user,"TOPIC %s :%s",Ptr->name, Ptr->topic);
3357                         }
3358                         else
3359                         {
3360                                 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
3361                         }
3362                 }
3363         }
3364 }
3365
3366 /* sends out an error notice to all connected clients (not to be used
3367  * lightly!) */
3368
3369 void send_error(char *s)
3370 {
3371         log(DEBUG,"send_error: %s",s);
3372         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
3373         {
3374                 if (isnick(i->second->nick))
3375                 {
3376                         WriteServ(i->second->fd,"NOTICE %s :%s",i->second->nick,s);
3377                 }
3378                 else
3379                 {
3380                         // fix - unregistered connections receive ERROR, not NOTICE
3381                         Write(i->second->fd,"ERROR :%s",s);
3382                 }
3383         }
3384 }
3385
3386 void Error(int status)
3387 {
3388         signal (SIGALRM, SIG_IGN);
3389         signal (SIGPIPE, SIG_IGN);
3390         signal (SIGTERM, SIG_IGN);
3391         signal (SIGABRT, SIG_IGN);
3392         signal (SIGSEGV, SIG_IGN);
3393         signal (SIGURG, SIG_IGN);
3394         signal (SIGKILL, SIG_IGN);
3395         log(DEBUG,"*** fell down a pothole in the road to perfection ***");
3396         send_error("Error! Segmentation fault! save meeeeeeeeeeeeee *splat!*");
3397         exit(status);
3398 }
3399
3400 int main (int argc, char *argv[])
3401 {
3402         Start();
3403         log(DEBUG,"*** InspIRCd starting up!");
3404         if (!FileExists(CONFIG_FILE))
3405         {
3406                 printf("ERROR: Cannot open config file: %s\nExiting...\n",CONFIG_FILE);
3407                 log(DEBUG,"main: no config");
3408                 printf("ERROR: Your config file is missing, this IRCd will self destruct in 10 seconds!\n");
3409                 Exit(ERROR);
3410         }
3411         if (argc > 1) {
3412                 if (!strcmp(argv[1],"-nofork")) {
3413                         nofork = true;
3414                 }
3415         }
3416         if (InspIRCd() == ERROR)
3417         {
3418                 log(DEBUG,"main: daemon function bailed");
3419                 printf("ERROR: could not initialise. Shutting down.\n");
3420                 Exit(ERROR);
3421         }
3422         Exit(TRUE);
3423         return 0;
3424 }
3425
3426 template<typename T> inline string ConvToStr(const T &in)
3427 {
3428         stringstream tmp;
3429         if (!(tmp << in)) return string();
3430         return tmp.str();
3431 }
3432
3433 /* re-allocates a nick in the user_hash after they change nicknames,
3434  * returns a pointer to the new user as it may have moved */
3435
3436 userrec* ReHashNick(char* Old, char* New)
3437 {
3438         user_hash::iterator newnick;
3439         user_hash::iterator oldnick = clientlist.find(Old);
3440
3441         log(DEBUG,"ReHashNick: %s %s",Old,New);
3442         
3443         if (!strcasecmp(Old,New))
3444         {
3445                 log(DEBUG,"old nick is new nick, skipping");
3446                 return oldnick->second;
3447         }
3448         
3449         if (oldnick == clientlist.end()) return NULL; /* doesnt exist */
3450
3451         log(DEBUG,"ReHashNick: Found hashed nick %s",Old);
3452
3453         clientlist[New] = new userrec();
3454         clientlist[New] = oldnick->second;
3455         /*delete oldnick->second; */
3456         clientlist.erase(oldnick);
3457
3458         log(DEBUG,"ReHashNick: Nick rehashed as %s",New);
3459         
3460         return clientlist[New];
3461 }
3462
3463 /* adds or updates an entry in the whowas list */
3464 void AddWhoWas(userrec* u)
3465 {
3466         user_hash::iterator iter = whowas.find(u->nick);
3467         userrec *a = new userrec();
3468         strcpy(a->nick,u->nick);
3469         strcpy(a->ident,u->ident);
3470         strcpy(a->dhost,u->dhost);
3471         strcpy(a->host,u->host);
3472         strcpy(a->fullname,u->fullname);
3473         strcpy(a->server,u->server);
3474         a->signon = u->signon;
3475
3476         /* MAX_WHOWAS:   max number of /WHOWAS items
3477          * WHOWAS_STALE: number of hours before a WHOWAS item is marked as stale and
3478          *               can be replaced by a newer one
3479          */
3480         
3481         if (iter == whowas.end())
3482         {
3483                 if (whowas.size() == WHOWAS_MAX)
3484                 {
3485                         for (user_hash::iterator i = whowas.begin(); i != whowas.end(); i++)
3486                         {
3487                                 // 3600 seconds in an hour ;)
3488                                 if ((i->second->signon)<(time(NULL)-(WHOWAS_STALE*3600)))
3489                                 {
3490                                         delete i->second;
3491                                         i->second = a;
3492                                         log(DEBUG,"added WHOWAS entry, purged an old record");
3493                                         return;
3494                                 }
3495                         }
3496                 }
3497                 else
3498                 {
3499                         log(DEBUG,"added fresh WHOWAS entry");
3500                         whowas[a->nick] = a;
3501                 }
3502         }
3503         else
3504         {
3505                 log(DEBUG,"updated WHOWAS entry");
3506                 delete iter->second;
3507                 iter->second = a;
3508         }
3509 }
3510
3511
3512 /* add a client connection to the sockets list */
3513 void AddClient(int socket, char* host, int port, bool iscached)
3514 {
3515         int i;
3516         int blocking = 1;
3517         char resolved[MAXBUF];
3518         string tempnick;
3519         char tn2[MAXBUF];
3520         user_hash::iterator iter;
3521
3522         tempnick = ConvToStr(socket) + "-unknown";
3523         sprintf(tn2,"%d-unknown",socket);
3524
3525         iter = clientlist.find(tempnick);
3526
3527         if (iter != clientlist.end()) return;
3528
3529         /*
3530          * It is OK to access the value here this way since we know
3531          * it exists, we just created it above.
3532          *
3533          * At NO other time should you access a value in a map or a
3534          * hash_map this way.
3535          */
3536         clientlist[tempnick] = new userrec();
3537
3538         NonBlocking(socket);
3539         log(DEBUG,"AddClient: %d %s %d",socket,host,port);
3540
3541         clientlist[tempnick]->fd = socket;
3542         strncpy(clientlist[tempnick]->nick, tn2,NICKMAX);
3543         strncpy(clientlist[tempnick]->host, host,160);
3544         strncpy(clientlist[tempnick]->dhost, host,160);
3545         strncpy(clientlist[tempnick]->server, ServerName,256);
3546         strncpy(clientlist[tempnick]->ident, "unknown",9);
3547         clientlist[tempnick]->registered = 0;
3548         clientlist[tempnick]->signon = time(NULL);
3549         clientlist[tempnick]->nping = time(NULL)+240;
3550         clientlist[tempnick]->lastping = 1;
3551         clientlist[tempnick]->port = port;
3552
3553         if (iscached)
3554         {
3555                 WriteServ(socket,"NOTICE Auth :Found your hostname (cached)...");
3556         }
3557         else
3558         {
3559                 WriteServ(socket,"NOTICE Auth :Looking up your hostname...");
3560         }
3561
3562         // set the registration timeout for this user
3563         unsigned long class_regtimeout = 90;
3564         for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
3565         {
3566                 if (match(clientlist[tempnick]->host,i->host) && (i->type == CC_ALLOW))
3567                 {
3568                         class_regtimeout = (unsigned long)i->registration_timeout;
3569                         break;
3570                 }
3571         }
3572         log(DEBUG,"Client has a connection timeout value of %d",class_regtimeout);
3573         clientlist[tempnick]->timeout = time(NULL)+class_regtimeout;
3574
3575         if (clientlist.size() == MAXCLIENTS)
3576                 kill_link(clientlist[tempnick],"No more connections allowed in this class");
3577 }
3578
3579 void handle_names(char **parameters, int pcnt, userrec *user)
3580 {
3581         chanrec* c;
3582
3583         if (loop_call(handle_names,parameters,pcnt,user,0,pcnt-1,0))
3584                 return;
3585         c = FindChan(parameters[0]);
3586         if (c)
3587         {
3588                 /*WriteServ(user->fd,"353 %s = %s :%s", user->nick, c->name,*/
3589                 userlist(user,c);
3590                 WriteServ(user->fd,"366 %s %s :End of /NAMES list.", user->nick, c->name);
3591         }
3592         else
3593         {
3594                 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
3595         }
3596 }
3597
3598
3599 void handle_privmsg(char **parameters, int pcnt, userrec *user)
3600 {
3601         userrec *dest;
3602         chanrec *chan;
3603
3604         user->idle_lastmsg = time(NULL);
3605         
3606         if (loop_call(handle_privmsg,parameters,pcnt,user,0,pcnt-2,0))
3607                 return;
3608         if (parameters[0][0] == '#')
3609         {
3610                 chan = FindChan(parameters[0]);
3611                 if (chan)
3612                 {
3613                         if ((chan->noexternal) && (!has_channel(user,chan)))
3614                         {
3615                                 WriteServ(user->fd,"404 %s %s :Cannot send to channel (no external messages)", user->nick, chan->name);
3616                                 return;
3617                         }
3618                         if ((chan->moderated) && (cstatus(user,chan)<STATUS_VOICE))
3619                         {
3620                                 WriteServ(user->fd,"404 %s %s :Cannot send to channel (+m)", user->nick, chan->name);
3621                                 return;
3622                         }
3623                         ChanExceptSender(chan, user, "PRIVMSG %s :%s", chan->name, parameters[1]);
3624                 }
3625                 else
3626                 {
3627                         /* no such nick/channel */
3628                         WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
3629                 }
3630                 return;
3631         }
3632         
3633         dest = Find(parameters[0]);
3634         if (dest)
3635         {
3636                 if (strcmp(dest->awaymsg,""))
3637                 {
3638                         /* auto respond with aweh msg */
3639                         WriteServ(user->fd,"301 %s %s :%s",user->nick,dest->nick,dest->awaymsg);
3640                 }
3641                 WriteTo(user, dest, "PRIVMSG %s :%s", dest->nick, parameters[1]);
3642         }
3643         else
3644         {
3645                 /* no such nick/channel */
3646                 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
3647         }
3648 }
3649
3650 void handle_notice(char **parameters, int pcnt, userrec *user)
3651 {
3652         userrec *dest;
3653         chanrec *chan;
3654
3655         user->idle_lastmsg = time(NULL);
3656         
3657         if (loop_call(handle_notice,parameters,pcnt,user,0,pcnt-2,0))
3658                 return;
3659         if (parameters[0][0] == '#')
3660         {
3661                 chan = FindChan(parameters[0]);
3662                 if (chan)
3663                 {
3664                         if ((chan->noexternal) && (!has_channel(user,chan)))
3665                         {
3666                                 WriteServ(user->fd,"404 %s %s :Cannot send to channel (no external messages)", user->nick, chan->name);
3667                                 return;
3668                         }
3669                         if ((chan->moderated) && (cstatus(user,chan)<STATUS_VOICE))
3670                         {
3671                                 WriteServ(user->fd,"404 %s %s :Cannot send to channel (+m)", user->nick, chan->name);
3672                                 return;
3673                         }
3674                         WriteChannel(chan, user, "NOTICE %s :%s", chan->name, parameters[1]);
3675                 }
3676                 else
3677                 {
3678                         /* no such nick/channel */
3679                         WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
3680                 }
3681                 return;
3682         }
3683         
3684         dest = Find(parameters[0]);
3685         if (dest)
3686         {
3687                 WriteTo(user, dest, "NOTICE %s :%s", dest->nick, parameters[1]);
3688         }
3689         else
3690         {
3691                 /* no such nick/channel */
3692                 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
3693         }
3694 }
3695
3696 char lst[MAXBUF];
3697
3698 char* chlist(userrec *user)
3699 {
3700         int i = 0;
3701         char cmp[MAXBUF];
3702
3703         log(DEBUG,"chlist: %s",user->nick);
3704         strcpy(lst,"");
3705         if (!user)
3706         {
3707                 return lst;
3708         }
3709         for (i = 0; i != MAXCHANS; i++)
3710         {
3711                 if (user->chans[i].channel != NULL)
3712                 {
3713                         if (user->chans[i].channel->name)
3714                         {
3715                                 strcpy(cmp,user->chans[i].channel->name);
3716                                 strcat(cmp," ");
3717                                 if (!strstr(lst,cmp))
3718                                 {
3719                                         if ((!user->chans[i].channel->c_private) && (!user->chans[i].channel->secret))
3720                                         {
3721                                                 strcat(lst,cmode(user,user->chans[i].channel));
3722                                                 strcat(lst,user->chans[i].channel->name);
3723                                                 strcat(lst," ");
3724                                         }
3725                                 }
3726                         }
3727                 }
3728         }
3729         return lst;
3730 }
3731
3732 void handle_info(char **parameters, int pcnt, userrec *user)
3733 {
3734         WriteServ(user->fd,"371 %s :The Inspire IRCd Project Has been brought to you by the following people..",user->nick);
3735         WriteServ(user->fd,"371 %s :Craig Edwards, Craig McLure, and Others..",user->nick);
3736         WriteServ(user->fd,"371 %s :Will finish this later when i can be arsed :p",user->nick);
3737         FOREACH_MOD OnInfo(user);
3738         WriteServ(user->fd,"374 %s :End of /INFO list",user->nick);
3739 }
3740
3741 void handle_time(char **parameters, int pcnt, userrec *user)
3742 {
3743         time_t rawtime;
3744         struct tm * timeinfo;
3745
3746         time ( &rawtime );
3747         timeinfo = localtime ( &rawtime );
3748         WriteServ(user->fd,"391 %s %s :%s",user->nick,ServerName, asctime (timeinfo) );
3749   
3750 }
3751
3752 void handle_whois(char **parameters, int pcnt, userrec *user)
3753 {
3754         userrec *dest;
3755         char *t;
3756
3757         if (loop_call(handle_whois,parameters,pcnt,user,0,pcnt-1,0))
3758                 return;
3759         dest = Find(parameters[0]);
3760         if (dest)
3761         {
3762                 // bug found by phidjit - were able to whois an incomplete connection if it had sent a NICK or USER
3763                 if (dest->registered == 7)
3764                 {
3765                         WriteServ(user->fd,"311 %s %s %s %s * :%s",user->nick, dest->nick, dest->ident, dest->dhost, dest->fullname);
3766                         if ((user == dest) || (strchr(user->modes,'o')))
3767                         {
3768                                 WriteServ(user->fd,"378 %s %s :is connecting from *@%s",user->nick, dest->nick, dest->host);
3769                         }
3770                         if (strcmp(chlist(dest),""))
3771                         {
3772                                 WriteServ(user->fd,"319 %s %s :%s",user->nick, dest->nick, chlist(dest));
3773                         }
3774                         WriteServ(user->fd,"312 %s %s %s :%s",user->nick, dest->nick, dest->server, ServerDesc);
3775                         if (strcmp(dest->awaymsg,""))
3776                         {
3777                                 WriteServ(user->fd,"301 %s %s :%s",user->nick, dest->nick, dest->awaymsg);
3778                         }
3779                         if (strchr(dest->modes,'o'))
3780                         {
3781                                 WriteServ(user->fd,"313 %s %s :is an IRC operator",user->nick, dest->nick);
3782                         }
3783                         FOREACH_MOD OnWhois(user,dest);
3784                         //WriteServ(user->fd,"310 %s %s :is available for help.",user->nick, dest->nick);
3785                         WriteServ(user->fd,"317 %s %s %d %d :seconds idle, signon time",user->nick, dest->nick, abs((dest->idle_lastmsg)-time(NULL)), dest->signon);
3786                         
3787                         WriteServ(user->fd,"318 %s %s :End of /WHOIS list.",user->nick, dest->nick);
3788                 }
3789                 else
3790                 {
3791                         WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
3792                 }
3793         }
3794         else
3795         {
3796                 /* no such nick/channel */
3797                 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
3798         }
3799 }
3800
3801 void handle_quit(char **parameters, int pcnt, userrec *user)
3802 {
3803         user_hash::iterator iter = clientlist.find(user->nick);
3804         char* reason;
3805
3806         if (user->registered == 7)
3807         {
3808                 /* theres more to do here, but for now just close the socket */
3809                 if (pcnt == 1)
3810                 {
3811                         if (parameters[0][0] == ':')
3812                         {
3813                                 *parameters[0]++;
3814                         }
3815                         reason = parameters[0];
3816
3817                         if (strlen(reason)>MAXQUIT)
3818                         {
3819                                 reason[MAXQUIT-1] = '\0';
3820                         }
3821
3822                         Write(user->fd,"ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,parameters[0]);
3823                         WriteOpers("*** Client exiting: %s!%s@%s [%s]",user->nick,user->ident,user->host,parameters[0]);
3824                         WriteCommonExcept(user,"QUIT :%s%s",PrefixQuit,parameters[0]);
3825                 }
3826                 else
3827                 {
3828                         Write(user->fd,"ERROR :Closing link (%s@%s) [QUIT]",user->ident,user->host);
3829                         WriteOpers("*** Client exiting: %s!%s@%s [Client exited]",user->nick,user->ident,user->host);
3830                         WriteCommonExcept(user,"QUIT :Client exited");
3831                 }
3832                 FOREACH_MOD OnUserQuit(user);
3833                 AddWhoWas(user);
3834         }
3835
3836         /* push the socket on a stack of sockets due to be closed at the next opportunity */
3837         fd_reap.push_back(user->fd);
3838         
3839         if (iter != clientlist.end())
3840         {
3841                 log(DEBUG,"deleting user hash value %d",iter->second);
3842                 if ((iter->second) && (user->registered == 7)) {
3843                         delete iter->second;
3844                 }
3845                 clientlist.erase(iter);
3846         }
3847
3848         if (user->registered == 7) {
3849                 purge_empty_chans();
3850         }
3851 }
3852
3853 void handle_who(char **parameters, int pcnt, userrec *user)
3854 {
3855         chanrec* Ptr = NULL;
3856         
3857         /* theres more to do here, but for now just close the socket */
3858         if (pcnt == 1)
3859         {
3860                 if ((!strcmp(parameters[0],"0")) || (!strcmp(parameters[0],"*")))
3861                 {
3862                         if (user->chans[0].channel)
3863                         {
3864                                 Ptr = user->chans[0].channel;
3865                                 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
3866                                 {
3867                                         if ((common_channels(user,i->second)) && (isnick(i->second->nick)))
3868                                         {
3869                                                 WriteServ(user->fd,"352 %s %s %s %s %s %s Hr@ :0 %s",user->nick, Ptr->name, i->second->ident, i->second->dhost, ServerName, i->second->nick, i->second->fullname);
3870                                         }
3871                                 }
3872                         }
3873                         if (Ptr)
3874                         {
3875                                 WriteServ(user->fd,"315 %s %s :End of /WHO list.",user->nick, Ptr->name);
3876                         }
3877                         else
3878                         {
3879                                 WriteServ(user->fd,"315 %s %s :End of /WHO list.",user->nick, user->nick);
3880                         }
3881                         return;
3882                 }
3883                 if (parameters[0][0] = '#')
3884                 {
3885                         Ptr = FindChan(parameters[0]);
3886                         if (Ptr)
3887                         {
3888                                 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
3889                                 {
3890                                         if ((has_channel(i->second,Ptr)) && (isnick(i->second->nick)))
3891                                         {
3892                                                 WriteServ(user->fd,"352 %s %s %s %s %s %s Hr@ :0 %s",user->nick, Ptr->name, i->second->ident, i->second->dhost, ServerName, i->second->nick, i->second->fullname);
3893                                         }
3894                                 }
3895                                 WriteServ(user->fd,"315 %s %s :End of /WHO list.",user->nick, Ptr->name);
3896                         }
3897                         else
3898                         {
3899                                 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
3900                         }
3901                 }
3902         }
3903         if (pcnt == 2)
3904         {
3905                 if ((!strcmp(parameters[0],"0")) || (!strcmp(parameters[0],"*")) && (!strcmp(parameters[1],"o")))
3906                 {
3907                         Ptr = user->chans[0].channel;
3908                         printf(user->chans[0].channel->name);
3909                         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
3910                         {
3911                                 if ((common_channels(user,i->second)) && (isnick(i->second->nick)))
3912                                 {
3913                                         if (strchr(i->second->modes,'o'))
3914                                         {
3915                                                 WriteServ(user->fd,"352 %s %s %s %s %s %s Hr@ :0 %s",user->nick, Ptr->name, i->second->ident, i->second->dhost, ServerName, i->second->nick, i->second->fullname);
3916                                         }
3917                                 }
3918                         }
3919                         WriteServ(user->fd,"315 %s %s :End of /WHO list.",user->nick, Ptr->name);
3920                         return;
3921                 }
3922         }
3923 }
3924
3925 void handle_wallops(char **parameters, int pcnt, userrec *user)
3926 {
3927         WriteWallOps(user,"%s",parameters[0]);
3928 }
3929
3930 void handle_list(char **parameters, int pcnt, userrec *user)
3931 {
3932         chanrec* Ptr;
3933         
3934         WriteServ(user->fd,"321 %s Channel :Users Name",user->nick);
3935         for (chan_hash::const_iterator i = chanlist.begin(); i != chanlist.end(); i++)
3936         {
3937                 if ((!i->second->c_private) && (!i->second->secret))
3938                 {
3939                         WriteServ(user->fd,"322 %s %s %d :[+%s] %s",user->nick,i->second->name,usercount_i(i->second),chanmodes(i->second),i->second->topic);
3940                 }
3941         }
3942         WriteServ(user->fd,"323 %s :End of channel list.",user->nick);
3943 }
3944
3945
3946 void handle_rehash(char **parameters, int pcnt, userrec *user)
3947 {
3948         WriteServ(user->fd,"382 %s %s :Rehashing",user->nick,CONFIG_FILE);
3949         ReadConfig();
3950         FOREACH_MOD OnRehash();
3951         WriteOpers("%s is rehashing config file %s",user->nick,CONFIG_FILE);
3952 }
3953
3954
3955 int usercnt(void)
3956 {
3957         return clientlist.size();
3958 }
3959
3960 int usercount_invisible(void)
3961 {
3962         int c = 0;
3963
3964         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
3965         {
3966                 if ((i->second->fd) && (isnick(i->second->nick)) && (strchr(i->second->modes,'i'))) c++;
3967         }
3968         return c;
3969 }
3970
3971 int usercount_opers(void)
3972 {
3973         int c = 0;
3974
3975         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
3976         {
3977                 if ((i->second->fd) && (isnick(i->second->nick)) && (strchr(i->second->modes,'o'))) c++;
3978         }
3979         return c;
3980 }
3981
3982 int usercount_unknown(void)
3983 {
3984         int c = 0;
3985
3986         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
3987         {
3988                 if ((i->second->fd) && (i->second->registered != 7))
3989                         c++;
3990         }
3991         return c;
3992 }
3993
3994 int chancount(void)
3995 {
3996         return chanlist.size();
3997 }
3998
3999 int servercount(void)
4000 {
4001         return 1;
4002 }
4003
4004 void handle_lusers(char **parameters, int pcnt, userrec *user)
4005 {
4006         WriteServ(user->fd,"251 %s :There are %d users and %d invisible on %d servers",user->nick,usercnt()-usercount_invisible(),usercount_invisible(),servercount());
4007         WriteServ(user->fd,"252 %s %d :operator(s) online",user->nick,usercount_opers());
4008         WriteServ(user->fd,"253 %s %d :unknown connections",user->nick,usercount_unknown());
4009         WriteServ(user->fd,"254 %s %d :channels formed",user->nick,chancount());
4010         WriteServ(user->fd,"254 %s :I have %d clients and 0 servers",user->nick,usercnt());
4011 }
4012
4013 void handle_admin(char **parameters, int pcnt, userrec *user)
4014 {
4015         WriteServ(user->fd,"256 %s :Administrative info for %s",user->nick,ServerName);
4016         WriteServ(user->fd,"257 %s :Name     - %s",user->nick,AdminName);
4017         WriteServ(user->fd,"258 %s :Nickname - %s",user->nick,AdminNick);
4018         WriteServ(user->fd,"258 %s :E-Mail   - %s",user->nick,AdminEmail);
4019 }
4020
4021 void ShowMOTD(userrec *user)
4022 {
4023         if (!MOTD.size())
4024         {
4025                 WriteServ(user->fd,"422 %s :Message of the day file is missing.",user->nick);
4026                 return;
4027         }
4028         WriteServ(user->fd,"375 %s :- %s message of the day",user->nick,ServerName);
4029         for (int i = 0; i != MOTD.size(); i++)
4030         {
4031                                 WriteServ(user->fd,"372 %s :- %s",user->nick,MOTD[i].c_str());
4032         }
4033         WriteServ(user->fd,"376 %s :End of %s message of the day.",user->nick,ServerName);
4034 }
4035
4036 void ShowRULES(userrec *user)
4037 {
4038         if (!RULES.size())
4039         {
4040                 WriteServ(user->fd,"NOTICE %s :Rules file is missing.",user->nick);
4041                 return;
4042         }
4043         WriteServ(user->fd,"NOTICE %s :%s rules",user->nick,ServerName);
4044         for (int i = 0; i != RULES.size(); i++)
4045         {
4046                                 WriteServ(user->fd,"NOTICE %s :%s",user->nick,RULES[i].c_str());
4047         }
4048         WriteServ(user->fd,"NOTICE %s :End of %s rules.",user->nick,ServerName);
4049 }
4050
4051 /* shows the message of the day, and any other on-logon stuff */
4052 void ConnectUser(userrec *user)
4053 {
4054         user->registered = 7;
4055         user->idle_lastmsg = time(NULL);
4056         log(DEBUG,"ConnectUser: %s",user->nick);
4057
4058         if (strcmp(Passwd(user),"") && (!user->haspassed))
4059         {
4060                 kill_link(user,"Invalid password");
4061                 return;
4062         }
4063         if (IsDenied(user))
4064         {
4065                 kill_link(user,"Unauthorised connection");
4066                 return;
4067         }
4068
4069         WriteServ(user->fd,"NOTICE Auth :Welcome to \002%s\002!",Network);
4070         WriteServ(user->fd,"001 %s :Welcome to the %s IRC Network %s!%s@%s",user->nick,Network,user->nick,user->ident,user->host);
4071         WriteServ(user->fd,"002 %s :Your host is %s, running version %s",user->nick,ServerName,VERSION);
4072         WriteServ(user->fd,"003 %s :This server was created %s %s",user->nick,__TIME__,__DATE__);
4073         WriteServ(user->fd,"004 %s :%s %s iowghraAsORVSxNCWqBzvdHtGI lvhopsmntikrRcaqOALQbSeKVfHGCuzN",user->nick,ServerName,VERSION);
4074         WriteServ(user->fd,"005 %s :MAP KNOCK SAFELIST HCN MAXCHANNELS=20 MAXBANS=60 NICKLEN=30 TOPICLEN=307 KICKLEN=307 MAXTARGETS=20 AWAYLEN=307 :are supported by this server",user->nick);
4075         WriteServ(user->fd,"005 %s :WALLCHOPS WATCH=128 SILENCE=5 MODES=13 CHANTYPES=# PREFIX=(ohv)@%c+ CHANMODES=ohvbeqa,kfL,l,psmntirRcOAQKVHGCuzN NETWORK=%s :are supported by this server",user->nick,'%',Network);
4076         ShowMOTD(user);
4077         FOREACH_MOD OnUserConnect(user);
4078         WriteOpers("*** Client connecting on port %d: %s!%s@%s",user->port,user->nick,user->ident,user->host);
4079 }
4080
4081 void handle_version(char **parameters, int pcnt, userrec *user)
4082 {
4083         WriteServ(user->fd,"351 %s :%s %s %s :%s",user->nick,VERSION,"$Id$",ServerName,SYSTEM);
4084 }
4085
4086 void handle_ping(char **parameters, int pcnt, userrec *user)
4087 {
4088         WriteServ(user->fd,"PONG %s :%s",ServerName,parameters[0]);
4089 }
4090
4091 void handle_pong(char **parameters, int pcnt, userrec *user)
4092 {
4093         // set the user as alive so they survive to next ping
4094         user->lastping = 1;
4095 }
4096
4097 void handle_motd(char **parameters, int pcnt, userrec *user)
4098 {
4099         ShowMOTD(user);
4100 }
4101
4102 void handle_rules(char **parameters, int pcnt, userrec *user)
4103 {
4104         ShowRULES(user);
4105 }
4106
4107 void handle_user(char **parameters, int pcnt, userrec *user)
4108 {
4109         if (user->registered < 3)
4110         {
4111                 if (isident(parameters[0]) == 0) {
4112                         // This kinda Sucks, According to the RFC thou, its either this,
4113                         // or "You have already registered" :p -- Craig
4114                         WriteServ(user->fd,"461 %s USER :Not enough parameters",user->nick);
4115                 }
4116                 else {
4117                         WriteServ(user->fd,"NOTICE Auth :No ident response, ident prefixed with ~");
4118                         strcpy(user->ident,"~"); /* we arent checking ident... but these days why bother anyway? */
4119                         strncat(user->ident,parameters[0],IDENTMAX);
4120                         strncpy(user->fullname,parameters[3],128);
4121                         user->registered = (user->registered | 1);
4122                 }
4123         }
4124         else
4125         {
4126                 WriteServ(user->fd,"462 %s :You may not reregister",user->nick);
4127                 return;
4128         }
4129         /* parameters 2 and 3 are local and remote hosts, ignored when sent by client connection */
4130         if (user->registered == 3)
4131         {
4132                 /* user is registered now, bit 0 = USER command, bit 1 = sent a NICK command */
4133                 ConnectUser(user);
4134         }
4135 }
4136
4137 void handle_userhost(char **parameters, int pcnt, userrec *user)
4138 {
4139         char Return[MAXBUF],junk[MAXBUF];
4140         sprintf(Return,"302 %s :",user->nick);
4141         for (int i = 0; i < pcnt; i++)
4142         {
4143                 userrec *u = Find(parameters[i]);
4144                 if (u)
4145                 {
4146                         if (strchr(u->modes,'o'))
4147                         {
4148                                 sprintf(junk,"%s*=+%s@%s ",u->nick,u->ident,u->host);
4149                                 strcat(Return,junk);
4150                         }
4151                         else
4152                         {
4153                                 sprintf(junk,"%s=+%s@%s ",u->nick,u->ident,u->host);
4154                                 strcat(Return,junk);
4155                         }
4156                 }
4157         }
4158         WriteServ(user->fd,Return);
4159 }
4160
4161
4162 void handle_ison(char **parameters, int pcnt, userrec *user)
4163 {
4164         char Return[MAXBUF];
4165         sprintf(Return,"303 %s :",user->nick);
4166         for (int i = 0; i < pcnt; i++)
4167         {
4168                 userrec *u = Find(parameters[i]);
4169                 if (u)
4170                 {
4171                         strcat(Return,u->nick);
4172                         strcat(Return," ");
4173                 }
4174         }
4175         WriteServ(user->fd,Return);
4176 }
4177
4178
4179 void handle_away(char **parameters, int pcnt, userrec *user)
4180 {
4181         if (pcnt)
4182         {
4183                 strcpy(user->awaymsg,parameters[0]);
4184                 WriteServ(user->fd,"306 %s :You have been marked as being away",user->nick);
4185         }
4186         else
4187         {
4188                 strcpy(user->awaymsg,"");
4189                 WriteServ(user->fd,"305 %s :You are no longer marked as being away",user->nick);
4190         }
4191 }
4192
4193 void handle_whowas(char **parameters, int pcnt, userrec* user)
4194 {
4195         user_hash::iterator i = whowas.find(parameters[0]);
4196
4197         if (i == whowas.end())
4198         {
4199                 WriteServ(user->fd,"406 %s %s :There was no such nickname",user->nick,parameters[0]);
4200                 WriteServ(user->fd,"369 %s %s :End of WHOWAS",user->nick,parameters[0]);
4201         }
4202         else
4203         {
4204                 time_t rawtime = i->second->signon;
4205                 tm *timeinfo;
4206                 char b[MAXBUF];
4207                 
4208                 timeinfo = localtime(&rawtime);
4209                 strcpy(b,asctime(timeinfo));
4210                 b[strlen(b)-1] = '\0';
4211                 
4212                 WriteServ(user->fd,"314 %s %s %s %s * :%s",user->nick,i->second->nick,i->second->ident,i->second->dhost,i->second->fullname);
4213                 WriteServ(user->fd,"312 %s %s %s :%s",user->nick,i->second->nick,i->second->server,b);
4214                 WriteServ(user->fd,"369 %s %s :End of WHOWAS",user->nick,parameters[0]);
4215         }
4216
4217 }
4218
4219 void handle_trace(char **parameters, int pcnt, userrec *user)
4220 {
4221         for (user_hash::iterator i = clientlist.begin(); i != clientlist.end(); i++)
4222         {
4223                 if (i->second)
4224                 {
4225                         if (isnick(i->second->nick))
4226                         {
4227                                 if (strchr(i->second->modes,'o'))
4228                                 {
4229                                         WriteServ(user->fd,"205 %s :Oper 0 %s",user->nick,i->second->nick);
4230                                 }
4231                                 else
4232                                 {
4233                                         WriteServ(user->fd,"204 %s :User 0 %s",user->nick,i->second->nick);
4234                                 }
4235                         }
4236                         else
4237                         {
4238                                 WriteServ(user->fd,"203 %s :???? 0 [%s]",user->nick,i->second->host);
4239                         }
4240                 }
4241         }
4242 }
4243
4244 void handle_modules(char **parameters, int pcnt, userrec *user)
4245 {
4246         for (int i = 0; i < module_names.size(); i++)
4247         {
4248                         Version V = modules[i]->GetVersion();
4249                         WriteServ(user->fd,"900 0x%08lx %d.%d.%d.%d :%s",modules[i],V.Major,V.Minor,V.Revision,V.Build,module_names[i].c_str());
4250         }
4251 }
4252
4253 void handle_stats(char **parameters, int pcnt, userrec *user)
4254 {
4255         if (pcnt != 1)
4256         {
4257                 return;
4258         }
4259         if (strlen(parameters[0])>1)
4260         {
4261                 /* make the stats query 1 character long */
4262                 parameters[0][1] = '\0';
4263         }
4264
4265         /* stats m (list number of times each command has been used, plus bytecount) */
4266         if (!strcasecmp(parameters[0],"m"))
4267         {
4268                 for (int i = 0; i < cmdlist.size(); i++)
4269                 {
4270                         if (cmdlist[i].handler_function)
4271                         {
4272                                 if (cmdlist[i].use_count)
4273                                 {
4274                                         /* RPL_STATSCOMMANDS */
4275                                         WriteServ(user->fd,"212 %s %s %d %d",user->nick,cmdlist[i].command,cmdlist[i].use_count,cmdlist[i].total_bytes);
4276                                 }
4277                         }
4278                 }
4279                         
4280         }
4281
4282         /* stats z (debug and memory info) */
4283         if (!strcasecmp(parameters[0],"z"))
4284         {
4285                 WriteServ(user->fd,"249 %s :Users(HASH_MAP) %d (%d bytes, %d buckets)",user->nick,clientlist.size(),clientlist.size()*sizeof(userrec),clientlist.bucket_count());
4286                 WriteServ(user->fd,"249 %s :Channels(HASH_MAP) %d (%d bytes, %d buckets)",user->nick,chanlist.size(),chanlist.size()*sizeof(chanrec),chanlist.bucket_count());
4287                 WriteServ(user->fd,"249 %s :Commands(VECTOR) %d (%d bytes)",user->nick,cmdlist.size(),cmdlist.size()*sizeof(command_t));
4288                 WriteServ(user->fd,"249 %s :MOTD(VECTOR) %d, RULES(VECTOR) %d",user->nick,MOTD.size(),RULES.size());
4289                 WriteServ(user->fd,"249 %s :address_cache(HASH_MAP) %d (%d buckets)",user->nick,IP.size(),IP.bucket_count());
4290                 WriteServ(user->fd,"249 %s :Modules(VECTOR) %d (%d)",user->nick,modules.size(),modules.size()*sizeof(Module));
4291                 WriteServ(user->fd,"249 %s :ClassFactories(VECTOR) %d (%d)",user->nick,factory.size(),factory.size()*sizeof(ircd_module));
4292                 WriteServ(user->fd,"249 %s :Ports(STATIC_ARRAY) %d",user->nick,boundPortCount);
4293         }
4294         
4295         /* stats o */
4296         if (!strcasecmp(parameters[0],"o"))
4297         {
4298                 for (int i = 0; i < ConfValueEnum("oper"); i++)
4299                 {
4300                         char LoginName[MAXBUF];
4301                         char HostName[MAXBUF];
4302                         char OperType[MAXBUF];
4303                         ConfValue("oper","name",i,LoginName);
4304                         ConfValue("oper","host",i,HostName);
4305                         ConfValue("oper","type",i,OperType);
4306                         WriteServ(user->fd,"243 %s O %s * %s %s 0",user->nick,HostName,LoginName,OperType);
4307                 }
4308         }
4309         
4310         /* stats l (show user I/O stats) */
4311         if (!strcasecmp(parameters[0],"l"))
4312         {
4313                 WriteServ(user->fd,"211 %s :server:port nick bytes_in cmds_in bytes_out cmds_out",user->nick);
4314                 for (user_hash::iterator i = clientlist.begin(); i != clientlist.end(); i++)
4315                 {
4316                         if (isnick(i->second->nick))
4317                         {
4318                                 WriteServ(user->fd,"211 %s :%s:%d %s %d %d %d %d",user->nick,ServerName,i->second->port,i->second->nick,i->second->bytes_in,i->second->cmds_in,i->second->bytes_out,i->second->cmds_out);
4319                         }
4320                         else
4321                         {
4322                                 WriteServ(user->fd,"211 %s :%s:%d (unknown@%d) %d %d %d %d",user->nick,ServerName,i->second->port,i->second->fd,i->second->bytes_in,i->second->cmds_in,i->second->bytes_out,i->second->cmds_out);
4323                         }
4324                         
4325                 }
4326         }
4327         
4328         /* stats u (show server uptime) */
4329         if (!strcasecmp(parameters[0],"u"))
4330         {
4331                 time_t current_time = 0;
4332                 current_time = time(NULL);
4333                 time_t server_uptime = current_time - startup_time;
4334                 struct tm* stime;
4335                 stime = gmtime(&server_uptime);
4336                 /* i dont know who the hell would have an ircd running for over a year nonstop, but
4337                  * Craig suggested this, and it seemed a good idea so in it went */
4338                 if (stime->tm_year > 70)
4339                 {
4340                         WriteServ(user->fd,"242 %s :Server up %d years, %d days, %.2d:%.2d:%.2d",user->nick,(stime->tm_year-70),stime->tm_yday,stime->tm_hour,stime->tm_min,stime->tm_sec);
4341                 }
4342                 else
4343                 {
4344                         WriteServ(user->fd,"242 %s :Server up %d days, %.2d:%.2d:%.2d",user->nick,stime->tm_yday,stime->tm_hour,stime->tm_min,stime->tm_sec);
4345                 }
4346         }
4347
4348         WriteServ(user->fd,"219 %s %s :End of /STATS report",user->nick,parameters[0]);
4349         WriteOpers("*** Notice: Stats '%s' requested by %s (%s@%s)",parameters[0],user->nick,user->ident,user->host);
4350         
4351 }
4352
4353 void handle_connect(char **parameters, int pcnt, userrec *user)
4354 {
4355         char Link_ServerName[1024];
4356         char Link_IPAddr[1024];
4357         char Link_Port[1024];
4358         char Link_Pass[1024];
4359         int LinkPort;
4360         bool found = false;
4361         
4362         for (int i = 0; i < ConfValueEnum("link"); i++)
4363         {
4364                 ConfValue("link","name",i,Link_ServerName);
4365                 ConfValue("link","ipaddr",i,Link_IPAddr);
4366                 ConfValue("link","port",i,Link_Port);
4367                 ConfValue("link","sendpass",i,Link_Pass);
4368                 log(DEBUG,"(%d) Comparing against name='%s', ipaddr='%s', port='%s', recvpass='%s'",i,Link_ServerName,Link_IPAddr,Link_Port,Link_Pass);
4369                 LinkPort = atoi(Link_Port);
4370                 if (match(Link_ServerName,parameters[0])) {
4371                         found = true;
4372                 }
4373         }
4374         
4375         if (!found) {
4376                 WriteServ(user->fd,"NOTICE %s :*** Failed to connect to %s: No servers matching this pattern are configured for linking.",user->nick,parameters[0]);
4377                 return;
4378         }
4379         
4380         // TODO: Perform a check here to stop a server being linked twice!
4381
4382         WriteServ(user->fd,"NOTICE %s :*** Connecting to %s (%s) port %s...",user->nick,Link_ServerName,Link_IPAddr,Link_Port);
4383
4384         if (me[defaultRoute])
4385         {
4386
4387                 // at this point parameters[0] is an ip in a string.
4388                 // TODO: Look this up from the <link> blocks instead!
4389                 for (int j = 0; j < 255; j++) {
4390                         if (servers[j] == NULL) {
4391                                 servers[j] = new serverrec;
4392                                 strcpy(servers[j]->internal_addr,Link_IPAddr);
4393                                 strcpy(servers[j]->name,Link_ServerName);
4394                                 log(DEBUG,"Allocated new serverrec");
4395                                 if (!me[defaultRoute]->BeginLink(Link_IPAddr,LinkPort,Link_Pass))
4396                                 {
4397                                         WriteServ(user->fd,"NOTICE %s :*** Failed to send auth packet to %s!",user->nick,Link_IPAddr);
4398                                 }
4399                                 return;
4400                         }
4401                 }
4402                 WriteServ(user->fd,"NOTICE %s :*** Failed to create server record for address %s!",user->nick,Link_IPAddr);
4403         }
4404         else
4405         {
4406                 WriteServ(user->fd,"NOTICE %s :No default route is defined for server connections on this server. You must define a server connection to be default route so that sockets can be bound to it.",user->nick);
4407         }
4408 }
4409
4410 void handle_squit(char **parameters, int pcnt, userrec *user)
4411 {
4412         // send out an squit across the mesh and then clear the server list (for local squit)
4413 }
4414
4415 void handle_oper(char **parameters, int pcnt, userrec *user)
4416 {
4417         char LoginName[MAXBUF];
4418         char Password[MAXBUF];
4419         char OperType[MAXBUF];
4420         char TypeName[MAXBUF];
4421         char Hostname[MAXBUF];
4422         int i,j;
4423
4424         for (i = 0; i < ConfValueEnum("oper"); i++)
4425         {
4426                 ConfValue("oper","name",i,LoginName);
4427                 ConfValue("oper","password",i,Password);
4428                 if ((!strcmp(LoginName,parameters[0])) && (!strcmp(Password,parameters[1])))
4429                 {
4430                         /* correct oper credentials */
4431                         ConfValue("oper","type",i,OperType);
4432                         WriteOpers("*** %s (%s@%s) is now an IRC operator of type %s",user->nick,user->ident,user->host,OperType);
4433                         WriteServ(user->fd,"381 %s :You are now an IRC operator of type %s",user->nick,OperType);
4434                         WriteServ(user->fd,"MODE %s :+o",user->nick);
4435                         for (j =0; j < ConfValueEnum("type"); j++)
4436                         {
4437                                 ConfValue("type","name",j,TypeName);
4438                                 if (!strcmp(TypeName,OperType))
4439                                 {
4440                                         /* found this oper's opertype */
4441                                         ConfValue("type","host",j,Hostname);
4442                                         strncpy(user->dhost,Hostname,256);
4443                                 }
4444                         }
4445                         if (!strchr(user->modes,'o'))
4446                         {
4447                                 strcat(user->modes,"o");
4448                         }
4449                         FOREACH_MOD OnOper(user);
4450                         return;
4451                 }
4452         }
4453         /* no such oper */
4454         WriteServ(user->fd,"491 %s :Invalid oper credentials",user->nick);
4455         WriteOpers("*** WARNING! Failed oper attempt by %s!%s@%s!",user->nick,user->ident,user->host);
4456 }
4457                                 
4458 void handle_nick(char **parameters, int pcnt, userrec *user)
4459 {
4460         if (pcnt < 1) 
4461         {
4462                 log(DEBUG,"not enough params for handle_nick");
4463                 return;
4464         }
4465         if (!parameters[0])
4466         {
4467                 log(DEBUG,"invalid parameter passed to handle_nick");
4468                 return;
4469         }
4470         if (!strlen(parameters[0]))
4471         {
4472                 log(DEBUG,"zero length new nick passed to handle_nick");
4473                 return;
4474         }
4475         if (!user)
4476         {
4477                 log(DEBUG,"invalid user passed to handle_nick");
4478                 return;
4479         }
4480         if (!user->nick)
4481         {
4482                 log(DEBUG,"invalid old nick passed to handle_nick");
4483                 return;
4484         }
4485         if (!strcasecmp(user->nick,parameters[0]))
4486         {
4487                 log(DEBUG,"old nick is new nick, skipping");
4488                 return;
4489         }
4490         else
4491         {
4492                 if (strlen(parameters[0]) > 1)
4493                 {
4494                         if (parameters[0][0] == ':')
4495                         {
4496                                 *parameters[0]++;
4497                         }
4498                 }
4499                 if ((Find(parameters[0])) && (Find(parameters[0]) != user))
4500                 {
4501                         WriteServ(user->fd,"433 %s %s :Nickname is already in use.",user->nick,parameters[0]);
4502                         return;
4503                 }
4504         }
4505         if (isnick(parameters[0]) == 0)
4506         {
4507                 WriteServ(user->fd,"432 %s %s :Erroneous Nickname",user->nick,parameters[0]);
4508                 return;
4509         }
4510
4511         if (user->registered == 7)
4512         {
4513                 WriteCommon(user,"NICK %s",parameters[0]);
4514         }
4515         
4516         /* change the nick of the user in the users_hash */
4517         user = ReHashNick(user->nick, parameters[0]);
4518         /* actually change the nick within the record */
4519         if (!user) return;
4520         if (!user->nick) return;
4521
4522         strncpy(user->nick, parameters[0],NICKMAX);
4523
4524         log(DEBUG,"new nick set: %s",user->nick);
4525         
4526         if (user->registered < 3)
4527                 user->registered = (user->registered | 2);
4528         if (user->registered == 3)
4529         {
4530                 /* user is registered now, bit 0 = USER command, bit 1 = sent a NICK command */
4531                 ConnectUser(user);
4532         }
4533         log(DEBUG,"exit nickchange: %s",user->nick);
4534 }
4535
4536 int process_parameters(char **command_p,char *parameters)
4537 {
4538         int i = 0;
4539         int j = 0;
4540         int q = 0;
4541         q = strlen(parameters);
4542         if (!q)
4543         {
4544                 /* no parameters, command_p invalid! */
4545                 return 0;
4546         }
4547         if (parameters[0] == ':')
4548         {
4549                 command_p[0] = parameters+1;
4550                 return 1;
4551         }
4552         if (q)
4553         {
4554                 if ((strchr(parameters,' ')==NULL) || (parameters[0] == ':'))
4555                 {
4556                         /* only one parameter */
4557                         command_p[0] = parameters;
4558                         if (parameters[0] == ':')
4559                         {
4560                                 if (strchr(parameters,' ') != NULL)
4561                                 {
4562                                         command_p[0]++;
4563                                 }
4564                         }
4565                         return 1;
4566                 }
4567         }
4568         command_p[j++] = parameters;
4569         for (i = 0; i <= q; i++)
4570         {
4571                 if (parameters[i] == ' ')
4572                 {
4573                         command_p[j++] = parameters+i+1;
4574                         parameters[i] = '\0';
4575                         if (command_p[j-1][0] == ':')
4576                         {
4577                                 *command_p[j-1]++; /* remove dodgy ":" */
4578                                 break;
4579                                 /* parameter like this marks end of the sequence */
4580                         }
4581                 }
4582         }
4583         return j; /* returns total number of items in the list */
4584 }
4585
4586 void process_command(userrec *user, char* cmd)
4587 {
4588         char *parameters;
4589         char *command;
4590         char *command_p[127];
4591         char p[MAXBUF], temp[MAXBUF];
4592         int i, j, items, cmd_found;
4593
4594         for (int i = 0; i < 127; i++)
4595                 command_p[i] = NULL;
4596
4597         if (!user)
4598         {
4599                 return;
4600         }
4601         if (!cmd)
4602         {
4603                 return;
4604         }
4605         if (!strcmp(cmd,""))
4606         {
4607                 return;
4608         }
4609         strcpy(temp,cmd);
4610
4611         string tmp = cmd;
4612         FOREACH_MOD OnServerRaw(tmp,true);
4613         const char* cmd2 = tmp.c_str();
4614         snprintf(cmd,512,"%s",cmd2);
4615
4616         if (!strchr(cmd,' '))
4617         {
4618                 /* no parameters, lets skip the formalities and not chop up
4619                  * the string */
4620                 items = 0;
4621                 command_p[0] = NULL;
4622                 parameters = NULL;
4623                 for (int i = 0; i <= strlen(cmd); i++)
4624                 {
4625                         cmd[i] = toupper(cmd[i]);
4626                 }
4627         }
4628         else
4629         {
4630                 strcpy(cmd,"");
4631                 j = 0;
4632                 /* strip out extraneous linefeeds through mirc's crappy pasting (thanks Craig) */
4633                 for (i = 0; i < strlen(temp); i++)
4634                 {
4635                         if ((temp[i] != 10) && (temp[i] != 13) && (temp[i] != 0) && (temp[i] != 7))
4636                         {
4637                                 cmd[j++] = temp[i];
4638                                 cmd[j] = 0;
4639                         }
4640                 }
4641                 /* split the full string into a command plus parameters */
4642                 parameters = p;
4643                 strcpy(p," ");
4644                 command = cmd;
4645                 if (strchr(cmd,' '))
4646                 {
4647                         for (i = 0; i <= strlen(cmd); i++)
4648                         {
4649                                 /* capitalise the command ONLY, leave params intact */
4650                                 cmd[i] = toupper(cmd[i]);
4651                                 /* are we nearly there yet?! :P */
4652                                 if (cmd[i] == ' ')
4653                                 {
4654                                         command = cmd;
4655                                         parameters = cmd+i+1;
4656                                         cmd[i] = '\0';
4657                                         break;
4658                                 }
4659                         }
4660                 }
4661                 else
4662                 {
4663                         for (i = 0; i <= strlen(cmd); i++)
4664                         {
4665                                 cmd[i] = toupper(cmd[i]);
4666                         }
4667                 }
4668
4669         }
4670         
4671         cmd_found = 0;
4672
4673         if (strlen(command)>MAXCOMMAND)
4674         {
4675                 command[MAXCOMMAND-1] = '\0';
4676                 WriteOpers("Possible command-flood from %s, sending excessively long commands.",user->nick);
4677         }
4678
4679         for (i = 0; i != cmdlist.size(); i++)
4680         {
4681                 if (strcmp(cmdlist[i].command,""))
4682                 {
4683                         if (!strcmp(command, cmdlist[i].command))
4684                         {
4685                                 if (parameters)
4686                                 {
4687                                         if (strcmp(parameters,""))
4688                                         {
4689                                                 items = process_parameters(command_p,parameters);
4690                                         }
4691                                         else
4692                                         {
4693                                                 items = 0;
4694                                                 command_p[0] = NULL;
4695                                         }
4696                                 }
4697                                 else
4698                                 {
4699                                         items = 0;
4700                                         command_p[0] = NULL;
4701                                 }
4702                                 
4703                                 if (user)
4704                                 {
4705                                         /* activity resets the ping pending timer */
4706                                         user->nping = time(NULL) + 120;
4707                                         if ((items) < cmdlist[i].min_params)
4708                                         {
4709                                                 log(DEBUG,"process_command: not enough parameters: %s %s",user->nick,command);
4710                                                 WriteServ(user->fd,"461 %s %s :Not enough parameters",user->nick,command);
4711                                                 return;
4712                                         }
4713                                         if ((!strchr(user->modes,cmdlist[i].flags_needed)) && (cmdlist[i].flags_needed))
4714                                         {
4715                                                 log(DEBUG,"process_command: permission denied: %s %s",user->nick,command);
4716                                                 WriteServ(user->fd,"481 %s :Permission Denied- You do not have the required operator privilages",user->nick);
4717                                                 cmd_found = 1;
4718                                                 return;
4719                                         }
4720                 /* if the command isnt USER, PASS, or NICK, and nick is empty,
4721                  * deny command! */
4722                                         if ((strcmp(command,"USER")) && (strcmp(command,"NICK")) && (strcmp(command,"PASS")))
4723                                         {
4724                                                 if ((!isnick(user->nick)) || (user->registered != 7))
4725                                                 {
4726                                                         log(DEBUG,"process_command: not registered: %s %s",user->nick,command);
4727                                                         WriteServ(user->fd,"451 %s :You have not registered",command);
4728                                                         return;
4729                                                 }
4730                                         }
4731                                         if ((user->registered == 7) || (!strcmp(command,"USER")) || (!strcmp(command,"NICK")) || (!strcmp(command,"PASS")))
4732                                         {
4733                                                 log(DEBUG,"process_command: handler: %s %s %d",user->nick,command,items);
4734                                                 if (cmdlist[i].handler_function)
4735                                                 {
4736                                                         /* ikky /stats counters */
4737                                                         if (temp)
4738                                                         {
4739                                                                 if (user)
4740                                                                 {
4741                                                                         user->bytes_in += strlen(temp);
4742                                                                         user->cmds_in++;
4743                                                                 }
4744                                                                 cmdlist[i].use_count++;
4745                                                                 cmdlist[i].total_bytes+=strlen(temp);
4746                                                         }
4747
4748                                                         /* WARNING: nothing may come after the
4749                                                          * command handler call, as the handler
4750                                                          * may free the user structure! */
4751
4752                                                         cmdlist[i].handler_function(command_p,items,user);
4753                                                 }
4754                                                 return;
4755                                         }
4756                                         else
4757                                         {
4758                                                 log(DEBUG,"process_command: not registered: %s %s",user->nick,command);
4759                                                 WriteServ(user->fd,"451 %s :You have not registered",command);
4760                                                 return;
4761                                         }
4762                                 }
4763                                 cmd_found = 1;
4764                         }
4765                 }
4766         }
4767         if ((!cmd_found) && (user))
4768         {
4769                 log(DEBUG,"process_command: not in table: %s %s",user->nick,command);
4770                 WriteServ(user->fd,"421 %s %s :Unknown command",user->nick,command);
4771         }
4772 }
4773
4774
4775 void createcommand(char* cmd, handlerfunc f, char flags, int minparams)
4776 {
4777         command_t comm;
4778         /* create the command and push it onto the table */     
4779         strcpy(comm.command,cmd);
4780         comm.handler_function = f;
4781         comm.flags_needed = flags;
4782         comm.min_params = minparams;
4783         comm.use_count = 0;
4784         comm.total_bytes = 0;
4785         cmdlist.push_back(comm);
4786         log(DEBUG,"Added command %s (%d parameters)",cmd,minparams);
4787 }
4788
4789 void SetupCommandTable(void)
4790 {
4791   createcommand("USER",handle_user,0,4);
4792   createcommand("NICK",handle_nick,0,1);
4793   createcommand("QUIT",handle_quit,0,0);
4794   createcommand("VERSION",handle_version,0,0);
4795   createcommand("PING",handle_ping,0,1);
4796   createcommand("PONG",handle_pong,0,1);
4797   createcommand("ADMIN",handle_admin,0,0);
4798   createcommand("PRIVMSG",handle_privmsg,0,2);
4799   createcommand("INFO",handle_info,0,0);
4800   createcommand("TIME",handle_time,0,0);
4801   createcommand("WHOIS",handle_whois,0,1);
4802   createcommand("WALLOPS",handle_wallops,'o',1);
4803   createcommand("NOTICE",handle_notice,0,2);
4804   createcommand("JOIN",handle_join,0,1);
4805   createcommand("NAMES",handle_names,0,1);
4806   createcommand("PART",handle_part,0,1);
4807   createcommand("KICK",handle_kick,0,2);
4808   createcommand("MODE",handle_mode,0,1);
4809   createcommand("TOPIC",handle_topic,0,1);
4810   createcommand("WHO",handle_who,0,1);
4811   createcommand("MOTD",handle_motd,0,0);
4812   createcommand("RULES",handle_join,0,0);
4813   createcommand("OPER",handle_oper,0,2);
4814   createcommand("LIST",handle_list,0,0);
4815   createcommand("DIE",handle_die,'o',1);
4816   createcommand("RESTART",handle_restart,'o',1);
4817   createcommand("KILL",handle_kill,'o',2);
4818   createcommand("REHASH",handle_rehash,'o',0);
4819   createcommand("LUSERS",handle_lusers,0,0);
4820   createcommand("STATS",handle_stats,0,1);
4821   createcommand("USERHOST",handle_userhost,0,1);
4822   createcommand("AWAY",handle_away,0,0);
4823   createcommand("ISON",handle_ison,0,0);
4824   createcommand("SUMMON",handle_summon,0,0);
4825   createcommand("USERS",handle_users,0,0);
4826   createcommand("INVITE",handle_invite,0,2);
4827   createcommand("PASS",handle_pass,0,1);
4828   createcommand("TRACE",handle_trace,'o',0);
4829   createcommand("WHOWAS",handle_whowas,0,1);
4830   createcommand("CONNECT",handle_connect,'o',1);
4831   createcommand("SQUIT",handle_squit,'o',1);
4832   createcommand("MODULES",handle_modules,'o',0);
4833 }
4834
4835 void process_buffer(userrec *user)
4836 {
4837         if (!user)
4838         {
4839                 log(DEFAULT,"*** BUG *** process_buffer was given an invalid parameter");
4840                 return;
4841         }
4842         char cmd[MAXBUF];
4843         int i;
4844         if (!user->inbuf)
4845         {
4846                 log(DEFAULT,"*** BUG *** process_buffer was given an invalid parameter");
4847                 return;
4848         }
4849         if (!strcmp(user->inbuf,""))
4850         {
4851                 return;
4852         }
4853         strncpy(cmd,user->inbuf,MAXBUF);
4854         if (!strcmp(cmd,""))
4855         {
4856                 return;
4857         }
4858         if ((cmd[strlen(cmd)-1] == 13) || (cmd[strlen(cmd)-1] == 10))
4859         {
4860                 cmd[strlen(cmd)-1] = '\0';
4861         }
4862         if ((cmd[strlen(cmd)-1] == 13) || (cmd[strlen(cmd)-1] == 10))
4863         {
4864                 cmd[strlen(cmd)-1] = '\0';
4865         }
4866         strcpy(user->inbuf,"");
4867         if (!strcmp(cmd,""))
4868         {
4869                 return;
4870         }
4871         log(DEBUG,"InspIRCd: processing: %s %s",user->nick,cmd);
4872         tidystring(cmd);
4873         if (user)
4874         {
4875                 process_command(user,cmd);
4876         }
4877 }
4878
4879 void process_restricted_commands(char token,char* params,serverrec* source,serverrec* reply, char* udp_host,int udp_port)
4880 {
4881         WriteOpers("Secure-UDP-Channel: Token='%c', Params='%s'",token,params);
4882 }
4883
4884
4885 void handle_link_packet(long theirkey, char* udp_msg, char* udp_host, int udp_port, serverrec *serv)
4886 {
4887         char response[10240];
4888         char token = udp_msg[0];
4889         char* params = udp_msg + 2;
4890         char finalparam[1024];
4891         strcpy(finalparam," :xxxx");
4892         if (strstr(params," :")) {
4893                 strncpy(finalparam,strstr(params," :"),1024);
4894         }
4895         if (token == 'S') {
4896                 // S test.chatspike.net password :ChatSpike InspIRCd test server
4897                 char* servername = strtok(params," ");
4898                 char* password = strtok(NULL," ");
4899                 char* serverdesc = finalparam+2;
4900                 WriteOpers("CONNECT from %s (%s)",servername,udp_host,password,serverdesc);
4901                 
4902                 
4903                 char Link_ServerName[1024];
4904                 char Link_IPAddr[1024];
4905                 char Link_Port[1024];
4906                 char Link_Pass[1024];
4907                 char Link_SendPass[1024];
4908                 int LinkPort = 0;
4909                 
4910                 // search for a corresponding <link> block in the config files
4911                 for (int i = 0; i < ConfValueEnum("link"); i++)
4912                 {
4913                         ConfValue("link","name",i,Link_ServerName);
4914                         ConfValue("link","ipaddr",i,Link_IPAddr);
4915                         ConfValue("link","port",i,Link_Port);
4916                         ConfValue("link","recvpass",i,Link_Pass);
4917                         ConfValue("link","sendpass",i,Link_SendPass);
4918                         log(DEBUG,"(%d) Comparing against name='%s', ipaddr='%s', port='%s', recvpass='%s'",i,Link_ServerName,Link_IPAddr,Link_Port,Link_Pass);
4919                         LinkPort = atoi(Link_Port);
4920                         if (!strcasecmp(Link_ServerName,servername)) {
4921                                 if (!strcasecmp(Link_IPAddr,udp_host)) {
4922                                         if (LinkPort == udp_port) {
4923                                                 // we have a matching link line -
4924                                                 // send a 'diminutive' server message back...
4925                                                 snprintf(response,10240,"s %s %s :%s",ServerName,Link_SendPass,ServerDesc);
4926                                                 serv->SendPacket(response,udp_host,udp_port,0);
4927                                                 WriteOpers("CONNECT from %s accepted, authenticating",servername);
4928                                                 for (int j = 0; j < 255; j++) {
4929                                                         if (servers[j] == NULL) {
4930                                                                 servers[j] = new serverrec;
4931                                                                 strcpy(servers[j]->internal_addr,udp_host);
4932                                                                 strcpy(servers[j]->name,servername);
4933                                                                 // create a server record for this server
4934                                                                 snprintf(response,10240,"O %d",MyKey);
4935                                                                 serv->SendPacket(response,udp_host,udp_port,0);
4936                                                                 return;
4937                                                         }
4938                                                 }
4939                                                 WriteOpers("Internal error connecting to %s, failed to create server record!",servername);
4940                                                 return;
4941                                         }
4942                                         else {
4943                                                 log(DEBUG,"Port numbers '%d' and '%d' don't match",LinkPort,udp_port);
4944                                         }
4945                                 }
4946                                 else {
4947                                         log(DEBUG,"IP Addresses '%s' and '%s' don't match",Link_IPAddr,udp_host);
4948                                 }
4949                         }
4950                         else {
4951                                 log(DEBUG,"Server names '%s' and '%s' don't match",Link_ServerName,servername);
4952                         }
4953                 }
4954                 serv->SendPacket("E :Access is denied (no matching link block)",udp_host,udp_port,0);
4955                 WriteOpers("CONNECT from %s denied, no matching link block",servername);
4956                 return;
4957         }
4958         else
4959         if (token == 'O') {
4960                 // if this is received, this means the server-ip that sent it said "OK" to credentials.
4961                 // only when a server says this do we exchange keys. The server MUST have an entry in the servers
4962                 // array, which is only added by an 'S' packet or BeginLink().
4963                 for (int i = 0; i < 255; i++) {
4964                         if (servers[i] != NULL) {
4965                                 if (!strcasecmp(servers[i]->internal_addr,udp_host)) {
4966                                         servers[i]->key = atoi(params);
4967                                         log(DEBUG,"Key for this server is now %d",servers[i]->key);
4968                                         serv->SendPacket("Z blah blah",udp_host,udp_port,MyKey);
4969                                         return;
4970                                 }
4971                         }
4972                 }
4973                 WriteOpers("\2WARNING!\2 Server ip %s attempted a key exchange, but is not in the authentication state! Possible intrusion attempt!",udp_host);
4974         }
4975         else
4976         if (token == 's') {
4977                 // S test.chatspike.net password :ChatSpike InspIRCd test server
4978                 char* servername = strtok(params," ");
4979                 char* password = strtok(NULL," ");
4980                 char* serverdesc = finalparam+2;
4981                 
4982                 // TODO: we should do a check here to ensure that this server is one we recently initiated a
4983                 // link with, and didnt hear an 's' or 'E' back from yet (these are the only two valid responses
4984                 // to an 'S' command. If we didn't recently send an 'S' to this server, theyre trying to spoof
4985                 // a connect, so put out an oper alert!
4986                 
4987                 
4988                 
4989                 
4990                 // for now, just accept all, we'll fix that later.
4991                 WriteOpers("%s accepted our link credentials ",servername);
4992                 
4993                 char Link_ServerName[1024];
4994                 char Link_IPAddr[1024];
4995                 char Link_Port[1024];
4996                 char Link_Pass[1024];
4997                 char Link_SendPass[1024];
4998                 int LinkPort = 0;
4999                 
5000                 // search for a corresponding <link> block in the config files
5001                 for (int i = 0; i < ConfValueEnum("link"); i++)
5002                 {
5003                         ConfValue("link","name",i,Link_ServerName);
5004                         ConfValue("link","ipaddr",i,Link_IPAddr);
5005                         ConfValue("link","port",i,Link_Port);
5006                         ConfValue("link","recvpass",i,Link_Pass);
5007                         ConfValue("link","sendpass",i,Link_SendPass);
5008                         log(DEBUG,"(%d) Comparing against name='%s', ipaddr='%s', port='%s', recvpass='%s'",i,Link_ServerName,Link_IPAddr,Link_Port,Link_Pass);
5009                         LinkPort = atoi(Link_Port);
5010                         if (!strcasecmp(Link_ServerName,servername)) {
5011                                 if (!strcasecmp(Link_IPAddr,udp_host)) {
5012                                         if (LinkPort == udp_port) {
5013                                                 // matching link at this end too, we're all done!
5014                                                 // at this point we must begin key exchange and insert this
5015                                                 // server into our 'active' table.
5016                                                 for (int j = 0; j < 255; j++) {
5017                                                         if (servers[j] != NULL) {
5018                                                                 if (!strcasecmp(servers[j]->internal_addr,udp_host)) {
5019                                                                         WriteOpers("Server %s authenticated, exchanging server keys...",servername);
5020                                                                         snprintf(response,10240,"O %d",MyKey);
5021                                                                         serv->SendPacket(response,udp_host,udp_port,0);
5022                                                                         return;
5023                                                                 }
5024                                                         }
5025                                                 }
5026                                                 WriteOpers("\2WARNING!\2 %s sent us an authentication packet but we are not authenticating with this server right noe! Possible intrusion attempt!",udp_host);
5027                                                 return;
5028
5029                                         }
5030                                         else {
5031                                                 log(DEBUG,"Port numbers '%d' and '%d' don't match",LinkPort,udp_port);
5032                                         }
5033                                 }
5034                                 else {
5035                                         log(DEBUG,"IP Addresses '%s' and '%s' don't match",Link_IPAddr,udp_host);
5036                                 }
5037                         }
5038                         else {
5039                                 log(DEBUG,"Server names '%s' and '%s' don't match",Link_ServerName,servername);
5040                         }
5041                 }
5042                 serv->SendPacket("E :Access is denied (no matching link block)",udp_host,udp_port,0);
5043                 WriteOpers("CONNECT from %s denied, no matching link block",servername);
5044                 return;
5045         }
5046         else
5047         if (token == 'E') {
5048                 char* error_message = finalparam+2;
5049                 WriteOpers("ERROR from %s: %s",udp_host,error_message);
5050                 // remove this server from any lists
5051                 for (int j = 0; j < 255; j++) {
5052                         if (servers[j] != NULL) {
5053                                 if (!strcasecmp(servers[j]->internal_addr,udp_host)) {
5054                                         delete servers[j];
5055                                         return;
5056                                 }
5057                         }
5058                 }
5059                 return;
5060         }
5061         else {
5062
5063                 serverrec* source_server = NULL;
5064
5065                 for (int j = 0; j < 255; j++) {
5066                         if (servers[j] != NULL) {
5067                                 if (!strcasecmp(servers[j]->internal_addr,udp_host)) {
5068                                         if (servers[j]->key == theirkey) {
5069                                                 // found a valid key for this server, can process restricted stuff here
5070                                                 process_restricted_commands(token,params,servers[j],serv,udp_host,udp_port);
5071                                                 
5072                                                 return;
5073                                         }
5074                                 }
5075                         }
5076                 }
5077
5078                 log(DEBUG,"Unrecognised token or unauthenticated host in datagram from %s:%d: %c",udp_host,udp_port,token);
5079         }
5080 }
5081
5082 int reap_counter = 0;
5083
5084 int InspIRCd(void)
5085 {
5086   struct sockaddr_in client, server;
5087   char addrs[MAXBUF][255];
5088   int openSockfd[MAXSOCKS], incomingSockfd, result = TRUE;
5089   socklen_t length;
5090   int count = 0, scanDetectTrigger = TRUE, showBanner = FALSE;
5091   int selectResult = 0;
5092   char *temp, configToken[MAXBUF], stuff[MAXBUF], Addr[MAXBUF], Type[MAXBUF];
5093   char resolvedHost[MAXBUF];
5094   fd_set selectFds;
5095   struct timeval tv;
5096
5097   log_file = fopen("ircd.log","a+");
5098   if (!log_file)
5099   {
5100         printf("ERROR: Could not write to logfile ircd.log, bailing!\n\n");
5101         Exit(ERROR);
5102   }
5103
5104   log(DEBUG,"InspIRCd: startup: begin");
5105   log(DEBUG,"$Id$");
5106   if (geteuid() == 0)
5107   {
5108         printf("WARNING!!! You are running an irc server as ROOT!!! DO NOT DO THIS!!!\n\n");
5109         Exit(ERROR);
5110         log(DEBUG,"InspIRCd: startup: not starting with UID 0!");
5111   }
5112   SetupCommandTable();
5113   log(DEBUG,"InspIRCd: startup: default command table set up");
5114
5115   ReadConfig();
5116   if (strcmp(DieValue,"")) 
5117   { 
5118         printf("WARNING: %s\n\n",DieValue);
5119         exit(0); 
5120   }  
5121   log(DEBUG,"InspIRCd: startup: read config");
5122   
5123   int count2 = 0, count3 = 0;
5124   for (count = 0; count < ConfValueEnum("bind"); count++)
5125   {
5126         ConfValue("bind","port",count,configToken);
5127         ConfValue("bind","address",count,Addr);
5128         ConfValue("bind","type",count,Type);
5129         if (!strcmp(Type,"servers"))
5130         {
5131                 char Default[MAXBUF];
5132                 strcpy(Default,"no");
5133                 ConfValue("bind","default",count,Default);
5134                 if (strchr(Default,'y'))
5135                 {
5136                                 defaultRoute = count3;
5137                                 log(DEBUG,"InspIRCd: startup: binding '%s:%s' is default server route",Addr,configToken);
5138                 }
5139                 me[count3] = new serverrec(ServerName,100L,false);
5140                 me[count3]->CreateListener(Addr,atoi(configToken));
5141                 count3++;
5142         }
5143         else
5144         {
5145                 ports[count2] = atoi(configToken);
5146                 strcpy(addrs[count2],Addr);
5147                 count2++;
5148         }
5149         log(DEBUG,"InspIRCd: startup: read binding %s:%s [%s] from config",Addr,configToken, Type);
5150   }
5151   portCount = count2;
5152   UDPportCount = count3;
5153   
5154   log(DEBUG,"InspIRCd: startup: read %d total client ports and %d total server ports",portCount,UDPportCount);
5155
5156   log(DEBUG,"InspIRCd: startup: InspIRCd is now running!");
5157
5158   printf("\n");
5159
5160   /* BugFix By Craig! :p */
5161   count2 = 0;
5162   for (count = 0; count2 < ConfValueEnum("module"); count2++)
5163   {
5164         char modfile[MAXBUF];
5165         ConfValue("module","name",count,configToken);
5166         sprintf(modfile,"%s/%s",MOD_PATH,configToken);
5167         printf("Loading module... \033[1;37m%s\033[0;37m\n",modfile);
5168         log(DEBUG,"InspIRCd: startup: Loading module: %s",modfile);
5169         /* If The File Doesnt exist, Trying to load it
5170          * Will Segfault the IRCd.. So, check to see if
5171          * it Exists, Before Proceeding. */
5172         if (FileExists(modfile))
5173         {
5174                 factory[count] = new ircd_module(modfile);
5175                 if (factory[count]->LastError())
5176                 {
5177                         log(DEBUG,"Unable to load %s: %s",modfile,factory[count]->LastError());
5178                         sprintf("Unable to load %s: %s\nExiting...\n",modfile,factory[count]->LastError());
5179                         Exit(ERROR);
5180                 }
5181                 if (factory[count]->factory)
5182                 {
5183                         modules[count] = factory[count]->factory->CreateModule();
5184                         /* save the module and the module's classfactory, if
5185                          * this isnt done, random crashes can occur :/ */
5186                         module_names.push_back(modfile);        
5187                 }
5188                 else
5189                 {
5190                         log(DEBUG,"Unable to load %s",modfile);
5191                         sprintf("Unable to load %s\nExiting...\n",modfile);
5192                         Exit(ERROR);
5193                 }
5194                 /* Increase the Count */
5195                 count++;
5196         }
5197         else
5198         {
5199                 log(DEBUG,"InspIRCd: startup: Module Not Found %s",modfile);
5200                 printf("Module Not Found: \033[1;37m%s\033[0;37m, Skipping\n",modfile);
5201         }
5202   }
5203   MODCOUNT = count - 1;
5204   log(DEBUG,"Total loaded modules: %d",MODCOUNT+1);
5205
5206   printf("\nInspIRCd is now running!\n");
5207
5208   startup_time = time(NULL);
5209   
5210   if (nofork)
5211   {
5212         log(VERBOSE,"Not forking as -nofork was specified");
5213   }
5214   else
5215   {
5216         if (DaemonSeed() == ERROR)
5217         {
5218                 log(DEBUG,"InspIRCd: startup: can't daemonise");
5219                 printf("ERROR: could not go into daemon mode. Shutting down.\n");
5220                 Exit(ERROR);
5221         }
5222   }
5223   
5224   
5225   /* setup select call */
5226   FD_ZERO(&selectFds);
5227   log(DEBUG,"InspIRCd: startup: zero selects");
5228   log(VERBOSE,"InspIRCd: startup: portCount = %d", portCount);
5229
5230   for (count = 0; count < portCount; count++)
5231   {
5232           if ((openSockfd[boundPortCount] = OpenTCPSocket()) == ERROR)
5233       {
5234                 log(DEBUG,"InspIRCd: startup: bad fd %d",openSockfd[boundPortCount]);
5235                 return(ERROR);
5236       }
5237       if (BindSocket(openSockfd[boundPortCount],client,server,ports[count],addrs[count]) == ERROR)
5238       {
5239                 log(DEBUG,"InspIRCd: startup: failed to bind port %d",ports[count]);
5240       }
5241       else                      /* well we at least bound to one socket so we'll continue */
5242       {
5243                 boundPortCount++;
5244       }
5245   }
5246
5247   log(DEBUG,"InspIRCd: startup: total bound ports %d",boundPortCount);
5248   
5249   /* if we didn't bind to anything then abort */
5250   if (boundPortCount == 0)
5251   {
5252      log(DEBUG,"InspIRCd: startup: no ports bound, bailing!");
5253      return (ERROR);
5254   }
5255
5256   length = sizeof (client);
5257   int flip_flop = 0, udp_port = 0;
5258   char udp_msg[MAXBUF], udp_host[MAXBUF];
5259   
5260   /* main loop for multiplexing/resetting */
5261   for (;;)
5262   {
5263       /* set up select call */
5264       for (count = 0; count < boundPortCount; count++)
5265       {
5266                 FD_SET (openSockfd[count], &selectFds);
5267       }
5268         
5269       /* added timeout! select was waiting forever... wank... :/ */
5270       tv.tv_usec = 0;
5271
5272       flip_flop++;
5273       reap_counter++;
5274       if (flip_flop > 20)
5275       {
5276               tv.tv_usec = 1;
5277               flip_flop = 0;
5278       }
5279       
5280         vector<int>::iterator niterator;
5281                 
5282
5283         // *FIX* Instead of closing sockets in kill_link when they receive the ERROR :blah line, we should queue
5284         // them in a list, then reap the list every second or so.
5285         if (reap_counter>5000) {
5286                 if (fd_reap.size() > 0) {
5287                         for( int n = 0; n < fd_reap.size(); n++)
5288                         {
5289                                 Blocking(fd_reap[n]);
5290                                 close(fd_reap[n]);
5291                                 NonBlocking(fd_reap[n]);
5292                         }
5293                 }
5294                 fd_reap.clear();
5295                 reap_counter=0;
5296         }
5297
5298       
5299       tv.tv_sec = 0;
5300       selectResult = select(MAXSOCKS, &selectFds, NULL, NULL, &tv);
5301
5302       for (int x = 0; x != UDPportCount; x++)
5303       {
5304            long theirkey = 0;
5305            if (me[x]->RecvPacket(udp_msg, udp_host, udp_port, theirkey))
5306            {
5307                         if (strlen(udp_msg)<1) {
5308                                 log(DEBUG,"Invalid datagram from %s:%d:%d [route%d]",udp_host,udp_port,me[x]->port,x);
5309                         }
5310                         else {
5311                                 FOREACH_MOD OnPacketReceive(udp_msg);
5312                                 // Packets must go back via the route they arrived on :)
5313                                 handle_link_packet(theirkey, udp_msg, udp_host, udp_port, me[x]);
5314                         }
5315            }
5316       }
5317
5318         for (user_hash::iterator count2 = clientlist.begin(); count2 != clientlist.end(); count2++)
5319         {
5320                 char data[MAXBUF];
5321
5322                 if (!count2->second) break;
5323                 
5324                 if (count2->second)
5325                 if (count2->second->fd)
5326                 {
5327                         // registration timeout -- didnt send USER/NICK/HOST in the time specified in
5328                         // their connection class.
5329                         if ((time(NULL) > count2->second->timeout) && (count2->second->registered != 7)) 
5330                         {
5331                                 log(DEBUG,"InspIRCd: registration timeout: %s",count2->second->nick);
5332                                 kill_link(count2->second,"Registration timeout");
5333                                 break;
5334                         }
5335                         if (((time(NULL)) > count2->second->nping) && (isnick(count2->second->nick)) && (count2->second->registered == 7))
5336                         {
5337                                 if (!count2->second->lastping) 
5338                                 {
5339                                         log(DEBUG,"InspIRCd: ping timeout: %s",count2->second->nick);
5340                                         kill_link(count2->second,"Ping timeout");
5341                                         break;
5342                                 }
5343                                 Write(count2->second->fd,"PING :%s",ServerName);
5344                                 log(DEBUG,"InspIRCd: pinging: %s",count2->second->nick);
5345                                 count2->second->lastping = 0;
5346                                 count2->second->nping = time(NULL)+120;
5347                         }
5348                         
5349                         result = read(count2->second->fd, data, 1);
5350                         // result EAGAIN means nothing read
5351                         if (result == EAGAIN)
5352                         {
5353                         }
5354                         else
5355                         if (result == 0)
5356                         {
5357                                 if (count2->second)
5358                                 {
5359                                         log(DEBUG,"InspIRCd: Exited: %s",count2->second->nick);
5360                                         kill_link(count2->second,"Client exited");
5361                                         // must bail here? kill_link removes the hash, corrupting the iterator
5362                                         log(DEBUG,"Bailing from client exit");
5363                                         break;
5364                                 }
5365                         }
5366                         else if (result > 0)
5367                         {
5368                                 if (count2->second)
5369                                 {
5370                                 
5371                                         // until the buffer is at 509 chars anything can be inserted into it.
5372                                         if (strlen(count2->second->inbuf) < 509) {
5373                                                 strncat(count2->second->inbuf, data, result);
5374                                         }
5375
5376                                         // once you reach 509 chars, only a \r or \n can be inserted,
5377                                         // completing the line.
5378                                         if ((strlen(count2->second->inbuf) >= 509) && ((data[0] == '\r') || (data[0] == '\n'))) {
5379                                                 count2->second->inbuf[509] = '\r';
5380                                                 count2->second->inbuf[510] = '\n';
5381                                                 count2->second->inbuf[511] = '\0';
5382                                         }
5383
5384                                         if (strchr(count2->second->inbuf, '\n') || strchr(count2->second->inbuf, '\r') || (strlen(count2->second->inbuf) > 509))
5385                                         {
5386                                                 /* at least one complete line is waiting to be processed */
5387                                                 if (!count2->second->fd)
5388                                                         break;
5389                                                 else
5390                                                 {
5391                                                         if (strlen(count2->second->inbuf)<513)
5392                                                         {
5393                                                                 // double check the length before processing!
5394                                                                 process_buffer(count2->second);
5395                                                         }
5396                                                         break;
5397                                                 }
5398                                         }
5399                                 }
5400                         }
5401                 }
5402         }
5403
5404       /* select is reporting a waiting socket. Poll them all to find out which */
5405       if (selectResult > 0)
5406       {
5407         char target[MAXBUF], resolved[MAXBUF];
5408         for (count = 0; count < boundPortCount; count++)                
5409         {
5410             if (FD_ISSET (openSockfd[count], &selectFds))
5411             {
5412               incomingSockfd = accept (openSockfd[count], (struct sockaddr *) &client, &length);
5413               
5414               address_cache::iterator iter = IP.find(client.sin_addr);
5415               bool iscached = false;
5416               if (iter == IP.end())
5417               {
5418                         /* ip isn't in cache, add it */
5419                         strncpy (target, (char *) inet_ntoa (client.sin_addr), MAXBUF);
5420                         if(CleanAndResolve(resolved, target) != TRUE)
5421                         {
5422                                 strncpy(resolved,target,MAXBUF);
5423                         }
5424                         /* hostname now in 'target' */
5425                         IP[client.sin_addr] = new string(resolved);
5426               /* hostname in cache */
5427               }
5428               else
5429               {
5430               /* found ip (cached) */
5431               strncpy(resolved, iter->second->c_str(), MAXBUF);
5432               iscached = true;
5433            }
5434
5435               if (incomingSockfd < 0)
5436               {
5437                         WriteOpers("*** WARNING: Accept failed on port %d (%s)", ports[count],target);
5438                         log(DEBUG,"InspIRCd: accept failed: %d",ports[count]);
5439                         break;
5440               }
5441
5442               AddClient(incomingSockfd, resolved, ports[count], iscached);
5443               log(DEBUG,"InspIRCd: adding client on port %d fd=%d",ports[count],incomingSockfd);
5444               break;
5445             }
5446
5447            }
5448       }
5449   }
5450
5451   /* not reached */
5452   close (incomingSockfd);
5453 }
5454