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