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