]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/inspircd.cpp
Moved all command handler functions into commands.cpp/commands.h
[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 <unistd.h>
45 #include <sched.h>
46 #include "connection.h"
47 #include "users.h"
48 #include "servers.h"
49 #include "ctables.h"
50 #include "globals.h"
51 #include "modules.h"
52 #include "dynamic.h"
53 #include "wildcard.h"
54 #include "message.h"
55 #include "mode.h"
56 #include "commands.h"
57
58 #ifdef GCC3
59 #define nspace __gnu_cxx
60 #else
61 #define nspace std
62 #endif
63
64 int LogLevel = DEFAULT;
65 char ServerName[MAXBUF];
66 char Network[MAXBUF];
67 char ServerDesc[MAXBUF];
68 char AdminName[MAXBUF];
69 char AdminEmail[MAXBUF];
70 char AdminNick[MAXBUF];
71 char diepass[MAXBUF];
72 char restartpass[MAXBUF];
73 char motd[MAXBUF];
74 char rules[MAXBUF];
75 char list[MAXBUF];
76 char PrefixQuit[MAXBUF];
77 char DieValue[MAXBUF];
78 int debugging =  0;
79 int WHOWAS_STALE = 48; // default WHOWAS Entries last 2 days before they go 'stale'
80 int WHOWAS_MAX = 100;  // default 100 people maximum in the WHOWAS list
81 int DieDelay  =  5;
82 time_t startup_time = time(NULL);
83 int NetBufferSize = 10240; // NetBufferSize used as the buffer size for all read() ops
84 time_t nb_start = 0;
85
86 extern vector<Module*> modules;
87 std::vector<std::string> module_names;
88 extern vector<ircd_module*> factory;
89 std::vector<int> fd_reap;
90
91 extern int MODCOUNT;
92
93 bool nofork = false;
94
95 namespace nspace
96 {
97         template<> struct nspace::hash<in_addr>
98         {
99                 size_t operator()(const struct in_addr &a) const
100                 {
101                         size_t q;
102                         memcpy(&q,&a,sizeof(size_t));
103                         return q;
104                 }
105         };
106
107         template<> struct nspace::hash<string>
108         {
109                 size_t operator()(const string &s) const
110                 {
111                         char a[MAXBUF];
112                         static struct hash<const char *> strhash;
113                         strcpy(a,s.c_str());
114                         strlower(a);
115                         return strhash(a);
116                 }
117         };
118 }       
119
120
121 struct StrHashComp
122 {
123
124         bool operator()(const string& s1, const string& s2) const
125         {
126                 char a[MAXBUF],b[MAXBUF];
127                 strcpy(a,s1.c_str());
128                 strcpy(b,s2.c_str());
129                 return (strcasecmp(a,b) == 0);
130         }
131
132 };
133
134 struct InAddr_HashComp
135 {
136
137         bool operator()(const in_addr &s1, const in_addr &s2) const
138         {
139                 size_t q;
140                 size_t p;
141                 
142                 memcpy(&q,&s1,sizeof(size_t));
143                 memcpy(&p,&s2,sizeof(size_t));
144                 
145                 return (q == p);
146         }
147
148 };
149
150
151 typedef nspace::hash_map<std::string, userrec*, nspace::hash<string>, StrHashComp> user_hash;
152 typedef nspace::hash_map<std::string, chanrec*, nspace::hash<string>, StrHashComp> chan_hash;
153 typedef nspace::hash_map<in_addr,string*, nspace::hash<in_addr>, InAddr_HashComp> address_cache;
154 typedef std::deque<command_t> command_table;
155
156 serverrec* me[32];
157
158 FILE *log_file;
159
160 user_hash clientlist;
161 chan_hash chanlist;
162 user_hash whowas;
163 command_table cmdlist;
164 file_cache MOTD;
165 file_cache RULES;
166 address_cache IP;
167
168 ClassVector Classes;
169
170 struct linger linger = { 0 };
171 char bannerBuffer[MAXBUF];
172 int boundPortCount = 0;
173 int portCount = 0, UDPportCount = 0, ports[MAXSOCKS];
174 int defaultRoute = 0;
175
176 connection C;
177
178 long MyKey = C.GenKey();
179
180 /* prototypes */
181
182 int has_channel(userrec *u, chanrec *c);
183 int usercount(chanrec *c);
184 int usercount_i(chanrec *c);
185 void update_stats_l(int fd,int data_out);
186 char* Passwd(userrec *user);
187 bool IsDenied(userrec *user);
188 void AddWhoWas(userrec* u);
189
190 std::vector<long> auth_cookies;
191 std::stringstream config_f(stringstream::in | stringstream::out);
192
193
194
195 long GetRevision()
196 {
197         char Revision[] = "$Revision$";
198         char *s1 = Revision;
199         char *savept;
200         char *v1 = strtok_r(s1," ",&savept);
201         s1 = savept;
202         char *v2 = strtok_r(s1," ",&savept);
203         s1 = savept;
204         return (long)(atof(v2)*10000);
205 }
206
207
208 std::string getservername()
209 {
210         return ServerName;
211 }
212
213 std::string getserverdesc()
214 {
215         return ServerDesc;
216 }
217
218 std::string getnetworkname()
219 {
220         return Network;
221 }
222
223 std::string getadminname()
224 {
225         return AdminName;
226 }
227
228 std::string getadminemail()
229 {
230         return AdminEmail;
231 }
232
233 std::string getadminnick()
234 {
235         return AdminNick;
236 }
237
238 void log(int level,char *text, ...)
239 {
240         char textbuffer[MAXBUF];
241         va_list argsPtr;
242         time_t rawtime;
243         struct tm * timeinfo;
244         if (level < LogLevel)
245                 return;
246
247         time(&rawtime);
248         timeinfo = localtime (&rawtime);
249
250         if (log_file)
251         {
252                 char b[MAXBUF];
253                 va_start (argsPtr, text);
254                 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
255                 va_end(argsPtr);
256                 strcpy(b,asctime(timeinfo));
257                 b[strlen(b)-1] = ':';
258                 fprintf(log_file,"%s %s\n",b,textbuffer);
259                 if (nofork)
260                 {
261                         // nofork enabled? display it on terminal too
262                         printf("%s %s\n",b,textbuffer);
263                 }
264         }
265 }
266
267 void readfile(file_cache &F, const char* fname)
268 {
269   FILE* file;
270   char linebuf[MAXBUF];
271
272   log(DEBUG,"readfile: loading %s",fname);
273   F.clear();
274   file =  fopen(fname,"r");
275   if (file)
276   {
277         while (!feof(file))
278         {
279                 fgets(linebuf,sizeof(linebuf),file);
280                 linebuf[strlen(linebuf)-1]='\0';
281                 if (!strcmp(linebuf,""))
282                 {
283                         strcpy(linebuf,"  ");
284                 }
285                 if (!feof(file))
286                 {
287                         F.push_back(linebuf);
288                 }
289         }
290         fclose(file);
291   }
292   else
293   {
294           log(DEBUG,"readfile: failed to load file: %s",fname);
295   }
296   log(DEBUG,"readfile: loaded %s, %d lines",fname,F.size());
297 }
298
299 void ReadConfig(void)
300 {
301   char dbg[MAXBUF],pauseval[MAXBUF],Value[MAXBUF],timeout[MAXBUF],NB[MAXBUF],flood[MAXBUF];
302   ConnectClass c;
303
304   LoadConf(CONFIG_FILE,&config_f);
305   
306   ConfValue("server","name",0,ServerName,&config_f);
307   ConfValue("server","description",0,ServerDesc,&config_f);
308   ConfValue("server","network",0,Network,&config_f);
309   ConfValue("admin","name",0,AdminName,&config_f);
310   ConfValue("admin","email",0,AdminEmail,&config_f);
311   ConfValue("admin","nick",0,AdminNick,&config_f);
312   ConfValue("files","motd",0,motd,&config_f);
313   ConfValue("files","rules",0,rules,&config_f);
314   ConfValue("power","diepass",0,diepass,&config_f);
315   ConfValue("power","pause",0,pauseval,&config_f);
316   ConfValue("power","restartpass",0,restartpass,&config_f);
317   ConfValue("options","prefixquit",0,PrefixQuit,&config_f);
318   ConfValue("die","value",0,DieValue,&config_f);
319   ConfValue("options","loglevel",0,dbg,&config_f);
320   ConfValue("options","netbuffersize",0,NB,&config_f);
321   NetBufferSize = atoi(NB);
322   if ((!NetBufferSize) || (NetBufferSize > 65535) || (NetBufferSize < 1024))
323   {
324         log(DEFAULT,"No NetBufferSize specified or size out of range, setting to default of 10240.");
325         NetBufferSize = 10240;
326   }
327   if (!strcmp(dbg,"debug"))
328         LogLevel = DEBUG;
329   if (!strcmp(dbg,"verbose"))
330         LogLevel = VERBOSE;
331   if (!strcmp(dbg,"default"))
332         LogLevel = DEFAULT;
333   if (!strcmp(dbg,"sparse"))
334         LogLevel = SPARSE;
335   if (!strcmp(dbg,"none"))
336         LogLevel = NONE;
337   readfile(MOTD,motd);
338   log(DEBUG,"Reading message of the day");
339   readfile(RULES,rules);
340   log(DEBUG,"Reading connect classes");
341   Classes.clear();
342   for (int i = 0; i < ConfValueEnum("connect",&config_f); i++)
343   {
344         strcpy(Value,"");
345         ConfValue("connect","allow",i,Value,&config_f);
346         ConfValue("connect","timeout",i,timeout,&config_f);
347         ConfValue("connect","flood",i,flood,&config_f);
348         if (strcmp(Value,""))
349         {
350                 strcpy(c.host,Value);
351                 c.type = CC_ALLOW;
352                 strcpy(Value,"");
353                 ConfValue("connect","password",i,Value,&config_f);
354                 strcpy(c.pass,Value);
355                 c.registration_timeout = 90; // default is 2 minutes
356                 c.flood = atoi(flood);
357                 if (atoi(timeout)>0)
358                 {
359                         c.registration_timeout = atoi(timeout);
360                 }
361                 Classes.push_back(c);
362                 log(DEBUG,"Read connect class type ALLOW, host=%s password=%s timeout=%d flood=%d",c.host,c.pass,c.registration_timeout,c.flood);
363         }
364         else
365         {
366                 ConfValue("connect","deny",i,Value,&config_f);
367                 strcpy(c.host,Value);
368                 c.type = CC_DENY;
369                 Classes.push_back(c);
370                 log(DEBUG,"Read connect class type DENY, host=%s",c.host);
371         }
372         
373   }
374 }
375
376 /* write formatted text to a socket, in same format as printf */
377
378 void Write(int sock,char *text, ...)
379 {
380   if (!text)
381   {
382         log(DEFAULT,"*** BUG *** Write was given an invalid parameter");
383         return;
384   }
385   char textbuffer[MAXBUF];
386   va_list argsPtr;
387   char tb[MAXBUF];
388
389   va_start (argsPtr, text);
390   vsnprintf(textbuffer, MAXBUF, text, argsPtr);
391   va_end(argsPtr);
392   sprintf(tb,"%s\r\n",textbuffer);
393   chop(tb);
394   if (sock != -1)
395   {
396         write(sock,tb,strlen(tb));
397         update_stats_l(sock,strlen(tb)); /* add one line-out to stats L for this fd */
398   }
399 }
400
401 /* write a server formatted numeric response to a single socket */
402
403 void WriteServ(int sock, char* text, ...)
404 {
405   if (!text)
406   {
407         log(DEFAULT,"*** BUG *** WriteServ was given an invalid parameter");
408         return;
409   }
410   char textbuffer[MAXBUF],tb[MAXBUF];
411   va_list argsPtr;
412   va_start (argsPtr, text);
413
414   vsnprintf(textbuffer, MAXBUF, text, argsPtr);
415   va_end(argsPtr);
416   sprintf(tb,":%s %s\r\n",ServerName,textbuffer);
417   chop(tb);
418   if (sock != -1)
419   {
420         write(sock,tb,strlen(tb));
421         update_stats_l(sock,strlen(tb)); /* add one line-out to stats L for this fd */
422   }
423 }
424
425 /* write text from an originating user to originating user */
426
427 void WriteFrom(int sock, userrec *user,char* text, ...)
428 {
429   if ((!text) || (!user))
430   {
431         log(DEFAULT,"*** BUG *** WriteFrom was given an invalid parameter");
432         return;
433   }
434   char textbuffer[MAXBUF],tb[MAXBUF];
435   va_list argsPtr;
436   va_start (argsPtr, text);
437
438   vsnprintf(textbuffer, MAXBUF, text, argsPtr);
439   va_end(argsPtr);
440   sprintf(tb,":%s!%s@%s %s\r\n",user->nick,user->ident,user->dhost,textbuffer);
441   chop(tb);
442   if (sock != -1)
443   {
444         write(sock,tb,strlen(tb));
445         update_stats_l(sock,strlen(tb)); /* add one line-out to stats L for this fd */
446   }
447 }
448
449 /* write text to an destination user from a source user (e.g. user privmsg) */
450
451 void WriteTo(userrec *source, userrec *dest,char *data, ...)
452 {
453         if ((!dest) || (!data))
454         {
455                 log(DEFAULT,"*** BUG *** WriteTo was given an invalid parameter");
456                 return;
457         }
458         char textbuffer[MAXBUF],tb[MAXBUF];
459         va_list argsPtr;
460         va_start (argsPtr, data);
461         vsnprintf(textbuffer, MAXBUF, data, argsPtr);
462         va_end(argsPtr);
463         chop(tb);
464
465         // if no source given send it from the server.
466         if (!source)
467         {
468                 WriteServ(dest->fd,":%s %s",ServerName,textbuffer);
469         }
470         else
471         {
472                 WriteFrom(dest->fd,source,"%s",textbuffer);
473         }
474 }
475
476 /* write formatted text from a source user to all users on a channel
477  * including the sender (NOT for privmsg, notice etc!) */
478
479 void WriteChannel(chanrec* Ptr, userrec* user, char* text, ...)
480 {
481         if ((!Ptr) || (!user) || (!text))
482         {
483                 log(DEFAULT,"*** BUG *** WriteChannel was given an invalid parameter");
484                 return;
485         }
486         char textbuffer[MAXBUF];
487         va_list argsPtr;
488         va_start (argsPtr, text);
489         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
490         va_end(argsPtr);
491         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
492         {
493                 if (has_channel(i->second,Ptr))
494                 {
495                         WriteTo(user,i->second,"%s",textbuffer);
496                 }
497         }
498 }
499
500 /* write formatted text from a source user to all users on a channel
501  * including the sender (NOT for privmsg, notice etc!) doesnt send to
502  * users on remote servers */
503
504 void WriteChannelLocal(chanrec* Ptr, userrec* user, char* text, ...)
505 {
506         if ((!Ptr) || (!text))
507         {
508                 log(DEFAULT,"*** BUG *** WriteChannel was given an invalid parameter");
509                 return;
510         }
511         char textbuffer[MAXBUF];
512         va_list argsPtr;
513         va_start (argsPtr, text);
514         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
515         va_end(argsPtr);
516         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
517         {
518                 if (has_channel(i->second,Ptr))
519                 {
520                         if (i->second->fd != -1)
521                         {
522                                 if (!user)
523                                 {
524                                         WriteServ(i->second->fd,"%s",textbuffer);
525                                 }
526                                 else
527                                 {
528                                         WriteTo(user,i->second,"%s",textbuffer);
529                                 }
530                         }       
531                 }
532         }
533 }
534
535
536 void WriteChannelWithServ(char* ServerName, chanrec* Ptr, userrec* user, char* text, ...)
537 {
538         if ((!Ptr) || (!user) || (!text))
539         {
540                 log(DEFAULT,"*** BUG *** WriteChannelWithServ was given an invalid parameter");
541                 return;
542         }
543         char textbuffer[MAXBUF];
544         va_list argsPtr;
545         va_start (argsPtr, text);
546         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
547         va_end(argsPtr);
548         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
549         {
550                 if (i->second)
551                 {
552                         if (has_channel(i->second,Ptr))
553                         {
554                                 WriteServ(i->second->fd,"%s",textbuffer);
555                         }
556                 }
557         }
558 }
559
560
561 /* write formatted text from a source user to all users on a channel except
562  * for the sender (for privmsg etc) */
563
564 void ChanExceptSender(chanrec* Ptr, userrec* user, char* text, ...)
565 {
566         if ((!Ptr) || (!user) || (!text))
567         {
568                 log(DEFAULT,"*** BUG *** ChanExceptSender was given an invalid parameter");
569                 return;
570         }
571         char textbuffer[MAXBUF];
572         va_list argsPtr;
573         va_start (argsPtr, text);
574         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
575         va_end(argsPtr);
576
577         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
578         {
579                 if (i->second)
580                 {
581                         if (has_channel(i->second,Ptr) && (user != i->second))
582                         {
583                                 WriteTo(user,i->second,"%s",textbuffer);
584                         }
585                 }
586         }
587 }
588
589
590 std::string GetServerDescription(char* servername)
591 {
592         for (int j = 0; j < 32; j++)
593         {
594                 if (me[j] != NULL)
595                 {
596                         for (int k = 0; k < me[j]->connectors.size(); k++)
597                         {
598                                 if (!strcasecmp(me[j]->connectors[k].GetServerName().c_str(),servername))
599                                 {
600                                         return me[j]->connectors[k].GetDescription();
601                                 }
602                         }
603                 }
604                 return ServerDesc; // not a remote server that can be found, it must be me.
605         }
606 }
607
608
609 /* write a formatted string to all users who share at least one common
610  * channel, including the source user e.g. for use in NICK */
611
612 void WriteCommon(userrec *u, char* text, ...)
613 {
614         if (!u)
615         {
616                 log(DEFAULT,"*** BUG *** WriteCommon was given an invalid parameter");
617                 return;
618         }
619
620         if (u->registered != 7) {
621                 log(DEFAULT,"*** BUG *** WriteCommon on an unregistered user");
622                 return;
623         }
624         
625         char textbuffer[MAXBUF];
626         va_list argsPtr;
627         va_start (argsPtr, text);
628         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
629         va_end(argsPtr);
630
631         WriteFrom(u->fd,u,"%s",textbuffer);
632
633         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
634         {
635                 if (i->second)
636                 {
637                         if (common_channels(u,i->second) && (i->second != u))
638                         {
639                                 WriteFrom(i->second->fd,u,"%s",textbuffer);
640                         }
641                 }
642         }
643 }
644
645 /* write a formatted string to all users who share at least one common
646  * channel, NOT including the source user e.g. for use in QUIT */
647
648 void WriteCommonExcept(userrec *u, char* text, ...)
649 {
650         if (!u)
651         {
652                 log(DEFAULT,"*** BUG *** WriteCommon was given an invalid parameter");
653                 return;
654         }
655
656         if (u->registered != 7) {
657                 log(DEFAULT,"*** BUG *** WriteCommon on an unregistered user");
658                 return;
659         }
660
661         char textbuffer[MAXBUF];
662         va_list argsPtr;
663         va_start (argsPtr, text);
664         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
665         va_end(argsPtr);
666
667         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
668         {
669                 if (i->second)
670                 {
671                         if ((common_channels(u,i->second)) && (u != i->second))
672                         {
673                                 WriteFrom(i->second->fd,u,"%s",textbuffer);
674                         }
675                 }
676         }
677 }
678
679 void WriteOpers(char* text, ...)
680 {
681         if (!text)
682         {
683                 log(DEFAULT,"*** BUG *** WriteOpers was given an invalid parameter");
684                 return;
685         }
686
687         char textbuffer[MAXBUF];
688         va_list argsPtr;
689         va_start (argsPtr, text);
690         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
691         va_end(argsPtr);
692
693         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
694         {
695                 if (i->second)
696                 {
697                         if (strchr(i->second->modes,'o'))
698                         {
699                                 if (strchr(i->second->modes,'s'))
700                                 {
701                                         // send server notices to all with +s
702                                         // (TODO: needs SNOMASKs)
703                                         WriteServ(i->second->fd,"NOTICE %s :%s",i->second->nick,textbuffer);
704                                 }
705                         }
706                 }
707         }
708 }
709
710 // returns TRUE of any users on channel C occupy server 'servername'.
711
712 bool ChanAnyOnThisServer(chanrec *c,char* servername)
713 {
714         log(DEBUG,"ChanAnyOnThisServer");
715         for (user_hash::iterator i = clientlist.begin(); i != clientlist.end(); i++)
716         {
717                 if (has_channel(i->second,c))
718                 {
719                         if (!strcasecmp(i->second->server,servername))
720                         {
721                                 return true;
722                         }
723                 }
724         }
725         return false;
726 }
727
728 // returns true if user 'u' shares any common channels with any users on server 'servername'
729
730 bool CommonOnThisServer(userrec* u,const char* servername)
731 {
732         log(DEBUG,"ChanAnyOnThisServer");
733         for (user_hash::iterator i = clientlist.begin(); i != clientlist.end(); i++)
734         {
735                 if ((common_channels(u,i->second)) && (u != i->second))
736                 {
737                         if (!strcasecmp(i->second->server,servername))
738                         {
739                                 log(DEBUG,"%s is common to %s sharing with %s",i->second->nick,servername,u->nick);
740                                 return true;
741                         }
742                 }
743         }
744         return false;
745 }
746
747
748 void NetSendToCommon(userrec* u, char* s)
749 {
750         char buffer[MAXBUF];
751         snprintf(buffer,MAXBUF,"%s",s);
752         
753         log(DEBUG,"NetSendToCommon: '%s' '%s'",u->nick,s);
754
755         for (int j = 0; j < 32; j++)
756         {
757                 if (me[j] != NULL)
758                 {
759                         for (int k = 0; k < me[j]->connectors.size(); k++)
760                         {
761                                 if (CommonOnThisServer(u,me[j]->connectors[k].GetServerName().c_str()))
762                                 {
763                                         me[j]->SendPacket(buffer,me[j]->connectors[k].GetServerName().c_str());
764                                 }
765                         }
766                 }
767         }
768 }
769
770
771 void NetSendToAll(char* s)
772 {
773         char buffer[MAXBUF];
774         snprintf(buffer,MAXBUF,"%s",s);
775         
776         log(DEBUG,"NetSendToAll: '%s'",s);
777
778         for (int j = 0; j < 32; j++)
779         {
780                 if (me[j] != NULL)
781                 {
782                         for (int k = 0; k < me[j]->connectors.size(); k++)
783                         {
784                                 me[j]->SendPacket(buffer,me[j]->connectors[k].GetServerName().c_str());
785                         }
786                 }
787         }
788 }
789
790 void NetSendToAllAlive(char* s)
791 {
792         char buffer[MAXBUF];
793         snprintf(buffer,MAXBUF,"%s",s);
794         
795         log(DEBUG,"NetSendToAllAlive: '%s'",s);
796
797         for (int j = 0; j < 32; j++)
798         {
799                 if (me[j] != NULL)
800                 {
801                         for (int k = 0; k < me[j]->connectors.size(); k++)
802                         {
803                                 if (me[j]->connectors[k].GetState() != STATE_DISCONNECTED)
804                                 {
805                                         me[j]->SendPacket(buffer,me[j]->connectors[k].GetServerName().c_str());
806                                 }
807                                 else
808                                 {
809                                         log(DEBUG,"%s is dead, not sending to it.",me[j]->connectors[k].GetServerName().c_str());
810                                 }
811                         }
812                 }
813         }
814 }
815
816
817 void NetSendToOne(char* target,char* s)
818 {
819         char buffer[MAXBUF];
820         snprintf(buffer,MAXBUF,"%s",s);
821         
822         log(DEBUG,"NetSendToOne: '%s' '%s'",target,s);
823
824         for (int j = 0; j < 32; j++)
825         {
826                 if (me[j] != NULL)
827                 {
828                         for (int k = 0; k < me[j]->connectors.size(); k++)
829                         {
830                                 if (!strcasecmp(me[j]->connectors[k].GetServerName().c_str(),target))
831                                 {
832                                         me[j]->SendPacket(buffer,me[j]->connectors[k].GetServerName().c_str());
833                                 }
834                         }
835                 }
836         }
837 }
838
839 void NetSendToAllExcept(const char* target,char* s)
840 {
841         char buffer[MAXBUF];
842         snprintf(buffer,MAXBUF,"%s",s);
843         
844         log(DEBUG,"NetSendToAllExcept: '%s' '%s'",target,s);
845         
846         for (int j = 0; j < 32; j++)
847         {
848                 if (me[j] != NULL)
849                 {
850                         for (int k = 0; k < me[j]->connectors.size(); k++)
851                         {
852                                 if (strcasecmp(me[j]->connectors[k].GetServerName().c_str(),target))
853                                 {
854                                         me[j]->SendPacket(buffer,me[j]->connectors[k].GetServerName().c_str());
855                                 }
856                         }
857                 }
858         }
859 }
860
861
862 void WriteMode(const char* modes, int flags, const char* text, ...)
863 {
864         if ((!text) || (!modes) || (!flags))
865         {
866                 log(DEFAULT,"*** BUG *** WriteMode was given an invalid parameter");
867                 return;
868         }
869
870         char textbuffer[MAXBUF];
871         va_list argsPtr;
872         va_start (argsPtr, text);
873         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
874         va_end(argsPtr);
875
876         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
877         {
878                 if (i->second)
879                 {
880                         bool send_to_user = false;
881                         
882                         if (flags == WM_AND)
883                         {
884                                 send_to_user = true;
885                                 for (int n = 0; n < strlen(modes); n++)
886                                 {
887                                         if (!hasumode(i->second,modes[n]))
888                                         {
889                                                 send_to_user = false;
890                                                 break;
891                                         }
892                                 }
893                         }
894                         else if (flags == WM_OR)
895                         {
896                                 send_to_user = false;
897                                 for (int n = 0; n < strlen(modes); n++)
898                                 {
899                                         if (hasumode(i->second,modes[n]))
900                                         {
901                                                 send_to_user = true;
902                                                 break;
903                                         }
904                                 }
905                         }
906
907                         if (send_to_user)
908                         {
909                                 WriteServ(i->second->fd,"NOTICE %s :%s",i->second->nick,textbuffer);
910                         }
911                 }
912         }
913 }
914
915
916 void WriteWallOps(userrec *source, bool local_only, 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         if (!local_only)
943         {
944                 char buffer[MAXBUF];
945                 snprintf(buffer,MAXBUF,"@ %s :%s",source->nick,textbuffer);
946                 NetSendToAll(buffer);
947         }
948 }  
949
950 /* convert a string to lowercase. Note following special circumstances
951  * taken from RFC 1459. Many "official" server branches still hold to this
952  * rule so i will too;
953  *
954  *  Because of IRC's scandanavian origin, the characters {}| are
955  *  considered to be the lower case equivalents of the characters []\,
956  *  respectively. This is a critical issue when determining the
957  *  equivalence of two nicknames.
958  */
959
960 void strlower(char *n)
961 {
962         if (!n)
963         {
964                 return;
965         }
966         for (int i = 0; i != strlen(n); i++)
967         {
968                 n[i] = tolower(n[i]);
969                 if (n[i] == '[')
970                         n[i] = '{';
971                 if (n[i] == ']')
972                         n[i] = '}';
973                 if (n[i] == '\\')
974                         n[i] = '|';
975         }
976 }
977
978
979
980 /* Find a user record by nickname and return a pointer to it */
981
982 userrec* Find(string nick)
983 {
984         user_hash::iterator iter = clientlist.find(nick);
985
986         if (iter == clientlist.end())
987                 /* Couldn't find it */
988                 return NULL;
989
990         return iter->second;
991 }
992
993 void update_stats_l(int fd,int data_out) /* add one line-out to stats L for this fd */
994 {
995         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
996         {
997                 if (i->second)
998                 {
999                         if (i->second->fd == fd)
1000                         {
1001                                 i->second->bytes_out+=data_out;
1002                                 i->second->cmds_out++;
1003                         }
1004                 }
1005         }
1006 }
1007
1008
1009 /* find a channel record by channel name and return a pointer to it */
1010
1011 chanrec* FindChan(const char* chan)
1012 {
1013         if (!chan)
1014         {
1015                 log(DEFAULT,"*** BUG *** Findchan was given an invalid parameter");
1016                 return NULL;
1017         }
1018
1019         chan_hash::iterator iter = chanlist.find(chan);
1020
1021         if (iter == chanlist.end())
1022                 /* Couldn't find it */
1023                 return NULL;
1024
1025         return iter->second;
1026 }
1027
1028
1029 void purge_empty_chans(void)
1030 {
1031         int go_again = 1, purge = 0;
1032         
1033         while (go_again)
1034         {
1035                 go_again = 0;
1036                 for (chan_hash::iterator i = chanlist.begin(); i != chanlist.end(); i++)
1037                 {
1038                         if (i->second) {
1039                                 if (!usercount(i->second))
1040                                 {
1041                                         /* kill the record */
1042                                         if (i != chanlist.end())
1043                                         {
1044                                                 log(DEBUG,"del_channel: destroyed: %s",i->second->name);
1045                                                 delete i->second;
1046                                                 chanlist.erase(i);
1047                                                 go_again = 1;
1048                                                 purge++;
1049                                                 break;
1050                                         }
1051                                 }
1052                                 else
1053                                 {
1054                                         log(DEBUG,"skipped purge for %s",i->second->name);
1055                                 }
1056                         }
1057                 }
1058         }
1059         log(DEBUG,"completed channel purge, killed %d",purge);
1060 }
1061
1062
1063 char scratch[MAXBUF];
1064 char sparam[MAXBUF];
1065
1066 char* chanmodes(chanrec *chan)
1067 {
1068         if (!chan)
1069         {
1070                 log(DEFAULT,"*** BUG *** chanmodes was given an invalid parameter");
1071                 strcpy(scratch,"");
1072                 return scratch;
1073         }
1074
1075         strcpy(scratch,"");
1076         strcpy(sparam,"");
1077         if (chan->noexternal)
1078         {
1079                 strncat(scratch,"n",MAXMODES);
1080         }
1081         if (chan->topiclock)
1082         {
1083                 strncat(scratch,"t",MAXMODES);
1084         }
1085         if (strcmp(chan->key,""))
1086         {
1087                 strncat(scratch,"k",MAXMODES);
1088         }
1089         if (chan->limit)
1090         {
1091                 strncat(scratch,"l",MAXMODES);
1092         }
1093         if (chan->inviteonly)
1094         {
1095                 strncat(scratch,"i",MAXMODES);
1096         }
1097         if (chan->moderated)
1098         {
1099                 strncat(scratch,"m",MAXMODES);
1100         }
1101         if (chan->secret)
1102         {
1103                 strncat(scratch,"s",MAXMODES);
1104         }
1105         if (chan->c_private)
1106         {
1107                 strncat(scratch,"p",MAXMODES);
1108         }
1109         if (strcmp(chan->key,""))
1110         {
1111                 strncat(sparam,chan->key,MAXBUF);
1112         }
1113         if (chan->limit)
1114         {
1115                 char foo[24];
1116                 sprintf(foo," %d",chan->limit);
1117                 strncat(sparam,foo,MAXBUF);
1118         }
1119         if (strlen(chan->custom_modes))
1120         {
1121                 strncat(scratch,chan->custom_modes,MAXMODES);
1122                 for (int z = 0; z < strlen(chan->custom_modes); z++)
1123                 {
1124                         std::string extparam = chan->GetModeParameter(chan->custom_modes[z]);
1125                         if (extparam != "")
1126                         {
1127                                 strncat(sparam," ",MAXBUF);
1128                                 strncat(sparam,extparam.c_str(),MAXBUF);
1129                         }
1130                 }
1131         }
1132         log(DEBUG,"chanmodes: %s %s%s",chan->name,scratch,sparam);
1133         strncat(scratch,sparam,MAXMODES);
1134         return scratch;
1135 }
1136
1137
1138 /* compile a userlist of a channel into a string, each nick seperated by
1139  * spaces and op, voice etc status shown as @ and + */
1140
1141 void userlist(userrec *user,chanrec *c)
1142 {
1143         if ((!c) || (!user))
1144         {
1145                 log(DEFAULT,"*** BUG *** userlist was given an invalid parameter");
1146                 return;
1147         }
1148
1149         sprintf(list,"353 %s = %s :", user->nick, c->name);
1150         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1151         {
1152                 if (has_channel(i->second,c))
1153                 {
1154                         if (isnick(i->second->nick))
1155                         {
1156                                 if ((!has_channel(i->second,c)) && (strchr(i->second->modes,'i')))
1157                                 {
1158                                         /* user is +i, and source not on the channel, does not show
1159                                          * nick in NAMES list */
1160                                         continue;
1161                                 }
1162                                 strcat(list,cmode(i->second,c));
1163                                 strcat(list,i->second->nick);
1164                                 strcat(list," ");
1165                                 if (strlen(list)>(480-NICKMAX))
1166                                 {
1167                                         /* list overflowed into
1168                                          * multiple numerics */
1169                                         WriteServ(user->fd,list);
1170                                         sprintf(list,"353 %s = %s :", user->nick, c->name);
1171                                 }
1172                         }
1173                 }
1174         }
1175         /* if whats left in the list isnt empty, send it */
1176         if (list[strlen(list)-1] != ':')
1177         {
1178                 WriteServ(user->fd,list);
1179         }
1180 }
1181
1182 /* return a count of the users on a specific channel accounting for
1183  * invisible users who won't increase the count. e.g. for /LIST */
1184
1185 int usercount_i(chanrec *c)
1186 {
1187         int i = 0;
1188         int count = 0;
1189         
1190         if (!c)
1191         {
1192                 log(DEFAULT,"*** BUG *** usercount_i was given an invalid parameter");
1193                 return 0;
1194         }
1195
1196         strcpy(list,"");
1197         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1198         {
1199                 if (i->second)
1200                 {
1201                         if (has_channel(i->second,c))
1202                         {
1203                                 if (isnick(i->second->nick))
1204                                 {
1205                                         if ((!has_channel(i->second,c)) && (strchr(i->second->modes,'i')))
1206                                         {
1207                                                 /* user is +i, and source not on the channel, does not show
1208                                                  * nick in NAMES list */
1209                                                 continue;
1210                                         }
1211                                         count++;
1212                                 }
1213                         }
1214                 }
1215         }
1216         log(DEBUG,"usercount_i: %s %d",c->name,count);
1217         return count;
1218 }
1219
1220
1221 int usercount(chanrec *c)
1222 {
1223         int i = 0;
1224         int count = 0;
1225         
1226         if (!c)
1227         {
1228                 log(DEFAULT,"*** BUG *** usercount was given an invalid parameter");
1229                 return 0;
1230         }
1231
1232         strcpy(list,"");
1233         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1234         {
1235                 if (i->second)
1236                 {
1237                         if (has_channel(i->second,c))
1238                         {
1239                                 if ((isnick(i->second->nick)) && (i->second->registered == 7))
1240                                 {
1241                                         count++;
1242                                 }
1243                         }
1244                 }
1245         }
1246         log(DEBUG,"usercount: %s %d",c->name,count);
1247         return count;
1248 }
1249
1250
1251 /* add a channel to a user, creating the record for it if needed and linking
1252  * it to the user record */
1253
1254 chanrec* add_channel(userrec *user, const char* cn, const char* key, bool override)
1255 {
1256         if ((!user) || (!cn))
1257         {
1258                 log(DEFAULT,"*** BUG *** add_channel was given an invalid parameter");
1259                 return 0;
1260         }
1261
1262         int i = 0;
1263         chanrec* Ptr;
1264         int created = 0;
1265         char cname[MAXBUF];
1266
1267         strncpy(cname,cn,MAXBUF);
1268         
1269         // we MUST declare this wherever we use FOREACH_RESULT
1270         int MOD_RESULT = 0;
1271
1272         if (strlen(cname) > CHANMAX-1)
1273         {
1274                 cname[CHANMAX-1] = '\0';
1275         }
1276
1277         log(DEBUG,"add_channel: %s %s",user->nick,cname);
1278         
1279         if ((FindChan(cname)) && (has_channel(user,FindChan(cname))))
1280         {
1281                 return NULL; // already on the channel!
1282         }
1283
1284
1285         if (!FindChan(cname))
1286         {
1287                 FOREACH_RESULT(OnUserPreJoin(user,NULL,cname));
1288                 if (MOD_RESULT) {
1289                         return NULL;
1290                 }
1291
1292                 /* create a new one */
1293                 log(DEBUG,"add_channel: creating: %s",cname);
1294                 {
1295                         chanlist[cname] = new chanrec();
1296
1297                         strcpy(chanlist[cname]->name, cname);
1298                         chanlist[cname]->topiclock = 1;
1299                         chanlist[cname]->noexternal = 1;
1300                         chanlist[cname]->created = time(NULL);
1301                         strcpy(chanlist[cname]->topic, "");
1302                         strncpy(chanlist[cname]->setby, user->nick,NICKMAX);
1303                         chanlist[cname]->topicset = 0;
1304                         Ptr = chanlist[cname];
1305                         log(DEBUG,"add_channel: created: %s",cname);
1306                         /* set created to 2 to indicate user
1307                          * is the first in the channel
1308                          * and should be given ops */
1309                         created = 2;
1310                 }
1311         }
1312         else
1313         {
1314                 /* channel exists, just fish out a pointer to its struct */
1315                 Ptr = FindChan(cname);
1316                 if (Ptr)
1317                 {
1318                         log(DEBUG,"add_channel: joining to: %s",Ptr->name);
1319                         
1320                         // the override flag allows us to bypass channel modes
1321                         // and bans (used by servers)
1322                         if (!override)
1323                         {
1324                                 FOREACH_RESULT(OnUserPreJoin(user,Ptr,cname));
1325                                 if (MOD_RESULT) {
1326                                         return NULL;
1327                                 }
1328                                 
1329                                 if (strcmp(Ptr->key,""))
1330                                 {
1331                                         log(DEBUG,"add_channel: %s has key %s",Ptr->name,Ptr->key);
1332                                         if (!key)
1333                                         {
1334                                                 log(DEBUG,"add_channel: no key given in JOIN");
1335                                                 WriteServ(user->fd,"475 %s %s :Cannot join channel (Requires key)",user->nick, Ptr->name);
1336                                                 return NULL;
1337                                         }
1338                                         else
1339                                         {
1340                                                 log(DEBUG,"key at %p is %s",key,key);
1341                                                 if (strcasecmp(key,Ptr->key))
1342                                                 {
1343                                                         log(DEBUG,"add_channel: bad key given in JOIN");
1344                                                         WriteServ(user->fd,"475 %s %s :Cannot join channel (Incorrect key)",user->nick, Ptr->name);
1345                                                         return NULL;
1346                                                 }
1347                                         }
1348                                 }
1349                                 log(DEBUG,"add_channel: no key");
1350         
1351                                 if (Ptr->inviteonly)
1352                                 {
1353                                         log(DEBUG,"add_channel: channel is +i");
1354                                         if (user->IsInvited(Ptr->name))
1355                                         {
1356                                                 /* user was invited to channel */
1357                                                 /* there may be an optional channel NOTICE here */
1358                                         }
1359                                         else
1360                                         {
1361                                                 WriteServ(user->fd,"473 %s %s :Cannot join channel (Invite only)",user->nick, Ptr->name);
1362                                                 return NULL;
1363                                         }
1364                                 }
1365                                 log(DEBUG,"add_channel: channel is not +i");
1366         
1367                                 if (Ptr->limit)
1368                                 {
1369                                         if (usercount(Ptr) == Ptr->limit)
1370                                         {
1371                                                 WriteServ(user->fd,"471 %s %s :Cannot join channel (Channel is full)",user->nick, Ptr->name);
1372                                                 return NULL;
1373                                         }
1374                                 }
1375                                 
1376                                 log(DEBUG,"add_channel: about to walk banlist");
1377         
1378                                 /* check user against the channel banlist */
1379                                 if (Ptr)
1380                                 {
1381                                         if (Ptr->bans.size())
1382                                         {
1383                                                 for (BanList::iterator i = Ptr->bans.begin(); i != Ptr->bans.end(); i++)
1384                                                 {
1385                                                         if (match(user->GetFullHost(),i->data))
1386                                                         {
1387                                                                 WriteServ(user->fd,"474 %s %s :Cannot join channel (You're banned)",user->nick, Ptr->name);
1388                                                                 return NULL;
1389                                                         }
1390                                                 }
1391                                         }
1392                                 }
1393                                 
1394                                 log(DEBUG,"add_channel: bans checked");
1395                                 
1396
1397                                 if ((Ptr) && (user))
1398                                 {
1399                                         user->RemoveInvite(Ptr->name);
1400                                 }
1401         
1402                                 log(DEBUG,"add_channel: invites removed");
1403
1404                         }
1405                         else
1406                         {
1407                                 log(DEBUG,"Overridden checks");
1408                         }
1409
1410                         
1411                 }
1412                 created = 1;
1413         }
1414
1415         log(DEBUG,"Passed channel checks");
1416         
1417         for (int i =0; i != MAXCHANS; i++)
1418         {
1419                 log(DEBUG,"Check location %d",i);
1420                 if (user->chans[i].channel == NULL)
1421                 {
1422                         log(DEBUG,"Adding into their channel list at location %d",i);
1423
1424                         if (created == 2) 
1425                         {
1426                                 /* first user in is given ops */
1427                                 user->chans[i].uc_modes = UCMODE_OP;
1428                         }
1429                         else
1430                         {
1431                                 user->chans[i].uc_modes = 0;
1432                         }
1433                         user->chans[i].channel = Ptr;
1434                         WriteChannel(Ptr,user,"JOIN :%s",Ptr->name);
1435                         
1436                         if (!override) // we're not overriding... so this isnt part of a netburst, broadcast it.
1437                         {
1438                                 // use the stamdard J token with no privilages.
1439                                 char buffer[MAXBUF];
1440                                 snprintf(buffer,MAXBUF,"J %s :%s",user->nick,Ptr->name);
1441                                 NetSendToAll(buffer);
1442                         }
1443
1444                         log(DEBUG,"Sent JOIN to client");
1445
1446                         if (Ptr->topicset)
1447                         {
1448                                 WriteServ(user->fd,"332 %s %s :%s", user->nick, Ptr->name, Ptr->topic);
1449                                 WriteServ(user->fd,"333 %s %s %s %d", user->nick, Ptr->name, Ptr->setby, Ptr->topicset);
1450                         }
1451                         userlist(user,Ptr);
1452                         WriteServ(user->fd,"366 %s %s :End of /NAMES list.", user->nick, Ptr->name);
1453                         WriteServ(user->fd,"324 %s %s +%s",user->nick, Ptr->name,chanmodes(Ptr));
1454                         WriteServ(user->fd,"329 %s %s %d", user->nick, Ptr->name, Ptr->created);
1455                         FOREACH_MOD OnUserJoin(user,Ptr);
1456                         return Ptr;
1457                 }
1458         }
1459         log(DEBUG,"add_channel: user channel max exceeded: %s %s",user->nick,cname);
1460         WriteServ(user->fd,"405 %s %s :You are on too many channels",user->nick, cname);
1461         return NULL;
1462 }
1463
1464 /* remove a channel from a users record, and remove the record from memory
1465  * if the channel has become empty */
1466
1467 chanrec* del_channel(userrec *user, const char* cname, const char* reason, bool local)
1468 {
1469         if ((!user) || (!cname))
1470         {
1471                 log(DEFAULT,"*** BUG *** del_channel was given an invalid parameter");
1472                 return NULL;
1473         }
1474
1475         chanrec* Ptr;
1476         int created = 0;
1477
1478         if ((!cname) || (!user))
1479         {
1480                 return NULL;
1481         }
1482
1483         Ptr = FindChan(cname);
1484         
1485         if (!Ptr)
1486         {
1487                 return NULL;
1488         }
1489
1490         FOREACH_MOD OnUserPart(user,Ptr);
1491         log(DEBUG,"del_channel: removing: %s %s",user->nick,Ptr->name);
1492         
1493         for (int i =0; i != MAXCHANS; i++)
1494         {
1495                 /* zap it from the channel list of the user */
1496                 if (user->chans[i].channel == Ptr)
1497                 {
1498                         if (reason)
1499                         {
1500                                 WriteChannel(Ptr,user,"PART %s :%s",Ptr->name, reason);
1501
1502                                 if (!local)
1503                                 {
1504                                         char buffer[MAXBUF];
1505                                         snprintf(buffer,MAXBUF,"L %s %s :%s",user->nick,Ptr->name,reason);
1506                                         NetSendToAll(buffer);
1507                                 }
1508
1509                                 
1510                         }
1511                         else
1512                         {
1513                                 if (!local)
1514                                 {
1515                                         char buffer[MAXBUF];
1516                                         snprintf(buffer,MAXBUF,"L %s %s :",user->nick,Ptr->name);
1517                                         NetSendToAll(buffer);
1518                                 }
1519                         
1520                                 WriteChannel(Ptr,user,"PART :%s",Ptr->name);
1521                         }
1522                         user->chans[i].uc_modes = 0;
1523                         user->chans[i].channel = NULL;
1524                         log(DEBUG,"del_channel: unlinked: %s %s",user->nick,Ptr->name);
1525                         break;
1526                 }
1527         }
1528         
1529         /* if there are no users left on the channel */
1530         if (!usercount(Ptr))
1531         {
1532                 chan_hash::iterator iter = chanlist.find(Ptr->name);
1533
1534                 log(DEBUG,"del_channel: destroying channel: %s",Ptr->name);
1535
1536                 /* kill the record */
1537                 if (iter != chanlist.end())
1538                 {
1539                         log(DEBUG,"del_channel: destroyed: %s",Ptr->name);
1540                         delete iter->second;
1541                         chanlist.erase(iter);
1542                 }
1543         }
1544 }
1545
1546
1547 void kick_channel(userrec *src,userrec *user, chanrec *Ptr, char* reason)
1548 {
1549         if ((!src) || (!user) || (!Ptr) || (!reason))
1550         {
1551                 log(DEFAULT,"*** BUG *** kick_channel was given an invalid parameter");
1552                 return;
1553         }
1554
1555         int i = 0;
1556         int created = 0;
1557
1558         if ((!Ptr) || (!user) || (!src))
1559         {
1560                 return;
1561         }
1562
1563         log(DEBUG,"kick_channel: removing: %s %s %s",user->nick,Ptr->name,src->nick);
1564
1565         if (!has_channel(user,Ptr))
1566         {
1567                 WriteServ(src->fd,"441 %s %s %s :They are not on that channel",src->nick, user->nick, Ptr->name);
1568                 return;
1569         }
1570         if ((cstatus(src,Ptr) < STATUS_HOP) || (cstatus(src,Ptr) < cstatus(user,Ptr)))
1571         {
1572                 if (cstatus(src,Ptr) == STATUS_HOP)
1573                 {
1574                         WriteServ(src->fd,"482 %s %s :You must be a channel operator",src->nick, Ptr->name);
1575                 }
1576                 else
1577                 {
1578                         WriteServ(src->fd,"482 %s %s :You must be at least a half-operator to change modes on this channel",src->nick, Ptr->name);
1579                 }
1580                 
1581                 return;
1582         }
1583         
1584         for (int i =0; i != MAXCHANS; i++)
1585         {
1586                 /* zap it from the channel list of the user */
1587                 if (user->chans[i].channel)
1588                 if (!strcasecmp(user->chans[i].channel->name,Ptr->name))
1589                 {
1590                         WriteChannel(Ptr,src,"KICK %s %s :%s",Ptr->name, user->nick, reason);
1591                         user->chans[i].uc_modes = 0;
1592                         user->chans[i].channel = NULL;
1593                         log(DEBUG,"del_channel: unlinked: %s %s",user->nick,Ptr->name);
1594                         break;
1595                 }
1596         }
1597         
1598         /* if there are no users left on the channel */
1599         if (!usercount(Ptr))
1600         {
1601                 chan_hash::iterator iter = chanlist.find(Ptr->name);
1602
1603                 log(DEBUG,"del_channel: destroying channel: %s",Ptr->name);
1604
1605                 /* kill the record */
1606                 if (iter != chanlist.end())
1607                 {
1608                         log(DEBUG,"del_channel: destroyed: %s",Ptr->name);
1609                         delete iter->second;
1610                         chanlist.erase(iter);
1611                 }
1612         }
1613 }
1614
1615
1616
1617
1618 /* This function pokes and hacks at a parameter list like the following:
1619  *
1620  * PART #winbot, #darkgalaxy :m00!
1621  *
1622  * to turn it into a series of individual calls like this:
1623  *
1624  * PART #winbot :m00!
1625  * PART #darkgalaxy :m00!
1626  *
1627  * The seperate calls are sent to a callback function provided by the caller
1628  * (the caller will usually call itself recursively). The callback function
1629  * must be a command handler. Calling this function on a line with no list causes
1630  * no action to be taken. You must provide a starting and ending parameter number
1631  * where the range of the list can be found, useful if you have a terminating
1632  * parameter as above which is actually not part of the list, or parameters
1633  * before the actual list as well. This code is used by many functions which
1634  * can function as "one to list" (see the RFC) */
1635
1636 int loop_call(handlerfunc fn, char **parameters, int pcnt, userrec *u, int start, int end, int joins)
1637 {
1638         char plist[MAXBUF];
1639         char *param;
1640         char *pars[32];
1641         char blog[32][MAXBUF];
1642         char blog2[32][MAXBUF];
1643         int i = 0, j = 0, q = 0, total = 0, t = 0, t2 = 0, total2 = 0;
1644         char keystr[MAXBUF];
1645         char moo[MAXBUF];
1646
1647         for (int i = 0; i <32; i++)
1648                 strcpy(blog[i],"");
1649
1650         for (int i = 0; i <32; i++)
1651                 strcpy(blog2[i],"");
1652
1653         strcpy(moo,"");
1654         for (int i = 0; i <10; i++)
1655         {
1656                 if (!parameters[i])
1657                 {
1658                         parameters[i] = moo;
1659                 }
1660         }
1661         if (joins)
1662         {
1663                 if (pcnt > 1) /* we have a key to copy */
1664                 {
1665                         strcpy(keystr,parameters[1]);
1666                 }
1667         }
1668
1669         if (!parameters[start])
1670         {
1671                 return 0;
1672         }
1673         if (!strchr(parameters[start],','))
1674         {
1675                 return 0;
1676         }
1677         strcpy(plist,"");
1678         for (int i = start; i <= end; i++)
1679         {
1680                 if (parameters[i])
1681                 {
1682                         strcat(plist,parameters[i]);
1683                 }
1684         }
1685         
1686         j = 0;
1687         param = plist;
1688
1689         t = strlen(plist);
1690         for (int i = 0; i < t; i++)
1691         {
1692                 if (plist[i] == ',')
1693                 {
1694                         plist[i] = '\0';
1695                         strcpy(blog[j++],param);
1696                         param = plist+i+1;
1697                         if (j>20)
1698                         {
1699                                 WriteServ(u->fd,"407 %s %s :Too many targets in list, message not delivered.",u->nick,blog[j-1]);
1700                                 return 1;
1701                         }
1702                 }
1703         }
1704         strcpy(blog[j++],param);
1705         total = j;
1706
1707         if ((joins) && (keystr) && (total>0)) // more than one channel and is joining
1708         {
1709                 strcat(keystr,",");
1710         }
1711         
1712         if ((joins) && (keystr))
1713         {
1714                 if (strchr(keystr,','))
1715                 {
1716                         j = 0;
1717                         param = keystr;
1718                         t2 = strlen(keystr);
1719                         for (int i = 0; i < t2; i++)
1720                         {
1721                                 if (keystr[i] == ',')
1722                                 {
1723                                         keystr[i] = '\0';
1724                                         strcpy(blog2[j++],param);
1725                                         param = keystr+i+1;
1726                                 }
1727                         }
1728                         strcpy(blog2[j++],param);
1729                         total2 = j;
1730                 }
1731         }
1732
1733         for (j = 0; j < total; j++)
1734         {
1735                 if (blog[j])
1736                 {
1737                         pars[0] = blog[j];
1738                 }
1739                 for (q = end; q < pcnt-1; q++)
1740                 {
1741                         if (parameters[q+1])
1742                         {
1743                                 pars[q-end+1] = parameters[q+1];
1744                         }
1745                 }
1746                 if ((joins) && (parameters[1]))
1747                 {
1748                         if (pcnt > 1)
1749                         {
1750                                 pars[1] = blog2[j];
1751                         }
1752                         else
1753                         {
1754                                 pars[1] = NULL;
1755                         }
1756                 }
1757                 /* repeatedly call the function with the hacked parameter list */
1758                 if ((joins) && (pcnt > 1))
1759                 {
1760                         if (pars[1])
1761                         {
1762                                 // pars[1] already set up and containing key from blog2[j]
1763                                 fn(pars,2,u);
1764                         }
1765                         else
1766                         {
1767                                 pars[1] = parameters[1];
1768                                 fn(pars,2,u);
1769                         }
1770                 }
1771                 else
1772                 {
1773                         fn(pars,pcnt-(end-start),u);
1774                 }
1775         }
1776
1777         return 1;
1778 }
1779
1780
1781
1782 void kill_link(userrec *user,const char* r)
1783 {
1784         user_hash::iterator iter = clientlist.find(user->nick);
1785         
1786         char reason[MAXBUF];
1787         
1788         strncpy(reason,r,MAXBUF);
1789
1790         if (strlen(reason)>MAXQUIT)
1791         {
1792                 reason[MAXQUIT-1] = '\0';
1793         }
1794
1795         log(DEBUG,"kill_link: %s '%s'",user->nick,reason);
1796         Write(user->fd,"ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,reason);
1797         log(DEBUG,"closing fd %d",user->fd);
1798
1799         /* bugfix, cant close() a nonblocking socket (sux!) */
1800         if (user->registered == 7) {
1801                 FOREACH_MOD OnUserQuit(user);
1802                 WriteCommonExcept(user,"QUIT :%s",reason);
1803
1804                 // Q token must go to ALL servers!!!
1805                 char buffer[MAXBUF];
1806                 snprintf(buffer,MAXBUF,"Q %s :%s",user->nick,reason);
1807                 NetSendToAll(buffer);
1808         }
1809
1810         /* push the socket on a stack of sockets due to be closed at the next opportunity
1811          * 'Client exited' is an exception to this as it means the client side has already
1812          * closed the socket, we don't need to do it.
1813          */
1814         fd_reap.push_back(user->fd);
1815         
1816         bool do_purge = false;
1817         
1818         if (user->registered == 7) {
1819                 WriteOpers("*** Client exiting: %s!%s@%s [%s]",user->nick,user->ident,user->host,reason);
1820                 AddWhoWas(user);
1821         }
1822
1823         if (iter != clientlist.end())
1824         {
1825                 log(DEBUG,"deleting user hash value %d",iter->second);
1826                 if ((iter->second) && (user->registered == 7)) {
1827                         delete iter->second;
1828                 }
1829                 clientlist.erase(iter);
1830         }
1831
1832         if (user->registered == 7) {
1833                 purge_empty_chans();
1834         }
1835 }
1836
1837
1838
1839 // looks up a users password for their connection class (<ALLOW>/<DENY> tags)
1840
1841 char* Passwd(userrec *user)
1842 {
1843         for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
1844         {
1845                 if (match(user->host,i->host) && (i->type == CC_ALLOW))
1846                 {
1847                         return i->pass;
1848                 }
1849         }
1850         return "";
1851 }
1852
1853 bool IsDenied(userrec *user)
1854 {
1855         for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
1856         {
1857                 if (match(user->host,i->host) && (i->type == CC_DENY))
1858                 {
1859                         return true;
1860                 }
1861         }
1862         return false;
1863 }
1864
1865
1866
1867
1868 /* sends out an error notice to all connected clients (not to be used
1869  * lightly!) */
1870
1871 void send_error(char *s)
1872 {
1873         log(DEBUG,"send_error: %s",s);
1874         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1875         {
1876                 if (isnick(i->second->nick))
1877                 {
1878                         WriteServ(i->second->fd,"NOTICE %s :%s",i->second->nick,s);
1879                 }
1880                 else
1881                 {
1882                         // fix - unregistered connections receive ERROR, not NOTICE
1883                         Write(i->second->fd,"ERROR :%s",s);
1884                 }
1885         }
1886 }
1887
1888 void Error(int status)
1889 {
1890         signal (SIGALRM, SIG_IGN);
1891         signal (SIGPIPE, SIG_IGN);
1892         signal (SIGTERM, SIG_IGN);
1893         signal (SIGABRT, SIG_IGN);
1894         signal (SIGSEGV, SIG_IGN);
1895         signal (SIGURG, SIG_IGN);
1896         signal (SIGKILL, SIG_IGN);
1897         log(DEBUG,"*** fell down a pothole in the road to perfection ***");
1898         send_error("Error! Segmentation fault! save meeeeeeeeeeeeee *splat!*");
1899         exit(status);
1900 }
1901
1902
1903 int main(int argc, char *argv[])
1904 {
1905         Start();
1906         srand(time(NULL));
1907         log(DEBUG,"*** InspIRCd starting up!");
1908         if (!FileExists(CONFIG_FILE))
1909         {
1910                 printf("ERROR: Cannot open config file: %s\nExiting...\n",CONFIG_FILE);
1911                 log(DEBUG,"main: no config");
1912                 printf("ERROR: Your config file is missing, this IRCd will self destruct in 10 seconds!\n");
1913                 Exit(ERROR);
1914         }
1915         if (argc > 1) {
1916                 if (!strcmp(argv[1],"-nofork")) {
1917                         nofork = true;
1918                 }
1919         }
1920         if (InspIRCd() == ERROR)
1921         {
1922                 log(DEBUG,"main: daemon function bailed");
1923                 printf("ERROR: could not initialise. Shutting down.\n");
1924                 Exit(ERROR);
1925         }
1926         Exit(TRUE);
1927         return 0;
1928 }
1929
1930 template<typename T> inline string ConvToStr(const T &in)
1931 {
1932         stringstream tmp;
1933         if (!(tmp << in)) return string();
1934         return tmp.str();
1935 }
1936
1937 /* re-allocates a nick in the user_hash after they change nicknames,
1938  * returns a pointer to the new user as it may have moved */
1939
1940 userrec* ReHashNick(char* Old, char* New)
1941 {
1942         user_hash::iterator newnick;
1943         user_hash::iterator oldnick = clientlist.find(Old);
1944
1945         log(DEBUG,"ReHashNick: %s %s",Old,New);
1946         
1947         if (!strcasecmp(Old,New))
1948         {
1949                 log(DEBUG,"old nick is new nick, skipping");
1950                 return oldnick->second;
1951         }
1952         
1953         if (oldnick == clientlist.end()) return NULL; /* doesnt exist */
1954
1955         log(DEBUG,"ReHashNick: Found hashed nick %s",Old);
1956
1957         clientlist[New] = new userrec();
1958         clientlist[New] = oldnick->second;
1959         /*delete oldnick->second; */
1960         clientlist.erase(oldnick);
1961
1962         log(DEBUG,"ReHashNick: Nick rehashed as %s",New);
1963         
1964         return clientlist[New];
1965 }
1966
1967 /* adds or updates an entry in the whowas list */
1968 void AddWhoWas(userrec* u)
1969 {
1970         user_hash::iterator iter = whowas.find(u->nick);
1971         userrec *a = new userrec();
1972         strcpy(a->nick,u->nick);
1973         strcpy(a->ident,u->ident);
1974         strcpy(a->dhost,u->dhost);
1975         strcpy(a->host,u->host);
1976         strcpy(a->fullname,u->fullname);
1977         strcpy(a->server,u->server);
1978         a->signon = u->signon;
1979
1980         /* MAX_WHOWAS:   max number of /WHOWAS items
1981          * WHOWAS_STALE: number of hours before a WHOWAS item is marked as stale and
1982          *               can be replaced by a newer one
1983          */
1984         
1985         if (iter == whowas.end())
1986         {
1987                 if (whowas.size() == WHOWAS_MAX)
1988                 {
1989                         for (user_hash::iterator i = whowas.begin(); i != whowas.end(); i++)
1990                         {
1991                                 // 3600 seconds in an hour ;)
1992                                 if ((i->second->signon)<(time(NULL)-(WHOWAS_STALE*3600)))
1993                                 {
1994                                         delete i->second;
1995                                         i->second = a;
1996                                         log(DEBUG,"added WHOWAS entry, purged an old record");
1997                                         return;
1998                                 }
1999                         }
2000                 }
2001                 else
2002                 {
2003                         log(DEBUG,"added fresh WHOWAS entry");
2004                         whowas[a->nick] = a;
2005                 }
2006         }
2007         else
2008         {
2009                 log(DEBUG,"updated WHOWAS entry");
2010                 delete iter->second;
2011                 iter->second = a;
2012         }
2013 }
2014
2015
2016 /* add a client connection to the sockets list */
2017 void AddClient(int socket, char* host, int port, bool iscached)
2018 {
2019         int i;
2020         int blocking = 1;
2021         char resolved[MAXBUF];
2022         string tempnick;
2023         char tn2[MAXBUF];
2024         user_hash::iterator iter;
2025
2026         tempnick = ConvToStr(socket) + "-unknown";
2027         sprintf(tn2,"%d-unknown",socket);
2028
2029         iter = clientlist.find(tempnick);
2030
2031         if (iter != clientlist.end()) return;
2032
2033         /*
2034          * It is OK to access the value here this way since we know
2035          * it exists, we just created it above.
2036          *
2037          * At NO other time should you access a value in a map or a
2038          * hash_map this way.
2039          */
2040         clientlist[tempnick] = new userrec();
2041
2042         NonBlocking(socket);
2043         log(DEBUG,"AddClient: %d %s %d",socket,host,port);
2044
2045         clientlist[tempnick]->fd = socket;
2046         strncpy(clientlist[tempnick]->nick, tn2,NICKMAX);
2047         strncpy(clientlist[tempnick]->host, host,160);
2048         strncpy(clientlist[tempnick]->dhost, host,160);
2049         strncpy(clientlist[tempnick]->server, ServerName,256);
2050         strncpy(clientlist[tempnick]->ident, "unknown",9);
2051         clientlist[tempnick]->registered = 0;
2052         clientlist[tempnick]->signon = time(NULL);
2053         clientlist[tempnick]->nping = time(NULL)+240;
2054         clientlist[tempnick]->lastping = 1;
2055         clientlist[tempnick]->port = port;
2056
2057         if (iscached)
2058         {
2059                 WriteServ(socket,"NOTICE Auth :Found your hostname (cached)...");
2060         }
2061         else
2062         {
2063                 WriteServ(socket,"NOTICE Auth :Looking up your hostname...");
2064         }
2065
2066         // set the registration timeout for this user
2067         unsigned long class_regtimeout = 90;
2068         for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
2069         {
2070                 if (match(clientlist[tempnick]->host,i->host) && (i->type == CC_ALLOW))
2071                 {
2072                         class_regtimeout = (unsigned long)i->registration_timeout;
2073                         break;
2074                 }
2075         }
2076
2077         int class_flood = 0;
2078         for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
2079         {
2080                 if (match(clientlist[tempnick]->host,i->host) && (i->type == CC_ALLOW))
2081                 {
2082                         class_flood = i->flood;
2083                         break;
2084                 }
2085         }
2086
2087         clientlist[tempnick]->timeout = time(NULL)+class_regtimeout;
2088         clientlist[tempnick]->flood = class_flood;
2089
2090         for (int i = 0; i < MAXCHANS; i++)
2091         {
2092                 clientlist[tempnick]->chans[i].channel = NULL;
2093                 clientlist[tempnick]->chans[i].uc_modes = 0;
2094         }
2095
2096         if (clientlist.size() == MAXCLIENTS)
2097                 kill_link(clientlist[tempnick],"No more connections allowed in this class");
2098 }
2099
2100
2101 int usercnt(void)
2102 {
2103         return clientlist.size();
2104 }
2105
2106
2107 int usercount_invisible(void)
2108 {
2109         int c = 0;
2110
2111         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
2112         {
2113                 if ((i->second->fd) && (isnick(i->second->nick)) && (strchr(i->second->modes,'i'))) c++;
2114         }
2115         return c;
2116 }
2117
2118 int usercount_opers(void)
2119 {
2120         int c = 0;
2121
2122         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
2123         {
2124                 if ((i->second->fd) && (isnick(i->second->nick)) && (strchr(i->second->modes,'o'))) c++;
2125         }
2126         return c;
2127 }
2128
2129 int usercount_unknown(void)
2130 {
2131         int c = 0;
2132
2133         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
2134         {
2135                 if ((i->second->fd) && (i->second->registered != 7))
2136                         c++;
2137         }
2138         return c;
2139 }
2140
2141 long chancount(void)
2142 {
2143         return chanlist.size();
2144 }
2145
2146 long count_servs(void)
2147 {
2148         int c = 0;
2149         //for (int j = 0; j < 255; j++)
2150         //{
2151         //      if (servers[j] != NULL)
2152         //              c++;
2153         //}
2154         return c;
2155 }
2156
2157 long servercount(void)
2158 {
2159         return count_servs()+1;
2160 }
2161
2162 long local_count()
2163 {
2164         int c = 0;
2165         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
2166         {
2167                 if ((i->second->fd) && (isnick(i->second->nick)) && (!strcasecmp(i->second->server,ServerName))) c++;
2168         }
2169         return c;
2170 }
2171
2172
2173 void ShowMOTD(userrec *user)
2174 {
2175         if (!MOTD.size())
2176         {
2177                 WriteServ(user->fd,"422 %s :Message of the day file is missing.",user->nick);
2178                 return;
2179         }
2180         WriteServ(user->fd,"375 %s :- %s message of the day",user->nick,ServerName);
2181         for (int i = 0; i != MOTD.size(); i++)
2182         {
2183                                 WriteServ(user->fd,"372 %s :- %s",user->nick,MOTD[i].c_str());
2184         }
2185         WriteServ(user->fd,"376 %s :End of %s message of the day.",user->nick,ServerName);
2186 }
2187
2188 void ShowRULES(userrec *user)
2189 {
2190         if (!RULES.size())
2191         {
2192                 WriteServ(user->fd,"NOTICE %s :Rules file is missing.",user->nick);
2193                 return;
2194         }
2195         WriteServ(user->fd,"NOTICE %s :%s rules",user->nick,ServerName);
2196         for (int i = 0; i != RULES.size(); i++)
2197         {
2198                                 WriteServ(user->fd,"NOTICE %s :%s",user->nick,RULES[i].c_str());
2199         }
2200         WriteServ(user->fd,"NOTICE %s :End of %s rules.",user->nick,ServerName);
2201 }
2202
2203 /* shows the message of the day, and any other on-logon stuff */
2204 void ConnectUser(userrec *user)
2205 {
2206         user->registered = 7;
2207         user->idle_lastmsg = time(NULL);
2208         log(DEBUG,"ConnectUser: %s",user->nick);
2209
2210         if (strcmp(Passwd(user),"") && (!user->haspassed))
2211         {
2212                 kill_link(user,"Invalid password");
2213                 return;
2214         }
2215         if (IsDenied(user))
2216         {
2217                 kill_link(user,"Unauthorised connection");
2218                 return;
2219         }
2220
2221         WriteServ(user->fd,"NOTICE Auth :Welcome to \002%s\002!",Network);
2222         WriteServ(user->fd,"001 %s :Welcome to the %s IRC Network %s!%s@%s",user->nick,Network,user->nick,user->ident,user->host);
2223         WriteServ(user->fd,"002 %s :Your host is %s, running version %s",user->nick,ServerName,VERSION);
2224         WriteServ(user->fd,"003 %s :This server was created %s %s",user->nick,__TIME__,__DATE__);
2225         WriteServ(user->fd,"004 %s :%s %s iowghraAsORVSxNCWqBzvdHtGI lvhopsmntikrRcaqOALQbSeKVfHGCuzN",user->nick,ServerName,VERSION);
2226         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);
2227         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);
2228         ShowMOTD(user);
2229         FOREACH_MOD OnUserConnect(user);
2230         WriteOpers("*** Client connecting on port %d: %s!%s@%s",user->port,user->nick,user->ident,user->host);
2231         
2232         char buffer[MAXBUF];
2233         snprintf(buffer,MAXBUF,"N %d %s %s %s %s +%s %s :%s",user->age,user->nick,user->host,user->dhost,user->ident,user->modes,ServerName,user->fullname);
2234         NetSendToAll(buffer);
2235 }
2236
2237 void handle_version(char **parameters, int pcnt, userrec *user)
2238 {
2239         char Revision[] = "$Revision$";
2240
2241         char *s1 = Revision;
2242         char *savept;
2243         char *v1 = strtok_r(s1," ",&savept);
2244         s1 = savept;
2245         char *v2 = strtok_r(s1," ",&savept);
2246         s1 = savept;
2247         
2248         WriteServ(user->fd,"351 %s :%s Rev. %s %s :%s (O=%d)",user->nick,VERSION,v2,ServerName,SYSTEM,OPTIMISATION);
2249 }
2250
2251
2252 // calls a handler function for a command
2253
2254 void call_handler(const char* commandname,char **parameters, int pcnt, userrec *user)
2255 {
2256                 for (int i = 0; i < cmdlist.size(); i++)
2257                 {
2258                         if (!strcasecmp(cmdlist[i].command,commandname))
2259                         {
2260                                 if (cmdlist[i].handler_function)
2261                                 {
2262                                         if (pcnt>=cmdlist[i].min_params)
2263                                         {
2264                                                 if (strchr(user->modes,cmdlist[i].flags_needed))
2265                                                 {
2266                                                         cmdlist[i].handler_function(parameters,pcnt,user);
2267                                                 }
2268                                         }
2269                                 }
2270                         }
2271                 }
2272 }
2273
2274 void DoSplitEveryone()
2275 {
2276         bool go_again = true;
2277         while (go_again)
2278         {
2279                 go_again = false;
2280                 for (int i = 0; i < 32; i++)
2281                 {
2282                         if (me[i] != NULL)
2283                         {
2284                                 for (vector<ircd_connector>::iterator j = me[i]->connectors.begin(); j != me[i]->connectors.end(); j++)
2285                                 {
2286                                         if (strcasecmp(j->GetServerName().c_str(),ServerName))
2287                                         {
2288                                                 j->routes.clear();
2289                                                 j->CloseConnection();
2290                                                 me[i]->connectors.erase(j);
2291                                                 go_again = true;
2292                                                 break;
2293                                         }
2294                                 }
2295                         }
2296                 }
2297         }
2298         log(DEBUG,"Removed server. Will remove clients...");
2299         // iterate through the userlist and remove all users on this server.
2300         // because we're dealing with a mesh, we dont have to deal with anything
2301         // "down-route" from this server (nice huh)
2302         go_again = true;
2303         char reason[MAXBUF];
2304         while (go_again)
2305         {
2306                 go_again = false;
2307                 for (user_hash::const_iterator u = clientlist.begin(); u != clientlist.end(); u++)
2308                 {
2309                         if (strcasecmp(u->second->server,ServerName))
2310                         {
2311                                 snprintf(reason,MAXBUF,"%s %s",ServerName,u->second->server);
2312                                 kill_link(u->second,reason);
2313                                 go_again = true;
2314                                 break;
2315                         }
2316                 }
2317         }
2318 }
2319
2320
2321
2322 char islast(const char* s)
2323 {
2324         char c = '`';
2325         for (int j = 0; j < 32; j++)
2326         {
2327                 if (me[j] != NULL)
2328                 {
2329                         for (int k = 0; k < me[j]->connectors.size(); k++)
2330                         {
2331                                 if (strcasecmp(me[j]->connectors[k].GetServerName().c_str(),s))
2332                                 {
2333                                         c = '|';
2334                                 }
2335                                 if (!strcasecmp(me[j]->connectors[k].GetServerName().c_str(),s))
2336                                 {
2337                                         c = '`';
2338                                 }
2339                         }
2340                 }
2341         }
2342         return c;
2343 }
2344
2345 long map_count(const char* s)
2346 {
2347         int c = 0;
2348         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
2349         {
2350                 if ((i->second->fd) && (isnick(i->second->nick)) && (!strcasecmp(i->second->server,s))) c++;
2351         }
2352         return c;
2353 }
2354
2355
2356 void force_nickchange(userrec* user,const char* newnick)
2357 {
2358         char nick[MAXBUF];
2359         strcpy(nick,"");
2360         
2361         if (user)
2362         {
2363                 if (newnick)
2364                 {
2365                         strncpy(nick,newnick,MAXBUF);
2366                 }
2367                 if (user->registered == 7)
2368                 {
2369                         char* pars[1];
2370                         pars[0] = nick;
2371                         handle_nick(pars,1,user);
2372                 }
2373         }
2374 }
2375                                 
2376
2377 int process_parameters(char **command_p,char *parameters)
2378 {
2379         int i = 0;
2380         int j = 0;
2381         int q = 0;
2382         q = strlen(parameters);
2383         if (!q)
2384         {
2385                 /* no parameters, command_p invalid! */
2386                 return 0;
2387         }
2388         if (parameters[0] == ':')
2389         {
2390                 command_p[0] = parameters+1;
2391                 return 1;
2392         }
2393         if (q)
2394         {
2395                 if ((strchr(parameters,' ')==NULL) || (parameters[0] == ':'))
2396                 {
2397                         /* only one parameter */
2398                         command_p[0] = parameters;
2399                         if (parameters[0] == ':')
2400                         {
2401                                 if (strchr(parameters,' ') != NULL)
2402                                 {
2403                                         command_p[0]++;
2404                                 }
2405                         }
2406                         return 1;
2407                 }
2408         }
2409         command_p[j++] = parameters;
2410         for (int i = 0; i <= q; i++)
2411         {
2412                 if (parameters[i] == ' ')
2413                 {
2414                         command_p[j++] = parameters+i+1;
2415                         parameters[i] = '\0';
2416                         if (command_p[j-1][0] == ':')
2417                         {
2418                                 *command_p[j-1]++; /* remove dodgy ":" */
2419                                 break;
2420                                 /* parameter like this marks end of the sequence */
2421                         }
2422                 }
2423         }
2424         return j; /* returns total number of items in the list */
2425 }
2426
2427 void process_command(userrec *user, char* cmd)
2428 {
2429         char *parameters;
2430         char *command;
2431         char *command_p[127];
2432         char p[MAXBUF], temp[MAXBUF];
2433         int i, j, items, cmd_found;
2434
2435         for (int i = 0; i < 127; i++)
2436                 command_p[i] = NULL;
2437
2438         if (!user)
2439         {
2440                 return;
2441         }
2442         if (!cmd)
2443         {
2444                 return;
2445         }
2446         if (!strcmp(cmd,""))
2447         {
2448                 return;
2449         }
2450         
2451         int total_params = 0;
2452         if (strlen(cmd)>2)
2453         {
2454                 for (int q = 0; q < strlen(cmd)-1; q++)
2455                 {
2456                         if ((cmd[q] == ' ') && (cmd[q+1] == ':'))
2457                         {
2458                                 total_params++;
2459                                 // found a 'trailing', we dont count them after this.
2460                                 break;
2461                         }
2462                         if (cmd[q] == ' ')
2463                                 total_params++;
2464                 }
2465         }
2466         
2467         // another phidjit bug...
2468         if (total_params > 126)
2469         {
2470                 kill_link(user,"Protocol violation (1)");
2471                 return;
2472         }
2473         
2474         strcpy(temp,cmd);
2475
2476         std::string tmp = cmd;
2477         for (int i = 0; i <= MODCOUNT; i++)
2478         {
2479                 std::string oldtmp = tmp;
2480                 modules[i]->OnServerRaw(tmp,true);
2481                 if (oldtmp != tmp)
2482                 {
2483                         log(DEBUG,"A Module changed the input string!");
2484                         log(DEBUG,"New string: %s",tmp.c_str());
2485                         log(DEBUG,"Old string: %s",oldtmp.c_str());
2486                         break;
2487                 }
2488         }
2489         strncpy(cmd,tmp.c_str(),MAXBUF);
2490         strcpy(temp,cmd);
2491
2492         if (!strchr(cmd,' '))
2493         {
2494                 /* no parameters, lets skip the formalities and not chop up
2495                  * the string */
2496                 log(DEBUG,"About to preprocess command with no params");
2497                 items = 0;
2498                 command_p[0] = NULL;
2499                 parameters = NULL;
2500                 for (int i = 0; i <= strlen(cmd); i++)
2501                 {
2502                         cmd[i] = toupper(cmd[i]);
2503                 }
2504                 log(DEBUG,"Preprocess done length=%d",strlen(cmd));
2505                 command = cmd;
2506         }
2507         else
2508         {
2509                 strcpy(cmd,"");
2510                 j = 0;
2511                 /* strip out extraneous linefeeds through mirc's crappy pasting (thanks Craig) */
2512                 for (int i = 0; i < strlen(temp); i++)
2513                 {
2514                         if ((temp[i] != 10) && (temp[i] != 13) && (temp[i] != 0) && (temp[i] != 7))
2515                         {
2516                                 cmd[j++] = temp[i];
2517                                 cmd[j] = 0;
2518                         }
2519                 }
2520                 /* split the full string into a command plus parameters */
2521                 parameters = p;
2522                 strcpy(p," ");
2523                 command = cmd;
2524                 if (strchr(cmd,' '))
2525                 {
2526                         for (int i = 0; i <= strlen(cmd); i++)
2527                         {
2528                                 /* capitalise the command ONLY, leave params intact */
2529                                 cmd[i] = toupper(cmd[i]);
2530                                 /* are we nearly there yet?! :P */
2531                                 if (cmd[i] == ' ')
2532                                 {
2533                                         command = cmd;
2534                                         parameters = cmd+i+1;
2535                                         cmd[i] = '\0';
2536                                         break;
2537                                 }
2538                         }
2539                 }
2540                 else
2541                 {
2542                         for (int i = 0; i <= strlen(cmd); i++)
2543                         {
2544                                 cmd[i] = toupper(cmd[i]);
2545                         }
2546                 }
2547
2548         }
2549         cmd_found = 0;
2550         
2551         if (strlen(command)>MAXCOMMAND)
2552         {
2553                 kill_link(user,"Protocol violation (2)");
2554                 return;
2555         }
2556         
2557         for (int x = 0; x < strlen(command); x++)
2558         {
2559                 if (((command[x] < 'A') || (command[x] > 'Z')) && (command[x] != '.'))
2560                 {
2561                         if (((command[x] < '0') || (command[x]> '9')) && (command[x] != '-'))
2562                         {
2563                                 if (!strchr("@!\"$%^&*(){}[]_-=+;:'#~,.<>/?\\|`",command[x]))
2564                                 {
2565                                         kill_link(user,"Protocol violation (3)");
2566                                         return;
2567                                 }
2568                         }
2569                 }
2570         }
2571
2572         for (int i = 0; i != cmdlist.size(); i++)
2573         {
2574                 if (strcmp(cmdlist[i].command,""))
2575                 {
2576                         if (strlen(command)>=(strlen(cmdlist[i].command))) if (!strncmp(command, cmdlist[i].command,MAXCOMMAND))
2577                         {
2578                                 log(DEBUG,"Found matching command");
2579
2580                                 if (parameters)
2581                                 {
2582                                         if (strcmp(parameters,""))
2583                                         {
2584                                                 items = process_parameters(command_p,parameters);
2585                                         }
2586                                         else
2587                                         {
2588                                                 items = 0;
2589                                                 command_p[0] = NULL;
2590                                         }
2591                                 }
2592                                 else
2593                                 {
2594                                         items = 0;
2595                                         command_p[0] = NULL;
2596                                 }
2597                                 
2598                                 if (user)
2599                                 {
2600                                         log(DEBUG,"Processing command");
2601                                         
2602                                         /* activity resets the ping pending timer */
2603                                         user->nping = time(NULL) + 120;
2604                                         if ((items) < cmdlist[i].min_params)
2605                                         {
2606                                                 log(DEBUG,"process_command: not enough parameters: %s %s",user->nick,command);
2607                                                 WriteServ(user->fd,"461 %s %s :Not enough parameters",user->nick,command);
2608                                                 return;
2609                                         }
2610                                         if ((!strchr(user->modes,cmdlist[i].flags_needed)) && (cmdlist[i].flags_needed))
2611                                         {
2612                                                 log(DEBUG,"process_command: permission denied: %s %s",user->nick,command);
2613                                                 WriteServ(user->fd,"481 %s :Permission Denied- You do not have the required operator privilages",user->nick);
2614                                                 cmd_found = 1;
2615                                                 return;
2616                                         }
2617                                         /* if the command isnt USER, PASS, or NICK, and nick is empty,
2618                                          * deny command! */
2619                                         if ((strncmp(command,"USER",4)) && (strncmp(command,"NICK",4)) && (strncmp(command,"PASS",4)))
2620                                         {
2621                                                 if ((!isnick(user->nick)) || (user->registered != 7))
2622                                                 {
2623                                                         log(DEBUG,"process_command: not registered: %s %s",user->nick,command);
2624                                                         WriteServ(user->fd,"451 %s :You have not registered",command);
2625                                                         return;
2626                                                 }
2627                                         }
2628                                         if ((user->registered == 7) || (!strcmp(command,"USER")) || (!strcmp(command,"NICK")) || (!strcmp(command,"PASS")))
2629                                         {
2630                                                 log(DEBUG,"process_command: handler: %s %s %d",user->nick,command,items);
2631                                                 if (cmdlist[i].handler_function)
2632                                                 {
2633                                                         /* ikky /stats counters */
2634                                                         if (temp)
2635                                                         {
2636                                                                 if (user)
2637                                                                 {
2638                                                                         user->bytes_in += strlen(temp);
2639                                                                         user->cmds_in++;
2640                                                                 }
2641                                                                 cmdlist[i].use_count++;
2642                                                                 cmdlist[i].total_bytes+=strlen(temp);
2643                                                         }
2644
2645                                                         /* WARNING: nothing may come after the
2646                                                          * command handler call, as the handler
2647                                                          * may free the user structure! */
2648
2649                                                         cmdlist[i].handler_function(command_p,items,user);
2650                                                 }
2651                                                 return;
2652                                         }
2653                                         else
2654                                         {
2655                                                 log(DEBUG,"process_command: not registered: %s %s",user->nick,command);
2656                                                 WriteServ(user->fd,"451 %s :You have not registered",command);
2657                                                 return;
2658                                         }
2659                                 }
2660                                 cmd_found = 1;
2661                         }
2662                 }
2663         }
2664         if ((!cmd_found) && (user))
2665         {
2666                 log(DEBUG,"process_command: not in table: %s %s",user->nick,command);
2667                 WriteServ(user->fd,"421 %s %s :Unknown command",user->nick,command);
2668         }
2669 }
2670
2671
2672 void createcommand(char* cmd, handlerfunc f, char flags, int minparams)
2673 {
2674         command_t comm;
2675         /* create the command and push it onto the table */     
2676         strcpy(comm.command,cmd);
2677         comm.handler_function = f;
2678         comm.flags_needed = flags;
2679         comm.min_params = minparams;
2680         comm.use_count = 0;
2681         comm.total_bytes = 0;
2682         cmdlist.push_back(comm);
2683         log(DEBUG,"Added command %s (%d parameters)",cmd,minparams);
2684 }
2685
2686 void SetupCommandTable(void)
2687 {
2688         createcommand("USER",handle_user,0,4);
2689         createcommand("NICK",handle_nick,0,1);
2690         createcommand("QUIT",handle_quit,0,0);
2691         createcommand("VERSION",handle_version,0,0);
2692         createcommand("PING",handle_ping,0,1);
2693         createcommand("PONG",handle_pong,0,1);
2694         createcommand("ADMIN",handle_admin,0,0);
2695         createcommand("PRIVMSG",handle_privmsg,0,2);
2696         createcommand("INFO",handle_info,0,0);
2697         createcommand("TIME",handle_time,0,0);
2698         createcommand("WHOIS",handle_whois,0,1);
2699         createcommand("WALLOPS",handle_wallops,'o',1);
2700         createcommand("NOTICE",handle_notice,0,2);
2701         createcommand("JOIN",handle_join,0,1);
2702         createcommand("NAMES",handle_names,0,1);
2703         createcommand("PART",handle_part,0,1);
2704         createcommand("KICK",handle_kick,0,2);
2705         createcommand("MODE",handle_mode,0,1);
2706         createcommand("TOPIC",handle_topic,0,1);
2707         createcommand("WHO",handle_who,0,1);
2708         createcommand("MOTD",handle_motd,0,0);
2709         createcommand("RULES",handle_rules,0,0);
2710         createcommand("OPER",handle_oper,0,2);
2711         createcommand("LIST",handle_list,0,0);
2712         createcommand("DIE",handle_die,'o',1);
2713         createcommand("RESTART",handle_restart,'o',1);
2714         createcommand("KILL",handle_kill,'o',2);
2715         createcommand("REHASH",handle_rehash,'o',0);
2716         createcommand("LUSERS",handle_lusers,0,0);
2717         createcommand("STATS",handle_stats,0,1);
2718         createcommand("USERHOST",handle_userhost,0,1);
2719         createcommand("AWAY",handle_away,0,0);
2720         createcommand("ISON",handle_ison,0,0);
2721         createcommand("SUMMON",handle_summon,0,0);
2722         createcommand("USERS",handle_users,0,0);
2723         createcommand("INVITE",handle_invite,0,2);
2724         createcommand("PASS",handle_pass,0,1);
2725         createcommand("TRACE",handle_trace,'o',0);
2726         createcommand("WHOWAS",handle_whowas,0,1);
2727         createcommand("CONNECT",handle_connect,'o',1);
2728         createcommand("SQUIT",handle_squit,'o',0);
2729         createcommand("MODULES",handle_modules,'o',0);
2730         createcommand("LINKS",handle_links,0,0);
2731         createcommand("MAP",handle_map,0,0);
2732 }
2733
2734 void process_buffer(const char* cmdbuf,userrec *user)
2735 {
2736         if (!user)
2737         {
2738                 log(DEFAULT,"*** BUG *** process_buffer was given an invalid parameter");
2739                 return;
2740         }
2741         char cmd[MAXBUF];
2742         int i;
2743         if (!cmdbuf)
2744         {
2745                 log(DEFAULT,"*** BUG *** process_buffer was given an invalid parameter");
2746                 return;
2747         }
2748         if (!strcmp(cmdbuf,""))
2749         {
2750                 return;
2751         }
2752         strncpy(cmd,cmdbuf,MAXBUF);
2753         if (!strcmp(cmd,""))
2754         {
2755                 return;
2756         }
2757         if ((cmd[strlen(cmd)-1] == 13) || (cmd[strlen(cmd)-1] == 10))
2758         {
2759                 cmd[strlen(cmd)-1] = '\0';
2760         }
2761         if ((cmd[strlen(cmd)-1] == 13) || (cmd[strlen(cmd)-1] == 10))
2762         {
2763                 cmd[strlen(cmd)-1] = '\0';
2764         }
2765         if (!strcmp(cmd,""))
2766         {
2767                 return;
2768         }
2769         log(DEBUG,"InspIRCd: processing: %s %s",user->nick,cmd);
2770         tidystring(cmd);
2771         if ((user) && (cmd))
2772         {
2773                 process_command(user,cmd);
2774         }
2775 }
2776
2777 void DoSync(serverrec* serv, char* udp_host)
2778 {
2779         char data[MAXBUF];
2780         // send start of sync marker: Y <timestamp>
2781         // at this point the ircd receiving it starts broadcasting this netburst to all ircds
2782         // except the ones its receiving it from.
2783         snprintf(data,MAXBUF,"Y %d",time(NULL));
2784         serv->SendPacket(data,udp_host);
2785         // send users and channels
2786         for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
2787         {
2788                 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);
2789                 serv->SendPacket(data,udp_host);
2790                 if (strcmp(chlist(u->second),""))
2791                 {
2792                         snprintf(data,MAXBUF,"J %s %s",u->second->nick,chlist(u->second));
2793                         serv->SendPacket(data,udp_host);
2794                 }
2795         }
2796         // send channel modes, topics etc...
2797         for (chan_hash::iterator c = chanlist.begin(); c != chanlist.end(); c++)
2798         {
2799                 snprintf(data,MAXBUF,"M %s +%s",c->second->name,chanmodes(c->second));
2800                 serv->SendPacket(data,udp_host);
2801                 if (strcmp(c->second->topic,""))
2802                 {
2803                         snprintf(data,MAXBUF,"T %d %s %s :%s",c->second->topicset,c->second->setby,c->second->name,c->second->topic);
2804                         serv->SendPacket(data,udp_host);
2805                 }
2806                 // send current banlist
2807                 
2808                 for (BanList::iterator b = c->second->bans.begin(); b != c->second->bans.end(); b++)
2809                 {
2810                         snprintf(data,MAXBUF,"M %s +b %s",b->set_time,c->second->name,b->data);
2811                         serv->SendPacket(data,udp_host);
2812                 }
2813         }
2814         // send end of sync marker: E <timestamp>
2815         snprintf(data,MAXBUF,"F %d",time(NULL));
2816         serv->SendPacket(data,udp_host);
2817         // ircd sends its serverlist after the end of sync here
2818 }
2819
2820
2821 void handle_V(char token,char* params,serverrec* source,serverrec* reply, char* udp_host)
2822 {
2823         char* src = strtok(params," ");
2824         char* dest = strtok(NULL," :");
2825         char* text = strtok(NULL,"\r\n");
2826         text++;
2827         
2828         userrec* user = Find(src);
2829         if (user)
2830         {
2831                 userrec* dst = Find(dest);
2832                 
2833                 if (dst)
2834                 {
2835                         WriteTo(user, dst, "NOTICE %s :%s", dst->nick, text);
2836                 }
2837                 else
2838                 {
2839                         chanrec* d = FindChan(dest);
2840                         if (d)
2841                         {
2842                                 ChanExceptSender(d, user, "NOTICE %s :%s", d->name, text);
2843                         }
2844                 }
2845         }
2846         
2847 }
2848
2849
2850 void handle_P(char token,char* params,serverrec* source,serverrec* reply, char* udp_host)
2851 {
2852         char* src = strtok(params," ");
2853         char* dest = strtok(NULL," :");
2854         char* text = strtok(NULL,"\r\n");
2855         text++;
2856         
2857         userrec* user = Find(src);
2858         if (user)
2859         {
2860                 userrec* dst = Find(dest);
2861                 
2862                 if (dst)
2863                 {
2864                         WriteTo(user, dst, "PRIVMSG %s :%s", dst->nick, text);
2865                 }
2866                 else
2867                 {
2868                         chanrec* d = FindChan(dest);
2869                         if (d)
2870                         {
2871                                 ChanExceptSender(d, user, "PRIVMSG %s :%s", d->name, text);
2872                         }
2873                 }
2874         }
2875         
2876 }
2877
2878 void handle_i(char token,char* params,serverrec* source,serverrec* reply, char* udp_host)
2879 {
2880         char* nick = strtok(params," ");
2881         char* from = strtok(NULL," ");
2882         char* channel = strtok(NULL," ");
2883         userrec* u = Find(nick);
2884         userrec* user = Find(from);
2885         chanrec* c = FindChan(channel);
2886         if ((c) && (u) && (user))
2887         {
2888                 u->InviteTo(c->name);
2889                 WriteFrom(u->fd,user,"INVITE %s :%s",u->nick,c->name);
2890         }
2891 }
2892
2893 void handle_t(char token,char* params,serverrec* source,serverrec* reply, char* udp_host)
2894 {
2895         char* setby = strtok(params," ");
2896         char* channel = strtok(NULL," :");
2897         char* topic = strtok(NULL,"\r\n");
2898         topic++;
2899         userrec* u = Find(setby);
2900         chanrec* c = FindChan(channel);
2901         if ((c) && (u))
2902         {
2903                 WriteChannelLocal(c,u,"TOPIC %s :%s",c->name,topic);
2904                 strncpy(c->topic,topic,MAXTOPIC);
2905                 strncpy(c->setby,u->nick,NICKMAX);
2906         }       
2907 }
2908         
2909
2910 void handle_T(char token,char* params,serverrec* source,serverrec* reply, char* udp_host)
2911 {
2912         char* tm = strtok(params," ");
2913         char* setby = strtok(NULL," ");
2914         char* channel = strtok(NULL," :");
2915         char* topic = strtok(NULL,"\r\n");
2916         topic++;
2917         time_t TS = atoi(tm);
2918         chanrec* c = FindChan(channel);
2919         if (c)
2920         {
2921                 // in the case of topics and TS, the *NEWER* 
2922                 if (TS <= c->topicset)
2923                 {
2924                         WriteChannelLocal(c,NULL,"TOPIC %s :%s",c->name,topic);
2925                         strncpy(c->topic,topic,MAXTOPIC);
2926                         strncpy(c->setby,setby,NICKMAX);
2927                 }
2928         }       
2929 }
2930         
2931 void handle_M(char token,char* params,serverrec* source,serverrec* reply, char* udp_host)
2932 {
2933         char* pars[128];
2934         char original[MAXBUF],target[MAXBUF];
2935         strncpy(original,params,MAXBUF);
2936         int index = 0;
2937         char* parameter = strtok(params," ");
2938         strncpy(target,parameter,MAXBUF);
2939         while (parameter)
2940         {
2941                 pars[index++] = parameter;
2942                 parameter = strtok(NULL," ");
2943         }
2944         merge_mode(pars,index);
2945         if (FindChan(target))
2946         {
2947                 WriteChannelLocal(FindChan(target), NULL, "MODE %s",original);
2948         }
2949         if (Find(target))
2950         {
2951                 WriteTo(NULL,Find(target),"MODE %s",original);
2952         }
2953 }
2954
2955 // m is modes set by users only (not servers) valid targets are channels or users.
2956
2957 void handle_m(char token,char* params,serverrec* source,serverrec* reply, char* udp_host)
2958 {
2959         // m blah #chatspike +b *!test@*4
2960         char* pars[128];
2961         char original[MAXBUF];
2962         strncpy(original,params,MAXBUF);
2963         
2964         if (!strchr(params,' '))
2965         {
2966                 WriteOpers("WARNING! 'm' token in data stream without any parameters! Something fishy is going on!");
2967                 return;
2968         }
2969         
2970         int index = 0;
2971         
2972         char* src = strtok(params," ");
2973         userrec* user = Find(src);
2974         
2975         if (user)
2976         {
2977                 log(DEBUG,"Found user: %s",user->nick);
2978                 char* parameter = strtok(NULL," ");
2979                 while (parameter)
2980                 {
2981                         pars[index++] = parameter;
2982                         parameter = strtok(NULL," ");
2983                 }
2984                 
2985                 log(DEBUG,"Calling merge_mode2");
2986                 merge_mode2(pars,index,user);
2987         }
2988 }
2989
2990
2991 void handle_L(char token,char* params,serverrec* source,serverrec* reply, char* udp_host)
2992 {
2993         char* nick = strtok(params," ");
2994         char* channel = strtok(NULL," :");
2995         char* reason = strtok(NULL,"\r\n");
2996         userrec* user = Find(nick);
2997         reason++;
2998         if (user)
2999         {
3000                 if (strcmp(reason,""))
3001                 {
3002                         del_channel(user,channel,reason,true);
3003                 }
3004                 else
3005                 {
3006                         del_channel(user,channel,NULL,true);
3007                 }
3008         }
3009 }
3010
3011 void handle_K(char token,char* params,serverrec* source,serverrec* reply, char* udp_host)
3012 {
3013         char* src = strtok(params," ");
3014         char* nick = strtok(NULL," :");
3015         char* reason = strtok(NULL,"\r\n");
3016         char kreason[MAXBUF];
3017         reason++;
3018
3019         userrec* u = Find(nick);
3020         userrec* user = Find(src);
3021         
3022         if ((user) && (u))
3023         {
3024                 WriteTo(user, u, "KILL %s :%s!%s!%s!%s (%s)", u->nick, source->name, ServerName, user->dhost,user->nick,reason);
3025                 WriteOpers("*** Remote kill from %s by %s: %s!%s@%s (%s)",source->name,user->nick,u->nick,u->ident,u->host,reason);
3026                 snprintf(kreason,MAXBUF,"[%s] Killed (%s (%s))",source->name,user->nick,reason);
3027                 kill_link(u,kreason);
3028         }
3029 }
3030
3031 void handle_Q(char token,char* params,serverrec* source,serverrec* reply, char* udp_host)
3032 {
3033         char* nick = strtok(params," :");
3034         char* reason = strtok(NULL,"\r\n");
3035         reason++;
3036
3037         userrec* user = Find(nick);
3038         
3039         if (user)
3040         {
3041                 if (strlen(reason)>MAXQUIT)
3042                 {
3043                         reason[MAXQUIT-1] = '\0';
3044                 }
3045
3046
3047                 WriteCommonExcept(user,"QUIT :%s",reason);
3048
3049                 user_hash::iterator iter = clientlist.find(user->nick);
3050         
3051                 if (iter != clientlist.end())
3052                 {
3053                         log(DEBUG,"deleting user hash value %d",iter->second);
3054                         if ((iter->second) && (user->registered == 7)) {
3055                                 delete iter->second;
3056                         }
3057                         clientlist.erase(iter);
3058                 }
3059
3060                 purge_empty_chans();
3061         }
3062 }
3063
3064 void handle_n(char token,char* params,serverrec* source,serverrec* reply, char* udp_host)
3065 {
3066         char* oldnick = strtok(params," ");
3067         char* newnick = strtok(NULL," ");
3068         
3069         userrec* user = Find(oldnick);
3070         
3071         if (user)
3072         {
3073                 WriteCommon(user,"NICK %s",newnick);
3074                 user = ReHashNick(user->nick, newnick);
3075                 if (!user) return;
3076                 if (!user->nick) return;
3077                 strncpy(user->nick, newnick,NICKMAX);
3078                 log(DEBUG,"new nick set: %s",user->nick);
3079         }
3080 }
3081
3082 // k <SOURCE> <DEST> <CHANNEL> :<REASON>
3083 void handle_k(char token,char* params,serverrec* source,serverrec* reply, char* udp_host)
3084 {
3085         char* src = strtok(params," ");
3086         char* dest = strtok(NULL," ");
3087         char* channel = strtok(NULL," :");
3088         char* reason = strtok(NULL,"\r\n");
3089         reason++;
3090         userrec* s = Find(src);
3091         userrec* d = Find(dest);
3092         chanrec* c = FindChan(channel);
3093         if ((s) && (d) && (c))
3094         {
3095                 kick_channel(s,d,c,reason);
3096         }
3097 }
3098
3099 void handle_AT(char token,char* params,serverrec* source,serverrec* reply, char* udp_host)
3100 {
3101         char* who = strtok(params," :");
3102         char* text = strtok(NULL,"\r\n");
3103         text++;
3104         userrec* s = Find(who);
3105         if (s)
3106         {
3107                 WriteWallOps(s,true,text);
3108         }
3109 }
3110
3111
3112 void handle_N(char token,char* params,serverrec* source,serverrec* reply, char* udp_host)
3113 {
3114         char* tm = strtok(params," ");
3115         char* nick = strtok(NULL," ");
3116         char* host = strtok(NULL," ");
3117         char* dhost = strtok(NULL," ");
3118         char* ident = strtok(NULL," ");
3119         char* modes = strtok(NULL," ");
3120         char* server = strtok(NULL," :");
3121         char* gecos = strtok(NULL,"\r\n");
3122         gecos++;
3123         modes++;
3124         time_t TS = atoi(tm);
3125         user_hash::iterator iter = clientlist.find(nick);
3126         if (iter != clientlist.end())
3127         {
3128                 // nick collision
3129                 WriteOpers("Nickname collision: %s@%s != %s@%s",nick,server,iter->second->nick,iter->second->server);
3130                 char str[MAXBUF];
3131                 snprintf(str,MAXBUF,"Killed (Nick Collision (%s@%s < %s@%s))",nick,server,iter->second->nick,iter->second->server);
3132                 WriteServ(iter->second->fd, "KILL %s :%s",iter->second->nick,str);
3133                 kill_link(iter->second,str);
3134         }
3135         clientlist[nick] = new userrec();
3136         // remote users have an fd of -1. This is so that our Write abstraction
3137         // routines know to route any messages to this record away to whatever server
3138         // theyre on.
3139         clientlist[nick]->fd = -1;
3140         strncpy(clientlist[nick]->nick, nick,NICKMAX);
3141         strncpy(clientlist[nick]->host, host,160);
3142         strncpy(clientlist[nick]->dhost, dhost,160);
3143         strncpy(clientlist[nick]->server, server,256);
3144         strncpy(clientlist[nick]->ident, ident,10); // +1 char to compensate for tilde
3145         strncpy(clientlist[nick]->fullname, gecos,128);
3146         clientlist[nick]->signon = TS;
3147         clientlist[nick]->nping = 0; // this is ignored for a remote user anyway.
3148         clientlist[nick]->lastping = 1;
3149         clientlist[nick]->port = 0; // so is this...
3150         clientlist[nick]->registered = 7; // this however we need to set for them to receive messages and appear online
3151         clientlist[nick]->idle_lastmsg = time(NULL); // this is unrealiable and wont actually be used locally
3152         for (int i = 0; i < MAXCHANS; i++)
3153         {
3154                 clientlist[nick]->chans[i].channel = NULL;
3155                 clientlist[nick]->chans[i].uc_modes = 0;
3156         }
3157 }
3158
3159 void handle_F(char token,char* params,serverrec* source,serverrec* reply, char* udp_host)
3160 {
3161         long tdiff = time(NULL) - atoi(params);
3162         if (tdiff)
3163                 WriteOpers("TS split for %s -> %s: %d",source->name,reply->name,tdiff);
3164 }
3165
3166 void handle_a(char token,char* params,serverrec* source,serverrec* reply, char* udp_host)
3167 {
3168         char* nick = strtok(params," :");
3169         char* gecos = strtok(NULL,"\r\n");
3170         
3171         userrec* user = Find(nick);
3172
3173         if (user)
3174                 strncpy(user->fullname,gecos,MAXBUF);
3175 }
3176
3177 void handle_b(char token,char* params,serverrec* source,serverrec* reply, char* udp_host)
3178 {
3179         char* nick = strtok(params," ");
3180         char* host = strtok(NULL," ");
3181         
3182         userrec* user = Find(nick);
3183
3184         if (user)
3185                 strncpy(user->dhost,host,160);
3186 }
3187
3188 void handle_plus(char token,char* params,serverrec* source,serverrec* reply, char* udp_host)
3189 {
3190         // %s %s %d %d
3191         // + test3.chatspike.net 7010 -2016508415
3192         char* servername = strtok(params," ");
3193         char* ipaddr = strtok(NULL," ");
3194         char* ipport = strtok(NULL," ");
3195         char* cookie = strtok(NULL," ");
3196         log(DEBUG,"*** Connecting back to %s:%d",ipaddr,atoi(ipport));
3197
3198
3199         bool conn_already = false;
3200         for (int i = 0; i < 32; i++)
3201         {
3202                 if (me[i] != NULL)
3203                 {
3204                         for (int j = 0; j < me[i]->connectors.size(); j++)
3205                         {
3206                                 if (!strcasecmp(me[i]->connectors[j].GetServerName().c_str(),servername))
3207                                 {
3208                                         if (me[i]->connectors[j].GetServerPort() == atoi(ipport))
3209                                         {
3210                                                 log(DEBUG,"Already got a connection to %s:%d, ignoring +",ipaddr,atoi(ipport));
3211                                                 conn_already = true;
3212                                         }
3213                                 }
3214                         }
3215                 }
3216         }
3217         if (!conn_already)
3218                 me[defaultRoute]->MeshCookie(ipaddr,atoi(ipport),atoi(cookie),servername);
3219 }
3220
3221 void handle_R(char token,char* params,serverrec* source,serverrec* reply, char* udp_host)
3222 {
3223         char* server = strtok(params," ");
3224         char* data = strtok(NULL,"\r\n");
3225         log(DEBUG,"Forwarded packet '%s' to '%s'",data,server);
3226         NetSendToOne(server,data);
3227 }
3228
3229 void handle_J(char token,char* params,serverrec* source,serverrec* reply, char* udp_host)
3230 {
3231         // IMPORTANT NOTE
3232         // The J token currently has no timestamp - this needs looking at
3233         // because it will allow splitriding.
3234         char* nick = strtok(params," ");
3235         char* channel = strtok(NULL," ");
3236         userrec* user = Find(nick);
3237         while (channel)
3238         {
3239                 if ((user != NULL) && (strcmp(channel,"")))
3240                 {
3241                         char privilage = '\0';
3242                         if (channel[0] != '#')
3243                         {
3244                                 privilage = channel[0];
3245                                 channel++;
3246                         }
3247                         add_channel(user,channel,"",true);
3248
3249                         // now work out the privilages they should have on each channel
3250                         // and send the appropriate servermodes.
3251                         for (int i = 0; i != MAXCHANS; i++)
3252                         {
3253                                 if (user->chans[i].channel)
3254                                 {
3255                                         if (!strcasecmp(user->chans[i].channel->name,channel))
3256                                         {
3257                                                 if (privilage == '@')
3258                                                 {
3259                                                         user->chans[i].uc_modes = user->chans[i].uc_modes | UCMODE_OP;
3260                                                         WriteChannelLocal(user->chans[i].channel, NULL, "MODE %s +o %s",channel,user->nick);
3261                                                 }
3262                                                 if (privilage == '%')
3263                                                 {
3264                                                         user->chans[i].uc_modes = user->chans[i].uc_modes | UCMODE_HOP;
3265                                                         WriteChannelLocal(user->chans[i].channel, NULL, "MODE %s +h %s",channel,user->nick);
3266                                                 }
3267                                                 if (privilage == '+')
3268                                                 {
3269                                                         user->chans[i].uc_modes = user->chans[i].uc_modes | UCMODE_VOICE;
3270                                                         WriteChannelLocal(user->chans[i].channel, NULL, "MODE %s +v %s",channel,user->nick);
3271                                                 }
3272                                         }
3273                                 }
3274                         }
3275
3276                 }
3277                 channel = strtok(NULL," ");
3278         }
3279 }
3280
3281 void NetSendMyRoutingTable()
3282 {
3283         // send out a line saying what is reachable to us.
3284         // E.g. if A is linked to B C and D, send out:
3285         // $ A B C D
3286         // if its only linked to B and D send out:
3287         // $ A B D
3288         // if it has no links, dont even send out the line at all.
3289         char buffer[MAXBUF];
3290         sprintf(buffer,"$ %s",ServerName);
3291         bool sendit = false;
3292         for (int i = 0; i < 32; i++)
3293         {
3294                 if (me[i] != NULL)
3295                 {
3296                         for (int j = 0; j < me[i]->connectors.size(); j++)
3297                         {
3298                                 if (me[i]->connectors[j].GetState() != STATE_DISCONNECTED)
3299                                 {
3300                                         strncat(buffer," ",MAXBUF);
3301                                         strncat(buffer,me[i]->connectors[j].GetServerName().c_str(),MAXBUF);
3302                                         sendit = true;
3303                                 }
3304                         }
3305                 }
3306         }
3307         if (sendit)
3308                 NetSendToAll(buffer);
3309 }
3310
3311 void handle_dollar(char token,char* params,serverrec* source,serverrec* reply, char* udp_host)
3312 {
3313         log(DEBUG,"Storing routing table...");
3314         char* sourceserver = strtok(params," ");
3315         char* server = strtok(NULL," ");
3316         for (int i = 0; i < 32; i++)
3317         {
3318                 if (me[i] != NULL)
3319                 {
3320                         for (int j = 0; j < me[i]->connectors.size(); j++)
3321                         {
3322                                 if (!strcasecmp(me[i]->connectors[j].GetServerName().c_str(),sourceserver))
3323                                 {
3324                                         me[i]->connectors[j].routes.clear();
3325                                         log(DEBUG,"Found entry for source server.");
3326                                         while (server)
3327                                         {
3328                                                 // store each route
3329                                                 me[i]->connectors[j].routes.push_back(server);
3330                                                 log(DEBUG,"*** Stored route: %s -> %s -> %s",ServerName,sourceserver,server);
3331                                                 server = strtok(NULL," ");
3332                                         }
3333                                         return;
3334                                 }
3335                         }
3336                 }
3337         }
3338         log(DEBUG,"Warning! routing table received from nonexistent server!");
3339 }
3340
3341
3342 void DoSplit(const char* params)
3343 {
3344         bool go_again = true;
3345         while (go_again)
3346         {
3347                 go_again = false;
3348                 for (int i = 0; i < 32; i++)
3349                 {
3350                         if (me[i] != NULL)
3351                         {
3352                                 for (vector<ircd_connector>::iterator j = me[i]->connectors.begin(); j != me[i]->connectors.end(); j++)
3353                                 {
3354                                         if (!strcasecmp(j->GetServerName().c_str(),params))
3355                                         {
3356                                                 j->routes.clear();
3357                                                 j->CloseConnection();
3358                                                 me[i]->connectors.erase(j);
3359                                                 go_again = true;
3360                                                 break;
3361                                         }
3362                                 }
3363                         }
3364                 }
3365         }
3366         log(DEBUG,"Removed server. Will remove clients...");
3367         // iterate through the userlist and remove all users on this server.
3368         // because we're dealing with a mesh, we dont have to deal with anything
3369         // "down-route" from this server (nice huh)
3370         go_again = true;
3371         char reason[MAXBUF];
3372         snprintf(reason,MAXBUF,"%s %s",ServerName,params);
3373         while (go_again)
3374         {
3375                 go_again = false;
3376                 for (user_hash::const_iterator u = clientlist.begin(); u != clientlist.end(); u++)
3377                 {
3378                         if (!strcasecmp(u->second->server,params))
3379                         {
3380                                 kill_link(u->second,reason);
3381                                 go_again = true;
3382                                 break;
3383                         }
3384                 }
3385         }
3386 }
3387
3388 // removes a server. Will NOT remove its users!
3389
3390 void RemoveServer(const char* name)
3391 {
3392         bool go_again = true;
3393         while (go_again)
3394         {
3395                 go_again = false;
3396                 for (int i = 0; i < 32; i++)
3397                 {
3398                         if (me[i] != NULL)
3399                         {
3400                                 for (vector<ircd_connector>::iterator j = me[i]->connectors.begin(); j != me[i]->connectors.end(); j++)
3401                                 {
3402                                         if (!strcasecmp(j->GetServerName().c_str(),name))
3403                                         {
3404                                                 j->routes.clear();
3405                                                 j->CloseConnection();
3406                                                 me[i]->connectors.erase(j);
3407                                                 go_again = true;
3408                                                 break;
3409                                         }
3410                                 }
3411                         }
3412                 }
3413         }
3414 }
3415
3416 void handle_amp(char token,char* params,serverrec* source,serverrec* reply, char* udp_host)
3417 {
3418         log(DEBUG,"Netsplit! %s split from mesh, removing!",params);
3419         bool go_again = true;
3420         while (go_again)
3421         {
3422                 go_again = false;
3423                 for (int i = 0; i < 32; i++)
3424                 {
3425                         if (me[i] != NULL)
3426                         {
3427                                 for (vector<ircd_connector>::iterator j = me[i]->connectors.begin(); j != me[i]->connectors.end(); j++)
3428                                 {
3429                                         if (!strcasecmp(j->GetServerName().c_str(),params))
3430                                         {
3431                                                 j->routes.clear();
3432                                                 j->CloseConnection();
3433                                                 me[i]->connectors.erase(j);
3434                                                 go_again = true;
3435                                                 break;
3436                                         }
3437                                 }
3438                         }
3439                 }
3440         }
3441         log(DEBUG,"Removed server. Will remove clients...");
3442         // iterate through the userlist and remove all users on this server.
3443         // because we're dealing with a mesh, we dont have to deal with anything
3444         // "down-route" from this server (nice huh)
3445         go_again = true;
3446         char reason[MAXBUF];
3447         snprintf(reason,MAXBUF,"%s %s",ServerName,params);
3448         while (go_again)
3449         {
3450                 go_again = false;
3451                 for (user_hash::const_iterator u = clientlist.begin(); u != clientlist.end(); u++)
3452                 {
3453                         if (!strcasecmp(u->second->server,params))
3454                         {
3455                                 kill_link(u->second,reason);
3456                                 go_again = true;
3457                                 break;
3458                         }
3459                 }
3460         }
3461 }
3462
3463 long authcookie;
3464
3465
3466 void process_restricted_commands(char token,char* params,serverrec* source,serverrec* reply, char* udp_host,char* ipaddr,int port)
3467 {
3468         char buffer[MAXBUF];
3469
3470         switch(token)
3471         {
3472                 // Y <TS>
3473                 // start netburst
3474                 case 'Y':
3475                         nb_start = time(NULL);
3476                         WriteOpers("Server %s is starting netburst.",udp_host);
3477                         // now broadcast this new servers address out to all servers that are linked to us,
3478                         // except the newcomer. They'll all attempt to connect back to it.
3479                         authcookie = rand()*rand();
3480                         snprintf(buffer,MAXBUF,"~ %d",authcookie);
3481                         NetSendToAll(buffer);
3482                 break;
3483                 // ~
3484                 // Store authcookie
3485                 // once stored, this authcookie permits other servers to log in
3486                 // without user or password, using it.
3487                 case '~':
3488                         auth_cookies.push_back(atoi(params));
3489                         log(DEBUG,"*** Stored auth cookie, will permit servers with auth-cookie %d",atoi(params));
3490                 break;
3491                 // connect back to a server using an authcookie
3492                 case '+':
3493                         handle_plus(token,params,source,reply,udp_host);
3494                 break;
3495                 // routing table
3496                 case '$':
3497                         handle_dollar(token,params,source,reply,udp_host);
3498                 break;
3499                 // node unreachable - we cant route to a server, sooooo we slit it off.
3500                 // servers can generate these for themselves for an squit.
3501                 case '&':
3502                         handle_amp(token,params,source,reply,udp_host);
3503                 break;
3504                 // R <server> <data>
3505                 // redirect token, send all of <data> along to the given 
3506                 // server as this server has been found to still have a route to it
3507                 case 'R':
3508                         handle_R(token,params,source,reply,udp_host);
3509                 break;
3510                 // ?
3511                 // ping
3512                 case '?':
3513                         reply->SendPacket("!",udp_host);
3514                 break;
3515                 // ?
3516                 // pong
3517                 case '!':
3518                 break;
3519                 // *
3520                 // no operation
3521                 case '*':
3522                 break;
3523                 // N <TS> <NICK> <HOST> <DHOST> <IDENT> <MODES> <SERVER> :<GECOS>
3524                 // introduce remote client
3525                 case 'N':
3526                         handle_N(token,params,source,reply,udp_host);
3527                 break;
3528                 // a <NICK> :<GECOS>
3529                 // change GECOS (SETNAME)
3530                 case 'a':
3531                         handle_a(token,params,source,reply,udp_host);
3532                 break;
3533                 // b <NICK> :<HOST>
3534                 // change displayed host (SETHOST)
3535                 case 'b':
3536                         handle_b(token,params,source,reply,udp_host);
3537                 break;
3538                 // t <NICK> <CHANNEL> :<TOPIC>
3539                 // change a channel topic
3540                 case 't':
3541                         handle_t(token,params,source,reply,udp_host);
3542                 break;
3543                 // i <NICK> <CHANNEL>
3544                 // invite a user to a channel
3545                 case 'i':
3546                         handle_i(token,params,source,reply,udp_host);
3547                 break;
3548                 // k <SOURCE> <DEST> <CHANNEL> :<REASON>
3549                 // kick a user from a channel
3550                 case 'k':
3551                         handle_k(token,params,source,reply,udp_host);
3552                 break;
3553                 // n <NICK> <NEWNICK>
3554                 // change nickname of client -- a server should only be able to
3555                 // change the nicknames of clients that reside on it unless
3556                 // they are ulined.
3557                 case 'n':
3558                         handle_n(token,params,source,reply,udp_host);
3559                 break;
3560                 // J <NICK> <CHANLIST>
3561                 // Join user to channel list, merge channel permissions
3562                 case 'J':
3563                         handle_J(token,params,source,reply,udp_host);
3564                 break;
3565                 // T <TS> <CHANNEL> <TOPICSETTER> :<TOPIC>
3566                 // change channel topic (netburst only)
3567                 case 'T':
3568                         handle_T(token,params,source,reply,udp_host);
3569                 break;
3570                 // M <TARGET> <MODES> [MODE-PARAMETERS]
3571                 // Server setting modes on an object
3572                 case 'M':
3573                         handle_M(token,params,source,reply,udp_host);
3574                 break;
3575                 // m <SOURCE> <TARGET> <MODES> [MODE-PARAMETERS]
3576                 // User setting modes on an object
3577                 case 'm':
3578                         handle_m(token,params,source,reply,udp_host);
3579                 break;
3580                 // P <SOURCE> <TARGET> :<TEXT>
3581                 // Send a private/channel message
3582                 case 'P':
3583                         handle_P(token,params,source,reply,udp_host);
3584                 break;
3585                 // V <SOURCE> <TARGET> :<TEXT>
3586                 // Send a private/channel notice
3587                 case 'V':
3588                         handle_V(token,params,source,reply,udp_host);
3589                 break;
3590                 // L <SOURCE> <CHANNEL> :<REASON>
3591                 // User parting a channel
3592                 case 'L':
3593                         handle_L(token,params,source,reply,udp_host);
3594                 break;
3595                 // Q <SOURCE> :<REASON>
3596                 // user quitting
3597                 case 'Q':
3598                         handle_Q(token,params,source,reply,udp_host);
3599                 break;
3600                 // K <SOURCE> <DEST> :<REASON>
3601                 // remote kill
3602                 case 'K':
3603                         handle_K(token,params,source,reply,udp_host);
3604                 break;
3605                 // @ <SOURCE> :<TEXT>
3606                 // wallops
3607                 case '@':
3608                         handle_AT(token,params,source,reply,udp_host);
3609                 break;
3610                 // F <TS>
3611                 // end netburst
3612                 case 'F':
3613                         WriteOpers("Server %s has completed netburst. (%d secs)",udp_host,time(NULL)-nb_start);
3614                         handle_F(token,params,source,reply,udp_host);
3615                         nb_start = 0;
3616                         // tell all the other servers to use this authcookie to connect back again
3617                         // got '+ test3.chatspike.net 7010 -2016508415' from test.chatspike.net
3618                         snprintf(buffer,MAXBUF,"+ %s %s %d %d",udp_host,ipaddr,port,authcookie);
3619                         NetSendToAllExcept(udp_host,buffer);
3620                 break;
3621                 // X <reserved>
3622                 // Send netburst now
3623                 case 'X':
3624                         WriteOpers("Sending my netburst to %s",udp_host);
3625                         DoSync(source,udp_host);
3626                         WriteOpers("Send of netburst to %s completed",udp_host);
3627                         NetSendMyRoutingTable();
3628                 break;
3629                 // anything else
3630                 default:
3631                         WriteOpers("WARNING! Unknown datagram type '%c'",token);
3632                 break;
3633         }
3634 }
3635
3636
3637 void handle_link_packet(char* udp_msg, char* udp_host, serverrec *serv)
3638 {
3639         char response[10240];
3640         char token = udp_msg[0];
3641         char* params = udp_msg + 2;
3642         char finalparam[1024];
3643         strcpy(finalparam," :xxxx");
3644         if (strstr(udp_msg," :")) {
3645                 strncpy(finalparam,strstr(udp_msg," :"),1024);
3646         }
3647         if (token == '-') {
3648                 char* cookie = strtok(params," ");
3649                 char* servername = strtok(NULL," ");
3650                 char* serverdesc = finalparam+2;
3651
3652                 WriteOpers("AuthCookie CONNECT from %s (%s)",servername,udp_host);
3653
3654                 for (int u = 0; u < auth_cookies.size(); u++)
3655                 {
3656                         if (auth_cookies[u] == atoi(cookie))
3657                         {
3658                                 WriteOpers("Allowed cookie from %s, is now part of the mesh",servername);
3659
3660
3661                                 for (int j = 0; j < 32; j++)
3662                                 {
3663                                         if (me[j] != NULL)
3664                                         {
3665                                                 for (int k = 0; k < me[j]->connectors.size(); k++)
3666                                                 {
3667                                                         if (!strcasecmp(me[j]->connectors[k].GetServerName().c_str(),udp_host))
3668                                                         {
3669                                                                 me[j]->connectors[k].SetServerName(servername);
3670                                                                 me[j]->connectors[k].SetDescription(serverdesc);
3671                                                                 me[j]->connectors[k].SetState(STATE_CONNECTED);
3672                                                                 NetSendMyRoutingTable();
3673                                                                 return;
3674                                                         }
3675                                                 }
3676                                         }
3677                                         WriteOpers("\2WARNING!\2 %s sent us an authentication packet but we are not authenticating with this server right now! Possible intrusion attempt!",udp_host);
3678                                         return;
3679                                 }
3680
3681
3682                                 return;
3683                         }
3684                 }
3685                 // bad cookie, bad bad! go sit in the corner!
3686                 WriteOpers("Bad cookie from %s!",servername);
3687                 return;
3688         }
3689         else
3690         if (token == 'S') {
3691                 // S test.chatspike.net password portn :ChatSpike InspIRCd test server
3692                 char* servername = strtok(params," ");
3693                 char* password = strtok(NULL," ");
3694                 char* myport = strtok(NULL," ");
3695                 char* revision = strtok(NULL," ");
3696                 char* serverdesc = finalparam+2;
3697
3698                 WriteOpers("CONNECT from %s (%s) (their port: %d)",servername,udp_host,atoi(myport));
3699                 
3700                 ircd_connector* cn = serv->FindHost(servername);
3701                 
3702                 if (cn)
3703                 {
3704                         WriteOpers("CONNECT aborted: Server %s already exists from %s",servername,ServerName);
3705                         char buffer[MAXBUF];
3706                         sprintf(buffer,"E :Server %s already exists!",servername);
3707                         serv->SendPacket(buffer,udp_host);
3708                         RemoveServer(udp_host);
3709                         return;
3710                 }
3711
3712                 if (atoi(revision) != GetRevision())
3713                 {
3714                         WriteOpers("CONNECT aborted: Could not link to %s, is an incompatible version %s, our version is %d",servername,revision,GetRevision());
3715                         char buffer[MAXBUF];
3716                         sprintf(buffer,"E :Version number mismatch");
3717                         serv->SendPacket(buffer,udp_host);
3718                         RemoveServer(udp_host);
3719                         RemoveServer(servername);
3720                         return;
3721                 }
3722
3723                 for (int j = 0; j < serv->connectors.size(); j++)
3724                 {
3725                         if (!strcasecmp(serv->connectors[j].GetServerName().c_str(),udp_host))
3726                         {
3727                                 serv->connectors[j].SetServerName(servername);
3728                                 serv->connectors[j].SetDescription(serverdesc);
3729                                 serv->connectors[j].SetServerPort(atoi(myport));
3730                         }
3731                 }
3732                 
3733                 
3734                 char Link_ServerName[1024];
3735                 char Link_IPAddr[1024];
3736                 char Link_Port[1024];
3737                 char Link_Pass[1024];
3738                 char Link_SendPass[1024];
3739                 int LinkPort = 0;
3740                 
3741                 // search for a corresponding <link> block in the config files
3742                 for (int i = 0; i < ConfValueEnum("link",&config_f); i++)
3743                 {
3744                         ConfValue("link","name",i,Link_ServerName,&config_f);
3745                         ConfValue("link","ipaddr",i,Link_IPAddr,&config_f);
3746                         ConfValue("link","port",i,Link_Port,&config_f);
3747                         ConfValue("link","recvpass",i,Link_Pass,&config_f);
3748                         ConfValue("link","sendpass",i,Link_SendPass,&config_f);
3749                         log(DEBUG,"(%d) Comparing against name='%s', ipaddr='%s', port='%s', recvpass='%s'",i,Link_ServerName,Link_IPAddr,Link_Port,Link_Pass);
3750                         LinkPort = atoi(Link_Port);
3751                         if (!strcasecmp(Link_ServerName,servername))
3752                         {
3753                                 // we have a matching link line -
3754                                 // send a 'diminutive' server message back...
3755                                 snprintf(response,10240,"s %s %s :%s",ServerName,Link_SendPass,ServerDesc);
3756                                 serv->SendPacket(response,servername);
3757
3758                                 for (int t = 0; t < serv->connectors.size(); t++)
3759                                 {
3760                                         if (!strcasecmp(serv->connectors[t].GetServerName().c_str(),servername))
3761                                         {
3762                                                 serv->connectors[t].SetState(STATE_CONNECTED);
3763                                         }
3764                                 }
3765                 
3766                                 return;
3767                         }
3768                 }
3769                 char buffer[MAXBUF];
3770                 sprintf(buffer,"E :Access is denied (no matching link block)");
3771                 serv->SendPacket(buffer,udp_host);
3772                 WriteOpers("CONNECT from %s denied, no matching link block",servername);
3773                 RemoveServer(udp_host);
3774                 RemoveServer(servername);
3775                 return;
3776         }
3777         else
3778         if (token == 's') {
3779                 // S test.chatspike.net password :ChatSpike InspIRCd test server
3780                 char* servername = strtok(params," ");
3781                 char* password = strtok(NULL," ");
3782                 char* serverdesc = finalparam+2;
3783                 
3784                 // TODO: we should do a check here to ensure that this server is one we recently initiated a
3785                 // link with, and didnt hear an 's' or 'E' back from yet (these are the only two valid responses
3786                 // to an 'S' command. If we didn't recently send an 'S' to this server, theyre trying to spoof
3787                 // a connect, so put out an oper alert!
3788                 
3789                 // for now, just accept all, we'll fix that later.
3790                 WriteOpers("%s accepted our link credentials ",servername);
3791                 
3792                 char Link_ServerName[1024];
3793                 char Link_IPAddr[1024];
3794                 char Link_Port[1024];
3795                 char Link_Pass[1024];
3796                 char Link_SendPass[1024];
3797                 int LinkPort = 0;
3798                 
3799                 // search for a corresponding <link> block in the config files
3800                 for (int i = 0; i < ConfValueEnum("link",&config_f); i++)
3801                 {
3802                         ConfValue("link","name",i,Link_ServerName,&config_f);
3803                         ConfValue("link","ipaddr",i,Link_IPAddr,&config_f);
3804                         ConfValue("link","port",i,Link_Port,&config_f);
3805                         ConfValue("link","recvpass",i,Link_Pass,&config_f);
3806                         ConfValue("link","sendpass",i,Link_SendPass,&config_f);
3807                         log(DEBUG,"(%d) Comparing against name='%s', ipaddr='%s', port='%s', recvpass='%s'",i,Link_ServerName,Link_IPAddr,Link_Port,Link_Pass);
3808                         LinkPort = atoi(Link_Port);
3809                         if (!strcasecmp(Link_ServerName,servername))
3810                         {
3811                                 // matching link at this end too, we're all done!
3812                                 // at this point we must begin key exchange and insert this
3813                                 // server into our 'active' table.
3814                                 for (int j = 0; j < 32; j++)
3815                                 {
3816                                         if (me[j] != NULL)
3817                                         {
3818                                                 for (int k = 0; k < me[j]->connectors.size(); k++)
3819                                                 {
3820                                                         if (!strcasecmp(me[j]->connectors[k].GetServerName().c_str(),udp_host))
3821                                                         {
3822                                                                 char buffer[MAXBUF];
3823                                                                 me[j]->connectors[k].SetDescription(serverdesc);
3824                                                                 me[j]->connectors[k].SetState(STATE_CONNECTED);
3825                                                                 sprintf(buffer,"X 0");
3826                                                                 serv->SendPacket(buffer,udp_host);
3827                                                                 DoSync(me[j],udp_host);
3828                                                                 NetSendMyRoutingTable();
3829                                                                 return;
3830                                                         }
3831                                                 }
3832                                         }
3833                                         WriteOpers("\2WARNING!\2 %s sent us an authentication packet but we are not authenticating with this server right noe! Possible intrusion attempt!",udp_host);
3834                                         return;
3835                                 }
3836                         }
3837                         else {
3838                                 log(DEBUG,"Server names '%s' and '%s' don't match",Link_ServerName,servername);
3839                         }
3840                 }
3841                 char buffer[MAXBUF];
3842                 sprintf(buffer,"E :Access is denied (no matching link block)");
3843                 serv->SendPacket(buffer,udp_host);
3844                 WriteOpers("CONNECT from %s denied, no matching link block",servername);
3845                 RemoveServer(udp_host);
3846                 RemoveServer(servername);
3847                 return;
3848         }
3849         else
3850         if (token == 'E') {
3851                 char* error_message = finalparam+2;
3852                 WriteOpers("ERROR from %s: %s",udp_host,error_message);
3853                 return;
3854         }
3855         else {
3856
3857                 serverrec* source_server = NULL;
3858
3859                 for (int j = 0; j < 32; j++)
3860                 {
3861                         if (me[j] != NULL)
3862                         {
3863                                 for (int x = 0; x < me[j]->connectors.size(); x++)
3864                                 {
3865                                         log(DEBUG,"Servers are: '%s' '%s'",udp_host,me[j]->connectors[x].GetServerName().c_str());
3866                                         if (!strcasecmp(me[j]->connectors[x].GetServerName().c_str(),udp_host))
3867                                         {
3868                                                 if (me[j]->connectors[x].GetState() == STATE_CONNECTED)
3869                                                 {
3870                                                         // found a valid ircd_connector.
3871                                                         process_restricted_commands(token,params,me[j],serv,udp_host,me[j]->connectors[x].GetServerIP(),me[j]->connectors[x].GetServerPort());
3872                                                         return;
3873                                                 }
3874                                         }
3875                                 }
3876                         }
3877                 }
3878
3879                 log(DEBUG,"Unrecognised token or unauthenticated host in datagram from %s: %c",udp_host,token);
3880         }
3881 }
3882
3883 int reap_counter = 0;
3884
3885 int InspIRCd(void)
3886 {
3887         struct sockaddr_in client, server;
3888         char addrs[MAXBUF][255];
3889         int openSockfd[MAXSOCKS], incomingSockfd, result = TRUE;
3890         socklen_t length;
3891         int count = 0, scanDetectTrigger = TRUE, showBanner = FALSE;
3892         int selectResult = 0, selectResult2 = 0;
3893         char *temp, configToken[MAXBUF], stuff[MAXBUF], Addr[MAXBUF], Type[MAXBUF];
3894         char resolvedHost[MAXBUF];
3895         fd_set selectFds;
3896         struct timeval tv;
3897
3898         log_file = fopen("ircd.log","a+");
3899         if (!log_file)
3900         {
3901                 printf("ERROR: Could not write to logfile ircd.log, bailing!\n\n");
3902                 Exit(ERROR);
3903         }
3904
3905         log(DEBUG,"InspIRCd: startup: begin");
3906         log(DEBUG,"$Id$");
3907         if (geteuid() == 0)
3908         {
3909                 printf("WARNING!!! You are running an irc server as ROOT!!! DO NOT DO THIS!!!\n\n");
3910                 Exit(ERROR);
3911                 log(DEBUG,"InspIRCd: startup: not starting with UID 0!");
3912         }
3913         SetupCommandTable();
3914         log(DEBUG,"InspIRCd: startup: default command table set up");
3915         
3916         ReadConfig();
3917         if (strcmp(DieValue,"")) 
3918         { 
3919                 printf("WARNING: %s\n\n",DieValue);
3920                 exit(0); 
3921         }  
3922         log(DEBUG,"InspIRCd: startup: read config");
3923           
3924         int count2 = 0, count3 = 0;
3925
3926         for (count = 0; count < ConfValueEnum("bind",&config_f); count++)
3927         {
3928                 ConfValue("bind","port",count,configToken,&config_f);
3929                 ConfValue("bind","address",count,Addr,&config_f);
3930                 ConfValue("bind","type",count,Type,&config_f);
3931                 if (!strcmp(Type,"servers"))
3932                 {
3933                         char Default[MAXBUF];
3934                         strcpy(Default,"no");
3935                         ConfValue("bind","default",count,Default,&config_f);
3936                         if (strchr(Default,'y'))
3937                         {
3938                                 defaultRoute = count3;
3939                                 log(DEBUG,"InspIRCd: startup: binding '%s:%s' is default server route",Addr,configToken);
3940                         }
3941                         me[count3] = new serverrec(ServerName,100L,false);
3942                         me[count3]->CreateListener(Addr,atoi(configToken));
3943                         count3++;
3944                 }
3945                 else
3946                 {
3947                         ports[count2] = atoi(configToken);
3948                         strcpy(addrs[count2],Addr);
3949                         count2++;
3950                 }
3951                 log(DEBUG,"InspIRCd: startup: read binding %s:%s [%s] from config",Addr,configToken, Type);
3952         }
3953         portCount = count2;
3954         UDPportCount = count3;
3955           
3956         log(DEBUG,"InspIRCd: startup: read %d total client ports and %d total server ports",portCount,UDPportCount);
3957         
3958         log(DEBUG,"InspIRCd: startup: InspIRCd is now running!");
3959         
3960         printf("\n");
3961         
3962         /* BugFix By Craig! :p */
3963         count = 0;
3964         for (count2 = 0; count2 < ConfValueEnum("module",&config_f); count2++)
3965         {
3966                 char modfile[MAXBUF];
3967                 ConfValue("module","name",count2,configToken,&config_f);
3968                 sprintf(modfile,"%s/%s",MOD_PATH,configToken,&config_f);
3969                 printf("Loading module... \033[1;37m%s\033[0;37m\n",modfile);
3970                 log(DEBUG,"InspIRCd: startup: Loading module: %s",modfile);
3971                 /* If The File Doesnt exist, Trying to load it
3972                  * Will Segfault the IRCd.. So, check to see if
3973                  * it Exists, Before Proceeding. */
3974                 if (FileExists(modfile))
3975                 {
3976                         factory[count] = new ircd_module(modfile);
3977                         if (factory[count]->LastError())
3978                         {
3979                                 log(DEBUG,"Unable to load %s: %s",modfile,factory[count]->LastError());
3980                                 sprintf("Unable to load %s: %s\nExiting...\n",modfile,factory[count]->LastError());
3981                                 Exit(ERROR);
3982                         }
3983                         if (factory[count]->factory)
3984                         {
3985                                 modules[count] = factory[count]->factory->CreateModule();
3986                                 /* save the module and the module's classfactory, if
3987                                  * this isnt done, random crashes can occur :/ */
3988                                 module_names.push_back(modfile);        
3989                         }
3990                         else
3991                         {
3992                                 log(DEBUG,"Unable to load %s",modfile);
3993                                 sprintf("Unable to load %s\nExiting...\n",modfile);
3994                                 Exit(ERROR);
3995                         }
3996                         /* Increase the Count */
3997                         count++;
3998                 }
3999                 else
4000                 {
4001                         log(DEBUG,"InspIRCd: startup: Module Not Found %s",modfile);
4002                         printf("Module Not Found: \033[1;37m%s\033[0;37m, Skipping\n",modfile);
4003                 }
4004         }
4005         MODCOUNT = count - 1;
4006         log(DEBUG,"Total loaded modules: %d",MODCOUNT+1);
4007         
4008         printf("\nInspIRCd is now running!\n");
4009         
4010         startup_time = time(NULL);
4011           
4012         if (nofork)
4013         {
4014                 log(VERBOSE,"Not forking as -nofork was specified");
4015         }
4016         else
4017         {
4018                 if (DaemonSeed() == ERROR)
4019                 {
4020                         log(DEBUG,"InspIRCd: startup: can't daemonise");
4021                         printf("ERROR: could not go into daemon mode. Shutting down.\n");
4022                         Exit(ERROR);
4023                 }
4024         }
4025           
4026           
4027         /* setup select call */
4028         FD_ZERO(&selectFds);
4029         log(DEBUG,"InspIRCd: startup: zero selects");
4030         log(VERBOSE,"InspIRCd: startup: portCount = %d", portCount);
4031         
4032         for (count = 0; count < portCount; count++)
4033         {
4034                 if ((openSockfd[boundPortCount] = OpenTCPSocket()) == ERROR)
4035                 {
4036                         log(DEBUG,"InspIRCd: startup: bad fd %d",openSockfd[boundPortCount]);
4037                         return(ERROR);
4038                 }
4039                 if (BindSocket(openSockfd[boundPortCount],client,server,ports[count],addrs[count]) == ERROR)
4040                 {
4041                         log(DEBUG,"InspIRCd: startup: failed to bind port %d",ports[count]);
4042                 }
4043                 else    /* well we at least bound to one socket so we'll continue */
4044                 {
4045                         boundPortCount++;
4046                 }
4047         }
4048         
4049         log(DEBUG,"InspIRCd: startup: total bound ports %d",boundPortCount);
4050           
4051         /* if we didn't bind to anything then abort */
4052         if (boundPortCount == 0)
4053         {
4054                 log(DEBUG,"InspIRCd: startup: no ports bound, bailing!");
4055                 return (ERROR);
4056         }
4057         
4058
4059         length = sizeof (client);
4060         char udp_msg[MAXBUF], udp_host[MAXBUF];
4061           
4062         /* main loop, this never returns */
4063         for (;;)
4064         {
4065 #ifdef _POSIX_PRIORITY_SCHEDULING
4066                 sched_yield();
4067 #endif
4068
4069                 fd_set sfd;
4070                 timeval tval;
4071                 FD_ZERO(&sfd);
4072
4073                 user_hash::iterator count2 = clientlist.begin();
4074
4075                 // *FIX* Instead of closing sockets in kill_link when they receive the ERROR :blah line, we should queue
4076                 // them in a list, then reap the list every second or so.
4077                 if (reap_counter>300)
4078                 {
4079                         if (fd_reap.size() > 0)
4080                         {
4081                                 for( int n = 0; n < fd_reap.size(); n++)
4082                                 {
4083                                         Blocking(fd_reap[n]);
4084                                         close(fd_reap[n]);
4085                                         NonBlocking(fd_reap[n]);
4086                                 }
4087                         }
4088                         fd_reap.clear();
4089                         reap_counter=0;
4090                 }
4091                 reap_counter++;
4092
4093                 fd_set serverfds;
4094                 FD_ZERO(&serverfds);
4095                 timeval tvs;
4096                 
4097                 for (int x = 0; x != UDPportCount; x++)
4098                 {
4099                         FD_SET(me[x]->fd, &serverfds);
4100                 }
4101                 
4102                 tvs.tv_usec = 0;                
4103                 tvs.tv_sec = 0;
4104                 
4105                 int servresult = select(32767, &serverfds, NULL, NULL, &tvs);
4106                 if (servresult > 0)
4107                 {
4108                         for (int x = 0; x != UDPportCount; x++)
4109                         {
4110                                 if (FD_ISSET (me[x]->fd, &serverfds))
4111                                 {
4112                                         char remotehost[MAXBUF],resolved[MAXBUF];
4113                                         length = sizeof (client);
4114                                         incomingSockfd = accept (me[x]->fd, (sockaddr *) &client, &length);
4115                                         strncpy(remotehost,(char *)inet_ntoa(client.sin_addr),MAXBUF);
4116                                         if(CleanAndResolve(resolved, remotehost) != TRUE)
4117                                         {
4118                                                 strncpy(resolved,remotehost,MAXBUF);
4119                                         }
4120                                         // add to this connections ircd_connector vector
4121                                         // *FIX* - we need the LOCAL port not the remote port in &client!
4122                                         me[x]->AddIncoming(incomingSockfd,resolved,me[x]->port);
4123                                 }
4124                         }
4125                 }
4126      
4127                 for (int x = 0; x < UDPportCount; x++)
4128                 {
4129                         std::deque<std::string> msgs;
4130                         msgs.clear();
4131                         if (me[x]->RecvPacket(msgs, udp_host))
4132                         {
4133                                 for (int ctr = 0; ctr < msgs.size(); ctr++)
4134                                 {
4135                                         char udp_msg[MAXBUF];
4136                                         strncpy(udp_msg,msgs[ctr].c_str(),MAXBUF);
4137                                         if (strlen(udp_msg)<1)
4138                                         {
4139                                                 log(DEBUG,"Invalid string from %s [route%d]",udp_host,x);
4140                                                 break;
4141                                         }
4142                                         // during a netburst, send all data to all other linked servers
4143                                         if ((nb_start>0) && (udp_msg[0] != 'Y') && (udp_msg[0] != 'X') && (udp_msg[0] != 'F'))
4144                                         {
4145                                                 NetSendToAllExcept(udp_host,udp_msg);
4146                                         }
4147                                         FOREACH_MOD OnPacketReceive(udp_msg);
4148                                         handle_link_packet(udp_msg, udp_host, me[x]);
4149                                 }
4150                                 goto label;
4151                         }
4152                 }
4153         
4154
4155         while (count2 != clientlist.end())
4156         {
4157                 char data[10240];
4158                 tval.tv_usec = tval.tv_sec = 0;
4159                 FD_ZERO(&sfd);
4160                 int total_in_this_set = 0;
4161
4162                 user_hash::iterator xcount = count2;
4163                 user_hash::iterator endingiter = count2;
4164
4165                 if (!count2->second) break;
4166                 
4167                 if (count2->second)
4168                 if (count2->second->fd != 0)
4169                 {
4170                         // assemble up to 64 sockets into an fd_set
4171                         // to implement a pooling mechanism.
4172                         //
4173                         // This should be up to 64x faster than the
4174                         // old implementation.
4175                         while (total_in_this_set < 64)
4176                         {
4177                                 if (count2 != clientlist.end())
4178                                 {
4179                                         // we don't check the state of remote users.
4180                                         if (count2->second->fd > 0)
4181                                         {
4182                                                 FD_SET (count2->second->fd, &sfd);
4183
4184                                                 // registration timeout -- didnt send USER/NICK/HOST in the time specified in
4185                                                 // their connection class.
4186                                                 if ((time(NULL) > count2->second->timeout) && (count2->second->registered != 7)) 
4187                                                 {
4188                                                         log(DEBUG,"InspIRCd: registration timeout: %s",count2->second->nick);
4189                                                         kill_link(count2->second,"Registration timeout");
4190                                                         goto label;
4191                                                 }
4192                                                 if (((time(NULL)) > count2->second->nping) && (isnick(count2->second->nick)) && (count2->second->registered == 7))
4193                                                 {
4194                                                         if ((!count2->second->lastping) && (count2->second->registered == 7))
4195                                                         {
4196                                                                 log(DEBUG,"InspIRCd: ping timeout: %s",count2->second->nick);
4197                                                                 kill_link(count2->second,"Ping timeout");
4198                                                                 goto label;
4199                                                         }
4200                                                         Write(count2->second->fd,"PING :%s",ServerName);
4201                                                         log(DEBUG,"InspIRCd: pinging: %s",count2->second->nick);
4202                                                         count2->second->lastping = 0;
4203                                                         count2->second->nping = time(NULL)+120;
4204                                                 }
4205                                         }
4206                                         count2++;
4207                                         total_in_this_set++;
4208                                 }
4209                                 else break;
4210                         }
4211    
4212                         endingiter = count2;
4213                         count2 = xcount; // roll back to where we were
4214         
4215                         int v = 0;
4216
4217                         tval.tv_usec = 0;
4218                         tval.tv_sec = 0;
4219                         selectResult2 = select(65535, &sfd, NULL, NULL, &tval);
4220                         
4221                         // now loop through all of the items in this pool if any are waiting
4222                         //if (selectResult2 > 0)
4223                         for (user_hash::iterator count2a = xcount; count2a != endingiter; count2a++)
4224                         {
4225
4226 #ifdef _POSIX_PRIORITY_SCHEDULING
4227                                 sched_yield();
4228 #endif
4229
4230                                 result = EAGAIN;
4231                                 if ((count2a->second->fd != -1) && (FD_ISSET (count2a->second->fd, &sfd)))
4232                                 {
4233                                         log(DEBUG,"Reading fd %d",count2a->second->fd);
4234                                         memset(data, 0, 10240);
4235                                         result = read(count2a->second->fd, data, 10240);
4236                                         
4237                                         if (result)
4238                                         {
4239                                                 if (result > 0)
4240                                                         log(DEBUG,"Read %d characters from socket",result);
4241                                                 userrec* current = count2a->second;
4242                                                 int currfd = current->fd;
4243                                                 char* l = strtok(data,"\n");
4244                                                 int floodlines = 0;
4245                                                 while (l)
4246                                                 {
4247                                                         floodlines++;
4248                                                         if ((floodlines > current->flood) && (current->flood != 0))
4249                                                         {
4250                                                                 log(DEFAULT,"Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
4251                                                                 WriteOpers("*** Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
4252                                                                 kill_link(current,"Excess flood");
4253                                                                 goto label;
4254                                                         }
4255                                                         char sanitized[NetBufferSize];
4256                                                         memset(sanitized, 0, NetBufferSize);
4257                                                         int ptt = 0;
4258                                                         for (int pt = 0; pt < strlen(l); pt++)
4259                                                         {
4260                                                                 if (l[pt] != '\r')
4261                                                                 {
4262                                                                         sanitized[ptt++] = l[pt];
4263                                                                 }
4264                                                         }
4265                                                         sanitized[ptt] = '\0';
4266                                                         if (strlen(sanitized))
4267                                                         {
4268
4269
4270                                                                 // we're gonna re-scan to check if the nick is gone, after every
4271                                                                 // command - if it has, we're gonna bail
4272                                                                 bool find_again = false;
4273                                                                 process_buffer(sanitized,current);
4274         
4275                                                                 // look for the user's record in case it's changed
4276                                                                 for (user_hash::iterator c2 = clientlist.begin(); c2 != clientlist.end(); c2++)
4277                                                                 {
4278                                                                         if (c2->second->fd == currfd)
4279                                                                         {
4280                                                                                 // found again, update pointer
4281                                                                                 current == c2->second;
4282                                                                                 find_again = true;
4283                                                                                 break;
4284                                                                         }
4285                                                                 }
4286                                                                 if (!find_again)
4287                                                                         goto label;
4288
4289                                                         }
4290                                                         l = strtok(NULL,"\n");
4291                                                 }
4292                                                 goto label;
4293                                         }
4294
4295                                         if ((result == -1) && (errno != EAGAIN) && (errno != EINTR))
4296                                         {
4297                                                 log(DEBUG,"killing: %s",count2a->second->nick);
4298                                                 kill_link(count2a->second,strerror(errno));
4299                                                 goto label;
4300                                         }
4301                                 }
4302                                 // result EAGAIN means nothing read
4303                                 if (result == EAGAIN)
4304                                 {
4305                                 }
4306                                 else
4307                                 if (result == 0)
4308                                 {
4309                                         if (count2->second)
4310                                         {
4311                                                 log(DEBUG,"InspIRCd: Exited: %s",count2a->second->nick);
4312                                                 kill_link(count2a->second,"Client exited");
4313                                                 // must bail here? kill_link removes the hash, corrupting the iterator
4314                                                 log(DEBUG,"Bailing from client exit");
4315                                                 goto label;
4316                                         }
4317                                 }
4318                                 else if (result > 0)
4319                                 {
4320                                 }
4321                         }
4322                 }
4323                 for (int q = 0; q < total_in_this_set; q++)
4324                 {
4325                         // there is no iterator += operator :(
4326                         //if (count2 != clientlist.end())
4327                         //{
4328                                 count2++;
4329                         //}
4330                 }
4331         }
4332         
4333         // set up select call
4334         for (count = 0; count < boundPortCount; count++)
4335         {
4336                 FD_SET (openSockfd[count], &selectFds);
4337         }
4338
4339         tv.tv_usec = 1;
4340         selectResult = select(MAXSOCKS, &selectFds, NULL, NULL, &tv);
4341
4342         /* select is reporting a waiting socket. Poll them all to find out which */
4343         if (selectResult > 0)
4344         {
4345                 char target[MAXBUF], resolved[MAXBUF];
4346                 for (count = 0; count < boundPortCount; count++)                
4347                 {
4348                         if (FD_ISSET (openSockfd[count], &selectFds))
4349                         {
4350                                 length = sizeof (client);
4351                                 incomingSockfd = accept (openSockfd[count], (struct sockaddr *) &client, &length);
4352                               
4353                                 address_cache::iterator iter = IP.find(client.sin_addr);
4354                                 bool iscached = false;
4355                                 if (iter == IP.end())
4356                                 {
4357                                         /* ip isn't in cache, add it */
4358                                         strncpy (target, (char *) inet_ntoa (client.sin_addr), MAXBUF);
4359                                         if(CleanAndResolve(resolved, target) != TRUE)
4360                                         {
4361                                                 strncpy(resolved,target,MAXBUF);
4362                                         }
4363                                         /* hostname now in 'target' */
4364                                         IP[client.sin_addr] = new string(resolved);
4365                                         /* hostname in cache */
4366                                 }
4367                                 else
4368                                 {
4369                                         /* found ip (cached) */
4370                                         strncpy(resolved, iter->second->c_str(), MAXBUF);
4371                                         iscached = true;
4372                                 }
4373                         
4374                                 if (incomingSockfd < 0)
4375                                 {
4376                                         WriteOpers("*** WARNING: Accept failed on port %d (%s)", ports[count],target);
4377                                         log(DEBUG,"InspIRCd: accept failed: %d",ports[count]);
4378                                 }
4379                                 else
4380                                 {
4381                                         AddClient(incomingSockfd, resolved, ports[count], iscached);
4382                                         log(DEBUG,"InspIRCd: adding client on port %d fd=%d",ports[count],incomingSockfd);
4383                                 }
4384                                 goto label;
4385                         }
4386                 }
4387         }
4388         label:
4389         if(0) {}; // "Label must be followed by a statement"... so i gave it one.
4390 }
4391 /* not reached */
4392 close (incomingSockfd);
4393 }
4394