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