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