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