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