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