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