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