]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/inspircd.cpp
Fixed typo in this file
[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))) && (!is_uline(src->server)))
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         int MOD_RESULT = 0;
2360         
2361         strcpy(nick,"");
2362
2363         FOREACH_RESULT(OnUserPreNick(user,newnick));
2364         if (MOD_RESULT) {
2365                 kill_link(user,"Nickname collision");
2366                 return;
2367         }
2368         
2369         if (user)
2370         {
2371                 if (newnick)
2372                 {
2373                         strncpy(nick,newnick,MAXBUF);
2374                 }
2375                 if (user->registered == 7)
2376                 {
2377                         char* pars[1];
2378                         pars[0] = nick;
2379                         handle_nick(pars,1,user);
2380                 }
2381         }
2382 }
2383                                 
2384
2385 int process_parameters(char **command_p,char *parameters)
2386 {
2387         int i = 0;
2388         int j = 0;
2389         int q = 0;
2390         q = strlen(parameters);
2391         if (!q)
2392         {
2393                 /* no parameters, command_p invalid! */
2394                 return 0;
2395         }
2396         if (parameters[0] == ':')
2397         {
2398                 command_p[0] = parameters+1;
2399                 return 1;
2400         }
2401         if (q)
2402         {
2403                 if ((strchr(parameters,' ')==NULL) || (parameters[0] == ':'))
2404                 {
2405                         /* only one parameter */
2406                         command_p[0] = parameters;
2407                         if (parameters[0] == ':')
2408                         {
2409                                 if (strchr(parameters,' ') != NULL)
2410                                 {
2411                                         command_p[0]++;
2412                                 }
2413                         }
2414                         return 1;
2415                 }
2416         }
2417         command_p[j++] = parameters;
2418         for (int i = 0; i <= q; i++)
2419         {
2420                 if (parameters[i] == ' ')
2421                 {
2422                         command_p[j++] = parameters+i+1;
2423                         parameters[i] = '\0';
2424                         if (command_p[j-1][0] == ':')
2425                         {
2426                                 *command_p[j-1]++; /* remove dodgy ":" */
2427                                 break;
2428                                 /* parameter like this marks end of the sequence */
2429                         }
2430                 }
2431         }
2432         return j; /* returns total number of items in the list */
2433 }
2434
2435 void process_command(userrec *user, char* cmd)
2436 {
2437         char *parameters;
2438         char *command;
2439         char *command_p[127];
2440         char p[MAXBUF], temp[MAXBUF];
2441         int i, j, items, cmd_found;
2442
2443         for (int i = 0; i < 127; i++)
2444                 command_p[i] = NULL;
2445
2446         if (!user)
2447         {
2448                 return;
2449         }
2450         if (!cmd)
2451         {
2452                 return;
2453         }
2454         if (!strcmp(cmd,""))
2455         {
2456                 return;
2457         }
2458         
2459         int total_params = 0;
2460         if (strlen(cmd)>2)
2461         {
2462                 for (int q = 0; q < strlen(cmd)-1; q++)
2463                 {
2464                         if ((cmd[q] == ' ') && (cmd[q+1] == ':'))
2465                         {
2466                                 total_params++;
2467                                 // found a 'trailing', we dont count them after this.
2468                                 break;
2469                         }
2470                         if (cmd[q] == ' ')
2471                                 total_params++;
2472                 }
2473         }
2474         
2475         // another phidjit bug...
2476         if (total_params > 126)
2477         {
2478                 kill_link(user,"Protocol violation (1)");
2479                 return;
2480         }
2481         
2482         strcpy(temp,cmd);
2483
2484         std::string tmp = cmd;
2485         for (int i = 0; i <= MODCOUNT; i++)
2486         {
2487                 std::string oldtmp = tmp;
2488                 modules[i]->OnServerRaw(tmp,true);
2489                 if (oldtmp != tmp)
2490                 {
2491                         log(DEBUG,"A Module changed the input string!");
2492                         log(DEBUG,"New string: %s",tmp.c_str());
2493                         log(DEBUG,"Old string: %s",oldtmp.c_str());
2494                         break;
2495                 }
2496         }
2497         strncpy(cmd,tmp.c_str(),MAXBUF);
2498         strcpy(temp,cmd);
2499
2500         if (!strchr(cmd,' '))
2501         {
2502                 /* no parameters, lets skip the formalities and not chop up
2503                  * the string */
2504                 log(DEBUG,"About to preprocess command with no params");
2505                 items = 0;
2506                 command_p[0] = NULL;
2507                 parameters = NULL;
2508                 for (int i = 0; i <= strlen(cmd); i++)
2509                 {
2510                         cmd[i] = toupper(cmd[i]);
2511                 }
2512                 log(DEBUG,"Preprocess done length=%d",strlen(cmd));
2513                 command = cmd;
2514         }
2515         else
2516         {
2517                 strcpy(cmd,"");
2518                 j = 0;
2519                 /* strip out extraneous linefeeds through mirc's crappy pasting (thanks Craig) */
2520                 for (int i = 0; i < strlen(temp); i++)
2521                 {
2522                         if ((temp[i] != 10) && (temp[i] != 13) && (temp[i] != 0) && (temp[i] != 7))
2523                         {
2524                                 cmd[j++] = temp[i];
2525                                 cmd[j] = 0;
2526                         }
2527                 }
2528                 /* split the full string into a command plus parameters */
2529                 parameters = p;
2530                 strcpy(p," ");
2531                 command = cmd;
2532                 if (strchr(cmd,' '))
2533                 {
2534                         for (int i = 0; i <= strlen(cmd); i++)
2535                         {
2536                                 /* capitalise the command ONLY, leave params intact */
2537                                 cmd[i] = toupper(cmd[i]);
2538                                 /* are we nearly there yet?! :P */
2539                                 if (cmd[i] == ' ')
2540                                 {
2541                                         command = cmd;
2542                                         parameters = cmd+i+1;
2543                                         cmd[i] = '\0';
2544                                         break;
2545                                 }
2546                         }
2547                 }
2548                 else
2549                 {
2550                         for (int i = 0; i <= strlen(cmd); i++)
2551                         {
2552                                 cmd[i] = toupper(cmd[i]);
2553                         }
2554                 }
2555
2556         }
2557         cmd_found = 0;
2558         
2559         if (strlen(command)>MAXCOMMAND)
2560         {
2561                 kill_link(user,"Protocol violation (2)");
2562                 return;
2563         }
2564         
2565         for (int x = 0; x < strlen(command); x++)
2566         {
2567                 if (((command[x] < 'A') || (command[x] > 'Z')) && (command[x] != '.'))
2568                 {
2569                         if (((command[x] < '0') || (command[x]> '9')) && (command[x] != '-'))
2570                         {
2571                                 if (!strchr("@!\"$%^&*(){}[]_-=+;:'#~,.<>/?\\|`",command[x]))
2572                                 {
2573                                         kill_link(user,"Protocol violation (3)");
2574                                         return;
2575                                 }
2576                         }
2577                 }
2578         }
2579
2580         for (int i = 0; i != cmdlist.size(); i++)
2581         {
2582                 if (strcmp(cmdlist[i].command,""))
2583                 {
2584                         if (strlen(command)>=(strlen(cmdlist[i].command))) if (!strncmp(command, cmdlist[i].command,MAXCOMMAND))
2585                         {
2586                                 log(DEBUG,"Found matching command");
2587
2588                                 if (parameters)
2589                                 {
2590                                         if (strcmp(parameters,""))
2591                                         {
2592                                                 items = process_parameters(command_p,parameters);
2593                                         }
2594                                         else
2595                                         {
2596                                                 items = 0;
2597                                                 command_p[0] = NULL;
2598                                         }
2599                                 }
2600                                 else
2601                                 {
2602                                         items = 0;
2603                                         command_p[0] = NULL;
2604                                 }
2605                                 
2606                                 if (user)
2607                                 {
2608                                         log(DEBUG,"Processing command");
2609                                         
2610                                         /* activity resets the ping pending timer */
2611                                         user->nping = time(NULL) + 120;
2612                                         if ((items) < cmdlist[i].min_params)
2613                                         {
2614                                                 log(DEBUG,"process_command: not enough parameters: %s %s",user->nick,command);
2615                                                 WriteServ(user->fd,"461 %s %s :Not enough parameters",user->nick,command);
2616                                                 return;
2617                                         }
2618                                         if ((!strchr(user->modes,cmdlist[i].flags_needed)) && (cmdlist[i].flags_needed))
2619                                         {
2620                                                 log(DEBUG,"process_command: permission denied: %s %s",user->nick,command);
2621                                                 WriteServ(user->fd,"481 %s :Permission Denied- You do not have the required operator privilages",user->nick);
2622                                                 cmd_found = 1;
2623                                                 return;
2624                                         }
2625                                         /* if the command isnt USER, PASS, or NICK, and nick is empty,
2626                                          * deny command! */
2627                                         if ((strncmp(command,"USER",4)) && (strncmp(command,"NICK",4)) && (strncmp(command,"PASS",4)))
2628                                         {
2629                                                 if ((!isnick(user->nick)) || (user->registered != 7))
2630                                                 {
2631                                                         log(DEBUG,"process_command: not registered: %s %s",user->nick,command);
2632                                                         WriteServ(user->fd,"451 %s :You have not registered",command);
2633                                                         return;
2634                                                 }
2635                                         }
2636                                         if ((user->registered == 7) || (!strcmp(command,"USER")) || (!strcmp(command,"NICK")) || (!strcmp(command,"PASS")))
2637                                         {
2638                                                 log(DEBUG,"process_command: handler: %s %s %d",user->nick,command,items);
2639                                                 if (cmdlist[i].handler_function)
2640                                                 {
2641                                                         /* ikky /stats counters */
2642                                                         if (temp)
2643                                                         {
2644                                                                 if (user)
2645                                                                 {
2646                                                                         user->bytes_in += strlen(temp);
2647                                                                         user->cmds_in++;
2648                                                                 }
2649                                                                 cmdlist[i].use_count++;
2650                                                                 cmdlist[i].total_bytes+=strlen(temp);
2651                                                         }
2652
2653                                                         /* WARNING: nothing may come after the
2654                                                          * command handler call, as the handler
2655                                                          * may free the user structure! */
2656
2657                                                         cmdlist[i].handler_function(command_p,items,user);
2658                                                 }
2659                                                 return;
2660                                         }
2661                                         else
2662                                         {
2663                                                 log(DEBUG,"process_command: not registered: %s %s",user->nick,command);
2664                                                 WriteServ(user->fd,"451 %s :You have not registered",command);
2665                                                 return;
2666                                         }
2667                                 }
2668                                 cmd_found = 1;
2669                         }
2670                 }
2671         }
2672         if ((!cmd_found) && (user))
2673         {
2674                 log(DEBUG,"process_command: not in table: %s %s",user->nick,command);
2675                 WriteServ(user->fd,"421 %s %s :Unknown command",user->nick,command);
2676         }
2677 }
2678
2679
2680 void createcommand(char* cmd, handlerfunc f, char flags, int minparams)
2681 {
2682         command_t comm;
2683         /* create the command and push it onto the table */     
2684         strcpy(comm.command,cmd);
2685         comm.handler_function = f;
2686         comm.flags_needed = flags;
2687         comm.min_params = minparams;
2688         comm.use_count = 0;
2689         comm.total_bytes = 0;
2690         cmdlist.push_back(comm);
2691         log(DEBUG,"Added command %s (%d parameters)",cmd,minparams);
2692 }
2693
2694 void SetupCommandTable(void)
2695 {
2696         createcommand("USER",handle_user,0,4);
2697         createcommand("NICK",handle_nick,0,1);
2698         createcommand("QUIT",handle_quit,0,0);
2699         createcommand("VERSION",handle_version,0,0);
2700         createcommand("PING",handle_ping,0,1);
2701         createcommand("PONG",handle_pong,0,1);
2702         createcommand("ADMIN",handle_admin,0,0);
2703         createcommand("PRIVMSG",handle_privmsg,0,2);
2704         createcommand("INFO",handle_info,0,0);
2705         createcommand("TIME",handle_time,0,0);
2706         createcommand("WHOIS",handle_whois,0,1);
2707         createcommand("WALLOPS",handle_wallops,'o',1);
2708         createcommand("NOTICE",handle_notice,0,2);
2709         createcommand("JOIN",handle_join,0,1);
2710         createcommand("NAMES",handle_names,0,1);
2711         createcommand("PART",handle_part,0,1);
2712         createcommand("KICK",handle_kick,0,2);
2713         createcommand("MODE",handle_mode,0,1);
2714         createcommand("TOPIC",handle_topic,0,1);
2715         createcommand("WHO",handle_who,0,1);
2716         createcommand("MOTD",handle_motd,0,0);
2717         createcommand("RULES",handle_rules,0,0);
2718         createcommand("OPER",handle_oper,0,2);
2719         createcommand("LIST",handle_list,0,0);
2720         createcommand("DIE",handle_die,'o',1);
2721         createcommand("RESTART",handle_restart,'o',1);
2722         createcommand("KILL",handle_kill,'o',2);
2723         createcommand("REHASH",handle_rehash,'o',0);
2724         createcommand("LUSERS",handle_lusers,0,0);
2725         createcommand("STATS",handle_stats,0,1);
2726         createcommand("USERHOST",handle_userhost,0,1);
2727         createcommand("AWAY",handle_away,0,0);
2728         createcommand("ISON",handle_ison,0,0);
2729         createcommand("SUMMON",handle_summon,0,0);
2730         createcommand("USERS",handle_users,0,0);
2731         createcommand("INVITE",handle_invite,0,2);
2732         createcommand("PASS",handle_pass,0,1);
2733         createcommand("TRACE",handle_trace,'o',0);
2734         createcommand("WHOWAS",handle_whowas,0,1);
2735         createcommand("CONNECT",handle_connect,'o',1);
2736         createcommand("SQUIT",handle_squit,'o',0);
2737         createcommand("MODULES",handle_modules,'o',0);
2738         createcommand("LINKS",handle_links,0,0);
2739         createcommand("MAP",handle_map,0,0);
2740 }
2741
2742 void process_buffer(const char* cmdbuf,userrec *user)
2743 {
2744         if (!user)
2745         {
2746                 log(DEFAULT,"*** BUG *** process_buffer was given an invalid parameter");
2747                 return;
2748         }
2749         char cmd[MAXBUF];
2750         int i;
2751         if (!cmdbuf)
2752         {
2753                 log(DEFAULT,"*** BUG *** process_buffer was given an invalid parameter");
2754                 return;
2755         }
2756         if (!strcmp(cmdbuf,""))
2757         {
2758                 return;
2759         }
2760         while ((cmdbuf[0] == ' ') && (strlen(cmdbuf)>0)) cmdbuf++; // strip leading spaces
2761
2762         strncpy(cmd,cmdbuf,MAXBUF);
2763         if (!strcmp(cmd,""))
2764         {
2765                 return;
2766         }
2767         if ((cmd[strlen(cmd)-1] == 13) || (cmd[strlen(cmd)-1] == 10))
2768         {
2769                 cmd[strlen(cmd)-1] = '\0';
2770         }
2771         if ((cmd[strlen(cmd)-1] == 13) || (cmd[strlen(cmd)-1] == 10))
2772         {
2773                 cmd[strlen(cmd)-1] = '\0';
2774         }
2775
2776         while ((cmd[strlen(cmd)-1] == ' ') && (strlen(cmd)>0)) // strip trailing spaces
2777         {
2778                 cmd[strlen(cmd)-1] = '\0';
2779         }
2780
2781         if (!strcmp(cmd,""))
2782         {
2783                 return;
2784         }
2785         log(DEBUG,"InspIRCd: processing: %s %s",user->nick,cmd);
2786         tidystring(cmd);
2787         if ((user) && (cmd))
2788         {
2789                 process_command(user,cmd);
2790         }
2791 }
2792
2793 void DoSync(serverrec* serv, char* tcp_host)
2794 {
2795         char data[MAXBUF];
2796         log(DEBUG,"Sending sync");
2797         // send start of sync marker: Y <timestamp>
2798         // at this point the ircd receiving it starts broadcasting this netburst to all ircds
2799         // except the ones its receiving it from.
2800         snprintf(data,MAXBUF,"Y %d",time(NULL));
2801         serv->SendPacket(data,tcp_host);
2802         // send users and channels
2803         for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
2804         {
2805                 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);
2806                 serv->SendPacket(data,tcp_host);
2807                 if (strcmp(chlist(u->second),""))
2808                 {
2809                         snprintf(data,MAXBUF,"J %s %s",u->second->nick,chlist(u->second));
2810                         serv->SendPacket(data,tcp_host);
2811                 }
2812         }
2813         // send channel modes, topics etc...
2814         for (chan_hash::iterator c = chanlist.begin(); c != chanlist.end(); c++)
2815         {
2816                 snprintf(data,MAXBUF,"M %s +%s",c->second->name,chanmodes(c->second));
2817                 serv->SendPacket(data,tcp_host);
2818                 if (strcmp(c->second->topic,""))
2819                 {
2820                         snprintf(data,MAXBUF,"T %d %s %s :%s",c->second->topicset,c->second->setby,c->second->name,c->second->topic);
2821                         serv->SendPacket(data,tcp_host);
2822                 }
2823                 // send current banlist
2824                 
2825                 for (BanList::iterator b = c->second->bans.begin(); b != c->second->bans.end(); b++)
2826                 {
2827                         snprintf(data,MAXBUF,"M %s +b %s",b->set_time,c->second->name,b->data);
2828                         serv->SendPacket(data,tcp_host);
2829                 }
2830         }
2831         snprintf(data,MAXBUF,"F %d",time(NULL));
2832         serv->SendPacket(data,tcp_host);
2833         log(DEBUG,"Sent sync");
2834         // ircd sends its serverlist after the end of sync here
2835 }
2836
2837
2838 void NetSendMyRoutingTable()
2839 {
2840         // send out a line saying what is reachable to us.
2841         // E.g. if A is linked to B C and D, send out:
2842         // $ A B C D
2843         // if its only linked to B and D send out:
2844         // $ A B D
2845         // if it has no links, dont even send out the line at all.
2846         char buffer[MAXBUF];
2847         sprintf(buffer,"$ %s",ServerName);
2848         bool sendit = false;
2849         for (int i = 0; i < 32; i++)
2850         {
2851                 if (me[i] != NULL)
2852                 {
2853                         for (int j = 0; j < me[i]->connectors.size(); j++)
2854                         {
2855                                 if (me[i]->connectors[j].GetState() != STATE_DISCONNECTED)
2856                                 {
2857                                         strncat(buffer," ",MAXBUF);
2858                                         strncat(buffer,me[i]->connectors[j].GetServerName().c_str(),MAXBUF);
2859                                         sendit = true;
2860                                 }
2861                         }
2862                 }
2863         }
2864         if (sendit)
2865                 NetSendToAll(buffer);
2866 }
2867
2868
2869 void DoSplit(const char* params)
2870 {
2871         bool go_again = true;
2872         while (go_again)
2873         {
2874                 go_again = false;
2875                 for (int i = 0; i < 32; i++)
2876                 {
2877                         if (me[i] != NULL)
2878                         {
2879                                 for (vector<ircd_connector>::iterator j = me[i]->connectors.begin(); j != me[i]->connectors.end(); j++)
2880                                 {
2881                                         if (!strcasecmp(j->GetServerName().c_str(),params))
2882                                         {
2883                                                 j->routes.clear();
2884                                                 j->CloseConnection();
2885                                                 me[i]->connectors.erase(j);
2886                                                 go_again = true;
2887                                                 break;
2888                                         }
2889                                 }
2890                         }
2891                 }
2892         }
2893         log(DEBUG,"Removed server. Will remove clients...");
2894         // iterate through the userlist and remove all users on this server.
2895         // because we're dealing with a mesh, we dont have to deal with anything
2896         // "down-route" from this server (nice huh)
2897         go_again = true;
2898         char reason[MAXBUF];
2899         snprintf(reason,MAXBUF,"%s %s",ServerName,params);
2900         while (go_again)
2901         {
2902                 go_again = false;
2903                 for (user_hash::const_iterator u = clientlist.begin(); u != clientlist.end(); u++)
2904                 {
2905                         if (!strcasecmp(u->second->server,params))
2906                         {
2907                                 kill_link(u->second,reason);
2908                                 go_again = true;
2909                                 break;
2910                         }
2911                 }
2912         }
2913 }
2914
2915 // removes a server. Will NOT remove its users!
2916
2917 void RemoveServer(const char* name)
2918 {
2919         bool go_again = true;
2920         while (go_again)
2921         {
2922                 go_again = false;
2923                 for (int i = 0; i < 32; i++)
2924                 {
2925                         if (me[i] != NULL)
2926                         {
2927                                 for (vector<ircd_connector>::iterator j = me[i]->connectors.begin(); j != me[i]->connectors.end(); j++)
2928                                 {
2929                                         if (!strcasecmp(j->GetServerName().c_str(),name))
2930                                         {
2931                                                 j->routes.clear();
2932                                                 j->CloseConnection();
2933                                                 me[i]->connectors.erase(j);
2934                                                 go_again = true;
2935                                                 break;
2936                                         }
2937                                 }
2938                         }
2939                 }
2940         }
2941 }
2942
2943
2944 int reap_counter = 0;
2945
2946 int InspIRCd(void)
2947 {
2948         struct sockaddr_in client, server;
2949         char addrs[MAXBUF][255];
2950         int openSockfd[MAXSOCKS], incomingSockfd, result = TRUE;
2951         socklen_t length;
2952         int count = 0, scanDetectTrigger = TRUE, showBanner = FALSE;
2953         int selectResult = 0, selectResult2 = 0;
2954         char *temp, configToken[MAXBUF], stuff[MAXBUF], Addr[MAXBUF], Type[MAXBUF];
2955         char resolvedHost[MAXBUF];
2956         fd_set selectFds;
2957         struct timeval tv;
2958
2959         log_file = fopen("ircd.log","a+");
2960         if (!log_file)
2961         {
2962                 printf("ERROR: Could not write to logfile ircd.log, bailing!\n\n");
2963                 Exit(ERROR);
2964         }
2965
2966         log(DEBUG,"InspIRCd: startup: begin");
2967         log(DEBUG,"$Id$");
2968         if (geteuid() == 0)
2969         {
2970                 printf("WARNING!!! You are running an irc server as ROOT!!! DO NOT DO THIS!!!\n\n");
2971                 Exit(ERROR);
2972                 log(DEBUG,"InspIRCd: startup: not starting with UID 0!");
2973         }
2974         SetupCommandTable();
2975         log(DEBUG,"InspIRCd: startup: default command table set up");
2976         
2977         ReadConfig();
2978         if (strcmp(DieValue,"")) 
2979         { 
2980                 printf("WARNING: %s\n\n",DieValue);
2981                 exit(0); 
2982         }  
2983         log(DEBUG,"InspIRCd: startup: read config");
2984           
2985         int count2 = 0, count3 = 0;
2986
2987         for (count = 0; count < ConfValueEnum("bind",&config_f); count++)
2988         {
2989                 ConfValue("bind","port",count,configToken,&config_f);
2990                 ConfValue("bind","address",count,Addr,&config_f);
2991                 ConfValue("bind","type",count,Type,&config_f);
2992                 if (!strcmp(Type,"servers"))
2993                 {
2994                         char Default[MAXBUF];
2995                         strcpy(Default,"no");
2996                         ConfValue("bind","default",count,Default,&config_f);
2997                         if (strchr(Default,'y'))
2998                         {
2999                                 defaultRoute = count3;
3000                                 log(DEBUG,"InspIRCd: startup: binding '%s:%s' is default server route",Addr,configToken);
3001                         }
3002                         me[count3] = new serverrec(ServerName,100L,false);
3003                         me[count3]->CreateListener(Addr,atoi(configToken));
3004                         count3++;
3005                 }
3006                 else
3007                 {
3008                         ports[count2] = atoi(configToken);
3009                         strcpy(addrs[count2],Addr);
3010                         count2++;
3011                 }
3012                 log(DEBUG,"InspIRCd: startup: read binding %s:%s [%s] from config",Addr,configToken, Type);
3013         }
3014         portCount = count2;
3015         UDPportCount = count3;
3016           
3017         log(DEBUG,"InspIRCd: startup: read %d total client ports and %d total server ports",portCount,UDPportCount);
3018         
3019         log(DEBUG,"InspIRCd: startup: InspIRCd is now running!");
3020         
3021         printf("\n");
3022         
3023         /* BugFix By Craig! :p */
3024         count = 0;
3025         for (count2 = 0; count2 < ConfValueEnum("module",&config_f); count2++)
3026         {
3027                 char modfile[MAXBUF];
3028                 ConfValue("module","name",count2,configToken,&config_f);
3029                 sprintf(modfile,"%s/%s",MOD_PATH,configToken,&config_f);
3030                 printf("Loading module... \033[1;37m%s\033[0;37m\n",modfile);
3031                 log(DEBUG,"InspIRCd: startup: Loading module: %s",modfile);
3032                 /* If The File Doesnt exist, Trying to load it
3033                  * Will Segfault the IRCd.. So, check to see if
3034                  * it Exists, Before Proceeding. */
3035                 if (FileExists(modfile))
3036                 {
3037                         factory[count] = new ircd_module(modfile);
3038                         if (factory[count]->LastError())
3039                         {
3040                                 log(DEBUG,"Unable to load %s: %s",modfile,factory[count]->LastError());
3041                                 sprintf("Unable to load %s: %s\nExiting...\n",modfile,factory[count]->LastError());
3042                                 Exit(ERROR);
3043                         }
3044                         if (factory[count]->factory)
3045                         {
3046                                 modules[count] = factory[count]->factory->CreateModule();
3047                                 /* save the module and the module's classfactory, if
3048                                  * this isnt done, random crashes can occur :/ */
3049                                 module_names.push_back(modfile);        
3050                         }
3051                         else
3052                         {
3053                                 log(DEBUG,"Unable to load %s",modfile);
3054                                 sprintf("Unable to load %s\nExiting...\n",modfile);
3055                                 Exit(ERROR);
3056                         }
3057                         /* Increase the Count */
3058                         count++;
3059                 }
3060                 else
3061                 {
3062                         log(DEBUG,"InspIRCd: startup: Module Not Found %s",modfile);
3063                         printf("Module Not Found: \033[1;37m%s\033[0;37m, Skipping\n",modfile);
3064                 }
3065         }
3066         MODCOUNT = count - 1;
3067         log(DEBUG,"Total loaded modules: %d",MODCOUNT+1);
3068         
3069         printf("\nInspIRCd is now running!\n");
3070         
3071         startup_time = time(NULL);
3072           
3073         if (nofork)
3074         {
3075                 log(VERBOSE,"Not forking as -nofork was specified");
3076         }
3077         else
3078         {
3079                 if (DaemonSeed() == ERROR)
3080                 {
3081                         log(DEBUG,"InspIRCd: startup: can't daemonise");
3082                         printf("ERROR: could not go into daemon mode. Shutting down.\n");
3083                         Exit(ERROR);
3084                 }
3085         }
3086           
3087           
3088         /* setup select call */
3089         FD_ZERO(&selectFds);
3090         log(DEBUG,"InspIRCd: startup: zero selects");
3091         log(VERBOSE,"InspIRCd: startup: portCount = %d", portCount);
3092         
3093         for (count = 0; count < portCount; count++)
3094         {
3095                 if ((openSockfd[boundPortCount] = OpenTCPSocket()) == ERROR)
3096                 {
3097                         log(DEBUG,"InspIRCd: startup: bad fd %d",openSockfd[boundPortCount]);
3098                         return(ERROR);
3099                 }
3100                 if (BindSocket(openSockfd[boundPortCount],client,server,ports[count],addrs[count]) == ERROR)
3101                 {
3102                         log(DEBUG,"InspIRCd: startup: failed to bind port %d",ports[count]);
3103                 }
3104                 else    /* well we at least bound to one socket so we'll continue */
3105                 {
3106                         boundPortCount++;
3107                 }
3108         }
3109         
3110         log(DEBUG,"InspIRCd: startup: total bound ports %d",boundPortCount);
3111           
3112         /* if we didn't bind to anything then abort */
3113         if (boundPortCount == 0)
3114         {
3115                 log(DEBUG,"InspIRCd: startup: no ports bound, bailing!");
3116                 return (ERROR);
3117         }
3118         
3119
3120         length = sizeof (client);
3121         char udp_msg[MAXBUF], tcp_host[MAXBUF];
3122           
3123         /* main loop, this never returns */
3124         for (;;)
3125         {
3126 #ifdef _POSIX_PRIORITY_SCHEDULING
3127                 sched_yield();
3128 #endif
3129
3130                 fd_set sfd;
3131                 timeval tval;
3132                 FD_ZERO(&sfd);
3133
3134                 user_hash::iterator count2 = clientlist.begin();
3135
3136                 // *FIX* Instead of closing sockets in kill_link when they receive the ERROR :blah line, we should queue
3137                 // them in a list, then reap the list every second or so.
3138                 if (reap_counter>300)
3139                 {
3140                         if (fd_reap.size() > 0)
3141                         {
3142                                 for( int n = 0; n < fd_reap.size(); n++)
3143                                 {
3144                                         Blocking(fd_reap[n]);
3145                                         close(fd_reap[n]);
3146                                         NonBlocking(fd_reap[n]);
3147                                 }
3148                         }
3149                         fd_reap.clear();
3150                         reap_counter=0;
3151                 }
3152                 reap_counter++;
3153
3154                 fd_set serverfds;
3155                 FD_ZERO(&serverfds);
3156                 timeval tvs;
3157                 
3158                 for (int x = 0; x != UDPportCount; x++)
3159                 {
3160                         FD_SET(me[x]->fd, &serverfds);
3161                 }
3162                 
3163                 tvs.tv_usec = 0;                
3164                 tvs.tv_sec = 0;
3165                 
3166                 int servresult = select(32767, &serverfds, NULL, NULL, &tvs);
3167                 if (servresult > 0)
3168                 {
3169                         for (int x = 0; x != UDPportCount; x++)
3170                         {
3171                                 if (FD_ISSET (me[x]->fd, &serverfds))
3172                                 {
3173                                         char remotehost[MAXBUF],resolved[MAXBUF];
3174                                         length = sizeof (client);
3175                                         incomingSockfd = accept (me[x]->fd, (sockaddr *) &client, &length);
3176                                         strncpy(remotehost,(char *)inet_ntoa(client.sin_addr),MAXBUF);
3177                                         if(CleanAndResolve(resolved, remotehost) != TRUE)
3178                                         {
3179                                                 strncpy(resolved,remotehost,MAXBUF);
3180                                         }
3181                                         // add to this connections ircd_connector vector
3182                                         // *FIX* - we need the LOCAL port not the remote port in &client!
3183                                         me[x]->AddIncoming(incomingSockfd,resolved,me[x]->port);
3184                                 }
3185                         }
3186                 }
3187      
3188                 for (int x = 0; x < UDPportCount; x++)
3189                 {
3190                         std::deque<std::string> msgs;
3191                         msgs.clear();
3192                         if (me[x]->RecvPacket(msgs, tcp_host))
3193                         {
3194                                 for (int ctr = 0; ctr < msgs.size(); ctr++)
3195                                 {
3196                                         char udp_msg[MAXBUF];
3197                                         strncpy(udp_msg,msgs[ctr].c_str(),MAXBUF);
3198                                         if (strlen(udp_msg)<1)
3199                                         {
3200                                                 log(DEBUG,"Invalid string from %s [route%d]",tcp_host,x);
3201                                                 break;
3202                                         }
3203                                         // during a netburst, send all data to all other linked servers
3204                                         if ((((nb_start>0) && (udp_msg[0] != 'Y') && (udp_msg[0] != 'X') && (udp_msg[0] != 'F'))) || (is_uline(tcp_host)))
3205                                         {
3206                                                 if (is_uline(tcp_host))
3207                                                 {
3208                                                         if ((udp_msg[0] != 'Y') && (udp_msg[0] != 'X') && (udp_msg[0] != 'F'))
3209                                                         {
3210                                                                 NetSendToAllExcept(tcp_host,udp_msg);
3211                                                         }
3212                                                 }
3213                                                 else
3214                                                         NetSendToAllExcept(tcp_host,udp_msg);
3215                                         }
3216                                         FOREACH_MOD OnPacketReceive(udp_msg);
3217                                         handle_link_packet(udp_msg, tcp_host, me[x]);
3218                                 }
3219                                 goto label;
3220                         }
3221                 }
3222         
3223
3224         while (count2 != clientlist.end())
3225         {
3226                 char data[10240];
3227                 tval.tv_usec = tval.tv_sec = 0;
3228                 FD_ZERO(&sfd);
3229                 int total_in_this_set = 0;
3230
3231                 user_hash::iterator xcount = count2;
3232                 user_hash::iterator endingiter = count2;
3233
3234                 if (!count2->second) break;
3235                 
3236                 if (count2->second)
3237                 if (count2->second->fd != 0)
3238                 {
3239                         // assemble up to 64 sockets into an fd_set
3240                         // to implement a pooling mechanism.
3241                         //
3242                         // This should be up to 64x faster than the
3243                         // old implementation.
3244                         while (total_in_this_set < 64)
3245                         {
3246                                 if (count2 != clientlist.end())
3247                                 {
3248                                         // we don't check the state of remote users.
3249                                         if (count2->second->fd > 0)
3250                                         {
3251                                                 FD_SET (count2->second->fd, &sfd);
3252
3253                                                 // registration timeout -- didnt send USER/NICK/HOST in the time specified in
3254                                                 // their connection class.
3255                                                 if ((time(NULL) > count2->second->timeout) && (count2->second->registered != 7)) 
3256                                                 {
3257                                                         log(DEBUG,"InspIRCd: registration timeout: %s",count2->second->nick);
3258                                                         kill_link(count2->second,"Registration timeout");
3259                                                         goto label;
3260                                                 }
3261                                                 if (((time(NULL)) > count2->second->nping) && (isnick(count2->second->nick)) && (count2->second->registered == 7))
3262                                                 {
3263                                                         if ((!count2->second->lastping) && (count2->second->registered == 7))
3264                                                         {
3265                                                                 log(DEBUG,"InspIRCd: ping timeout: %s",count2->second->nick);
3266                                                                 kill_link(count2->second,"Ping timeout");
3267                                                                 goto label;
3268                                                         }
3269                                                         Write(count2->second->fd,"PING :%s",ServerName);
3270                                                         log(DEBUG,"InspIRCd: pinging: %s",count2->second->nick);
3271                                                         count2->second->lastping = 0;
3272                                                         count2->second->nping = time(NULL)+120;
3273                                                 }
3274                                         }
3275                                         count2++;
3276                                         total_in_this_set++;
3277                                 }
3278                                 else break;
3279                         }
3280    
3281                         endingiter = count2;
3282                         count2 = xcount; // roll back to where we were
3283         
3284                         int v = 0;
3285
3286                         tval.tv_usec = 0;
3287                         tval.tv_sec = 0;
3288                         selectResult2 = select(65535, &sfd, NULL, NULL, &tval);
3289                         
3290                         // now loop through all of the items in this pool if any are waiting
3291                         //if (selectResult2 > 0)
3292                         for (user_hash::iterator count2a = xcount; count2a != endingiter; count2a++)
3293                         {
3294
3295 #ifdef _POSIX_PRIORITY_SCHEDULING
3296                                 sched_yield();
3297 #endif
3298
3299                                 result = EAGAIN;
3300                                 if ((count2a->second->fd != -1) && (FD_ISSET (count2a->second->fd, &sfd)))
3301                                 {
3302                                         log(DEBUG,"Reading fd %d",count2a->second->fd);
3303                                         memset(data, 0, 10240);
3304                                         result = read(count2a->second->fd, data, 10240);
3305                                         
3306                                         if (result)
3307                                         {
3308                                                 if (result > 0)
3309                                                         log(DEBUG,"Read %d characters from socket",result);
3310                                                 userrec* current = count2a->second;
3311                                                 int currfd = current->fd;
3312                                                 char* l = strtok(data,"\n");
3313                                                 int floodlines = 0;
3314                                                 while (l)
3315                                                 {
3316                                                         floodlines++;
3317                                                         if ((floodlines > current->flood) && (current->flood != 0))
3318                                                         {
3319                                                                 log(DEFAULT,"Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
3320                                                                 WriteOpers("*** Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
3321                                                                 kill_link(current,"Excess flood");
3322                                                                 goto label;
3323                                                         }
3324                                                         char sanitized[NetBufferSize];
3325                                                         memset(sanitized, 0, NetBufferSize);
3326                                                         int ptt = 0;
3327                                                         for (int pt = 0; pt < strlen(l); pt++)
3328                                                         {
3329                                                                 if (l[pt] != '\r')
3330                                                                 {
3331                                                                         sanitized[ptt++] = l[pt];
3332                                                                 }
3333                                                         }
3334                                                         sanitized[ptt] = '\0';
3335                                                         if (strlen(sanitized))
3336                                                         {
3337
3338
3339                                                                 // we're gonna re-scan to check if the nick is gone, after every
3340                                                                 // command - if it has, we're gonna bail
3341                                                                 bool find_again = false;
3342                                                                 process_buffer(sanitized,current);
3343         
3344                                                                 // look for the user's record in case it's changed
3345                                                                 for (user_hash::iterator c2 = clientlist.begin(); c2 != clientlist.end(); c2++)
3346                                                                 {
3347                                                                         if (c2->second->fd == currfd)
3348                                                                         {
3349                                                                                 // found again, update pointer
3350                                                                                 current == c2->second;
3351                                                                                 find_again = true;
3352                                                                                 break;
3353                                                                         }
3354                                                                 }
3355                                                                 if (!find_again)
3356                                                                         goto label;
3357
3358                                                         }
3359                                                         l = strtok(NULL,"\n");
3360                                                 }
3361                                                 goto label;
3362                                         }
3363
3364                                         if ((result == -1) && (errno != EAGAIN) && (errno != EINTR))
3365                                         {
3366                                                 log(DEBUG,"killing: %s",count2a->second->nick);
3367                                                 kill_link(count2a->second,strerror(errno));
3368                                                 goto label;
3369                                         }
3370                                 }
3371                                 // result EAGAIN means nothing read
3372                                 if (result == EAGAIN)
3373                                 {
3374                                 }
3375                                 else
3376                                 if (result == 0)
3377                                 {
3378                                         if (count2->second)
3379                                         {
3380                                                 log(DEBUG,"InspIRCd: Exited: %s",count2a->second->nick);
3381                                                 kill_link(count2a->second,"Client exited");
3382                                                 // must bail here? kill_link removes the hash, corrupting the iterator
3383                                                 log(DEBUG,"Bailing from client exit");
3384                                                 goto label;
3385                                         }
3386                                 }
3387                                 else if (result > 0)
3388                                 {
3389                                 }
3390                         }
3391                 }
3392                 for (int q = 0; q < total_in_this_set; q++)
3393                 {
3394                         // there is no iterator += operator :(
3395                         //if (count2 != clientlist.end())
3396                         //{
3397                                 count2++;
3398                         //}
3399                 }
3400         }
3401         
3402         // set up select call
3403         for (count = 0; count < boundPortCount; count++)
3404         {
3405                 FD_SET (openSockfd[count], &selectFds);
3406         }
3407
3408         tv.tv_usec = 1;
3409         selectResult = select(MAXSOCKS, &selectFds, NULL, NULL, &tv);
3410
3411         /* select is reporting a waiting socket. Poll them all to find out which */
3412         if (selectResult > 0)
3413         {
3414                 char target[MAXBUF], resolved[MAXBUF];
3415                 for (count = 0; count < boundPortCount; count++)                
3416                 {
3417                         if (FD_ISSET (openSockfd[count], &selectFds))
3418                         {
3419                                 length = sizeof (client);
3420                                 incomingSockfd = accept (openSockfd[count], (struct sockaddr *) &client, &length);
3421                               
3422                                 address_cache::iterator iter = IP.find(client.sin_addr);
3423                                 bool iscached = false;
3424                                 if (iter == IP.end())
3425                                 {
3426                                         /* ip isn't in cache, add it */
3427                                         strncpy (target, (char *) inet_ntoa (client.sin_addr), MAXBUF);
3428                                         if(CleanAndResolve(resolved, target) != TRUE)
3429                                         {
3430                                                 strncpy(resolved,target,MAXBUF);
3431                                         }
3432                                         /* hostname now in 'target' */
3433                                         IP[client.sin_addr] = new string(resolved);
3434                                         /* hostname in cache */
3435                                 }
3436                                 else
3437                                 {
3438                                         /* found ip (cached) */
3439                                         strncpy(resolved, iter->second->c_str(), MAXBUF);
3440                                         iscached = true;
3441                                 }
3442                         
3443                                 if (incomingSockfd < 0)
3444                                 {
3445                                         WriteOpers("*** WARNING: Accept failed on port %d (%s)", ports[count],target);
3446                                         log(DEBUG,"InspIRCd: accept failed: %d",ports[count]);
3447                                 }
3448                                 else
3449                                 {
3450                                         AddClient(incomingSockfd, resolved, ports[count], iscached);
3451                                         log(DEBUG,"InspIRCd: adding client on port %d fd=%d",ports[count],incomingSockfd);
3452                                 }
3453                                 goto label;
3454                         }
3455                 }
3456         }
3457         label:
3458         if(0) {}; // "Label must be followed by a statement"... so i gave it one.
3459 }
3460 /* not reached */
3461 close (incomingSockfd);
3462 }
3463