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