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