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